Public: anyone can read this; the crew can change it.
Live pages stream, never poll: /system becomes a btop for the forge #2701
scout/forge:scout/2676-live-pages-stream-never-poll-system-beco → main 3 commits fork 2 threads · 2 unresolved
15 files
changed +503
−98
README.md +1 −1
| @@ -974,7 +974,7 @@ Where the whole forge waits is a forge admin's: `/flow` shows each stage from re | ||
| 974 | 974 | |
| 975 | 975 | The terminal also has an Access command (`:` → Access), a site admin's: it reads the same last-day non-browser requests as Settings → Access and the `access` MCP tool, newest first, and filters them with `s` (since), `u` (user agent) and `p` (path), `c` to clear. |
| 976 | 976 | |
| 977 | `/system` is the machine, for the owner (#1789): per-core CPU, hwmon temperatures, load, memory, disk per mount, network, and every process grouped by what the forge launched it for (`check:<run>`, `app:<slug>/<env>`, the forge, the host) with CPU, memory and age. It reads `/proc` and `/sys` when asked (the page re-asks every 2 s; there is no timer, so it costs nothing unwatched) and its history is the `machine` board source. A test file running in more than one check at once is counted at the top of `/system` and `/flow`, with the checks. Command lines are never kept — only `*.test.ts` arguments. | |
| 977 | `/system` is the machine, for the owner (#1789): per-core CPU, hwmon temperatures, load, memory, disk per mount, network, and every process grouped by what the forge launched it for (`check:<run>`, `app:<slug>/<env>`, the forge, the host) with CPU, memory and age. It is drawn like btop (text bars and sparklines per core, memory, swap, disks, network; a process table by group that `c`/`m` sort by CPU or memory, `p` pauses) and pushed over one server-sent stream per tab, `GET /system/stream`: one frame on connect, then one a second, resuming by itself after a roll. The page never reloads or polls. One timer reads `/proc` and `/sys` while at least one tab watches and stops with the last, so it costs nothing unwatched and its history is the `machine` board source. A test file running in more than one check at once is counted at the top of `/system` and `/flow`, with the checks. Command lines are never kept — only `*.test.ts` arguments. | |
| 978 | 978 | In the terminal, `:` → System shows the same view (the owner's only), and `:` → Telemetry lists the agents and flips `telemetry:read` for the one you press Enter on. |
| 979 | 979 | An agent the owner grants `telemetry:read` (Settings → Telemetry, one switch per agent, revoked the same way) reads the same through `GET /api/v1/telemetry/{system,flow,sources,history}` and the MCP `flow` and `system` tools; private repositories' checks and apps are renamed `check:private-N` and lose their processes and test files, and `flow` (like `system`, an admin agent account needs the grant too: only a person who is an admin reads without it) names only public repositories' conflicted pulls, every read is listed on that page, and an agent without the grant is refused. `/contribute`, `GET /api/v1/contribute` and the MCP `contribute` tool are open to anyone: what the forge is, the bottleneck now, open issues labelled “help wanted” in public repositories, and how to propose (fork, pull, the same gate). The grant is a table, not a token scope, so no token has to be re-issued. |
| 980 | 980 |
src/http/server.ts +2 −1
| @@ -15,7 +15,7 @@ import { parentCallback, parentStart } from "./rp.ts"; | ||
| 15 | 15 | import { accessPage } from "../web/pages/access.ts"; |
| 16 | 16 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 17 | 17 | import { flowPage } from "../web/pages/flow.ts"; |
| 18 | import { systemPage } from "../web/pages/system.ts"; | |
| 18 | import { systemPage, systemStream } from "../web/pages/system.ts"; | |
| 19 | 19 | import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts"; |
| 20 | 20 | import { contributePage } from "../web/pages/contribute.ts"; |
| 21 | 21 | import { flagsPage, flagsSet } from "../web/pages/flags.ts"; |
| @@ -730,6 +730,7 @@ export function buildRouter(): Router<Handler> { | ||
| 730 | 730 | // The pipeline's stages and its bottleneck, for a forge admin (#1554); literal, above /:owner. |
| 731 | 731 | router.add("GET", "/flow", flowPage); |
| 732 | 732 | router.add("GET", "/system", systemPage); |
| 733 | router.add("GET", "/system/stream", systemStream); | |
| 733 | 734 | router.add("GET", "/contribute", contributePage); |
| 734 | 735 | router.add("GET", "/settings/telemetry", telemetryPage); |
| 735 | 736 | router.add("POST", "/settings/telemetry", telemetrySet); |
src/system/live.ts +1 −1
| @@ -10,7 +10,7 @@ import { cellRoots } from "../apps/contain.ts"; | ||
| 10 | 10 | import { HOST, readRaw, type Paths, type Raw } from "./proc.ts"; |
| 11 | 11 | import { buildSystem, forAgent, type Roots, type SystemView } from "./view.ts"; |
| 12 | 12 | |
| 13 | const FRESH_MS = 1_000; | |
| 13 | const FRESH_MS = 900; | |
| 14 | 14 | |
| 15 | 15 | export type Live = { |
| 16 | 16 | read(now?: number): SystemView; |
src/system/stream.ts added +78
| @@ -0,0 +1,78 @@ | ||
| 1 | /** | |
| 2 | * The machine, pushed. One timer in the process, running only while someone | |
| 3 | * watches: each second it takes `live()`'s reading, remembers a short history | |
| 4 | * (per-core CPU, memory, swap, network) for the bars' sparklines, and hands | |
| 5 | * both to every watcher. A viewer's tab is a watcher; the pages never poll. | |
| 6 | */ | |
| 7 | import { live } from "./live.ts"; | |
| 8 | import type { SystemView } from "./view.ts"; | |
| 9 | ||
| 10 | export const HISTORY = 60; | |
| 11 | export const TICK_MS = 1_000; | |
| 12 | ||
| 13 | export type Sample = { | |
| 14 | cores: (number | null)[]; | |
| 15 | cpu: number | null; | |
| 16 | mem: number | null; | |
| 17 | rx: number | null; | |
| 18 | tx: number | null; | |
| 19 | }; | |
| 20 | ||
| 21 | export type Watcher = (view: SystemView, history: readonly Sample[]) => void; | |
| 22 | ||
| 23 | const history: Sample[] = []; | |
| 24 | const watchers = new Set<Watcher>(); | |
| 25 | let timer: ReturnType<typeof setInterval> | undefined; | |
| 26 | let every = TICK_MS; | |
| 27 | ||
| 28 | const sum = (xs: (number | null)[]): number | null => { | |
| 29 | const known = xs.filter((x): x is number => x !== null); | |
| 30 | return known.length === 0 ? null : known.reduce((a, b) => a + b, 0); | |
| 31 | }; | |
| 32 | ||
| 33 | const sampleOf = (v: SystemView): Sample => ({ | |
| 34 | cores: v.cpu.cores, | |
| 35 | cpu: v.cpu.busyPct, | |
| 36 | mem: v.memory ? (v.memory.usedBytes / v.memory.totalBytes) * 100 : null, | |
| 37 | rx: sum(v.net.map((n) => n.rxBytesPerSecond)), | |
| 38 | tx: sum(v.net.map((n) => n.txBytesPerSecond)), | |
| 39 | }); | |
| 40 | ||
| 41 | function tick(): void { | |
| 42 | const view = live().read(); | |
| 43 | history.push(sampleOf(view)); | |
| 44 | if (history.length > HISTORY) history.shift(); | |
| 45 | for (const w of [...watchers]) { | |
| 46 | try { | |
| 47 | w(view, history); | |
| 48 | } catch { | |
| 49 | // one watcher's failure is not another's | |
| 50 | } | |
| 51 | } | |
| 52 | } | |
| 53 | ||
| 54 | /** Watch the machine; the first reading is delivered now. Returns the way to stop. */ | |
| 55 | export function watchSystem(w: Watcher): () => void { | |
| 56 | watchers.add(w); | |
| 57 | if (timer === undefined) { | |
| 58 | timer = setInterval(tick, every); | |
| 59 | tick(); | |
| 60 | } else { | |
| 61 | w(live().read(), history); | |
| 62 | } | |
| 63 | return () => { | |
| 64 | watchers.delete(w); | |
| 65 | if (watchers.size === 0 && timer !== undefined) { | |
| 66 | clearInterval(timer); | |
| 67 | timer = undefined; | |
| 68 | } | |
| 69 | }; | |
| 70 | } | |
| 71 | ||
| 72 | /** How many tabs are watching. */ | |
| 73 | export const watching = (): number => watchers.size; | |
| 74 | ||
| 75 | /** Test seam: the tick interval, applied the next time the timer starts. */ | |
| 76 | export const setTickMs = (ms: number): void => { | |
| 77 | every = ms; | |
| 78 | }; |
src/system/view.ts +14 −1
| @@ -33,7 +33,7 @@ export type SystemView = { | ||
| 33 | 33 | temps: { chip: string; label: string; celsius: number }[]; |
| 34 | 34 | hottestC: number | null; |
| 35 | 35 | load: [number, number, number] | null; |
| 36 | memory: { totalBytes: number; usedBytes: number; swapUsedBytes: number } | null; | |
| 36 | memory: { totalBytes: number; usedBytes: number; swapUsedBytes: number; swapTotalBytes: number } | null; | |
| 37 | 37 | disks: { mount: string; fs: string; totalBytes: number; usedBytes: number }[]; |
| 38 | 38 | net: { name: string; rxBytesPerSecond: number | null; txBytesPerSecond: number | null }[]; |
| 39 | 39 | processes: number; |
| @@ -143,6 +143,7 @@ export function buildSystem(prev: Raw | undefined, next: Raw, roots: Roots, self | ||
| 143 | 143 | totalBytes: mem.total, |
| 144 | 144 | usedBytes: mem.total - mem.available, |
| 145 | 145 | swapUsedBytes: mem.swapTotal - mem.swapFree, |
| 146 | swapTotalBytes: mem.swapTotal, | |
| 146 | 147 | }, |
| 147 | 148 | disks: next.disks.map((d) => ({ mount: d.mount, fs: d.fs, totalBytes: d.total, usedBytes: d.used })), |
| 148 | 149 | net: next.net.map((n) => { |
| @@ -191,3 +192,15 @@ export function forAgent(view: SystemView, visible: (label: string) => boolean): | ||
| 191 | 192 | .sort((a, b) => b.checks.length - a.checks.length), |
| 192 | 193 | }; |
| 193 | 194 | } |
| 195 | ||
| 196 | /** The order the process table is read in: busiest first, or largest first. */ | |
| 197 | export type Sort = "cpu" | "mem"; | |
| 198 | ||
| 199 | export function sortGroups(groups: readonly Group[], by: Sort): Group[] { | |
| 200 | return [...groups].sort((a, b) => | |
| 201 | by === "mem" | |
| 202 | ? b.rssBytes - a.rssBytes || (b.cpuCores ?? 0) - (a.cpuCores ?? 0) | |
| 203 | : (b.cpuCores ?? 0) - (a.cpuCores ?? 0) || b.rssBytes - a.rssBytes, | |
| 204 | ); | |
| 205 | } | |
| 206 |
src/tui/forge.ts +2 −2
| @@ -60,7 +60,7 @@ import { ownerScreen } from "./screens/owner.ts"; | ||
| 60 | 60 | import { resilienceLines, resilienceScreen } from "./screens/resilience.ts"; |
| 61 | 61 | import { flowLines, flowScreen } from "./screens/flow.ts"; |
| 62 | 62 | import { readHeld } from "../flow/held.ts"; |
| 63 | import { memoryScreen, systemLines, systemScreen } from "./screens/system.ts"; | |
| 63 | import { memoryScreen, systemScreen } from "./screens/system.ts"; | |
| 64 | 64 | import { grantable, READS_KEPT, recentReads } from "../core/telemetry.ts"; |
| 65 | 65 | import { noteRead, setTelemetryGrant, telemetryReader } from "../actions/telemetry.ts"; |
| 66 | 66 | import { queuesFor, systemFor } from "../system/telemetry.ts"; |
| @@ -284,7 +284,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 284 | 284 | id: "system", |
| 285 | 285 | title: "System", |
| 286 | 286 | hint: "the machine now: CPU, memory, disks, processes", |
| 287 | run: () => ctx.push(systemScreen(ctx, systemLines(liveMachine().read()))), | |
| 287 | run: () => ctx.push(systemScreen(ctx, liveMachine().read())), | |
| 288 | 288 | }); |
| 289 | 289 | commands.push({ |
| 290 | 290 | id: "telemetry", |
src/tui/screens/system.ts +27 −8
| @@ -12,7 +12,8 @@ | ||
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | 14 | import type { Ctx, Screen } from "../app/app.ts"; |
| 15 | import type { SystemView } from "../../system/view.ts"; | |
| 15 | import { sortGroups, type Sort, type SystemView } from "../../system/view.ts"; | |
| 16 | import { watchSystem } from "../../system/stream.ts"; | |
| 16 | 17 | import { canSeeMemory, memoryHours } from "../../boards/memory.ts"; |
| 17 | 18 | import { binding } from "../app/keys.ts"; |
| 18 | 19 | import type { Session } from "../session.ts"; |
| @@ -44,27 +45,42 @@ export function duplicateLines(dups: SystemView["duplicates"], inner: number): s | ||
| 44 | 45 | const capOf = (g: SystemView["groups"][number]): string => |
| 45 | 46 | g.capBytes === null ? "" : `${bytes(g.rssBytes)} of ${bytes(g.capBytes)} ${g.capBy === "kernel" ? "kernel" : "watched"}`; |
| 46 | 47 | |
| 47 | export function systemLines(v: SystemView): string[] { | |
| 48 | export function systemLines(v: SystemView, by: Sort = "cpu"): string[] { | |
| 48 | 49 | const inner = WIDTH - 6; |
| 49 | 50 | return [ |
| 50 | 51 | `CPU ${pct(v.cpu.busyPct)} over ${v.cpu.cores.length} cores · load ${v.load ? v.load.map((l) => l.toFixed(2)).join(" ") : "—"}`, |
| 51 | 52 | `hottest ${v.hottestC === null ? "—" : `${v.hottestC.toFixed(0)}°C`} · memory ${v.memory ? `${bytes(v.memory.usedBytes)} of ${bytes(v.memory.totalBytes)}` : "—"} · ${v.processes} processes`, |
| 52 | 53 | ...v.disks.map((d) => `${pad(d.mount, 20)} ${Math.round((d.usedBytes / Math.max(1, d.totalBytes)) * 100)}% of ${bytes(d.totalBytes)}`), |
| 53 | 54 | "", |
| 54 | ...v.groups.slice(0, GROUPS).map((g) => `${pad(g.label, 24)} ${pad(String(g.procs), 4, "right")} procs ${capOf(g)}`.trimEnd()), | |
| 55 | ...sortGroups(v.groups, by).slice(0, GROUPS).map((g) => `${pad(g.label, 24)} ${pad(String(g.procs), 4, "right")} procs ${capOf(g)}`.trimEnd()), | |
| 55 | 56 | "", |
| 56 | 57 | ...duplicateLines(v.duplicates, inner), |
| 57 | 58 | ]; |
| 58 | 59 | } |
| 59 | 60 | |
| 60 | export function systemScreen(ctx: Ctx, lines: readonly string[]): Screen { | |
| 61 | /** | |
| 62 | * The System dialog, live: while it is open it watches the machine like a | |
| 63 | * tab on /system does (`system/stream.ts`) and redraws on every tick; `c` / `m` | |
| 64 | * sort the groups by CPU or memory. Closing it ends the watch. | |
| 65 | */ | |
| 66 | export function systemScreen(ctx: Ctx, first: SystemView, watch: typeof watchSystem = watchSystem): Screen { | |
| 67 | let view = first; | |
| 68 | let by: Sort = "cpu"; | |
| 61 | 69 | return { |
| 62 | 70 | title: "System", |
| 63 | keys: [binding(["enter", "esc", "q"], "close")], | |
| 71 | keys: [binding(["c"], "sort by cpu"), binding(["m"], "sort by memory"), binding(["enter", "esc", "q"], "close")], | |
| 72 | load(signal) { | |
| 73 | const stop = watch((v) => { | |
| 74 | view = v; | |
| 75 | ctx.invalidate(); | |
| 76 | }); | |
| 77 | signal.addEventListener("abort", stop); | |
| 78 | return Promise.resolve(); | |
| 79 | }, | |
| 64 | 80 | render(area, s) { |
| 65 | 81 | const buttons = dialog(s, area, ctx.theme.c, { |
| 66 | title: "System", | |
| 67 | body: lines, | |
| 82 | title: `System · by ${by === "mem" ? "memory" : "cpu"}`, | |
| 83 | body: systemLines(view, by), | |
| 68 | 84 | actions: [{ label: "Close" }], |
| 69 | 85 | selected: 0, |
| 70 | 86 | width: WIDTH, |
| @@ -72,7 +88,10 @@ export function systemScreen(ctx: Ctx, lines: readonly string[]): Screen { | ||
| 72 | 88 | buttons.forEach((rect) => ctx.hit(rect, () => ctx.pop())); |
| 73 | 89 | }, |
| 74 | 90 | key(e) { |
| 75 | if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop(); | |
| 91 | if (e.key === "c" || e.key === "m") { | |
| 92 | by = e.key === "m" ? "mem" : "cpu"; | |
| 93 | ctx.invalidate(); | |
| 94 | } else if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop(); | |
| 76 | 95 | return true; |
| 77 | 96 | }, |
| 78 | 97 | }; |
src/web/pages/system.ts +38 −82
| @@ -2,9 +2,10 @@ | ||
| 2 | 2 | * /system, for the owner: the machine as it is now — cores, temperatures, |
| 3 | 3 | * load, memory, disks, network — and every process grouped by what the |
| 4 | 4 | * forge launched it for, each with CPU, memory and age. The same test file |
| 5 | * in more than one check at once is named at the top. It refreshes itself | |
| 6 | * every 2 s (a few lines of static script; `?pause` turns that off), so a | |
| 7 | * viewer *is* the sampler (`system/live.ts`). Numbers are `system/view.ts`'s. | |
| 5 | * in more than one check at once is named at the top. It is drawn the way | |
| 6 | * btop draws it (`system-board.ts`) and updated by one server-sent stream | |
| 7 | * per tab (`GET /system/stream`, `system/stream.ts`) — no reload, no timer | |
| 8 | * poll. Numbers are `system/view.ts`'s. | |
| 8 | 9 | * Below it, for a forge admin who is a person, the forge's resident memory |
| 9 | 10 | * (RSS) beside its JS heap, hourly for 24 h (#2151): RSS climbing while the |
| 10 | 11 | * heap stays flat is native memory growth. Drawn on the server as SVG. |
| @@ -14,21 +15,16 @@ import { canSeeMemory, memoryHours } from "../../boards/memory.ts"; | ||
| 14 | 15 | import { telemetryReader } from "../../actions/telemetry.ts"; |
| 15 | 16 | import type { Ctx } from "../../http/context.ts"; |
| 16 | 17 | import { memoryCapHolder } from "../../apps/contain.ts"; |
| 17 | import { bytes, span } from "../../system/format.ts"; | |
| 18 | import { bytes } from "../../system/format.ts"; | |
| 18 | 19 | import { live } from "../../system/live.ts"; |
| 20 | import { watchSystem } from "../../system/stream.ts"; | |
| 21 | import { eventStream } from "../../http/sse.ts"; | |
| 22 | import { parseSort, systemBoard } from "../system-board.ts"; | |
| 23 | import { SYSTEM_CLIENT } from "../system-client.ts"; | |
| 19 | 24 | import { notFoundPage, signInFirst } from "../chrome.ts"; |
| 20 | 25 | import { html, raw, type Html } from "../html.ts"; |
| 21 | 26 | import { page } from "../layout.ts"; |
| 22 | import { card, empty, listCard, pill, row } from "../ui.ts"; | |
| 23 | ||
| 24 | /** A group's memory, and a cell's beside its cap and who holds the cap. */ | |
| 25 | const memoryOf = (g: { rssBytes: number; capBytes: number | null; capBy: "kernel" | "watch" | null }): Html => | |
| 26 | g.capBytes === null | |
| 27 | ? html`${bytes(g.rssBytes)}` | |
| 28 | : html`${bytes(g.rssBytes)} <span class="muted small" data-cap="${String(g.capBytes)}" data-cap-by="${g.capBy ?? ""}">of ${bytes(g.capBytes)} (${g.capBy === "kernel" ? "kernel cap" : "watched"})</span>`; | |
| 29 | ||
| 30 | const pct = (n: number | null): string => (n === null ? "—" : `${n.toFixed(1)}%`); | |
| 31 | const coresOf = (n: number | null): string => (n === null ? "—" : n.toFixed(2)); | |
| 27 | import { card, empty } from "../ui.ts"; | |
| 32 | 28 | |
| 33 | 29 | const mib = (n: number) => `${(n / 1_048_576).toFixed(1)} MiB`; |
| 34 | 30 | const hhmm = (at: number) => new Date(at).toISOString().slice(0, 16).replace("T", " "); |
| @@ -51,84 +47,44 @@ function memorySection(ctx: Ctx): Html { | ||
| 51 | 47 | </table>`; |
| 52 | 48 | } |
| 53 | 49 | |
| 54 | const RELOAD = `if (!/[?&]pause\\b/.test(location.search)) setTimeout(function () { location.reload(); }, 2000);`; | |
| 50 | /** The cell-memory note: who holds the cap. */ | |
| 51 | const capsNote = (): Html => { | |
| 52 | const holder = memoryCapHolder(); | |
| 53 | return holder.by === "kernel" | |
| 54 | ? html`<p class="small" id="cell-caps" data-by="kernel">Each cell's memory is capped by the kernel (its own cgroup's <code>memory.max</code>): a cell over it is killed alone.</p>` | |
| 55 | : html`<p class="small" id="cell-caps" data-by="watch">Each cell's memory is watched once a second and the cell stopped over its cap; the kernel does not cap it (${holder.reason}).</p>`; | |
| 56 | }; | |
| 57 | ||
| 58 | /** Only the forge's owner reads the machine. */ | |
| 59 | const ownerOnly = (ctx: Ctx): boolean => telemetryReader(ctx.app, ctx.auth.user)?.kind === "owner"; | |
| 55 | 60 | |
| 56 | 61 | // GET /system |
| 57 | 62 | export function systemPage(ctx: Ctx): Response { |
| 58 | 63 | if (!ctx.auth.user) return signInFirst(ctx); |
| 59 | const reader = telemetryReader(ctx.app, ctx.auth.user); | |
| 60 | if (reader?.kind !== "owner") return notFoundPage(ctx); | |
| 64 | if (!ownerOnly(ctx)) return notFoundPage(ctx); | |
| 65 | const sort = parseSort(new URL(ctx.request.url).searchParams.get("sort")); | |
| 61 | 66 | const v = live().read(); |
| 62 | const dup: Html = | |
| 63 | v.duplicates.length === 0 | |
| 64 | ? html`<p id="duplicates" data-count="0" class="muted">No test file is running in more than one check.</p>` | |
| 65 | : html`<p id="duplicates" data-count="${String(v.duplicates.length)}"> | |
| 66 | <strong>${String(v.duplicates.length)} test file${v.duplicates.length === 1 ? " is" : "s are"} | |
| 67 | running in more than one check at once:</strong> | |
| 68 | </p> | |
| 69 | <ul class="list small mono"> | |
| 70 | ${v.duplicates.map((d) => html`<li>${d.file} · ${String(d.checks.length)} checks: ${d.checks.join(", ")}</li>`)} | |
| 71 | </ul>`; | |
| 72 | const holder = memoryCapHolder(); | |
| 73 | const caps: Html = | |
| 74 | holder.by === "kernel" | |
| 75 | ? html`<p class="small" id="cell-caps" data-by="kernel">Each cell's memory is capped by the kernel (its own cgroup's <code>memory.max</code>): a cell over it is killed alone.</p>` | |
| 76 | : html`<p class="small" id="cell-caps" data-by="watch">Each cell's memory is watched once a second and the cell stopped over its cap; the kernel does not cap it (${holder.reason}).</p>`; | |
| 77 | const cores = v.cpu.cores.map( | |
| 78 | (c, i) => html`<span class="mono small" title="cpu${String(i)}">${c === null ? "—" : String(Math.round(c))}</span> `, | |
| 79 | ); | |
| 80 | 67 | const body = html`<div class="page-head"> |
| 81 | <h1>System</h1> | |
| 68 | <h1>System <span id="sys-state" class="pill" data-tone="accent" role="status">live</span></h1> | |
| 82 | 69 | <p class="muted"> |
| 83 | The machine now, sampled each time this page refreshes (every 2 s); | |
| 84 | <a href="/system?pause">pause</a>. Its history is on | |
| 70 | The machine as it happens, pushed to this tab. Its history is on | |
| 85 | 71 | <a href="/boards">Boards</a> (the machine source); the pipeline is on |
| 86 | 72 | <a href="/flow">Flow</a>. |
| 87 | 73 | </p> |
| 88 | 74 | </div> |
| 89 | ${dup} | |
| 90 | ${card( | |
| 91 | html`<div id="summary" class="row-meta"> | |
| 92 | ${pill(`CPU ${pct(v.cpu.busyPct)}`, v.cpu.busyPct !== null && v.cpu.busyPct >= 90 ? "danger" : undefined)} | |
| 93 | ${pill(`${String(v.cpu.cores.length)} cores`)} | |
| 94 | ${pill(`load ${v.load ? v.load.map((l) => l.toFixed(2)).join(" ") : "—"}`)} | |
| 95 | ${pill(`hottest ${v.hottestC === null ? "—" : `${v.hottestC.toFixed(0)}°C`}`)} | |
| 96 | ${pill(`memory ${v.memory ? `${bytes(v.memory.usedBytes)} of ${bytes(v.memory.totalBytes)}` : "—"}`)} | |
| 97 | ${pill(`${String(v.processes)} processes`)} | |
| 98 | </div> | |
| 99 | <p class="small" id="cores" aria-label="Per-core CPU, percent">${cores}</p> | |
| 100 | ${caps} | |
| 101 | <p class="small mono" id="temps">${v.temps.map((t) => `${t.chip} ${t.label} ${t.celsius.toFixed(0)}°C`).join(" · ")}</p>`, | |
| 102 | { head: html`<h2>Machine</h2>` }, | |
| 103 | )} | |
| 104 | ${listCard( | |
| 105 | [ | |
| 106 | ...v.disks.map((d) => | |
| 107 | row({ | |
| 108 | title: html`<span class="mono">${d.mount}</span>`, | |
| 109 | meta: html`${d.fs}`, | |
| 110 | trail: html`${pill(`${String(Math.round((d.usedBytes / d.totalBytes) * 100))}%`)} ${bytes(d.totalBytes)}`, | |
| 111 | }), | |
| 112 | ), | |
| 113 | ...v.net.map((n) => | |
| 114 | row({ | |
| 115 | title: html`<span class="mono">${n.name}</span>`, | |
| 116 | trail: html`↓ ${n.rxBytesPerSecond === null ? "—" : `${bytes(n.rxBytesPerSecond)}/s`} ↑ ${n.txBytesPerSecond === null ? "—" : `${bytes(n.txBytesPerSecond)}/s`}`, | |
| 117 | }), | |
| 118 | ), | |
| 119 | ], | |
| 120 | { head: html`<h2>Disks and network</h2>` }, | |
| 121 | )} | |
| 122 | ${listCard( | |
| 123 | v.groups.map( | |
| 124 | (g) => html`<li data-kind="${g.kind}"><div class="row"> | |
| 125 | <span class="row-main"><span class="row-title mono">${g.label}</span> | |
| 126 | <span class="row-meta">${String(g.procs)} processes · oldest ${span(g.oldestSeconds)}${g.top.length ? html` · ${g.top.slice(0, 3).map((p) => `${p.comm} ${coresOf(p.cpuCores)}`).join(" · ")}` : null}</span></span> | |
| 127 | <span class="row-trail">${pill(`${coresOf(g.cpuCores)} cores`)} ${memoryOf(g)}</span> | |
| 128 | </div></li>`, | |
| 129 | ), | |
| 130 | { head: html`<h2>Processes</h2>` }, | |
| 131 | )} | |
| 75 | <div id="sys-board" class="sysboard" data-sort="${sort}" aria-live="off">${systemBoard(v, [], sort, capsNote())}</div> | |
| 132 | 76 | ${memorySection(ctx)}`; |
| 133 | return page({ ctx, title: "System", body, wide: true, scriptJs: RELOAD }); | |
| 77 | return page({ ctx, title: "System", body, wide: true, scriptJs: SYSTEM_CLIENT }); | |
| 78 | } | |
| 79 | ||
| 80 | // GET /system/stream — one board frame at connect, then one a second. | |
| 81 | export function systemStream(ctx: Ctx): Response { | |
| 82 | if (!ctx.auth.user || !ownerOnly(ctx)) return new Response("not found", { status: 404 }); | |
| 83 | const sort = parseSort(new URL(ctx.request.url).searchParams.get("sort")); | |
| 84 | let n = 0; | |
| 85 | return eventStream(ctx.request, (emit) => | |
| 86 | watchSystem((v, history) => { | |
| 87 | emit("board", { at: v.at, html: String(systemBoard(v, history, sort, capsNote())) }, String(++n)); | |
| 88 | }), | |
| 89 | ); | |
| 134 | 90 | } |
src/web/style/content.ts +19
| @@ -406,6 +406,25 @@ a.origin-chip:hover { border-color: var(--border-strong); color: var(--fg); } | ||
| 406 | 406 | .bform .qf > span { font-size: 12.5px; font-weight: 600; color: var(--fg); } |
| 407 | 407 | .bform .btn { flex: none; } |
| 408 | 408 | .boards-result .table { margin-top: 12px; } |
| 409 | .sysboard { font-family: var(--mono); font-size: 12.5px; } | |
| 410 | .sb-summary { margin: 0 0 8px; } | |
| 411 | .sb-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 340px), 1fr)); gap: 12px; margin-bottom: 12px; } | |
| 412 | .sb-box { border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); padding: 8px 10px; min-width: 0; margin-bottom: 12px; } | |
| 413 | .sb-grid .sb-box { margin-bottom: 0; } | |
| 414 | .sb-box h2 { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--accent); margin: 6px 0 4px; } | |
| 415 | .sb-box h2:first-child { margin-top: 0; } | |
| 416 | .sb-row { display: flex; gap: 8px; align-items: baseline; white-space: pre; overflow: hidden; line-height: 1.5; } | |
| 417 | .sb-k { color: var(--muted-fg); min-width: 4.5ch; } | |
| 418 | .sb-mount { max-width: 12ch; overflow: hidden; text-overflow: ellipsis; } | |
| 419 | .sb-v { min-width: 4ch; text-align: right; } | |
| 420 | .bar { letter-spacing: 0; } | |
| 421 | .bar i { font-style: normal; color: var(--faint); } | |
| 422 | .bar[data-lvl="lo"] { color: var(--success); } | |
| 423 | .bar[data-lvl="mid"] { color: var(--attn); } | |
| 424 | .bar[data-lvl="hi"] { color: var(--danger); } | |
| 425 | .spark { color: var(--accent); } | |
| 426 | .sb-proc { color: var(--muted-fg); } | |
| 427 | @media (max-width: 480px) { .sysboard { font-size: 11.5px; } .sb-row { gap: 5px; } .spark { display: none; } } | |
| 409 | 428 | .sys-pair { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px; margin-bottom: 16px; } |
| 410 | 429 | .sys-pair .chart-box { max-width: none; } |
| 411 | 430 | .bgrid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; } |
src/web/system-board.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 2 | * The /system board as one fragment, drawn the way btop draws it: text bars | |
| 3 | * and sparklines in monospace, a process table by what launched each | |
| 4 | * process. The first paint and every pushed frame are this function's | |
| 5 | * output, so what the stream patches in is what the server rendered. | |
| 6 | */ | |
| 7 | import { bytes, span } from "../system/format.ts"; | |
| 8 | import type { Sample } from "../system/stream.ts"; | |
| 9 | import { sortGroups, type Group, type Sort, type SystemView } from "../system/view.ts"; | |
| 10 | import { html, type Html } from "./html.ts"; | |
| 11 | import { pill } from "./ui.ts"; | |
| 12 | ||
| 13 | export const parseSort = (s: string | null): Sort => (s === "mem" ? "mem" : "cpu"); | |
| 14 | ||
| 15 | const BAR = 16; | |
| 16 | const SPARK = "▁▂▃▄▅▆▇█"; | |
| 17 | const level = (p: number): string => (p >= 85 ? "hi" : p >= 60 ? "mid" : "lo"); | |
| 18 | ||
| 19 | /** `████░░░░` for a percentage, with its level for colour. */ | |
| 20 | function bar(p: number | null, label: string): Html { | |
| 21 | if (p === null) return html`<span class="bar" aria-label="${label}: unknown">${"·".repeat(BAR)}</span>`; | |
| 22 | const c = Math.max(0, Math.min(100, p)); | |
| 23 | const n = Math.round((c / 100) * BAR); | |
| 24 | return html`<span class="bar" data-lvl="${level(c)}" role="img" aria-label="${label} ${c.toFixed(0)}%">${"█".repeat(n)}<i>${"░".repeat(BAR - n)}</i></span>`; | |
| 25 | } | |
| 26 | ||
| 27 | /** The last `width` values as a sparkline, scaled to `max`. */ | |
| 28 | function spark(values: readonly (number | null)[], max: number, width: number): string { | |
| 29 | const tail = values.slice(-width); | |
| 30 | const cells = tail.map((v) => | |
| 31 | v === null || max <= 0 ? " " : SPARK[Math.min(SPARK.length - 1, Math.floor((Math.max(0, v) / max) * SPARK.length))]!, | |
| 32 | ); | |
| 33 | return " ".repeat(width - cells.length) + cells.join(""); | |
| 34 | } | |
| 35 | ||
| 36 | const pct = (n: number | null): string => (n === null ? " —" : `${n.toFixed(0)}%`.padStart(4)); | |
| 37 | const cores = (n: number | null): string => (n === null ? "—" : n.toFixed(2)); | |
| 38 | const rate = (n: number | null): string => (n === null ? "—" : `${bytes(n)}/s`); | |
| 39 | ||
| 40 | const memoryOf = (g: Group): Html => | |
| 41 | g.capBytes === null | |
| 42 | ? html`${bytes(g.rssBytes)}` | |
| 43 | : html`${bytes(g.rssBytes)} <span class="muted" data-cap="${String(g.capBytes)}" data-cap-by="${g.capBy ?? ""}">of ${bytes(g.capBytes)} (${g.capBy === "kernel" ? "kernel cap" : "watched"})</span>`; | |
| 44 | ||
| 45 | export function systemBoard(v: SystemView, history: readonly Sample[], by: Sort, caps: Html): Html { | |
outdated
Grouping comes from |
||
| 46 | const coreRows = v.cpu.cores.map( | |
| 47 | (c, i) => html`<div class="sb-row"><span class="sb-k">cpu${String(i)}</span>${bar(c, `cpu${String(i)}`)}<span class="sb-v">${pct(c)}</span><span class="spark" aria-hidden="true">${spark(history.map((h) => h.cores[i] ?? null), 100, 20)}</span></div>`, | |
| 48 | ); | |
| 49 | const m = v.memory; | |
| 50 | const memPct = m ? (m.usedBytes / m.totalBytes) * 100 : null; | |
| 51 | const swapPct = m && m.swapTotalBytes > 0 ? (m.swapUsedBytes / m.swapTotalBytes) * 100 : null; | |
| 52 | const netMax = Math.max(1, ...history.flatMap((h) => [h.rx ?? 0, h.tx ?? 0])); | |
| 53 | const dup: Html = | |
| 54 | v.duplicates.length === 0 | |
| 55 | ? html`<p id="duplicates" data-count="0" class="muted">No test file is running in more than one check.</p>` | |
| 56 | : html`<p id="duplicates" data-count="${String(v.duplicates.length)}"><strong>${String(v.duplicates.length)} test file${v.duplicates.length === 1 ? " is" : "s are"} running in more than one check at once:</strong></p> | |
| 57 | <ul class="list small mono">${v.duplicates.map((d) => html`<li>${d.file} · ${String(d.checks.length)} checks: ${d.checks.join(", ")}</li>`)}</ul>`; | |
| 58 | const groups = sortGroups(v.groups, by).map( | |
| 59 | (g) => html`<li data-kind="${g.kind}"><div class="row"> | |
| 60 | <span class="row-main"><span class="row-title mono">${g.label}</span> | |
| 61 | <span class="row-meta">${String(g.procs)} processes · oldest ${span(g.oldestSeconds)}</span> | |
| 62 | ${g.top.map((p) => html`<span class="row-meta sb-proc mono">└ ${p.comm} ${String(p.pid)} · ${cores(p.cpuCores)} cores · ${bytes(p.rssBytes)} · ${span(p.ageSeconds)}</span>`)}</span> | |
| 63 | <span class="row-trail">${pill(`${cores(g.cpuCores)} cores`)} ${memoryOf(g)}</span> | |
| 64 | </div></li>`, | |
| 65 | ); | |
| 66 | return html`<div id="summary" class="row-meta sb-summary"> | |
| 67 | ${pill(`CPU ${v.cpu.busyPct === null ? "—" : `${v.cpu.busyPct.toFixed(1)}%`}`, v.cpu.busyPct !== null && v.cpu.busyPct >= 90 ? "danger" : undefined)} | |
| 68 | ${pill(`${String(v.cpu.cores.length)} cores`)} | |
| 69 | ${pill(`load ${v.load ? v.load.map((l) => l.toFixed(2)).join(" ") : "—"}`)} | |
| 70 | ${pill(`hottest ${v.hottestC === null ? "—" : `${v.hottestC.toFixed(0)}°C`}`)} | |
| 71 | ${pill(`memory ${m ? `${bytes(m.usedBytes)} of ${bytes(m.totalBytes)}` : "—"}`)} | |
| 72 | ${pill(`${String(v.processes)} processes`)} | |
| 73 | </div> | |
| 74 | ${dup} | |
| 75 | <div class="sb-grid"> | |
| 76 | <section class="sb-box" aria-label="CPU"><h2>cpu</h2> | |
| 77 | <div class="sb-row"><span class="sb-k">all </span>${bar(v.cpu.busyPct, "cpu")}<span class="sb-v">${pct(v.cpu.busyPct)}</span><span class="spark" aria-hidden="true">${spark(history.map((h) => h.cpu), 100, 20)}</span></div> | |
| 78 | <div id="cores" aria-label="Per-core CPU, percent">${coreRows}</div> | |
| 79 | <div class="sb-row muted"><span class="sb-k">load</span>${v.load ? v.load.map((l) => l.toFixed(2)).join(" ") : "—"}</div> | |
| 80 | <div id="temps" class="sb-row mono muted">${v.temps.length === 0 ? "no temperature sensors" : v.temps.map((t) => `${t.chip} ${t.label} ${t.celsius.toFixed(0)}°C`).join(" · ")}</div> | |
| 81 | </section> | |
| 82 | <section class="sb-box" aria-label="Memory, disks, network"><h2>mem</h2> | |
| 83 | <div class="sb-row"><span class="sb-k">mem </span>${bar(memPct, "memory")}<span class="sb-v">${pct(memPct)}</span><span class="spark" aria-hidden="true">${spark(history.map((h) => h.mem), 100, 20)}</span></div> | |
| 84 | <div class="sb-row"><span class="sb-k">swap</span>${bar(swapPct, "swap")}<span class="sb-v">${pct(swapPct)}</span><span class="muted">${m ? bytes(m.swapUsedBytes) : ""}</span></div> | |
| 85 | <h2>disks</h2> | |
| 86 | ${v.disks.map((d) => { const p = d.totalBytes > 0 ? (d.usedBytes / d.totalBytes) * 100 : null; return html`<div class="sb-row"><span class="sb-k sb-mount">${d.mount}</span>${bar(p, d.mount)}<span class="sb-v">${pct(p)}</span><span class="muted">${bytes(d.totalBytes)}</span></div>`; })} | |
| 87 | <h2>net</h2> | |
| 88 | ${v.net.map((n) => html`<div class="sb-row"><span class="sb-k sb-mount">${n.name}</span><span class="mono">↓ ${rate(n.rxBytesPerSecond)} ↑ ${rate(n.txBytesPerSecond)}</span></div>`)} | |
| 89 | <div class="sb-row"><span class="sb-k">↓</span><span class="spark" aria-hidden="true">${spark(history.map((h) => h.rx), netMax, 30)}</span></div> | |
| 90 | <div class="sb-row"><span class="sb-k">↑</span><span class="spark" aria-hidden="true">${spark(history.map((h) => h.tx), netMax, 30)}</span></div> | |
| 91 | </section> | |
| 92 | </div> | |
| 93 | ${caps} | |
| 94 | <section class="sb-box" aria-label="Processes by what launched them"><h2>proc <span class="muted">sorted by ${by === "mem" ? "memory" : "cpu"} — <kbd>c</kbd> cpu <kbd>m</kbd> memory <kbd>p</kbd> pause</span></h2> | |
| 95 | <ul class="list">${groups}</ul> | |
| 96 | </section>`; | |
| 97 | } |
src/web/system-client.ts added +35
| @@ -0,0 +1,35 @@ | ||
| 1 | /** | |
| 2 | * The /system page's script: one EventSource for the tab, each frame the | |
| 3 | * server-rendered board swapped in place. `c` / `m` sort the process table | |
| 4 | * (the stream is reopened with the sort), `p` pauses and resumes. The | |
| 5 | * browser reconnects a dropped stream by itself, and the server's first frame | |
| 6 | * on every connection is the whole board, so a roll loses nothing. | |
| 7 | */ | |
| 8 | export const SYSTEM_CLIENT = `(function () { | |
| 9 | var box = document.getElementById('sys-board'); | |
| 10 | var state = document.getElementById('sys-state'); | |
| 11 | if (!box || typeof EventSource === 'undefined') return; | |
| 12 | var sort = box.getAttribute('data-sort') === 'mem' ? 'mem' : 'cpu'; | |
| 13 | var es = null; | |
| 14 | function say(t) { if (state) state.textContent = t; } | |
| 15 | function stop() { if (es) { es.close(); es = null; } } | |
| 16 | function start() { | |
| 17 | stop(); | |
| 18 | es = new EventSource('/system/stream?sort=' + sort); | |
| 19 | es.addEventListener('board', function (e) { | |
| 20 | try { box.innerHTML = JSON.parse(e.data).html; box.setAttribute('data-sort', sort); say('live'); } catch (x) {} | |
| 21 | }); | |
| 22 | es.onerror = function () { say('reconnecting'); }; | |
| 23 | } | |
| 24 | function pick(s) { sort = s; history.replaceState(null, '', '?sort=' + s); start(); } | |
| 25 | document.addEventListener('keydown', function (e) { | |
| 26 | if (e.ctrlKey || e.metaKey || e.altKey) return; | |
| 27 | var t = e.target && e.target.tagName; | |
| 28 | if (t === 'INPUT' || t === 'TEXTAREA' || t === 'SELECT') return; | |
| 29 | if (e.key === 'c') pick('cpu'); | |
| 30 | else if (e.key === 'm') pick('mem'); | |
| 31 | else if (e.key === 'p') { if (es) { stop(); say('paused'); } else start(); } | |
| 32 | }); | |
| 33 | window.addEventListener('pagehide', stop); | |
| 34 | start(); | |
| 35 | })();`; |
test/design-audit.test.ts +1 −1
| @@ -11,7 +11,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8"); | ||
| 11 | 11 | |
| 12 | 12 | /** Routes that answer a file, a fragment, a redirect hop or a callback. */ |
| 13 | 13 | const NOT_PAGES = |
| 14 | /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|events$|sw\.js$|robots\.txt$|sitemap\.xml$|manifest\.webmanifest$|llms\.txt$|releases\.json$|audit\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/)/; | |
| 14 | /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|events$|sw\.js$|robots\.txt$|sitemap\.xml$|manifest\.webmanifest$|llms\.txt$|releases\.json$|audit\.csv$|fleet\/graph\/live$|system\/stream$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/)/; | |
| 15 | 15 | |
| 16 | 16 | const getRoutes = [ |
| 17 | 17 | ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g), |
test/system-stream.test.ts added +147
| @@ -0,0 +1,147 @@ | ||
| 1 | /** | |
| 2 | * /system streams (#2676): no meta refresh and no timer reload on the page; | |
| 3 | * a sample recorded shows up in the stream within 2 s; one timer serves every | |
| 4 | * tab and stops with the last; only the owner opens it. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp } from "../src/app.ts"; | |
| 11 | import { createToken } from "../src/core/tokens.ts"; | |
| 12 | import { createUser } from "../src/core/users.ts"; | |
| 13 | import { serve } from "../src/http/server.ts"; | |
| 14 | import { live, useLive, type Live } from "../src/system/live.ts"; | |
| 15 | import { setTickMs, watching, watchSystem } from "../src/system/stream.ts"; | |
| 16 | import type { SystemView } from "../src/system/view.ts"; | |
| 17 | ||
| 18 | let dir: string; | |
| 19 | let app: ReturnType<typeof createApp>; | |
| 20 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 21 | const tok: Record<string, string> = {}; | |
| 22 | const real = live(); | |
| 23 | let procs = 100; | |
| 24 | ||
| 25 | const view = (): SystemView => ({ | |
| 26 | at: new Date().toISOString(), | |
| 27 | seconds: 1, | |
| 28 | cpu: { busyPct: 42, cores: [10, 90] }, | |
| 29 | temps: [], | |
| 30 | hottestC: null, | |
| 31 | load: [0.1, 0.2, 0.3], | |
| 32 | memory: { totalBytes: 1e9, usedBytes: 5e8, swapUsedBytes: 0, swapTotalBytes: 0 }, | |
| 33 | disks: [], | |
| 34 | net: [{ name: "eth0", rxBytesPerSecond: 10, txBytesPerSecond: 20 }], | |
| 35 | processes: procs, | |
| 36 | groups: [], | |
| 37 | duplicates: [], | |
| 38 | }); | |
| 39 | const fake: Live = { read: () => view() }; | |
| 40 | ||
| 41 | const auth = (who: string) => ({ authorization: `Bearer ${tok[who]}` }); | |
| 42 | ||
| 43 | /** Read frames until one holds `needle`, or give up after `ms`. */ | |
| 44 | async function frameWith(path: string, needle: string, ms: number, who = "alice"): Promise<string | undefined> { | |
| 45 | // Aborting the request is what a tab closing does. | |
| 46 | const stop = new AbortController(); | |
| 47 | const res = await fetch(servers.url + path, { headers: auth(who), signal: stop.signal }); | |
| 48 | const reader = res.body!.getReader(); | |
| 49 | const dec = new TextDecoder(); | |
| 50 | let buf = ""; | |
| 51 | const end = Date.now() + ms; | |
| 52 | while (Date.now() < end) { | |
| 53 | const got = await Promise.race([reader.read(), Bun.sleep(end - Date.now()).then(() => undefined)]); | |
| 54 | if (!got || got.done) break; | |
| 55 | buf += dec.decode(got.value); | |
| 56 | if (buf.includes(needle)) { | |
| 57 | stop.abort(); | |
| 58 | return buf; | |
| 59 | } | |
| 60 | } | |
| 61 | stop.abort(); | |
| 62 | return undefined; | |
| 63 | } | |
| 64 | ||
| 65 | beforeAll(async () => { | |
| 66 | dir = await mkdtemp(join(tmpdir(), "forge-sysstream-")); | |
| 67 | app = createApp({ dataDir: dir, port: 0 }); | |
| 68 | servers = await serve(app); | |
| 69 | for (const [username, first] of [["alice", true], ["bob", false]] as const) { | |
| 70 | const r = await createUser(app.db, { | |
| 71 | origin: "seed", trusted: true, username, email: `${username}@forge.local`, | |
| 72 | password: "a-good-passphrase", ...(first ? { adminIfFirst: true } : {}), | |
| 73 | }); | |
| 74 | if (!r.ok) throw new Error(r.error); | |
| 75 | tok[username] = createToken(app.db, r.value.id, "t", "admin").token; | |
| 76 | } | |
| 77 | useLive(fake); | |
| 78 | setTickMs(200); | |
| 79 | }); | |
| 80 | afterAll(async () => { | |
| 81 | useLive(real); | |
| 82 | setTickMs(1000); | |
| 83 | await servers.stop(); | |
| 84 | await rm(dir, { recursive: true, force: true }); | |
| 85 | }); | |
| 86 | ||
| 87 | describe("/system page", () => { | |
| 88 | test("does not refresh or poll itself, and opens one stream", async () => { | |
| 89 | const html = await (await fetch(servers.url + "/system", { headers: auth("alice") })).text(); | |
| 90 | expect(html).not.toContain('http-equiv="refresh"'); | |
| 91 | expect(html).not.toContain("location.reload"); | |
| 92 | expect(html).not.toContain("setInterval"); | |
| 93 | expect(html).not.toMatch(/setTimeout\([^)]*reload/); | |
| 94 | expect(html).toContain("new EventSource('/system/stream?sort="); | |
| 95 | expect(html).toContain('id="sys-board"'); | |
| 96 | expect(html).toContain("100 processes"); | |
| 97 | }); | |
| 98 | }); | |
| 99 | ||
| 100 | describe("GET /system/stream", () => { | |
| 101 | test("a sample appears within 2 s of being recorded", async () => { | |
| 102 | procs = 4242; | |
| 103 | const got = await frameWith("/system/stream", "4242 processes", 2000); | |
| 104 | expect(got).toBeDefined(); | |
| 105 | expect(got).toContain("event: board"); | |
| 106 | }); | |
| 107 | ||
| 108 | test("the sort is honoured and an unknown one falls back to cpu", async () => { | |
| 109 | const mem = await frameWith("/system/stream?sort=mem", "sorted by", 2000); | |
| 110 | expect(mem).toContain("sorted by memory"); | |
| 111 | const odd = await frameWith("/system/stream?sort=%3Cx%3E", "sorted by", 2000); | |
| 112 | expect(odd).toContain("sorted by cpu"); | |
| 113 | }); | |
| 114 | ||
| 115 | test("only the owner opens it", async () => { | |
| 116 | expect((await fetch(servers.url + "/system/stream", { headers: auth("bob") })).status).toBe(404); | |
| 117 | expect((await fetch(servers.url + "/system/stream")).status).toBe(404); | |
| 118 | }); | |
| 119 | }); | |
| 120 | ||
| 121 | describe("the sampler", () => { | |
| 122 | test("one timer serves every watcher and stops with the last", async () => { | |
| 123 | const end = Date.now() + 2000; | |
| 124 | while (watching() > 0 && Date.now() < end) await Bun.sleep(50); | |
| 125 | let a = 0; | |
| 126 | let b = 0; | |
| 127 | const stopA = watchSystem(() => a++); | |
| 128 | const stopB = watchSystem(() => b++); | |
| 129 | expect(watching()).toBe(2); | |
| 130 | await Bun.sleep(500); | |
| 131 | expect(a).toBeGreaterThanOrEqual(2); | |
| 132 | expect(b).toBeGreaterThanOrEqual(2); | |
| 133 | stopA(); | |
| 134 | stopB(); | |
| 135 | expect(watching()).toBe(0); | |
| 136 | const seen = a; | |
| 137 | await Bun.sleep(400); | |
| 138 | expect(a).toBe(seen); | |
| 139 | }); | |
| 140 | ||
| 141 | test("a closed stream leaves no watcher behind", async () => { | |
| 142 | await frameWith("/system/stream", "event: board", 2000); | |
| 143 | const end = Date.now() + 2000; | |
| 144 | while (watching() > 0 && Date.now() < end) await Bun.sleep(50); | |
| 145 | expect(watching()).toBe(0); | |
| 146 | }); | |
| 147 | }); |
test/system-telemetry.test.ts +1 −1
| @@ -100,7 +100,7 @@ describe("the machine, read from /proc and /sys", () => { | ||
| 100 | 100 | expect(v.cpu.cores.length).toBe(2); |
| 101 | 101 | expect(v.hottestC).toBe(76); |
| 102 | 102 | expect(v.load?.[0]).toBe(64); |
| 103 | expect(v.memory).toEqual({ totalBytes: 1024_000, usedBytes: 614_400, swapUsedBytes: 0 }); | |
| 103 | expect(v.memory).toEqual({ totalBytes: 1024_000, usedBytes: 614_400, swapUsedBytes: 0, swapTotalBytes: 0 }); | |
| 104 | 104 | expect(JSON.stringify(v)).not.toContain("hunter2"); |
| 105 | 105 | // A later reading gives rates over the two latest. |
| 106 | 106 | fakeHost(root, 300); |
test/tui-system.test.ts +40
| @@ -99,3 +99,43 @@ describe("tui system memory", () => { | ||
| 99 | 99 | } |
| 100 | 100 | }); |
| 101 | 101 | }); |
| 102 | ||
| 103 | describe("the terminal's System dialog is live", () => { | |
| 104 | const group = (label: string, cpuCores: number, rssBytes: number) => ({ | |
| 105 | label, kind: "check" as const, procs: 1, cpuCores, rssBytes, capBytes: null, capBy: null, | |
| 106 | oldestSeconds: 1, top: [], tests: [], | |
| 107 | }); | |
| 108 | const viewOf = (processes: number): import("../src/system/view.ts").SystemView => ({ | |
| 109 | at: "", seconds: 1, cpu: { busyPct: 1, cores: [1] }, temps: [], hottestC: null, load: null, memory: null, | |
| 110 | disks: [], net: [], processes, duplicates: [], | |
| 111 | groups: [group("check:thin", 3, 1_000), group("check:fat", 0.1, 9_000_000)], | |
| 112 | }); | |
| 113 | ||
| 114 | test("a tick redraws, m reorders the groups, closing stops the watch", async () => { | |
| 115 | const { systemScreen } = await import("../src/tui/screens/system.ts"); | |
| 116 | const terminal = headlessTerminal(120, 30); | |
| 117 | const { app: tui } = createForgeApp(app, identity(), { terminal, exitHooks: false }); | |
| 118 | tui.start(); | |
| 119 | let tick: ((v: ReturnType<typeof viewOf>) => void) | undefined; | |
| 120 | let stopped = false; | |
| 121 | const watch = ((w: typeof tick) => { | |
| 122 | tick = w; | |
| 123 | return () => { stopped = true; }; | |
| 124 | }) as never; | |
| 125 | tui.ctx.push(systemScreen(tui.ctx, viewOf(11), watch)); | |
| 126 | await settleApp(tui); | |
| 127 | expect(tui.screen.toText()).toContain("11 processes"); | |
| 128 | tick!(viewOf(77)); | |
| 129 | await settleApp(tui); | |
| 130 | expect(tui.screen.toText()).toContain("77 processes"); | |
| 131 | const order = () => { const t = tui.screen.toText(); return t.indexOf("check:thin") - t.indexOf("check:fat"); }; | |
| 132 | expect(order()).toBeLessThan(0); | |
| 133 | terminal.feed("m"); | |
| 134 | await settleApp(tui); | |
| 135 | expect(order()).toBeGreaterThan(0); | |
| 136 | terminal.feed("q"); | |
| 137 | await settleApp(tui); | |
| 138 | expect(stopped).toBe(true); | |
| 139 | tui.stop?.(); | |
| 140 | }); | |
| 141 | }); |
new above
offline
This is the right primitive. Use it from
src/tui/screens/system.tstoo, so the terminal's System view updates live like the tab does. Today it is a one-shotlive().read().