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

The maintenance page shows the last restore drill in words: when, how long, and whether it passed #16153

Merged opened this

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

Merged

scout/forge:scout/16139-the-maintenance-page-shows-the-last-rest → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16139-the-maintenance-page-shows-the-last-rest was merged into main as 5a5668e.

Review

Sign in to review this change.
5 files changed +126 −2
docs/features/maintenance.md +7
@@ -20,6 +20,13 @@ row: Maintenance: shut down for a move and come back by itself
2020 The page says plainly what stops: releases, new crew runs, then the forge, its
2121 apps and previews when the host powers off.
2222
23 **The restore drill line.** Under the status line, `/maintenance` and the terminal's Maintenance screen
24 (`src/tui/screens/maintenance.ts`, admins only, hidden on the calm "For information" view) read the last
25 restore drill in one sentence from `drillLine` (`src/maintenance/drill_line.ts`): "Last restore drill:
26 restored in 4 minutes, passed, 2 days ago." or "failed after 10 minutes, 2 days ago: <cause>." (the cause is
27 one line, at most 200 characters, no raw milliseconds). With no drill yet it reads "No restore drill has run
28 yet." Spans come from `durationWords` (`src/system/format.ts`). Tests: `test/maintenance-drill.test.ts`.
29
2330 **The page.** `/maintenance` answers one question first: one status line, "Healthy: nothing needs you" or
2431 "Needs you" with what waits (maintenance on, a failed return, overdue or paused duties, stale pulls; `needsYou`
2532 in `src/web/pages/maintenance.ts`). Below it, each part is a `disclosure` with a count in its summary:
src/maintenance/drill_line.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * The last restore drill as one line for the maintenance page: how long the restore took, whether
3 * it passed, how long ago; a failed drill adds its one-line cause. Never raw milliseconds.
4 * Plain data in, a string out; the page escapes it.
5 */
6
7 import { agoWords } from "../kernel/ago.ts";
8 import { durationWords } from "../system/format.ts";
9 import { drillFailure } from "../snapshot/drill_card_words.ts";
10 import type { DrillResult } from "../snapshot/drill.ts";
11
12 const CAUSE_MAX = 200;
13
outdated

Duplicates formatSpan and durationWords (principle 8 / clean). Reuse or consolidate in src/system/format.ts.

