import { AlertTriangle, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw } from 'lucide-react' import React, { useLayoutEffect, useMemo, useRef, useState } from 'react' import { t } from '../i18n' import { LogLine } from '../lib/logs' import { taskDetail, taskTitle } from '../lib/tasks' import { HostReport, Locale, Task } from '../types' import { Button, IconButton, Tip } from '../ui/controls' export type LogTab = 'app' | 'serial' | 'qemu' interface Props { locale: Locale open: boolean onToggle: () => void tab: LogTab onTab: (tab: LogTab) => void lines: LogLine[] unseenErrors: number onClear: () => void serialText: string qemuText: string showSerial: boolean onRefreshSerial: () => void onRefreshQemu: () => void task: Task | null runningTasks: number onCancelTask: (id: string) => void host?: HostReport runningVMs?: number onCopy?: (text: string) => void /** False when WHPX or the runtime needs attention; the bar then leads with a link to the host page. */ hostReady?: boolean onOpenHost?: () => void } /** Sticks to the bottom until the user scrolls up; offers "jump to latest" then. */ function useStickToBottom(dep: unknown, active: boolean) { const ref = useRef(null) const [stuck, setStuck] = useState(true) useLayoutEffect(() => { const el = ref.current if (el && active && stuck) el.scrollTop = el.scrollHeight }, [dep, active, stuck]) const onScroll = () => { const el = ref.current if (!el) return setStuck(el.scrollHeight - el.scrollTop - el.clientHeight < 24) } const jump = () => { const el = ref.current if (el) el.scrollTop = el.scrollHeight setStuck(true) } return { ref, stuck, onScroll, jump } } const LogRow = React.memo(({ line }: { line: LogLine }) => (
{line.ts} {line.source} {line.line}
)) LogRow.displayName = 'LogRow' const LOG_HEIGHT_KEY = 'reims-go-log-height' const DEFAULT_LOG_HEIGHT = 240 const MIN_LOG_HEIGHT = 120 const MAX_LOG_HEIGHT = 520 export const LogPanel: React.FC = ({ locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu, task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, hostReady = true, onOpenHost, }) => { const tr = (k: Parameters[1], v?: Record) => t(locale, k, v) const [query, setQuery] = useState('') const [errorsOnly, setErrorsOnly] = useState(false) const q = query.trim().toLowerCase() const filteredLines = useMemo(() => { return lines.filter((l) => { if (errorsOnly && l.level !== 'error' && l.level !== 'warn') return false if (q && !l.line.toLowerCase().includes(q) && !l.source.toLowerCase().includes(q)) return false return true }) }, [lines, errorsOnly, q]) // Same element list while the lines are unchanged, so an App re-render for // something else doesn't rebuild up to MAX_LOG_LINES rows; a new line renders // just its own row (LogRow is memoised on the line object). const rows = useMemo(() => filteredLines.map((l) => ), [filteredLines]) const filteredText = useMemo(() => { const raw = tab === 'serial' ? serialText : qemuText if (!q || !raw) return raw return raw.split('\n').filter((line) => line.toLowerCase().includes(q)).join('\n') }, [tab, serialText, qemuText, q]) const copyVisible = () => { if (!onCopy) return if (tab === 'app') { const txt = filteredLines.map((l) => `${l.ts} [${l.source}] ${l.line}`).join('\n') if (txt) onCopy(txt) } else if (filteredText) { onCopy(filteredText) } } const content = tab === 'app' ? filteredLines : filteredText const { ref, stuck, onScroll, jump } = useStickToBottom(content, open) const memPct = host ? Math.max(0, Math.min(100, host.memory_load_pct > 0 ? host.memory_load_pct : host.total_ram_gb > 0 ? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100) : 0)) : 0 const usedMemGB = host && host.total_ram_gb > 0 ? Math.max(0, host.total_ram_gb - host.avail_ram_gb) : 0 const memTone = memPct >= 90 ? ' high' : memPct >= 80 ? ' warn' : '' const lowDisk = !!host && host.free_disk_gb > 0 && host.free_disk_gb < 30 // "D:\Data\reims-go" → "D:": the drive VM disks and snapshots grow on. const dataDrive = /^([A-Za-z]:)/.exec(host?.data_root ?? '')?.[1]?.toUpperCase() ?? '' const [height, setHeight] = useState(() => { try { const saved = Number(localStorage.getItem(LOG_HEIGHT_KEY)) if (Number.isFinite(saved) && saved >= MIN_LOG_HEIGHT && saved <= MAX_LOG_HEIGHT) return saved } catch {} return DEFAULT_LOG_HEIGHT }) const [dragging, setDragging] = useState(false) const dragRef = useRef<{ startY: number; startH: number } | null>(null) const onResizeDown = (e: React.PointerEvent) => { e.preventDefault() e.currentTarget.setPointerCapture(e.pointerId) dragRef.current = { startY: e.clientY, startH: height } setDragging(true) } const onResizeMove = (e: React.PointerEvent) => { if (!dragRef.current) return const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, Math.round(dragRef.current.startH + (dragRef.current.startY - e.clientY)))) setHeight(next) } const onResizeUp = (e: React.PointerEvent) => { if (!dragRef.current) return dragRef.current = null setDragging(false) if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId) try { localStorage.setItem(LOG_HEIGHT_KEY, String(height)) } catch {} } return (
{open && (
{ if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return e.preventDefault() const delta = e.key === 'ArrowUp' ? 24 : -24 const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, height + delta)) setHeight(next) try { localStorage.setItem(LOG_HEIGHT_KEY, String(next)) } catch {} }} onDoubleClick={() => { setHeight(DEFAULT_LOG_HEIGHT) try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {} }} >
)}
{task ? ( <> {task.cancelable && ( } onClick={() => onCancelTask(task.id)} /> )} ) : host ? ( // Host at a glance: a problem first (only when there is one), then // memory, the data drive and running VMs. "Label value" pairs with // thin rules between them; exact figures live in the tooltips.
{!hostReady && onOpenHost && ( )} {host.total_ram_gb > 0 && ( {tr('footerMemLabel')} {tr('footerMemValue', { used: usedMemGB.toFixed(1), total: host.total_ram_gb.toFixed(0) })} )} {host.free_disk_gb > 0 && ( {dataDrive || tr('footerDiskLabel')} {tr('footerDiskValue', { gb: host.free_disk_gb.toFixed(0) })} )} {runningVMs > 0 && ( )}
) : null} {open && ( <> setQuery(e.target.value)} /> {tab === 'app' && ( )}
{ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return e.preventDefault() const order: LogTab[] = showSerial ? ['app', 'serial', 'qemu'] : ['app'] const cur = Math.max(0, order.indexOf(tab)) const isRTL = getComputedStyle(e.currentTarget).direction === 'rtl' const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1 const next = order[(cur + delta + order.length) % order.length] onTab(next) const btns = e.currentTarget.querySelectorAll('[role="tab"]') btns[order.indexOf(next)]?.focus() }} > {showSerial && ( <> )}
)} {open && onCopy && ( } onClick={copyVisible} /> )} {open && tab === 'app' && lines.length > 0 && ( } onClick={onClear} /> )} {open && tab === 'serial' && ( } onClick={onRefreshSerial} /> )} {open && tab === 'qemu' && ( } onClick={onRefreshQemu} /> )} {!open && unseenErrors > 0 && }
{open && (
{tab === 'app' ? (filteredLines.length === 0 ? {tr('logsEmpty')} : rows) : (filteredText || {tr('logsEmpty')})}
{!stuck && ( )}
)}
) }