import React, { useEffect, useId, useMemo, useState } from "react"; import { ArrowDown, ArrowUp, Clock3, Copy, Cpu, Gauge, Gpu, HardDrive, LayoutGrid, List, MemoryStick, Pencil, Play, Plus, Server, Square, Terminal, Trash2, } from "lucide-react"; import { useI18n } from "../../application/i18n/I18nProvider"; import { deleteMonitorPanel, saveMonitorPanel, useMonitorPanels, } from "../../application/state/monitorPanelsStorage"; import { monitorActions, useMonitorSnapshot, } from "../../application/state/monitorRuntimeStore"; import { DEFAULT_MONITOR_INTERVAL, MONITOR_INTERVALS, reorderMonitorHosts, type MonitorPanel } from "../../domain/monitorPanels"; import { monitorStateSince, type MonitorHostState, type MonitorPoint, } from "../../domain/monitorRuntime"; import type { Host } from "../../domain/models"; import { buildMonitorTrendGeometry, findMonitorChartPoint } from "../../domain/monitorChart"; import { cn } from "../../lib/utils"; import { Button } from "../ui/button"; import { ContextMenuItem } from "../ui/context-menu"; import { Input } from "../ui/input"; import { Label } from "../ui/label"; import { Textarea } from "../ui/textarea"; import { Combobox } from "../ui/combobox"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "../ui/select"; import { AsideActionMenu, AsideActionMenuItem, AsidePanel, AsidePanelContent, AsidePanelFooter, } from "../ui/aside-panel"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../ui/dialog"; import SelectHostPanel from "../SelectHostPanel"; import { DistroAvatar } from "../DistroAvatar"; import { ResourceBar } from "../systemManager/ResourceBar"; import { MonitorDiskUsage } from "./MonitorDiskUsage"; import { MonitorDiskIo } from "./MonitorDiskIo"; import { useMonitorDiskGroups } from "../../application/state/useMonitorDiskGroups"; import { formatMonitorRate as rate } from "../../domain/monitorFormatting"; import { VaultHeaderSearch, VaultPageHeader, vaultHeaderIconButtonClass, vaultHeaderSecondaryButtonClass } from "./VaultPageHeader"; import { toast } from "../ui/toast"; import { TooltipProvider } from "../ui/tooltip"; import { MonitorHostCollection } from "./MonitorHostCollection"; import { MonitorHostLatency, MonitorHostNotes, MonitorHostTags } from "./MonitorHostMetadata"; const emptyMonitorPoints: MonitorPoint[] = []; const percent = (n: number | null | undefined) => n == null || !Number.isFinite(n) ? "--" : `${n.toFixed(1)}%`; const capacity = (n: number | null | undefined) => n == null ? "--" : n >= 1024 ? `${(n / 1024).toFixed(1)} GiB` : `${n.toFixed(0)} MiB`; const monitorAsideHeaderClass = "relative h-14 py-0 border-b-0 after:pointer-events-none after:absolute after:inset-x-0 after:bottom-0 after:h-px after:origin-bottom after:[transform:scaleY(.5)] after:bg-border/40 after:content-['']"; const monitorAsideClass = "border-border/30 shadow-[-12px_0_24px_hsl(var(--foreground)/0.04)]"; /** Sparse lines: never bridge a missing sample or invent history before monitoring started. */ export const MonitorTrend = React.memo(function MonitorTrend({ points, field, range, interval, clock, label, className, }: { points: MonitorPoint[]; field: "cpu" | "memory" | "rx" | "tx"; range: number; interval: number; clock: number; label: string; className?: string; }) { const gradientId = useId(); const { resolvedLocale } = useI18n(); const [hoverAt, setHoverAt] = useState(null); const { end, start, visible, max, segments } = useMemo( () => buildMonitorTrendGeometry(points, field, range, interval, Math.max(Date.now(), clock * 5000)), [points, field, range, interval, clock], ); const hovered = hoverAt == null ? undefined : visible.find((p) => p.at === hoverAt); const hoveredValue = hovered?.[field]; const hoverX = hovered ? ((hovered.at - start) / (end - start)) * 300 : 0; const hoverY = hoveredValue == null ? 0 : 58 - (Math.min(max, Math.max(0, hoveredValue)) / max) * 54; return (
{ const rect = event.currentTarget.getBoundingClientRect(); if (!rect.width) return; const fraction = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)); const point = findMonitorChartPoint( visible, field, start + fraction * (end - start), Math.max(interval * 1250, ((end - start) / rect.width) * 4), ); setHoverAt(point?.at ?? null); }} onPointerLeave={() => setHoverAt(null)} > {segments.map(({ path, firstX, x, y }, i) => ( ))} {hoveredValue != null && ( )} {hovered && hoveredValue != null && (
{label} · {field === "cpu" || field === "memory" ? `${hoveredValue.toFixed(2)}%` : rate(hoveredValue)}
)}
); }); export function MonitorPanels({ hosts, customGroups, onConnect, }: { hosts: Host[]; customGroups: string[]; onConnect: (host: Host) => void; }) { const { t } = useI18n(); const panels = useMonitorPanels(); const runtime = useMonitorSnapshot(); const diskGroups = useMonitorDiskGroups(); const [selected, setSelected] = useState(null); const [search, setSearch] = useState(""); const [dragging, setDragging] = useState<{ panelId: string; hostId: string } | null>(null); const [dropTarget, setDropTarget] = useState(null); const [editor, setEditor] = useState<{ base: MonitorPanel | null; draft: MonitorPanel; } | null>(null); const [selecting, setSelecting] = useState(false); const [detail, setDetail] = useState(null); const [recovery, setRecovery] = useState<{ hostId: string; username: string; password: string } | null>(null); const [deleting, setDeleting] = useState(null); const [error, setError] = useState(null); const [saving, setSaving] = useState(false); const panel = panels.find((p) => p.id === selected) ?? panels[0]; const running = !!panel && runtime.running.includes(panel.id); const startEdit = (base: MonitorPanel | null) => { setDetail(null); setRecovery(null); setSelecting(false); setError(null); setEditor({ base, draft: base ? { ...base, hostIds: [...base.hostIds] } : { id: crypto.randomUUID(), name: "", description: "", hostIds: [], view: "charts", interval: DEFAULT_MONITOR_INTERVAL, range: 15, sort: "manual", }, }); }; const updateDraft = (patch: Partial) => setEditor((prev) => prev ? { ...prev, draft: { ...prev.draft, ...patch } } : prev, ); const save = async () => { if (!editor) return; if (!editor.draft.name.trim()) { setError("monitor.nameRequired"); return; } if (!editor.draft.hostIds.length) { setError("monitor.hostRequired"); return; } setSaving(true); try { await saveMonitorPanel(editor.base, editor.draft); setSelected(editor.draft.id); setEditor(null); } catch (e) { setError( e instanceof Error && e.message.startsWith("monitor.") ? e.message : "monitor.saveFailed", ); } finally { setSaving(false); } }; const patchPanel = async (patch: Partial) => { if (!panel) return; try { await saveMonitorPanel(panel, { ...panel, ...patch }); } catch { toast.error(t("monitor.saveFailed")); } }; const duplicate = async () => { if (!panel) return; let name = t("monitor.copyName", { name: panel.name }); let suffix = 2; while ( panels.some( (p) => p.name.toLocaleLowerCase() === name.toLocaleLowerCase(), ) ) name = `${t("monitor.copyName", { name: panel.name })} ${suffix++}`; const copy = { ...panel, id: crypto.randomUUID(), name }; try { await saveMonitorPanel(null, copy); setSelected(copy.id); setDetail(null); setEditor(null); } catch { toast.error(t("monitor.saveFailed")); } }; const hostById = useMemo( () => new Map(hosts.map((host) => [host.id, host])), [hosts], ); const orderedHostIds = useMemo(() => { if (!panel) return []; return panel.sort === "manual" ? panel.hostIds : [...panel.hostIds].sort((a, b) => (hostById.get(a)?.label ?? a).localeCompare( hostById.get(b)?.label ?? b, ), ); }, [panel, hostById]); const rows = useMemo(() => { if (!panel) return []; const q = search.trim().toLocaleLowerCase(); const rows = orderedHostIds.map((id) => ({ id, host: hostById.get(id), state: monitorStateSince(runtime.hosts[id], runtime.startedAt[panel.id]), })); return rows.filter( ({ host }) => !q || `${host?.label ?? ""} ${host?.hostname ?? ""} ${host?.group ?? ""} ${host?.tags.join(" ") ?? ""} ${host?.notes ?? ""}` .toLocaleLowerCase() .includes(q), ); }, [panel, orderedHostIds, hostById, runtime, search]); const dragProps = ( hostId: string, ): React.HTMLAttributes & { "data-monitor-host": string } => ({ draggable: true, "data-monitor-host": hostId, onDragStart: (event) => { if (!panel) return; event.dataTransfer.effectAllowed = "move"; event.dataTransfer.setData("text/plain", hostId); setDragging({ panelId: panel.id, hostId }); }, onDragOver: (event) => { if ( !panel || dragging?.panelId !== panel.id || dragging.hostId === hostId ) return; event.preventDefault(); event.dataTransfer.dropEffect = "move"; setDropTarget(hostId); }, onDrop: (event) => { if (!panel || dragging?.panelId !== panel.id) return; event.preventDefault(); if (dragging.hostId !== hostId) void patchPanel({ hostIds: reorderMonitorHosts(orderedHostIds, dragging.hostId, hostId), sort: "manual", }); setDragging(null); setDropTarget(null); }, onDragEnd: () => { setDragging(null); setDropTarget(null); }, }); const status = (host: Host | undefined, state?: MonitorHostState) => !host ? "missing" : !running ? "stopped" : state?.status === "live" && Date.now() - state.at > Math.max( 5000, (panel?.interval ?? DEFAULT_MONITOR_INTERVAL) * 2500, ) ? "stale" : (state?.status ?? "queued"); const stateBadge = (host: Host | undefined, state?: MonitorHostState) => ( ); const renderMetrics = ( state: MonitorHostState | undefined, large = false, ) => { const s = state?.stats; const memory = s?.memTotal && s.memUsed != null ? (s.memUsed / s.memTotal) * 100 : null; return (
{t("monitor.cpu")}
{percent(s?.cpu)}
{s?.cpuCores ? t("monitor.cores", { count: s.cpuCores }) : "--"}
{panel && ( )}
{t("monitor.memory")}
{percent(memory)}
{capacity(s?.memUsed)} / {capacity(s?.memTotal)}
{panel && ( )}
); }; const hostDetail = hosts.find((h) => h.id === detail); const detailState = detail && panel ? monitorStateSince(runtime.hosts[detail], runtime.startedAt[panel.id]) : undefined; const detailAvailable = status(hostDetail, detailState) === "live"; useEffect(() => { if (detail && !detailAvailable) setDetail(null); }, [detail, detailAvailable]); return (
{panel && ( <> ({ value: p.id, label: p.name, sublabel: p.description, }))} value={panel.id} onValueChange={(id) => { setSelected(id); setDetail(null); setEditor(null); }} triggerClassName="w-56 min-w-24 shrink" clearable={false} ariaLabel={t("monitor.choosePanel")} /> { void duplicate(); }} > {t("monitor.copy")} setDeleting(panel)} > {t("monitor.delete")} {!!runtime.count && ( {t("monitor.stopAll")} )} )}
{panel && ( )} {runtime.unavailable && (

{t("monitor.unavailable")}

)} {!panel ? (

{t("monitor.empty")}

{t("monitor.emptyHint")}

) : ( <>
{(["list", "charts"] as const).map((view) => ( ))}
setSearch(e.target.value)} placeholder={t("monitor.search")} className="min-w-36 flex-1" inputClassName="h-8 text-xs" />
{!rows.length ? (
{t("monitor.noMatches")}
) : ( ( <> host && onConnect(host)}> {t("monitor.openTerminal")} {host && running && ["login", "error", "disconnected"].includes(status(host, state)) && ( setRecovery({hostId: id, username: host.username ?? "", password: ""})}> {t("monitor.retry")} )} )} rowProps={({ id, host, state }) => ({ ...dragProps(id), className: cn( "group cursor-default [&>td]:bg-card/70 hover:[&>td]:bg-card [&>td:first-child]:rounded-l-xl [&>td]:min-w-0 [&>td]:px-3 [&>td]:py-3 [&>td]:flex [&>td]:items-center", dragging?.panelId === panel.id && dragging.hostId === id && "cursor-grabbing opacity-40", dropTarget === id && "[&>td]:bg-accent", status(host, state) !== "live" && "text-muted-foreground opacity-50", ), })} renderCard={({ id, host, state }) => (
)} renderCells={({ id, host, state }, visibleColumns) => { const diskLayout = diskGroups.layoutFor(id, state?.stats); return ({ host: ( ), latency: ( ), tags: ( ), notes: (
), cpu: ( ), memory: ( ), disks: (
diskGroups.toggle(id)} />
), diskIo: ( diskGroups.toggle(id)} /> ), network: (
{t("monitor.download")}:{" "} {rate( state?.stats?.networkReady ? state.stats.netRxSpeed : null, )}
{t("monitor.upload")}:{" "} {rate( state?.stats?.networkReady ? state.stats.netTxSpeed : null, )}
), updated: ( {state?.at ? new Date(state.at).toLocaleTimeString() : "--"} ), status: ({stateBadge(host, state)}), terminal: ( ) }); }} />
)} )}
{editor && !selecting && ( setEditor(null)} title={t(editor.base ? "monitor.edit" : "monitor.create")} layout="inline" resizable resizeAriaLabel={t("vault.panel.resizeWidth")} headerClassName={monitorAsideHeaderClass} width="w-[380px]" className={monitorAsideClass} >
updateDraft({ name: e.target.value })} />