14 /**
15 * "restored in 4 minutes, passed, 2 days ago"; "failed after 4 minutes, 2 days ago: <cause>"; the
16 * cause loses a final full stop, the sentence adds one.
17 */
18 export function drillLine(d: Pick<DrillResult, "at" | "ms" | "verdict" | "reason" | "failedStep" | "budgetMs"> | undefined, now: number = Date.now()): string {
19 if (d === undefined) return "No restore drill has run yet.";
20 const ago = agoWords(d.at, now);
21 if (d.verdict === "green") return `Last restore drill: restored in ${durationWords(d.ms)}, passed, ${ago}.`;
22 const cause = drillFailure(d).replace(/[\u0000-\u001f\u007f]+/g, " ").trim().replace(/[.\s]+$/, "");
23 const one = cause.length > CAUSE_MAX ? `${cause.slice(0, CAUSE_MAX - 1)}…` : cause;
24 return `Last restore drill: failed after ${durationWords(d.ms)}, ${ago}: ${one}.`;
25 }
src/tui/screens/maintenance.ts +6 −2
@@ -14,6 +14,8 @@ import { autoClosedCauses, findingLines, reopenFinding } from "../../maintenance
1414 import { LEVEL_WORDS, nextLevel, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts";
1515 import { dutyStates } from "../../maintain/pause.ts";
1616 import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts";
17 import { drillLine } from "../../maintenance/drill_line.ts";
18 import { lastDrill } from "../../snapshot/drills.ts";
1719 import { stalledNow } from "../../maintenance/stalled.ts";
1820 import { STALE_WORDS, nudge } from "../../maintain/stale_pulls.ts";
1921 import { ABOUT_TO_STOP_ROWS, prepare, resumeNow, status } from "../../maintenance/service.ts";
@@ -61,6 +63,8 @@ export function maintenanceLines(f: Session, standby?: Standby, level?: Level):
6163 // The one stalled step, as on the page; it waits on a person, so the calm view leaves it out.
6264 const step = stalledNow(f.db, new Date());
6365 const stalled = step === undefined || level === "fyi" || f.user?.isAdmin !== true || f.user.kind === "agent" ? [] : [...wrap(`Stalled: ${step.step} ${step.says} (a asks if still wanted)`, INNER), ""];
66 // The last restore drill in words, as on the page; the calm view leaves it out.
67 const drill = level === "fyi" ? [] : [...wrap(drillLine(lastDrill(f.app.db)), INNER), ""];
6468 const findings = findingLines(f.app.db).flatMap((l) => wrap(l, INNER));
6569 // Findings quieted (#14557): numbered, so `b` can bring one back; when each is back.
6670 const hidden = quieted(f.app.db).flatMap((q, i) => wrap(`${String(i + 1)}. quieted until ${when(q.until)}: ${q.label}`, INNER));
@@ -71,14 +75,14 @@ export function maintenanceLines(f: Session, standby?: Standby, level?: Level):
7175 // here.
7276 const disk = diskLine((f.app.config.disk ?? readDisk)(f.app.config.dataDir));
7377 const diskText = disk === null ? [] : [...wrap(diskSentence(disk), INNER), ""];
74 if (level === undefined) return [...diskText, ...stalled, ...lead, "", ...facts, ...checks, "", ...dutyText(loud), ...paused, ...quietText, ...findings, ...hiddenText];
78 if (level === undefined) return [...diskText, ...stalled, ...drill, ...lead, "", ...facts, ...checks, "", ...dutyText(loud), ...paused, ...quietText, ...findings, ...hiddenText];
7579 // The same split as the page, by the same rule (maintenance/level.ts): what waits on a person,
7680 // and what is only to read.
7781 const needs = stateLevel(s.phase) === "needs-you" || returnLevel(last?.healthy) === "needs-you";
7882 const overdue = loud.filter((d) => d.overdue);
7983 const out =
8084 level === "needs-you"
81 ? [...(disk?.low === true ? diskText : []), ...stalled, ...(needs ? [...lead, "", ...facts, ...checks, ""] : []), ...dutyText(overdue), ...paused]
85 ? [...(disk?.low === true ? diskText : []), ...stalled, ...drill, ...(needs ? [...lead, "", ...facts, ...checks, ""] : []), ...dutyText(overdue), ...paused]
8286 : [...(disk?.low === false ? diskText : []), ...(needs ? [] : [...lead, "", ...facts, ...checks, ""]), ...dutyText(loud.filter((d) => !d.overdue)), ...quietText, ...findings, ...hiddenText];
8387 return out.length === 0 ? [level === "needs-you" ? "Nothing here needs you." : "Nothing here to read."] : out;
8488 }
src/web/pages/maintenance.ts +4
@@ -13,6 +13,8 @@ import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts";
1313 import { LEVELS, LEVEL_WORDS, dutiesLevel, levelOf, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts";
1414 import { AUTO_CLOSE_NOTE, closedDate, findingRows, findingsJson, reopenFinding, seenWords } from "../../maintenance/findings.ts";
1515 import { NOTHING_FILED, filedPieces } from "../../maintenance/filed.ts";
16 import { drillLine } from "../../maintenance/drill_line.ts";
17 import { lastDrill } from "../../snapshot/drills.ts";
1618 import { stalledStep } from "../../maintenance/stalled.ts";
1719 import { statusWithStandby } from "../../maintenance/standby.ts";
1820 import { ABOUT_TO_STOP_ROWS, prepare, resumeNow, status } from "../../maintenance/service.ts";
@@ -134,6 +136,7 @@ async function maintenanceAnswer(ctx: Ctx): Promise<Response> {
134136 const paused = states.filter((d) => d.paused).length;
135137 const waiting = needsYou({ phase: s.phase, ...(s.healthy === undefined ? {} : { healthy: s.healthy }), overdue, paused, stale });
136138 const idle = s.phase === "idle";
139 const drill = lastDrill(ctx.app.db);
137140 const statusLine = waiting.length === 0
138141 ? html`<p id="maintenance-status" class="mb" data-state="healthy">${icon("check")} <strong>Healthy</strong> <span class="muted">Nothing needs you.</span></p>`
139142 : html`<p id="maintenance-status" class="mb" data-state="needs-you">${icon("alert")} <strong>Needs you</strong> <span class="muted">${waiting.join("; ")}.</span></p>`;
@@ -229,6 +232,7 @@ async function maintenanceAnswer(ctx: Ctx): Promise<Response> {
229232 ${calm ? null : stalledCard(stalledStep(stalePending), ctx.auth.user!.kind !== "agent")}
230233 ${idle || calm ? null : html`<p id="maintenance-says" class="muted">${s.says}</p>
231234 <div class="form-actions mb"><form method="post" action="/maintenance/resume">${btn("End maintenance now")}</form></div>`}
235 ${calm ? null : html`<p id="maintenance-drill" class="muted" data-drill="${drill?.verdict ?? "none"}">${drillLine(drill)}</p>`}
232236 ${strip}
233237 ${empty}
234238 ${shown}`;
test/maintenance-drill.test.ts added +84
@@ -0,0 +1,84 @@
1 /** The maintenance page says the last restore drill in words (#16139). */
2 import { expect, test } from "bun:test";
3 import { drillLine } from "../src/maintenance/drill_line.ts";
4
5 const NOW = Date.parse("2026-11-23T12:00:00Z");
6 const base = { at: "2026-11-21T12:00:00Z", ms: 240_000, verdict: "green" as const, reason: null, failedStep: null, budgetMs: 600_000 };
7
8 test("a passed drill reads when, how long, and that it passed", () => {
9 expect(drillLine(base, NOW)).toBe("Last restore drill: restored in 4 minutes, passed, 2 days ago.");
10 });
11
12 test("a failed drill adds its one-line cause, with no raw milliseconds", () => {
13 const line = drillLine({ ...base, verdict: "red", failedStep: "restore", ms: 600_000, reason: "restore timed out in bundles after its 600000 ms" }, NOW);
14 expect(line).toContain("failed after 10 minutes");
15 expect(line).toContain("restoring the snapshot");
16 expect(line).not.toMatch(/\d{4,} ?ms/);
17 expect(line).not.toContain("\n");
18 });
19
20 test("spans are short words; no drill says so", () => {
21 expect(drillLine({ ...base, ms: 45_000 }, NOW)).toContain("restored in 45 seconds");
22 expect(drillLine({ ...base, ms: 5_400_000 }, NOW)).toContain("restored in 1 hour 30 minutes");
23 expect(drillLine(undefined, NOW)).toBe("No restore drill has run yet.");
24 });
25
26 test("a cause already ending in a full stop gets no second one", () => {
27 const line = drillLine({ ...base, verdict: "red", failedStep: "restore", reason: "the key did not open the snapshot..." }, NOW);
28 expect(line).not.toContain("..");
29 expect(line.endsWith(".")).toBe(true);
30 });
31
32 test("a cause over 200 characters is cut with an ellipsis", () => {
33 const line = drillLine({ ...base, verdict: "red", failedStep: "restore", reason: "x".repeat(500) }, NOW);
34 expect(line).toContain("…");
35 expect(line.length).toBeLessThan(320);
36 });
37
38 test("the terminal's maintenance screen reads the same line, and the calm view leaves it out", async () => {
39 const { mkdtemp, rm } = await import("node:fs/promises");
40 const { tmpdir } = await import("node:os");
41 const { join } = await import("node:path");
42 const { createApp } = await import("../src/app.ts");
43 const { recordDrill } = await import("../src/snapshot/drills.ts");
44 const { maintenanceLines } = await import("../src/tui/screens/maintenance.ts");
45 type Session = import("../src/tui/session.ts").Session;
46 const dir = await mkdtemp(join(tmpdir(), "forge-maint-drill-tui-"));
47 const app = createApp({ dataDir: dir, port: 0 });
48 try {
49 const f = { app, db: app.db, user: { isAdmin: true, kind: "human" } } as unknown as Session;
50 expect(maintenanceLines(f).join(" ")).toContain("No restore drill has run yet.");
51 recordDrill(app.db, { ...base, at: new Date(Date.now() - 2 * 86_400_000).toISOString(), snapshotId: null, counts: { repositories: 1, issues: 1, users: 1, pulls: 1, apps: 1 }, health: "ok", phases: [] });
52 expect(maintenanceLines(f).join(" ")).toContain("restored in 4 minutes, passed, 2 days ago");
53 expect(maintenanceLines(f, undefined, "fyi").join(" ")).not.toContain("restore drill");
54 } finally {
55 app.close();
56 await rm(dir, { recursive: true, force: true });
57 }
58 });
59
60 test("/maintenance shows the line in the first paint", async () => {
61 const { mkdtemp, rm } = await import("node:fs/promises");
62 const { tmpdir } = await import("node:os");
63 const { join } = await import("node:path");
64 const { createApp } = await import("../src/app.ts");
65 const { createUser } = await import("../src/core/users.ts");
66 const { serve } = await import("../src/http/server.ts");
67 const { recordDrill } = await import("../src/snapshot/drills.ts");
68 const dir = await mkdtemp(join(tmpdir(), "forge-maint-drill-"));
69 const app = createApp({ dataDir: dir, port: 0 });
70 const servers = await serve(app);
71 try {
72 await createUser(app.db, { username: "boss", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, isAdmin: true });
73 const res = await fetch(`${servers.url}/signin`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url }, body: new URLSearchParams({ username: "boss", password: "a-good-passphrase" }) });
74 const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
75 const text = async (): Promise<string> => (await fetch(`${servers.url}/maintenance`, { headers: { cookie } })).text();
76 expect(await text()).toContain("No restore drill has run yet.");
77 recordDrill(app.db, { ...base, at: new Date(Date.now() - 2 * 86_400_000).toISOString(), snapshotId: null, counts: { repositories: 1, issues: 1, users: 1, pulls: 1, apps: 1 }, health: "ok", phases: [] });
78 expect(await text()).toContain("restored in 4 minutes, passed, 2 days ago");
79 } finally {
80 servers.stop();
81 app.close();
82 await rm(dir, { recursive: true, force: true });
83 }
84 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs