"use client"; import * as React from "react"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { sseUrl } from "@/lib/api"; import { MOCK } from "@/lib/mock/enabled"; import type { LogLine } from "@/lib/types"; import { cn } from "@/lib/utils"; // Mock demo:无后端 SSE,塞几行示例日志。 const MOCK_LOGS: LogLine[] = [ { seq: 1, ts: "2026-07-26T03:55:00Z", level: "info", tag: "engine", text: "ARTEX v0.1.0 backend listening on :8787 (workers=3)" }, { seq: 2, ts: "2026-07-26T03:55:01Z", level: "info", tag: "config", text: "LLM configured from DB: anthropic / claude-opus-4-8" }, { seq: 3, ts: "2026-07-26T03:56:10Z", level: "info", tag: "planner", text: "task t-acme-web: 第 3 轮规划,生成意图 i-4" }, { seq: 4, ts: "2026-07-26T03:57:00Z", level: "warn", tag: "guard", text: "block bash: 目标越界 out.evil.example 不在 scope 内" }, { seq: 5, ts: "2026-07-26T03:57:30Z", level: "info", tag: "work#1", text: "report_finding: Default Credentials (high) 已落库" }, { seq: 6, ts: "2026-07-26T03:58:20Z", level: "error", tag: "work#3", text: "intercept: mysqldump 命中破坏性规则,等待人工审批" }, ]; const levelTone: Record = { info: "text-foreground/80", warn: "text-amber-600 dark:text-amber-400", error: "text-red-600 dark:text-red-400", }; const levelDot: Record = { info: "bg-muted-foreground/40", warn: "bg-amber-500", error: "bg-red-500", }; function fmtTime(ts: string) { const d = new Date(ts); if (isNaN(d.getTime())) return ""; const p = (n: number) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; } export default function LogsPage() { const [lines, setLines] = React.useState([]); const [q, setQ] = React.useState(""); const [level, setLevel] = React.useState<"all" | LogLine["level"]>("all"); const [paused, setPaused] = React.useState(false); const [loadingHistory, setLoadingHistory] = React.useState(false); const [hasMore, setHasMore] = React.useState(false); const bottom = React.useRef(null); const stick = React.useRef(true); const pausedRef = React.useRef(false); pausedRef.current = paused; // Minimum db_id seen — used as the cursor for loading older history. const minDbId = React.useMemo(() => { let min = 0; for (const l of lines) { if (l.db_id && (min === 0 || l.db_id < min)) min = l.db_id; } return min; }, [lines]); // Live tail via SSE. on connect, replays whatever is in the ring (includes // DB-restored history from the last 100 rows written before restart). React.useEffect(() => { if (MOCK) { setLines(MOCK_LOGS); return; } const es = new EventSource(sseUrl("/api/logs/stream?since=0")); es.onmessage = (e) => { if (pausedRef.current) return; try { const l = JSON.parse(e.data) as LogLine; setLines((prev) => (prev.some((x) => x.seq === l.seq) ? prev : [...prev, l].slice(-3000))); } catch { /* ignore malformed frame */ } }; return () => es.close(); }, []); // Mark "has more" once we have any db_id in view. React.useEffect(() => { if (minDbId > 1) setHasMore(true); }, [minDbId]); async function loadOlderHistory() { if (loadingHistory) return; setLoadingHistory(true); try { const params = minDbId > 0 ? `?before=${minDbId}&limit=200` : `?limit=200`; const res = await fetch(`/api/logs/history${params}`); if (!res.ok) return; const data = await res.json() as { items: LogLine[]; has_more: boolean }; if (data.items?.length) { // Assign synthetic seq numbers below current minimum to keep dedup working. setLines((prev) => { const minSeq = prev.reduce((m, l) => Math.min(m, l.seq ?? 0), 0); const older = data.items.map((l, i) => ({ ...l, seq: minSeq - data.items.length + i, })); // Prepend, dedup by db_id, cap at 5000. const merged = [...older, ...prev]; const seen = new Set(); const deduped = merged.filter((l) => { if (!l.db_id) return true; if (seen.has(l.db_id)) return false; seen.add(l.db_id); return true; }); return deduped.slice(-5000); }); } setHasMore(data.has_more ?? false); } finally { setLoadingHistory(false); } } const filtered = React.useMemo(() => { const needle = q.trim().toLowerCase(); return lines.filter( (l) => (level === "all" || l.level === level) && (!needle || l.text.toLowerCase().includes(needle) || l.tag.toLowerCase().includes(needle)), ); }, [lines, q, level]); React.useEffect(() => { if (stick.current && !paused) bottom.current?.scrollIntoView(); }, [filtered, paused]); const counts = React.useMemo(() => { let warn = 0, error = 0; for (const l of lines) { if (l.level === "warn") warn++; else if (l.level === "error") error++; } return { warn, error, total: lines.length }; }, [lines]); return (

系统日志

后端实时日志流(planner / worker / 数据库 / 流量 …)

setQ(e.target.value)} className="h-8 max-w-xs" />
{(["all", "info", "warn", "error"] as const).map((lv) => ( ))}
{counts.total} 行 ·{" "} {counts.warn} 警告 ·{" "} {counts.error} 错误
{ const el = e.currentTarget; stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40; }} className="h-[calc(100vh-14rem)] overflow-auto rounded-lg border bg-card p-2 font-mono text-xs leading-relaxed" > {hasMore && (
)} {filtered.length === 0 ? (

暂无日志。

) : ( filtered.map((l) => { const body = l.tag && l.text.startsWith("[" + l.tag + "]") ? l.text.slice(l.tag.length + 2).trimStart() : l.text; return (
{fmtTime(l.ts)} {l.tag && ( {l.tag} )} {body}
); }) )}
); }