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

The client list narrows by state with plain links (waiting, in, quiet) that survive a reload #14625

Merged opened this

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

Merged

scout/forge:scout/14538-the-client-list-narrows-by-state-with-pl → main 4 commits fork 3 threads · 3 unresolved

  • Merged. scout/14538-the-client-list-narrows-by-state-with-pl was merged into main as a9cf7ca.

Review

Sign in to review this change.
6 files changed +270 −13
docs/features/client-states.md added +12
@@ -0,0 +1,12 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: The forges you sent narrow by state
4 ---
5 # The forges you sent narrow by state (#14538)
6
7 Three words the owner thinks in, one for each forge you sent: **Waiting** (the link has not been opened), **Signed in** (opened or claimed) and **Quiet** (a forge that stopped reporting). Each forge is in exactly one, quiet first (`clientStateOf`, `src/spawn/client_state.ts`, the one source for both doors).
8
9 - **On the page.** `/forges` lists the states as links with counts under the Forges heading; `/forges?state=waiting|in|quiet` narrows the list and the Side by side table together and survives a reload. Any other value shows all and is never echoed. A state with no forges says "No forges are waiting" (and so on) with a link back to All.
10 - **In the terminal.** Open *Forges you sent* from the palette (`ctrl+k`, admins) and press `f`: waiting, then signed in, then quiet, then all again. The first line names the view and its count (`stateLines`, `src/tui/screens/forges.ts`); an empty view says so and that `f` shows all.
11 - **Not narrowed.** The receipt after a link change and the "Forge code" section list every forge.
12 - **Tests.** `bun test test/clients-filter.test.ts test/tui-forges.test.ts`.
src/spawn/client_state.ts added +51
@@ -0,0 +1,51 @@
1 /**

Both doors: nothing in src/tui/ uses this module, and there is no docs/features/ how-to. Add both.

2 * The client list narrows by where each sent forge stands (#14538), three words the owner
3 * thinks in: waiting (the link has not been opened), in (opened or claimed), quiet (a forge
4 * that stopped reporting). Read from the stage and attention the page already shows; each row
5 * is in exactly one, quiet first.
6 */
7
8 import { attentionOf, type ClientRow } from "./clients.ts";
9
10 export const CLIENT_STATES = ["waiting", "in", "quiet"] as const;
11 export type ClientState = (typeof CLIENT_STATES)[number];
12
13 export const CLIENT_STATE_WORDS: Record<ClientState, string> = {
14 waiting: "Waiting",
15 in: "Signed in",
16 quiet: "Quiet",
17 };
18
19 /** What an empty narrowed list says, in words a person reads. */
20 export const CLIENT_STATE_EMPTY: Record<ClientState, string> = {
21 waiting: "No forges are waiting",
22 in: "No forges are signed in",
23 quiet: "No forges are quiet",
24 };
25
26 /** The next view when `f` is pressed in the terminal: all, then each state, then all again. */
27 export function nextClientState(state: ClientState | null): ClientState | null {
28 if (state === null) return CLIENT_STATES[0];
29 return CLIENT_STATES[CLIENT_STATES.indexOf(state) + 1] ?? null;
30 }
31
32 /** The state asked for, or null for anything else (shows all). */
33 export function parseClientState(raw: string | null): ClientState | null {
34 return (CLIENT_STATES as readonly string[]).includes(raw ?? "") ? (raw as ClientState) : null;
35 }
36
37 export function clientStateOf(r: ClientRow, now: number): ClientState {
38 if (attentionOf(r, now) === "silent") return "quiet";
39 const key = r.stage?.key ?? "sent";
40 return key === "sent" ? "waiting" : "in";
41 }
42
43 export function stateCounts(rows: readonly ClientRow[], now: number): Record<ClientState, number> {
44 const counts: Record<ClientState, number> = { waiting: 0, in: 0, quiet: 0 };
45 for (const r of rows) counts[clientStateOf(r, now)]++;
46 return counts;
47 }
48
49 export function narrowByState<T extends ClientRow>(rows: readonly T[], state: ClientState | null, now: number): T[] {
50 return state === null ? [...rows] : rows.filter((r) => clientStateOf(r, now) === state);
51 }
src/tui/screens/forges.ts +20 −4
@@ -13,6 +13,7 @@ import { card } from "../ui/widgets.ts";
1313 import { drawFacts, runAsync } from "./common.ts";
1414 import type { PaletteEntry } from "./entries.ts";
1515 import { clientRows } from "../../spawn/clients.ts";
16 import { CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, nextClientState, type ClientState } from "../../spawn/client_state.ts";
1617 import { diskWords } from "../../spawn/disk_mount.ts";
1718 import { archiveForge, archivedForges, destinationWords, restoreForge } from "../../spawn/archive.ts";
1819 import { claimedWords, keepWords } from "../../spawn/keep_words.ts";
@@ -101,8 +102,20 @@ export function ownCodePicks(app: App, rows: readonly ClientRow[]): { id: string
101102 });
102103 }
103104
104 export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Session): Screen {
105 const lines = forgeLines(rows, session?.user?.isAdmin === true);
105 /**
106 * The lines for one state (#14538), as /forges?state= narrows them: a heading with the count, then
107 * the rows, or the page's empty words with the way back. Null shows all, unheaded.
108 */
109 export function stateLines(rows: readonly ClientRow[], state: ClientState | null, sender = false, now = Date.now()): [string, string][] {
110 if (state === null) return forgeLines(rows, sender, now);
111 const shown = narrowByState(rows, state, now);
112 const head: [string, string] = ["Showing", `${CLIENT_STATE_WORDS[state]} (${String(shown.length)} of ${String(rows.length)}) · f for the next view`];
113 return shown.length === 0 ? [head, ["", `${CLIENT_STATE_EMPTY[state]} · f shows all`]] : [head, ...forgeLines(shown, sender, now)];
114 }
115
116 export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Session, from: ClientState | null = null): Screen {
117 let state = from;
118 let lines = stateLines(rows, state, session?.user?.isAdmin === true);
106119 // Stop and Remove are the page's buttons, through the same actions (`spawn/manage.ts`).
107120 const choose = (title: string, act: (name: string) => void): void => {
108121 const items = rows.filter((r) => r.made).map((r) => ({ id: r.name, label: r.name, hint: r.awake === true ? "awake" : "asleep" }));
@@ -208,7 +221,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
208221 };
209222 const screen: Screen = {
210223 title: "Forges you sent",
211 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["w"], "raise to xlarge"), binding(["esc"], "close")],
224 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["esc"], "close")],
212225 render(area, s) {
213226 const c = ctx.theme.c;
214227 const w = Math.min(100, Math.max(30, area.w - 6));
@@ -220,7 +233,10 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
220233 },
221234 key(e) {
222235 if (e.key === "esc" || e.key === "q") ctx.pop();
223 else if (e.key === "s" && session !== undefined)
236 else if (e.key === "f") {
237 state = nextClientState(state);
238 lines = stateLines(rows, state, session?.user?.isAdmin === true);
239 } else if (e.key === "s" && session !== undefined)
224240 choose("Stop which forge?", (name) => void stopForge(session.app, name).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger")));
225241 else if (e.key === "n") newLink();
226242 else if (e.key === "l") changeOne("revoke");
src/web/pages/forges.ts +20 −8
@@ -35,6 +35,7 @@ import { REACH_SETTINGS, reachByForge, type ForgeReach } from "../../actions/chi
3535 import { forgeReachRows } from "./hosted-forges.ts";
3636 import { keptWords, readHosted } from "../../snapshot/hosted.ts";
3737 import { archiveForge, archivedForges, restoreForge, type ArchiveRecord } from "../../spawn/archive.ts";
38 import { CLIENT_STATES, CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, parseClientState, stateCounts } from "../../spawn/client_state.ts";
3839 import { claimedWords, isForgeSort, keepWords, SORT_WORDS, sortForges, type ForgeSort } from "../../spawn/keep_words.ts";
3940 import { CHILD_NAME } from "../../spawn/placement.ts";
4041 import { forgesMemory, memoryOverLine } from "../../spawn/memory_fit.ts";
@@ -241,7 +242,11 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
241242 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
242243 const asked = ctx.url.searchParams.get("sort");
243244 const sort: ForgeSort = isForgeSort(asked) ? asked : "attention";
244 const rows = sortForges(await timePhaseAsync(ctx.request, "clients", () => servedRows(ctx.app)), sort);
245 const everyone = sortForges(await timePhaseAsync(ctx.request, "clients", () => servedRows(ctx.app)), sort);
246 const state = parseClientState(ctx.url.searchParams.get("state"));
247 const now = Date.now();
248 const counts = stateCounts(everyone, now);
249 const rows = narrowByState(everyone, state, now);
245250 const archived = archivedForges(ctx.app);
246251 const full = timePhase(ctx.request, "room", () => noRoom(ctx.app));
247252 // Two small tables, by name: the rows themselves come from memory, and this reads no ledger.
@@ -264,25 +269,32 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
264269 actions: action,
265270 })}
266271 ${over === undefined ? null : html`<p class="muted small" role="status" data-memory-over>${over}</p>`}
267 ${receipt(ctx, rows)}
268 ${rows.length === 0
272 ${receipt(ctx, everyone)}
273 ${everyone.length === 0
269274 ? html`<section class="settings-block">
270275 <h2>No forges sent yet</h2>
271276 <p>${action}</p>
272277 </section>`
273278 : html`<section class="settings-block" id="forges-compare">
outdated

Principle 1: Side by side still shows every forge while the list under the same heading narrows. Narrow it too, or say in one line that it shows all.

274279 <h2>Side by side</h2>
275 ${sideBySide(rows)}
280 ${rows.length === 0 ? null : sideBySide(rows)}
281 ${state === null || rows.length === 0 ? null : html`<p class="muted small" data-narrowed>Showing ${CLIENT_STATE_WORDS[state].toLowerCase()} forges only.</p>`}
276282 </section>
277283 <section class="settings-block">
outdated

Principle 8 and 6/7: 'In' is not a plain word; use 'Signed in'. This is one dense line with two navs; make the states a short list of links that wraps cleanly on 360px with touch-sized targets. Also: add the empty state when the narrowed list is empty.

278284 <h2>Forges</h2>
279 <nav class="muted small" aria-label="Sort forges" data-sorts>Sort: ${(Object.keys(SORT_WORDS) as ForgeSort[]).map((k, i) => html`${i > 0 ? " · " : ""}${k === sort ? html`<strong aria-current="true">${SORT_WORDS[k]}</strong>` : html`<a href="/forges?sort=${k}">${SORT_WORDS[k]}</a>`}`)}</nav>
285 <nav class="muted small" aria-label="Sort forges" data-sorts>Sort: ${(Object.keys(SORT_WORDS) as ForgeSort[]).map((k, i) => html`${i > 0 ? " · " : ""}${k === sort ? html`<strong aria-current="true">${SORT_WORDS[k]}</strong>` : html`<a href="/forges?sort=${k}${state === null ? null : html`&amp;state=${state}`}">${SORT_WORDS[k]}</a>`}`)}</nav>
286 <ul class="list setting-list" aria-label="Narrow forges by state" data-states>
287 <li>${state === null ? html`<strong aria-current="true">All (${everyone.length})</strong>` : html`<a href="/forges?sort=${sort}">All (${everyone.length})</a>`}</li>
288 ${CLIENT_STATES.map((k) => html`<li>${k === state ? html`<strong aria-current="true">${CLIENT_STATE_WORDS[k]} (${counts[k]})</strong>` : html`<a href="/forges?state=${k}&amp;sort=${sort}">${CLIENT_STATE_WORDS[k]} (${counts[k]})</a>`}</li>`)}
289 </ul>
280290 <form id="forges-archive-form" method="get" action="/forges/archive" class="mt">
281291 ${btn("Archive selected", { size: "sm", title: "Pick forges with the boxes; the next page says what happens before anything does" })}
282292 </form>
283 <ul class="list setting-list">
284 ${rows.map((r) => forgeRow(r, Date.now(), reachOf.get(r.name), claimsBill(user, r.billTo), keptWords(hostedKept, r.name, Date.now())))}
285 </ul>
293 ${state !== null && rows.length === 0
294 ? html`<p data-empty>${CLIENT_STATE_EMPTY[state]}. <a href="/forges?sort=${sort}">All forges</a></p>`
295 : html`<ul class="list setting-list">
296 ${rows.map((r) => forgeRow(r, now, reachOf.get(r.name), claimsBill(user, r.billTo), keptWords(hostedKept, r.name, now)))}
297 </ul>`}
286298 </section>`}
287299 ${sealedLine(ctx)}
288300 ${archivedSection(ctx, archived)}
test/clients-filter.test.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * The client list narrows by state (#14538): `/forges?state=waiting|in|quiet`, plain links with
3 * counts, the current one marked; an unknown value shows all and is never echoed.
4 */
5
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { commitFiles } from "../src/git/write.ts";
15 import { repoDir } from "../src/git/repos.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { useChildFetch, type ClientRow } from "../src/spawn/clients.ts";
18 import { clientStateOf, narrowByState, nextClientState, parseClientState, stateCounts } from "../src/spawn/client_state.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const NOW = Date.parse("2026-11-10T12:00:00Z");
24 const DAY = 86_400_000;
25 const row = (name: string, over: Record<string, unknown>) =>
26 ({
27 name, made: true, claimed: false, sentAt: new Date(NOW - DAY).toISOString(), lastActivityAt: null,
28 running: null, reach: null, link: { state: "open" }, nextStep: { lastTellAt: null },
29 stage: { key: "sent" }, ...over,
30 }) as unknown as ClientRow;
31
32 const rows = [
33 row("w", {}),
34 row("o", { stage: { key: "opened" }, link: { state: "used" } }),
35 row("i", { claimed: true, stage: { key: "signedin" }, lastActivityAt: new Date(NOW - 1000).toISOString() }),
36 row("q", { claimed: null, stage: { key: "sent" } }),
37 ];
38
39 describe("client states", () => {
40 test("each state narrows to its own rows", () => {
41 expect(narrowByState(rows, "waiting", NOW).map((r) => r.name)).toEqual(["w"]);
42 expect(narrowByState(rows, "in", NOW).map((r) => r.name)).toEqual(["o", "i"]);
43 expect(narrowByState(rows, "quiet", NOW).map((r) => r.name)).toEqual(["q"]);
44 expect(stateCounts(rows, NOW)).toEqual({ waiting: 1, in: 2, quiet: 1 });
45 expect(clientStateOf(rows[3]!, NOW)).toBe("quiet");
46 });
47 test("f walks waiting, in, quiet, then all", () => {
48 expect(nextClientState(null)).toBe("waiting");
49 expect(nextClientState("waiting")).toBe("in");
50 expect(nextClientState("in")).toBe("quiet");
51 expect(nextClientState("quiet")).toBeNull();
52 });
53 test("anything else is ignored", () => {
54 expect(parseClientState("<b>")).toBeNull();
55 expect(parseClientState(null)).toBeNull();
56 expect(narrowByState(rows, parseClientState("nope"), NOW)).toHaveLength(4);
57 });
58 });
59
60 describe("the client list page", () => {
61 let dir = "";
62 let app: App;
63 let servers: Servers;
64 let cookie = "";
65 const get = async (q: string) => {
66 const res = await fetch(`${servers.url}/forges${q}`, { headers: { cookie } });
67 return res.text();
68 };
69
70 beforeAll(async () => {
71 dir = await mkdtemp(join(tmpdir(), "forge-clients-filter-"));
72 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
73 const pw = "a-long-client-filter-passphrase";
74 const alice = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: pw, isAdmin: true });
75 if (!alice.ok) throw new Error("user");
76 const rw = createToken(app.db, alice.value.id, "rw", "rw").token;
77 const repo = await createRepo(app, alice.value, { name: "bakery" });
78 if (!repo.ok) throw new Error("repo");
79 const c = await commitFiles(repoDir(app.reposRoot, "alice", "bakery"), {
80 branch: "main", message: "bakery", files: [{ path: "README.md", content: "# bakery\n" }], author: { name: "a", email: "[email protected]" },
81 });
82 if (!c.ok) throw new Error("commit");
83 servers = await serve(app);
84 useChildFetch(app, () => Promise.reject(new Error("unreachable")));
85 const made = await fetch(`${servers.url}/api/v1/forges`, {
86 method: "POST",
87 headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" },
88 body: JSON.stringify({ name: "maria", for: "Maria", apps: ["alice/bakery"], dryRun: false }),
89 });
90 if (made.status !== 201) throw new Error(`spawn ${made.status}`);
91 const res = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: pw }), redirect: "manual" });
92 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
93 });
94 afterAll(async () => {
95 await servers.stop();
96 await rm(dir, { recursive: true, force: true });
97 });
98
99 test("three links with counts, the current one marked, no script", async () => {
100 const body = await get("?state=quiet");
101 const nav = body.match(/<ul[^>]*data-states[\s\S]*?<\/ul>/)![0];
102 expect(nav).toContain('href="/forges?state=waiting&amp;sort=attention"');
103 expect(nav).toContain('href="/forges?state=in&amp;sort=attention"');
104 expect(nav).toMatch(/<strong aria-current="true">Quiet \(1\)<\/strong>/);
105 expect(nav).not.toContain("<script");
106 expect(nav).toContain("Waiting (0)");
107 });
108 test("a state narrows the list; an unknown value shows all", async () => {
109 expect(await get("?state=quiet")).toContain('data-forge="maria"');
110 expect(await get("?state=waiting")).not.toContain('data-forge="maria"');
111 expect(await get("?state=bogus")).toContain('data-forge="maria"');
112 });
113 test("the state is a list, 'In' reads Signed in", async () => {
114 const nav = (await get(""))!.match(/<ul[^>]*data-states[\s\S]*?<\/ul>/)![0];
115 expect(nav).toContain("Signed in (0)");
116 expect(nav.match(/<li>/g)).toHaveLength(4);
117 });
118 test("a state with no forges says so and links back to all; side by side narrows too", async () => {
119 const body = await get("?state=waiting");
120 expect(body).toContain("No forges are waiting");
121 expect(body).toMatch(/data-empty[^>]*>[^<]*<a href="\/forges\?sort=attention">All forges/);
122 expect(body).not.toContain('data-compare="maria"');
123 const quiet = await get("?state=quiet");
124 expect(quiet).toContain('data-compare="maria"');
125 expect(quiet).toContain("Showing quiet forges only.");
126 expect(await get("")).toContain('data-compare="maria"');
127 });
128 test("markup in the value is not echoed", async () => {
129 const body = await get("?state=%3Cscript%3Ealert(1)%3C/script%3E");
130 expect(body).not.toContain("alert(1)");
131 expect(body).toContain("All (1)");
132 });
133 });
test/tui-forges.test.ts +34 −1
@@ -6,7 +6,7 @@ import { join } from "node:path";
66 import { createApp, type App as Forge } from "../src/app.ts";
77 import { createUser, getUserByName } from "../src/core/users.ts";
88 import { createForgeApp } from "../src/tui/forge.ts";
9 import { fitLines, forgeLines } from "../src/tui/screens/forges.ts";
9 import { fitLines, forgeLines, stateLines } from "../src/tui/screens/forges.ts";
1010 import { firstScreenLine } from "../src/core/next-steps.ts";
1111 import { runningWords, type ClientRow } from "../src/spawn/clients.ts";
1212 import type { TuiIdentity } from "../src/tui/session.ts";
@@ -42,6 +42,26 @@ const row = (over: Partial<ClientRow>): ClientRow => ({
4242 ...over,
4343 });
4444
45 describe("forges narrowed by state in the terminal (#14538)", () => {
46 const NOW = Date.parse("2026-11-10T12:00:00Z");
47 const sent = row({ name: "w", for: null, link: { state: "open" } as ClientRow["link"], stage: { key: "sent" } as ClientRow["stage"], sentAt: new Date(NOW - 1000).toISOString() });
48 const claimed = row({ name: "c", claimed: true, stage: { key: "signedin" } as ClientRow["stage"] });
49 test("a state keeps its own forges and heads the list with the count", () => {
50 const lines = stateLines([sent, claimed], "waiting", false, NOW);
51 expect(lines[0]).toEqual(["Showing", "Waiting (1 of 2) · f for the next view"]);
52 expect(lines.map((l) => l[0])).toContain("w");
53 expect(lines.map((l) => l[0])).not.toContain("c");
54 expect(stateLines([sent, claimed], "in", false, NOW)[0]![1]).toContain("Signed in (1 of 2)");
55 });
56 test("a state with none says so and how to get back", () => {
57 const lines = stateLines([claimed], "waiting", false, NOW);
58 expect(lines[1]).toEqual(["", "No forges are waiting · f shows all"]);
59 });
60 test("no state is the plain list", () => {
61 expect(stateLines([sent, claimed], null, false, NOW)).toEqual(forgeLines([sent, claimed], false, NOW));
62 });
63 });
64
4565 describe("forges you sent in the terminal", () => {
4666 let dataDir: string;
4767 let forge: Forge;
@@ -103,6 +123,19 @@ describe("forges you sent in the terminal", () => {
103123 h.stop();
104124 });
105125
126 test("f narrows the screen to a state; the next press goes on until all", async () => {
127 const h = boot("alice");
128 await h.palette();
129 await h.enter();
130 await h.press("f");
131 expect(h.text()).toContain("No forges are waiting");
132 await h.press("f");
133 await h.press("f");
134 await h.press("f");
135 expect(h.text()).toContain("You have not sent a forge yet");
136 h.stop();
137 });
138
106139 test("the screen lists the keys for a link: end it, undo it; with none to change it says so", async () => {
107140 const h = boot("alice");
108141 await h.palette();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs