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

The maintenance board filters findings by severity with plain links that survive a reload #14567

Merged opened this

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

Merged

scout/forge:scout/14544-the-maintenance-board-filters-findings-b → main 9 commits fork 5 threads · 5 unresolved

  • Merged. scout/14544-the-maintenance-board-filters-findings-b was merged into main as b0ba3d7.

Review

Sign in to review this change.
7 files changed +280 −40
docs/design/areas/maintenance.md added +3
@@ -0,0 +1,3 @@
1 # Maintenance
2
3 `.levels` wraps the `seg()` links that narrow /maintenance by level (All, Needs you, For information). It adds one thing: at 480px or on a coarse pointer each link is 44px tall, so a thumb hits it. The links carry words, not counts: a count of sections would read as a count of findings.

Non-blocking: this says the links carry no counts, but Needs you now shows the number of things waiting. Update the sentence to match the head.

docs/features/maintenance.md +2
@@ -160,6 +160,8 @@ log was cut the finding says earlier files are missing; where the log has no per
160160 finished check is stored, the run says so and names nothing it did not read. It shows as the `slow-tests`
161161 row on `/maintenance`. Test: `test/maintain-slow-tests.test.ts`.
162162
163 **Filter by level (#14544).** `/maintenance?level=needs-you` or `?level=fyi` narrows the board to the sections that wait on a person or the calm ones; anything else shows all. The three links (All, Needs you, For information) are the `seg()` component with plain words, no counts, since a count of sections would read as a count of findings; the current one is marked `aria-current`, and each is 44px tall on a phone (`.levels`, `docs/design/areas/maintenance.md`). A level with nothing in it says "Nothing here needs you." The "For information" view leaves out the status line, which speaks for the whole board. A section's level is fixed except Duties (needs-you while one is overdue or paused), the state fold (needs-you while maintenance is on) and Last return (needs-you when it failed): the same rule as the status line. The terminal's Maintenance screen has the same filter: `l` cycles all, Needs you, For information (`maintenanceLines`, `nextLevel` in `src/maintenance/level.ts`); there overdue duties count as needing you, paused ones are not listed. Tests: `test/maintenance-level.test.ts`.
164
163165 ## Quiet a finding for a day (#14557)
164166
165167 Each row of the stale-pull, merged-branch and preview-data cards on `/maintenance` has a small "Quiet for a day" button: a
src/maintenance/level.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * The maintenance board's severity filter: every section of the board is either something that
3 * needs a decision ("needs-you") or a calm fact ("fyi"). `?level=` narrows to one; anything else
4 * shows all. Plain data in, plain data out.
5 */
6
7 export const LEVELS = ["needs-you", "fyi"] as const;
8 export type Level = (typeof LEVELS)[number];
9
10 export const LEVEL_WORDS: Record<Level, string> = { "needs-you": "Needs you", fyi: "For information" };
11
12 /** The level asked for, or undefined (show all) for a missing, repeated or unknown value. */
13 export function levelOf(raw: string | null): Level | undefined {
14 return LEVELS.find((l) => l === raw);
15 }
16
17 /** The next filter of the terminal's cycle: all, then each level, then all again. */
18 export function nextLevel(now: Level | undefined): Level | undefined {
19 const i = now === undefined ? -1 : LEVELS.indexOf(now);
20 return LEVELS[i + 1];
21 }
22
23 /**
24 * Where each section of the board sits, written once for the page and the terminal so the two
25 * doors cannot drift: duties need you while one is overdue or paused, the maintenance state while
26 * maintenance is on, the last return when it failed a check. Everything else is fixed per section.
27 */
28 export const dutiesLevel = (overdue: number, paused: number): Level => (overdue + paused > 0 ? "needs-you" : "fyi");
29 export const stateLevel = (phase: string): Level => (phase === "idle" ? "fyi" : "needs-you");
30 export const returnLevel = (healthy: boolean | undefined): Level => (healthy === false ? "needs-you" : "fyi");
src/tui/screens/maintenance.ts +30 −18
@@ -9,6 +9,8 @@
99
1010 import { filedText } from "../../maintenance/filed.ts";
1111 import { findingLines } from "../../maintenance/findings.ts";
12 import { LEVEL_WORDS, nextLevel, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts";
13 import { dutyStates } from "../../maintain/pause.ts";
1214 import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts";
1315 import { ABOUT_TO_STOP_ROWS, prepare, resumeNow, status } from "../../maintenance/service.ts";
1416 import { probeStandby, withStandby, type Standby } from "../../maintenance/standby.ts";
@@ -25,7 +27,7 @@ import type { PaletteEntry } from "./entries.ts";
2527 const WIDTH = 72;
2628 const INNER = WIDTH - 6;
2729
28 export function maintenanceLines(f: Session, standby?: Standby): string[] {
30 export function maintenanceLines(f: Session, standby?: Standby, level?: Level): string[] {
2931 const s = standby ? withStandby(status(f.app), standby) : status(f.app);
3032 // Said once: the lead sentence carries it when ready; otherwise its own line.
3133 const standbyLine = standby && s.phase !== "ready" ? wrap(standby.says, INNER) : [];
@@ -49,22 +51,25 @@ export function maintenanceLines(f: Session, standby?: Standby): string[] {
4951 : [];
5052 // Quiet duties fold into one line, as on the page; the rest keep their lines.
5153 const { quiet, loud } = splitDuties(duties(f.app.config.dataDir));
52 const dutyLines = [
53 ...loud.flatMap((d) => wrap(filedText(f.app.db, d, f.user), INNER)),
54 ...(quiet.length === 0 ? [] : wrap(`${quietLine(quiet.length, loud.length === 0)}: ${quiet.map((d) => d.name).join(", ")}`, INNER)),
55 ];
54 const quietText = quiet.length === 0 ? [] : wrap(`${quietLine(quiet.length, loud.length === 0)}: ${quiet.map((d) => d.name).join(", ")}`, INNER);
55 const dutyText = (ds: typeof loud): string[] => ds.flatMap((d) => wrap(filedText(f.app.db, d, f.user), INNER));
56 const lead = wrap(s.says, INNER);
57 const findings = findingLines(f.app.db).flatMap((l) => wrap(l, INNER));
5658 // Findings quieted (#14557): numbered, so `b` can bring one back; when each is back.
5759 const hidden = quieted(f.app.db).flatMap((q, i) => wrap(`${String(i + 1)}. quieted until ${when(q.until)}: ${q.label}`, INNER));
58 return [
59 ...wrap(s.says, INNER),
60 "",
61 ...facts,
62 ...checks,
63 "",
64 ...dutyLines,
65 ...findingLines(f.app.db).flatMap((l) => wrap(l, INNER)),
66 ...(hidden.length === 0 ? [] : ["", ...hidden]),
67 ];
60 const hiddenText = hidden.length === 0 ? [] : ["", ...hidden];
61 // A paused duty waits on a person to resume it, as on the page.
62 const paused = dutyStates(f.app.db).filter((d) => d.paused).flatMap((d) => wrap(d.says, INNER));
63 if (level === undefined) return [...lead, "", ...facts, ...checks, "", ...dutyText(loud), ...paused, ...quietText, ...findings, ...hiddenText];
64 // The same split as the page, by the same rule (maintenance/level.ts): what waits on a person,
65 // and what is only to read.
66 const needs = stateLevel(s.phase) === "needs-you" || returnLevel(last?.healthy) === "needs-you";
67 const overdue = loud.filter((d) => d.overdue);
68 const out =
69 level === "needs-you"
70 ? [...(needs ? [...lead, "", ...facts, ...checks, ""] : []), ...dutyText(overdue), ...paused]
71 : [...(needs ? [] : [...lead, "", ...facts, ...checks, ""]), ...dutyText(loud.filter((d) => !d.overdue)), ...quietText, ...findings, ...hiddenText];
72 return out.length === 0 ? [level === "needs-you" ? "Nothing here needs you." : "Nothing here to read."] : out;
6873 }
6974
7075 export function maintenanceScreen(f: Session, ctx: Ctx): Screen {
@@ -77,6 +82,7 @@ export function maintenanceScreen(f: Session, ctx: Ctx): Screen {
7782 ctx.invalidate();
7883 });
7984 learnStandby();
85 let level: Level | undefined;
8086 let note = "";
8187 // The findings on the three cards, numbered for `z`; read again after each press.
8288 let live: Live[] = [];
@@ -174,6 +180,7 @@ export function maintenanceScreen(f: Session, ctx: Ctx): Screen {
174180 get keys() {
175181 const idle = status(f.app).phase === "idle";
176182 return [
183 binding(["l"], `show ${level === undefined ? LEVEL_WORDS["needs-you"] : level === "needs-you" ? LEVEL_WORDS.fyi : "all"}`),
177184 ...(!mayAct() || busy
178185 ? []
179186 : idle
@@ -188,8 +195,10 @@ export function maintenanceScreen(f: Session, ctx: Ctx): Screen {
188195 title: "Maintenance",
189196 body: [
190197 ...(note === "" ? [] : [...wrap(note, INNER), ""]),
191 ...maintenanceLines(f, standby),
192 ...(live.length === 0 ? [] : ["", "Findings (z quiets one):", ...live.flatMap((l, i) => wrap(`${String(i + 1)}. ${l.label} (${l.kind})`, INNER))]),
198 ...(level === undefined ? [] : [`Showing: ${LEVEL_WORDS[level]}`, ""]),
199 ...maintenanceLines(f, standby, level),
200 // The numbered findings wait on a person, so the calm view leaves them out.
201 ...(live.length === 0 || level === "fyi" ? [] : ["", "Findings (z quiets one):", ...live.flatMap((l, i) => wrap(`${String(i + 1)}. ${l.label} (${l.kind})`, INNER))]),
193202 ],
194203 actions: [{ label: "Close" }],
195204 selected: 0,
@@ -201,7 +210,10 @@ export function maintenanceScreen(f: Session, ctx: Ctx): Screen {
201210 if (e.ctrl || e.alt) return true;
202211 const idle = status(f.app).phase === "idle";
203212 if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop();
204 else if (!mayAct() || busy) return true;
213 else if (e.key === "l") {
214 level = nextLevel(level);
215 ctx.invalidate();
216 } else if (!mayAct() || busy) return true;
205217 else if (e.key === "p" && idle) ctx.push(askPrepare());
206218 else if (e.key === "c" && !idle) doPrepare("");
207219 else if (e.key === "e" && !idle) ctx.push(askEnd());
src/web/pages/maintenance.ts +47 −22
@@ -8,6 +8,7 @@ import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
88 import { dutyStates, switchDuty } from "../../maintain/pause.ts";
99 import { DISMISS_DAYS, REASON_MAX, dismiss, dismissals, dismissalWords } from "../../maintain/dismiss.ts";
1010 import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts";
11 import { LEVELS, LEVEL_WORDS, dutiesLevel, levelOf, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts";
1112 import { findingRows, seenWords } from "../../maintenance/findings.ts";
1213 import { NOTHING_FILED, filedPieces } from "../../maintenance/filed.ts";
1314 import { statusWithStandby } from "../../maintenance/standby.ts";
@@ -18,7 +19,7 @@ import { field as formField, readForm } from "../form.ts";
1819 import { html, type Html } from "../html.ts";
1920 import { icon } from "../icons.ts";
2021 import { flashTo, page } from "../layout.ts";
21 import { badge, btn, disclosure, field } from "../ui.ts";
22 import { badge, btn, disclosure, field, seg } from "../ui.ts";
2223 import { STALE_DAYS, STALE_WORDS, closeStale, nudge, stalePulls } from "../../maintain/stale_pulls.ts";
2324 import { PREVIEW_DAYS, PREVIEW_WORDS, previewDirs, previewLine, removePreviewDirs, sizeWords, totalWords, type PreviewDir } from "../../maintain/previews.ts";
2425 import { MERGED_DAYS, MERGED_WORDS, deleteMerged, lineOf, mergedBranches, type MergedBranch } from "../../maintain/duties/merged_branches.ts";
@@ -98,11 +99,10 @@ export async function maintenancePage(ctx: Ctx): Promise<Response> {
9899 const statusLine = waiting.length === 0
99100 ? html`<p id="maintenance-status" class="mb" data-state="healthy">${icon("check")} <strong>Healthy</strong> <span class="muted">Nothing needs you.</span></p>`
100101 : html`<p id="maintenance-status" class="mb" data-state="needs-you">${icon("alert")} <strong>Needs you</strong> <span class="muted">${waiting.join("; ")}.</span></p>`;
101 const body = html`<div class="page-head"><h1>Maintenance</h1></div>
102 ${statusLine}
103 ${idle ? null : html`<p id="maintenance-says" class="muted">${s.says}</p>
104 <div class="form-actions mb"><form method="post" action="/maintenance/resume">${btn("End maintenance now")}</form></div>`}
105 ${fold("maintenance-duties-fold", "Duties", `${String(ran.length)}${overdue + paused > 0 ? `, ${String(overdue + paused)} need you` : ""}`, overdue + paused > 0,
102 // Each section of the board and how loud it is; ?level= narrows them. Where a section's own
103 // state decides, the rule lives in maintenance/level.ts, shared with the terminal.
104 const sections: [Level, Html | null][] = [
105 [dutiesLevel(overdue, paused), fold("maintenance-duties-fold", "Duties", `${String(ran.length)}${overdue + paused > 0 ? `, ${String(overdue + paused)} need you` : ""}`, overdue + paused > 0,
106106 html`<dl id="maintenance-duties" class="status-rows">
107107 ${loud.map((d) => fact(d.name, html`${foundWords(ctx, d)}${d.overdue ? html` ${badge("overdue", { tone: "danger" })}` : null}`))}
108108 ${quiet.length === 0 ? null : disclosure(html`<span class="muted">${quietLine(quiet.length, loud.length === 0)}</span>`, html`<dl class="status-rows">${quiet.map((d) => fact(d.name, d.detail))}</dl>`, { id: "maintenance-quiet", extra: "mb" })}
@@ -118,23 +118,24 @@ export async function maintenancePage(ctx: Ctx): Promise<Response> {
118118 ${dismissable.length === 0 ? null : html`<form method="post" action="/maintenance/dismiss" id="maintenance-dismiss" class="inline">
119119 <select class="input" name="duty" aria-label="Duty whose finding to dismiss">${dismissable.map((n) => html`<option value="${n}">${n}</option>`)}</select>
120120 <input type="text" name="reason" required maxlength="${String(REASON_MAX)}" autocomplete="off" placeholder="Why (kept)" aria-label="Why dismiss it for ${String(DISMISS_DAYS)} days">${btn(`Dismiss ${String(DISMISS_DAYS)} days`, { variant: "outline" })}
121 </form>`}`)}
122 ${fold("maintenance-budgets", "Budgets", String(states.length), false, html`<dl class="status-rows">${budgetRows(ctx.app, states.map((d) => d.name))}</dl>`)}
123 ${findingsFold(ctx.app.db)}
124 ${writePauseFold(ctx.app.db)}
125 ${stale > 0
121 </form>`}`)],
122 ["fyi", fold("maintenance-budgets", "Budgets", String(states.length), false, html`<dl class="status-rows">${budgetRows(ctx.app, states.map((d) => d.name))}</dl>`)],
123 ["fyi", findingsFold(ctx.app.db)],
124 ["fyi", writePauseFold(ctx.app.db)],
125 ["needs-you", stale > 0
126126 ? fold("stale-pulls", `Pulls untouched for ${String(STALE_DAYS)} days`, String(stale), true, staleRows(ctx.auth.user!.kind !== "agent", stalePending))
127 : null}
128 ${mergedPending.length > 0
127 : null],
128 ["needs-you", mergedPending.length > 0
129129 ? fold("merged-branches", `Branches of pulls merged over ${String(MERGED_DAYS)} days ago`, String(mergedPending.length), true, mergedRows(ctx.auth.user!.kind !== "agent", mergedPending))
130 : null}
131 ${previewPending.length > 0
130 : null],
131 ["needs-you", previewPending.length > 0
132132 ? fold("preview-dirs", `Preview data of pulls closed over ${String(PREVIEW_DAYS)} days ago`, `${String(previewPending.length)}, ${totalWords(previewPending)}`, true, previewRows(ctx.auth.user!.kind !== "agent", previewPending))
133 : null}
134 ${hidden.length > 0
133 : null],
134 // Findings put aside for a day: something to read, never something waiting on a person.
135 ["fyi", hidden.length > 0
135136 ? fold("maintenance-quieted", "Quieted", String(hidden.length), false, quietedRows(ctx.auth.user!.kind !== "agent", hidden))
136 : null}
137 ${idle
137 : null],
138 [stateLevel(s.phase), idle
138139 ? fold("maintenance-prepare", "Prepare for a power-off", `${String(ABOUT_TO_STOP_ROWS.length)} things stop`, false,
139140 html`<p id="maintenance-standby" class="muted">${s.standby.says}</p>
140141 <dl class="status-rows">${ABOUT_TO_STOP_ROWS.map((r) => fact(r.what, r.stops))}</dl>
@@ -149,8 +150,8 @@ export async function maintenancePage(ctx: Ctx): Promise<Response> {
149150 ${fact("Since", s.since ?? "")} ${s.reason ? fact("Reason", s.reason) : null}
150151 ${fact("Backup", s.backup?.says ?? "")} ${fact("Still working", String(s.working))}
151152 </dl>
152 <div class="form-actions"><form method="post" action="/maintenance/prepare">${btn("Check again and retake the backup", { variant: "outline" })}</form></div>`)}
153 ${idle && s.last
153 <div class="form-actions"><form method="post" action="/maintenance/prepare">${btn("Check again and retake the backup", { variant: "outline" })}</form></div>`)],
154 [returnLevel(s.healthy), idle && s.last
154155 ? fold("maintenance-return", "Last return", s.healthy === false ? "failed" : "ok", s.healthy === false,
155156 html`<p id="maintenance-last" class="muted">${s.last.says}</p>
156157 ${s.last.checks
@@ -160,7 +161,31 @@ export async function maintenancePage(ctx: Ctx): Promise<Response> {
160161 )}
outdated

Principle 1: when a level has no sections, nothing is rendered. Add one plain sentence ('Nothing here needs you.') so the page does not go blank.

161162 </dl>`
outdated

Principle 7/design system: hand-rolled nav with ' · ' text separators. Use the named tab/filter component from docs/DESIGN.md (or add one to docs/design/areas/maintenance.md) with link targets large enough for a thumb at 360px.

162163 : html`<ul id="maintenance-checks" class="muted">${s.last.verified.map((v) => html`<li>${v}</li>`)}</ul>`}`)
163 : null}`;
164 : null],
165 ];
166 const asked = levelOf(ctx.url.searchParams.get("level"));
167 const shown = sections.filter(([l]) => asked === undefined || l === asked).map(([, h]) => h);
168 // Needs you carries how many things wait on a person, the same things the status line names;
169 // For information is reading matter, so it carries no number to act on.
170 const waitingCount = overdue + paused + stale + mergedPending.length + previewPending.length + (idle ? 0 : 1) + (s.healthy === false ? 1 : 0);
171 const strip = html`<div id="maintenance-levels" class="levels mb">${seg([
172 { label: "All", href: "/maintenance", current: asked === undefined },
173 ...LEVELS.map((l) => ({ label: LEVEL_WORDS[l], href: `/maintenance?level=${l}`, current: asked === l, ...(l === "needs-you" ? { count: waitingCount } : {}) })),
174 ])}</div>`;
175 // Said once: on Needs you the status line already says when nothing waits, so the empty line is
176 // only for For information, where the status line is not shown.
177 const empty = asked === "fyi" && shown.every((h) => h === null)
178 ? html`<p id="maintenance-level-empty" class="muted">Nothing here to read.</p>`
179 : null;
180 // Maintenance being on waits on a person: its sentence and button stay off the calm view.
181 const calm = asked === "fyi";
182 const body = html`<div class="page-head"><h1>Maintenance</h1></div>
183 ${calm ? null : statusLine}
184 ${idle || calm ? null : html`<p id="maintenance-says" class="muted">${s.says}</p>
185 <div class="form-actions mb"><form method="post" action="/maintenance/resume">${btn("End maintenance now")}</form></div>`}
186 ${strip}
187 ${empty}
188 ${shown}`;
164189 const response = page({ ctx, title: "Maintenance", body });
165190 notePhase(ctx.request, "render", performance.now() - rendering);
166191 return response;
src/web/style/components.ts +2
@@ -717,6 +717,8 @@ details[open] > summary.row > .row-lead { transform: rotate(90deg); }
717717 }
718718 @media (min-width: 720px) { .tabs { mask-image: none; } }
719719
720 /* The maintenance level filter: thumb-sized links on a phone. */
721 @media (max-width: 480px), (pointer: coarse) { .levels .seg > a { min-height: 44px; } }
720722 /* ---- segmented control (radios in a GET form, links, or a form's submit buttons) ---- */
721723 .seg {
722724 display: inline-flex; align-items: center; gap: 2px; flex: none;
test/maintenance-level.test.ts added +166
@@ -0,0 +1,166 @@
1 /** /maintenance?level= narrows the board to one severity; anything else shows all. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/core/repos.ts";
8 import { id } from "../src/kernel/id.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { dutiesLevel, levelOf, nextLevel, returnLevel, stateLevel, type Level } from "../src/maintenance/level.ts";
12 import { JOBS } from "../src/nightly/jobs.ts";
13 import { writeLast } from "../src/nightly/stamps.ts";
14 import { dutyStates, setPaused } from "../src/maintain/pause.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18 let dir = "", app: App, servers: Servers, cookie = "";
19
20 beforeAll(async () => {
21 dir = await mkdtemp(join(tmpdir(), "forge-maint-level-"));
22 app = createApp({ dataDir: dir, port: 0 });
23 servers = await serve(app);
24 const made = await createUser(app.db, { username: "boss", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, isAdmin: true });
25 if (!made.ok) throw new Error("user");
26 const res = await fetch(`${servers.url}/signin`, {
27 method: "POST", redirect: "manual",
28 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
29 body: new URLSearchParams({ username: "boss", password: "a-good-passphrase" }),
30 });
31 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
32 });
33 afterAll(async () => { await servers.stop(); await rm(dir, { recursive: true, force: true }); });
34
35 const get = async (q: string): Promise<string> => (await fetch(`${servers.url}/maintenance${q}`, { headers: { cookie } })).text();
36
37 test("levelOf accepts the two levels and nothing else", () => {
38 expect(levelOf("needs-you")).toBe("needs-you");
39 expect(levelOf("fyi")).toBe("fyi");
40 expect(levelOf("FYI")).toBeUndefined();
41 expect(levelOf(null)).toBeUndefined();
42 const steps: (Level | undefined)[] = [undefined, "needs-you", "fyi"];
43 expect(steps.map((l) => nextLevel(l))).toEqual(["needs-you", "fyi", undefined]);
44 });
45
46 test("the default view is unchanged and carries the level links, current marked", async () => {
47 const all = await get("");
48 expect(all).toContain('id="maintenance-budgets"');
49 expect(all).toContain('id="maintenance-prepare"');
50 expect(all).toContain('href="/maintenance?level=needs-you"');
outdated

Add the opposite assertion: fyi must not contain a needs-you section. Seed a stale pull or overdue duty and assert it appears under needs-you and not under fyi.

51 expect(all).toContain('href="/maintenance?level=fyi"');
52 expect(all).toMatch(/aria-current="page"\s*>All<\/a\s*>/);
53 expect(all).toContain('class="seg"');
54 expect(all).not.toContain("</a> ·");
55 });
56
57 test("fyi narrows to calm sections and marks itself current", async () => {
58 const t = await get("?level=fyi");
59 expect(t).toContain('id="maintenance-budgets"');
60 expect(t).toMatch(/aria-current="page"\s*>For information<\/a\s*>/);
61 expect(t).toContain('href="/maintenance"');
62 expect(t).not.toContain('id="stale-pulls"');
63 expect(t).not.toContain('id="maintenance-status"');
64 });
65
66 test("a level with no sections says so in one sentence", async () => {
67 const t = await get("?level=needs-you");
68 expect(t.match(/[Nn]othing (here )?needs you\./g)).toEqual(["Nothing needs you."]);
69 expect(t).not.toContain('id="maintenance-level-empty"');
70 expect(t).toMatch(/>Needs you<span[^>]*>0</);
71 expect(t).not.toContain('id="maintenance-budgets"');
72 expect(t).not.toContain('id="maintenance-prepare"');
73 expect(t).toMatch(/aria-current="page"\s*>Needs you</);
74 });
75
76 test("a stale pull shows under needs-you and not under fyi", async () => {
77 const boss = (await Promise.resolve(app.db.query("SELECT id FROM user WHERE username = 'boss'").get())) as { id: string };
78 const made = await createRepo(app.db, app.reposRoot, { ownerId: boss.id, name: "r", visibility: "public", description: "r" });
79 if (!made.ok) throw new Error("repo");
80 const issue = id();
81 const at = new Date(Date.now() - 30 * 86_400_000).toISOString();
82 app.db.query("INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at, updated_at) VALUES (?1, ?2, 1, 'pull', 'Quiet', '', ?3, 'open', ?4, ?4)").run(issue, made.value.id, boss.id, at);
83 app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', 'b/1', ?2, ?2, ?3)").run(issue, "0".repeat(40), made.value.id);
84 const needs = await get("?level=needs-you");
85 expect(needs).toContain('id="stale-pulls"');
86 expect(needs).not.toContain('data-state="healthy"');
87 expect(needs).toMatch(/>Needs you<span[^>]*>1</);
88 expect(needs).not.toContain('id="maintenance-budgets"');
89 const fyi = await get("?level=fyi");
90 expect(fyi).not.toContain('id="stale-pulls"');
91 expect(fyi).toContain('id="maintenance-budgets"');
92 expect(await get("")).toContain('id="stale-pulls"');
93 });
94
95 test("an unknown level shows everything and markup in it is not echoed", async () => {
96 const evil = encodeURIComponent('"><script>alert(1)</script>');
97 const t = await get(`?level=${evil}`);
98 expect(t).toContain('id="maintenance-budgets"');
99 expect(t).not.toContain("<script>alert(1)");
100 expect(t).not.toContain("alert(1)");
101 });
102
103 test("the terminal's level filter narrows the same way", async () => {
104 const { maintenanceLines } = await import("../src/tui/screens/maintenance.ts");
105 const { Session } = await import("../src/tui/session.ts");
106 const boss = app.db.query("SELECT id FROM user WHERE username = 'boss'").get() as { id: string };
107 const { getUserById } = await import("../src/core/users.ts");
108 const f = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: getUserById(app.db, boss.id) });
109 const all = maintenanceLines(f, undefined).join("\n");
110 const needs = maintenanceLines(f, undefined, "needs-you").join("\n");
111 const fyi = maintenanceLines(f, undefined, "fyi").join("\n");
112 expect(needs).toBe("Nothing here needs you.");
113 expect(nextLevel(undefined)).toBe("needs-you");
114 expect(fyi.length).toBeGreaterThan(0);
115 expect(fyi).not.toBe("Nothing here needs you.");
116 expect(all.length).toBeGreaterThanOrEqual(fyi.length);
117 });
118
119 test("one rule places the sections that move", () => {
120 expect([dutiesLevel(0, 0), dutiesLevel(1, 0), dutiesLevel(0, 1)]).toEqual(["fyi", "needs-you", "needs-you"]);
121 expect([stateLevel("idle"), stateLevel("ready")]).toEqual(["fyi", "needs-you"]);
122 expect([returnLevel(undefined), returnLevel(true), returnLevel(false)]).toEqual(["fyi", "fyi", "needs-you"]);
123 });
124
125 test("the terminal puts an overdue duty and a paused duty under needs-you, not fyi", async () => {
126 const { maintenanceLines } = await import("../src/tui/screens/maintenance.ts");
127 const { Session } = await import("../src/tui/session.ts");
128 const { getUserById } = await import("../src/core/users.ts");
129 const boss = app.db.query("SELECT id FROM user WHERE username = 'boss'").get() as { id: string };
130 const f = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: getUserById(app.db, boss.id) });
131 const slot = Date.now() - 3 * 86_400_000;
132 const late = JOBS[0]!.name;
133 writeLast(dir, late, { slot, startedAt: slot, finishedAt: slot + 1000, says: "filed nothing" });
134 const stopped = dutyStates(app.db)[0]!.name;
135 setPaused(app.db, stopped, true, "boss");
136 try {
137 const needs = maintenanceLines(f, undefined, "needs-you").join("\n");
138 const fyi = maintenanceLines(f, undefined, "fyi").join("\n");
139 expect(needs).toContain("overdue");
140 expect(needs).toContain(`${stopped}: paused since`);
141 expect(fyi).not.toContain("overdue");
142 expect(fyi).not.toContain(`${stopped}: paused since`);
143 // The page agrees: both put Duties under Needs you.
144 expect(await get("?level=needs-you")).toContain('id="maintenance-duties-fold"');
145 expect(await get("?level=fyi")).not.toContain('id="maintenance-duties-fold"');
146 } finally {
147 setPaused(app.db, stopped, false, "boss");
148 }
149 });
150
151 test("while maintenance is on, its sentence and End button stay off the calm view", async () => {
152 await fetch(`${servers.url}/maintenance/prepare`, {
153 method: "POST", redirect: "manual",
154 headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
155 body: new URLSearchParams({ confirm: "yes" }),
156 });
157 try {
158 expect(await get("")).toContain('action="/maintenance/resume"');
159 expect(await get("?level=needs-you")).toContain('action="/maintenance/resume"');
160 const fyi = await get("?level=fyi");
161 expect(fyi).not.toContain('action="/maintenance/resume"');
162 expect(fyi).not.toContain('id="maintenance-says"');
163 } finally {
164 await fetch(`${servers.url}/maintenance/resume`, { method: "POST", redirect: "manual", headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body: "" });
165 }
166 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs