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

JSON for the home lanes, figures and slot graphs, with ETags #17923

opened this in answer to

Merged 24h 59m ago, live in production

scout/forge:scout/17919-json-for-the-home-lanes-figures-and-slot → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/17919-json-for-the-home-lanes-figures-and-slot was merged into main as e16b19a.

Review

Sign in to review this change.
21 files changed +782 −177
docs/features/home-json.md added +31
@@ -0,0 +1,31 @@
1 ---
2 topic: Agents: MCP, git, or the terminal
3 row: The home's lanes, figures and slots as JSON
4 ---
5 # The home's lanes, figures and slots as JSON (#17919)
6
7 A client reads the home without parsing its page. Three read-only routes, drawn by the page's own
8 readers and held to the page's audience (`src/http/home_json.ts`, shapes in `src/flow/home_json.ts`):
9
10 - `GET /api/v1/home/lanes[?s=<lane>]`: for the caller, each lane's `key`, `tone`, `count`, `health`
11 sentence, `now` and `typical` times (ms), and its `tiles` `{key, state, kind, repo, number, issue,
12 run, title, hint, since}`. `s` names one lane; another word is a 422 naming `s`.
13 - `GET /api/v1/home/strip`: the figures (`label`, `value`, `note`, `href`, `tone`) with shipped's
14 `series`, landed per hour, oldest first. A forge admin's only: an everyday account is refused 403,
15 a client forge's owner gets 404, as the page draws no strip for them.
16 - `GET /api/v1/home/slots`: per kind (`checks`, `crew`) the `slots`, `busy`, `waiting`, median run and
17 wait, the estimated wait, the `bucketMs` width and the 96 `buckets` `{busy, waiting, full}`,
18 oldest first. Same audience as the strip.
19
20 Each answer carries `live`: the events that make that region due, the page's `data-live` list, so a
21 client knows which stream events to refetch on. The lanes send an `ETag` header (it changes with the
22 lane picture and each minute) and answer 304 to `If-None-Match` before shaping anything; the strip and
23 slots tag their bytes. Until the forge has read its lanes the answer is 503 `reading` with
24 `Retry-After`. All three are in the forge's OpenAPI document (the one `/api` lists) with their response schemas.
25
26 Terminal: the home's figures list ends, for an admin, with one line a kind of slots ("Checks: 2 of 4
27 slots busy · 1 waiting, oldest 3m", `slotLines` in `src/tui/slot_lines.ts`, read in
28 `src/tui/screens/dashboard.ts`), the words the page's slot line says; the API screen (`/api`) lists the three routes
29 from the OpenAPI document, which carries them.
30
31 Tests: `test/home-json.test.ts`.
src/contract/openapi/routes/getApiV1HomeLanes.ts added +46
@@ -0,0 +1,46 @@
1 import { bool, int, list, obj, orNull, str, words, type Schema } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 /** Milliseconds: a median of two is a half. */
5 const ms: Schema = { type: "number" };
6 const NOW = obj({ medianMs: ms, oldestMs: ms, n: int });
7 const TYPICAL = obj({ medianMs: ms, p90Ms: ms, n: int });
8 const TILE = obj({
9 key: str,
10 state: words("waiting", "active", "done"),
11 kind: words("issue", "pull", "main", "deploy"),
12 repo: str,
13 number: orNull(int),
14 issue: orNull(str),
15 run: orNull(str),
16 title: str,
17 hint: str,
18 since: str,
19 });
20 const LANE = obj({
21 key: words("asked", "building", "checks", "review", "landing", "live"),
22 name: str,
23 tone: words("quiet", "flowing", "waiting", "stuck"),
24 count: int,
25 health: str,
26 now: orNull(NOW),
27 typical: orNull(TYPICAL),
28 slowest: bool,
29 live: list(str),
30 tiles: list(TILE),
31 });
32
33 export const route: Route = {
34 method: "get",
35 path: "/api/v1/home/lanes",
36 summary: "The home's lanes: tone, count, health, times and tiles",
37 detail:
38 "The six lanes the home draws (asked, building, checks, review, landing, live) for the caller, as { lanes }: each { key, name, tone, count, health, now, typical, slowest, live, tiles }; `now` is the median and oldest age of what is in the lane, `typical` the median and p90 of 24 hours (the forge-wide one only for an admin), `live` the events that make the lane due (the page's data-live), and a tile { key, state, kind, repo, number, issue, run, title, hint, since } (run only in the lanes whose tiles are runs). `s` names one lane. The answer carries an ETag that changes with the lane picture (and each minute, the ages being in minutes); a repeat sending it in If-None-Match gets 304 with no body. While the forge is still reading its lanes: 503 `reading` with Retry-After",
39 auth: true,
40 role: "member",
41 query: { s: "string" },
42 alsoStatus: [304],
43 errorStatus: { 422: "s names no lane: the error is `invalid` and `field` is s", 503: "the lanes are not read yet: Retry-After says when to ask again" },
44 refuses: [401],
45 response: obj({ lanes: list(LANE) }),
46 };
src/contract/openapi/routes/getApiV1HomeSlots.ts added +34
@@ -0,0 +1,34 @@
1 import { bool, int, list, obj, orNull, str, words, type Schema } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 /** Milliseconds: a median of two is a half. */
5 const ms: Schema = { type: "number" };
6
7 export const route: Route = {
8 method: "get",
9 path: "/api/v1/home/slots",
10 summary: "Checks and crew slots against what fills them, with 24 hours of buckets",
11 detail:
12 "The home's two slot graphs, for a forge admin (an everyday account is refused 403, a client forge's owner gets 404): { kinds, live }; each kind { kind (checks or crew), slots, busy, waiting, medianRunMs, medianWaitMs, waitEstimateMs, bucketMs, buckets } where `buckets` run oldest first, the last being now, each { busy, waiting, full } (full: busy reached the slots) and `live` the events that make the graphs due. ETag and 304 as for the lanes",
13 auth: true,
14 role: "admin",
15 alsoStatus: [304],
16 errorStatus: { 403: "an everyday account: the forge's figures are its admin's", 404: "a client forge's owner has no forge-wide figures" },
17 refuses: [401],
18 response: obj({
19 kinds: list(
20 obj({
21 kind: words("checks", "crew"),
22 slots: int,
23 busy: int,
24 waiting: int,
25 medianRunMs: orNull(ms),
26 medianWaitMs: orNull(ms),
27 waitEstimateMs: orNull(ms),
28 bucketMs: int,
29 buckets: list(obj({ busy: int, waiting: int, full: bool })),
30 }),
31 ),
32 live: list(str),
33 }),
34 };
src/contract/openapi/routes/getApiV1HomeStrip.ts added +20
@@ -0,0 +1,20 @@
1 import { int, list, obj, str } from "../schema_kit.ts";
2 import type { Route } from "../shared.ts";
3
4 export const route: Route = {
5 method: "get",
6 path: "/api/v1/home/strip",
7 summary: "The home's figures, with their sparkline series",
8 detail:
9 "The row of figures under the home's lanes, for a forge admin (an everyday account is refused 403, and a client forge's owner gets 404, as they have no strip): { figures, seriesStepMs, live }; each figure { label, value, note, href, tone, series? } where `series` is shipped's changes landed per step, oldest first, and `live` the events that make the strip due. ETag and 304 as for the lanes. While the forge is still reading its figures: 503 `reading`",
10 auth: true,
11 role: "admin",
12 alsoStatus: [304],
13 errorStatus: { 403: "an everyday account: the forge's figures are its admin's", 404: "a client forge's owner has no forge-wide figures", 503: "the figures are not read yet: Retry-After says when to ask again" },
14 refuses: [401],
15 response: obj({
16 figures: list(obj({ label: str, value: str, note: str, href: str, tone: { type: ["string", "null"], enum: ["attn", null] }, series: list(int) }, ["series"])),
17 seriesStepMs: int,
18 live: list(str),
19 }),
20 };
src/contract/openapi/routes/index.ts +3
@@ -129,6 +129,9 @@ export { route as getApiV1Front } from "./getApiV1Front.ts";
129129 export { route as getApiV1GamesAgentScript } from "./getApiV1GamesAgentScript.ts";
130130 export { route as getApiV1Health } from "./getApiV1Health.ts";
131131 export { route as getApiV1Here } from "./getApiV1Here.ts";
132 export { route as getApiV1HomeLanes } from "./getApiV1HomeLanes.ts";
133 export { route as getApiV1HomeSlots } from "./getApiV1HomeSlots.ts";
134 export { route as getApiV1HomeStrip } from "./getApiV1HomeStrip.ts";
132135 export { route as getApiV1Keeper } from "./getApiV1Keeper.ts";
133136 export { route as getApiV1KeeperPulse } from "./getApiV1KeeperPulse.ts";
134137 export { route as getApiV1MailKeyScope } from "./getApiV1MailKeyScope.ts";
src/contract/tags.ts +1
@@ -63,6 +63,7 @@ const ALIAS: Readonly<Record<string, string>> = {
6363 changelog: "meta",
6464 flags: "meta",
6565 here: "meta",
66 home: "meta",
6667 map: "meta",
6768 api: "meta",
6869 mcp: "meta",
src/flow/home_json.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * The home's lanes, figures and slot graphs as plain data (#17919): what the page draws from
3 * `laneRegion`, `stripRegion` and `slotsBlock`, said without markup so a client reads numbers, not
4 * attributes or SVG heights. Each shaper takes what the page's own reader gave it and returns data;
5 * `http/home_json.ts` answers with them.
6 */
7 import type { Health, LaneKey, LaneView } from "./lanes.ts";
8 import { LANE_NAME } from "./lanes.ts";
9 import type { LaneTimes, NowTimes, Typical } from "./lane_times.ts";
10 import { SLOT_STEP_MS, waitEstimate, type SlotLine } from "./slots.ts";
11 import { HOUR_MS } from "./kpis.ts";
12 import type { RowFigure } from "../web/home_row.ts";
13
14 /** One tile: the attributes the page's tile carries, as fields. */
15 export interface TileData {
16 readonly key: string;
17 readonly state: "waiting" | "active" | "done";
18 readonly kind: "issue" | "pull" | "main" | "deploy";
19 readonly repo: string;
20 readonly number: number | null;
21 readonly issue: string | null;
22 /** The run, in the lanes whose tiles are runs; null elsewhere. */
23 readonly run: string | null;
24 readonly title: string;
25 readonly hint: string;
26 readonly since: string;
27 }
28
29 export interface LaneData {
30 readonly key: LaneKey;
31 readonly name: string;
32 readonly tone: Health["tone"];
33 readonly count: number;
34 /** The lane's health sentence. */
35 readonly health: string;
36 /** The median and oldest age of what is in the lane now; null when it is empty. */
37 readonly now: NowTimes | null;
38 /** The median and p90 time a card spent here over 24 hours; null when too few say. */
39 readonly typical: Typical | null;
40 /** Whether this is the lane the cards wait longest in, against its own typical. */
41 readonly slowest: boolean;
42 /** The events that make this lane due, as the page's `data-live` lists them. */
43 readonly live: readonly string[];
44 readonly tiles: readonly TileData[];
45 }
46
47 /** A `data-live` list as an array of the event names it holds. */
48 export const eventsOf = (list: string): string[] => list.split(",");
49
50 export function laneData(view: LaneView, health: Health, times: LaneTimes, runLanes: ReadonlySet<LaneKey>, live: string): LaneData {
51 const key = view.key;
52 return {
53 key,
54 name: LANE_NAME[key],
55 tone: health.tone,
56 count: view.total,
57 health: health.words,
58 now: times.nows[key] ?? null,
59 typical: times.typicals[key] ?? null,
60 slowest: times.slowest === key,
61 live: eventsOf(live),
62 tiles: view.items.map((i) => ({
63 key: i.key,
64 state: i.state,
65 kind: i.kind,
66 repo: i.repo,
67 number: i.number,
68 issue: i.issueId,
69 run: runLanes.has(key) ? (i.runId ?? null) : null,
70 title: i.title,
71 hint: i.hint,
72 since: i.since,
73 })),
74 };
75 }
76
77 /** The strip's figures with their series, and the events that redraw it. */
78 export function stripData(row: readonly RowFigure[], live: string): { readonly figures: readonly RowFigure[]; readonly seriesStepMs: number; readonly live: readonly string[] } {
79 return { figures: row, seriesStepMs: HOUR_MS, live: eventsOf(live) };
80 }
81
82 /** One kind's slots: the line the page says, and its 24 hours as buckets. */
83 export interface SlotsData {
84 readonly kind: SlotLine["kind"];
85 readonly slots: number;
86 readonly busy: number;
87 readonly waiting: number;
88 readonly medianRunMs: number | null;
89 readonly medianWaitMs: number | null;
90 /**
91 * The wait a new one would see at today's setting; null when nothing waits or no run is known.
92 */
93 readonly waitEstimateMs: number | null;
94 /** The width of a bucket; buckets run oldest first and the last is now. */
95 readonly bucketMs: number;
96 readonly buckets: readonly { readonly busy: number; readonly waiting: number; readonly full: boolean }[];
97 }
98
99 export function slotsData(lines: readonly SlotLine[]): SlotsData[] {
100 return lines.map((l) => ({
101 kind: l.kind,
102 slots: l.slots,
103 busy: l.busy,
104 waiting: l.waiting,
105 medianRunMs: l.medianRunMs,
106 medianWaitMs: l.medianWaitMs,
107 waitEstimateMs: waitEstimate(l, l.slots),
108 bucketMs: SLOT_STEP_MS,
109 buckets: l.points.map((p) => ({ busy: p.running, waiting: p.queued, full: p.running >= l.slots })),
110 }));
111 }
src/flow/kpis.ts +1 −1
@@ -28,7 +28,7 @@ import { readReach, type Reach } from "./reach.ts";
2828 import { countBugs, type BugCount } from "./bugs.ts";
2929 import { HOURS, median } from "./throughput.ts";
3030
31 const HOUR_MS = 3_600_000;
31 export const HOUR_MS = 3_600_000;
3232
3333 export interface Kpis {
3434 /** Non-empty landings on a default branch per hour, bucket 0 the last hour. */
src/flow/slots.ts +3 −3
@@ -25,7 +25,7 @@ import { median } from "./estimate_score.ts";
2525
2626 /** The instants the 24 hours are read at: one each quarter hour, oldest first. */
2727 export const SLOT_POINTS = 96;
28 const STEP_MS = 15 * 60_000;
28 export const SLOT_STEP_MS = 15 * 60_000;
2929 const HOUR_MS = 3_600_000;
3030
3131 export interface SlotPoint {
@@ -189,7 +189,7 @@ export function slotLine(kind: SlotLine["kind"], slots: number, runs: readonly R
189189 const spans = runs.map((r) => ({ asked: t(r.created_at), started: t(r.started_at), ended: t(r.finished_at) }));
190190 const points: SlotPoint[] = [];
191191 for (let i = SLOT_POINTS - 1; i >= 0; i--) {
192 const at = now - i * STEP_MS;
192 const at = now - i * SLOT_STEP_MS;
193193 let running = 0;
194194 let queued = 0;
195195 for (const { asked, started, ended } of spans) {
@@ -349,7 +349,7 @@ function paceOf(app: App, now: Date): { slots: number; reason: string } | undefi
349349 * pace, kept a minute, unless `pace` is false (home, which draws no pace).
350350 */
351351 export function readSlots(app: App, now: Date = new Date(), o: { readonly pace?: boolean } = {}): SlotLine[] {
352 const since = new Date(now.getTime() - SLOT_POINTS * STEP_MS).toISOString();
352 const since = new Date(now.getTime() - SLOT_POINTS * SLOT_STEP_MS).toISOString();
353353 const set = capacityValues(app.db, ["checks.concurrency", "crew.concurrency"] as const);
354354 const runs = rows(app.db, since);
355355 const said = lastEstimates(app.db);
src/generated/marks.ts +164 −162
@@ -45,168 +45,169 @@ import k40 from "../http/marks/api-v1-games.json";
4545 import k41 from "../http/marks/api-v1-health.json";
4646 import k42 from "../http/marks/api-v1-heartbeat.json";
4747 import k43 from "../http/marks/api-v1-here.json";
48 import k44 from "../http/marks/api-v1-keeper.json";
49 import k45 from "../http/marks/api-v1-mail-key.json";
50 import k46 from "../http/marks/api-v1-maintenance.json";
51 import k47 from "../http/marks/api-v1-map.json";
52 import k48 from "../http/marks/api-v1-migrate.json";
53 import k49 from "../http/marks/api-v1-offers.json";
54 import k50 from "../http/marks/api-v1-openapi.json.json";
55 import k51 from "../http/marks/api-v1-orgs.json";
56 import k52 from "../http/marks/api-v1-packs.json";
57 import k53 from "../http/marks/api-v1-passport.json";
58 import k54 from "../http/marks/api-v1-places.json";
59 import k55 from "../http/marks/api-v1-plans.json";
60 import k56 from "../http/marks/api-v1-proof.json";
61 import k57 from "../http/marks/api-v1-reach.json";
62 import k58 from "../http/marks/api-v1-release.json";
63 import k59 from "../http/marks/api-v1-releases.json";
64 import k60 from "../http/marks/api-v1-repos.json";
65 import k61 from "../http/marks/api-v1-returns.json";
66 import k62 from "../http/marks/api-v1-runner.json";
67 import k63 from "../http/marks/api-v1-search.json";
68 import k64 from "../http/marks/api-v1-secrets.json";
69 import k65 from "../http/marks/api-v1-sessions.json";
70 import k66 from "../http/marks/api-v1-share.json";
71 import k67 from "../http/marks/api-v1-slash.json";
72 import k68 from "../http/marks/api-v1-start.json";
73 import k69 from "../http/marks/api-v1-status.json";
74 import k70 from "../http/marks/api-v1-telemetry.json";
75 import k71 from "../http/marks/api-v1-templates.json";
76 import k72 from "../http/marks/api-v1-thoughts.json";
77 import k73 from "../http/marks/api-v1-timers.json";
78 import k74 from "../http/marks/api-v1-tokens.json";
79 import k75 from "../http/marks/api-v1-usage.json";
80 import k76 from "../http/marks/api-v1-user.json";
81 import k77 from "../http/marks/api-v1-users.json";
82 import k78 from "../http/marks/api-v1-version.json";
83 import k79 from "../http/marks/api-v1.json";
84 import k80 from "../http/marks/api.json";
85 import k81 from "../http/marks/apple-touch-icon-precomposed.png.json";
86 import k82 from "../http/marks/apple-touch-icon.png.json";
87 import k83 from "../http/marks/apps.json";
88 import k84 from "../http/marks/archive.json";
89 import k85 from "../http/marks/asked.json";
90 import k86 from "../http/marks/asks.json";
91 import k87 from "../http/marks/assets.json";
92 import k88 from "../http/marks/audit.csv.json";
93 import k89 from "../http/marks/audit.json";
94 import k90 from "../http/marks/big.json";
95 import k91 from "../http/marks/board.json";
96 import k92 from "../http/marks/boards.json";
97 import k93 from "../http/marks/bring.json";
98 import k94 from "../http/marks/broker.json";
99 import k95 from "../http/marks/changelog.atom.json";
100 import k96 from "../http/marks/changelog.json";
101 import k97 from "../http/marks/claim.json";
102 import k98 from "../http/marks/cloud.json";
103 import k99 from "../http/marks/cockpit.json";
104 import k100 from "../http/marks/contract.json";
105 import k101 from "../http/marks/contribute.json";
106 import k102 from "../http/marks/csp-report.json";
107 import k103 from "../http/marks/dash.json";
108 import k104 from "../http/marks/data.json";
109 import k105 from "../http/marks/dataset.json";
110 import k106 from "../http/marks/deploy-to.json";
111 import k107 from "../http/marks/design.json";
112 import k108 from "../http/marks/desk.json";
113 import k109 from "../http/marks/displays.json";
114 import k110 from "../http/marks/docs.json";
115 import k111 from "../http/marks/edge.json";
116 import k112 from "../http/marks/edition.json";
117 import k113 from "../http/marks/events.json";
118 import k114 from "../http/marks/explore.atom.json";
119 import k115 from "../http/marks/explore.json";
120 import k116 from "../http/marks/explore.json.json";
121 import k117 from "../http/marks/family.json";
122 import k118 from "../http/marks/favicon.ico.json";
123 import k119 from "../http/marks/feed.json";
124 import k120 from "../http/marks/feed.json.json";
125 import k121 from "../http/marks/first-admin.json";
126 import k122 from "../http/marks/fleet.json";
127 import k123 from "../http/marks/flow.json";
128 import k124 from "../http/marks/forge.json";
129 import k125 from "../http/marks/forges.json";
130 import k126 from "../http/marks/forks.json";
131 import k127 from "../http/marks/front.json";
132 import k128 from "../http/marks/funnel.json";
133 import k129 from "../http/marks/games.json";
134 import k130 from "../http/marks/go.json";
135 import k131 from "../http/marks/health.json";
136 import k132 from "../http/marks/home.json";
137 import k133 from "../http/marks/hooks.json";
138 import k134 from "../http/marks/icons.json";
139 import k135 from "../http/marks/infra.json";
140 import k136 from "../http/marks/join.json";
141 import k137 from "../http/marks/live.json";
142 import k138 from "../http/marks/llms-full.txt.json";
143 import k139 from "../http/marks/llms.txt.json";
144 import k140 from "../http/marks/login.json";
145 import k141 from "../http/marks/logout.json";
146 import k142 from "../http/marks/maintenance-json.json";
147 import k143 from "../http/marks/maintenance.json";
148 import k144 from "../http/marks/manifest.webmanifest.json";
149 import k145 from "../http/marks/map.json";
150 import k146 from "../http/marks/mcp.json";
151 import k147 from "../http/marks/measure.json";
152 import k148 from "../http/marks/metrics.json";
153 import k149 from "../http/marks/migrate.json";
154 import k150 from "../http/marks/new.json";
155 import k151 from "../http/marks/next.json";
156 import k152 from "../http/marks/notes.json";
157 import k153 from "../http/marks/now.json";
158 import k154 from "../http/marks/oauth.json";
159 import k155 from "../http/marks/oembed.json";
160 import k156 from "../http/marks/offers.json";
161 import k157 from "../http/marks/offline.json";
162 import k158 from "../http/marks/og.json";
163 import k159 from "../http/marks/openapi.json.json";
164 import k160 from "../http/marks/opensearch.xml.json";
165 import k161 from "../http/marks/organizations.json";
166 import k162 from "../http/marks/origins.json";
167 import k163 from "../http/marks/owner.atom.json";
168 import k164 from "../http/marks/owner.json";
169 import k165 from "../http/marks/packs.json";
170 import k166 from "../http/marks/peek.json";
171 import k167 from "../http/marks/pinned.json";
172 import k168 from "../http/marks/pipeline.json";
173 import k169 from "../http/marks/plugins.json";
174 import k170 from "../http/marks/pricing.json";
175 import k171 from "../http/marks/privacy.json";
176 import k172 from "../http/marks/r.json";
177 import k173 from "../http/marks/recover.json";
178 import k174 from "../http/marks/releases.json";
179 import k175 from "../http/marks/releases.json.json";
180 import k176 from "../http/marks/repos.json";
181 import k177 from "../http/marks/resilience.json";
182 import k178 from "../http/marks/review.json";
183 import k179 from "../http/marks/robots.txt.json";
184 import k180 from "../http/marks/root.json";
185 import k181 from "../http/marks/runs.json";
186 import k182 from "../http/marks/script-error.json";
187 import k183 from "../http/marks/search.json";
188 import k184 from "../http/marks/security.json";
189 import k185 from "../http/marks/settings.json";
190 import k186 from "../http/marks/sign-in.json";
191 import k187 from "../http/marks/signin.json";
192 import k188 from "../http/marks/signup.json";
193 import k189 from "../http/marks/sitemap.xml.json";
194 import k190 from "../http/marks/status.json";
195 import k191 from "../http/marks/sw.js.json";
196 import k192 from "../http/marks/system.json";
197 import k193 from "../http/marks/tab.json";
198 import k194 from "../http/marks/tabforge.json";
199 import k195 from "../http/marks/talk.json";
200 import k196 from "../http/marks/tell.json";
201 import k197 from "../http/marks/templates.json";
202 import k198 from "../http/marks/templates.json.json";
203 import k199 from "../http/marks/terms.json";
204 import k200 from "../http/marks/theme.json";
205 import k201 from "../http/marks/toolbar-lab.js.json";
206 import k202 from "../http/marks/toolbar-lab.json";
207 import k203 from "../http/marks/verify.json";
208 import k204 from "../http/marks/welcome.json";
209 import k205 from "../http/marks/well-known.json";
48 import k44 from "../http/marks/api-v1-home.json";
49 import k45 from "../http/marks/api-v1-keeper.json";
50 import k46 from "../http/marks/api-v1-mail-key.json";
51 import k47 from "../http/marks/api-v1-maintenance.json";
52 import k48 from "../http/marks/api-v1-map.json";
53 import k49 from "../http/marks/api-v1-migrate.json";
54 import k50 from "../http/marks/api-v1-offers.json";
55 import k51 from "../http/marks/api-v1-openapi.json.json";
56 import k52 from "../http/marks/api-v1-orgs.json";
57 import k53 from "../http/marks/api-v1-packs.json";
58 import k54 from "../http/marks/api-v1-passport.json";
59 import k55 from "../http/marks/api-v1-places.json";
60 import k56 from "../http/marks/api-v1-plans.json";
61 import k57 from "../http/marks/api-v1-proof.json";
62 import k58 from "../http/marks/api-v1-reach.json";
63 import k59 from "../http/marks/api-v1-release.json";
64 import k60 from "../http/marks/api-v1-releases.json";
65 import k61 from "../http/marks/api-v1-repos.json";
66 import k62 from "../http/marks/api-v1-returns.json";
67 import k63 from "../http/marks/api-v1-runner.json";
68 import k64 from "../http/marks/api-v1-search.json";
69 import k65 from "../http/marks/api-v1-secrets.json";
70 import k66 from "../http/marks/api-v1-sessions.json";
71 import k67 from "../http/marks/api-v1-share.json";
72 import k68 from "../http/marks/api-v1-slash.json";
73 import k69 from "../http/marks/api-v1-start.json";
74 import k70 from "../http/marks/api-v1-status.json";
75 import k71 from "../http/marks/api-v1-telemetry.json";
76 import k72 from "../http/marks/api-v1-templates.json";
77 import k73 from "../http/marks/api-v1-thoughts.json";
78 import k74 from "../http/marks/api-v1-timers.json";
79 import k75 from "../http/marks/api-v1-tokens.json";
80 import k76 from "../http/marks/api-v1-usage.json";
81 import k77 from "../http/marks/api-v1-user.json";
82 import k78 from "../http/marks/api-v1-users.json";
83 import k79 from "../http/marks/api-v1-version.json";
84 import k80 from "../http/marks/api-v1.json";
85 import k81 from "../http/marks/api.json";
86 import k82 from "../http/marks/apple-touch-icon-precomposed.png.json";
87 import k83 from "../http/marks/apple-touch-icon.png.json";
88 import k84 from "../http/marks/apps.json";
89 import k85 from "../http/marks/archive.json";
90 import k86 from "../http/marks/asked.json";
91 import k87 from "../http/marks/asks.json";
92 import k88 from "../http/marks/assets.json";
93 import k89 from "../http/marks/audit.csv.json";
94 import k90 from "../http/marks/audit.json";
95 import k91 from "../http/marks/big.json";
96 import k92 from "../http/marks/board.json";
97 import k93 from "../http/marks/boards.json";
98 import k94 from "../http/marks/bring.json";
99 import k95 from "../http/marks/broker.json";
100 import k96 from "../http/marks/changelog.atom.json";
101 import k97 from "../http/marks/changelog.json";
102 import k98 from "../http/marks/claim.json";
103 import k99 from "../http/marks/cloud.json";
104 import k100 from "../http/marks/cockpit.json";
105 import k101 from "../http/marks/contract.json";
106 import k102 from "../http/marks/contribute.json";
107 import k103 from "../http/marks/csp-report.json";
108 import k104 from "../http/marks/dash.json";
109 import k105 from "../http/marks/data.json";
110 import k106 from "../http/marks/dataset.json";
111 import k107 from "../http/marks/deploy-to.json";
112 import k108 from "../http/marks/design.json";
113 import k109 from "../http/marks/desk.json";
114 import k110 from "../http/marks/displays.json";
115 import k111 from "../http/marks/docs.json";
116 import k112 from "../http/marks/edge.json";
117 import k113 from "../http/marks/edition.json";
118 import k114 from "../http/marks/events.json";
119 import k115 from "../http/marks/explore.atom.json";
120 import k116 from "../http/marks/explore.json";
121 import k117 from "../http/marks/explore.json.json";
122 import k118 from "../http/marks/family.json";
123 import k119 from "../http/marks/favicon.ico.json";
124 import k120 from "../http/marks/feed.json";
125 import k121 from "../http/marks/feed.json.json";
126 import k122 from "../http/marks/first-admin.json";
127 import k123 from "../http/marks/fleet.json";
128 import k124 from "../http/marks/flow.json";
129 import k125 from "../http/marks/forge.json";
130 import k126 from "../http/marks/forges.json";
131 import k127 from "../http/marks/forks.json";
132 import k128 from "../http/marks/front.json";
133 import k129 from "../http/marks/funnel.json";
134 import k130 from "../http/marks/games.json";
135 import k131 from "../http/marks/go.json";
136 import k132 from "../http/marks/health.json";
137 import k133 from "../http/marks/home.json";
138 import k134 from "../http/marks/hooks.json";
139 import k135 from "../http/marks/icons.json";
140 import k136 from "../http/marks/infra.json";
141 import k137 from "../http/marks/join.json";
142 import k138 from "../http/marks/live.json";
143 import k139 from "../http/marks/llms-full.txt.json";
144 import k140 from "../http/marks/llms.txt.json";
145 import k141 from "../http/marks/login.json";
146 import k142 from "../http/marks/logout.json";
147 import k143 from "../http/marks/maintenance-json.json";
148 import k144 from "../http/marks/maintenance.json";
149 import k145 from "../http/marks/manifest.webmanifest.json";
150 import k146 from "../http/marks/map.json";
151 import k147 from "../http/marks/mcp.json";
152 import k148 from "../http/marks/measure.json";
153 import k149 from "../http/marks/metrics.json";
154 import k150 from "../http/marks/migrate.json";
155 import k151 from "../http/marks/new.json";
156 import k152 from "../http/marks/next.json";
157 import k153 from "../http/marks/notes.json";
158 import k154 from "../http/marks/now.json";
159 import k155 from "../http/marks/oauth.json";
160 import k156 from "../http/marks/oembed.json";
161 import k157 from "../http/marks/offers.json";
162 import k158 from "../http/marks/offline.json";
163 import k159 from "../http/marks/og.json";
164 import k160 from "../http/marks/openapi.json.json";
165 import k161 from "../http/marks/opensearch.xml.json";
166 import k162 from "../http/marks/organizations.json";
167 import k163 from "../http/marks/origins.json";
168 import k164 from "../http/marks/owner.atom.json";
169 import k165 from "../http/marks/owner.json";
170 import k166 from "../http/marks/packs.json";
171 import k167 from "../http/marks/peek.json";
172 import k168 from "../http/marks/pinned.json";
173 import k169 from "../http/marks/pipeline.json";
174 import k170 from "../http/marks/plugins.json";
175 import k171 from "../http/marks/pricing.json";
176 import k172 from "../http/marks/privacy.json";
177 import k173 from "../http/marks/r.json";
178 import k174 from "../http/marks/recover.json";
179 import k175 from "../http/marks/releases.json";
180 import k176 from "../http/marks/releases.json.json";
181 import k177 from "../http/marks/repos.json";
182 import k178 from "../http/marks/resilience.json";
183 import k179 from "../http/marks/review.json";
184 import k180 from "../http/marks/robots.txt.json";
185 import k181 from "../http/marks/root.json";
186 import k182 from "../http/marks/runs.json";
187 import k183 from "../http/marks/script-error.json";
188 import k184 from "../http/marks/search.json";
189 import k185 from "../http/marks/security.json";
190 import k186 from "../http/marks/settings.json";
191 import k187 from "../http/marks/sign-in.json";
192 import k188 from "../http/marks/signin.json";
193 import k189 from "../http/marks/signup.json";
194 import k190 from "../http/marks/sitemap.xml.json";
195 import k191 from "../http/marks/status.json";
196 import k192 from "../http/marks/sw.js.json";
197 import k193 from "../http/marks/system.json";
198 import k194 from "../http/marks/tab.json";
199 import k195 from "../http/marks/tabforge.json";
200 import k196 from "../http/marks/talk.json";
201 import k197 from "../http/marks/tell.json";
202 import k198 from "../http/marks/templates.json";
203 import k199 from "../http/marks/templates.json.json";
204 import k200 from "../http/marks/terms.json";
205 import k201 from "../http/marks/theme.json";
206 import k202 from "../http/marks/toolbar-lab.js.json";
207 import k203 from "../http/marks/toolbar-lab.json";
208 import k204 from "../http/marks/verify.json";
209 import k205 from "../http/marks/welcome.json";
210 import k206 from "../http/marks/well-known.json";
210211
211212 /** Each file of `http/marks/`, parsed, in name order. */
212213 export const MARK_FILES: readonly unknown[] = [
@@ -416,4 +417,5 @@ export const MARK_FILES: readonly unknown[] = [
416417 k203,
417418 k204,
418419 k205,
420 k206,
419421 ];
src/http/home_api.ts added +13
@@ -0,0 +1,13 @@
1 /**
2 * The home's lanes, figures and slot graphs as JSON (#17919), on the API router: a path under
3 * `/api` never reaches the pages'.
4 */
5 import { homeLanesJson, homeSlotsJson, homeStripJson } from "./home_json.ts";
6 import type { Handler } from "./context.ts";
7 import type { Router } from "./router.ts";
8
9 export function homeApiRoutes(router: Router<Handler>): void {
10 router.add("GET", "/api/v1/home/lanes", homeLanesJson);
11 router.add("GET", "/api/v1/home/strip", homeStripJson);
12 router.add("GET", "/api/v1/home/slots", homeSlotsJson);
13 }
src/http/home_json.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * The home's lanes, figures and slot graphs as JSON (#17919): `GET /api/v1/home/lanes[?s=]`,
3 * `/api/v1/home/strip` and `/api/v1/home/slots`. The page's own readers, the page's own audience
4 * rules (the lanes are the viewer's cards; the figures and slots are a forge admin's, and not a
5 * client forge's owner's), read-only. The lanes carry an ETag that changes with the lane picture
6 * (the fragment's `laneTag`), so a repeat sending it gets 304 before anything is shaped; the
7 * figures and the slots are tagged by their bytes.
8 */
9 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../core/route_timing.ts";
10 import { idleFor } from "../crew/idle_reason.ts";
11 import { lanePicture, LANES, viewFor, type LaneKey } from "../flow/lanes.ts";
12 import { eventsOf, laneData, slotsData, stripData } from "../flow/home_json.ts";
13 import { readSlots } from "../flow/slots.ts";
14 import { spawnedForge } from "../spawn/claim.ts";
15 import { homeRow } from "../web/home_row.ts";
16 import { healthOf, LANE_LIVE, laneTag, optionsOf, RUN_LANES, STRIP_LIVE, timesFor } from "../web/pages/home_flow.ts";
17 import { requestHolds } from "./conditional.ts";
18 import type { Ctx } from "./context.ts";
19 import { weakEtag } from "./etag.ts";
20 import { json, notFound, unauthorized } from "./respond.ts";
21
22 /** The events that move the slots' counts: a run asked for, started or finished. */
23 export const SLOTS_LIVE = "run.queued,run.started,run.finished";
24
25 const HEADERS = { "cache-control": "private, no-cache", vary: "authorization, cookie" };
26
27 /** Tagged by `etag`: a repeat holding it gets 304 and no body. */
28 function answer(ctx: Ctx, etag: string, data: () => unknown): Response {
29 if (requestHolds(ctx.request, etag)) return new Response(null, { status: 304, headers: { ...HEADERS, etag } });
30 return json(data(), 200, { ...HEADERS, etag });
31 }
32
33 /** A forge admin who is not a client forge's owner: whose the forge-wide figures and slots are. */
34 const wideFor = async (ctx: Ctx): Promise<boolean> => ctx.auth.user?.isAdmin === true && (await spawnedForge(ctx.app)) === undefined;
35
36 // GET /api/v1/home/lanes[?s=<lane>] — the lanes the home draws, for this viewer.
37 export async function homeLanesJson(ctx: Ctx): Promise<Response> {
38 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
39 const user = ctx.auth.user;
40 if (user === undefined) return unauthorized();
41 const asked = ctx.url.searchParams.get("s");
42 const only = asked === null ? undefined : LANES.find((k) => k === asked);
43 if (asked !== null && only === undefined) return json({ error: "invalid", field: "s", message: `s is one of ${LANES.join(", ")}` }, 422);
44 const keys: readonly LaneKey[] = only === undefined ? LANES : [only];
45 const now = Date.now();
46 const picture = await timePhaseAsync(ctx.request, "picture", () => lanePicture(ctx.app.db, optionsOf(ctx), "lane", now));
47 if (picture === undefined) return json({ error: "reading", message: "the forge is still reading its lanes; ask again in a moment" }, 503, { "retry-after": "1" });
48 // The body differs by `wide` (the forge-wide typicals), so the tag is keyed on it, not on admin
49 // alone.
outdated

The viewer key is admin for every admin, but timesFor is passed user.isAdmin && user.kind !== "agent" as wide. An agent admin and a human admin get the same tag for different bodies. Use the same wide value in the key.

50 const wide = user.isAdmin && user.kind !== "agent";
51 const viewer = wide ? "admin" : user.isAdmin ? `${user.id}|admin` : user.id;
52 const etag = `"${Bun.hash(keys.map((k) => laneTag(picture, k, viewer, null, now)).join("|")).toString(36)}"`;
53 return answer(ctx, etag, () => {
54 const viewing = timePhase(ctx.request, "viewing", () => viewFor(ctx.app.db, user, picture, null));
55 const times = timesFor(viewing, picture, wide, now);
56 return { lanes: keys.map((k) => laneData(viewing.lanes[k], healthOf(viewing.lanes[k], picture, now), times, RUN_LANES, LANE_LIVE[k])) };
57 });
58 }
59
60 // GET /api/v1/home/strip — the figures row, for an admin of this forge; no one else has one.
61 export async function homeStripJson(ctx: Ctx): Promise<Response> {
62 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
63 const user = ctx.auth.user;
64 if (user === undefined) return unauthorized();
65 if (!(await wideFor(ctx))) return notFound();
66 const now = Date.now();
67 const picture = await timePhaseAsync(ctx.request, "picture", () => lanePicture(ctx.app.db, optionsOf(ctx, user), "lane", now));
68 if (picture === undefined) return json({ error: "reading", message: "the forge is still reading its figures; ask again in a moment" }, 503, { "retry-after": "1" });
69 const data = stripData(homeRow(picture, (idle) => idleFor(ctx.app, user, idle), now), STRIP_LIVE);
70 return answer(ctx, weakEtag(JSON.stringify(data)), () => data);
71 }
72
73 // GET /api/v1/home/slots — checks and crew slots with their 24 hours, for an admin of this forge.
74 export async function homeSlotsJson(ctx: Ctx): Promise<Response> {
75 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
76 if (ctx.auth.user === undefined) return unauthorized();
77 if (!(await wideFor(ctx))) return notFound();
78 const data = { kinds: slotsData(timePhase(ctx.request, "slots", () => readSlots(ctx.app, new Date(), { pace: false }))), live: eventsOf(SLOTS_LIVE) };
79 return answer(ctx, weakEtag(JSON.stringify(data)), () => data);
80 }
src/http/lazy_lists.ts +8
@@ -5,6 +5,13 @@
55 * order (which matters beside a `:name`). `test/boot-lazy.test.ts` fails when this is stale.
66 */
77
8 /** The `home-api` family. */
9 export const HOME_API_ROUTES = [
10 ["GET", "/api/v1/home/lanes"],
11 ["GET", "/api/v1/home/strip"],
12 ["GET", "/api/v1/home/slots"],
13 ] as const;
14
815 /** The `MCP` family. */
916 export const MCP_ROUTES = [
1017 ["POST", "/mcp"],
@@ -1726,6 +1733,7 @@ export const API_PAGES_ROUTES = [
17261733
17271734 /** Each family's list by its name, as `lazyRoutes` reads it. */
17281735 export const LAZY_ROUTES: Readonly<Record<string, readonly (readonly [method: string, pattern: string])[]>> = {
1736 "home-api": HOME_API_ROUTES,
17291737 "MCP": MCP_ROUTES,
17301738 "settings": SETTINGS_ROUTES,
17311739 "forges": FORGES_ROUTES,
src/http/marks/api-v1-home.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/home",
3 "mark": "open"
4 }
src/http/server.ts +1
@@ -306,6 +306,7 @@ export function buildApiRouter(): Router<Handler> {
306306 return (own) => apiRoutes(own, isPublicPage);
307307 });
308308 lazyRoutes(router, "feed", async () => (await import("./feed.ts")).feedRoutes);
309 lazyRoutes(router, "home-api", async () => (await import("./home_api.ts")).homeApiRoutes);
309310 lazyRoutes(router, "config", async () => (await import("./config.ts")).configRoutes);
310311 lazyRoutes(router, "checks-recheck", async () => (await import("./checks_recheck.ts")).checksRecheckRoutes);
311312 router.add("GET", "/api/v1", apiRoot);
src/tui/screens/dashboard.ts +3 −1
@@ -145,6 +145,8 @@ import {
145145 plural,
146146 linkScreen,
147147 } from "./common.ts";
148 import { readSlots } from "../../flow/slots.ts";
149 import { slotLines } from "../slot_lines.ts";
148150 import { homeRow, homeRowLines } from "../../web/home_row.ts";
149151 import { running, runningLine } from "../../kernel/version.ts";
150152 import { spawnedForge } from "../../spawn/claim.ts";
@@ -492,7 +494,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
492494 if (f.user.isAdmin) crewWeek = picture?.strip?.week ?? null;
493495 // The page's one row of figures, each said once (`homeRow`): the same list, as lines.
494496 // As on the page: an admin's, and never on a hosted forge, whose owner is a client.
495 row = f.user.isAdmin && picture !== undefined && (await spawnedForge(f.app)) === undefined ? [...homeRowLines(homeRow(picture, (idle) => idleFor(f.app, f.user, idle), Date.now())), liveVersionLine()] : [];
497 row = f.user.isAdmin && picture !== undefined && (await spawnedForge(f.app)) === undefined ? [...homeRowLines(homeRow(picture, (idle) => idleFor(f.app, f.user, idle), Date.now())), ...slotLines(readSlots(f.app, new Date(), { pace: false }), Date.now()), liveVersionLine()] : [];
496498 // Every viewer reads the parked pulls of the repositories they can read, as on the web home.
497499 parked = terminalLines(parkedFor(f.db, f.user, picture?.strip?.parked));
498500 asks = picture === undefined ? [] : asksLines(f.db, f.user, picture);
src/tui/slot_lines.ts added +15
@@ -0,0 +1,15 @@
1 /**
2 * The slots as the terminal's home prints them (#17919): one line a kind, the same words the
3 * page's slot line says (how many are busy, what waits and for how long), so both doors tell the
4 * same.
5 */
6 import { span } from "../flow/pipeline.ts";
7 import { isFull, type SlotLine } from "../flow/slots.ts";
8 import { NAME, slotsWords } from "../web/flow_slots.ts";
9
10 export function slotLines(lines: readonly SlotLine[], now: number): string[] {
11 return lines.map((l) => {
12 const waits = l.waiting === 0 ? "" : ` · ${String(l.waiting)} waiting, oldest ${span(now - Date.parse(l.oldestAt ?? new Date(now).toISOString()))}`;
13 return `${NAME[l.kind]}: ${slotsWords(l.busy, l.slots)}${isFull(l) ? " (full)" : ""}${waits} /settings/capacity`;
14 });
15 }
src/web/flow_slots.ts +2 −2
@@ -11,7 +11,7 @@ import { badge } from "./ui.ts";
1111 import { span } from "../flow/pipeline.ts";
1212 import { isFull, offByMore, roomSaysUpTo, SLOT_POINTS, waitEstimate, type SlotLine, type SlotRoom } from "../flow/slots.ts";
1313
14 const NAME: Readonly<Record<SlotLine["kind"], string>> = { checks: "Checks", crew: "Crew runs" };
14 export const NAME: Readonly<Record<SlotLine["kind"], string>> = { checks: "Checks", crew: "Crew runs" };
1515 const H = 32;
1616
1717 /**
@@ -78,7 +78,7 @@ const roomData = (kind: SlotLine["kind"], r: SlotRoom): Html => html` data-room=
7878 * How busy the slots are, honestly: "2 of 4 slots busy", but never "2 of 1" when more run than
7979 * there are slots (a local fallback runs past them): then "2 running, 1 slot".
8080 */
81 const slotsWords = (busy: number, slots: number): string =>
81 export const slotsWords = (busy: number, slots: number): string =>
8282 busy > slots ? `${String(busy)} running, ${String(slots)} ${slots === 1 ? "slot" : "slots"}` : `${String(busy)} of ${String(slots)} slots busy`;
8383
8484 function line(l: SlotLine, now: number, admin = false): Html {
src/web/pages/home_flow.ts +7 −7
@@ -85,7 +85,7 @@ import { idleFor, type IdleReason } from "../../crew/idle_reason.ts";
8585 /**
8686 * The events that can move work between lanes, per lane. A burst of them is one fetch of the lane.
8787 */
88 const LANE_LIVE: Record<LaneKey, string> = {
88 export const LANE_LIVE: Record<LaneKey, string> = {
8989 asked: "issue.opened,issue.closed,issue.reopened,issue.blocked,issue.unblocked,run.queued,run.started,run.finished",
9090 building: "run.queued,run.started,run.finished,pull.opened,pull.closed",
9191 checks: "run.queued,run.started,run.finished,pull.opened,pull.pushed,pull.merged",
@@ -93,7 +93,7 @@ const LANE_LIVE: Record<LaneKey, string> = {
9393 landing: "pull.reviewed,pull.merged,pull.closed,pull.pushed,queue.*,run.finished,app.serving",
9494 live: "app.serving,release.*,run.finished,run.started,pull.merged",
9595 };
96 const STRIP_LIVE = "pull.merged,run.finished,release.*,app.serving,app.stopped,forge.*,queue.*";
96 export const STRIP_LIVE = "pull.merged,run.finished,release.*,app.serving,app.stopped,forge.*,queue.*";
9797
9898 /** An `owner/name` the filter may hold; anything else is no filter. */
9999 const APP_SLUG = /^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/;
@@ -131,7 +131,7 @@ const TONE_DOT = {
131131 } as const;
132132
133133 /** The lanes whose tiles are runs: there a tile names its run, for Stop and Watch. */
134 const RUN_LANES: ReadonlySet<LaneKey> = new Set(["building", "checks", "review"]);
134 export const RUN_LANES: ReadonlySet<LaneKey> = new Set(["building", "checks", "review"]);
135135
136136 function tile(i: LaneView["items"][number], now: number, lane: LaneKey): Html {
137137 const no =
@@ -175,7 +175,7 @@ function laneHref(key: LaneKey, only: string | null): string {
175175 * What the viewer may read decides the times: their cards, and forge-wide typicals only for a
176176 * person who is a forge admin.
177177 */
178 function timesFor(viewing: Viewing, picture: LanePicture, wide: boolean, now: number): LaneTimes {
178 export function timesFor(viewing: Viewing, picture: LanePicture, wide: boolean, now: number): LaneTimes {
179179 const held = Object.fromEntries(LANES.map((k) => [k, { items: viewing.lanes[k].all }])) as Record<LaneKey, { items: Viewing["lanes"][LaneKey]["all"] }>;
180180 return timesOf(held, wide ? picture.typicals : null, now);
181181 }
@@ -262,7 +262,7 @@ export function laneRegion(
262262
263263 /** What the lanes' reading needs of the forge. */
264264 const pictureOptions = (app: App): PictureOptions => ({ dataDir: app.config.dataDir, ceilingUsd: forgeCeiling(app.config) });
265 const optionsOf = (ctx: Ctx, user: { readonly id: string } | undefined = ctx.auth.user): PictureOptions => ({ ...pictureOptions(ctx.app), ...(user === undefined ? {} : { viewer: user.id }) });
265 export const optionsOf = (ctx: Ctx, user: { readonly id: string } | undefined = ctx.auth.user): PictureOptions => ({ ...pictureOptions(ctx.app), ...(user === undefined ? {} : { viewer: user.id }) });
266266
267267 /**
268268 * The Asked lane's one line for the ready work waiting for the crew: never a card each, since it
@@ -277,7 +277,7 @@ export function queueLine(viewing: Viewing, picture: LanePicture): Html | null {
277277 /** For a person here for a game box alone (`playsOnly`), their games: the pipeline has nothing of theirs. */
278278 const gamesLink = (ctx: Ctx): Html | null => (playsOnly(ctx) ? html` <a href="/games" data-your-games>Your games</a>` : null);
279279
280 const healthOf = (view: LaneView, picture: LanePicture, now: number): Health => laneHealth(view, { now, builders: picture.builders, moved: picture.moved, idle: picture.idle });
280 export const healthOf = (view: LaneView, picture: LanePicture, now: number): Health => laneHealth(view, { now, builders: picture.builders, moved: picture.moved, idle: picture.idle });
281281
282282 // ---- the header's one line, and the strip: today's figures ----
283283
@@ -560,7 +560,7 @@ export async function liveTableFragment(ctx: Ctx): Promise<Response> {
560560 * and this filter, and the minute (its ages are in
561561 * minutes). A lane that has not changed answers 304 without being drawn.
562562 */
563 function laneTag(picture: LanePicture, key: LaneKey, viewer: string, only: string | null, now: number, mine = ""): string {
563 export function laneTag(picture: LanePicture, key: LaneKey, viewer: string, only: string | null, now: number, mine = ""): string {
564564 const b = picture.builders;
565565 return Bun.hash(`${picture.versions[key]}|${picture.moved[key]}|${b.running}/${b.slots}|${viewer}|${only ?? ""}|${mine}|${Math.floor(now / 60_000)}`).toString(36);
566566 }
test/home-json.test.ts added +234
@@ -0,0 +1,234 @@
1 /**
2 * The home's lanes, figures and slot graphs as JSON (#17919): the same lanes the page draws, for
3 * the same audience, with an ETag a repeat can hold, and no markup to read.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { openapi } from "../src/contract/openapi.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser, getUserByName, type User } from "../src/core/users.ts";
14 import { claimedForge } from "./helpers/claimed-forge.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { dashboardScreen } from "../src/tui/screens/dashboard.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { settleApp } from "./helpers/tui.ts";
19 import { LANES } from "../src/flow/lanes.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { misfits } from "./helpers/json_schema.ts";
22 import { promote } from "./helpers/members.ts";
23 import { seedHomeFlow, startCheck, type HomeFlowSeed } from "./helpers/home-flow-seed.ts";
24
25 let dataDir: string;
26 let app: App;
27 let servers: Servers;
28 let owner = "";
29 let bob = "";
30 let seeded: HomeFlowSeed;
31
32 const get = (path: string, cookie: string, held?: string) =>
33 fetch(`${servers.url}${path}`, { headers: { cookie, ...(held === undefined ? {} : { "if-none-match": held }) }, redirect: "manual" });
34 const anonymous = (path: string) => fetch(`${servers.url}${path}`, { redirect: "manual" });
35
36 interface Tile { key: string; state: string; kind: string; repo: string; number: number | null; issue: string | null; run: string | null; title: string; hint: string; since: string }
37 interface Lane { key: string; name: string; tone: string; count: number; health: string; now: unknown; typical: unknown; slowest: boolean; live: string[]; tiles: Tile[] }
38
39 beforeAll(async () => {
40 dataDir = await mkdtemp(join(tmpdir(), "forge-home-json-"));
41 app = createApp({ dataDir, port: 0 });
42 const seed = await seedHomeFlow(app);
43 seeded = seed;
44 servers = await serve(app);
45 owner = `forge_session=${createSession(app.db, seed.owner.id).token}`;
46 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
47 if (!made.ok) throw new Error(made.error);
48 promote(app.db, made.value);
49 bob = `forge_session=${createSession(app.db, made.value.id).token}`;
50 });
51
52 afterAll(async () => {
53 servers.stop();
54 app.close();
55 await rm(dataDir, { recursive: true, force: true });
56 });
57
58 describe("GET /api/v1/home/lanes", () => {
59 test("answers the six lanes with their tiles as fields, and the events that make each due", async () => {
60 const res = await get("/api/v1/home/lanes", owner);
61 expect(res.status).toBe(200);
62 expect(res.headers.get("etag")).toMatch(/^"[0-9a-z]+"$/);
63 const { lanes } = (await res.json()) as { lanes: Lane[] };
64 expect(lanes.map((l) => l.key)).toEqual([...LANES]);
65 const building = lanes.find((l) => l.key === "building")!;
66 expect(building.count).toBeGreaterThan(0);
67 expect(building.health.length).toBeGreaterThan(0);
68 expect(["quiet", "flowing", "waiting", "stuck"]).toContain(building.tone);
69 expect(building.live).toContain("run.started");
70 const tile = building.tiles.find((t) => t.title === "A cost ledger per delivery: tokens, compute and time")!;
71 expect(tile.repo).toContain("/");
72 expect(tile.run).not.toBeNull();
73 expect(tile.state).toMatch(/^(waiting|active|done)$/);
74 expect(Date.parse(tile.since)).not.toBeNaN();
75 // a lane whose tiles are not runs names no run
76 for (const l of lanes.filter((l) => l.key === "asked" || l.key === "landing" || l.key === "live")) for (const t of l.tiles) expect(t.run).toBeNull();
77 });
78
79 test("holds the page: the same tiles, in the lane the page's fragment draws them", async () => {
80 const { lanes } = (await (await get("/api/v1/home/lanes?s=checks", owner)).json()) as { lanes: Lane[] };
81 expect(lanes.map((l) => l.key)).toEqual(["checks"]);
82 const html = await (await get("/live/lane?s=checks", owner)).text();
83 const keys = [...html.matchAll(/class="tile" data-key="([^"]*)"/g)].map((m) => m[1]!);
84 expect(lanes[0]!.tiles.map((t) => t.key)).toEqual(keys);
85 expect(html).toContain(`data-live="${lanes[0]!.live.join(",")}"`);
86 });
87
88 test("sends its ETag as a header and answers 304 to it; a lane that changes has another", async () => {
89 const first = await get("/api/v1/home/lanes", owner);
90 const tag = first.headers.get("etag")!;
91 const again = await get("/api/v1/home/lanes", owner, tag);
92 expect(again.status).toBe(304);
93 expect(await again.text()).toBe("");
94 expect(again.headers.get("etag")).toBe(tag);
95 // one lane's tag is not the six's
96 expect((await get("/api/v1/home/lanes?s=asked", owner)).headers.get("etag")).not.toBe(tag);
97 // a card that moves gives another tag, and the old one now gets the lanes, not a 304
98 app.db.run("UPDATE run SET state = 'ok' WHERE issue_id = ?1 AND kind = 'agent'", [seeded.pulls["r2"]!]);
99 startCheck(app, seeded.pulls["r2"]!, seeded.repos.notes.id);
100 app.bus.append({ kind: "run.started", repoId: seeded.repos.notes.id, payload: {} });
101 const moved = await get("/api/v1/home/lanes", owner, tag);
102 expect(moved.status).toBe(200);
103 expect(moved.headers.get("etag")).not.toBe(tag);
104 expect(((await moved.json()) as { lanes: Lane[] }).lanes.length).toBe(6);
105 });
106
107 test("refuses a lane it does not know, naming the field, and a caller with no account", async () => {
108 const bad = await get("/api/v1/home/lanes?s=nonsense", owner);
109 expect(bad.status).toBe(422);
110 expect(await bad.json()).toMatchObject({ error: "invalid", field: "s" });
111 expect((await anonymous("/api/v1/home/lanes")).status).toBe(401);
112 });
113
114 test("shows a viewer only what they may read, as the page does", async () => {
115 const { lanes } = (await (await get("/api/v1/home/lanes", bob)).json()) as { lanes: Lane[] };
116 const titles = lanes.flatMap((l) => l.tiles.map((t) => t.title));
117 const html = await (await get("/", bob)).text();
118 for (const t of titles) expect(html).toContain(t.replaceAll("'", "&#39;"));
119 const mine = (await (await get("/api/v1/home/lanes", owner)).json()) as { lanes: Lane[] };
120 expect(mine.lanes.flatMap((l) => l.tiles).length).toBeGreaterThanOrEqual(titles.length);
121 });
122 });
123
124 describe("GET /api/v1/home/strip", () => {
125 test("answers an admin's figures with the shipped series, and its events", async () => {
126 const res = await get("/api/v1/home/strip", owner);
127 expect(res.status).toBe(200);
128 const body = (await res.json()) as { figures: { label: string; value: string; href: string; series?: number[] }[]; seriesStepMs: number; live: string[] };
129 const shipped = body.figures.find((f) => f.label === "Shipped in 24 hours")!;
130 expect(shipped.series).toHaveLength(24);
131 expect(body.seriesStepMs).toBe(3_600_000);
132 expect(body.live).toContain("pull.merged");
133 const html = await (await get("/live/strip", owner)).text();
134 expect(html).toContain(`data-live="${body.live.join(",")}"`);
135 for (const f of body.figures) expect(html).toContain(f.label);
136 });
137
138 test("answers 304 to its ETag; no one but an admin of the forge has a strip", async () => {
139 const tag = (await get("/api/v1/home/strip", owner)).headers.get("etag")!;
140 expect((await get("/api/v1/home/strip", owner, tag)).status).toBe(304);
141 expect((await get("/api/v1/home/strip", bob)).status).toBe(403);
142 expect((await anonymous("/api/v1/home/strip")).status).toBe(401);
143 });
144 });
145
146 describe("GET /api/v1/home/slots", () => {
147 test("answers checks and crew with the counts and 24 hours of buckets", async () => {
148 const res = await get("/api/v1/home/slots", owner);
149 expect(res.status).toBe(200);
150 const body = (await res.json()) as { kinds: { kind: string; slots: number; busy: number; waiting: number; bucketMs: number; buckets: { busy: number; waiting: number; full: boolean }[] }[]; live: string[] };
151 expect(body.kinds.map((k) => k.kind)).toEqual(["checks", "crew"]);
152 for (const k of body.kinds) {
153 expect(k.slots).toBeGreaterThan(0);
154 expect(k.buckets).toHaveLength(96);
155 expect(k.bucketMs * k.buckets.length).toBe(24 * 3_600_000);
156 for (const b of k.buckets) expect(b.full).toBe(b.busy >= k.slots);
157 }
158 expect(body.live).toEqual(["run.queued", "run.started", "run.finished"]);
159 // the page's own figures say the same slots
160 const html = await (await get("/", owner)).text();
161 for (const k of body.kinds) expect(html).toContain(`data-kind="${k.kind}" `);
162 });
163
164 test("answers 304 to its ETag; no one but an admin of the forge has the graphs", async () => {
165 const tag = (await get("/api/v1/home/slots", owner)).headers.get("etag")!;
166 expect((await get("/api/v1/home/slots", owner, tag)).status).toBe(304);
167 expect((await get("/api/v1/home/slots", bob)).status).toBe(403);
168 expect((await anonymous("/api/v1/home/slots")).status).toBe(401);
169 });
170 });
171
172 describe("the document says what they answer", () => {
173 type Node = Record<string, unknown>;
174 const doc = openapi("http://forge.test", "1", "admin") as unknown as { paths: Record<string, Record<string, { responses: Record<string, { content?: Record<string, { schema: Node }> }> }>>; components: { schemas: Record<string, Node> } };
175
176 test.each(["lanes", "strip", "slots"])("/api/v1/home/%s answers the schema it declares, field for field", async (name) => {
177 const path = `/api/v1/home/${name}`;
178 const schema = doc.paths[path]!.get!.responses["200"]!.content!["application/json"]!.schema;
179 expect(misfits(await (await get(path, owner)).json(), schema, doc.components.schemas, "response")).toEqual([]);
180 });
181
182 test("a bearer token reads them as the person it belongs to", async () => {
183 const user = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'trevato'").get()!;
184 const bearer = { authorization: `Bearer ${createToken(app.db, user.id, "t", "ro").token}` };
185 const res = await fetch(`${servers.url}/api/v1/home/lanes?s=asked`, { headers: bearer });
186 expect(res.status).toBe(200);
187 });
188 });
189
190 describe("the terminal says the slots the page says", () => {
191 /** The home screen as the terminal draws it for this person on this forge. */
192 async function screenOf(forge: App, user: User): Promise<string> {
193 const { app: tui, session } = createForgeApp(
194 forge,
195 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
196 { terminal: headlessTerminal(140, 40), exitHooks: false },
197 );
198 tui.start();
199 tui.ctx.push(dashboardScreen(session, tui.ctx));
200 await settleApp(tui);
201 const text = tui.screen.toText();
202 tui.stop?.();
203 return text;
204 }
205 const userNamed = (forge: App, name: string): User => {
206 return getUserByName(forge.db, name)!;
207 };
208
209 test("an admin's home lists a line a kind, in the page's words", async () => {
210 const text = await screenOf(app, seeded.owner);
211 expect(text).toMatch(/Checks: \d+ (of \d+ slots busy|running, \d+ slots?)/);
212 expect(text).toMatch(/Crew runs: \d+ (of \d+ slots busy|running, \d+ slots?)/);
213 const html = await (await get("/", owner)).text();
214 expect(html).toMatch(/data-busy="\d+" data-slots="\d+"/);
215 });
216
217 test("a person who is not an admin sees no slots", async () => {
218 const text = await screenOf(app, userNamed(app, "bob"));
219 expect(text).not.toContain("Checks:");
220 expect(text).not.toContain("Crew runs:");
221 });
222
223 test("a client forge's owner sees no slots", async () => {
224 const forge = await claimedForge("forge-home-json-client-");
225 try {
226 const admin = forge.child.db.query<{ username: string }, []>("SELECT username FROM user WHERE is_admin = 1 LIMIT 1").get()!;
227 const text = await screenOf(forge.child, userNamed(forge.child, admin.username));
228 expect(text).not.toContain("Checks:");
229 expect(text).not.toContain("Crew runs:");
230 } finally {
231 await forge.stop();
232 }
233 });
234 });
test/openapi.test.ts +1 −1
@@ -41,7 +41,7 @@ test("every http route the manifest names is described", () => {
4141 });
4242
4343 test("every described route is registered in the router", () => {
44 const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/config.ts", "src/http/error_envelope.ts", "src/http/checks_recheck.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts", "src/http/games_routes.ts", "src/contract/served.ts",
44 const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/config.ts", "src/http/error_envelope.ts", "src/http/checks_recheck.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts", "src/http/games_routes.ts", "src/http/home_api.ts", "src/contract/served.ts",
4545 ...readdirSync("src/http/routes").map((f) => `src/http/routes/${f}`),
4646 ...readdirSync("src/http/api").map((f) => `src/http/api/${f}`)]
4747 .map((f) => readFileSync(f, "utf8"))

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

Keyboard shortcuts

Docs