// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // System's Overview (components/SystemInfo.tsx): the machine at a glance, a // resource monitor. Rendered only while System's window shows this section, // which is also when stats.ts takes its full samples every INTERVAL // (useStats()); otherwise the top bar's light, slower ones go on // (TopBar.tsx), so its charts may start with what they gathered. // - The state (#sys-state, its dot, Settings…), the uptime (the guest's // /proc/uptime, else the SDK's time since kernel entry), the distro and // its image id, the kernel release, the CPUs and the time to boot. // - Panels, in a grid by the section's own width (container queries: one // column at phone width, two, then three), each a figure, a chart of the // last three minutes or a meter, and a few short facts; each resource in // its colour (Charts.tsx TONE, as in the top bar's applets): // CPU (busy history, each CPU's bar, load, tasks, context switches); // Memory (in use, cache and free as one bar, in-use history, swap); // Disk (/data and the root's own changes as bars, host block I/O history // and rates, the root image); Network (received and sent history, the // interface, totals); GPU, only with guest GL (frames per second the GPU // path showed, or the renderer's command buffers per second without // virtio-gpu; the renderer's share of the page's time, fences, errors, // the scanout, the WebGL2 implementation: the GPU's own load is not // measured, WebGL does not tell); Vulkan, only with guest Vulkan (vm.vk: // frames per second presented with those read back, or compute // dispatches per second while nothing presents; bytes to the GPU and read // back per second; draws, dispatches and submits per second, the // renderer's share of the page's time, the instances, live objects, // pipelines, shader translations, errors and device losses in red, the // load time, the WebGPU adapter; before its load, its state); Emulator // (JIT compiles or task switches); Processes (the busiest TOP, sortable // by CPU or memory). // What needs the guest says it waits for it until its first read (and the // rest shows). Sources: the guest's /proc through stats.ts, the SDK's // vm.stats() (block I/O, the JIT, task switches), vm.gl and vm.vk, the store (the // data disk) and the page's config. // - Boot, under the panels: the stages (ui.stages()) as a timeline from the // page's load, stages that overlap on lanes of their own, and their list // (#stages, a row per stage with data-s, its state). A segment under the // pointer, focused or tapped shows its name, start, duration and detail, // and it and its row are highlighted (a row under the pointer does the // same for its segment). // - Machine: the facts the Overview listed before (kernel build, distro URL, // CPUs, memory, data disk, command line), last and small. import { useRef, useState, type ReactNode } from "react"; import { useOutsidePress, useTick } from "../hooks.ts"; import { openSection } from "../sysapps.ts"; import { KW } from "../kw.ts"; import { DEFAULT_WISP_SERVERS } from "../net.ts"; import type { KernelHandle } from "../sdk.ts"; import { INTERVAL, RING, useStats, type DfRow, type NetDev, type Point, type StatsState, type TopProc } from "../stats.ts"; import { isRunning, isStarting, phase, useStore } from "../store.ts"; import { capitalize, fmtBytes, fmtCount, fmtPct, fmtRate, fmtT, fmtUptime, plural } from "../format.ts"; import { H3 } from "./AppShell.tsx"; import { Bars, Key, Meter, SECOND, Spark, TONE, fullness } from "./Charts.tsx"; import { diskUse, GPU_STATE, gpuSeries, latest, VK_STATE, vkPath, vkSeries, vkTrouble } from "./Glance.tsx"; import { ActivityIcon, CpuIcon, DiskIcon, GpuIcon, LogIcon, NetIcon, PromptIcon, RamIcon } from "./icons.tsx"; const B = __KW_BUILD__; // ---- formatting ------------------------------------------------------------------ // (sizes, rates, shares, counts, durations and plurals: format.ts) const MiB = 1048576; const pct = fmtPct; /** Rows of the process table. */ const TOP = 8; /** The charts' heights, px. */ const CHART_H = 48, CHART_H_SM = 36; const vmOf = () => KW.vm as KernelHandle | undefined; /** A colour, faded: a part of a meter next to its full tone. */ const faded = (c: string, f = 35) => `color-mix(in srgb, ${c} ${f}%, transparent)`; // ---- pieces -------------------------------------------------------------------------- function Card({ title, icon, tone, aside, children, className = "" }: { title: string; icon: ReactNode; tone?: string; aside?: ReactNode; children: ReactNode; className?: string }) { return (

{title}

