This commit is contained in:
Orionis312050 committed 2026-04-17 12:08:37 +02:00
1 parent 4beb27e618
commit 76de333507
30 files changed
+5047 -2113

No files matched your search

+117 -85
View File
@@ -1,19 +1,21 @@
import { useEffect, useState, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import { Download, Sparkles } from 'lucide-react';
import { Download, Sparkles, Play, Pause, CircleCheck, Terminal } from 'lucide-react';
import type { LogService } from '../types';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
export default function LogTerminal({ service, initialLogs = [] }: {
service: LogService,
initialLogs?: { id: string, line: string, isError: boolean }[]
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 isPausedRef = useRef(false);
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]);
@@ -25,16 +27,15 @@ export default function LogTerminal({ service, initialLogs = [] }: {
});
}
// 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 | string, 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 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) {
@@ -49,7 +50,7 @@ export default function LogTerminal({ service, initialLogs = [] }: {
return () => {
socketRef.current?.off('logLine', handleLogLine);
};
}, [service.id]); // DÉPENDANCE UNIQUEMENT SUR L'ID DU SERVICE
}, [service.id]);
const terminalContentRef = useRef<HTMLDivElement>(null);
@@ -63,15 +64,12 @@ export default function LogTerminal({ service, initialLogs = [] }: {
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, '""')}"`)
@@ -81,7 +79,7 @@ export default function LogTerminal({ service, initialLogs = [] }: {
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.setAttribute("download", `logs_${service.name}_${new Date().toISOString().slice(0, 10)}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
@@ -89,117 +87,151 @@ export default function LogTerminal({ service, initialLogs = [] }: {
};
const handleAnalyzeLog = (line: string) => {
// Émission d'un événement global pour la sidebar
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line, serviceName: service.name }
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line, serviceName: service.name }
}));
};
const handleAnalyzeChunk = (chunk: { id: string, line: string, isError: boolean }[]) => {
if (chunk.length === 0) return;
const batchText = chunk.map(l => l.line).join('\n');
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: `Voici un ensemble de ${chunk.length} logs :\n${batchText}`, serviceName: service.name }
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: `Voici un ensemble de ${chunk.length} logs :\n${batchText}`, serviceName: service.name }
}));
};
const handleGlobalCheckup = () => {
if (logs.length === 0) return;
// Limite de caractères par défaut (Ollama LLaMA3 = ~8K context, on reste safe avec 6000 chars)
const MAX_CHARS = 6000;
let batchText = "";
let truncated = false;
let includedCount = 0;
// On part de la fin vers le début pour privilégier les logs les plus récents
for (let i = logs.length - 1; i >= 0; i--) {
const lineWithBreak = logs[i].line + '\n';
if (batchText.length + lineWithBreak.length > MAX_CHARS) {
truncated = true;
break;
}
// Ajout au début pour conserver l'ordre chronologique (haut vers bas)
batchText = lineWithBreak + batchText;
includedCount++;
const lineWithBreak = logs[i].line + '\n';
if (batchText.length + lineWithBreak.length > MAX_CHARS) {
truncated = true;
break;
}
batchText = lineWithBreak + batchText;
includedCount++;
}
const message = truncated
? `Fais un diagnostic de ces logs récents. (Attention : l'historique a été tronqué car il était trop grand. Voici les ${includedCount} logs les plus récents) :\n\n${batchText}`
: `Fais un diagnostic complet pour ce service. Voici l'intégralité des ${includedCount} logs dans la console :\n\n${batchText}`;
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: message, serviceName: service.name }
const message = truncated
? `### 📊 Diagnostic complet demandé\n\n*Analyse des ${includedCount} logs les plus récents...*\n\n<details>\n<summary>Voir les logs transmis à l'IA</summary>\n\n\`\`\`\n${batchText}\n\`\`\`\n</details>`
: `### 📊 Diagnostic complet demandé\n\n*Analyse de l'intégralité des logs (${includedCount})...*\n\n<details>\n<summary>Voir les logs transmis à l'IA</summary>\n\n\`\`\`\n${batchText}\n\`\`\`\n</details>`;
window.dispatchEvent(new CustomEvent('analyze-log', {
detail: { line: message, serviceName: service.name }
}));
};
const chunkedLogs = [];
// Chunk starting from the end so latest logs are strictly grouped by 5
for (let i = logs.length; i > 0; i -= 5) {
const start = Math.max(0, i - 5);
chunkedLogs.unshift(logs.slice(start, i));
}
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>
<button
className="btn-terminal btn-outline-sm"
style={{ color: 'var(--accent-color)', borderColor: 'rgba(59, 130, 246, 0.3)' }}
onClick={handleGlobalCheckup}
title="Analyser l'intégralité de la console via l'IA"
<div className="flex flex-col h-[75vh] bg-[#1a1b1e] overflow-hidden border-t">
{/* Terminal Toolbar */}
<div className="flex items-center justify-between px-6 py-4 bg-background dark:bg-card border-b border-border/40">
<div className="flex items-center gap-3">
<Button
variant={isPaused ? "secondary" : "ghost"}
size="sm"
onClick={togglePause}
className={cn("h-10 px-4 gap-2 rounded-xl transition-all", isPaused && "bg-destructive/10 text-destructive hover:bg-destructive/20 border border-destructive/20")}
>
<Sparkles size={14} /> Diagnostic Complet
</button>
{isPaused ? <Play size={16} /> : <Pause size={16} />}
<span className="font-bold uppercase tracking-widest text-[10px]">{isPaused ? 'Reprendre' : 'Pauser'}</span>
{isPaused && pendingLogsRef.current.length > 0 && (
<Badge variant="destructive" className="ml-1 h-5 min-w-5 flex items-center justify-center p-0 text-[10px] font-bold">
{pendingLogsRef.current.length}
</Badge>
)}
</Button>
<Button variant="ghost" size="sm" onClick={handleExport} className="h-10 px-4 gap-2 rounded-xl text-muted-foreground hover:text-foreground hover:bg-white/5 border border-transparent hover:border-white/5">
<Download size={16} />
<span className="font-bold uppercase tracking-widest text-[10px]">Exporter</span>
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleGlobalCheckup}
className="h-10 px-4 gap-2 rounded-xl ai-outline-v2 font-bold uppercase tracking-widest text-[10px]"
>
{/* SVG Gradient Definition */}
<svg width="0" height="0" className="absolute">
<defs>
<linearGradient id="ai-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stopColor="#3b82f6" />
<stop offset="46%" stopColor="#a855f7" />
<stop offset="100%" stopColor="#f97316" />
</linearGradient>
</defs>
</svg>
<div className="ai-icon-box">
<Sparkles size={16} className="ai-icon-svg" />
<span>Diagnostic IA</span>
</div>
</Button>
</div>
<div className="flex items-center gap-4">
<Badge variant="outline" className={cn(
"gap-2 border-none px-4 py-1.5 rounded-full text-[10px] font-bold tracking-[0.2em]",
isPaused ? "bg-destructive/10 text-destructive" : "bg-green-500/10 text-green-500"
)}>
<div className={cn("w-2 h-2 rounded-full", isPaused ? "bg-destructive" : "bg-green-500 animate-pulse")} />
{isPaused ? 'TERMINAL PAUSÉ' : 'FLUX EN DIRECT'}
</Badge>
</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}>
{/* Terminal View */}
<div
className="flex-1 overflow-y-auto p-6 font-mono text-[13px] antialiased scrollbar-terminal selection:bg-primary/30"
ref={terminalContentRef}
>
{chunkedLogs.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 className="flex flex-col items-center justify-center h-full gap-4 opacity-20 italic">
<Terminal size={64} className="stroke-[1px]" />
<p className="tracking-widest uppercase text-xs font-bold">Initialisation de la sortie standard...</p>
</div>
) : (
chunkedLogs.map((chunk, chunkIndex) => (
<div key={`chunk-${chunkIndex}`} className="log-chunk">
<div className="chunk-lines">
<div key={`chunk-${chunkIndex}`} className="group relative flex hover:bg-white/[0.03] transition-colors">
<div className="flex-1 py-1.5 pl-4">
{chunk.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"
<div key={log.id} className="flex items-start gap-4 group/line py-0.5">
<span className={cn(
"flex-1 break-all whitespace-pre-wrap leading-relaxed tracking-tight",
log.isError ? "text-destructive font-bold" : "text-white/80"
)}>
{log.line}
</span>
<button
className="opacity-0 group-hover/line:opacity-100 p-1.5 text-secondary/40 hover:text-secondary transition-all"
onClick={() => handleAnalyzeLog(log.line)}
title="Analyser ce log uniquement"
title="Analyser la ligne"
>
<Sparkles size={12} />
<Sparkles size={14} />
</button>
</div>
))}
</div>
<div className="chunk-sidebar" onClick={() => handleAnalyzeChunk(chunk)} title="Analyser cette zone de logs">
<div className="chunk-sidebar-icon">
<Sparkles size={14} />
</div>
{/* Chunk Sidebar */}
<div
className="w-12 flex items-center justify-center cursor-pointer border-l border-transparent hover:border-secondary/20 hover:bg-secondary/5 text-transparent hover:text-secondary/50 transition-all"
onClick={() => handleAnalyzeChunk(chunk)}
title="Analyser ce bloc de logs"
>
<Sparkles size={18} />
</div>
</div>
))