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

Boards, step 2: /boards/data draws a query as a line chart an admin can edit in place #1732

Closed opened this
Closed without merging

scout/forge:scout/1560-boards-step-2-boards-data-draws-a-query → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +366 −1
scripts/gate.ts +1
@@ -34,6 +34,7 @@ export const GATE: readonly string[] = [
3434 "test/apps-idle.test.ts",
3535 "test/body-limits.test.ts",
3636 "test/boards-query.test.ts",
37 "test/boards-page.test.ts",
3738 "test/turnstile.test.ts",
3839 "test/thoughts.test.ts",
3940 "test/passkeys.test.ts",
src/boards/chart.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * A line chart as an SVG string: a pure function from points to markup, no
3 * I/O, no dependencies, drawn the way `web/og/card.ts` draws. The viewBox is
4 * fixed and the element carries its aspect ratio, so the space is held
5 * before the first paint and nothing shifts. Colour is `currentColor`; every
6 * label is stripped of what XML cannot carry, clamped, then escaped.
7 */
8 import { escapeXml } from "../web/og/card.ts";
9
10 export type Point = { label: string; value: number; href?: string };
11
12 export const CHART_WIDTH = 720;
13 export const CHART_HEIGHT = 260;
14 const LEFT = 56;
15 const RIGHT = 16;
16 const TOP = 16;
17 const BOTTOM = 40;
18 const MAX_LABEL = 16;
19 const X_TICKS = 6;
20
21 const clean = (s: string) =>
22 s.replace(/[^\u0009\u000A\u000D -퟿-�]/gu, "").replace(/\s+/g, " ").trim();
23 const clamp = (s: string, n = MAX_LABEL) => {
24 const c = clean(s);
25 return c.length > n ? `${c.slice(0, n - 1)}…` : c;
26 };
27 const num = (n: number) => String(Math.round(n * 100) / 100);
28
29 /** A short, readable number for an axis. */
30 export function formatValue(v: number): string {
31 const a = Math.abs(v);
32 if (a >= 1e9) return `${num(v / 1e9)}G`;
33 if (a >= 1e6) return `${num(v / 1e6)}M`;
34 if (a >= 1e4) return `${num(v / 1e3)}k`;
35 return num(v);
36 }
37
38 export function lineChart(points: readonly Point[], title: string): string {
39 const w = CHART_WIDTH - LEFT - RIGHT;
40 const h = CHART_HEIGHT - TOP - BOTTOM;
41 const max = Math.max(0, ...points.map((p) => p.value));
42 const min = Math.min(0, ...points.map((p) => p.value));
43 const span = max - min || 1;
44 const x = (i: number) => LEFT + (points.length < 2 ? w / 2 : (i * w) / (points.length - 1));
45 const y = (v: number) => TOP + h - ((v - min) / span) * h;
46
47 const out: string[] = [
48 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${CHART_WIDTH} ${CHART_HEIGHT}" width="${CHART_WIDTH}" height="${CHART_HEIGHT}" role="img" aria-label="${escapeXml(clamp(title, 120))}" class="chart" preserveAspectRatio="xMidYMid meet" font-size="11" font-family="inherit" fill="currentColor">`,
49 `<title>${escapeXml(clamp(title, 120))}</title>`,
50 ];
51 for (const t of [0, 0.5, 1]) {
52 const v = min + span * t;
53 const gy = y(v);
54 out.push(
55 `<line x1="${LEFT}" x2="${CHART_WIDTH - RIGHT}" y1="${num(gy)}" y2="${num(gy)}" stroke="currentColor" stroke-opacity="0.2"/>`,
56 `<text x="${LEFT - 6}" y="${num(gy + 4)}" text-anchor="end">${escapeXml(formatValue(v))}</text>`,
57 );
58 }
59 if (points.length === 0) {
60 out.push(`<text x="${CHART_WIDTH / 2}" y="${CHART_HEIGHT / 2}" text-anchor="middle">No points</text></svg>`);
61 return out.join("");
62 }
63 const step = Math.max(1, Math.ceil(points.length / X_TICKS));
64 points.forEach((p, i) => {
65 if (i % step !== 0) return;
66 out.push(
67 `<text x="${num(x(i))}" y="${CHART_HEIGHT - 16}" text-anchor="middle">${escapeXml(clamp(p.label))}</text>`,
68 );
69 });
70 const d = points.map((p, i) => `${i === 0 ? "M" : "L"}${num(x(i))} ${num(y(p.value))}`).join(" ");
71 out.push(`<path d="${d}" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>`);
72 points.forEach((p, i) => {
73 const dot = `<circle cx="${num(x(i))}" cy="${num(y(p.value))}" r="4"><title>${escapeXml(clamp(p.label, 40))}: ${escapeXml(formatValue(p.value))}</title></circle>`;
74 out.push(p.href === undefined ? dot : `<a href="${escapeXml(p.href)}">${dot}</a>`);
75 });
76 out.push("</svg>");
77 return out.join("");
78 }
src/core/reserved.ts +1
@@ -63,6 +63,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6363 "audit.csv",
6464 "big",
6565 "board",
66 "boards",
6667 "events",
6768 "explore",
6869 "fleet",
src/http/server.ts +2
@@ -9,6 +9,7 @@ import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
99 import { unsealReleased } from "../actions/sealed.ts";
1010 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1111 import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts";
12 import { boardsPage } from "../web/pages/boards.ts";
1213 import {
1314 closeStreamsOf,
1415 closeStreamsOfSession,
@@ -691,6 +692,7 @@ export function buildRouter(): Router<Handler> {
691692 router.add("POST", "/settings/cloud/remove", cloudRemove);
692693 router.add("GET", "/settings/capacity", capacityPage);
693694 router.add("POST", "/settings/capacity", capacitySet);
695 router.add("GET", "/boards/data", boardsPage);
694696 router.add("GET", "/admin/limits", limitsPage);
695697 router.add("POST", "/admin/limits", limitsSet);
696698 router.add("GET", "/settings/backups", backupsPage);
src/web/layout.ts +6 −1
@@ -208,7 +208,12 @@ function userMenu(ctx: Ctx, user: User, signOut: MenuItem): Html {
208208 { label: "SSH keys", href: "/settings/keys", icon: "lock" },
209209 { label: "Origins", href: "/settings/origins", icon: "globe" },
210210 ...(user.isAdmin
211 ? [{ label: "Crew", href: "/settings/crew", icon: "bot" as const }]
211 ? [
212 { label: "Crew", href: "/settings/crew", icon: "bot" as const },
213 ...(user.kind === "agent"
214 ? []
215 : [{ label: "Boards", href: "/boards/data", icon: "activity" as const }]),
216 ]
212217 : []),
213218 { separator: true, label: "" },
214219 signOut,
src/web/pages/boards.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * Boards, for a forge admin who is a person: `GET /boards/data` lists the
3 * sources and their columns, and draws one query as a line chart with the
4 * table of its points under it. The query is the URL (GET params), so a
5 * query is a link. Each point links to the rows behind it: the same query
6 * narrowed to that point's window and listed by the source's first column.
7 * Anyone else gets the not-found page.
8 */
9 import { lineChart } from "../../boards/chart.ts";
10 import { runQuery, type Query } from "../../boards/query.ts";
11 import { SOURCES } from "../../boards/sources.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { notFoundPage } from "../chrome.ts";
14 import { html, raw } from "../html.ts";
15 import { page } from "../layout.ts";
16 import { btn, card, empty } from "../ui.ts";
17
18 const BUCKET_MS = { minute: 60_000, hour: 3_600_000, day: 86_400_000 } as const;
19 const AGGREGATES = ["count", "sum", "avg", "max"] as const;
20 const OPS = ["eq", "ne", "lt", "lte", "gt", "gte"] as const;
21 const MAX_PARAM = 256;
22
23 type Bucket = keyof typeof BUCKET_MS;
24 const isBucket = (s: string): s is Bucket => Object.hasOwn(BUCKET_MS, s);
25
26 /** What the URL asks for: plain strings, bounded; `runQuery` judges them. */
27 function readParams(url: URL) {
28 const get = (k: string, d = "") => (url.searchParams.get(k) ?? d).slice(0, MAX_PARAM);
29 return {
30 source: get("source", "runs"),
31 aggregate: get("aggregate", "count"),
32 column: get("column"),
33 by: get("by", "day"),
34 from: get("from"),
35 to: get("to"),
36 fcolumn: get("fcolumn"),
37 fop: get("fop", "eq"),
38 fvalue: get("fvalue"),
39 rows: get("rows") === "1" ? "1" : "",
40 };
41 }
42 type Params = ReturnType<typeof readParams>;
43
44 function toQuery(p: Params): Query {
45 const src = Object.hasOwn(SOURCES, p.source) ? SOURCES[p.source]! : undefined;
46 const q: Query = { source: p.source, aggregate: p.aggregate };
47 if (p.column !== "") q.column = p.column;
48 if (p.from !== "") q.from = p.from;
49 if (p.to !== "") q.to = p.to;
50 q.groupBy = isBucket(p.by) ? { bucket: p.by } : p.by;
51 if (p.fcolumn !== "") {
52 const numeric = src?.columns[p.fcolumn] === "number";
53 q.filter = [{ column: p.fcolumn, op: p.fop, value: numeric ? Number(p.fvalue) : p.fvalue }];
54 }
55 return q;
56 }
57
58 const link = (p: Params) => {
59 const s = new URLSearchParams();
60 for (const [k, v] of Object.entries(p)) if (v !== "") s.set(k, v);
61 return `/boards/data?${s}`;
62 };
63
64 /** The rows behind one point: its window, listed by the source's first column. */
65 function behind(p: Params, group: string | number | null): string {
66 const first = Object.keys(SOURCES[p.source]!.columns)[0]!;
67 if (!isBucket(p.by) || typeof group !== "string") {
68 return link({ ...p, rows: "1", by: first, aggregate: "count", column: "", ...(typeof group === "string" ? { fcolumn: p.by, fop: "eq", fvalue: group } : {}) });
69 }
70 const start = new Date(group);
71 return link({
72 ...p, rows: "1", by: first, aggregate: "count", column: "",
73 from: start.toISOString(), to: new Date(start.getTime() + BUCKET_MS[p.by]).toISOString(),
74 });
75 }
76
77 const option = (value: string, label: string, selected: boolean) =>
78 html`<option value="${value}" ${selected ? raw("selected") : null}>${label}</option>`;
79
80 // GET /boards/data
81 export function boardsPage(ctx: Ctx): Response {
82 const user = ctx.auth.user;
83 if (user?.isAdmin !== true || user.kind === "agent") return notFoundPage(ctx);
84 const p = readParams(ctx.url);
85 const src = Object.hasOwn(SOURCES, p.source) ? SOURCES[p.source]! : undefined;
86 const answer = runQuery(ctx.app.db, toQuery(p), { repoIds: "all" });
87 const cols = src ? Object.keys(src.columns) : [];
88
89 const sources = card(
90 html`<ul class="list">
91 ${Object.entries(SOURCES).map(
92 ([name, s]) => html`<li class="row">
93 <a href="${link({ ...p, source: name, by: "day", column: "", fcolumn: "", fvalue: "", rows: "" })}"><strong>${name}</strong></a>
94 <span class="muted small mono">${Object.entries(s.columns).map(([c, t]) => `${c}:${t}`).join(" ")}</span>
95 </li>`,
96 )}
97 </ul>`,
98 { head: html`<h2>Sources</h2>`, pad: false },
99 );
100
101 const form = card(
102 html`<form method="get" action="/boards/data" class="row-actions">
103 <select class="input" name="source" aria-label="Source">
104 ${Object.keys(SOURCES).map((n) => option(n, n, n === p.source))}
105 </select>
106 <select class="input" name="aggregate" aria-label="Aggregate">
107 ${AGGREGATES.map((a) => option(a, a, a === p.aggregate))}
108 </select>
109 <select class="input" name="column" aria-label="Column to aggregate">
110 ${option("", "(rows)", p.column === "")}
111 ${cols.filter((c) => src!.columns[c] === "number").map((c) => option(c, c, c === p.column))}
112 </select>
113 <select class="input" name="by" aria-label="Group by">
114 ${(Object.keys(BUCKET_MS) as Bucket[]).map((b) => option(b, `per ${b}`, b === p.by))}
115 ${cols.map((c) => option(c, `by ${c}`, c === p.by))}
116 </select>
117 <input class="input mono" name="from" value="${p.from}" placeholder="from 2026-10-01" aria-label="From" maxlength="${MAX_PARAM}" />
118 <input class="input mono" name="to" value="${p.to}" placeholder="to 2026-10-08" aria-label="To" maxlength="${MAX_PARAM}" />
119 <select class="input" name="fcolumn" aria-label="Filter column">
120 ${option("", "(no filter)", p.fcolumn === "")}
121 ${cols.map((c) => option(c, c, c === p.fcolumn))}
122 </select>
123 <select class="input" name="fop" aria-label="Filter operator">
124 ${OPS.map((o) => option(o, o, o === p.fop))}
125 </select>
126 <input class="input mono" name="fvalue" value="${p.fvalue}" placeholder="value" aria-label="Filter value" maxlength="${MAX_PARAM}" />
127 ${btn("Draw", { variant: "primary" })}
128 </form>`,
129 { head: html`<h2>Query</h2>` },
130 );
131
132 let result;
133 if (!answer.ok) {
134 result = empty({ icon: "activity", title: "That query was refused", note: answer.error });
135 } else if (answer.rows.length === 0) {
136 result = empty({ icon: "activity", title: "No rows", note: "Nothing matches this query." });
137 } else {
138 const points = answer.rows.map((r) => ({
139 label: String(r.group ?? "all"),
140 value: r.value ?? 0,
141 ...(p.rows === "" ? { href: behind(p, r.group) } : {}),
142 }));
143 const chart =
144 p.rows === ""
145 ? html`<div class="chart-box">${raw(lineChart(points, `${p.aggregate} of ${p.source}`))}</div>`
146 : html`<p class="muted small">The rows behind a point. <a href="${link({ ...p, rows: "" })}">Back to the chart</a>.</p>`;
147 result = html`${chart}
148 <table class="table">
149 <thead><tr><th scope="col">${isBucket(p.by) ? p.by : p.by}</th><th scope="col" class="num">${p.aggregate}</th></tr></thead>
150 <tbody>
151 ${answer.rows.map(
152 (r, i) => html`<tr>
153 <td class="mono">${p.rows === "" ? html`<a href="${points[i]!.href!}">${points[i]!.label}</a>` : points[i]!.label}</td>
154 <td class="num mono">${String(r.value ?? "")}</td>
155 </tr>`,
156 )}
157 </tbody>
158 </table>`;
159 }
160
161 return page({
162 ctx,
163 title: "Boards",
164 body: html`<div class="page-head"><h1>Boards</h1></div>
165 ${form} ${card(result, { head: html`<h2>${p.source}</h2>`, extra: "boards-result" })} ${sources}`,
166 });
167 }
src/web/style/content.ts +5
@@ -373,6 +373,11 @@ a.origin-chip:hover { border-color: var(--border-strong); color: var(--fg); }
373373 .fleet-windows { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 380px), 1fr)); gap: 16px; margin: 0 0 16px; }
374374 .fleet-window { margin: 0; }
375375 .fleet-window figcaption { font-size: 13px; font-weight: 600; margin: 0 0 4px; display: flex; gap: 8px; align-items: baseline; }
376 .chart-box { color: var(--accent); aspect-ratio: 720 / 260; max-width: 720px; }
377 .chart-box .chart { display: block; width: 100%; height: auto; }
378 .chart-box text { fill: var(--muted-fg); font-family: var(--mono); font-size: 10px; }
379 .chart-box circle { fill: var(--accent); }
380 .boards-result .table { margin-top: 12px; }
376381 .fleet-svg { display: block; width: 100%; height: auto; aspect-ratio: 600 / 230; }
377382 .fleet-grid line { stroke: var(--border); stroke-width: 1; }
378383 .fleet-ticks text { fill: var(--muted-fg); font-size: 10px; text-anchor: end; font-family: var(--mono); }
test/boards-page.test.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * /boards/data: seeded runs draw a path with one point per bucket, a query
3 * is a link, points link to their rows, and anyone but a person who is an
4 * admin gets the not-found page.
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 { lineChart } from "../src/boards/chart.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve } from "../src/http/server.ts";
15
16 let dir: string;
17 let app: ReturnType<typeof createApp>;
18 let servers: Awaited<ReturnType<typeof serve>>;
19 const tok: Record<string, string> = {};
20 const get = (path: string, who: string | null) =>
21 fetch(servers.url + path, { headers: who ? { authorization: `Bearer ${tok[who]}` } : {} });
22
23 beforeAll(async () => {
24 dir = await mkdtemp(join(tmpdir(), "forge-boards-page-"));
25 app = createApp({ dataDir: dir, port: 0 });
26 servers = await serve(app);
27 const mk = async (username: string, adminIfFirst?: boolean) => {
28 const r = await createUser(app.db, {
29 trusted: true, username, email: `${username}@forge.local`,
30 password: "a-good-passphrase", ...(adminIfFirst ? { adminIfFirst } : {}),
31 });
32 if (!r.ok) throw new Error(r.error);
33 return r.value;
34 };
35 const alice = await mk("alice", true);
36 const bob = await mk("bob");
37 tok.admin = createToken(app.db, alice.id, "t", "admin").token;
38 tok.bob = createToken(app.db, bob.id, "t", "admin").token;
39 app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('rb', ?, 'n')", [alice.id]);
40 const ins = app.db.prepare("INSERT INTO run (id, repo_id, kind, state, created_at) VALUES (?, 'rb', 'agent', 'ok', ?)");
41 ins.run("a", "2026-10-01T10:05:00.000Z");
42 ins.run("b", "2026-10-02T10:05:00.000Z");
43 ins.run("c", "2026-10-02T11:05:00.000Z");
44 ins.run("d", "2026-10-04T11:05:00.000Z");
45 });
46
47 afterAll(async () => {
48 servers.stop();
49 app.close();
50 await rm(dir, { recursive: true, force: true });
51 });
52
53 describe("/boards/data", () => {
54 test("seeded runs per day draw one path with one point per day", async () => {
55 const res = await get("/boards/data?source=runs&by=day", "admin");
56 expect(res.status).toBe(200);
57 const body = await res.text();
58 expect(body.match(/<path d="M[^"]*" fill="none" stroke="currentColor" stroke-width="2"/g)?.length).toBe(1);
59 expect(body.match(/<circle cx="[^"]*" cy="[^"]*" r="4">/g)?.length).toBe(3);
60 expect(body).toContain("2026-10-02T00:00:00Z");
61 });
62
63 test("a point links to the rows behind it", async () => {
64 const body = await (await get("/boards/data?source=runs&by=day", "admin")).text();
65 const m = body.match(/href="(\/boards\/data\?[^"]*rows=1[^"]*)"/);
66 expect(m).not.toBeNull();
67 const rows = await (await get(m![1]!.replaceAll("&amp;", "&"), "admin")).text();
68 expect(rows).not.toContain('r="4">');
69 expect(rows).toContain("<table");
70 });
71
72 test("a bad query is refused on the page, not thrown", async () => {
73 const res = await get("/boards/data?source=nope", "admin");
74 expect(res.status).toBe(200);
75 expect(await res.text()).toContain("That query was refused");
76 });
77
78 test("a filter narrows the points", async () => {
79 const body = await (await get("/boards/data?source=runs&by=day&from=2026-10-02&to=2026-10-03", "admin")).text();
80 expect(body.match(/<circle cx="[^"]*" cy="[^"]*" r="4">/g)?.length).toBe(1);
81 });
82
83 test("hostile params are escaped", async () => {
84 const body = await (await get('/boards/data?from="><script>x</script>', "admin")).text();
85 expect(body).not.toContain("<script>x</script>");
86 });
87
88 test("a non-admin and a stranger get 404; the admin's menu links Boards", async () => {
89 expect((await get("/boards/data", "bob")).status).toBe(404);
90 expect((await get("/boards/data", null)).status).toBe(404);
91 expect(await (await get("/", "admin")).text()).toContain('href="/boards/data"');
92 expect(await (await get("/", "bob")).text()).not.toContain('href="/boards/data"');
93 });
94 });
95
96 describe("lineChart", () => {
97 test("escapes labels and holds its size", () => {
98 const svg = lineChart([{ label: "<b>&", value: 1 }, { label: "x", value: 2 }], "t");
99 expect(svg).not.toContain("<b>");
100 expect(svg).toContain("&lt;b&gt;&amp;");
101 expect(svg).toContain('viewBox="0 0 720 260"');
102 });
103 test("no points still draws", () => {
104 expect(lineChart([], "t")).toContain("No points");
105 });
106 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs