import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { sanitizeLogLine } from '@snowluma/common/log-sanitize'; import { useVirtualizer } from '@tanstack/react-virtual'; import { motion, AnimatePresence } from 'motion/react'; import { ArrowDownToLine, Download, Filter, Highlighter, Inbox, Pause, Plus, RefreshCw, Search, SearchX, SlidersHorizontal, Trash2, TriangleAlert, WrapText, X } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Input } from '@/components/ui/input'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; import { ConfirmDialog } from '@/components/confirm-dialog'; import { SkeletonSwap } from '@/components/interior/skeleton-swap'; import { cn } from '@/lib/utils'; import type { LogEntry, LogLevel, LogsPreset, UiHighlightRule } from '@/types'; import { useApi } from '@/lib/api'; import { selectServerLogLevel, TRACE_CONFIRMATION_WARNINGS, } from '@/lib/server-log-level'; import { useTheme } from '@/contexts/ThemeContext'; import { useLayout } from '@/contexts/LayoutContext'; import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; // Dedicated log-level text tokens (see index.css): the app accent colors are // too light as small text on the light canvas (WCAG AA fails), so these hit // >=4.5:1 in light mode while keeping the bright values in dark. trace stays the // faintest level (dimmer than debug) but at /90 it now also clears AA. const levelClass: Record = { trace: 'text-muted-foreground/90', debug: 'text-muted-foreground', info: 'text-log-info', success: 'text-log-success', warn: 'text-log-warn', error: 'text-log-error', }; const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error']; // More than this many new lines in one flush ⇒ firehose: suppress the per-row // entrance so a 100 line/s stream never strobes (scroll flow + edge fade carry it). const BURST_MAX = 4; // View presets bundle the display prefs (levels/maxLines/autoScroll/wrap). The // server stores only the id; 'custom' (any hand-tuned state) has no bundle. interface PresetBundle { visibleLevels: LogLevel[]; maxLines: number; autoScroll: boolean; wrap: boolean } const LOG_PRESETS: { id: Exclude; label: string; hint: string; bundle: PresetBundle }[] = [ { id: 'dev', label: '开发', hint: '全部级别 · 2000 行 · 换行', bundle: { visibleLevels: [...LEVELS], maxLines: 2000, autoScroll: true, wrap: true } }, { id: 'ops', label: '运维', hint: 'INFO 以上 · 1000 行', bundle: { visibleLevels: ['info', 'success', 'warn', 'error'], maxLines: 1000, autoScroll: true, wrap: false } }, { id: 'minimal', label: '精简', hint: '仅 WARN/ERROR · 500 行', bundle: { visibleLevels: ['warn', 'error'], maxLines: 500, autoScroll: true, wrap: false } }, ]; // Highlight palette — keyword rules tint a matching row. Stored as an id. const HIGHLIGHT_COLORS: { id: string; label: string; swatch: string }[] = [ { id: 'amber', label: '琥珀', swatch: '#f59e0b' }, { id: 'rose', label: '玫瑰', swatch: '#f43f5e' }, { id: 'emerald', label: '翡翠', swatch: '#10b981' }, { id: 'sky', label: '天蓝', swatch: '#38bdf8' }, { id: 'violet', label: '紫', swatch: '#8b5cf6' }, ]; const colorSwatch = (id: string) => HIGHLIGHT_COLORS.find((c) => c.id === id)?.swatch ?? '#f59e0b'; function matchHighlight(message: string, rules: UiHighlightRule[]): string | null { if (rules.length === 0) return null; const m = message.toLowerCase(); for (const r of rules) { if (r.keyword && m.includes(r.keyword.toLowerCase())) return colorSwatch(r.color); } return null; } // Apple-style toolbar icon button: icon-only, tooltip-labelled, calm hover. interface ToolButtonProps { label: string; onClick: () => void; children: ReactNode; active?: boolean; danger?: boolean; disabled?: boolean; } function ToolButton({ label, onClick, children, active, danger, disabled }: ToolButtonProps) { return ( {label} ); } export function LogsPage() { const api = useApi(); const { runAction } = useActionFeedback(); const { formatClock, appearance } = useTheme(); const { pages, setPages } = useLayout(); const prefs = pages.logs; const [logs, setLogs] = useState([]); const [logsReady, setLogsReady] = useState(false); const [logsError, setLogsError] = useState(null); const [streamStatus, setStreamStatus] = useState('连接中'); const [filter, setFilter] = useState(''); const [confirmClear, setConfirmClear] = useState(false); const [serverLevel, setServerLevel] = useState(null); const [serverLevelReady, setServerLevelReady] = useState(false); const [serverLevelError, setServerLevelError] = useState(null); const [levelBusy, setLevelBusy] = useState(false); const [confirmTrace, setConfirmTrace] = useState(false); const [traceExportBusy, setTraceExportBusy] = useState(false); const [showOptions, setShowOptions] = useState(false); const [newKeyword, setNewKeyword] = useState(''); const [newColor, setNewColor] = useState(HIGHLIGHT_COLORS[0].id); const scrollRef = useRef(null); // Ids currently playing the entrance animation. Populated in the flush (from // real arrivals, so it's immune to filter/idle churn) and pruned by a 260ms // timer so a later scroll-into-view never replays. Render reads it directly. const animatingRef = useRef>(new Set()); const animTimersRef = useRef>(new Set()); const motionOnRef = useRef(true); // live motion pref for the async flush closure // maxLines is read through a ref so changing it doesn't re-subscribe the SSE. const maxLines = prefs.maxLines; const maxLinesRef = useRef(maxLines); useEffect(() => { maxLinesRef.current = maxLines; }, [maxLines]); const enabled = useMemo(() => new Set(prefs.visibleLevels as LogLevel[]), [prefs.visibleLevels]); const loadLogs = useCallback(async () => { setLogsError(null); try { // Backfill is capped at the server's ring-buffer size (1000); `maxLines` // can exceed that, but only the live SSE stream grows the view past 1000. setLogs(await api.logs.list(Math.min(1000, maxLinesRef.current))); } catch (e) { console.error('logs', e); setLogsError(e instanceof Error ? e.message : '加载日志失败'); } finally { setLogsReady(true); } }, [api]); useEffect(() => { void loadLogs(); }, [loadLogs]); const loadServerLevel = useCallback(async () => { setServerLevelReady(false); setServerLevelError(null); try { const { level } = await api.logs.getLevel(); setServerLevel(level); } catch (error) { console.error('get server log level failed', error); setServerLevelError(error instanceof Error ? error.message : '加载服务端日志级别失败'); } finally { setServerLevelReady(true); } }, [api]); useEffect(() => { void loadServerLevel(); }, [loadServerLevel]); const applyServerLevel = useCallback(async (lv: LogLevel) => { if (lv === serverLevel || levelBusy) return; setLevelBusy(true); try { const { level } = await runAction( { title: '正在更新服务端日志级别', detail: `切换为 ${lv.toUpperCase()}`, successTitle: '日志级别已更新', successDetail: `${lv.toUpperCase()} 已生效`, errorTitle: '日志级别更新失败', }, () => api.logs.setLevel(lv), ); setServerLevel(level); } catch (err) { console.error('setLevel', err); } finally { setLevelBusy(false); } }, [api, serverLevel, levelBusy, runAction]); const changeServerLevel = useCallback((lv: LogLevel) => { if (levelBusy) return; selectServerLogLevel({ currentLevel: serverLevel, nextLevel: lv, applyLevel: (level) => void applyServerLevel(level), requestTraceConfirmation: () => setConfirmTrace(true), }); }, [applyServerLevel, levelBusy, serverLevel]); useEffect(() => { // Batch incoming lines: buffer in a ref and flush on a ~80ms timer instead // of a per-line setState. Under a high log rate this turns N O(n) array // copies + N React commits per window into one. Dedup-by-id and the // maxLines cap are preserved (a reconnect can replay recent ids). let pending: LogEntry[] = []; let flushTimer: number | null = null; // Stable Set instances — captured so cleanup clears the very sets the flush // mutates (satisfies the ref-in-cleanup lint without changing behaviour). const animating = animatingRef.current; const animTimers = animTimersRef.current; const flush = () => { flushTimer = null; if (pending.length === 0) return; const batchMap = new Map(pending.map((e) => [e.id, e] as const)); pending = []; // Mark just-arrived lines for the entrance animation — but suppress a // firehose batch (> BURST_MAX) so 100 lines/s never strobes; the scroll // flow + edge fade carry it instead. Populating here (before setLogs) // means the very first paint of the row already has the class, and the // 260ms timer bounds it so a later scroll-into-view can't replay it. if (motionOnRef.current && batchMap.size > 0 && batchMap.size <= BURST_MAX) { for (const id of batchMap.keys()) { animatingRef.current.add(id); const t = window.setTimeout(() => { animatingRef.current.delete(id); animTimersRef.current.delete(t); }, 260); animTimersRef.current.add(t); } } setLogs((prev) => { const kept = prev.length ? prev.filter((it) => !batchMap.has(it.id)) : prev; const merged = kept.length ? [...kept, ...batchMap.values()] : [...batchMap.values()]; return merged.length > maxLinesRef.current ? merged.slice(-maxLinesRef.current) : merged; }); }; const dispose = api.logs.stream({ onLine: (entry) => { pending.push(entry); if (flushTimer == null) flushTimer = window.setTimeout(flush, 80); }, onStatus: (s) => { if (s === 'open') setStreamStatus('实时'); else if (s === 'reconnecting') setStreamStatus('重连中'); else setStreamStatus('已断开'); }, }); return () => { dispose(); if (flushTimer != null) clearTimeout(flushTimer); for (const t of animTimers) clearTimeout(t); animTimers.clear(); animating.clear(); }; }, [api]); const filtered = useMemo(() => { const f = filter.trim().toLowerCase(); const capped = logs.slice(-maxLines); return capped.filter((l) => { if (!enabled.has(l.level)) return false; if (!f) return true; return ( l.message.toLowerCase().includes(f) || l.scope.toLowerCase().includes(f) || l.level.toLowerCase().includes(f) || (l.req !== undefined && String(l.req).includes(f)) ); }); }, [logs, filter, enabled, maxLines]); // Virtualize the log rows: only the visible window (+overscan) is mounted, so // the DOM stays at a few dozen nodes regardless of how many lines the view // holds. Rows are dynamically measured (measureElement) so wrap mode's // variable-height lines are handled without a fixed row-height assumption. const rowVirtualizer = useVirtualizer({ count: filtered.length, getScrollElement: () => scrollRef.current, estimateSize: () => 28, overscan: 12, // Key the size cache by row id, not index: the list is front-dropped at the // maxLines cap, so every surviving row's index shifts down each flush. Keying // by id keeps each measured height with its content (and matches the React // key), avoiding a one-frame height mis-attribution on off-screen rows. getItemKey: (index) => filtered[index]?.id ?? index, }); // Toggling wrap changes every row's height — force a clean re-measure so the // cached sizes don't leave gaps/overlaps. useEffect(() => { rowVirtualizer.measure(); }, [prefs.wrap, rowVirtualizer]); // Follow the tail while auto-scroll is on. Re-run on anything that changes the // visible set or row heights (new logs, filter/level/maxLines → filtered.length, // wrap → heights), not just new logs. Freshly-appended rows still carry the // estimate on this pass, so a second pin on the next frame (after ResizeObserver // measures them) reaches the true bottom in wrap mode. useEffect(() => { if (!prefs.autoScroll || filtered.length === 0) return; const last = filtered.length - 1; rowVirtualizer.scrollToIndex(last, { align: 'end' }); const raf = requestAnimationFrame(() => rowVirtualizer.scrollToIndex(last, { align: 'end' })); return () => cancelAnimationFrame(raf); // eslint-disable-next-line react-hooks/exhaustive-deps }, [logs, filtered.length, prefs.autoScroll, prefs.wrap]); // Entrance detection lives in the flush (real arrivals only). Here we just keep // the flush's motion read live, since it was captured once in the [api] effect. const motionOn = !appearance.reduceMotion && !appearance.disableMotion; useEffect(() => { motionOnRef.current = motionOn; }, [motionOn]); // Scroll-position-aware edge fade: fade a boundary only when hidden content // actually exists past it, so a fully-scrolled top/bottom row is never dimmed. const [edges, setEdges] = useState({ top: false, bottom: false }); const recomputeEdges = useCallback(() => { const el = scrollRef.current; if (!el) return; const top = el.scrollTop > 4; // small hysteresis so a 1px nudge can't flicker the fade const bottom = el.scrollTop + el.clientHeight < el.scrollHeight - 1; setEdges((p) => (p.top === top && p.bottom === bottom ? p : { top, bottom })); }, []); useEffect(() => { const el = scrollRef.current; if (!el) return; recomputeEdges(); el.addEventListener('scroll', recomputeEdges, { passive: true }); // A ResizeObserver on the viewport catches height changes the scroll/content // effects miss — e.g. the options panel expanding above the list, or a window // resize — in one listener. const ro = new ResizeObserver(() => recomputeEdges()); ro.observe(el); return () => { el.removeEventListener('scroll', recomputeEdges); ro.disconnect(); }; }, [recomputeEdges]); // New lines / wrap changes shift the overflow, so recheck the edges then too. useEffect(() => { recomputeEdges(); }, [filtered.length, prefs.wrap, recomputeEdges]); const maskCls = appearance.disableMotion ? undefined : edges.top && edges.bottom ? 'log-fade-both' : edges.top ? 'log-fade-top' : edges.bottom ? 'log-fade-bottom' : undefined; // Any hand edit to the bundled prefs drops the active preset to 'custom'. const toggleLevel = (lv: LogLevel) => { const next = new Set(enabled); if (next.has(lv)) next.delete(lv); else next.add(lv); setPages({ logs: { ...prefs, visibleLevels: LEVELS.filter((l) => next.has(l)), preset: 'custom' } }); }; const clearFilters = useCallback(() => { setFilter(''); setPages({ logs: { ...prefs, visibleLevels: [...LEVELS], preset: 'custom' } }); }, [prefs, setPages]); const applyPreset = useCallback((p: typeof LOG_PRESETS[number]) => { setPages({ logs: { ...prefs, ...p.bundle, preset: p.id } }); }, [prefs, setPages]); // Dump the current (filtered) view to a .log text file — purely client-side. const exportLogs = useCallback(() => { if (filtered.length === 0) return; const lines = filtered.map((l) => sanitizeLogLine( l.line || `${l.time} ${l.level.toUpperCase().padEnd(7)} [${l.scope}] ${l.message}`, )); const blob = new Blob([lines.join('\n') + '\n'], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); a.href = url; a.download = `snowluma-logs-${ts}.log`; a.click(); URL.revokeObjectURL(url); }, [filtered]); const exportFullTrace = useCallback(async () => { if (traceExportBusy) return; setTraceExportBusy(true); try { const { text, filename } = await runAction( { title: '正在导出完整 TRACE', detail: '正在读取服务端 TRACE 文件', successTitle: '完整 TRACE 已导出', errorTitle: 'TRACE 导出失败', }, () => api.logs.exportTrace(), ); const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); } catch (err) { console.error('exportTrace', err); } finally { setTraceExportBusy(false); } }, [api, traceExportBusy, runAction]); const addHighlight = () => { const kw = newKeyword.trim(); if (!kw) return; setPages({ logs: { ...prefs, highlightRules: [...prefs.highlightRules, { keyword: kw, color: newColor }].slice(0, 20) } }); setNewKeyword(''); }; const removeHighlight = (idx: number) => { setPages({ logs: { ...prefs, highlightRules: prefs.highlightRules.filter((_, i) => i !== idx) } }); }; const live = streamStatus === '实时'; const connecting = streamStatus === '连接中' || streamStatus === '重连中'; const levelsFiltered = enabled.size < LEVELS.length; return ( {/* ── Toolbar ─────────────────────────────────────────────── */}
运行日志 {streamStatus}
{filtered.length}/{logs.length} 条 · SSE 实时推送 {serverLevel && ( <> {' · 服务端 '} {serverLevel.toUpperCase()} )}
setFilter(e.target.value)} className="h-8 w-44 rounded-lg pl-8 pr-7 sm:w-56" /> {filter && ( )}
setPages({ logs: { ...prefs, autoScroll: !prefs.autoScroll, preset: 'custom' } })} > {prefs.autoScroll ? : } setPages({ logs: { ...prefs, wrap: !prefs.wrap, preset: 'custom' } })} > setShowOptions((v) => !v)}>
void loadLogs()}> void exportFullTrace()} disabled={traceExportBusy}> setConfirmClear(true)}>
{serverLevel === 'trace' && (
TRACE 已开启:正在记录大量、可能未经脱敏的数据
)} {/* ── Level filter (segmented, always visible) ────────────── */}
{LEVELS.map((lv) => { const active = enabled.has(lv); return ( ); })}
{/* ── Options panel (progressive disclosure) ──────────────── */} {showOptions && (
{/* View presets */}
视图预设 · 一键套用级别 / 行数 / 换行;手动调整后变为「自定义」
{LOG_PRESETS.map((p) => { const active = prefs.preset === p.id; return ( ); })} 自定义
{/* Server-side level */}
服务端日志级别 · 普通日志仅影响控制台 / 实时流;首次登录凭据仅输出到启动终端;文件等级由环境变量决定,默认为 debug
{serverLevelReady ? ( serverLevelError ? (
{serverLevelError}
) : (
{LEVELS.map((lv) => { const active = serverLevel === lv; return ( ); })}
) ) : null}
{/* Highlight rules */}
高亮规则 · 命中关键词的行会被着色
setNewKeyword(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') addHighlight(); }} className="h-8 w-44 rounded-lg" />
{HIGHLIGHT_COLORS.map((c) => (
{prefs.highlightRules.length > 0 && (
{prefs.highlightRules.map((r, i) => ( {r.keyword} ))}
)}
)}
{/* ── Log stream ──────────────────────────────────────────── */}
{/* Column header lives OUTSIDE the scroll viewport so the virtualizer's scroll element contains only the rows (no sticky-offset math). */} {logsReady && filtered.length > 0 && (
时间 级别 模块 消息
)} {logsReady && logsError && logs.length > 0 && (
{logsError};当前显示已读取和实时接收的日志。
)} div]:!block', maskCls)}> {logsReady ? (
{logsError && logs.length === 0 ? (
{logsError}
) : filtered.length === 0 ? (
{logs.length === 0 ? ( <> 暂无日志 ) : ( <> 没有符合筛选条件的日志 )}
) : (
{rowVirtualizer.getVirtualItems().map((vRow) => { const log = filtered[vRow.index]; if (!log) return null; // guard a transient count/measurement skew const hl = matchHighlight(log.message, prefs.highlightRules); // Entrance is decided entirely by animatingRef (populated in // the flush from real arrivals, pruned at 260ms), so it fires // on the first paint, never replays on scroll-into-view, and // is immune to filter/idle churn. Outer = positioning + // measurement (its translateY); inner = visual row + the // transform-based entrance, kept separate so they never collide. const entering = animatingRef.current.has(log.id); return (
{formatClock(log.time)} {log.level.toUpperCase()} [{log.scope}]
{log.req !== undefined && ( #{log.req} )} {log.message}
); })}
)}
) : null}

开启前请确认:

    {TRACE_CONFIRMATION_WARNINGS.map((warning) => (
  • {warning}
  • ))}
)} confirmText="开启 TRACE" destructive onConfirm={() => applyServerLevel('trace')} /> setLogs([])} />
); }