{aside && {aside}}
{children}
); } /** The panel's figure, with its unit and what it is of. */ const Figure = ({ value, unit, of }: { value: ReactNode; unit?: ReactNode; of?: ReactNode }) => (

{value} {unit && {unit}} {of && {of}}

); /** Short facts: a label over each value. */ const Facts = ({ items }: { items: Array<[string, ReactNode] | false | null | undefined> }) => (
{items.filter((x): x is [string, ReactNode] => !!x).map(([k, v]) => (
{k}
{v}
))}
); /** A labelled meter: name and figures on one line, the bar under it. */ function Usage({ name, used, size, color, note }: { name: ReactNode; used: number; size: number; color: string; note?: string }) { const f = size > 0 ? used / size : 0; return (
{name} {fmtBytes(used)} of {fmtBytes(size)}{note ? ` ${note}` : ""} · {pct(f)}
); } /** In place of a chart that needs the guest: the same height, a quiet line. */ const Waiting = ({ why, height = CHART_H }: { why: string; height?: number }) => (
{why}
); /** Why a guest figure is not there yet. */ function waitText(st: StatsState): string { if (st.idle && st.idle !== "the page is hidden") return `Not sampled: ${st.idle}`; return "Waiting for the guest…"; } // ---- the state line -------------------------------------------------------------------- const STATE_TONE: Record = { running: "bg-ok", error: "bg-err", halted: "bg-off" }; function Uptime({ st }: { st: StatsState }) { const running = useStore(isRunning); // The clock moves while it runs (also while Suspend saves it), not while it is held. const live = useStore((s) => isRunning(s) && phase(s) !== "held"); useTick(1000, live); const since = (t: number) => (live ? (Date.now() - t) / 1000 : 0); let up: number | null = null; if (st.guest?.raw.uptime != null) up = st.guest.raw.uptime + since(st.guest.t); else if (running) { try { up = (vmOf()?.stats().uptimeMs ?? 0) / 1000 || null; } catch { /* stopped */ } } if (up == null) return null; return up {fmtUptime(up)}; } function StateLine({ st }: { st: StatsState }) { const state = useStore((s) => s.state); const label = useStore((s) => s.label); const suspended = useStore((s) => s.suspended); const paused = useStore((s) => s.paused); const distro = useStore((s) => s.distro); const p = useStore(phase); const busy = p === "starting"; const tone = p === "held" || p === "suspending" ? "bg-warn" : STATE_TONE[state] ?? "bg-warn"; const user = KW.ui!.stages().find((s) => s.id === "userspace"); const release = st.guest?.raw.release || B.linux; const name = distro ? capitalize(distro.name) : "Base shell"; const cpus = st.guest?.raw.stat?.cpus.length || KW.config.cpus; return (

{name}{distro?.image && <> {distro.image}} Linux {release || "?"} {cpus} {cpus === 1 ? "CPU" : "CPUs"} {user?.t1 != null && {user.detail === "resumed" ? "resumed in" : "booted in"} {fmtT(user.t1)}}

); } // ---- boot ------------------------------------------------------------------------------------ /** A stage's tone on the timeline: steps of the foreground, adjacent ones apart. */ const STAGE_TONE: Record = { preflight: faded("var(--color-fg)", 30), kernel: faded("var(--color-fg)", 90), compile: faded("var(--color-fg)", 55), memory: faded("var(--color-fg)", 35), boot: faded("var(--color-fg)", 75), userspace: faded("var(--color-fg)", 48), }; const STATE_WORD: Record = { done: "", fail: "failed", active: "running", pending: "pending", skip: "skipped" }; type StageRow = ReturnType["stages"]>[number]; /** * Each shown stage's lane: the first one free at its start, so stages that * overlap (the compile streams while the download runs) sit on lanes of their * own and none hides another. */ function lanes(stages: StageRow[], end: (s: StageRow) => number): Map { const ends: number[] = [], out = new Map(); for (const s of [...stages].sort((a, b) => a.t0! - b.t0!)) { let i = ends.findIndex((e) => e <= s.t0! + 1); if (i < 0) i = ends.length; ends[i] = end(s); out.set(s.id, i); } return out; } const LANE_H = 10, LANE_GAP = 3; function BootTimeline() { const ui = KW.ui!; const busy = useStore(isStarting); // The stages live in ui.ts, outside the store: read them again on any store change, and each second while booting. useStore((s) => s); useTick(1000, busy); // The stage under the pointer (a segment or its row), and the one focused or tapped. const [hover, setHover] = useState(null); const [sel, setSel] = useState(null); const box = useRef(null); // A tapped segment's label goes with a press anywhere else (touch: a button may not take the focus, so no blur). useOutsidePress(box, () => setSel(null), !!sel); const stages = ui.stages(); const now = Date.now() - KW.t0; const end = (s: StageRow) => s.t1 ?? (s.s === "active" ? now : null); const total = Math.max(1, ...stages.map((s) => end(s) ?? 0)); const user = stages.find((s) => s.id === "userspace"); const shown = stages.filter((s) => s.t0 != null && end(s) != null); const lane = lanes(shown, (s) => end(s)!); const nLanes = Math.max(1, ...[...lane.values()].map((i) => i + 1)); const hot = hover ?? sel; const describe = (s: StageRow) => `${s.label} · started at ${fmtT(s.t0!)} · ${s.t1 != null ? "took" : "running for"} ${fmtT(end(s)! - s.t0!)}${s.s === "fail" ? " · failed" : ""}`; const tip = shown.find((s) => s.id === hot); const center = tip ? Math.min(100, ((tip.t0! + end(tip)!) / 2 / total) * 100) : 0; return ( } aside={user?.t1 != null ? `${user.detail === "resumed" ? "resumed" : "user space"} at ${fmtT(user.t1)}` : busy ? "booting…" : ""}>
{Array.from({ length: nLanes }, (_, i) => (
    {stages.map((st) => (
  • setHover(st.id)} onPointerLeave={() => setHover(null)} className={`-mx-1 grid min-w-0 grid-cols-[auto_1fr_auto] items-baseline gap-x-2 rounded px-1 py-px text-[11.5px] ${st.s === "pending" ? "opacity-50" : ""} ${hot === st.id ? "bg-hover" : ""}`}>
  • ))}
); } // ---- the panels ------------------------------------------------------------------------------ function CpuCard({ st }: { st: StatsState }) { const cfg = KW.config; const g = st.guest, d = g?.derived, raw = g?.raw; const n = raw?.stat?.cpus.length || st.host?.stats.cpus || cfg.cpus; const load = raw?.load; return ( } tone={TONE.cpu} aside={`${plural(n, "CPU")}${cfg.worker ? ", Web Workers" : ""}`}>
{g ? p.cpu, label: "busy", color: TONE.cpu, area: true }]} max={1} fmt={pct} label="CPU use" /> : } {d?.cpus && `CPU ${i}`)} label="Each CPU's use" color={TONE.cpu} height={20} />} ); } function MemoryCard({ st }: { st: StatsState }) { const m = st.guest?.raw.mem; const host = KW.memActualMiB || vmOf()?.memoryMiB || 0; const used = m ? m.total - m.available : 0, cache = m ? Math.max(0, m.available - m.free) : 0; const f = m ? used / m.total : 0; const usedColor = fullness(f, TONE.mem), cacheColor = faded(TONE.mem); return ( } tone={TONE.mem} aside={host ? `${fmtBytes(host * MiB)} wasm` : undefined}>
{m ? ( <>
used {pct(f)} cache {fmtBytes(cache)} free {fmtBytes(m.free)}
p.mem, label: "in use", color: TONE.mem, area: true }]} max={m.total} fmt={fmtBytes} label="Guest memory in use" height={CHART_H_SM} /> {m.swapTotal > 0 && } ) : } ); } function DiskCard({ st }: { st: StatsState }) { const cfg = KW.config; const disk = useStore((s) => s.disk); const distro = useStore((s) => s.distro); const df: DfRow[] = (st.df ?? []).filter((r) => r.size > 0); const data = df.find((r) => r.mount === "/data"); const root = df.find((r) => r.mount === "/"); // An overlay root whose changes are on /data reports /data's file system: shown once. const rootOwn = root && !(data && root.size === data.size && Math.abs(root.used - data.used) < 4 * MiB) ? root : undefined; const du = diskUse(st, disk); const rd = latest(st.points, (p) => p.rd), wr = latest(st.points, (p) => p.wr); return ( } tone={TONE.disk} aside={disk ? (disk.saved ? "saved in this browser" : "in memory only") : "no data disk"}>
p.rd, label: "read", color: TONE.disk, area: true }, { get: (p) => p.wr, label: "write", color: SECOND }, ]} />
readwriteall disks
{du && } {rootOwn && } {distro?.image || cfg.distro.name}, {fmtBytes(cfg.distro.size)} : "base initramfs"], ]} />
); } const ifaces = (net: NetDev[]) => net.filter((n) => n.name !== "lo"); const host = (u: string) => { try { return new URL(u).host; } catch { return u; } }; function NetworkCard({ st }: { st: StatsState }) { const cfg = KW.config; const g = st.guest, raw = g?.raw, d = g?.derived; const netStats = st.host?.stats.net; if (!cfg.net) { return ( } tone={TONE.net} aside="no device">
openSection("network")}>Settings…]]} /> ); } const devs = raw ? ifaces(raw.net) : []; const dev = devs.find((x) => x.name === "eth0") ?? devs[0]; const oper = dev && raw ? raw.ifs[dev.name] : undefined; const servers = cfg.wisp ?? [...DEFAULT_WISP_SERVERS]; const tot = devs.reduce((a, x) => ({ rx: a.rx + x.rx, tx: a.tx + x.tx }), { rx: 0, tx: 0 }); return ( } tone={TONE.net} aside={dev ? <>{dev.name} {oper ?? "?"} : undefined}>
{g ? ( <> p.rx, label: "in", color: TONE.net, area: true }, { get: (p) => p.tx, label: "out", color: SECOND }, ]} />
inout
) : } {servers.map(host).join(", ")}], ]} />
); } /** Guest GL (stats.ts GpuInfo): shown only with it. */ function GpuCard({ st }: { st: StatsState }) { const gpu = st.gpu!; const gs = gpuSeries(gpu); const gv = latest(st.points, gs.get); const busy = latest(st.points, (p) => p.glBusy), cmd = latest(st.points, (p) => p.glCmd); const dev = gpu.device; const ready = gpu.state === "ready"; const lost = gpu.state === "lost" || !!dev?.contextLost; return ( } tone={TONE.gpu} aside={dev ? "virtio-gpu 3D" : "GL over vtest"}> {ready && !lost ?
:
} p.glBusy, label: "renderer", color: SECOND }]} />
{gs.label}renderer busy
{busy != null ? pct(busy) : "–"}], ready && dev && ["commands", cmd != null ? `${fmtCount(cmd)}/s` : "–"], dev?.scanout && ["scanout", `${dev.scanout.width}×${dev.scanout.height}`], dev && ["frames", fmtCount(dev.presents + gpu.wlGpu)], dev && dev.parks > 0 && ["fence waits", `${fmtCount(dev.parks)} of ${fmtCount(dev.fenced)}`], gpu.clients > 0 && ["vtest clients", String(gpu.clients)], dev && dev.errors > 0 && ["errors", {fmtCount(dev.errors)}], gpu.loadMs != null && ["loaded in", fmtT(gpu.loadMs)], ]} /> {gpu.webgl &&

WebGL2 {gpu.webgl}

} ); } /** Guest Vulkan (stats.ts VkInfo): shown only with it. */ function VkCard({ st }: { st: StatsState }) { const vk = st.vk!; const pts = st.points; const vs = vkSeries(pts); const vv = latest(pts, vs.get); const at = (get: (p: Point) => number | null) => latest(pts, get); const busy = at((p) => p.vkBusy), up = at((p) => p.vkUp), down = at((p) => p.vkDown); const draws = at((p) => p.vkDraws), disp = at((p) => p.vkDispatch), subs = at((p) => p.vkSubmits); const path = vkPath(at((p) => p.vkFps), at((p) => p.vkExt)); const r = vk.renderer; const ready = vk.state === "ready"; const bad = vkTrouble(vk); const frames = vs.label === "frames/s"; const rate = (v: number | null) => (v != null ? `${fmtCount(v)}/s` : "–"); return ( } tone={TONE.vk} aside={ready ? plural(vk.connections, "instance") : "on WebGPU"}> {ready ?
:
{capitalize(VK_STATE[vk.state])}} of={vk.state === "idle" ? "loads on the first Vulkan program" : vk.state === "lost" ? "restart the Vulkan programs" : undefined} />} (p.vkFps != null && p.vkExt != null ? Math.max(0, p.vkFps - p.vkExt) : null), label: "read back", color: SECOND }] : [{ get: vs.get, label: vs.label, color: TONE.vk, area: true }]} /> p.vkUp, label: "to GPU", color: TONE.vk, area: true }, { get: (p) => p.vkDown, label: "read back", color: SECOND }, ]} />
{frames ? "frames · to GPU" : `${vs.label} · to GPU`}read back
0 && ["errors", {fmtCount(bad.errors)}], bad && bad.losses > 0 && ["device lost", {bad.losses === 1 ? "once" : `${fmtCount(bad.losses)} times`}], bad && bad.lost > 0 && ["programs cut off", {fmtCount(bad.lost)}], vk.state === "failed" && ["error", {vk.error ?? "unknown"}], ready && ["renderer busy", {busy != null ? pct(busy) : "–"}], ready && ["draws", rate(draws)], ready && ["dispatches", rate(disp)], ready && ["submits", rate(subs)], ready && ["to GPU", up != null ? fmtRate(up) : "–"], ready && ["read back", down != null ? fmtRate(down) : "–"], r && ["frames", {fmtCount(r.presents)}], r && ["live objects", {fmtCount(r.liveObjects)} · {fmtCount(r.liveGpu)}], r && ["pipelines", fmtCount(r.pipelines)], r && ["shaders", {fmtCount(r.translations)}, {fmtT(r.translateMs)}], ["instances", `${fmtCount(vk.connections)} now · ${fmtCount(vk.opened)} so far`], vk.loadMs != null && ["loaded in", fmtT(vk.loadMs)], ]} /> {vk.adapter &&

WebGPU {vk.adapter}

} ); } function EmulatorCard({ st }: { st: StatsState }) { const cfg = KW.config; const s = st.host?.stats, j = s?.jit; const vm = vmOf(); const last = st.points[st.points.length - 1]; const jitOn = !!j?.enabled && !!j.requested; const runs = cfg.worker ? `Web Worker${vm?.transport === "shared" ? ", shared memory" : vm?.transport === "messages" ? ", messages" : ""}` : "the page's thread"; return ( } aside={`AArch64 on wasm${jitOn ? ", JIT" : j ? ", interpreter" : ""}`}> {jitOn ?
:
} {s ? ( `${fmtCount(v)}/s`} series={[jitOn ? { get: (p) => p.jit, label: "compiles", color: "var(--color-fg)", area: true } : { get: (p) => p.sw, label: "switches", color: "var(--color-fg)", area: true }]} /> ) : } 0 && ["failed", fmtCount(j.failed)], last?.sw != null && ["task switches", `${fmtCount(last.sw)}/s`], last?.mips != null && ["guest MIPS", last.mips.toFixed(1)], ["runs on", runs], ["isolation", crossOriginIsolated ? "isolated" : "not isolated"], ]} /> ); } type SortKey = "cpu" | "mem"; const byKey: Record number> = { cpu: (a, b) => (b.cpu ?? -1) - (a.cpu ?? -1) || b.rss - a.rss, mem: (a, b) => b.rss - a.rss || (b.cpu ?? -1) - (a.cpu ?? -1), }; function ProcessesCard({ st, className = "" }: { st: StatsState; className?: string }) { const [sort, setSort] = useState("cpu"); const g = st.guest, raw = g?.raw; const all = g?.derived.procs ?? []; const top = [...all].sort(byKey[sort]).slice(0, TOP); const memTotal = raw?.mem?.total ?? 0; // A plain call, not a component: a component made here would be new on each render and its button lose the focus at each sample. const th = (k: SortKey, label: string, c: string) => ( ); return ( } className={className} aside={raw ? `${all.length} user · ${raw.load ? fmtCount(raw.load.tasks) : "?"} tasks` : undefined}> {g && all.length ? ( {th("cpu", "CPU", "w-24")} {th("mem", "memory", "w-24")} {top.map((p) => ( ))}
The busiest user processes since the last sample; CPU is the share of one CPU, memory the resident set; kernel threads left out
process pid
{p.comm} {p.pid}
) : }
); } function Row({ k, children }: { k: string; children: ReactNode }) { return <>
{k}
{children}
; } function Machine() { const cfg = KW.config; const distro = useStore((s) => s.distro); const disk = useStore((s) => s.disk); const mem = KW.memActualMiB || cfg.memMiB; return (
Linux {B.linux || "?"}{B.kernel && , {B.kernel === "local" ? "local build" : B.kernel}} {distro ? <>{distro.image || distro.name}, {distro.url} : "none (base shell)"} {cfg.cpus}{cfg.worker ? , in Web Workers : , on the page's thread} {mem >= 1024 ? `${+(mem / 1024).toFixed(1)} GiB` : `${mem} MiB`} ({cfg.memWhy}) {disk ? <>{fmtBytes(disk.used)} of {fmtBytes(disk.size)}, {disk.saved ? "saved in this browser" : "in memory only"} : "none"} {cfg.cmdline}
); } /** Whether the numbers are live, and why not. */ function Live({ st }: { st: StatsState }) { const live = !st.idle; return ( ); } export function Overview() { const st = useStats(); const gpu = !!st.gpu, vk = !!st.vk; // The panels before Processes: five, with guest GL's and Vulkan's six or seven; it fills the grid's last row. const n = 5 + Number(gpu) + Number(vk); const span = `${n % 2 ? "" : "@lg:col-span-2"} ${["@4xl:col-span-3", "@4xl:col-span-2", "@4xl:col-span-1"][n % 3]}`; return (

Resources

{gpu && } {vk && }

Machine

); }