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

The home page names the first thing wrong in one calm line, with the one action that fixes it #15862

Merged opened this

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

Merged

mason/forge:mason/15841-the-home-page-names-the-first-thing-wron → main 0 commits fork 3 threads · 3 unresolved

  • Merged. mason/15841-the-home-page-names-the-first-thing-wron was merged into main as 36688f4.

Review

Sign in to review this change.
6 files changed +241 −1
docs/features/first-wrong.md added +11
@@ -0,0 +1,11 @@
1 ---
2 topic: When something is wrong
3 row: The first thing wrong, in one line on home
4 ---
5 # The first thing wrong
6
7 When something needs you, home says so in one calm line under the title, with the one link that fixes it. At most one line shows, the most urgent first: production behind main (admins), a pull whose check is stuck (anyone who can write to its repository), the crew past its share of the week (admins). When all is well there is no line, and a guest never sees one.
8
9 The terminal home shows the same line, read by the same function, with the web path to fix it at the end. The allowance line waits until the week has a share above zero.
10
11 Code: `src/web/first_wrong.ts` (`firstWrong`, `readFacts`), `src/web/pages/home_flow.ts` (the page), `src/tui/screens/dashboard.ts` (the terminal). Test: `test/home-first-wrong.test.ts`, `test/tui-dashboard-alarms.test.ts`.
src/tui/screens/dashboard.ts +29 −1
@@ -39,6 +39,8 @@ import { clientLines as crewSentences, IDLE_LINE } from "../../actions/client_li
3939 import { lastVisit } from "../../core/home_visit.ts";
4040 import { quietFor, quietText } from "../../web/studio/home_empty.ts";
4141 import { firstWeekText } from "../../web/first_week.ts";
42 import { firstWrong, firstWrongText, readFacts } from "../../web/first_wrong.ts";
43 import { lanePicture } from "../../flow/lanes.ts";
4244 import { startedFromText } from "../../web/started_from.ts";
4345 import { sinceDigest } from "../../web/studio/since.ts";
4446 import { askForSomething } from "./tell.ts";
@@ -298,6 +300,12 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
298300 let startedFrom: string | null = null;
299301 /** The first week's three steps as one line (`core/first_week.ts`); null when none are due. */
300302 let firstWeek: string | null = null;
303 /**
304 * The first thing wrong, the web home's one line (`web/first_wrong.ts`); null when all is well.
305 */
306 let wrongLine: string | null = null;
307 /** The crew's week as the lane picture last read it; only an admin's line uses it. */
308 let crewWeek: { usedPct: number; mayUsePct: number } | null = null;
301309 /**
302310 * One line per fired flow alarm; an admin reads every repository, anyone else public ones alone.
303311 */
@@ -454,6 +462,20 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
454462 ctx.invalidate();
455463 };
456464
465 const readWrong = (): void => {
466 const user = f.user;
467 wrongLine = user === undefined ? null : firstWrongText(firstWrong(readFacts(f.db, user, { admin: user.isAdmin && user.kind !== "agent", week: crewWeek, now: Date.now() })));
468 };
469
470 const loadWrong = async (): Promise<void> => {
471 if (f.user?.isAdmin === true) {
472 const picture = await lanePicture(f.db, { dataDir: f.app.config.dataDir, ceilingUsd: forgeCeiling(f.app.config), viewer: f.user.id }, "lane");
473 crewWeek = picture?.strip?.week ?? null;
474 }
475 readWrong();
476 ctx.invalidate();
477 };
478
457479 const loadPanelLines = async (): Promise<void> => {
458480 const listed = await listPinned(f.app, f.user);
459481 const titles = listed.ok ? listed.value.map((p) => `${plain(p.panel.title)} (${plain(p.board.title)})`) : [];
@@ -473,6 +495,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
473495 stalePins = mine.filter((p) => !readable.has(p.repoId)).map((p) => p.repoId);
474496 startedFrom = f.user === undefined ? null : startedFromText(f.app.config.dataDir);
475497 firstWeek = firstWeekText(f.db, f.user);
498 readWrong();
476499 pinned = f.user ? pinnedRepoIds(f.db, f.user.id) : new Set<string>();
477500 all = listReposVisibleTo(f.db, f.user, { limit: 200 });
478501 found = undefined;
@@ -1257,7 +1280,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
12571280 live(f, signal, {}, reload);
12581281 reload();
12591282 loadSinceLines();
1260 return Promise.all([loadClientLines(), loadPanelLines()]).then(() => undefined);
1283 return Promise.all([loadClientLines(), loadPanelLines(), loadWrong()]).then(() => undefined);
12611284 },
12621285 render(area, s) {
12631286 const c = ctx.theme.c;
@@ -1270,6 +1293,11 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
12701293 s.text(strip!.x, strip!.y, truncate(firstWeek, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w);
12711294 body = rest!;
12721295 }
1296 if (wrongLine !== null) {
1297 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
1298 s.text(strip!.x, strip!.y, truncate(wrongLine, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w);
1299 body = rest!;
1300 }
12731301 if (startedFrom !== null) {
12741302 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
12751303 s.text(strip!.x, strip!.y, truncate(startedFrom, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w);
src/web/first_wrong.ts added +80
@@ -0,0 +1,80 @@
1 /**
2 * The first thing wrong, in one calm line on the home: production behind main, a check that is
3 * stuck, the crew out of its allowance. At most one shows, chosen by `PRIORITY` (the order is the
4 * list, and a test pins it); when all is well there is nothing. It is a plain `.small .muted`
5 * paragraph with one link to the fix, never red and never a banner over the board.
6 */
7
8 import { readStalled, type StalledStep } from "../flow/stalled.ts";
9 import { behindStanding } from "../release/behind.ts";
10 import type { User } from "../core/users.ts";
11 import type { Database } from "bun:sqlite";
12 import { html, type Html } from "./html.ts";
13
14 export type WrongKey = "behind" | "stuck" | "allowance";
15
16 /** What is wrong and the one link that fixes it. `href` is a same-origin path. */
17 export interface Wrong {
18 readonly says: string;
19 readonly href: string;
20 readonly action: string;
21 }
22
23 /**
24 * Most urgent first: production not following main, then work that cannot move, then the crew's own
25 * limit.
26 */
27 export const PRIORITY: readonly WrongKey[] = ["behind", "stuck", "allowance"];
28
29 export type Facts = Partial<Record<WrongKey, Wrong>>;
30
31 /** The first of `PRIORITY` that the facts hold; null when none. */
32 export function firstWrong(facts: Facts): (Wrong & { readonly key: WrongKey }) | null {
33 for (const key of PRIORITY) {
34 const wrong = facts[key];
35 if (wrong !== undefined) return { ...wrong, key };
36 }
37 return null;
38 }
39
40 /**
41 * What the viewer's home can say, from what is already read: the lane picture's week and the
42 * stores.
43 */
44 export function readFacts(
45 db: Database,
46 user: User,
47 o: { readonly admin: boolean; readonly week: { readonly usedPct: number; readonly mayUsePct: number } | null | undefined; readonly now: number; readonly stalled?: readonly StalledStep[] },
48 ): Facts {
49 const facts: { -readonly [K in WrongKey]?: Wrong } = {};
50 const behind = o.admin ? behindStanding(o.now) : undefined;
51 if (behind !== undefined) facts.behind = { says: `${behind.sentence}.`, href: "/releases", action: "See the release" };
52 // A caller that has read the stalled steps passes them, so nothing is read twice.
53 const step = (o.stalled ?? readStalled(db, user, new Date(o.now)))[0];
54 if (step !== undefined) {
55 facts.stuck = {
56 says: `${step.ownerName}/${step.repoName} #${String(step.pull)} is waiting: ${step.unblock}`,
57 href: `/${step.ownerName}/${step.repoName}/pulls/${String(step.pull)}`,
58 action: step.action === "run" ? "Run the check" : "Re-run the check",
59 };
60 }
outdated

Allowance fires whenever usedPct >= mayUsePct, so mayUsePct 0 (or both 0 at the start of a week) shows the line permanently. Guard mayUsePct > 0 and test 0/0. Also this needs the terminal door.

61 if (o.admin && o.week != null && o.week.mayUsePct > 0 && o.week.usedPct >= o.week.mayUsePct) {
62 facts.allowance = {
63 says: `The crew has used its share of the week (${String(o.week.usedPct)}% of ${String(o.week.mayUsePct)}%) and waits for the reset.`,
64 href: "/settings/crew",
65 action: "Raise the weekly budget",
66 };
67 }
68 return facts;
69 }
70
71 /** The line, or nothing: no box is left behind when all is well. */
72 export function firstWrongLine(wrong: ReturnType<typeof firstWrong>): Html | null {
73 if (wrong === null) return null;
74 return html`<p class="small muted break" id="first-wrong" data-first-wrong="${wrong.key}">${wrong.says} <a href="${wrong.href}">${wrong.action}</a></p>`;
75 }
76
77 /** The same line for the terminal home: the sentence, then the web path that fixes it. */
78 export function firstWrongText(wrong: ReturnType<typeof firstWrong>): string | null {
79 return wrong === null ? null : `${wrong.says} ${wrong.action}: ${wrong.href}`;
80 }
src/web/pages/home_flow.ts +2
@@ -15,6 +15,7 @@
1515 * version without being drawn. The page is a static picture with scripts off.
1616 */
1717
18 import { firstWrong, firstWrongLine, readFacts } from "../first_wrong.ts";
1819 import { focusLine } from "../studio/held.ts";
1920 import { time } from "../time_element.ts";
2021 import { requestHolds } from "../../http/conditional.ts";
@@ -570,6 +571,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited
570571 ${viewSwitch(view, only)}
571572 ${view === "lanes" ? filterForm(viewing?.repos ?? [], only, mine) : null}
572573 ${need}
574 ${need === null ? firstWrongLine(firstWrong(readFacts(ctx.app.db, user, { admin: wide, week: picture?.strip?.week, now }))) : null}

readFacts runs readStalled on every home render. Confirm it stays within the 50 ms budget, reusing what the page already read for the stalled cards instead of reading twice. The terminal home should call the same firstWrong.

573575 </header>
574576 ${mine ? askedSection(ctx, user) : null}
575577 ${main}
test/home-first-wrong.test.ts added +110
@@ -0,0 +1,110 @@
1 /**
2 * The first thing wrong (#15841): one calm line on the home, chosen by a fixed priority; nothing
3 * when all is well.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp as mkTmp, rm as rmDir } 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 { createRepo } from "../src/actions/repos.ts";
11 import { id } from "../src/kernel/id.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { setBehind, watchBehind } from "../src/release/behind.ts";
15 import { firstWrong, firstWrongLine, firstWrongText, PRIORITY, readFacts, type Facts } from "../src/web/first_wrong.ts";
16 import { getUserByName } from "../src/core/users.ts";
17 import { seedAdmin } from "./helpers/admin.ts";
18
19 const w = (says: string) => ({ says, href: "/x", action: "Fix" });
20 const ALL: Facts = { allowance: w("c"), stuck: w("b"), behind: w("a") };
21
22 test("the priority is behind, stuck, allowance, and the first held fact wins", () => {
23 expect(PRIORITY).toEqual(["behind", "stuck", "allowance"]);
24 expect(firstWrong(ALL)?.key).toBe("behind");
25 expect(firstWrong({ allowance: w("c"), stuck: w("b") })?.key).toBe("stuck");
26 expect(firstWrong({ allowance: w("c") })?.key).toBe("allowance");
27 expect(firstWrong({})).toBeNull();
28 expect(firstWrongLine(null)).toBeNull();
29 });
30
31 let dataDir = "", cookie = "";
32 let app: App, servers: Servers;
33
34 beforeAll(async () => {
35 dataDir = await mkTmp(join(tmpdir(), "forge-firstwrong-"));
36 app = createApp({ dataDir, port: 0 });
37 servers = await serve(app);
38 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
39 if (!admin.ok) throw new Error(admin.error);
40 cookie = `forge_session=${createSession(app.db, admin.value.id).token}`;
41 }, 30_000);
42
43 afterAll(async () => {
44 setBehind(undefined);
45 servers.stop();
46 app.close();
47 await rmDir(dataDir, { recursive: true, force: true });
48 });
49
50 const home = async (): Promise<string> => (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
51
52 test("a quiet forge shows no line", async () => {
53 expect(await home()).not.toContain("data-first-wrong");
54 });
55
56 test("production behind main is one calm line with one link, never an alert", async () => {
57 const now = Date.now();
58 const watch = watchBehind({ live: () => "1.0.0", read: async () => ({ version: "1.1.0", at: now - 3 * 3_600_000 }) });
59 await watch.tick();
60 setBehind(watch);
61 const body = await home();
62 const line = body.match(/<p[^>]*data-first-wrong="behind"[^>]*>[\s\S]*?<\/p>/)?.[0] ?? "";
63 expect(line).toContain("production is 1.0.0; main released 1.1.0");
64 expect(line).toContain('<a href="/releases">');
65 expect(line).not.toMatch(/role=|banner|notice|danger/);
66 expect(body.match(/data-first-wrong=/g)?.length).toBe(1);
67 setBehind(undefined);
68 });
69
70 test("facts read from the forge: the week spent is the allowance line, and behind outranks it", async () => {
71 const user = getUserByName(app.db, "alice");
outdated

Needless Promise.resolve(user).then wrapper and u! assertion; make the test async. No test covers the stuck fact through the page.

72 if (user === undefined) throw new Error("alice");
73 const read = (admin: boolean, usedPct: number, mayUsePct: number) => readFacts(app.db, user, { admin, week: { usedPct, mayUsePct }, now: Date.now(), stalled: [] });
74 const facts = read(true, 80, 80);
75 expect(facts.allowance?.href).toBe("/settings/crew");
76 expect(firstWrong(facts)?.key).toBe("allowance");
77 expect(read(true, 79, 80).allowance).toBeUndefined();
78 expect(read(false, 99, 80).allowance).toBeUndefined();
79 });
80
81 test("a week with no allowance yet (0 of 0, or any use of 0) is not a wrong", () => {
82 const user = getUserByName(app.db, "alice");
83 if (user === undefined) throw new Error("alice");
84 for (const week of [{ usedPct: 0, mayUsePct: 0 }, { usedPct: 5, mayUsePct: 0 }]) {
85 expect(readFacts(app.db, user, { admin: true, week, now: Date.now(), stalled: [] }).allowance).toBeUndefined();
86 }
87 });
88
89 test("the terminal line is the sentence, the action and the path", () => {
90 expect(firstWrongText(null)).toBeNull();
91 expect(firstWrongText(firstWrong({ stuck: w("a is waiting") }))).toBe("a is waiting Fix: /x");
92 });
93
94 test("a stalled pull is the line for its writer, with its one link; a guest sees nothing", async () => {
95 const alice = getUserByName(app.db, "alice");
96 if (alice === undefined) throw new Error("alice");
97 const made = await createRepo(app, alice, { name: "app", visibility: "public" });
98 if (!made.ok) throw new Error("repo");
99 const old = new Date(Date.now() - 9 * 86_400_000).toISOString();
100 app.db.query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at) VALUES (?1, ?2, 7, 'pull', 'P', '', ?3, 'open', ?4)`).run(id(), made.value.id, alice.id, old);
101 const issue = app.db.query<{ id: string }, []>("SELECT id FROM issue WHERE number = 7").get();
102 app.db.query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', 'b', '', 'h', ?2)`).run(issue?.id ?? "", made.value.id);
103 const body = await home();
104 const line = body.match(/<p[^>]*data-first-wrong="stuck"[^>]*>[\s\S]*?<\/p>/)?.[0] ?? "";
105 expect(line).toContain("alice/app #7 is waiting");
106 expect(line).toContain('<a href="/alice/app/pulls/7">');
107 expect(line).toContain("Run the check");
108 const guest = await (await fetch(`${servers.url}/`)).text();
109 expect(guest).not.toContain("data-first-wrong");
110 });
test/tui-dashboard-alarms.test.ts +9
@@ -97,3 +97,12 @@ test("the dashboard's since-you-were-here shows a release and a failed gate", as
9797 expect(text).toContain("1 released");
9898 expect(text).toContain("1 failed");
9999 });
100
101 test("the terminal home carries the web home's first-wrong line for a stalled pull (#15841)", async () => {
102 const db = forge.db;
103 db.run("INSERT INTO repo (id, owner_id, name, visibility) VALUES ('fw', ?1, 'fw', 'public')", [alice.id]);
104 db.run("INSERT INTO issue (id, repo_id, number, kind, title, author_id, state, created_at) VALUES ('fw', 'fw', 1, 'pull', 't', ?1, 'open', ?2)", [alice.id, old]);
105 db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES ('fw', 'main', 'b', '', 'h')");
106 expect(await firstScreen(alice)).toContain("is waiting");
107 expect(await firstScreen(bob)).not.toContain("is waiting");
108 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs