Public: anyone can read this; the crew can change it.

Observability 3: boards are live by streaming per-panel points, never by re-fetching HTML #16653

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/3692-observability-3-boards-are-live-by-strea → main 0 commits fork 6 threads · 6 unresolved

  • Merged. scout/3692-observability-3-boards-are-live-by-strea was merged into main as 8d526ef.

Review

Sign in to review this change.
18 files changed +619 −53
docs/STATUS.md +2 −2
@@ -78,8 +78,8 @@ cannot confirm. A package registry is not shipped yet.
7878 - `GET /api/v1/boards/pins` (the list, in order) and `POST /api/v1/boards/pins` with `{"op":"pin|unpin|move","slug":"…","title":"…","by":-1|1}` (`by` for move only);
7979 - the `board_pins` MCP tool (no `op` lists; `op` pin, unpin or move changes). `pins` is therefore not a board slug.
8080 The first boot also writes the starting boards, **Usage**, **Serving**, **Crew**, **Releases**, **Apps**, **Security**, **Throughput**, **Reach** and **Forges**; Serving is the forge's event-loop lag p99 beside the checks and crew runs running, so checks' concurrency is raised on numbers. Apps' per-app panels show repo ids until a source exposes a safe name; Security (sign-ins, failed sign-ins, tokens by scope, admin actions, from the admin-only `signins`, `tokens` and `adminActions` sources and `usage`) shows no token text, hash, payload or IP; Throughput is items entering each stage from issue to live, per hour, from the `stages` source. Each is written once: `.offered` in that repo records them, so an edit stays and a deletion sticks.
81 A live board (any `refresh` but `off`; the form offers off or on, and `10s` and `1m` are still accepted and mean the same) redraws its grid when a run, pull, check, issue or usage event arrives, through the live-region swap
82 (`/boards/:slug/live`, etag'd, one fetch per burst). The same doors are in the API: `GET /api/v1/boards`, `GET|PUT|DELETE /api/v1/boards/:slug`, and each panel's data as JSON or CSV at `GET /api/v1/boards/:slug/panels/:id?from=&to=&step=5m&format=csv`, bucketed in SQL to the step and never cut short (`docs/APPS.md`); each panel's card links `json` and `csv` (a plain download link) beside `explore`
81 A live board (any `refresh` but `off`; the form offers off or on, and `10s` and `1m` are still accepted and mean the same) draws the points that moved in its line, bar and number charts when a run, pull, check, issue or usage event arrives, over one stream per tab
82 (`/boards/:slug/stream`; one read per board is shared by every tab; `docs/features/boards-live.md`). The same doors are in the API: `GET /api/v1/boards`, `GET|PUT|DELETE /api/v1/boards/:slug`, and each panel's data as JSON or CSV at `GET /api/v1/boards/:slug/panels/:id?from=&to=&step=5m&format=csv`, bucketed in SQL to the step and never cut short (`docs/APPS.md`); each panel's card links `json` and `csv` (a plain download link) beside `explore`
8383 (an agent or anyone but an admin is 403; a panel whose query cannot run is refused with 422). The same four doors are MCP tools (`boards`, `board_write`, `board_delete`; `boards` with a `slug` reads one, and with a `panel` too that panel's data, with the same `from`, `to` and `step`) and, for the same person, a **Boards** screen in the terminal that lists boards and shows a board's panels as text, each with what its data holds now (a time panel's last bucket and step, another's row count). No dependency was added.
8484 - **Parked work**: the terminal's Flow dialog says how many issues the crew parked (an open issue whose newest comment is the crew's `Parked by the crew` note) in the last 24 h and 7 d, and names the newest three; the MCP `flow` tool returns the same as `parked`. The flow panel on `/boards` draws two lines under its numbers, each left out at 0: `N idle pulls` (open crew pulls whose head has not moved for 72 h; the oldest three linked, `and K more` after) and `N parked today, M this week` (linking the newest parked issue). The Flow dialog lists them too (`idle: N`, a row each, `+K more`). `/boards` is the owner's; the MCP `flow` tool, as an agent, reads public repositories only (sealed issues left out). `and K more` opens `/boards?idle=all`, a list of every idle pull. See `docs/TOUR.md`.
8585 - **Issues**: labels, threaded comments, close/reopen, markdown.
docs/features/boards-live.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Tell the crew
3 row: A live board moves its charts as events arrive
4 ---
5 # A live board moves its charts as events arrive (#3692)
6
7 A board whose **Live** setting is on (`refresh` anything but `off`) opens one event stream, `GET /boards/<slug>/stream`, and never fetches its page again. Open `/boards/<slug>` as an admin: under the title it reads `live · updated Ns ago`, and when a run, pull, check, issue or usage event arrives the charts that moved are drawn again. Without JavaScript it reads "Moves as events arrive." and the page stays as it was served.
8
9 - **What goes down**: only the points that are new or moved, a few hundred bytes a frame, at most every 750 ms and never while nothing moved. A burst of more than 24 points in one panel says "reload to redraw" instead.
10 - **What is drawn**: line, bar and number charts of one series are drawn again from the points (the same scale, path and bars as the page). Area, heat, table and split charts keep what was served, and the header says "some charts changed a lot; reload to redraw" when one of them moved.
11 - **Many tabs, one read**: every tab on a board shares one read of its panels (`src/boards/live_hub.ts`); ten tabs cost the queries of one.
12 - **Who**: a person who is an admin. An agent or anyone else gets the not-found page, as for the board.
13 - **In the terminal**: open the board from the Boards screen (`src/tui/screens/boards.ts`). While it is open, a panel that moved says `live HH:MM:SSZ: N points moved · latest X` under its data line, fed by the same frames (`deltaOf` in `src/boards/delta.ts`).
14
15 The stream is `src/web/pages/boards-stream.ts`, which sends the frames and carries the client that draws them.
scripts/unused-exports-allow.json +1
@@ -13,6 +13,7 @@
1313 "src/billing/orders.ts bySession",
1414 "src/billing/orders.ts recentOrders",
1515 "src/billing/sync.ts setStripeFetch",
16 "src/boards/live_hub.ts hubsOpen",
1617 "src/boards/model_fill.ts useModel",
1718 "src/checks/deepsec_plan.ts sweepArgvs",
1819 "src/checks/doctor.ts isDoctorHold",
src/boards/delta.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * What changed in a board since the last look, as points: one panel's rows
3 * against the rows last sent, giving only the points that are new or moved.
4 * Plain data in, plain data out; the stream (`web/pages/boards-stream.ts`)
5 * sends these instead of the page.
6 */
7 import { formatValue } from "./chart.ts";
8 import { latestOf } from "./panel_data.ts";
9 import type { Row } from "./query.ts";
10 import type { Panel } from "./store.ts";
11
12 /** A point: its group, its value, and its series when the panel is split. */
13 export type DeltaPoint = [group: string, value: number] | [group: string, value: number, series: string];
14 /**
15 * A panel's change: its place on the board, the points that are new or moved, and its latest value
16 * as words.
17 */
18 export type PanelDelta = { i: number; points: DeltaPoint[]; now?: string };
19 /** What was last sent for one panel: value by point key. */
20 export type Seen = Map<string, number>;
21
22 /**
23 * Most points one frame carries for one panel: a burst past it is not a delta, and the page is told
24 * to reload.
25 */
26 export const MAX_POINTS = 24;
27
28 const keyOf = (r: Row): string => `${String(r.group ?? "all")}\u0000${r.series === undefined ? "" : String(r.series ?? "none")}`;
29
30 /** The rows as what a later `deltaOf` compares against. */
31 export function seenOf(rows: readonly Row[]): Seen {
32 return new Map(rows.map((r) => [keyOf(r), r.value ?? 0]));
33 }
34
35 /**
36 * `rows` against `seen`: the new or moved points, or null when nothing changed. `next` is what to
37 * remember.
38 */
39 export function deltaOf(i: number, panel: Panel, rows: readonly Row[], seen: Seen): { delta: PanelDelta | null; next: Seen; tooMany: boolean } {
40 const points: DeltaPoint[] = [];
41 for (const r of rows) {
42 const v = r.value ?? 0;
43 if (seen.get(keyOf(r)) === v) continue;
44 const g = String(r.group ?? "all");
45 points.push(r.series === undefined ? [g, v] : [g, v, String(r.series ?? "none")]);
46 }
47 const next = seenOf(rows);
48 if (points.length === 0) return { delta: null, next, tooMany: false };
49 const latest = latestOf(panel, rows);
50 return {
51 delta: { i, points: points.slice(-MAX_POINTS), ...(latest === null ? {} : { now: formatValue(latest) }) },
52 next,
53 tooMany: points.length > MAX_POINTS,
54 };
55 }
src/boards/live_hub.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * One live read per open board, however many people watch it. The first watcher of a board starts
3 * a hub: it listens to the bus once, and when a run, pull, check, issue or usage event arrives it
4 * reads the panels' rows once (at most every `MIN_GAP_MS`), takes `deltaOf` against what it last
5 * sent and hands the same frame to every watcher. The last one to leave stops it. The stream
6 * (`web/pages/boards-stream.ts`) and the terminal board (`tui/screens/boards.ts`) both watch
7 * through here, so ten tabs cost one set of queries per event.
8 */
9 import type { App } from "../app.ts";
10 import { during } from "../perf/jobs.ts";
11 import { deltaOf, seenOf, type PanelDelta, type Seen } from "./delta.ts";
12 import { panelData } from "./panel_data.ts";
13 import type { Board } from "./store.ts";
14
15 /** The events a board's queries read: any of them may move a chart. */
16 export const STREAM_READS = ["run.", "pull.", "check.", "issue.", "usage."] as const;
17 /** Rows are read at most this often, however many events arrive. */
18 export const MIN_GAP_MS = 750;
19
20 /** What a watcher is told: the moved points, and whether a burst is too big to apply. */
21 export type Frame = { at: number; panels: PanelDelta[]; reload?: true };
22 /** A panel's points as the hub last read them, for a chart a page can redraw itself. */
23 export type Base = { i: number; points: [group: string, value: number][] };
24
25 const DRAWN = new Set(["line", "bar", "number"]);
26
27 class Hub {
28 private seen: Seen[];
29 private readonly watchers = new Set<(f: Frame) => void>();
30 private timer: ReturnType<typeof setTimeout> | undefined;
31 private last = 0;
32 private off: () => void;
33
34 constructor(private readonly app: App, private readonly board: Board, private readonly drop: () => void) {
35 this.seen = board.panels.map((p) => this.rowsOf(p));
36 this.off = app.bus.subscribe((event) => {
37 if (this.timer !== undefined || !STREAM_READS.some((k) => event.kind.startsWith(k))) return;
38 this.timer = setTimeout(() => during("boards-stream", () => this.send(), undefined, app), Math.max(0, MIN_GAP_MS - (Date.now() - this.last)));
39 }, "ordered");
40 }
41
42 private rowsOf(p: Board["panels"][number]): Seen {
43 const d = panelData(this.app.db, this.board, p);
44 return d.ok ? seenOf(d.rows) : new Map();
45 }
46
47 /** The points of every panel a page redraws itself, as last read. */
48 base(): Base[] {
49 const out: Base[] = [];
50 this.board.panels.forEach((p, i) => {
51 const keys = [...(this.seen[i] ?? new Map<string, number>())];
52 if (!DRAWN.has(p.chart) || keys.some(([k]) => !k.endsWith("\u0000"))) return;
53 out.push({ i, points: keys.map(([k, v]) => [k.slice(0, -1), v]) });
54 });
55 return out;
56 }
57
58 private send(): void {
59 this.timer = undefined;
60 this.last = Date.now();
61 const panels: PanelDelta[] = [];
62 let reload = false;
63 this.board.panels.forEach((p, i) => {
64 const d = panelData(this.app.db, this.board, p);
65 if (!d.ok) return;
66 const r = deltaOf(i, p, d.rows, this.seen[i] ?? new Map());
67 this.seen[i] = r.next;
68 if (r.delta) panels.push(r.delta);
69 reload ||= r.tooMany;
70 });
71 if (panels.length === 0) return;
72 const frame: Frame = { at: this.last, panels, ...(reload ? { reload: true as const } : {}) };
73 for (const w of this.watchers) w(frame);
74 }
75
76 join(onFrame: (f: Frame) => void): () => void {
77 this.watchers.add(onFrame);
78 return () => {
79 this.watchers.delete(onFrame);
80 if (this.watchers.size > 0) return;
81 this.off();
82 if (this.timer !== undefined) clearTimeout(this.timer);
83 this.drop();
84 };
85 }
86 }
87
88 const hubs = new WeakMap<object, Map<string, Hub>>();
89
90 /**
91 * Watch a board: `onFrame` hears each frame of moved points; `base` is where the points stand now;
92 * `stop` leaves (the last one out stops the hub). A board edited meanwhile is another hub: the key
93 * holds the board itself.
94 */
95 export function watchBoard(app: App, slug: string, board: Board, onFrame: (f: Frame) => void): { base: Base[]; stop: () => void } {
96 let of = hubs.get(app.db);
97 if (of === undefined) hubs.set(app.db, (of = new Map()));
98 const key = `${slug}\u0000${JSON.stringify(board)}`;
99 let hub = of.get(key);
100 if (hub === undefined) {
101 const made = new Hub(app, board, () => of.delete(key));
102 hub = made;
103 of.set(key, made);
104 }
105 return { base: hub.base(), stop: hub.join(onFrame) };
106 }
107
108 /** How many boards are being read live: for the test that watchers share one. */
109 export const hubsOpen = (app: App): number => hubs.get(app.db)?.size ?? 0;
src/boards/panel_data.ts +10 −3
@@ -136,12 +136,19 @@ export const cellsOf = (rows: readonly Row[], hrefs: readonly (string | null)[]
136136 /** A panel as it is drawn: its chart's markup and, for one series over time, its latest value; or why it could not be read. */
137137 export type PanelDrawn = { ok: true; chart: string; latest: number | null } | { ok: false; error: string };
138138
139 /**
140 * One series drawn over time says its latest value beside its name; a split, a table or groups of
141 * anything else have no one latest.
142 */
143 export function latestOf(panel: Panel, rows: readonly Row[]): number | null {
144 const newest = panel.chart === "line" || panel.chart === "bar" ? rows[rows.length - 1] : undefined;
145 return newest !== undefined && newest.series === undefined && /^\d{4}-\d{2}-\d{2}/.test(String(newest.group)) ? (newest.value ?? 0) : null;
146 }
147
139148 /** Draw `panel` from its rows: the chart is markup from here on, so whoever reads the rows off the serving thread draws them there too. */
140149 export function drawnPanel(panel: Panel, answer: PanelData): PanelDrawn {
141150 if (!answer.ok) return answer;
142 const newest = panel.chart === "line" || panel.chart === "bar" ? answer.rows[answer.rows.length - 1] : undefined;
143 // One series drawn over time says its latest value beside its name; a split, a table or groups of anything else have no one latest.
144 const latest = newest !== undefined && newest.series === undefined && /^\d{4}-\d{2}-\d{2}/.test(String(newest.group)) ? (newest.value ?? 0) : null;
151 const latest = latestOf(panel, answer.rows);
145152 return { ok: true, chart: drawChart(panel.chart, cellsOf(answer.rows), panel.title, typeof panel.query.source === "string" ? panel.query.source : undefined), latest };
146153 }
147154
src/http/marks/boards.json +1 −1
@@ -11,7 +11,7 @@
1111 "/boards/unpin-panel": "open",
1212 "/boards/move-pin": "open",
1313 "/boards/:slug": "open",
14 "/boards/:slug/live": "open",
14 "/boards/:slug/stream": "open",
1515 "/boards/:slug/:op": "open"
1616 }
1717 }
src/http/server.ts +3 −2
@@ -72,7 +72,8 @@ import { nowPage } from "../web/pages/now.ts";
7272 import { myReposPage } from "../web/pages/my-repos.ts";
7373 import { displayChoose, displayPage } from "../web/pages/display.ts";
7474 import { displaysPage } from "../web/pages/displays.ts";
75 import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts";
75 import { boardStream } from "../web/pages/boards-stream.ts";
76 import { boardShow, boardsList } from "../web/pages/boards-view.ts";
7677 import { actingVia } from "../core/acting_via.ts";
7778 import {
7879 closeStreamsOf,
@@ -1309,7 +1310,7 @@ export function buildRouter(): Router<Handler> {
13091310 router.add("POST", "/boards/pin", boardPin);
13101311 for (const op of ["pin-panel", "unpin-panel", "move-pin"]) router.add("POST", `/boards/${op}`, pinPost);
13111312 router.add("GET", "/boards/:slug", boardShow);
1312 router.add("GET", "/boards/:slug/live", boardLive);
1313 router.add("GET", "/boards/:slug/stream", boardStream);
13131314 router.add("POST", "/boards/:slug/:op", boardPost);
13141315 router.add("GET", "/admin/data", adminDataPage);
13151316 router.add("GET", "/admin/limits", limitsPage);
src/tui/screens/boards.ts +30 −5
@@ -9,10 +9,13 @@
99 * panel is said as its title, chart, size and the query that feeds it, then what `panelData` reads
1010 * for it (the page's and the API's door): a time panel's last bucket and its step, else its row
1111 * count. `[`/`]` mark a panel, `p` pins or unpins it to home and `<`/`>` move a pinned one
12 * (`actions/board-pins.ts`).
12 * (`actions/board-pins.ts`). A board that is live (`refresh` not `off`) keeps itself current while
13 * its screen is open: it watches through the same hub as the page's stream (`boards/live_hub.ts`),
14 * so a panel that moved says how many points and its latest value (`liveWords`).
1315 */
1416
1517 import { formatValue } from "../../boards/chart.ts";
18 import { watchBoard, type Frame } from "../../boards/live_hub.ts";
1619 import { panelData, type PanelData } from "../../boards/panel_data.ts";
1720 import { RANGES, type Board } from "../../boards/store.ts";
1821 import { listPinned, movePinned, pinPanel, unpinPanel } from "../../actions/board-pins.ts";
@@ -76,7 +79,7 @@ export function dataLine(d: PanelData): string {
7679 * A board, panel by panel, as lines of text; the panel at `at` is marked, a
7780 * pinned one says so, and each panel with its `data` read says what it holds.
7881 */
79 export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = []): string[] {
82 export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = [], moved: ReadonlyMap<number, string> = new Map()): string[] {
8083 const lines = [
8184 plain(board.title),
8285 `range ${board.range} · refresh ${board.refresh} · ${plural(board.panels.length, "panel")}`,
@@ -88,10 +91,20 @@ export function boardLines(board: Board, at = -1, pinned: readonly string[] = []
8891 lines.push("", `${i === at ? "▸ " : ""}${plain(p.title)}${pinned.includes(p.title) ? " [pinned to home]" : ""}`, ` ${p.chart} · ${p.w}×${p.h}`, ` ${query === "" ? "no query" : query}`);
8992 const d = data[i];
9093 if (d !== undefined) lines.push(` ${dataLine(d)}`);
94 const m = moved.get(i);
95 if (m !== undefined) lines.push(` ${m}`);
9196 }
9297 return lines;
9398 }
9499
100 /** What a live frame says of one panel: the points that moved and its latest value. */
101 export function liveWords(frame: Frame, i: number): string | undefined {
102 const p = frame.panels.find((x) => x.i === i);
103 if (p === undefined) return undefined;
104 const clock = new Date(frame.at).toISOString().slice(11, 19);
105 return `live ${clock}Z: ${plural(p.points.length, "point")} moved${p.now === undefined ? "" : ` · latest ${plain(p.now)}`}`;
106 }
107
95108 export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): Screen {
96109 let board = first;
97110 const scroll = new Scroll();
@@ -103,12 +116,13 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
103116 // The gate is `changeBoard`'s, read once as the list's is.
104117 const mayEdit = f.user?.isAdmin === true && f.user.kind !== "agent";
105118 let lines = boardLines(board, at, pinned);
119 const moved = new Map<number, string>();
106120 const read = async (): Promise<void> => {
107121 const listed = await listPinned(f.app, f.user);
108122 pinned = listed.ok ? listed.value.filter((p) => p.slug === slug).map((p) => p.title) : [];
109123 // Only an admin person reaches this screen (`showBoard` let them in), as `panelData` asks.
110124 data = board.panels.map((p) => panelData(f.app.db, board, p));
111 lines = boardLines(board, at, pinned, data);
125 lines = boardLines(board, at, pinned, data, moved);
112126 ctx.invalidate();
113127 };
114128 /** Pin the marked panel, or unpin it when it is; `by` moves a pinned one in the home order. */
@@ -161,7 +175,18 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
161175 binding(["esc", "q"], "back"),
162176 ];
163177 },
164 load: read,
178 async load(signal) {
179 await read();
180 if (board.refresh === "off" || !mayEdit || signal.aborted) return;
181 const watch = watchBoard(f.app, slug, board, (frame) => {
182 board.panels.forEach((_, i) => {
183 const words = liveWords(frame, i);
184 if (words !== undefined) moved.set(i, words);
185 });
186 runAsync(ctx, read);
187 });
188 signal.addEventListener("abort", watch.stop, { once: true });
189 },
165190 render(area, s) {
166191 const c = ctx.theme.c;
167192 if (asking !== undefined) {
@@ -191,7 +216,7 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
191216 }
192217 if (e.key === "[" || e.key === "]") {
193218 if (board.panels.length > 0) at = (at + (e.key === "]" ? 1 : board.panels.length - 1)) % board.panels.length;
194 lines = boardLines(board, at, pinned, data);
219 lines = boardLines(board, at, pinned, data, moved);
195220 return true;
196221 }
197222 if (e.key === "p") return act(), true;
src/web/pages/boards-stream.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * GET /boards/:slug/stream: a board kept live by points, not by pages. One SSE per open tab; the
3 * panels are read once per board for every tab (`boards/live_hub.ts`), and only the points that are
4 * new or moved go down, as `panels` frames of a few hundred bytes. Nothing is sent when nothing
5 * moved. The `hello` frame carries the points of the charts the page redraws itself (line, bar,
6 * number, one series). The client is `boardStreamJs`, which draws them.
7 */
8 import { boardPicture, isFailed } from "../../flow/pages.ts";
9 import { watchBoard } from "../../boards/live_hub.ts";
10 import { isSlug } from "../../boards/store.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { eventStream } from "../../http/sse.ts";
13 import { notFoundPage } from "../chrome.ts";
14
15 export async function boardStream(ctx: Ctx): Promise<Response> {
16 const u = ctx.auth.user;
17 const slug = ctx.params.slug ?? "";
18 if (u?.isAdmin !== true || u.kind === "agent" || !isSlug(slug)) return notFoundPage(ctx);
19 const picture = await boardPicture(ctx.app, slug);
20 if (picture === undefined || isFailed(picture) || picture.board === null) return notFoundPage(ctx);
21 const board = picture.board;
22
23 return eventStream(ctx.app, ctx.request, (emit, _close, ready) => {
24 const watch = watchBoard(ctx.app, slug, board, (frame) => {
25 if (ready()) emit("panels", frame);
26 });
27 emit("hello", { at: Date.now(), base: watch.base });
28 return watch.stop;
29 });
30 }
31
32 /**
outdated

Every stream runs every panel query on the serving thread, at open and on each send. N open tabs = N identical reads per event. Share one read per board (keyed by slug) or move it off the serving thread.

33 * The page's end of the stream. The header says "live · updated Ns ago" or "paused"; the latest
34 * number moves in place; and a line, bar or number chart is drawn again from its points, with the
35 * same scale, path and bars as `boards/chart.ts`. Area, heat, table and split charts are not drawn
36 * here: a frame that moves one says so, and the page keeps what it was served. Every word set on
37 * the page is set as text.
38 */
39 export const boardStreamJs = /* js */ `
40 (function () {
41 var grid = document.getElementById('board-grid');
42 var say = document.getElementById('board-live');
43 var src = grid && grid.getAttribute('data-stream');
44 if (!src || !say || typeof EventSource === 'undefined') return;
45 var NS = 'http://www.w3.org/2000/svg';
46 var at = Date.now(), live = false, pts = {}, stale = false;
47 var es = new EventSource(src);
48 function group(n, d) {
49 var s = Math.pow(10, d), r = Math.round(Math.abs(n) * s) / s, p = String(r).split('.');
50 var w = p[0].length > 3 && p[0].indexOf('e') < 0 ? p[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',') : p[0];
51 return (n < 0 && r !== 0 ? '-' : '') + w + (p[1] === undefined ? '' : '.' + p[1]);
52 }
53 function fmt(v) {
54 var a = Math.abs(v);
55 if (a >= 1e9) return group(v / 1e9, a >= 1e10 ? 1 : 2) + 'G';
56 if (a >= 1e6) return group(v / 1e6, a >= 1e7 ? 1 : 2) + 'M';
57 if (a >= 1e4) return group(v / 1e3, a >= 1e5 ? 0 : 1) + 'k';
58 return group(v, a >= 100 ? 0 : a >= 10 ? 1 : 2);
59 }
60 function r2(n) { return String(Math.round(n * 100) / 100); }
61 var STEPS = [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10];
62 function nice(v) {
63 if (!(v > 0)) return 1;
64 var p = Math.pow(10, Math.floor(Math.log(v) / Math.LN10));
65 for (var i = 0; i < STEPS.length; i++) if (STEPS[i] * p >= v * 0.999999) return STEPS[i] * p;
66 return 10 * p;
67 }
68 function scale(lo, hi) {
69 var top = hi > 0 ? nice(hi) : 0, bottom = lo < 0 ? -nice(-lo) : 0, span = top - bottom || 1;
70 return { top: bottom + span, bottom: bottom, y: function (v) { return 100 - ((v - bottom) / span) * 100; } };
71 }
72 function line(vals, y) {
73 var n = vals.length;
74 if (n === 1) return 'M40 ' + r2(y(vals[0])) + ' L60 ' + r2(y(vals[0]));
75 return vals.map(function (v, i) { return (i ? 'L' : 'M') + r2(n < 2 ? 50 : i * 100 / (n - 1)) + ' ' + r2(y(v)); }).join(' ');
76 }
77 function el(tag, attrs, title) {
78 var e = document.createElementNS(NS, tag);
79 for (var k in attrs) e.setAttribute(k, attrs[k]);
80 if (title) { var t = document.createElementNS(NS, 'title'); t.textContent = title; e.appendChild(t); }
81 return e;
82 }
83 function clear(plot, sel) {
84 plot.querySelectorAll(sel).forEach(function (n) { var a = n.parentNode; if (a && a.nodeName === 'a') a.remove(); else n.remove(); });
85 }
86 function words(card, list) {
87 var vals = list.map(function (p) { return p[1]; });
88 var box = card.querySelector('.chart'), sr = card.querySelector('.chart .sr-only');
89 if (sr && box) sr.textContent = (box.getAttribute('aria-label') || '') + ': ' + list.length + ' points; lowest ' + fmt(Math.min.apply(null, vals)) + ', highest ' + fmt(Math.max.apply(null, vals)) + ', latest ' + fmt(vals[vals.length - 1]) + '.';
90 }
91 function draw(card, kind, list) {
92 var plot = card.querySelector('svg.chart-plot');
outdated

Principle 2 (the real product is the visual): the points arrive and only the number is updated; data-moved is read by nothing. Apply the points to the chart, otherwise the stream carries data the page throws away. Also dead attribute as it stands.

93 if (!plot || list.length === 0) return false;
94 var vals = list.map(function (p) { return p[1]; });
95 var lo = Math.min.apply(null, vals), hi = Math.max.apply(null, vals), n = list.length;
96 if (kind === 'number') {
97 var span = hi - lo || 1, d = line(vals, function (v) { return 92 - ((v - lo) / span) * 84; });
98 var sp = plot.querySelector('.spark'); if (!sp) return false;
99 sp.setAttribute('d', d);
100 var big = card.querySelector('.chart-big .big'); if (big) big.textContent = fmt(vals[n - 1]);
101 var note = card.querySelector('.chart-note'); if (note) note.textContent = list[n - 1][0] + ', the latest of ' + n;
102 words(card, list); return true;
103 }
104 var s = scale(lo, hi);
105 var ys = card.querySelectorAll('.chart-y span');
106 if (ys.length === 3) { ys[0].textContent = fmt(s.top); ys[1].textContent = fmt((s.top + s.bottom) / 2); ys[2].textContent = fmt(s.bottom); }
107 if (kind === 'bar') {
108 clear(plot, '.bar');
109 var slot = 100 / n;
110 list.forEach(function (p, i) {
111 var top = Math.min(s.y(p[1]), s.y(0)), h = Math.abs(s.y(p[1]) - s.y(0));
112 plot.appendChild(el('rect', { 'class': 'bar', x: r2(slot * i + slot * 0.15), y: r2(top), width: r2(slot * 0.7), height: r2(h) }, p[0] + ': ' + fmt(p[1])));
113 });
114 } else {
115 var d2 = line(vals, s.y), ln = plot.querySelector('.chart-line'), wash = plot.querySelector('.chart-wash');
116 if (!ln) return false;
117 ln.setAttribute('d', d2);
118 if (wash && n > 1) wash.setAttribute('d', d2 + ' L100 ' + r2(s.y(0)) + ' L0 ' + r2(s.y(0)) + ' Z');
119 clear(plot, '.chart-hit');
120 list.forEach(function (p, i) {
121 var l = i === 0 || n < 2 ? 0 : (i + i - 1) * 50 / (n - 1), rt = i === n - 1 ? 100 : (i + i + 1) * 50 / (n - 1);
122 plot.appendChild(el('rect', { 'class': 'chart-hit', x: r2(l), y: '0', width: r2(rt - l), height: '100' }, p[0] + ': ' + fmt(p[1])));
123 });
124 }
125 words(card, list); return true;
126 }
127 function paint() {
128 var s = Math.max(0, Math.round((Date.now() - at) / 1000));
129 say.textContent = stale ? 'live \\u00b7 some charts changed a lot; reload to redraw' : live ? 'live \\u00b7 updated ' + (s < 2 ? 'just now' : s + 's ago') : 'paused \\u00b7 reconnecting';
130 say.setAttribute('data-state', live ? 'live' : 'paused');
131 }
132 function parse(e) { try { return JSON.parse(e.data); } catch (_) { return null; } }
133 es.addEventListener('hello', function (e) {
134 var d = parse(e); live = true; at = Date.now();
135 if (d && d.base) d.base.forEach(function (b) { pts[b.i] = b.points; });
136 paint();
137 });
138 es.addEventListener('panels', function (e) {
139 var d = parse(e); if (!d) return;
140 at = Date.now(); live = true;
141 var cards = grid.querySelectorAll('.bp');
142 d.panels.forEach(function (p) {
143 var card = cards[p.i]; if (!card) return;
144 var n = card.querySelector('.bp-now .num');
145 if (n && p.now) n.textContent = p.now;
146 var list = pts[p.i], box = card.querySelector('.chart'), kind = box && box.getAttribute('data-chart');
147 if (!list || !kind) { stale = true; return; }
148 p.points.forEach(function (q) {
149 for (var i = 0; i < list.length; i++) if (list[i][0] === q[0]) { list[i][1] = q[1]; return; }
150 list.push([q[0], q[1]]);
151 });
152 if (!draw(card, kind, list)) stale = true;
153 });
154 if (d.reload) stale = true;
155 paint();
156 });
157 es.onerror = function () { live = false; paint(); };
158 setInterval(paint, 1000);
159 })();
160 `;
src/web/pages/boards-view.ts +8 −25
@@ -2,9 +2,8 @@
22 * Boards, drawn: `/boards` lists them and makes one, `/boards/:slug` is the
33 * grid with each panel's chart and, under it, the panels' management (edit,
44 * move, remove) and the board's own (rename, range, live, duplicate,
5 * delete). The grid is a live region with an address of its own
6 * (`/boards/:slug/live`): a board that is live is refetched, by the same
7 * swap the wall uses, when a run, pull, check, issue or usage event arrives.
5 * delete). A live board's grid names a stream (`/boards/:slug/stream`,
6 * `boards-stream.ts`) that carries new points; the page is never refetched.
87 * No client framework. Every form posts to `boards-edit.ts`. Anyone but a
98 * person who is an admin gets the not-found page.
109 */
@@ -15,9 +14,10 @@ import type { Ctx } from "../../http/context.ts";
1514 import { driftSection } from "./boards-drift.ts";
1615 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
1716 import { liveRegionsJs } from "../client.ts";
17 import { boardStreamJs } from "./boards-stream.ts";
1818 import { notFoundPage, signInFirst } from "../chrome.ts";
1919 import { html, when, type Html } from "../html.ts";
20 import { fragment, page } from "../layout.ts";
20 import { page } from "../layout.ts";
2121 import { btn, chartFrame, confirmAction, field, selectField } from "../ui.ts";
2222 import { emptyList } from "../empty_words.ts";
2323 import { fold, reading, readingFailed, readingJs } from "../figure.ts";
@@ -31,12 +31,6 @@ import { drawnPanel, panelData, runFor, type PanelDrawn } from "../../boards/pan
3131 import { readParams } from "../../boards/params.ts";
3232 import { paramsOf, queryFields } from "./boards.ts";
3333
34 /**
35 * The events the panels' queries read (runs, pulls, checks, issues, usage): any of them may change
36 * a chart.
37 */
38 const READS = "run.queued,run.started,run.finished,pull.*,check.*,issue.*,usage.*";
39
4034 const sizes = (max: number, word: string, now: number) =>
4135 [1, 2, 3].slice(0, max).map((n) => ({ value: String(n), label: `${String(n)} ${word}`, selected: n === now }));
4236
@@ -72,14 +66,14 @@ export function drawPanel(
7266 </div>`;
7367 }
7468
75 /** The grid alone: what the page shows and what the live address answers with. */
69 /** The grid: each panel as drawn, naming the stream when the board is live. */
7670 function grid(app: App, slug: string, board: Board, panels: readonly PanelDrawn[]): Html {
7771 return html`<section
7872 class="bgrid"
7973 id="board-grid"
8074 ${board.refresh === "off"
8175 ? null
82 : html`data-live="${READS}" data-live-src="/boards/${slug}/live"`}
76 : html`data-stream="/boards/${slug}/stream"`}
8377 >
8478 ${board.panels.length === 0
8579 ? html`<p class="muted bp-w3">This board has no panel yet. Add the first one under "Add a panel" below, or pin a chart from <a href="/boards/data">Explore the data</a>.</p>`
@@ -278,25 +272,14 @@ export async function boardShow(ctx: Ctx): Promise<Response> {
278272 wide: true,
279273 body: html`<div class="hf bd">
280274 <header class="hf-head">
281 <div class="hf-title"><h1>${board.title}</h1><p class="hf-live muted">${String(n)} ${n === 1 ? "chart" : "charts"} over ${RANGE_WORDS[board.range].toLowerCase()}${board.refresh === "off" ? "" : ", redrawn as things happen"}. Times are UTC.</p></div>
275 <div class="hf-title"><h1>${board.title}</h1><p class="hf-live muted">${String(n)} ${n === 1 ? "chart" : "charts"} over ${RANGE_WORDS[board.range].toLowerCase()}. Times are UTC. ${board.refresh === "off" ? null : html`<span id="board-live" class="num" role="status" data-state="idle">Moves as events arrive.</span>`}</p></div>
282276 <nav class="bd-nav" aria-label="Elsewhere">${btn("All boards", { href: "/boards", variant: "ghost" })}${btn("Explore the data", { href: "/boards/data", variant: "ghost" })}</nav>
outdated

Principle 1: 'redrawn as things happen' and the live status say the same thing twice, and the first is untrue (charts do not redraw). The no-JS state 'live · connecting' also claims live when nothing is. Keep one sentence.

283277 </header>
284278 ${panels}
285279 ${manage(slug, board, queryFields(readParams(ctx.url.searchParams)), listPins(ctx.app.db, ctx.auth.user?.id ?? ""))}
286280 </div>`,
287 scriptJs: liveRegionsJs,
281 scriptJs: boardStreamJs,
288282 });
outdated

liveRegionsJs is still shipped but this grid no longer carries data-live; it is dead script on this page, and /boards/:slug/live is now unused by it. Remove what the stream replaces.

289283 notePhase(ctx.request, "render", performance.now() - rendering);
290284 return response;
291285 }
292
293 // GET /boards/:slug/live
294 export async function boardLive(ctx: Ctx): Promise<Response> {
295 if (denied(ctx)) return fragment(html``, { status: 404 });
296 const slug = ctx.params.slug ?? "";
297 if (!isSlug(slug)) return fragment(html``, { status: 404 });
298 const picture = await boardPicture(ctx.app, slug);
299 if (picture === undefined || isFailed(picture)) return fragment(html``, { status: 503 });
300 if (picture.board === null) return fragment(html``, { status: 404 });
301 return fragment(grid(ctx.app, slug, picture.board, picture.panels), { request: ctx.request });
302 }
test/boards-doors.test.ts +1 −2
@@ -77,13 +77,12 @@ describe("/boards doors", () => {
7777 expect(page).toContain("<h1>Mine</h1>");
7878 expect(page).toContain("One");
7979 expect(await (await get("/boards", "alice")).text()).toContain("/boards/mine");
80 expect((await get("/boards/mine/live", "alice")).status).toBe(200);
8180 });
8281
8382 for (const who of [null, "bob"]) {
8483 const name = who ?? "a guest";
8584 test(`${name}: every board page is not found`, async () => {
86 for (const path of ["/boards", "/boards/mine", "/boards/mine/live"]) {
85 for (const path of ["/boards", "/boards/mine", "/boards/mine/stream"]) {
8786 const r = await get(path, who);
8887 // The list sends a guest to sign in first; it is never the list.
8988 if (who === null && path === "/boards") {
test/boards-store.test.ts +7 −11
@@ -191,18 +191,14 @@ describe("/boards", () => {
191191 const body = await (await asAdmin("/boards/fleet-health")).text();
192192 const grid = body.match(/<section[^>]*id="board-grid"[^>]*>/)?.[0] ?? "";
193193 expect(grid).not.toContain("data-live-every");
194 expect(grid).toMatch(/data-live="[^"]+"/);
195 expect(grid).toContain('data-live="run.queued,run.started,run.finished,pull.*,check.*,issue.*,usage.*"');
196 expect(body).toContain('data-live-src="/boards/fleet-health/live"');
194 expect(grid).not.toContain("data-live=");
195 expect(grid).toContain('data-stream="/boards/fleet-health/stream"');
197196 expect(body).toMatch(/<option\s+value="10s"\s+selected\s*>\s*on: redraw when events arrive\s*<\/option>/);
198197 expect(body).not.toContain(">1m</option>");
199 const live = await asAdmin("/boards/fleet-health/live");
200 expect(live.status).toBe(200);
201 const text = await live.text();
202 expect(text.startsWith("<section")).toBe(true);
203 expect(text.match(LINE)?.length).toBe(3);
204 const again = await asAdmin("/boards/fleet-health/live", { headers: { "if-none-match": live.headers.get("etag")! } });
205 expect(again.status).toBe(304);
198 expect(body).toContain('data-state="idle">Moves as events arrive.');
199 expect(body).not.toContain("connecting");
200 expect(body.match(LINE)?.length).toBe(3);
201 expect((await asAdmin("/boards/fleet-health/live")).status).toBe(405); // the HTML grid door is gone: the stream replaced it
206202 expect((await post("/boards/fleet-health/settings", { range: "weeks", refresh: "10s" })).headers.get("set-cookie")).toContain("danger");
207203 });
208204
@@ -268,7 +264,7 @@ describe("/boards", () => {
268264 });
269265
270266 test("a non-admin and a stranger get 404 on every board route", async () => {
271 for (const path of ["/boards", "/boards/fleet-health", "/boards/fleet-health/live"]) {
267 for (const path of ["/boards", "/boards/fleet-health", "/boards/fleet-health/stream"]) {
272268 expect((await fetch(servers.url + path, { headers: { authorization: `Bearer ${tok.bob}` } })).status).toBe(404);
273269 const stranger = await fetch(servers.url + path, { redirect: "manual" });
274270 // The list sends a stranger to sign in (#6733, so /flow is no dead end); a board itself stays a 404.
test/boards-stream.test.ts added +201
@@ -0,0 +1,201 @@
1 /**
2 * A board is live by points (#3692): a new data point reaches an open board
3 * within 2 s in under 2 KB, nothing is sent while idle, and the stream is an
4 * admin's. `deltaOf` is checked on its own.
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 { writeBoard } from "../src/actions/boards.ts";
11 import { createApp } from "../src/app.ts";
12 import { deltaOf, MAX_POINTS, seenOf } from "../src/boards/delta.ts";
13 import type { Board, Panel } from "../src/boards/store.ts";
14 import { createRun } from "../src/core/runs.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { serve } from "../src/http/server.ts";
18 import { hubsOpen, watchBoard, type Frame } from "../src/boards/live_hub.ts";
19 import { boardStreamJs } from "../src/web/pages/boards-stream.ts";
20
21 const panel: Panel = { title: "Runs", chart: "bar", query: { source: "runs", aggregate: "count", groupBy: "kind" }, w: 1, h: 1 };
22
23 describe("deltaOf", () => {
24 test("only new or moved points, and nothing when nothing moved", () => {
25 const rows = [{ group: "check", value: 2 }, { group: "deploy", value: 1 }];
26 const seen = seenOf(rows);
27 expect(deltaOf(0, panel, rows, seen).delta).toBeNull();
28 const r = deltaOf(0, panel, [{ group: "check", value: 3 }, { group: "deploy", value: 1 }, { group: "build", value: 1 }], seen);
29 expect(r.delta?.points).toEqual([["check", 3], ["build", 1]]);
30 });
31 test("a burst past the cap is cut and flagged", () => {
32 const rows = Array.from({ length: MAX_POINTS + 5 }, (_, i) => ({ group: `g${String(i)}`, value: 1 }));
33 const r = deltaOf(0, panel, rows, new Map());
34 expect(r.delta?.points.length).toBe(MAX_POINTS);
35 expect(r.tooMany).toBe(true);
36 });
37 });
38
39 describe("GET /boards/:slug/stream", () => {
40 let dir: string;
41 let app: ReturnType<typeof createApp>;
42 let servers: Awaited<ReturnType<typeof serve>>;
43 let admin = "";
44 let other = "";
45 beforeAll(async () => {
46 dir = await mkdtemp(join(tmpdir(), "forge-boards-stream-"));
47 app = createApp({ dataDir: dir, port: 0 });
48 servers = await serve(app);
49 const mk = async (username: string, adminIfFirst?: boolean) => {
50 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", ...(adminIfFirst ? { adminIfFirst } : {}) });
51 if (!r.ok) throw new Error(r.error);
52 return r.value;
53 };
54 const alice = await mk("alice", true);
55 const bob = await mk("bob");
56 admin = createToken(app.db, alice.id, "t", "admin").token;
57 other = createToken(app.db, bob.id, "t", "admin").token;
58 app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('r1', ?, 'app')", [alice.id]);
59 const w = await writeBoard(app, alice, "live", { title: "Live", range: "all", refresh: "10s", panels: [panel] });
60 if (!w.ok) throw new Error(JSON.stringify(w.error));
61 });
62 afterAll(async () => {
63 await servers.stop?.();
64 await rm(dir, { recursive: true, force: true });
65 });
66 const open = (who: string, slug = "live", signal?: AbortSignal) =>
67 fetch(`${servers.url}/boards/${slug}/stream`, { headers: { authorization: `Bearer ${who}` }, ...(signal ? { signal } : {}) });
68
69 test("not an admin's, or not a board: not found", async () => {
70 expect((await open(other)).status).toBe(404);
71 expect((await open(admin, "nope")).status).toBe(404);
72 });
73
74 test("a new point arrives within 2 s in under 2 KB, and an idle stream sends nothing", async () => {
75 const stop = new AbortController();
76 const res = await open(admin, "live", stop.signal);
77 expect(res.headers.get("content-type")).toContain("text/event-stream");
78 const reader = res.body!.getReader();
79 const dec = new TextDecoder();
80 let text = "";
81 let pending: ReturnType<typeof reader.read> | undefined;
82 const until = async (needle: string, ms: number) => {
83 const end = Date.now() + ms;
84 while (!text.includes(needle) && Date.now() < end) {
85 pending ??= reader.read();
86 const got = await Promise.race([pending, new Promise<null>((r) => setTimeout(() => r(null), Math.max(1, end - Date.now())))]);
87 if (got === null) continue;
88 pending = undefined;
89 if (got.done) break;
90 text += dec.decode(got.value);
91 }
92 return text.includes(needle);
93 };
94 expect(await until("event: hello", 2000)).toBe(true);
95 expect(text).toContain('"base":[{"i":0,"points":[');
96 // Idle: an event the board does not read moves nothing.
97 app.bus.append({ kind: "run.queued", repoId: "r1", payload: {} });
98 expect(await until("event: panels", 1200)).toBe(false);
99 const sent = text.length;
100 createRun(app.db, { repoId: "r1", kind: "check" });
101 app.bus.append({ kind: "run.queued", repoId: "r1", payload: {} });
102 const t0 = Date.now();
103 expect(await until("event: panels", 2000)).toBe(true);
104 expect(Date.now() - t0).toBeLessThan(2000);
105 const frame = text.slice(sent);
106 expect(new TextEncoder().encode(frame).length).toBeLessThan(2048);
107 expect(frame).toContain('"check"');
108 stop.abort();
109 });
110 });
111
112 describe("one read per board", () => {
113 test("every watcher of a board shares one hub, hears the same frame, and the last one out stops it", async () => {
114 const dir = await mkdtemp(join(tmpdir(), "forge-boards-hub-"));
115 const app = createApp({ dataDir: dir, port: 0 });
116 const board: Board = { title: "Hub", range: "all", refresh: "10s", panels: [panel] };
117 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
118 if (!made.ok) throw new Error(made.error);
119 app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('r1', ?, 'app')", [made.value.id]);
120 const a: Frame[] = [];
121 const b: Frame[] = [];
122 let heard!: () => void;
123 const both = new Promise<void>((r) => (heard = r));
124 const hear = (into: Frame[]) => (f: Frame) => {
125 into.push(f);
126 if (a.length > 0 && b.length > 0) heard();
127 };
128 const one = watchBoard(app, "hub", board, hear(a));
129 const two = watchBoard(app, "hub", board, hear(b));
130 expect(hubsOpen(app)).toBe(1);
131 createRun(app.db, { repoId: "r1", kind: "check" });
132 app.bus.append({ kind: "run.queued", repoId: "r1", payload: {} });
133 await both;
134 expect(a.length).toBe(1);
135 expect(b).toEqual(a);
136 one.stop();
137 expect(hubsOpen(app)).toBe(1);
138 two.stop();
139 expect(hubsOpen(app)).toBe(0);
140 await rm(dir, { recursive: true, force: true });
141 });
142 });
143
144 describe("the page's drawer", () => {
145 /** A page of one bar panel, as little of a DOM as the client script asks of one. */
146 function drawnPage() {
147 const mk = (cls = "") => {
148 const e: any = { kids: [] as any[], attrs: { class: cls } as Record<string, string>, text: "", parentNode: null };
149 e.setAttribute = (k: string, v: string) => (e.attrs[k] = v);
150 e.getAttribute = (k: string) => e.attrs[k] ?? null;
151 e.appendChild = (c: any) => (c.parentNode = e, e.kids.push(c), c);
152 e.remove = () => (e.parentNode.kids = e.parentNode.kids.filter((k: any) => k !== e));
153 e.querySelectorAll = (sel: string) => (sel === ".bar" ? e.kids.filter((k: any) => k.attrs.class === "bar") : sel === ".chart-hit" ? [] : []);
154 Object.defineProperty(e, "textContent", { get: () => e.text + e.kids.map((k: any) => k.textContent).join(""), set: (v: string) => ((e.text = v), (e.kids = [])) });
155 return e;
156 };
157 const plot = mk("chart-plot");
158 const ys = [mk(), mk(), mk()];
159 const now = mk();
160 const sr = mk();
161 const box = mk("chart");
162 box.attrs["data-chart"] = "bar";
163 box.attrs["aria-label"] = "Runs";
164 const card = mk("bp");
165 card.querySelector = (sel: string) => ({ ".bp-now .num": now, ".chart": box, ".chart .sr-only": sr, "svg.chart-plot": plot }[sel] ?? null);
166 card.querySelectorAll = (sel: string) => (sel === ".chart-y span" ? ys : []);
167 const grid = mk();
168 grid.attrs["data-stream"] = "/boards/x/stream";
169 grid.querySelectorAll = () => [card];
170 const say = mk();
171 const heard: Record<string, (e: { data: string }) => void> = {};
172 const run = new Function("document", "EventSource", "setInterval", boardStreamJs);
173 run(
174 { getElementById: (id: string) => (id === "board-grid" ? grid : say), createElementNS: (_: string, t: string) => mk(t) },
175 class { constructor() {} addEventListener(n: string, f: (e: { data: string }) => void) { heard[n] = f; } },
176 () => 0,
177 );
178 return { heard, plot, ys, now, say, sr };
179 }
180
181 test("a frame redraws the bars, the axis and the latest number, from the hello's points", () => {
182 const p = drawnPage();
183 p.heard.hello!({ data: JSON.stringify({ at: 1, base: [{ i: 0, points: [["check", 2], ["deploy", 1]] }] }) });
184 p.heard.panels!({ data: JSON.stringify({ at: 2, panels: [{ i: 0, points: [["check", 5], ["build", 3]], now: "3" }] }) });
185 const bars = p.plot.kids.filter((k: any) => k.attrs.class === "bar");
186 expect(bars.length).toBe(3);
187 expect(bars[0].textContent).toBe("check: 5");
188 expect(bars[2].textContent).toBe("build: 3");
189 expect(p.ys[0].textContent).toBe("5");
190 expect(p.now.textContent).toBe("3");
191 expect(p.sr.textContent).toContain("3 points; lowest 1, highest 5, latest 3");
192 expect(p.say.textContent).toContain("live");
193 });
194
195 test("a chart it cannot draw says so instead of going quiet", () => {
196 const p = drawnPage();
197 p.heard.hello!({ data: JSON.stringify({ at: 1, base: [] }) });
198 p.heard.panels!({ data: JSON.stringify({ at: 2, panels: [{ i: 0, points: [["check", 5]] }] }) });
199 expect(p.say.textContent).toContain("reload to redraw");
200 });
201 });
test/job-slices.test.ts +1
@@ -276,6 +276,7 @@ const UNTIMED: Record<string, string> = {
276276 "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly",
277277 "meter-watch": "one indexed read of held-full windows every 15 minutes, and a status fetch only while one is held full; meter-watch.test.ts drives it with a fake fetcher; the fixture holds no window",
278278 "talk-live": "a one-shot timer in talkStream (web/pages/talk.ts), armed only while a person has /talk open and a reply is being written: it sends that one stream its latest live frame, at most one per 125 ms, drawing a block of at most 20,000 characters; talk-live.test.ts drives the stream and counts its frames",
279 "boards-stream": "a one-shot timer in boards/live_hub.ts, armed only while a person has /boards/<slug> open: one read per board for every tab, sent as the points newer than the last, at most one per MIN_GAP_MS; boards-stream.test.ts drives the stream and counts its frames",
279280 "view-stream-send": "re-reads the forge view for one open stream, at most once per VIEW_GAP_MS, only while an agent follows the view; the view is cached and forge-view-stream.test.ts drives it",
280281 "view-stream-token-check": "one user read and one token read every 30 s per open stream; forge-view-stream.test.ts drives revocation",
281282 desk: "expires notes past their time: one indexed delete on the desk table every 30 s (actions/desk.ts); the fixture has no notes",
test/no-polling.test.ts +2 −1
@@ -110,6 +110,7 @@ const ALLOWED: Record<string, { allow: string[]; why: string }> = {
110110 "src/web/pages/talk.ts": { allow: ["setInterval"], why: "server side: the stream of one turn watches the run's row, which has no event to hear" },
111111 "src/web/client.ts": { allow: ["setInterval"], why: "clocks that only redraw text" },
112112 "src/web/space_client.ts": { allow: ["setInterval"], why: "the map clock label only redraws text; it fetches and reloads nothing" },
113 "src/web/pages/boards-stream.ts": { allow: ["setInterval"], why: "the board's \"updated Ns ago\" label only redraws text; the stream carries the data" },
113114 };
114115
115116 const PATTERNS: [string, RegExp][] = [
@@ -321,7 +322,7 @@ const NOT_WALKED: Record<string, string> = {
321322 "/:owner/:name/variants/:group": "needs a variant group of agent tries",
322323 "/:owner/:name/waves/:version": "needs a wave of a milestone",
323324 "/boards/:slug": "needs a board",
324 "/boards/:slug/live": "needs a board; a stream, not a page",
325 "/boards/:slug/stream": "needs a board; a stream, not a page",
325326 "/bring/:id/:job": "needs a bring job",
326327 "/claim/start/:token": "needs the one-time token an anonymous start returned",
327328 "/join/:token": "needs a one-use link to work on a repository, which a repository's admin mints",
test/pages-budget.test.ts +1 −1
@@ -75,7 +75,7 @@ const MAX_UNFIXTURED = 156; // +1: /:owner/:name/bets/:id/walk/:walk, a journey
7575 const NOT_PAGES = new Set([
7676 "/events", "/system/stream", "/settings/teams/stream", "/fleet/graph/live",
7777 "/settings/traffic/scrapes/export", "/settings/backups/live", "/:owner/:name/stream",
78 "/settings/origins/flows/:id/stream", "/:owner/:name/archive/:file", // a tarball download, not a page
78 "/settings/origins/flows/:id/stream", "/boards/:slug/stream", "/:owner/:name/archive/:file", // a tarball download, not a page
7979 "/api/v1/runner/jobs/:id/git/info/refs", // a runner's git door for one job (#13652), not a page
8080 ]);
8181
test/tui-boards.test.ts +12
@@ -18,6 +18,7 @@ import { boardRows, boardsScreen, dataLine, refusal, stepWords } from "../src/tu
1818 import { headlessTerminal } from "../src/tui/term/terminal.ts";
1919 import { quietLogs } from "./helpers/globals.ts";
2020 import { settleApp } from "./helpers/tui.ts";
21 import type { Board, Panel } from "../src/boards/store.ts";
2122
2223 quietLogs();
2324
@@ -235,3 +236,14 @@ describe("tui boards", () => {
235236 expect(refusal({ refused: "bad\u001b[2J" })).toBe("That was refused: bad [2J.");
236237 });
237238 });
239
240 test("a live frame says, under its panel, how many points moved and the latest value", async () => {
241 const { boardLines, liveWords } = await import("../src/tui/screens/boards.ts");
242 const frame = { at: Date.UTC(2026, 10, 29, 16, 5, 9), panels: [{ i: 1, points: [["a", 1], ["b", 2]] as [string, number][], now: "2" }] };
243 expect(liveWords(frame, 0)).toBeUndefined();
244 expect(liveWords(frame, 1)).toBe("live 16:05:09Z: 2 points moved · latest 2");
245 const one: Panel = { title: "A", chart: "bar", query: { source: "runs", aggregate: "count", groupBy: "kind" }, w: 1, h: 1 };
246 const board: Board = { title: "T", range: "all", refresh: "10s", panels: [one, { ...one, title: "B" }] };
247 const lines = boardLines(board, -1, [], [], new Map([[1, liveWords(frame, 1)!]]));
248 expect(lines.filter((l) => l.includes("live 16:05:09Z"))).toHaveLength(1);
249 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs