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

Boards show check and crew slots against capacity; Capacity is findable; /flow answers first (3.3 MB → capped) #16830

Merged opened this

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

Merged

capacity-boards → main 0 commits 2 threads · 2 unresolved

  • Merged. capacity-boards was merged into main as ff9bc70.

Review

Sign in to review this change.
17 files changed +677 −54
docs/design/areas/boards.md +2
@@ -27,6 +27,8 @@ The card under the Pipeline table (`id="verified"`) adds no class: it is a `card
2727 - `.bd-live` — the region that redraws as work moves (`data-live`, no address of its own, so the page is refetched for it at most once in 30 s): the sentence, the figures, the pipeline.
2828 - `.bd-now`, `.bd-lead` — the bottleneck sentence at 16px and, under it in the muted colour, only the lines that hold right now (conflicted pulls, a held rebase lane, idle pulls).
2929 - `.bd-block`, `.bd-head`, `.bd-sub` — a block of the page: its `<h2>`, one sentence of what it shows, and its quiet links.
30 - `.fl-stages`, `.fl-stage` — /flow's answer under its one sentence: each stage that has anything waiting or worked, one line (`stageSays`: what waits, what is active, what limits it, the oldest wait), the bottleneck in the danger colour. Everything else on /flow folds under one line, and no list shows more than ten rows: the last line, "and N more", links to /flow?all=<list id>, that list whole with its fold open.
31 - `.sl-block`, `.sl`, `.sl-head` (the name, the busy count and, in `.sl-say`, what waits), `.sl-used`, `.sl-chart`, `.sl-busy`, `.sl-full`, `.sl-wait`, `.sl-line`, `.sl-foot` — the slots above the pipeline (`src/web/flow_slots.ts`): for checks and the crew, "4 of 4 slots busy" in the danger colour with a full badge when every slot is busy and something waits, what waits and its oldest and median wait, the crew's pace when it allows fewer, and the 24 hours as bars with the setting dashed across them (solid red where a bar reaches it, muted below, waiting lighter on top). Change capacity is a button under them.
3032 - `.pl`, `.pl-cap`, `.pl-trend`, `.pl-spark` — the pipeline: §5's `.table` with every number right-aligned and tabular, a zero in the faint colour, the day's 24 hours as bars. On a phone each stage is a card: its name, then its five numbers in one row with their names over them.
3133 - `.bd-boards` — the boards as tiles: two across on a phone, four from 720px. Each tile is a `data-nav` row for `j`/`k`.
3234 - `.folds`, `.fold`, `.fold-title`, `.fold-state`, `.fold-body` — `fold()`: a `disclosure` whose summary is the section's name and one sentence of how it stands now ("nothing queued; 26 landed in the last hour"); the detail is inside. Hairlines between, no card.
docs/design/attention-budget.json +6 −5
@@ -216,15 +216,16 @@
216216 },
217217 "boards": {
218218 "390": {
219 "words": 336,
220 "blocks": 95,
219 "words": 342,
220 "blocks": 98,
221221 "colours": 2
222222 },
223223 "1280": {
224 "words": 336,
225 "blocks": 95,
224 "words": 342,
225 "blocks": 98,
226226 "colours": 2
227 }
227 },
228 "note": "Raised by 6 words and 3 blocks for the slots above the pipeline, at their least: a line each for checks and the crew (\"Checks 0 of 1 slots busy\", nothing more while nothing waits) and the Change capacity button that replaced the header's Capacity link; no legend (#16830)."
228229 },
229230 "forges": {
230231 "390": {
docs/features/capacity-slots.md added +14
@@ -0,0 +1,14 @@
1 ---
2 topic: When something is wrong
3 row: Slots against what fills them, and /flow's one answer
4 ---
5 # Slots against what fills them, and /flow's one answer
6
7 The owner, looking at a solid bar of checks on /boards: "i cant see how it compares to available compute… cant see a capacity page… the flow page is interesting but the data is just spammed and hard to consume."
8
9 - **Slots** (`src/flow/slots.ts`, `src/web/flow_slots.ts`). Above the pipeline on /boards, and under /flow's answer, checks and crew runs each say how many of their slots are busy, "4 of 4 slots busy", against the live `checks.concurrency` and `crew.concurrency` (the line moves the moment a setting does). Under it: what waits, the oldest wait, and the median wait of what started in the last hour. A 24-hour picture, a bar each quarter hour, has the setting dashed across it: bars that reach it are solid in the danger colour, bars below it muted, what waited lighter on top. Every slot busy with something waiting is **full**, in the danger colour with a badge. When the crew's pace (the subscriptions' windows and the week's share, `repoPace`) allows fewer slots than the setting, its line says so and why: "pace allows 2: espo-corp's 5-hour window is full until 16:20 UTC", so an idle crew never reads as spare capacity. All of it is read from the run table; nothing new is sampled.
10 - **In the terminal** the same settings are set on the Capacity screen (`src/tui/screens/capacity.ts`), and the dashboard (`src/tui/screens/dashboard.ts`) says the bottleneck; the slot picture is the web's.
11 - **Capacity, findable.** `/settings/capacity` was the third tab of Settings › Crew and AI › Usage, a row that opens Spend, and the palette did not list it. It stays a Usage tab (Usage is one sidebar entry) and now has a palette row (admins only, as the page is), and **Change capacity** is a button under the slots on /boards and /flow.
12 - **/flow answers first.** One sentence says what holds the work back (the bottleneck stage, how many wait, the oldest, what limits it: the same sentence the MCP flow card leads with). Then, when more than one stage has anything waiting or worked, those stages, one line each in the words the card uses ("17 waiting · 0 active · checks at once 4 · oldest 44m"), then the slots. Everything else (the week's money and valves, clogs, checks stopped for CPU, approved and green pulls not landed, stale crew pulls, unproposed branches) folds under one line that says how it stands, and no list shows more than ten rows, then "and N more", a link to `/flow?all=<list id>`: that list whole, its fold open. The page was 3.3 MB on production (4,332 unproposed branches in one list); `FLOW_PAGE_BYTES` (200 KB) holds it.
13
14 Proof: `test/flow-slots.test.ts`, `test/flow-answer.test.ts`.
src/flow/pipeline.ts +9
@@ -330,6 +330,15 @@ export function span(ms: number): string {
330330 return `${Math.floor(h / 24)}d ${h % 24}h`;
331331 }
332332
333 /**
334 * A stage in one line, as /flow and the MCP flow card both say it: what waits, what is worked,
335 * what limits it, and the oldest wait. "17 waiting · 5 active · checks at once 4 · oldest 44m".
336 */
337 export function stageSays(s: PipelineStage, now: number): string {
338 const oldest = s.oldestWaiting === null || Number.isNaN(Date.parse(s.oldestWaiting)) ? "" : ` · oldest ${span(now - Date.parse(s.oldestWaiting))}`;
339 return `${s.waiting} waiting · ${s.active} active${s.capacity === null ? "" : ` · ${s.capacity}`}${oldest}`;
340 }
341
333342 /** How long a stage's oldest waiting item has waited, or null when nothing waits. */
334343 export const waited = (s: PipelineStage, now: number): string | null =>
335344 s.oldestWaiting === null ? null : span(now - Date.parse(s.oldestWaiting));
src/flow/slots.ts added +139
@@ -0,0 +1,139 @@
1 /**
2 * The forge's slots against what fills them (the owner: "i cant see how it compares to available
3 * compute"): checks and crew runs, each as its live ceiling (`checks.concurrency`,
4 * `crew.concurrency`), what runs now, what waits, the oldest wait and the median wait of what
5 * started in the last hour, and the last 24 hours at quarter-hour instants. Read from the run
6 * table alone: what ran and waited is in its own `created_at`, `started_at` and `finished_at`, so
7 * nothing new is sampled. For the crew, the pace (the subscriptions' windows and the week's
8 * share, `repoPace`) can allow fewer slots than the setting; then it says how many and why, so an
9 * idle crew never reads as spare capacity. The source is `paceHold`'s (#16722): it speaks only when
10 * no run may start; this says how many may.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import type { App } from "../app.ts";
15 import { capacityValues } from "../core/capacity.ts";
16 import { forgeRepo } from "../core/forge_repo.ts";
17 import { repoPace } from "../crew/autonomy_pace.ts";
18
19 /** The instants the 24 hours are read at: one each quarter hour, oldest first. */
20 export const SLOT_POINTS = 96;
21 const STEP_MS = 15 * 60_000;
22 const HOUR_MS = 3_600_000;
23
24 export interface SlotPoint {
25 readonly running: number;
26 readonly queued: number;
27 }
28
29 export interface SlotLine {
30 readonly kind: "checks" | "crew";
31 /** The live setting: what the line is drawn at. */
32 readonly slots: number;
33 readonly busy: number;
34 readonly waiting: number;
35 /** When the oldest waiting one was asked for; null when none waits. */
36 readonly oldestAt: string | null;
37 /**
38 * The median wait from asked to started, of what started in the last hour; null when none did.
39 */
40 readonly medianWaitMs: number | null;
41 readonly points: readonly SlotPoint[];
42 /** The crew's pace, when it allows fewer slots than the setting. */
43 readonly pace?: { readonly allows: number; readonly why: string };
44 }
45
46 /** Busy at or over the line with something waiting: full, and the queue is what that costs. */
47 export const isFull = (l: SlotLine): boolean => l.busy >= l.slots && l.waiting > 0;
48
49 type Row = { kind: string; created_at: string; started_at: string | null; finished_at: string | null; state: string };
50
51 /**
52 * Checks' and agents' runs that touched the last 24 hours, both in one statement. Crew runs are
53 * agent runs that build (a review is the crew too).
54 */
55 function rows(db: Database, since: string): Row[] {
56 return db
57 .query<Row, [string]>(
58 `SELECT kind, created_at, started_at, finished_at, state FROM run
59 WHERE kind IN ('check', 'agent') AND (state IN ('queued', 'running') OR finished_at >= ?1)`,
60 )
61 .all(since);
62 }
63
64 /** The line for one kind of run, read from its rows at `now`. Pure: rows in, figures out. */
65 export function slotLine(kind: SlotLine["kind"], slots: number, runs: readonly Row[], now: number): SlotLine {
66 const t = (iso: string | null): number => (iso === null ? Infinity : Date.parse(iso));
67 const points: SlotPoint[] = [];
68 for (let i = SLOT_POINTS - 1; i >= 0; i--) {
69 const at = now - i * STEP_MS;
70 let running = 0;
71 let queued = 0;
72 for (const r of runs) {
73 const asked = t(r.created_at),
74 started = t(r.started_at),
75 ended = t(r.finished_at);
76 if (started <= at && at < ended) running++;
77 else if (asked <= at && at < Math.min(started, ended)) queued++;
78 }
79 points.push({ running, queued });
80 }
81 const waitingNow = runs.filter((r) => r.state === "queued");
82 const waits = runs
83 .filter((r) => r.started_at !== null && now - t(r.started_at) <= HOUR_MS && now >= t(r.started_at))
84 .map((r) => t(r.started_at) - t(r.created_at))
85 .sort((a, b) => a - b);
86 const mid =
87 waits.length === 0
88 ? null
89 : waits.length % 2 === 1
90 ? waits[(waits.length - 1) / 2]!
91 : (waits[waits.length / 2 - 1]! + waits[waits.length / 2]!) / 2;
92 return {
93 kind,
94 slots,
95 busy: runs.filter((r) => r.state === "running").length,
96 waiting: waitingNow.length,
97 oldestAt: waitingNow.reduce<string | null>((o, r) => (o === null || r.created_at < o ? r.created_at : o), null),
98 medianWaitMs: mid,
99 points,
100 };
101 }
102
103 /** The setting as a count: what is in force now, so the line moves the moment it is changed. */
104 const slotsOf = (v: string): number => Math.max(1, Number(v) || 1);
105
106 /**
107 * How long the crew's pace is kept once read: it reads the windows and the week (several
108 * statements), changes on the crew's tick rather than per page, and /flow and /boards both draw it.
109 */
110 const PACE_KEPT_MS = 60_000;
111 const paceRead = new WeakMap<App, { at: number; slots: number; reason: string }>();
112
113 /** The crew's pace for the forge's own repository, read at most once a minute; none without one. */
114 function paceOf(app: App, now: Date): { slots: number; reason: string } | undefined {
115 const kept = paceRead.get(app);
116 if (kept !== undefined && Math.abs(now.getTime() - kept.at) < PACE_KEPT_MS) return kept;
117 const repo = forgeRepo(app);
118 if (repo === undefined) return undefined;
119 const p = repoPace(app, repo, now);
120 const read = { at: now.getTime(), slots: p.slots, reason: p.reason };
121 paceRead.set(app, read);
122 return read;
123 }
124
125 /**
126 * Checks, then the crew: their lines at `now`. Two statements (the settings, the runs) and the
127 * crew's pace, which is kept a minute.
128 */
129 export function readSlots(app: App, now: Date = new Date()): SlotLine[] {
130 const since = new Date(now.getTime() - SLOT_POINTS * STEP_MS).toISOString();
131 const set = capacityValues(app.db, ["checks.concurrency", "crew.concurrency"] as const);
132 const runs = rows(app.db, since);
133 const checks = slotLine("checks", slotsOf(set["checks.concurrency"]), runs.filter((r) => r.kind === "check"), now.getTime());
134 const crewSlots = slotsOf(set["crew.concurrency"]);
135 const crew = slotLine("crew", crewSlots, runs.filter((r) => r.kind === "agent"), now.getTime());
136 const paced = paceOf(app, now);
137 const allows = paced === undefined ? crewSlots : Math.min(crewSlots, paced.slots);
138 return [checks, allows < crewSlots && paced !== undefined && paced.reason !== "" ? { ...crew, pace: { allows, why: paced.reason } } : crew];
139 }
src/web/flow_slots.ts added +94
@@ -0,0 +1,94 @@
1 /**
2 * The slots, drawn (`flow/slots.ts`): for checks and for the crew, one line that says how many of
3 * the slots are busy against how many there are, what waits and for how long, and a 24-hour
4 * picture with the ceiling drawn across it, so a saturated lane reads as full at a glance. Bars
5 * that reach the line are drawn solid, those below it muted; what waited sits lighter on top.
6 * "Change capacity" goes to the page that sets the ceiling. Shown on /boards and on /flow.
7 */
8
9 import { html, type Html } from "./html.ts";
10 import { badge } from "./ui.ts";
11 import { span } from "../flow/pipeline.ts";
12 import { isFull, SLOT_POINTS, type SlotLine } from "../flow/slots.ts";
13
14 const NAME: Readonly<Record<SlotLine["kind"], string>> = { checks: "Checks", crew: "Crew runs" };
15 const H = 32;
16
17 /**
18 * The 24 hours: busy as bars, waiting stacked lighter above, the ceiling as a dashed line. A
19 * picture only.
20 */
21 function chart(l: SlotLine): Html {
22 const W = SLOT_POINTS * 3;
23 const top = Math.max(l.slots, ...l.points.map((p) => p.running + p.queued), 1);
24 const y = (n: number): number => H - Math.round((n / top) * (H - 2));
25 const bars = l.points.map((p, i) => {
26 const x = i * 3;
27 const run =
28 p.running === 0
29 ? null
30 : html`<rect
31 class="${p.running >= l.slots ? "sl-full" : "sl-busy"}"
32 x="${String(x)}"
33 y="${String(y(p.running))}"
34 width="2"
35 height="${String(H - y(p.running))}"
36 />`;
37 const wait =
38 p.queued === 0
39 ? null
40 : html`<rect
41 class="sl-wait"
42 x="${String(x)}"
43 y="${String(y(p.running + p.queued))}"
44 width="2"
45 height="${String(y(p.running) - y(p.running + p.queued))}"
46 />`;
47 return html`${run}${wait}`;
48 });
49 const at = y(l.slots);
50 return html`<svg class="sl-chart" viewBox="0 0 ${String(W)} ${String(H)}" preserveAspectRatio="none" aria-hidden="true" focusable="false">
51 ${bars}
52 <line class="sl-line" x1="0" x2="${String(W)}" y1="${String(at)}" y2="${String(at)}" />
53 </svg>`;
54 }
55
56 /**
57 * One kind's line: the headline figure, what waits, the pace when it holds the crew back, the
58 * picture.
59 */
60 function line(l: SlotLine, now: number): Html {
61 const full = isFull(l);
62 // What waits, the median wait and the pace, each only when there is one: a free lane is its
63 // count.
64 const says: (Html | string)[] = [
65 ...(l.waiting === 0 ? [] : [`${String(l.waiting)} waiting · oldest ${span(now - Date.parse(l.oldestAt ?? new Date(now).toISOString()))}`]),
66 ...(l.medianWaitMs === null ? [] : [`median wait ${span(l.medianWaitMs)} (last hour)`]),
67 ...(l.pace === undefined ? [] : [html`<span data-pace="${String(l.pace.allows)}">pace allows ${String(l.pace.allows)}: ${l.pace.why}</span>`]),
68 ];
69 return html`<div class="sl" data-kind="${l.kind}" ${full ? html`data-full` : null}>
70 <p class="sl-head">
71 <strong>${NAME[l.kind]}</strong>
72 <span class="sl-used" data-busy="${String(l.busy)}" data-slots="${String(l.slots)}"
73 >${String(l.busy)} of ${String(l.slots)} slots busy</span
74 >${full ? html` ${badge("full", { tone: "danger" })}` : null}
75 ${says.length === 0 ? null : html`<span class="sl-say small">${says.map((s, i) => html`${i === 0 ? "" : " · "}${s}`)}</span>`}
76 </p>
77 ${chart(l)}
78 </div>`;
79 }
80
81 /**
82 * The block: checks, then the crew, then the way to change them. `admin`: whether the link goes
83 * anywhere for this reader.
84 */
85 export function slotsBlock(lines: readonly SlotLine[], now: number, admin: boolean): Html {
86 return html`<div class="sl-block" id="slots" aria-label="Slots against what fills them">
87 ${lines.map((l) => line(l, now))}
88 ${admin
89 ? html`<p class="sl-foot small">
90 <a class="btn" data-size="sm" href="/settings/capacity">Change capacity</a>
91 </p>`
92 : null}
93 </div>`;
94 }
src/web/pages/flow-clog.ts +7 −5
@@ -7,22 +7,24 @@
77 import type { ClogView } from "../../flow/clog_view.ts";
88 import { html, type Html } from "../html.ts";
99 import { icon, row } from "../ui.ts";
10 import { shown } from "./flow-waiting.ts";
1011
1112 export { readClogView } from "../../flow/clog_view.ts";
1213
1314 type Ref = { repo: string; number: number };
1415 const pullLink = (r: Ref) => html`<a href="/${r.repo}/pulls/${String(r.number)}">${r.repo} #${String(r.number)}</a>`;
1516
16 export function clogSection(v: ClogView): Html {
17 /** The clog's two lists; `all` names one to show whole (`?all=`). */
18 export function clogSection(v: ClogView, all: string | null = null): Html {
1719 if (v.says === "" && v.shared.length === 0 && v.pairs.length === 0) return html``;
1820 return html`<div class="mb" id="flow-clog">${v.says === "" ? "" : html`<p id="clog-says">${v.says}</p>`}
19 ${v.shared.length === 0 ? "" : html`<ul class="list" id="flow-shared-red">${v.shared.map((s) => row({
21 ${v.shared.length === 0 ? "" : html`<ul class="list" id="flow-shared-red">${shown(v.shared, (s) => row({
2022 lead: icon("alert"),
2123 title: html`<code>${s.test}</code> <span class="muted small">fails on ${String(s.pulls.length)} open pulls</span>`,
2224 meta: html`<span class="small">${s.pulls.map((p, i) => html`${i === 0 ? "" : ", "}${pullLink(p)}`)}</span>`,
23 }))}</ul>`}
24 ${v.pairs.length === 0 ? "" : html`<ul class="list" id="flow-conflict-pairs">${v.pairs.map((c) => row({
25 }), "flow-shared-red", all)}</ul>`}
26 ${v.pairs.length === 0 ? "" : html`<ul class="list" id="flow-conflict-pairs">${shown(v.pairs, (c) => row({
2527 lead: icon("branch"),
2628 title: html`${pullLink(c.a)} and ${pullLink(c.b)} <span class="muted small">${String(c.shared)} shared ${c.shared === 1 ? "file" : "files"}</span>`,
27 }))}</ul>`}</div>`;
29 }), "flow-conflict-pairs", all)}</ul>`}</div>`;
2830 }
src/web/pages/flow-cpu.ts +5 −3
@@ -9,6 +9,7 @@
99 import type { CpuClosedPull } from "../../flow/cpu_closed.ts";
1010 import { html, type Html } from "../html.ts";
1111 import { icon, row, time } from "../ui.ts";
12 import { shown } from "./flow-waiting.ts";
1213
1314 const count = (n: number, one: string, many: string): string => `${String(n)} ${n === 1 ? one : many}`;
1415
@@ -21,14 +22,15 @@ export function cpuStopsSays(stopped: number, closed: number): string {
2122 return parts.length === 0 ? "" : `${parts.join("; ")}.`;
2223 }
2324
24 export function cpuStopsSection(stopped: number, closed: readonly CpuClosedPull[]): Html {
25 /** The CPU stops and the pulls closed after one; `all` shows that list whole (`?all=`). */
26 export function cpuStopsSection(stopped: number, closed: readonly CpuClosedPull[], all: string | null = null): Html {
2527 if (stopped === 0 && closed.length === 0) return html``;
2628 return html`<div class="mb" id="flow-cpu-stops"><p>${cpuStopsSays(stopped, closed.length)}</p>
27 ${closed.length === 0 ? "" : html`<ul class="list" id="flow-cpu-closed">${closed.map((p) => row({
29 ${closed.length === 0 ? "" : html`<ul class="list" id="flow-cpu-closed">${shown(closed, (p) => row({
2830 href: `/${p.repo}/pulls/${String(p.number)}`,
2931 lead: icon("pull"),
3032 title: `${p.repo} #${String(p.number)}`,
3133 meta: html`closed ${time(p.closedAt)}`,
3234 state: "closed",
33 }))}</ul>`}</div>`;
35 }), "flow-cpu-closed", all)}</ul>`}</div>`;
3436 }
src/web/pages/flow-panel.ts +4 −1
@@ -59,6 +59,8 @@ import { badge, card, meter } from "../ui.ts";
5959 import { count, figure, figures, fold } from "../figure.ts";
6060 import { panelFlow, type BoardsPicture, type StageFlow } from "../../flow/pages_read.ts";
6161 import { sparkline as homeSpark } from "../studio/kpi_row.ts";
62 import { readSlots } from "../../flow/slots.ts";
63 import { slotsBlock } from "../flow_slots.ts";
6264
6365 /** What the panel draws that is read off the thread: the figures, what each stage let out, what reviewers repeated and why ready issues wait. */
6466 export type PanelPicture = Pick<BoardsPicture, "fig" | "flow" | "repeats" | "held">;
@@ -193,7 +195,8 @@ export function flowPanel(app: App, reader: Reader, url: URL, base: string, slot
193195 </section>
194196 ${strip}
195197 <section class="bd-block" id="pipeline" aria-labelledby="pipeline-h">
196 <header class="bd-head"><h2 id="pipeline-h">Pipeline</h2><p class="bd-sub">Each row is a step a change takes: what waits there, what is being worked on, and what the step let out.</p><a href="/pipeline">The four steps</a><a href="/settings/capacity">Capacity</a></header>
198 <header class="bd-head"><h2 id="pipeline-h">Pipeline</h2><p class="bd-sub">Each row is a step a change takes: what waits there, what is being worked on, and what the step let out.</p><a href="/pipeline">The four steps</a></header>
outdated

Principle 1 / one way: this header's Capacity link is now a second route to /settings/capacity next to the Change capacity button added in the slots block below. Remove the link.

199 ${slotsBlock(readSlots(app, new Date(now)), now, owner)}
197200 <div class="card">
198201 <table class="table pl" aria-label="Pipeline stages">
199202 <thead>
src/web/pages/flow-waiting.ts +37 −16
@@ -13,6 +13,7 @@ import { readWaitingRows, type Waiting } from "../../flow/waiting_rows.ts";
1313 export type { Waiting } from "../../flow/waiting_rows.ts";
1414 import { html, type Html } from "../html.ts";
1515 import { btn, row } from "../ui.ts";
16 import { fold } from "../figure.ts";
1617 import { span } from "../../flow/pipeline.ts";
1718
1819
@@ -40,12 +41,32 @@ export function forgetUnproposed(): void {
4041
4142 const plural = (n: number, one: string): string => `${String(n)} ${n === 1 ? one : `${one}s`}`;
4243
43 /** One list of the section: its name, one sentence of what it is, and its rows, each a sentence that wraps. */
44 const waitingList = (id: string, name: string, says: string, rows: readonly Html[]): Html =>
45 html`<section class="bd-block">
46 <header class="bd-head"><h2>${name}</h2><p class="bd-sub">${says}</p></header>
47 <ul class="list" id="${id}">${[...rows]}</ul>
48 </section>`;
44 /**
45 * How many rows a list on /flow shows before it says how many more: the page answers one question
46 * at the top, and a list is there to open, not to scroll through (4,332 unproposed branches once
47 * made it 3.3 MB).
48 */

The cap is the finding: and N more is a bare <li> with no way to open the rest. Make it a link to the full list (or page it), so a cap on the first view does not make the data unreachable.

49 export const LIST_SHOWN = 10;
50
51 /**
52 * The first rows of the list `id`, drawn, and a last line for the rest, "and 4,322 more", that
53 * links to /flow with this list whole (`?all=<id>`); when `all` names it, every row.
54 */
55 export function shown<T>(items: readonly T[], draw: (item: T) => Html, id: string, all: string | null): Html[] {
56 if (all === id) return items.map(draw);
57 const rest = items.length - LIST_SHOWN;
58 return [
59 ...items.slice(0, LIST_SHOWN).map(draw),
60 ...(rest > 0 ? [html`<li class="muted small" data-more="${String(rest)}"><a href="/flow?all=${id}#${id}">and ${rest.toLocaleString("en")} more</a></li>`] : []),
61 ];
62 }
63
64 /**
65 * One list of the section, folded: its name, how many and what it is, and its first rows; open and
66 * whole when `all` names it.
67 */
68 const waitingList = <T>(id: string, name: string, says: string, items: readonly T[], draw: (item: T) => Html, all: string | null): Html =>
69 fold(name, `${items.length.toLocaleString("en")}: ${says}`, html`<ul class="list" id="${id}">${shown(items, draw, id, all)}</ul>`, { open: all === id });
4970
5071 /**
5172 * The one action of a stalled row: a form button, a POST on this origin that the route receipts,
@@ -59,43 +80,43 @@ const noWrite = html`<span class="valve-body muted small">You cannot write to th
5980
6081 /**
6182 * The section; empty html when all three are quiet. `mayWrite` says whether the viewer can act on a
62 * repository.
83 * repository; `all` names the list to show whole (`?all=`).
6384 */
64 export function waitingSection(w: Waiting, mayWrite: (repo: string) => boolean = () => true): Html {
85 export function waitingSection(w: Waiting, mayWrite: (repo: string) => boolean = () => true, all: string | null = null): Html {
6586 const parts: Html[] = [];
6687 if (w.approved.length > 0) {
67 parts.push(waitingList("flow-approved", "Approved, waiting on the merge queue", "Reviewed and approved; the queue has not landed them yet.", w.approved.map((a) => row({
88 parts.push(waitingList("flow-approved", "Approved, waiting on the merge queue", "Reviewed and approved; the queue has not landed them yet.", w.approved, (a) => row({
6889 title: html`<span class="valve-name"><a href="/${a.repo}/pulls/${String(a.oldest)}">${a.repo}</a>
6990 <span class="muted small">${plural(a.waiting, "approved pull")} waiting; the oldest, #${String(a.oldest)}, for ${span(a.oldestHours * 3_600_000)}</span></span>`,
7091 meta: mayWrite(a.repo) ? act(`/${a.repo}/pulls/${String(a.oldest)}/checks`, `Re-run check #${String(a.oldest)}`, `Re-run check ${a.repo} #${String(a.oldest)}`, { next: "/flow" }) : noWrite,
71 }))));
92 }), all));
7293 }
7394 const stalled = w.stalled ?? [];
7495 if (stalled.length > 0) {
75 parts.push(waitingList("flow-stalled", "Green, not landed", "Green for more than six hours.", stalled.map((s) => row({
96 parts.push(waitingList("flow-stalled", "Green, not landed", "Green for more than six hours.", stalled, (s) => row({
7697 href: `/${s.repo}/pulls/${String(s.number)}`,
7798 title: `${s.repo} #${String(s.number)}`,
7899 nav: true,
79100 data: { "waits-for": s.cause },
80101 facts: [{ label: "Waits for", value: s.says }, { label: "To unblock", value: s.action }],
81 }))));
102 }), all));
82103 }
83104 if (w.stale.length > 0) {
84 parts.push(waitingList("flow-stale", "Stale crew pulls", "Open with no push for days; a person closes one, and its work can fold back into its issue.", w.stale.map((s) => row({
105 parts.push(waitingList("flow-stale", "Stale crew pulls", "Open with no push for days; a person closes one, and its work can fold back into its issue.", w.stale, (s) => row({
85106 title: html`<span class="valve-name"><a href="/${s.repo}/pulls/${String(s.number)}">${s.repo} #${String(s.number)}</a>
86107 <span class="muted small">${plural(s.days, "day")} without a push; a person closes it</span></span>`,
87108 meta: html`${s.note === null
88109 ? html`<span class="valve-body muted small">No issue to fold back into.</span>`
89110 : html`<span class="valve-body small"><a href="/${s.repo}/issues/${String(s.issueNumber)}">Fold back into #${String(s.issueNumber)}</a>: <code>${s.note}</code></span>`}
90111 ${mayWrite(s.repo) ? act(`/${s.repo}/pulls/${String(s.number)}/state`, "Close", `Close ${s.repo} #${String(s.number)}`, { state: "closed", back: "/flow" }) : noWrite}`,
91 }))));
112 }), all));
92113 }
93114 if (w.unproposed.fires) {
94 parts.push(waitingList("flow-unproposed", "Work a crew fork never proposed", "Branches with commits and no pull: work that was done and never offered.", w.unproposed.branches.map((b) => row({
115 parts.push(waitingList("flow-unproposed", "Work a crew fork never proposed", "Branches with commits and no pull: work that was done and never offered.", w.unproposed.branches, (b) => row({
95116 title: html`<span class="valve-name"><a class="mono" href="/${b.repo}/tree/${encodeURIComponent(b.branch)}">${b.repo}: ${b.branch}</a>
96117 <span class="muted small">${span(b.ageMs)} old, no pull</span></span>`,
97118 meta: mayWrite(b.repo) ? btn("Open a pull", { href: `/${b.repo}/pulls/new?head=${encodeURIComponent(b.branch)}`, size: "sm", label: `Open a pull from ${b.repo}: ${b.branch}` }) : noWrite,
98 }))));
119 }), all));
99120 }
100121 return parts.length === 0 ? html`` : html`<div class="bd-live" id="flow-waiting">${parts}</div>`;
101122 }
src/web/pages/flow.ts +40 −16
@@ -1,5 +1,12 @@
11 /**
2 * /flow: the week's budget as pipes a forge admin can turn. The first paint
2 * /flow answers one question first (#16442's owner: "the data is just spammed and hard to
3 * consume"): what holds the work back. The bottleneck in one sentence, the stages that have
4 * anything in them as calm rows (what waits, what limits it, the oldest) when more than one has
5 * (one alone is what the sentence already says), and the slots against what fills them with Change
6 * capacity one step away; everything else is folded under one line that says how it stands, and no
7 * list shows more than ten rows.
8 *
9 * Below that, the week's budget as pipes a forge admin can turn. The first paint
310 * is the whole page (`flow_pipes.ts` draws it, a form per valve turns it);
411 * the little script only submits a drag. A turn is `POST /flow/valve`, the
512 * suggestion beside a valve is `POST /flow/suggestion`, and both end back
@@ -14,7 +21,7 @@ import type { Ctx } from "../../http/context.ts";
1421 import type { Pipes, ValveRow } from "../../flow/pipes.ts";
1522 import { flowPicture, isFailed, LONG_WAIT_MS, waitAnswer } from "../../flow/pages.ts";
1623 import { usd } from "../../core/money.ts";
17 import { count, figure, figures, reading, readingFailed, readingJs } from "../figure.ts";
24 import { count, figure, figures, fold, reading, readingFailed, readingJs } from "../figure.ts";
1825 import { levelWords } from "../../flow/valve.ts";
1926 import { notePhase, takeSessionTime, timePhaseAsync } from "../../core/route_timing.ts";
2027 import { notFoundPage, signInFirst } from "../chrome.ts";
@@ -29,9 +36,12 @@ import { readableStalled } from "../../flow/waits_for.ts";
2936 import { canWrite, getRepo } from "../../core/repos.ts";
3037 import { estimatesSection } from "./flow-estimates.ts";
3138 import { clogSection } from "./flow-clog.ts";
32 import { cpuStopsSection } from "./flow-cpu.ts";
39 import { cpuStopsSays, cpuStopsSection } from "./flow-cpu.ts";
3340 import { plannerHeld, type Held } from "../../flow/planner_held.ts";
3441 import { cpuStops } from "../../flow/cpu_stops.ts";
42 import { bottleneck, readPipeline, stageSays, STAGE_LABEL, verdict } from "../../flow/pipeline.ts";
43 import { readSlots } from "../../flow/slots.ts";
44 import { slotsBlock } from "../flow_slots.ts";
3545
3646 const plural = (n: number, one: string, many = `${one}s`): string => `${String(n)} ${n === 1 ? one : many}`;
3747
@@ -159,27 +169,41 @@ export async function flowPage(ctx: Ctx): Promise<Response> {
159169 figure("A pull costs", p.shipped === 0 ? "—" : usd(p.usd / p.shipped), p.shipped === 0 ? "none shipped yet" : "the spend over the pulls", "/settings/crew"),
160170 figure("Valves open", `${String(open)} of ${String(p.valves.length)}`, "drag one below to give a repository a smaller share of the week; nothing but you turns one", "#valves", null, open === p.valves.length ? null : "attn"),
161171 ], "This week");
172 const now = Date.now();
173 const stages = readPipeline(ctx.app.db, new Date(now));
174 const worst = bottleneck(stages);
175 const busy = stages.filter((s) => s.waiting > 0 || (s.key !== "live" && s.active > 0));
176 const stopped = cpuStops(ctx.app.db).stopped;
177 // A list shown whole (`?all=<id>`, from its "and N more"): every row, its fold open.
178 const all = ctx.url.searchParams.get("all");
179 const clogged = picture.clog.says !== "" || picture.clog.shared.length > 0 || picture.clog.pairs.length > 0;
162180 const body = html`<div class="hf bd">
163181 <header class="hf-head">
164182 <div class="hf-title"><h1>Flow</h1></div>
165183 <nav class="bd-nav" aria-label="Elsewhere">${btn("Boards", { href: "/boards", variant: "ghost" })}${btn("Explore the data", { href: "/boards/data", variant: "ghost" })}</nav>
166184 </header>
167 <section class="bd-now" aria-label="How the week stands">
168 <p class="bd-lead" id="flow-week"><strong>${weekSays(p)}</strong></p>
185 <section class="bd-now" aria-label="What holds the work back">
186 <p class="bd-lead" id="flow-answer" data-stage="${worst?.key ?? ""}"><strong>${verdict(stages, now)}</strong></p>
169187 ${heldRows(plannerHeld(ctx.app.db))}
170188 ${backupRow(alarmBackup(ctx.app.config.dataDir, new Date()))}
171 ${clogSection(picture.clog)}
172 ${cpuStopsSection(cpuStops(ctx.app.db).stopped, picture.cpuClosed)}
189 ${busy.length < 2
190 ? null
191 : html`<dl class="fl-stages" id="flow-stages">${busy.map((s) => html`<div class="fl-stage" data-stage="${s.key}" ${s === worst ? html`data-bottleneck` : null}><dt>${STAGE_LABEL[s.key]}</dt><dd>${stageSays(s, now)}</dd></div>`)}</dl>`}
192 ${slotsBlock(readSlots(ctx.app, new Date(now)), now, true)}
173193 </section>
174 ${p.valves.length === 0 ? null : strip}
175 ${waitingSection({ approved: picture.approved, stale: picture.stale, stalled: readableStalled(ctx.app.db, picture.stalled ?? [], user), unproposed: picture.unproposed ?? { fires: false, says: "", branches: [] } }, (name) => mayWriteRepo(ctx, name))}
176 ${p.valves.length === 0
177 ? null
178 : html`<section class="pipes-block" aria-label="Where the week's money went">${pipesSvg(p)}</section>
179 <section class="bd-block" id="valves" aria-labelledby="valves-h">
180 <header class="bd-head"><h2 id="valves-h">Valves</h2></header>
181 <ul class="list">${p.valves.map((v) => valveRow(v, p.usd))}</ul>
182 </section>`}
194 <div class="folds" id="flow-folds">
195 ${p.valves.length === 0
196 ? html`<p class="muted" id="flow-week">${weekSays(p)}</p>`
197 : fold("The week's money", weekSays(p), html`${strip}
198 <section class="pipes-block" aria-label="Where the week's money went">${pipesSvg(p)}</section>
199 <section class="bd-block" id="valves" aria-labelledby="valves-h">
200 <header class="bd-head"><h2 id="valves-h">Valves</h2></header>
201 <ul class="list">${p.valves.map((v) => valveRow(v, p.usd))}</ul>
202 </section>`, { id: "flow-week", open: p.valves.length > 0 && open < p.valves.length })}
203 ${clogged ? fold("Clogged", picture.clog.says === "" ? `${String(picture.clog.shared.length + picture.clog.pairs.length)} to look at` : picture.clog.says, clogSection(picture.clog, all), { open: all === "flow-shared-red" || all === "flow-conflict-pairs" }) : null}
204 ${stopped === 0 && picture.cpuClosed.length === 0 ? null : fold("Stopped for CPU", cpuStopsSays(stopped, picture.cpuClosed.length), cpuStopsSection(stopped, picture.cpuClosed, all), { open: all === "flow-cpu-closed" })}
205 ${waitingSection({ approved: picture.approved, stale: picture.stale, stalled: readableStalled(ctx.app.db, picture.stalled ?? [], user), unproposed: picture.unproposed ?? { fires: false, says: "", branches: [] } }, (name) => mayWriteRepo(ctx, name), all)}
206 </div>
183207 ${handoverSection(picture.handover)}
184208 ${estimatesSection(ctx.app.db, ctx.auth.user)}
185209 </div>`;
src/web/palette_rows.ts +7 −1
@@ -51,7 +51,13 @@ export function settingsRows(user: User | undefined): PaletteRow[] {
5151 { t: "Password", h: "/settings/password", c: "Settings" },
5252 { t: "Passkeys", h: "/settings/passkeys", c: "Settings" },
5353 // The crew's model credentials are the admin's (`/settings/subscriptions` answers anyone else 403).
54 ...(user.isAdmin ? [{ t: "Subscriptions", h: "/settings/subscriptions", c: "Settings" }] : []),
54 ...(user.isAdmin
55 ? [
56 { t: "Subscriptions", h: "/settings/subscriptions", c: "Settings" },
57 // How many checks and crew runs go at once: the slots /boards draws the line at.
58 { t: "Capacity", h: "/settings/capacity", c: "Settings" },
59 ]
60 : []),
5561 ];
5662 }
5763
src/web/studio/cards.ts +3 −5
@@ -12,7 +12,7 @@ import { CARD_PALETTE } from "../../http/mcp/card_palette.ts";
1212 import { timeAgo } from "../ui.ts";
1313 import { HIDDEN_FORK_WORD } from "../../actions/follow_words.ts";
1414 import { VERB_WORDS } from "../../actions/asks_words.ts";
15 import { span, STAGE_LABEL, verdict, type PipelineKey, type PipelineStage } from "../../flow/pipeline.ts";
15 import { span, stageSays, STAGE_LABEL, verdict, type PipelineKey, type PipelineStage } from "../../flow/pipeline.ts";
1616
1717 export type CardKind = "app" | "run" | "asks" | "wave" | "map" | "feed" | "pull" | "pulls" | "runs" | "asked" | "explore" | "issue" | "flow" | "scorecard" | "crew" | "board" | "forks" | "milestones" | "release" | "releases" | "search" | "issues" | "forges" | "held" | "drill" | "reports" | "usage" | "health" | "capacity" | "forge";
1818
@@ -280,10 +280,8 @@ export function cardFor(
280280 oldestWaiting: typeof s["oldestWaiting"] === "string" ? s["oldestWaiting"] : null,
281281 capacity: typeof s["capacity"] === "string" ? s["capacity"] : null,
282282 }));
283 for (const s of typed) {
284 const wait = s.oldestWaiting === null || Number.isNaN(Date.parse(s.oldestWaiting)) ? "" : ` · oldest ${span(now - Date.parse(s.oldestWaiting))}`;
285 rows.push({ label: STAGE_LABEL[s.key], value: `${s.waiting} waiting · ${s.active} active${wait}` });
286 }
283 // The same line /flow gives each stage (`stageSays`).
284 for (const s of typed) rows.push({ label: STAGE_LABEL[s.key], value: stageSays(s, now) });
287285 return { kind, title: CARD_TITLE[kind], status: verdict(typed, now), rows, actions };
288286 }
289287 if (kind === "board") {
src/web/style/components.ts +22 −1
@@ -1168,12 +1168,33 @@ a[data-palette] { display: none; }
11681168 .pl-cap { color: var(--muted-fg); }
11691169 .pl-trend { width: 88px; color: var(--muted-fg); }
11701170 .pl-spark { display: block; margin-left: auto; }
1171 /* /flow's stages that have anything in them: one calm line each, the bottleneck marked. */
1172 .fl-stages { display: grid; gap: 0; margin: 0; }
1173 .fl-stage { display: grid; grid-template-columns: minmax(0, 8rem) minmax(0, 1fr); gap: 12px; padding: 8px 0; border-top: 1px solid var(--border); }
1174 .fl-stage:first-child { border-top: 0; }
1175 .fl-stage > dt { font-weight: 600; }
1176 .fl-stage > dd { margin: 0; color: var(--muted-fg); font-variant-numeric: tabular-nums; }
1177 .fl-stage[data-bottleneck] > dt, .fl-stage[data-bottleneck] > dd { color: var(--danger); }
1178 /* The slots against what fills them (flow_slots.ts): the ceiling dashed across 24 hours. */
1179 .sl-block { display: grid; gap: 12px; margin: 0 0 12px; }
1180 .sl { display: grid; gap: 4px; }
1181 .sl-head { margin: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 8px; }
1182 .sl-used { font-variant-numeric: tabular-nums; }
1183 .sl[data-full] .sl-used { color: var(--danger); font-weight: 600; }
1184 .sl-say { color: var(--muted-fg); }
1185 .sl-chart { display: block; width: 100%; height: 32px; color: var(--muted-fg); }
1186 .sl-busy { fill: currentColor; fill-opacity: .45; }
1187 .sl-full { fill: var(--danger); }
1188 .sl-wait { fill: currentColor; fill-opacity: .18; }
1189 .sl-line { stroke: var(--fg); stroke-width: 1; stroke-dasharray: 4 3; vector-effect: non-scaling-stroke; }
1190 .sl-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0; }
1191 .sl-foot .btn { min-height: 44px; }
11711192 .pl tr[data-bottleneck] .pl-trend { color: var(--danger); }
11721193 .folds { border-bottom: 1px solid var(--border); }
11731194 .fold { border-top: 1px solid var(--border); }
11741195 .fold > summary { flex-wrap: wrap; align-items: baseline; gap: 0 12px; padding: 12px 0; }
11751196 .fold-title { margin: 0; font-size: 14px; font-weight: 600; color: var(--fg); }
1176 .fold-state { flex: 1 1 200px; font-size: 13px; font-weight: 400; color: var(--muted-fg); }
1197 .fold-state { flex: 1 1 200px; min-width: 0; overflow-wrap: anywhere; font-size: 13px; font-weight: 400; color: var(--muted-fg); }
11771198 @media (hover: hover) and (pointer: fine) { .fold > summary:hover .fold-title { color: var(--accent); } }
11781199 .fold-body { display: flex; flex-direction: column; gap: 8px; padding: 0 0 16px 16px; font-size: 14px; }
11791200 .fold-body > p { margin: 0; }
test/flow-answer.test.ts added +132
@@ -0,0 +1,132 @@
1 /**
2 * /flow answers one question first: the bottleneck in a sentence, the stages that have anything in
3 * them as calm lines (the MCP flow card says each the same way), and the slots with Change
4 * capacity one step away; everything else folds under one line and no list shows more than ten
5 * rows, so the page stays under its byte ceiling (production's was 3.3 MB, one list of 4,332
6 * branches).
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { createRun } from "../src/core/runs.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { stageSays } from "../src/flow/pipeline.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { html } from "../src/web/html.ts";
20 import { LIST_SHOWN, shown, waitingSection } from "../src/web/pages/flow-waiting.ts";
21 import { cardFor } from "../src/web/studio/cards.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 /**
27 * The most /flow may answer, in bytes of HTML: every list at its ten rows and two dozen valves sit
28 * well under it. Production's was 3.3 MB on 2026-11-30, one list of 4,332 branches; held here so it
29 * cannot grow back.
30 */
31 const FLOW_PAGE_BYTES = 200_000;
32
33 test("a list shows its first ten rows and links the rest: ?all= shows that list whole", () => {
34 const many = Array.from({ length: 4_332 }, (_, i) => i);
35 const li = (i: number) => html`<li>${String(i)}</li>`;
36 const rows = shown(many, li, "flow-unproposed", null);
37 expect(rows).toHaveLength(LIST_SHOWN + 1);
38 expect(rows.at(-1)!.text).toContain('<a href="/flow?all=flow-unproposed#flow-unproposed">and 4,322 more</a>');
39 expect(shown([1, 2], li, "flow-unproposed", null)).toHaveLength(2);
40 expect(shown(many, li, "flow-unproposed", "flow-unproposed")).toHaveLength(4_332);
41 // Another list's ?all= leaves this one at ten.
42 expect(shown(many, li, "flow-unproposed", "flow-approved")).toHaveLength(LIST_SHOWN + 1);
43 });
44
45 test("4,332 unproposed branches fold to one line and ten rows: kilobytes, not megabytes", () => {
46 const branches = Array.from({ length: 4_332 }, (_, i) => ({ repo: "smith/arm", owner: "smith", branch: `change-${i}`, oid: "0".repeat(40), ageMs: 86_400_000 }));
47 const out = waitingSection({ approved: [], stale: [], stalled: [], unproposed: { fires: true, says: "", branches } }).text;
48 expect(out).toContain("4,332: Branches with commits and no pull");
49 expect(out).toContain("and 4,322 more");
50 expect(out.match(/Open a pull from/g)).toHaveLength(LIST_SHOWN);
51 expect(out.length).toBeLessThan(20_000);
52 expect(out).toContain('<details class="disclosure fold"');
53 const whole = waitingSection({ approved: [], stale: [], stalled: [], unproposed: { fires: true, says: "", branches } }, () => true, "flow-unproposed").text;
54 expect(whole.match(/Open a pull from/g)).toHaveLength(4_332);
55 expect(whole).not.toContain("more</a>");
56 expect(whole).toMatch(/<details class="disclosure fold"[^>]*\sopen/);
57 });
58
59 test("a stage is one line, the same on /flow and on the MCP flow card", () => {
60 const now = Date.parse("2026-11-30T12:00:00Z");
61 const s = {
62 key: "check-queue" as const,
63 waiting: 17,
64 active: 0,
65 oldestWaiting: new Date(now - 44 * 60_000).toISOString(),
66 capacity: "checks at once 4",
67 };
68 expect(stageSays(s, now)).toBe("17 waiting · 0 active · checks at once 4 · oldest 44m");
69 const card = cardFor("flow", { stages: [{ ...s, oldestWaiting: new Date(Date.now() - 44 * 60_000).toISOString() }] })!;
70 expect(card.rows[0]!.value).toBe("17 waiting · 0 active · checks at once 4 · oldest 44m");
71 expect(card.status).toContain("Check queue is the bottleneck");
72 });
73
74 let dir: string;
75 let app: App;
76 let servers: Servers;
77 let admin: User;
78
79 beforeAll(async () => {
80 dir = await mkdtemp(join(tmpdir(), "forge-flow-answer-"));
81 app = createApp({ dataDir: dir, port: 0 });
82 servers = await serve(app);
83 const u = await createUser(app.db, {
84 origin: "seed",
85 trusted: true,
86 username: "olive",
87 email: "[email protected]",
88 password: "a-good-passphrase",
89 adminIfFirst: true,
90 });
91 if (!u.ok) throw new Error(u.error);
92 admin = u.value;
93 const repo = await createRepo(app, admin, { name: "shop", visibility: "public" });
94 if (!repo.ok) throw new Error("repo");
95 for (let i = 0; i < 3; i++) createRun(app.db, { repoId: repo.value.id, kind: "check" });
96 }, 30_000);
97 afterAll(async () => {
98 servers.stop();
99 app.close();
100 await rm(dir, { recursive: true, force: true });
101 });
102
103 test("/flow leads with what holds the work back, the busy stages and the slots, then folds the rest, under its byte ceiling", async () => {
104 const headers = { cookie: `forge_session=${createSession(app.db, admin.id).token}` };
105 // The picture is a worker's: wait for it once, then the page draws from it.
106 await (await fetch(`${servers.url}/flow?wait=1`, { headers })).arrayBuffer();
107 const page = await (await fetch(`${servers.url}/flow`, { headers })).text();
108 const answer = page.indexOf('id="flow-answer"');
109 expect(answer).toBeGreaterThan(-1);
110 expect(page).toContain("Check queue is the bottleneck");
111 // One busy stage is what the sentence says: no rows repeat it.
112 expect(page).not.toContain('id="flow-stages"');
113 expect(page.indexOf('id="slots"')).toBeGreaterThan(answer);
114 expect(page).toContain('href="/settings/capacity">Change capacity</a>');
115 expect(page.indexOf('id="flow-folds"')).toBeGreaterThan(page.indexOf('id="slots"'));
116 // No valve yet: the week is one sentence inside the folds.
117 expect(page.indexOf('id="flow-week"')).toBeGreaterThan(page.indexOf('id="flow-folds"'));
118 expect(page.length).toBeLessThan(FLOW_PAGE_BYTES);
119 });
120
121 test("with two stages busy, each is a calm row, the bottleneck marked and empty stages left out", async () => {
122 const headers = { cookie: `forge_session=${createSession(app.db, admin.id).token}` };
123 const repoId = app.db.query<{ id: string }, []>("SELECT id FROM repo LIMIT 1").get()!.id;
124 createRun(app.db, { repoId, kind: "agent" });
125 await (await fetch(`${servers.url}/flow?wait=1`, { headers })).arrayBuffer();
126 const page = await (await fetch(`${servers.url}/flow`, { headers })).text();
127 expect(page).toMatch(
128 /<div class="fl-stage" data-stage="check-queue"\s+data-bottleneck><dt>Check queue<\/dt><dd>3 waiting · 0 active · checks at once \d+ · oldest/,
129 );
130 expect(page.match(/class="fl-stage"/g)?.length).toBeGreaterThanOrEqual(2);
131 expect(page).not.toContain('data-stage="approved"');
132 });
test/flow-language.test.ts +3 −1
@@ -48,7 +48,9 @@ afterAll(async () => {
4848 test("with no valves: one sentence says so, no picture of nothing, no card", async () => {
4949 const text = await (await get(await login("alice"))).text();
5050 expect(text).not.toContain('class="card');
51 expect(text).toContain('<p class="bd-lead" id="flow-week"><strong>Nothing was spent, queued or shipped in the last 7 days, so there is no valve to turn yet.</strong></p>');
51 // The week folds under its one line; the page's lead is what holds the work back.
52 expect(text).toContain("Nothing was spent, queued or shipped in the last 7 days, so there is no valve to turn yet.");
53 expect(text).toContain('id="flow-answer"');
5254 expect(text).not.toContain('class="pipes"');
5355 expect(text).not.toContain(">Valves</h2>");
5456 });
test/flow-slots.test.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * The slots against what fills them (`flow/slots.ts`, `web/flow_slots.ts`): checks and crew
3 * runs as "busy of slots", what waits with its oldest and median wait, the 24 hours with the live
4 * setting dashed across them, full in the danger colour at saturation, the crew's pace when it
5 * allows fewer; on /boards above the pipeline with Change capacity one step away; and Capacity
6 * findable from Settings and the palette.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { setCapacity } from "../src/core/capacity.ts";
15 import { createRun } from "../src/core/runs.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { isFull, readSlots, slotLine, SLOT_POINTS, type SlotLine } from "../src/flow/slots.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { settingsRows } from "../src/web/palette_rows.ts";
21 import { statements } from "./helpers/statements.ts";
22 import { slotsBlock } from "../src/web/flow_slots.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { promote } from "./helpers/members.ts";
25
26 quietLogs();
27
28 const NOW = Date.parse("2026-11-30T12:00:00.000Z");
29 const ago = (min: number): string => new Date(NOW - min * 60_000).toISOString();
30 const run = (created: number, started: number | null, finished: number | null) => ({
31 kind: "check",
32 created_at: ago(created),
33 started_at: started === null ? null : ago(started),
34 finished_at: finished === null ? null : ago(finished),
35 state: finished !== null ? "ok" : started !== null ? "running" : "queued",
36 });
37
38 test("a line counts busy, waiting, the oldest and the median wait of the last hour, and the 24 hours at quarter hours", () => {
39 const l = slotLine(
40 "checks",
41 2,
42 [run(50, 40, null), run(45, 30, null), run(30, null, null), run(10, null, null), run(200, 190, 100)],
43 NOW,
44 );
45 expect(l.points).toHaveLength(SLOT_POINTS);
46 expect([l.busy, l.waiting, l.slots]).toEqual([2, 2, 2]);
47 expect(l.oldestAt).toBe(ago(30));
48 // Started in the last hour: waited 10 and 15 minutes.
49 expect(l.medianWaitMs).toBe(12.5 * 60_000);
50 expect(l.points.at(-1)).toEqual({ running: 2, queued: 2 });
51 // Two hours ago only the old run was running; 3 h 20 m ago it was still waiting to start.
52 expect(l.points[SLOT_POINTS - 1 - 8]).toEqual({ running: 1, queued: 0 });
53 expect(l.points[SLOT_POINTS - 1 - 13]).toEqual({ running: 0, queued: 1 });
54 expect(isFull(l)).toBe(true);
55 expect(isFull({ ...l, waiting: 0 })).toBe(false);
56 expect(isFull({ ...l, busy: 1 })).toBe(false);
57 });
58
59 test("drawn, a full lane reads as full: the danger badge, solid bars at the line, the setting dashed across", () => {
60 const full: SlotLine = {
61 ...slotLine("checks", 4, [], NOW),
62 busy: 4,
63 waiting: 17,
64 oldestAt: ago(44),
65 medianWaitMs: 12 * 60_000,
66 points: Array.from({ length: SLOT_POINTS }, () => ({ running: 4, queued: 3 })),
67 };
68 const calm: SlotLine = {
69 ...slotLine("crew", 6, [], NOW),
70 busy: 1,
71 pace: { allows: 2, why: "espo-corp's 5-hour window is full until 16:20 UTC" },
72 };
73 const out = slotsBlock([full, calm], NOW, true).text.replace(/\s+/g, " ");
74 expect(out).toContain('data-kind="checks" data-full');
75 expect(out).toContain("4 of 4 slots busy");
76 expect(out).toContain(">full<");
77 expect(out).toContain("17 waiting · oldest 44m · median wait 12m (last hour)");
78 expect(out).toContain('class="sl-full"');
79 expect(out).toContain('class="sl-wait"');
80 expect(out).toMatch(/<line class="sl-line"/);
81 expect(out).toContain("1 of 6 slots busy");
82 // Nothing waits on the crew: its line goes straight to the pace.
83 expect(out).toContain('class="sl-say small"><span data-pace="2">');
84 expect(out).not.toContain("nothing waits");
85 expect(out).toContain("pace allows 2: espo-corp&#39;s 5-hour window is full until 16:20 UTC");
86 expect(out).not.toContain('data-kind="crew" data-full');
87 expect(out).toContain('href="/settings/capacity">Change capacity</a>');
88 expect(slotsBlock([full], NOW, false).text).not.toContain("Change capacity");
89 });
90
91 let dir: string;
92 let app: App;
93 let servers: Servers;
94 let owner: User;
95 let other: User;
96
97 beforeAll(async () => {
98 dir = await mkdtemp(join(tmpdir(), "forge-slots-"));
99 app = createApp({ dataDir: dir, port: 0, forgeRepo: "olive/forge" });
100 servers = await serve(app);
101 const mk = async (username: string, first: boolean) => {
102 const u = await createUser(app.db, {
103 origin: "seed",
104 trusted: true,
105 username,
106 email: `${username}@forge.local`,
107 password: "a-good-passphrase",
108 adminIfFirst: first,
109 });
110 if (!u.ok) throw new Error(u.error);
111 promote(app.db, u.value);
112 return u.value;
113 };
114 owner = await mk("olive", true);
115 other = await mk("pablo", false);
116 const repo = await createRepo(app, owner, { name: "forge", visibility: "public" });
117 if (!repo.ok) throw new Error("repo");
118 for (let i = 0; i < 3; i++) createRun(app.db, { repoId: repo.value.id, kind: "check" });
119 }, 30_000);
120 afterAll(async () => {
121 servers.stop();
122 app.close();
123 await rm(dir, { recursive: true, force: true });
124 });
125
126 test("the line is the live setting: raising checks.concurrency moves it at once", () => {
127 setCapacity(app.db, "checks.concurrency", "4", owner.id);
128 expect(readSlots(app)[0]).toMatchObject({ kind: "checks", slots: 4, waiting: 3 });
129 setCapacity(app.db, "checks.concurrency", "8", owner.id);
130 expect(readSlots(app)[0]!.slots).toBe(8);
131 expect(readSlots(app).map((l) => l.kind)).toEqual(["checks", "crew"]);
132 });
133
134 test("read warm, the slots cost two statements: the settings, and the runs of both kinds; the pace is kept a minute", async () => {
135 readSlots(app);
136 expect(await statements(app.db, () => void readSlots(app))).toBe(2);
137 });
138
139 test("/boards draws the slots above the pipeline, with Change capacity one step away, and a palette row for Capacity", async () => {
140 const get = (path: string, u: User) =>
141 fetch(`${servers.url}${path}`, { headers: { cookie: `forge_session=${createSession(app.db, u.id).token}` } }).then((r) => r.text());
142 const boards = await get("/boards", owner);
143 expect(boards).toContain('id="slots"');
144 expect(boards.indexOf('id="slots"')).toBeLessThan(boards.indexOf('aria-label="Pipeline stages"'));
145 expect(boards).toContain("0 of 8 slots busy");
146 expect(boards).toContain('href="/settings/capacity">Change capacity</a>');
147 const capacity = await get("/settings/capacity", owner);
148 expect(capacity).toMatch(
149 /<a[^>]*href="\/settings\/capacity"[^>]*aria-current="page"|aria-current="page"[^>]*href="\/settings\/capacity"/,
150 );
151 expect(settingsRows(owner).map((r) => [r.t, r.h])).toContainEqual(["Capacity", "/settings/capacity"]);
152 expect(settingsRows(other).map((r) => r.h)).not.toContain("/settings/capacity");
153 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs