243 lines
9.7 KiB
TypeScript
243 lines
9.7 KiB
TypeScript
import { useEffect, useState, useRef } from 'react';
|
|
import { io, Socket } from 'socket.io-client';
|
|
import { Download, Sparkles, Play, Pause, 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 }[]
|
|
}) {
|
|
const [logs, setLogs] = useState<{ id: string, line: string, isError: boolean }[]>(initialLogs);
|
|
const [isPaused, setIsPaused] = useState(false);
|
|
const isPausedRef = useRef(false);
|
|
const pendingLogsRef = useRef<{ id: string, line: string, isError: boolean }[]>([]);
|
|
const socketRef = useRef<Socket | null>(null);
|
|
|
|
useEffect(() => {
|
|
isPausedRef.current = isPaused;
|
|
}, [isPaused]);
|
|
|
|
useEffect(() => {
|
|
if (!socketRef.current) {
|
|
socketRef.current = io(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}`, {
|
|
withCredentials: true
|
|
});
|
|
}
|
|
|
|
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 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]);
|
|
|
|
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) {
|
|
terminalContentRef.current.scrollTop = terminalContentRef.current.scrollHeight;
|
|
}
|
|
}, [logs, isPaused]);
|
|
|
|
const handleExport = () => {
|
|
if (logs.length === 0) return;
|
|
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) => {
|
|
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 }
|
|
}));
|
|
};
|
|
|
|
const handleGlobalCheckup = () => {
|
|
if (logs.length === 0) return;
|
|
const MAX_CHARS = 6000;
|
|
let batchText = "";
|
|
let truncated = false;
|
|
let includedCount = 0;
|
|
|
|
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;
|
|
}
|
|
batchText = lineWithBreak + batchText;
|
|
includedCount++;
|
|
}
|
|
|
|
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 = [];
|
|
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="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")}
|
|
>
|
|
{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>
|
|
</div>
|
|
|
|
{/* 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 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="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="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 la ligne"
|
|
>
|
|
<Sparkles size={14} />
|
|
</button>
|
|
</div>
|
|
))}
|
|
</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>
|
|
))
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|