Initial commit

This commit is contained in:
Orionis312050 committed 2026-04-16 14:18:56 +02:00
commit e6e07dc5c2
30 files changed
+5948

No files matched your search

+336
View File
@@ -0,0 +1,336 @@
import React, { useState, useEffect, useRef } from 'react';
import { Bot, User, History, MessageSquare, ChevronLeft, Trash2, Loader2, Send, Plus, X, Cpu, Square } from 'lucide-react';
import type { LogService, Conversation, Message } from '../types';
interface AIChatSidebarProps {
isOpen: boolean;
onClose: () => void;
currentService?: LogService | null;
}
export default function AIChatSidebar({ isOpen, onClose, currentService }: AIChatSidebarProps) {
const [conversations, setConversations] = useState<Conversation[]>([]);
const [currentConv, setCurrentConv] = useState<Conversation | null>(null);
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [isTyping, setIsTyping] = useState(false);
const [isGenerating, setIsGenerating] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const [view, setView] = useState<'chat' | 'history'>('chat');
// Charger les conversations au montage
useEffect(() => {
if (isOpen) fetchConversations();
}, [isOpen]);
// Charger les messages quand la conversation change
useEffect(() => {
if (currentConv) {
fetchMessages(currentConv.id);
setView('chat');
} else {
setMessages([]);
}
}, [currentConv]);
// Auto-scroll
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages, isTyping]);
const fetchConversations = async () => {
try {
const res = await fetch('http://localhost:3001/api/ai/conversations', { credentials: 'include' });
const data = await res.json();
setConversations(data);
// Si aucune conv n'est sélectionnée, prendre la plus récente
if (!currentConv && data.length > 0) {
setCurrentConv(data[0]);
}
} catch (err) {
console.error(err);
}
};
const fetchMessages = async (id: number) => {
try {
const res = await fetch(`http://localhost:3001/api/ai/conversations/${id}`, { credentials: 'include' });
const data = await res.json();
setMessages(data.messages || []);
} catch (err) {
console.error(err);
}
};
const startNewChat = async () => {
try {
const title = currentService ? `Analyse ${currentService.name}` : "Nouvelle discussion";
const res = await fetch('http://localhost:3001/api/ai/conversations', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ title })
});
const newConv = await res.json();
setConversations(prev => [newConv, ...prev]);
setCurrentConv(newConv);
setView('chat');
return newConv;
} catch (err) {
console.error(err);
return null;
}
};
const deleteConversation = async (e: React.MouseEvent, id: number) => {
e.stopPropagation();
try {
await fetch(`http://localhost:3001/api/ai/conversations/${id}`, {
method: 'DELETE',
credentials: 'include'
});
setConversations(prev => prev.filter(c => c.id !== id));
if (currentConv?.id === id) setCurrentConv(null);
} catch (err) {
console.error(err);
}
};
const stopGeneration = () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
setIsGenerating(false);
setIsTyping(false);
};
const sendMessage = async (text: string) => {
if (!text.trim()) return;
// Si pas de conversation active, on en crée une
let targetConv = currentConv;
if (!targetConv) {
targetConv = await startNewChat();
if (!targetConv) return; // Sécurité en cas d'échec de création
}
const userMsg: Message = { role: 'user', content: text };
setMessages(prev => [...prev, userMsg]);
setInput('');
setIsTyping(true); // Loader pendant le tout premier temps de latence réseau
setIsGenerating(true);
const abortController = new AbortController();
abortControllerRef.current = abortController;
try {
const response = await fetch('http://localhost:3001/api/ai/chat-stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ conversationId: targetConv.id, content: text }),
signal: abortController.signal
});
if (!response.ok) {
setMessages(prev => [...prev, { role: 'assistant', content: `Erreur HTTP: ${response.status}` }]);
setIsTyping(false);
return;
}
if (!response.body) throw new Error("Pas de stream disponible");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let isFirstChunk = true;
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunkText = decoder.decode(value, { stream: true });
const lines = chunkText.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.substring(6));
if (data.type === 'chunk') {
if (isFirstChunk) {
// Dès le premier mot, on enlève le loader "Qwen réfléchit" car l'IA a commencé à taper
setIsTyping(false);
setMessages(prev => [...prev, { role: 'assistant', content: data.content || "" }]);
isFirstChunk = false;
} else {
// On met à jour le dernier message avec la dernière fraction de texte reçue
setMessages(prev => {
const newMessages = [...prev];
const lastIndex = newMessages.length - 1;
if (newMessages[lastIndex].role === 'assistant') {
newMessages[lastIndex] = {
...newMessages[lastIndex],
content: newMessages[lastIndex].content + (data.content || "")
};
}
return newMessages;
});
}
} else if (data.type === 'done') {
// Si la conversation était "Nouvelle", c'est le moment de relire le titre qui a été généré
if (targetConv.title === "Nouvelle discussion") {
fetchConversations();
// et on met à jour la reférence locale pour ne pas avoir de glitch visuel
setCurrentConv(prev => prev ? {...prev, title: text.substring(0, 30)} : prev);
}
} else if (data.error) {
setIsTyping(false);
setMessages(prev => [...prev, { role: 'assistant', content: `Erreur : ${data.error}` }]);
}
} catch (e) {
// Parse error possible si un flux JSON est morcelé, on ignore et ça se complètera au prochain chunk
}
}
}
}
setIsGenerating(false);
} catch (error: any) {
setIsTyping(false);
setIsGenerating(false);
if (error.name === 'AbortError') {
// L'utilisateur a annulé, on ne rajoute pas de message d'erreur
} else {
setMessages(prev => [...prev, { role: 'assistant', content: "Erreur réseau / Déconnexion stream." }]);
}
}
};
// Écouge des événements d'analyse externes
useEffect(() => {
const handleAnalyzeLog = (e: any) => {
const { line, serviceName } = e.detail;
const contextMsg = `Analyse ce log du service '${serviceName}' : "${line}"`;
if (!isOpen) {
// L'App gèrera l'ouverture, mais on peut préparer le message
}
sendMessage(contextMsg);
};
window.addEventListener('analyze-log', handleAnalyzeLog);
return () => window.removeEventListener('analyze-log', handleAnalyzeLog);
}, [isOpen, currentConv]);
return (
<div className={`ai-sidebar ${isOpen ? 'open' : ''}`}>
<div className="ai-sidebar-header">
{view === 'history' ? (
<div className="ai-header-title">
<button className="btn-icon" onClick={() => setView('chat')}><ChevronLeft size={20} /></button>
<span>Historique</span>
</div>
) : (
<div className="ai-header-title" onClick={() => setView('history')} style={{ cursor: 'pointer' }}>
<History size={18} />
<span style={{ fontSize: '0.9rem' }}>{currentConv?.title || "Assistant"}</span>
</div>
)}
<div style={{ display: 'flex', gap: '0.5rem' }}>
<button className="btn-icon" onClick={startNewChat} title="Nouvelle discussion"><Plus size={18} /></button>
<button className="btn-icon" onClick={onClose}><X size={20} /></button>
</div>
</div>
<div className="ai-messages">
{view === 'history' ? (
<div className="ai-conv-list">
{conversations.length === 0 ? (
<p className="no-data">Aucune conversation passée.</p>
) : (
conversations.map(conv => (
<div
key={conv.id}
className={`ai-conv-item ${currentConv?.id === conv.id ? 'active' : ''}`}
onClick={() => setCurrentConv(conv)}
>
<MessageSquare size={14} />
<div className="ai-conv-info">
<span className="ai-conv-title">{conv.title}</span>
<span className="ai-conv-date">{new Date(conv.updatedAt).toLocaleDateString()}</span>
</div>
<button className="btn-delete-conv" onClick={(e) => deleteConversation(e, conv.id)}>
<Trash2 size={12} />
</button>
</div>
))
)}
</div>
) : (
<>
{!currentConv && (
<div className="ai-welcome">
<Cpu size={48} className="ai-welcome-icon" />
<h3>Prêt pour une nouvelle session ?</h3>
<p>Cliquez sur "+" pour démarrer une discussion ou consultez votre historique.</p>
<button className="btn btn-primary" onClick={startNewChat} style={{ marginTop: '1.5rem' }}>
<Plus size={16} /> Nouvelle discussion
</button>
</div>
)}
{messages.filter(m => m.role !== 'system').map((msg, idx) => (
<div key={idx} className={`ai-message-wrapper ${msg.role}`}>
<div className="ai-message-avatar">
{msg.role === 'assistant' ? <Bot size={14} /> : <User size={14} />}
</div>
<div className="ai-message-content">{msg.content}</div>
</div>
))}
{isTyping && (
<div className="ai-message-wrapper assistant">
<div className="ai-message-avatar"><Loader2 size={14} className="spin" /></div>
<div className="ai-message-content typing">Qwen réfléchit...</div>
</div>
)}
<div ref={messagesEndRef} />
</>
)}
</div>
{view === 'chat' && currentConv && (
<div className="ai-input-area">
<form onSubmit={(e) => { e.preventDefault(); sendMessage(input); }}>
<div className="ai-input-wrapper">
<input
type="text"
placeholder="Posez une question..."
value={input}
onChange={(e) => setInput(e.target.value)}
disabled={isGenerating}
/>
<button type="submit" disabled={!input.trim() || isGenerating}>
<Send size={18} />
</button>
</div>
{isGenerating && (
<div style={{ textAlign: 'center', marginTop: '0.75rem' }}>
<button
type="button"
className="btn btn-outline"
style={{ fontSize: '0.75rem', padding: '0.25rem 0.75rem', margin: '0 auto' }}
onClick={stopGeneration}
>
<Square size={12} fill="currentColor" />
Stopper la réponse
</button>
</div>
)}
</form>
</div>
)}
</div>
);
}
+100
View File
@@ -0,0 +1,100 @@
import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
export default function AddServiceModal({ onClose, onAdded }: { onClose: () => void, onAdded: () => void }) {
const [formData, setFormData] = useState({
name: '',
type: 'docker',
pathOrContainerId: ''
});
const [availableTargets, setAvailableTargets] = useState<{id: string, name: string}[]>([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetchTargets = async () => {
setIsLoading(true);
setAvailableTargets([]);
setFormData(prev => ({ ...prev, pathOrContainerId: '' }));
try {
const endpoint = formData.type === 'docker' ? '/api/docker/containers' : '/api/os/services';
const res = await fetch(`http://localhost:3001${endpoint}`, {
credentials: 'include'
});
const data = await res.json();
setAvailableTargets(data);
} catch (err) {
console.error("Erreur lors de la récupération des listes :", err);
}
setIsLoading(false);
};
fetchTargets();
}, [formData.type]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await fetch('http://localhost:3001/api/services', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify(formData)
});
onAdded();
} catch (err) {
console.error(err);
}
};
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="glass-panel modal-content" onClick={e => e.stopPropagation()}>
<form onSubmit={handleSubmit}>
<h2 style={{ marginBottom: '1.5rem', color: 'var(--text-main)' }}>Nouveau Service</h2>
<div className="form-group">
<label>Nom du service (Affichage)</label>
<input required type="text" className="form-control" value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} placeholder="ex: Mon App Backend" />
</div>
<div className="form-group">
<label>Environnement Source</label>
<select className="form-control" value={formData.type} onChange={e => setFormData({...formData, type: e.target.value})}>
<option value="docker">Conteneur Docker</option>
<option value="os_service">Service Système Natif (Host)</option>
</select>
</div>
<div className="form-group">
<label>Rechercher le conteneur ou service...</label>
<input
required
type="text"
list="targets-list"
className="form-control"
value={formData.pathOrContainerId}
onChange={e => setFormData({...formData, pathOrContainerId: e.target.value})}
placeholder={formData.type === 'docker' ? 'Saisissez ou choisissez un conteneur...' : 'Saisissez ou choisissez un service système...'}
disabled={isLoading}
/>
{isLoading && <small style={{ color: 'var(--text-muted)', display: 'block', marginTop: '0.5rem' }}>Analyse des services en cours...</small>}
<datalist id="targets-list">
{availableTargets.map(target => (
<option key={target.id} value={target.id}>{target.name}</option>
))}
</datalist>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', marginTop: '1.5rem' }}>
<button type="button" className="btn" onClick={onClose}>Annuler</button>
<button type="submit" className="btn btn-primary">Créer le service</button>
</div>
</form>
</div>
</div>,
document.body
);
}
+144
View File
@@ -0,0 +1,144 @@
import React, { useEffect, useState, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import { Download, Sparkles } from 'lucide-react';
import type { LogService } from '../types';
export default function LogTerminal({ service, initialLogs = [] }: {
service: LogService,
initialLogs?: { id: string, line: string, isError: boolean }[]
}) {
const [logs, setLogs] = useState<{ id: string, line: string, isError: boolean }[]>(initialLogs);
const [isPaused, setIsPaused] = useState(false);
const isPausedRef = useRef(false); // Ref pour éviter les fermetures (closures) obsolètes
const pendingLogsRef = useRef<{ id: string, line: string, isError: boolean }[]>([]);
const socketRef = useRef<Socket | null>(null);
// Synchronisation de la ref avec l'état
useEffect(() => {
isPausedRef.current = isPaused;
}, [isPaused]);
useEffect(() => {
if (!socketRef.current) {
socketRef.current = io('http://localhost:3001', {
withCredentials: true
});
}
// On ne vide les logs que si le service change, et on injecte les logs initiaux
setLogs(initialLogs);
pendingLogsRef.current = [];
const handleLogLine = (data: { serviceId: number, line: string }) => {
if (data.serviceId === service.id) {
const isError = service.alertKeyword
? data.line.includes(service.alertKeyword)
: (data.line.includes('ERROR') || data.line.includes('Exception'));
const newLog = { id: Date.now() + Math.random().toString(), line: data.line, isError };
if (!isPausedRef.current) {
setLogs(prev => [...prev, newLog].slice(-300));
} else {
pendingLogsRef.current = [...pendingLogsRef.current, newLog].slice(-300);
}
}
};
socketRef.current.on('logLine', handleLogLine);
return () => {
socketRef.current?.off('logLine', handleLogLine);
};
}, [service.id]); // DÉPENDANCE UNIQUEMENT SUR L'ID DU SERVICE
const terminalContentRef = useRef<HTMLDivElement>(null);
const togglePause = () => {
if (isPaused) {
setLogs(prev => [...prev, ...pendingLogsRef.current].slice(-300));
pendingLogsRef.current = [];
}
setIsPaused(!isPaused);
};
useEffect(() => {
if (!isPaused && terminalContentRef.current) {
// Défilement interne du conteneur sans affecter la page entière
terminalContentRef.current.scrollTop = terminalContentRef.current.scrollHeight;
}
}, [logs, isPaused]);
const handleExport = () => {
if (logs.length === 0) return;
// Header CSV
const csvContent = [
"ID,Status,Log Line",
...logs.map(log => `${log.id},${log.isError ? 'ERROR' : 'INFO'},"${log.line.replace(/"/g, '""')}"`)
].join("\n");
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", `logs_${service.name}_${new Date().toISOString().slice(0,10)}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const handleAnalyzeLog = (line: string) => {
// Émission d'un événement global pour la sidebar
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line, serviceName: service.name }
}));
};
return (
<div className={`terminal-container ${isPaused ? 'paused' : 'live'}`}>
<div className="terminal-controls">
<div style={{ display: 'flex', gap: '0.75rem' }}>
<button className={`btn-terminal ${isPaused ? 'btn-resume' : 'btn-pause'}`} onClick={togglePause}>
{isPaused ? '▶ Reprendre' : '⏸ Pauser'}
{isPaused && pendingLogsRef.current.length > 0 && (
<span className="pending-badge">{pendingLogsRef.current.length}</span>
)}
</button>
<button className="btn-terminal btn-outline-sm" onClick={handleExport} title="Exporter en CSV">
<Download size={14} /> Exporter
</button>
</div>
<span className="live-indicator">
<span className={`status-dot ${isPaused ? 'dot-red' : 'dot-green'}`}></span>
{isPaused ? 'TERMINAL EN PAUSE' : 'LOGS EN DIRECT'}
</span>
</div>
<div className="terminal-content" ref={terminalContentRef}>
{logs.length === 0 ? (
<div style={{ color: 'var(--text-muted)', display: 'flex', height: '100%', alignItems: 'center', justifyContent: 'center' }}>
En attente de nouveaux logs pour '{service.name}'...
</div>
) : (
logs.map(log => (
<div key={log.id} className="log-line-wrapper">
<div className="log-line">
<span className={`log-text ${log.isError ? 'log-error' : ''}`}>
{log.line}
</span>
</div>
<button
className="btn-analyze-log"
onClick={() => handleAnalyzeLog(log.line)}
title="Analyser avec l'IA"
>
<Sparkles size={12} />
</button>
</div>
))
)}
</div>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
const ProtectedRoute = () => {
const { user, loading } = useAuth();
if (loading) {
return <div className="loading-state">Vérification de la session...</div>;
}
if (!user) {
return <Navigate to="/login" replace />;
}
return <Outlet />;
};
export default ProtectedRoute;
+104
View File
@@ -0,0 +1,104 @@
import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
export default function SettingsModal({ onClose }: { onClose: () => void }) {
const [formData, setFormData] = useState({
notionToken: '',
notionDbId: '',
ollamaUrl: '',
ollamaModel: '',
searxngUrl: ''
});
const [saved, setSaved] = useState(false);
useEffect(() => {
fetch('http://localhost:3001/api/settings', {
credentials: 'include'
})
.then(res => res.json())
.then(data => {
if (data) {
setFormData({
notionToken: data.notionToken || '',
notionDbId: data.notionDbId || '',
ollamaUrl: data.ollamaUrl || '',
ollamaModel: data.ollamaModel || '',
searxngUrl: data.searxngUrl || ''
});
}
})
.catch(console.error);
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await fetch('http://localhost:3001/api/settings', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify(formData)
});
setSaved(true);
setTimeout(() => setSaved(false), 3000);
} catch (err) {
console.error(err);
}
};
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="glass-panel modal-content" onClick={e => e.stopPropagation()}>
<form onSubmit={handleSubmit} style={{ maxHeight: '90vh', overflowY: 'auto' }}>
<h2 style={{ marginBottom: '1.5rem', color: 'var(--text-main)' }}>Paramètres Globaux</h2>
<div style={{ padding: '1.5rem', background: 'rgba(59, 130, 246, 0.05)', borderRadius: '8px', border: '1px solid rgba(59, 130, 246, 0.2)', marginBottom: '1.5rem' }}>
<h4 style={{ fontSize: '1rem', marginBottom: '1rem', color: 'var(--text-main)' }}>Intégration Notion</h4>
<div className="form-group">
<label>Token d'intégration Notion (Internal App)</label>
<input type="password" className="form-control" value={formData.notionToken} onChange={e => setFormData({...formData, notionToken: e.target.value})} placeholder="secret_..." />
</div>
<div className="form-group" style={{ marginBottom: 0 }}>
<label>ID de la base de données (Database ID)</label>
<input type="text" className="form-control" value={formData.notionDbId} onChange={e => setFormData({...formData, notionDbId: e.target.value})} placeholder="ex: a1b2c3d4e5f6..." />
</div>
</div>
<div style={{ padding: '1.5rem', background: 'rgba(16, 185, 129, 0.05)', borderRadius: '8px', border: '1px solid rgba(16, 185, 129, 0.2)', marginBottom: '1.5rem' }}>
<h4 style={{ fontSize: '1rem', marginBottom: '1rem', color: 'var(--text-main)' }}>Intégration IA (Ollama Local)</h4>
<div className="form-group">
<label>URL de l'API Ollama</label>
<input type="text" className="form-control" value={formData.ollamaUrl} onChange={e => setFormData({...formData, ollamaUrl: e.target.value})} placeholder="ex: http://localhost:11434" />
</div>
<div className="form-group" style={{ marginBottom: 0 }}>
<label>Nom du modèle (ex: qwen:7b, llama3)</label>
<input type="text" className="form-control" value={formData.ollamaModel} onChange={e => setFormData({...formData, ollamaModel: e.target.value})} placeholder="ex: qwen:7b" />
</div>
</div>
<div style={{ padding: '1.5rem', background: 'rgba(234, 179, 8, 0.05)', borderRadius: '8px', border: '1px solid rgba(234, 179, 8, 0.2)', marginBottom: '1.5rem' }}>
<h4 style={{ fontSize: '1rem', marginBottom: '1rem', color: 'var(--text-main)' }}>Recherche Web (SearXNG)</h4>
<div className="form-group" style={{ marginBottom: 0 }}>
<label>URL de SearXNG (pour enrichir l'IA)</label>
<input type="text" className="form-control" value={formData.searxngUrl} onChange={e => setFormData({...formData, searxngUrl: e.target.value})} placeholder="ex: http://localhost:8080" />
</div>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', alignItems: 'center' }}>
{saved && <span style={{ color: 'var(--success-color)', fontSize: '0.875rem' }}>Sauvegardé !</span>}
<button type="button" className="btn" onClick={onClose}>Fermer</button>
<button type="submit" className="btn btn-primary">Enregistrer</button>
</div>
</form>
</div>
</div>,
document.body
);
}