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

Home feed you can catch up from in 15 seconds: a "since you were here" digest, honest counts, no dead buttons; validated by a cold-read agent each iteration #5736

Closed opened this in answer to
Closed without merging

scout/forge:scout/5735-home-feed-you-can-catch-up-from-in-15-se → main 3 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +481 −44
README.md +16 −1
@@ -346,6 +346,18 @@ or the last change landed in the past 7 days ("Last change: …, 3 days ago");
346346 a quiet app says nothing more. The terminal's first screen opens with the same
347347 lines, from the same queries (`src/core/client-apps.ts`).
348348
349 Above the feed, home has a **Last 24 h** digest: at most three lines, one per
350 repository, the biggest change first (`2 landed, 1 released`), each linked to
351 its evidence. It is built from the posts the timeline already read
352 (`src/feed/digest.ts`), over a fixed 24 hours, because the forge keeps no
353 last-seen time. The terminal's home shows the same lines above its figures.
354
355 Asks waiting over 30 days are counted apart as `N stale, archive?` and
356 collapsed on the asks page, where Archive leads to the bulk-dismiss preview.
357 The waiting count on home is the number of rows the asks page lists, the
358 forge's own needs included. A feed chip with nothing to filter among the
359 loaded posts is not drawn; one you switched off stays, so it can come back.
360
349361 Home shows nine figures first, from `src/flow/kpis.ts`: shipped per hour (with
350362 a 24 h sparkline), the live version and since when, the median check time, the crew builders
351363 running of their slots, and the crew's spend today of the forge's daily
@@ -353,7 +365,10 @@ ceiling (`FORGE_CREW_CEILING_USD`; without one, the spend alone and
353365 `no ceiling`), and the age of the last off-box backup (the newer of the
354366 mirror's newest snapshot, `mirror/state.json`, and the newest that landed in
355367 a destination that is a bucket, `snapshot/state.json`; `src/snapshot/off_box.ts`; `3 h ago`, the exact time in its title), linking to
356 `/settings/backups`. The spend tile links to `/settings/crew`, where the meter is.
368 `/settings/backups`. The spend tile links to `/settings/crew`, where the meter is. Once spend
369 passes the forge's ceiling the tile turns attention-toned and says
370 `ceiling hit 14:20Z, builders idle`; an account's own ceiling stops only
371 that account's repositories, so it is never shown as the forge's.
357372 The backup tile past 24 hours, or with none (`never`), takes the card's existing
358373 `data-tone="attn"` and says overdue in its label.
359374 The last three (`src/flow/reach.ts`, the `reach` board source's rows) are
src/feed/digest.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * The feed's top: what happened since the viewer was last here, in at most
3 * three lines, one per repository, the biggest change first. Built from the
4 * posts already read for the timeline, so every line links to its evidence
5 * and none says what the posts below do not.
6 */
7
8 import type { FeedItem } from "./rank.ts";
9
10 /** How many posts the home and the terminal read for the timeline and the digest. */
11 export const FEED_FIRST_PAGE = 20;
12 export const DIGEST_LINES = 3;
13 export const DIGEST_WINDOW_MS = 24 * 3_600_000;
14
15 /** What happened, ordered by how much it matters; the weight ranks a repository. */
16 const OUTCOMES = [
17 { word: "failed", weight: 4 },
18 { word: "landed", weight: 3 },
19 { word: "released", weight: 3 },
20 { word: "decided", weight: 2 },
21 { word: "opened", weight: 1 },
22 ] as const;
23 type Outcome = (typeof OUTCOMES)[number]["word"];
24
25 export interface DigestLine {
26 /** `owner/name`. */
27 readonly app: string;
28 /** `2 landed, 1 released`. */
29 readonly text: string;
30 /** The heaviest post in it: the evidence. */
31 readonly href: string;
32 readonly weight: number;
33 }
34
35 function outcomeOf(item: FeedItem): Outcome | undefined {
36 switch (item.kind) {
37 case "run":
38 return /\bfailed\b/.test(item.what) ? "failed" : undefined;
39 case "pull":
40 return item.what.startsWith("merged") ? "landed" : item.what.startsWith("opened") ? "opened" : undefined;
41 case "release":
42 return "released";
43 case "decision":
44 case "choose":
45 return "decided";
46 default:
47 return undefined;
48 }
49 }
50
51 const weightOf = (word: Outcome): number => OUTCOMES.find((o) => o.word === word)!.weight;
52
53 /** The digest of posts newer than the window, biggest repository first. */
54 export function digestOf(items: readonly FeedItem[], now: Date, windowMs = DIGEST_WINDOW_MS): DigestLine[] {
55 const since = now.getTime() - windowMs;
56 const groups = new Map<string, { counts: Map<Outcome, number>; best: { weight: number; href: string } }>();
57 for (const item of items) {
58 const word = outcomeOf(item);
59 if (word === undefined || Date.parse(item.at) < since) continue;
60 const g = groups.get(item.app) ?? { counts: new Map(), best: { weight: 0, href: item.link } };
61 g.counts.set(word, (g.counts.get(word) ?? 0) + 1);
62 if (weightOf(word) > g.best.weight) g.best = { weight: weightOf(word), href: item.link };
63 groups.set(item.app, g);
64 }
65 return [...groups.entries()]
66 .map(([app, g]): DigestLine => {
67 const parts = OUTCOMES.filter((o) => g.counts.has(o.word)).map((o) => `${g.counts.get(o.word)} ${o.word}`);
68 const weight = OUTCOMES.reduce((n, o) => n + (g.counts.get(o.word) ?? 0) * o.weight, 0);
69 return { app, text: parts.join(", "), href: g.best.href, weight };
70 })
71 .sort((a, b) => b.weight - a.weight || a.app.localeCompare(b.app))
72 .slice(0, DIGEST_LINES);
73 }
74
75 /** The same lines for the terminal: `Last 24 h` first, then one line per repository. */
76 export function digestWords(lines: readonly DigestLine[]): string[] {
77 return lines.length === 0 ? [] : ["Last 24 h", ...lines.map((l) => ` ${l.app}: ${l.text}`)];
78 }
src/flow/ceiling.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * Why builders are idle, for the figures. Only the forge-wide daily ceiling
3 * (FORGE_CREW_CEILING_USD) stops every builder; an account's own ceiling
4 * (`core/account_ceiling.ts`) stops only that account's repositories, so it
5 * is never read as the forge's. Null: none set.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { dayStart } from "../core/account_ceiling.ts";
10
11 /**
12 * When today's (UTC) agent spend crossed the ceiling: the creation time of the
outdated

High: MAX of per-account ceilings is not a forge ceiling. ceilingReachedAt then sums every account's agent spend against it, so "builders idle" can show while they all run. Use only the forge cap here, or compare each account's spend with its own ceiling.

13 * run that took the running total over it. Null while under, or with none.
14 */
15 export function ceilingReachedAt(db: Database, ceilingUsd: number | null, now: Date): string | null {
16 if (ceilingUsd === null) return null;
17 const runs = db
18 .query<{ at: string; cost: number | null }, [string]>(
19 "SELECT created_at AS at, cost_usd AS cost FROM run WHERE kind = 'agent' AND created_at >= ?1 ORDER BY created_at",
20 )
21 .all(dayStart(now));
22 let total = 0;
23 for (const r of runs) {
24 total += r.cost ?? 0;
25 if (total >= ceilingUsd) return r.at;
26 }
27 return null;
28 }
src/flow/kpi_words.ts +16 −5
@@ -45,6 +45,13 @@ export function spendValue(s: Kpis["spend"]): string {
4545 return s.ceilingUsd === null ? whole(s.todayUsd) : `${whole(s.todayUsd)} of ${whole(s.ceilingUsd)}`;
4646 }
4747
48 /** Under the spend: the ceiling, or why the builders sit idle once it is reached. */
49 export function spendNote(s: Kpis["spend"]): string {
50 if (s.ceilingUsd === null) return "no ceiling";
51 if (s.reachedAt) return `ceiling hit ${s.reachedAt.slice(11, 16)}Z, builders idle`;
52 return "of the daily ceiling";
53 }
54
4855 /** The same figure to the cent, for the title. */
4956 export function spendFull(s: Kpis["spend"]): string {
5057 return s.ceilingUsd === null ? cents(s.todayUsd) : `${cents(s.todayUsd)} of ${cents(s.ceilingUsd)}`;
@@ -99,13 +106,17 @@ export function reactNote(r: Reach): string {
99106 return r.inpP75 === null ? "no taps measured yet" : `reacts in ${speedWords(r.inpP75)}`;
100107 }
101108
109 /** Asks older than this are stale: collapsed, not counted as urgent. */
110 export const STALE_DAYS = 30;
111
102112 /** Home's one line over /review: `3 waiting on you, oldest 50 h`; null at zero, so the line is absent. */
103 export function waitingWords(count: number, oldestAt: string | null, now: Date): string | null {
104 if (count <= 0) return null;
113 export function waitingWords(count: number, oldestAt: string | null, now: Date, stale = 0): string | null {
114 const tail = stale > 0 ? `${count > 0 ? ", " : ""}${stale} stale, archive?` : "";
115 if (count <= 0) return stale > 0 ? tail : null;
105116 const t = oldestAt === null ? NaN : Date.parse(oldestAt);
106 if (Number.isNaN(t)) return `${count} waiting on you`;
117 if (Number.isNaN(t)) return `${count} waiting on you${tail}`;
107118 const h = Math.max(0, Math.floor((now.getTime() - t) / 3_600_000));
108 return `${count} waiting on you, oldest ${h < 1 ? "under 1" : h} h`;
119 return `${count} waiting on you, oldest ${h < 1 ? "under 1" : h} h${tail}`;
109120 }
110121
111122 /**
@@ -118,7 +129,7 @@ export function kpiLines(k: Kpis, live: { sha: string; since: string } | null, n
118129 `Live version ${live === null ? "— nothing live yet" : `${live.sha.slice(0, 7)}, live ${live.since}`}`,
119130 `Median check time ${checkTime(k.medianCheckMs)}`,
120131 `Builders running ${buildersValue(k.builders)}${k.builders.slots === 0 ? ", no slots set" : ""}`,
121 `Crew spend today ${spendValue(k.spend)}${k.spend.ceilingUsd === null ? ", no ceiling" : ""}`,
132 `Crew spend today ${spendValue(k.spend)}${k.spend.ceilingUsd === null ? ", no ceiling" : k.spend.reachedAt ? `, ${spendNote(k.spend)}` : ""}`,
122133 `Last off-box backup ${backupAge(k.backupAt, now)}${backupOverdue(k.backupAt, now) ? ", overdue" : ""}`,
123134 `Visitors ${visitorsValue(k.reach)}, ${visitorsNote(k.reach)} ${trendText(k.reach.visitorDays)} 30 days`,
124135 `Accounts ${usersValue(k.reach)} signed in today`,
src/flow/kpis.ts +3 −2
@@ -15,6 +15,7 @@
1515
1616 import type { Database } from "bun:sqlite";
1717 import { spentTodayEverywhere } from "../crew/autonomy.ts";
18 import { ceilingReachedAt } from "./ceiling.ts";
1819 import { lastOffBox } from "../snapshot/off_box.ts";
1920 import { readReach, type Reach } from "./reach.ts";
2021 import { HOURS, median } from "./throughput.ts";
@@ -33,7 +34,7 @@ export interface Kpis {
3334 /** Crew builders running now, of the slots the autonomous repositories are set to. */
3435 readonly builders: { readonly running: number; readonly slots: number };
3536 /** What the crew's runs cost since UTC midnight, and the forge's daily ceiling (null: none set). */
36 readonly spend: { readonly todayUsd: number; readonly ceilingUsd: number | null };
37 readonly spend: { readonly todayUsd: number; readonly ceilingUsd: number | null; readonly reachedAt: string | null };
3738 /** When a snapshot was last known off the machine (a bucket destination or the mirror, `off_box.ts`); null when never. */
3839 readonly backupAt: string | null;
3940 /** Accounts, visitors and page speed (`reach.ts`). */
@@ -100,7 +101,7 @@ export function readKpis(
100101 backupAt,
101102 builders,
102103 reach: readReach(db, now),
103 spend: { todayUsd, ceilingUsd: forge.ceilingUsd },
104 spend: { todayUsd, ceilingUsd: forge.ceilingUsd, reachedAt: forge.ceilingUsd !== null && todayUsd >= forge.ceilingUsd ? ceilingReachedAt(db, forge.ceilingUsd, now) : null },
104105 landedHours,
105106 landed: landedHours.reduce((a, b) => a + b, 0),
106107 live: live ?? null,
src/tui/screens/dashboard.ts +13
@@ -88,6 +88,8 @@ import {
8888 plural,
8989 linkScreen,
9090 } from "./common.ts";
91 import { digestOf, digestWords, FEED_FIRST_PAGE } from "../../feed/digest.ts";
92 import { readFeed } from "../../feed/feed.ts";
9193 import { readKpis } from "../../flow/kpis.ts";
9294 import { kpiLines } from "../../flow/kpi_words.ts";
9395 import { BOOTED } from "../../release/gate.ts";
@@ -179,6 +181,8 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
179181 let decider: string | null = null;
180182 /** Home's three figures, as the web's row says them; empty unless an admin looks (they count every repository). */
181183 let figures: string[] = [];
184 /** The web feed's top: what happened in the last 24 h, up to three lines (`feed/digest.ts`). */
185 let digest: string[] = [];
182186 /** The panels this admin pinned to the web home, by title and board, in their order. */
183187 let panelLines: string[] = [];
184188 const filter = new Filter();
@@ -195,6 +199,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
195199 if (!f.user || (await nextStepsFor(f.app, f.user)) === undefined) return;
196200 // A client's home never carries the forge-wide figures, on either door.
197201 figures = [];
202 digest = [];
198203 const apps = await clientAppRows(f.app, f.user);
199204 clientRepoIds = new Set(apps.map((a) => a.repo.id));
200205 clientLive = new Map(apps.flatMap((a) => (a.live === undefined ? [] : [[a.repo.id, a.live] as const])));
@@ -253,6 +258,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
253258 waits = ownerWaits(f.db, all.filter((r) => facts.has(r.id))).map(waitLine);
254259 lane = forgeLane(f.app, f.user);
255260 decider = deciderLine(f.app, f.user);
261 digest = f.user === undefined ? [] : digestWords(digestOf(readFeed(f.db, f.user, { limit: FEED_FIRST_PAGE, withoutAsks: true }).items, now));
256262 const commit = running().commit;
257263 figures =
258264 f.user?.isAdmin !== true
@@ -802,6 +808,13 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
802808 );
803809 body = rest!;
804810 }
811 if (digest.length > 0) {
812 const [strip, rest] = split(body, "v", [len(digest.length), fill(1)]);
813 digest.forEach((line, i) =>
814 s.text(strip!.x, strip!.y + i, truncate(line, strip!.w), style(c.fg, c.bg), strip!.x + strip!.w),
815 );
816 body = rest!;
817 }
805818 // A short terminal drops the last figures before it drops the list.
806819 const shown = figures.slice(0, Math.max(0, body.h - FIGURES_ROOM));
807820 if (shown.length > 0) {
src/web/studio/asks.ts +15 −2
@@ -19,6 +19,7 @@ import { lastPersonAction, recommendationsFor, waitWords, WAIT_LIMIT_MS, type Re
1919 import { getHold, holdsFor } from "../../core/holds.ts";
2020 import { issueTitles, proposalsFor, type Proposal } from "../../core/proposals.ts";
2121 import { chipsOf, type Chips } from "../../core/feed_chips.ts";
22 import { STALE_DAYS } from "../../flow/kpi_words.ts";
2223 import { chipHides } from "../../feed/chips.ts";
2324 import { askDismissals, mutedRepos } from "../../core/interactions.ts";
2425 import { askMeasure, syncAskLedger, type AskEnd } from "../../core/ask_ledger.ts";
@@ -138,6 +139,8 @@ export interface Decision {
138139 readonly consequence: Consequence;
139140 /** What it waits for, and on whom (`core/waiting_for.ts`). */
140141 readonly waiting: WaitingFor;
142 /** When it began to ask; past 30 days it is stale. */
143 readonly since: string;
141144 readonly why?: string | undefined;
142145 readonly recommendation?: Recommendation | undefined;
143146 }
@@ -1120,7 +1123,7 @@ export function decisionsFor(
11201123 look && lookUrl(repoBase(repo), look)
11211124 );
11221125 };
1123 const worded = (c: Scored): Omit<Decision, "consequence" | "waiting"> => {
1126 const worded = (c: Scored): Omit<Decision, "consequence" | "waiting" | "since"> => {
11241127 if (c.kind === "assigned") {
11251128 const thing = c.pull ?? c.issue!;
11261129 return {
@@ -1253,6 +1256,7 @@ export function decisionsFor(
12531256 preview: previewOf(c),
12541257 consequence: c.consequence,
12551258 waiting: c.waiting,
1259 since: c.since,
12561260 }));
12571261 }
12581262 /** The id of the form a row's own button submits (see `decisionForm`). */
@@ -1394,6 +1398,15 @@ export function forgeNeedsFor(ctx: Ctx, user: User | undefined): Degraded[] {
13941398 return forgeVitals(ctx.app).degraded;
13951399 }
13961400
1401 /** Asks that have waited past `STALE_DAYS` are stale: kept apart, never counted as urgent. */
1402 export function splitStale<T extends { since: string }>(asks: readonly T[], now: Date = new Date()): { fresh: T[]; stale: T[] } {
1403 const cut = now.getTime() - STALE_DAYS * 86_400_000;
1404 const fresh: T[] = [];
1405 const stale: T[] = [];
1406 for (const a of asks) (Date.parse(a.since) < cut ? stale : fresh).push(a);
1407 return { fresh, stale };
1408 }
1409
13971410 /**
13981411 * How many things ask the viewer: the one number the studio header and the
13991412 * asks page both show. It counts the rows the cards are made into
@@ -1404,7 +1417,7 @@ export function askCountFor(ctx: Ctx, user: User | undefined): number {
14041417 if (!user) return 0;
14051418 const repos = listReposVisibleTo(ctx.app.db, user, { limit: 200, withoutArchived: true });
14061419 return (
1407 askRows(waitingOn(ctx.app.db, user, repos)).length +
1420 askRows(splitStale(waitingOn(ctx.app.db, user, repos)).fresh).length +
14081421 forgeNeedsFor(ctx, user).length
14091422 );
14101423 }
src/web/studio/asks_page.ts +19 −2
@@ -46,6 +46,7 @@ import { btn, card, icon, row } from "../ui.ts";
4646 import {
4747 askAnchor,
4848 askRows,
49 splitStale,
4950 askSentence,
5051 ASK_WORDS,
5152 ROW_PLURAL,
@@ -392,7 +393,9 @@ export function needsYouSection(
392393 // Callers that build the section outside a request have none to time against.
393394 const decisions = ctx.request instanceof Request ? timePhase(ctx.request, "asks", read) : read();
394395 const needs = forgeNeedsFor(ctx, user);
395 const rows = askRows(decisions);
396 const split = splitStale(decisions);
397 const rows = askRows(split.fresh);
398 const staleRows = askRows(split.stale);
396399 const silenced = silencedRepos(ctx.app.db, user);
397400 const silencedNote =
398401 silenced.length === 0
@@ -430,7 +433,7 @@ export function needsYouSection(
430433 <span class="muted small">kept for a day</span>
431434 </form>`;
432435 const count = rows.length + needs.length;
433 if (count === 0 && top === undefined)
436 if (count === 0 && staleRows.length === 0 && top === undefined)
434437 return {
435438 body: html`<h2 id="asks-sentence" class="sr-only">${askSentence(0)}</h2>${silencedNote}${asideNote}${undo}`,
436439 scriptJs: "",
@@ -483,6 +486,20 @@ export function needsYouSection(
483486 ${reasonInput(top?.reason)} ${btn("Preview", { size: "sm" })}
484487 <span class="muted small">on the selected asks</span>
485488 </form>`}
489 ${staleRows.length === 0
490 ? null
491 : html`<details id="asks-stale">
492 <summary>${staleRows.length} stale, archive?</summary>
493 <div class="stack mt">
494 <form method="post" action="/asks/bulk" class="bar">
495 <input type="hidden" name="action" value="dismiss" />
496 ${split.stale.map((d) => html`<input type="hidden" name="item" value="${d.id}" />`)}
497 ${btn(`Archive ${staleRows.length}`, { size: "sm" })}
498 <span class="muted small">waiting over 30 days; you see a preview first</span>
499 </form>
500 ${staleRows.map((r) => mutableRow(ctx, r, picked))}
501 </div>
502 </details>`}
486503 ${silencedNote} ${asideNote} ${undo}
487504 ${decisions.map((d) => decisionForm(d, ctx.url.pathname))}
488505 </section>`;
src/web/studio/change.ts +1
@@ -480,6 +480,7 @@ async function changeConversation(
480480 : "This app does not wait on the check to ship. Look at the preview, then ship it or say what is off.",
481481 short: word === "look" ? "the check is green" : "ready to ship",
482482 consequence: KIND_TIER.look,
483 since: pull.createdAt,
483484 waiting: waitingFor({
484485 kind: "look",
485486 conflicts: conflicted ? 1 : 0,
src/web/studio/feed.ts +23 −2
@@ -15,6 +15,8 @@ import type { Ctx } from "../../http/context.ts";
1515 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1616 import { placementsOf, type Placement } from "../../core/placements.ts";
1717 import { recentThoughts, type Thought } from "../../core/thoughts.ts";
18 import { chipOfKind } from "../../feed/chips.ts";
19 import { digestOf, FEED_FIRST_PAGE } from "../../feed/digest.ts";
1820 import { readFeed } from "../../feed/feed.ts";
1921 import type { FeedItem } from "../../feed/rank.ts";
2022 import { html, type Html } from "../html.ts";
@@ -27,7 +29,6 @@ import { writableAppsOf } from "./asks.ts";
2729 export const FEED_LIVE =
2830 "run.finished,issue.opened,issue.commented,pull.commented,pull.opened,pull.merged,pull.reviewed,pull.closed,look.taken,app.serving,issue.blocked,issue.unblocked,issue.closed,decision.*,thought.received,thought.placed";
2931
30 export const FEED_FIRST_PAGE = 20;
3132
3233 const RUN_LINK = /^\/[^/]+\/[^/]+\/runs\/[A-Za-z0-9_-]+$/;
3334
@@ -233,11 +234,30 @@ function chipsBar(user: User, ctx: Ctx, items: readonly FeedItem[]): Html {
233234 aria-pressed="${String(shown)}"
234235 >${label}</button>`;
235236 return html`<div class="bar feed-chips" role="group" aria-label="Filter the feed">
236 ${KIND_CHIPS.map((k) => chip("kind", k, CHIP_LABEL[k], !chips.kinds.has(k)))}
237 ${KIND_CHIPS.flatMap((k) => {
238 // A chip that would change nothing is not drawn (no dead buttons); one
239 // switched off stays, so it can come back.
240 const shown = !chips.kinds.has(k);
241 return shown && !items.some((i) => chipOfKind(i.kind) === k) ? [] : [chip("kind", k, CHIP_LABEL[k], shown)];
242 })}
237243 ${[...names].sort().map((n) => chip("person", n, n, !hiddenNames.has(n)))}
238244 </div>`;
239245 }
240246
247 /** The last 24 hours: at most three lines, each a repository and what happened in it, linked to the evidence. */
248 function digestCard(items: readonly FeedItem[]): Html | null {
outdated

The digest exists only on the web. Give the terminal the same three lines, and say in the README where both live.

249 const lines = digestOf(items, new Date());
250 if (lines.length === 0) return null;
251 return html`<section class="stack stack-tight" id="digest" aria-label="What happened in the last 24 hours">
252 <h2 class="small muted">Last 24 h</h2>
253 <ul class="list">
254 ${lines.map(
255 (l) => html`<li class="row"><a href="${l.href}"><strong>${l.app}</strong>: ${l.text}</a></li>`,
256 )}
257 </ul>

Use row() here, not a hand-written <li class="row">, so the digest line has the named component's lead, title and meta, and the design lint stays meaningful.

258 </section>`;
259 }
260
241261 /** What the region shows, read: the posts, the thoughts, where they sit, who posted. */
242262 function readRegion(user: User, ctx: Ctx) {
243263 // What needs you is pinned above the timeline (`needsYouSection`), so an
@@ -267,6 +287,7 @@ function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>):
267287 data-live="${FEED_LIVE}"
268288 data-live-src="/live/feed"
269289 >
290 ${digestCard(items)}
270291 ${chipsBar(user, ctx, items)}
271292 ${thoughts.map((t) => thoughtCard(t, user.username, placed.get(t.id)))}
272293 ${items.length === 0 && thoughts.length === 0
src/web/studio/home.ts +1 −1
@@ -259,7 +259,7 @@ export async function studioHome(
259259 ${ask} ${address} ${figures
260260 ? timePhase(ctx.request, "kpis", () => kpiRow(ctx.app.db, kpiOpts), () => kpiCache(ctx.app.db))
261261 : liveLine(ctx)}
262 ${timePhase(ctx.request, "waiting", () => waitingLine(ctx.app.db, user))}
262 ${timePhase(ctx.request, "waiting", () => waitingLine(ctx, user))}
263263 ${figures
264264 ? await timePhaseAsync(ctx.request, "panels", () => pinnedPanels(ctx.app, user), () => panelCache(ctx.app.db))
265265 : null}
src/web/studio/kpi_row.ts +16 −9
@@ -8,7 +8,7 @@
88 */
99
1010 import type { Database } from "bun:sqlite";
11 import { backupAge, backupFull, backupOverdue, buildersValue, checkTime, reactNote, speedWords, spendFull, spendValue, usersValue, visitorsNote, visitorsValue, waitingWords } from "../../flow/kpi_words.ts";
11 import { backupAge, backupFull, backupOverdue, buildersValue, checkTime, spendNote, reactNote, speedWords, spendFull, spendValue, usersValue, visitorsNote, visitorsValue, waitingWords } from "../../flow/kpi_words.ts";
1212 import type { Kpis } from "../../flow/kpis.ts";
1313 import { cachedKpis } from "./home_cache.ts";
1414 import { escapeHtml, html, raw, type Html } from "../html.ts";
@@ -17,7 +17,8 @@ import { running } from "../../kernel/version.ts";
1717 import { sha, stat, time } from "../ui.ts";
1818 import { listReposVisibleTo } from "../../core/repos.ts";
1919 import type { User } from "../../core/users.ts";
20 import { waitingOn } from "./asks.ts";
20 import type { Ctx } from "../../http/context.ts";
21 import { askRows, forgeNeedsFor, splitStale, waitingOn } from "./asks.ts";
2122
2223 const W = 96;
2324 const H = 24;
@@ -131,8 +132,10 @@ export function kpiRowFor(k: Kpis, live: { sha: string; at: string } | null, now
131132 "/settings/crew",
132133 spendValue(k.spend),
133134 spendFull(k.spend),
134 k.spend.ceilingUsd === null ? "no ceiling" : "of the daily ceiling",
135 spendNote(k.spend),
135136 k.spend.ceilingUsd === null ? "No daily ceiling is set" : "Crew spend today (UTC), of the daily ceiling",
137 null,
138 k.spend.reachedAt ? "attn" : null,
136139 )}
137140 ${tile(
138141 "Last off-box backup",
@@ -165,13 +168,17 @@ export function kpiRow(db: Database, opts: { ceilingUsd?: number; dataDir?: stri
165168 }
166169
167170 /**
168 * One `.small .muted` line over `/review`: how many asks wait on the viewer
169 * (the very rows /review lists) and how long the oldest has. Empty at zero.
171 * One `.small .muted` line over `/review`: how many things wait on the viewer
172 * (the very rows /review lists, the forge's own needs among them) and how
173 * long the oldest has; asks past 30 days are counted apart as stale. Empty at zero.
170174 */
171 export function waitingLine(db: Database, user: User, now: Date = new Date()): Html {
175 export function waitingLine(ctx: Ctx, user: User, now: Date = new Date()): Html {
176 const db = ctx.app.db;
172177 const repos = listReposVisibleTo(db, user, { limit: 200, withoutArchived: true });
173 const asks = waitingOn(db, user, repos);
174 const oldest = asks.reduce<string | null>((o, a) => (o === null || Date.parse(a.since) < Date.parse(o) ? a.since : o), null);
175 const words = waitingWords(asks.length, oldest, now);
178 const { fresh, stale: old } = splitStale(waitingOn(db, user, repos), now);
179 const count = askRows(fresh).length + forgeNeedsFor(ctx, user).length;
180 const stale = askRows(old).length;
181 const oldest = fresh.reduce<string | null>((o, a) => (o === null || Date.parse(a.since) < Date.parse(o) ? a.since : o), null);

This runs forgeNeedsFor plus a full ask scan on every home render. Measure it with Server-Timing; the preview's / takes 1.3 to 2.5 s.

182 const words = waitingWords(count, oldest, now, stale);
176183 return words === null ? html`` : html`<p class="small muted"><a href="/review">${words}</a></p>`;
177184 }
test/feed-chips.test.ts +18
@@ -179,6 +179,24 @@ describe("the chips of a forge", () => {
179179 setChip(app.db, bob.id, { kind: "kind", value: "crew" }, false);
180180 });
181181
182 test("every chip drawn changes the feed: one with nothing to filter is not drawn, a switched-off one stays", async () => {
183 const session = createSession(app.db, bob.id);
184 const cookie = { cookie: `forge_session=${session.token}` };
185 const drawn = async () =>
186 [...(await (await fetch(`${servers.url}/live/feed`, { headers: cookie })).text()).matchAll(/data-chip="kind"\s+data-value="(\w+)"/g)].map((m) => m[1]);
187 expect(await drawn()).toEqual(["reviews", "crew", "releases"]);
188 // Pressing each one removes posts of its kind, and only drawn chips do.
189 for (const chip of await drawn()) {
190 const before = kinds(bob).length;
191 await call(bobToken, "POST", "/api/v1/feed/chips", { kind: "kind", value: chip, hidden: true });
192 expect(kinds(bob).length).toBeLessThan(before);
193 expect(await drawn()).toContain(chip);
194 await call(bobToken, "POST", "/api/v1/feed/chips", { kind: "kind", value: chip, hidden: false });
195 }
196 const page = await (await fetch(`${servers.url}/live/feed`, { headers: cookie })).text();
197 expect(page).toContain('id="digest"');
198 });
199
182200 test("a pressed chip refreshes the region in place and says when it failed", async () => {
183201 const handler = feedJs.slice(feedJs.indexOf("function chip(c)"), feedJs.indexOf("feed.addEventListener('click'"));
184202 expect(handler).not.toContain("location.reload");
test/home-digest.test.ts added +71
@@ -0,0 +1,71 @@
1 /**
2 * #5735: the feed's top says what happened in three lines; the spend says
3 * why builders are idle; the waiting count matches the list and stale asks
4 * stand apart; a chip that would change nothing is not drawn.
5 */
6 import { describe, expect, test } from "bun:test";
7 import { digestOf, digestWords } from "../src/feed/digest.ts";
8 import type { FeedItem } from "../src/feed/rank.ts";
9 import { waitingWords } from "../src/flow/kpi_words.ts";
10 import { splitStale } from "../src/web/studio/asks.ts";
11
12 const now = new Date("2026-10-25T18:00:00.000Z");
13 const item = (app: string, kind: FeedItem["kind"], what: string, hoursAgo = 1): FeedItem => ({
14 id: `${app}${kind}${what}${hoursAgo}`,
15 kind,
16 app,
17 actor: null,
18 at: new Date(now.getTime() - hoursAgo * 3_600_000).toISOString(),
19 link: `/${app}/${kind}`,
20 what,
21 reason: "",
22 score: 0,
23 });
24
25 describe("the digest", () => {
26 test("groups by repository, biggest first, at most three lines, each linked", () => {
27 const lines = digestOf(
28 [
29 item("a/one", "pull", "merged a pull request: x"),
30 item("b/two", "pull", "merged a pull request: y"),
31 item("b/two", "pull", "merged a pull request: z"),
32 item("b/two", "release", "a new version is serving"),
33 item("c/three", "run", "a check run failed"),
34 item("d/four", "pull", "opened a pull request: q"),
35 item("e/five", "tell", "said hi"),
36 ],
37 now,
38 );
39 expect(lines.map((l) => l.app)).toEqual(["b/two", "c/three", "a/one"]);
40 expect(lines[0]!.text).toBe("2 landed, 1 released");
41 expect(lines[1]!.text).toBe("1 failed");
42 expect(lines.every((l) => l.href.startsWith("/"))).toBe(true);
43 });
44
45 test("the terminal says the same lines", () => {
46 const words = digestWords(digestOf([item("a/one", "pull", "merged a pull request: x")], now));
47 expect(words).toEqual(["Last 24 h", " a/one: 1 landed"]);
48 expect(digestWords([])).toEqual([]);
49 });
50
51 test("older than a day is not 'since you were here'", () => {
52 expect(digestOf([item("a/one", "release", "a new version is serving", 30)], now)).toEqual([]);
53 });
54 });
55
56 describe("waiting and stale", () => {
57 test("30 days is the line; stale is counted apart", () => {
58 const { fresh, stale } = splitStale(
59 [{ since: "2026-10-20T00:00:00.000Z" }, { since: "2026-06-20T00:00:00.000Z" }],
60 now,
61 );
62 expect(fresh).toHaveLength(1);
63 expect(stale).toHaveLength(1);
64 });
65
66 test("the words keep stale out of the urgent count", () => {
67 expect(waitingWords(3, "2026-10-24T10:00:00.000Z", now, 2)).toBe("3 waiting on you, oldest 32 h, 2 stale, archive?");
68 expect(waitingWords(0, null, now, 2)).toBe("2 stale, archive?");
69 expect(waitingWords(0, null, now)).toBeNull();
70 });
71 });
test/home-honest.test.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * #5735, end to end: the spend never says builders are idle for a ceiling
3 * that is not the forge's; the waiting count on home is the list's count,
4 * the forge's own needs included; stale asks stand apart; the terminal
5 * shows the digest; the chips drawn are chips that change something.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { setAccountCeiling } from "../src/core/account_ceiling.ts";
13 import { setAssignee, createIssue } from "../src/core/issues.ts";
14 import { createRepo, type Repo } from "../src/core/repos.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import type { User } from "../src/core/users.ts";
17 import { readKpis } from "../src/flow/kpis.ts";
18 import { ERROR_BURST } from "../src/kernel/vitals.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import type { Ctx } from "../src/http/context.ts";
21 import { askCountFor } from "../src/web/studio/asks.ts";
22 import { kpiRowFor } from "../src/web/studio/kpi_row.ts";
23 import { createForgeApp } from "../src/tui/forge.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26 import { settleApp } from "./helpers/tui.ts";
27 import { seedAdmin } from "./helpers/admin.ts";
28
29 quietLogs();
30
31 let dir: string;
32 let app: App;
33 let servers: Servers;
34 let alice: User;
35 let bob: User;
36 let repo: Repo;
37 let cookie: string;
38
39 const now = new Date();
40 const get = async (path: string): Promise<string> =>
41 (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
42 const ctxOf = (user: User) => ({ app, auth: { user }, url: new URL("http://x/") }) as unknown as Ctx;
43
44 beforeAll(async () => {
45 dir = await mkdtemp(join(tmpdir(), "forge-home-honest-"));
46 app = createApp({ dataDir: dir, port: 0 });
47 servers = await serve(app);
48 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
49 const b = await seedAdmin(app, { username: "bob", email: "[email protected]", password: "a-long-passphrase" });
50 if (!a.ok || !b.ok) throw new Error("seed");
51 alice = a.value;
52 bob = b.value;
53 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
54 const r = await createRepo(app.db, app.reposRoot, { ownerId: bob.id, ownerName: "bob", name: "open", visibility: "public" } as never);
55 if (!r.ok) throw new Error("repo");
56 repo = r.value;
57 }, 30_000);
58
59 afterAll(async () => {
60 servers.stop();
61 app.close();
62 await rm(dir, { recursive: true, force: true });
63 });
64
65 const agent = (cost: number) =>
66 app.db
67 .query("INSERT INTO run (id, repo_id, kind, state, cost_usd, created_at) VALUES (?1, ?2, 'agent', 'ok', ?3, ?4)")
68 .run(crypto.randomUUID(), repo.id, cost, now.toISOString());
69
70 describe("the spend tile", () => {
71 test("another account's ceiling is never the forge's: $15 spent against alice's $10 says no ceiling", async () => {
72 expect(setAccountCeiling(app.db, alice.id, 10, 5, alice.id, now)).toBe(true);
73 agent(15);
74 const k = readKpis(app.db, now);
75 expect(k.spend).toEqual({ todayUsd: 15, ceilingUsd: null, reachedAt: null });
76 const page = await get("/");
77 expect(page).toContain("no ceiling");
78 expect(page).not.toContain("builders idle");
79 });
80
81 test("the forge's own ceiling, once passed, names when and turns the tile attention-toned", () => {
82 const k = readKpis(app.db, now, { ceilingUsd: 10 });
83 expect(k.spend.reachedAt).toBe(now.toISOString());
84 const tile = (kk: typeof k) =>
85 kpiRowFor(kk, null, now).toString().match(/<a class="stat"[^>]*Crew spend today[^>]*>[\s\S]*?<\/a>/)![0];
86 const hit = tile(k);
87 expect(hit).toContain("builders idle");
88 expect(hit).toContain('data-tone="attn"');
89 const under = readKpis(app.db, now, { ceilingUsd: 100 });
90 expect(under.spend.reachedAt).toBeNull();
91 expect(tile(under)).not.toContain("builders idle");
92 expect(tile(under)).not.toContain("data-tone");
93 });
94 });
95
96 describe("the waiting count", () => {
97 test("home's count is the asks page's count, the forge's own need among the rows; stale asks stand apart", async () => {
98 for (let i = 0; i < ERROR_BURST; i++) app.signals.errors.record("test", "boom", Date.now());
99 const mine = createIssue(app.db, { repoId: repo.id, authorId: bob.id, title: "fresh one", body: "" });
100 const old = createIssue(app.db, { repoId: repo.id, authorId: bob.id, title: "old one", body: "" });
101 if (!mine.ok || !old.ok) throw new Error("issue");
102 setAssignee(app.db, mine.value.id, alice.id);
103 setAssignee(app.db, old.value.id, alice.id);
104 app.db.query("UPDATE issue SET updated_at = ?2 WHERE id = ?1").run(old.value.id, new Date(now.getTime() - 40 * 86_400_000).toISOString());
105
106 const count = askCountFor(ctxOf(alice), alice);
107 expect(count).toBeGreaterThanOrEqual(2); // the fresh assignment and the degraded forge
108 const home = await get("/");
109 expect(home).toContain(`${count} waiting on you`);
110 expect(home).toContain("1 stale, archive?");
111 const asks = await get("/asks");
112 expect(asks).toContain(`${count} things need you`);
113 // The stale one is behind the fold, with an Archive that leads to the preview.
114 expect(asks).toContain('id="asks-stale"');
115 expect(asks).toMatch(/<summary>1 stale, archive\?<\/summary>/);
116 expect(asks).toContain('name="item" value="assigned:' + old.value.id + '"');
117 expect(asks).toContain("Archive 1");
118 expect(asks).not.toContain('name="item" value="assigned:' + mine.value.id + '"');
119 });
120 });
121
122 describe("the terminal", () => {
123 test("shows the digest above the figures, from the same posts", async () => {
124 app.bus.append({ kind: "pull.merged", repoId: repo.id, actorId: bob.id, payload: { number: 1 } });
125 const terminal = headlessTerminal(200, 40);
126 const { app: screen } = createForgeApp(
127 app,
128 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: alice },
129 { terminal, exitHooks: false },
130 );
131 screen.start();
132 await settleApp(screen);
133 const text = screen.screen.toText();
134 screen.stop();
135 expect(text).toContain("Last 24 h");
136 expect(text).toContain("bob/open: 1 landed");
137 expect(text.indexOf("Last 24 h")).toBeLessThan(text.indexOf("Shipped per hour"));
138 });
139
140 test("the web home says the same line", async () => {
141 expect(await get("/")).toMatch(/id="digest"[\s\S]*bob\/open<\/strong>: 1 landed/);
142 });
143 });
test/home-kpi-row.test.ts +19 −19
@@ -21,7 +21,7 @@ const hours = (n: number) => Array.from({ length: 24 }, (_, i) => (i === 3 ? n :
2121 describe("home kpi row", () => {
2222 test("five tiles with their links and figures", () => {
2323 const out = kpiRowFor(
24 { landedHours: hours(6), landed: 6, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH },
24 { landedHours: hours(6), landed: 6, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH },
2525 { sha: "abcdef0123456", at: "2026-10-19T11:00:00.000Z" },
2626 ).toString();
2727 expect(out).toContain('<span class="sha">abcdef0</span>');
@@ -36,7 +36,7 @@ describe("home kpi row", () => {
3636
3737 test("the whole figure is in the title and the link's label, rounded and in studio words", () => {
3838 const out = kpiRowFor(
39 { landedHours: hours(7), landed: 7, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH },
39 { landedHours: hours(7), landed: 7, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH },
4040 { sha: "abcdef0123456", at: "2026-10-19T11:00:00.000Z" },
4141 ).toString();
4242 expect(out).toContain('title="0.29"');
@@ -48,13 +48,13 @@ describe("home kpi row", () => {
4848 });
4949
5050 test("empty figures say so", () => {
51 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null }, medianCheckMs: null, backupAt: null, reach: NO_REACH }, null).toString();
51 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null }, medianCheckMs: null, backupAt: null, reach: NO_REACH }, null).toString();
5252 expect(out).toContain("Nothing live yet");
5353 expect(out).toContain("No check finished in 24 h");
5454 });
5555
5656 test("no git words render, not even in a title or label", () => {
57 const out = kpiRowFor({ landedHours: hours(1), landed: 1, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null }, medianCheckMs: 1000, backupAt: null, reach: NO_REACH }, null).toString();
57 const out = kpiRowFor({ landedHours: hours(1), landed: 1, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null }, medianCheckMs: 1000, backupAt: null, reach: NO_REACH }, null).toString();
5858 expect(out).not.toMatch(/commit|merge|branch|repositor|pull request|checks (passed|failed)/i);
5959 });
6060
@@ -78,7 +78,7 @@ describe("home kpi row", () => {
7878 });
7979
8080 test("a truncated note carries its whole text as a title", () => {
81 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null }, medianCheckMs: null, backupAt: null, reach: NO_REACH }, null).toString();
81 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null }, medianCheckMs: null, backupAt: null, reach: NO_REACH }, null).toString();
8282 expect(out).toContain('title="No check finished in 24 h"');
8383 });
8484
@@ -91,7 +91,7 @@ describe("home kpi row", () => {
9191 });
9292
9393 test("the builders tile says running of slots, titles it, and links to the crew", () => {
94 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null } }, null).toString();
94 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null } }, null).toString();
9595 expect(out).toContain('href="/settings/crew"');
9696 expect(out).toContain('class="stat-value num" title="2 of 4">2 of 4<');
9797 expect(out).toContain('title="Crew builders running now, of 4 slots"');
@@ -99,7 +99,7 @@ describe("home kpi row", () => {
9999 });
100100
101101 test("with no slots set the builders tile shows a dash and says so", () => {
102 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null } }, null).toString();
102 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null } }, null).toString();
103103 expect(out).toContain('class="stat-value num" title="—">—<');
104104 expect(out).toContain('title="No slots set">No slots set<');
105105 expect(out).toContain(`aria-label="Builders running: —, No slots set"`);
@@ -107,7 +107,7 @@ describe("home kpi row", () => {
107107 });
108108
109109 test("the builders note does not repeat the value", () => {
110 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null } }, null).toString();
110 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null } }, null).toString();
111111 expect(out).toContain(">running now<");
112112 });
113113
@@ -135,13 +135,13 @@ describe("the builders figure from the database", () => {
135135 });
136136
137137 describe("the terminal's figures", () => {
138 const k = { landedHours: hours(6), landed: 6, live: { sha: "abcdef0123456", at: new Date().toISOString() }, builders: { running: 2, slots: 4 }, spend: { todayUsd: 12, ceilingUsd: 40 }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH };
138 const k = { landedHours: hours(6), landed: 6, live: { sha: "abcdef0123456", at: new Date().toISOString() }, builders: { running: 2, slots: 4 }, spend: { todayUsd: 12, ceilingUsd: 40, reachedAt: null }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH };
139139 test("the same nine figures in the same words", () => {
140140 const lines = kpiLines(k, { sha: "abcdef0123456", since: "5m ago" });
141141 expect(lines).toHaveLength(9);
142142 expect(lines).toContain("Last off-box backup never, overdue");
143143 expect(lines[4]).toBe("Crew spend today $12 of $40");
144 expect(kpiLines({ ...k, spend: { todayUsd: 0.4, ceilingUsd: null } }, null)[4]).toBe("Crew spend today $0.40, no ceiling");
144 expect(kpiLines({ ...k, spend: { todayUsd: 0.4, ceilingUsd: null, reachedAt: null } }, null)[4]).toBe("Crew spend today $0.40, no ceiling");
145145 expect(lines[3]).toBe("Builders running 2 of 4");
146146 expect(kpiLines({ ...k, builders: { running: 0, slots: 0 } }, null)[3]).toBe("Builders running —, no slots set");
147147 expect(lines[0]).toContain("Shipped per hour 0.3");
@@ -158,8 +158,8 @@ describe("the terminal's figures", () => {
158158 });
159159
160160 describe("the spend tile", () => {
161 const row = (spend: { todayUsd: number; ceilingUsd: number | null }) =>
162 kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend }, null).toString();
161 const row = (spend: { todayUsd: number; ceilingUsd: number | null; reachedAt?: string | null }) =>
162 kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: NO_REACH, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { reachedAt: null, ...spend } }, null).toString();
163163
164164 test("shows today's spend of the ceiling, the cents in the title, linking to the crew page", () => {
165165 const out = row({ todayUsd: 12.34, ceilingUsd: 40 });
@@ -196,8 +196,8 @@ describe("the spend figure from the database", () => {
196196 ('1','agent',5,'2026-10-19T00:00:00.000Z'), ('2','agent',7.5,'2026-10-19T14:00:00.000Z'),
197197 ('3','agent',100,'2026-10-18T23:59:59.000Z'), ('4','check',9,'2026-10-19T10:00:00.000Z')`,
198198 );
199 expect(readKpis(db, now, { ceilingUsd: 40 }).spend).toEqual({ todayUsd: 12.5, ceilingUsd: 40 });
200 expect(readKpis(db, now).spend).toEqual({ todayUsd: 12.5, ceilingUsd: null });
199 expect(readKpis(db, now, { ceilingUsd: 40 }).spend).toEqual({ todayUsd: 12.5, ceilingUsd: 40, reachedAt: null });
200 expect(readKpis(db, now).spend).toEqual({ todayUsd: 12.5, ceilingUsd: null, reachedAt: null });
201201 });
202202 });
203203
@@ -205,7 +205,7 @@ describe("home kpi row: the last off-box backup", () => {
205205 const NOW = new Date("2026-10-20T12:00:00.000Z");
206206 const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3_600_000).toISOString();
207207 const row = (backupAt: string | null) =>
208 kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt, reach: NO_REACH, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null }, medianCheckMs: null }, null, NOW).toString();
208 kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt, reach: NO_REACH, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null }, medianCheckMs: null }, null, NOW).toString();
209209 const tile = (out: string) => /<a class="stat"[^>]*href="\/settings\/backups"[^>]*>/.exec(out)![0];
210210
211211 test("a backup 2 h old reads its age, with the exact time, and is not flagged", () => {
@@ -252,7 +252,7 @@ describe("home kpi row: the last off-box backup", () => {
252252 describe("the reach tiles", () => {
253253 test("say what they count in words, each linking to the reach board", () => {
254254 const reach = { usersToday: 3, usersTotal: 12, visitorsToday: 5, visitors7d: 31, visitorDays: new Array<number>(30).fill(0), loadP75: 1250, inpP75: 180 };
255 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null } }, null).toString();
255 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null } }, null).toString();
256256 for (const v of ["5 today", "31 in 7 days", "3 of 12", "signed in today", "1.3 s", "reacts in 180 ms"]) expect(out).toContain(`>${v}<`);
257257 expect((out.match(/class="stat" href="\/boards\/reach"/g) ?? []).length).toBe(3);
258258 expect(out).not.toContain("INP");
@@ -262,12 +262,12 @@ describe("the reach tiles", () => {
262262 test("the terminal draws the 30 days as one block per day", () => {
263263 const days = Array.from({ length: 30 }, (_, i) => (i === 29 ? 8 : 0));
264264 const reach = { usersToday: 0, usersTotal: 1, visitorsToday: 8, visitors7d: 8, visitorDays: days, loadP75: null, inpP75: null };
265 const line = kpiLines({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null } }, null).find((l) => l.startsWith("Visitors"))!;
265 const line = kpiLines({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null } }, null).find((l) => l.startsWith("Visitors"))!;
266266 expect(line).toContain("▁".repeat(29) + "█");
267267 });
268268
269269 test("the terminal says the same", () => {
270 const lines = kpiLines({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: { usersToday: 3, usersTotal: 12, visitorsToday: 5, visitors7d: 31, visitorDays: new Array<number>(30).fill(0), loadP75: 1250, inpP75: 180 }, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null } }, null);
270 const lines = kpiLines({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: { usersToday: 3, usersTotal: 12, visitorsToday: 5, visitors7d: 31, visitorDays: new Array<number>(30).fill(0), loadP75: 1250, inpP75: 180 }, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null } }, null);
271271 expect(lines.find((l) => l.startsWith("Visitors"))).toContain("Visitors 5 today, 31 in 7 days");
272272 expect(lines).toContain("Accounts 3 of 12 signed in today");
273273 expect(lines.find((l) => l.startsWith("Visitors"))).toContain("▁".repeat(30));
@@ -286,7 +286,7 @@ describe("the visitors sparkline", () => {
286286 expect(r.visitorDays[29]).toBe(2);
287287 expect(r.visitorDays[0]).toBe(1); // 2026-09-20 is 29 days back; 09-19 is out
288288 expect(r.visitorDays.reduce((a, b) => a + b, 0)).toBe(3);
289 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: r, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null } }, null).toString();
289 const out = kpiRowFor({ landedHours: hours(0), landed: 0, live: null, backupAt: null, reach: r, medianCheckMs: null, builders: { running: 0, slots: 0 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null } }, null).toString();
290290 const svg = /<svg[^>]*last 30 days[^>]*><polyline points="([^"]+)"/.exec(out)!;
291291 expect(svg[1]!.split(" ")).toHaveLength(30);
292292 expect(out).toContain('href="/boards/reach"');
test/home-kpis.test.ts +1 −1
@@ -132,7 +132,7 @@ describe("home kpis", () => {
132132
133133 describe("home kpi row titles", () => {
134134 const full = kpiRowFor(
135 { landedHours: Array.from({ length: 24 }, (_, i) => (i === 0 ? 6 : 0)), landed: 6, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH },
135 { landedHours: Array.from({ length: 24 }, (_, i) => (i === 0 ? 6 : 0)), landed: 6, live: null, builders: { running: 2, slots: 4 }, spend: { todayUsd: 0, ceilingUsd: null, reachedAt: null }, medianCheckMs: 185_000, backupAt: null, reach: NO_REACH },
136136 { sha: "abcdef0123456789", at: "2026-10-19T11:00:00.000Z" },
137137 ).toString();
138138

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs