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

The client list header says in one line how many forges were sent this week and how many were opened #14732

Merged opened this

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

Merged

torque/forge:torque/14724-the-client-list-header-says-in-one-line → main 7 commits fork 3 threads · 3 unresolved

  • Merged. torque/14724-the-client-list-header-says-in-one-line was merged into main as eec34e0.

Review

Sign in to review this change.
6 files changed +201 −2
docs/features/client-week-line.md added +11
@@ -0,0 +1,11 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: The client list's week line
4 ---
5 # The client list's week line
6
7 At the top of the client list, an admin reads one line: how many forges were sent this week and how many links were opened. `This week: 3 sent, 2 opened.`, or `None sent this week, 0 opened.` when nothing was sent. It is on the web page (`/forges`, a `data-week` paragraph) and at the top of the terminal screen "Forges you sent"; both come from `weekLine` in `src/spawn/client_week.ts`. An empty list has no line.
8
9 - **Week:** Monday 00:00 UTC up to now. A forge counts as sent by its send time, and a link as opened by its opened (else used) time, so a forge sent last week and opened this week counts only as opened.
10 - **Scope:** the line counts every forge sent, not the rows beneath it: a state filter or a search narrows the list but not the line, so the line can differ from the number of rows shown.
11 - **Cost:** one pass over the rows already loaded; no query.
src/spawn/client_week.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * The client list's one-line week (#14724): how many forges were sent this week and how many of
3 * those links were opened. One pass over the rows already loaded; no query.
4 */
5
6 /** The two fields of a client row this line reads. */
7 export interface WeekRow {
8 readonly sentAt: string | null;
9 readonly link: { readonly openedAt?: string | null; readonly usedAt?: string | null } | null;
10 }
11
12 const DAY_MS = 86_400_000;
13
14 /**
15 * Start of the week containing `now`: Monday 00:00 UTC, in epoch ms. (1970-01-01 was a Thursday,
16 * so days since the epoch plus 3 is days since a Monday.)
17 */
18 export function weekStart(now: number): number {
19 const day = Math.floor(now / DAY_MS);
20 return (day - ((day + 3) % 7)) * DAY_MS;
21 }
22
23 /** Counts of sends and opens whose time falls from this week's Monday 00:00 UTC up to `now`. */
24 export function weekCounts(rows: readonly WeekRow[], now: number): { sent: number; opened: number } {
25 const from = weekStart(now);
26 const within = (iso: string | null | undefined): boolean => {
27 if (iso == null) return false;
28 const t = Date.parse(iso);
29 return t >= from && t <= now;
30 };
31 let sent = 0;
32 let opened = 0;
33 for (const r of rows) {
34 if (within(r.sentAt)) sent++;
35 if (within(r.link?.openedAt ?? r.link?.usedAt)) opened++;
36 }
37 return { sent, opened };
38 }
39
40 /** `This week: 3 sent, 2 opened.`, or `None sent this week, 0 opened.` when nothing was sent. */
41 export function weekLine(rows: readonly WeekRow[], now: number): string {
42 const { sent, opened } = weekCounts(rows, now);
43 return sent === 0 ? `None sent this week, ${opened} opened.` : `This week: ${sent} sent, ${opened} opened.`;
outdated

Principle 1 and 8: 'This week: none sent this week, 0 opened.' repeats itself. Use 'None sent this week, 0 opened.' for the zero case; keep the phrase 'none sent this week' from the issue.

44 }
src/tui/screens/forges.ts +11 −2
@@ -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 { weekLine } from "../../spawn/client_week.ts";
1617 import { parseClientQuery, searchClients } from "../../spawn/client_search.ts";
1718 import { CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, nextClientState, type ClientState } from "../../spawn/client_state.ts";
1819 import { diskWords } from "../../spawn/disk_mount.ts";
@@ -118,13 +119,21 @@ export function stateLines(rows: readonly ClientRow[], state: ClientState | null
118119 return [head, ["", state === null ? none : `${none} · f shows all`]];
119120 }
120121
122 /**
123 * The list under its one-line week (#14724), as /forges says it over all the forges sent, not the
124 * narrowed rows; nothing above an empty list.
125 */
126 export function withWeek(rows: readonly ClientRow[], lines: [string, string][], now = Date.now()): [string, string][] {
127 return rows.length === 0 ? lines : [["", weekLine(rows, now)], ...lines];
128 }
129
121130 export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Session, from: ClientState | null = null): Screen {
122131 let state = from;
123132 let q = "";
124133 const redraw = (): void => {
125 lines = stateLines(rows, state, session?.user?.isAdmin === true, Date.now(), q);
134 lines = withWeek(rows, stateLines(rows, state, session?.user?.isAdmin === true, Date.now(), q));
126135 };
127 let lines = stateLines(rows, state, session?.user?.isAdmin === true);
136 let lines = withWeek(rows, stateLines(rows, state, session?.user?.isAdmin === true));
128137 // Stop and Remove are the page's buttons, through the same actions (`spawn/manage.ts`).
129138 const choose = (title: string, act: (name: string) => void): void => {
130139 const items = rows.filter((r) => r.made).map((r) => ({ id: r.name, label: r.name, hint: r.awake === true ? "awake" : "asleep" }));
src/web/pages/forges.ts +2
@@ -36,6 +36,7 @@ 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";
3838 import { CLIENT_STATES, CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, parseClientState, stateCounts } from "../../spawn/client_state.ts";
39 import { weekLine } from "../../spawn/client_week.ts";
3940 import { parseClientQuery, searchClients } from "../../spawn/client_search.ts";
4041 import { claimedWords, isForgeSort, keepWords, SORT_WORDS, sortForges, type ForgeSort } from "../../spawn/keep_words.ts";
4142 import { CHILD_NAME } from "../../spawn/placement.ts";
@@ -273,6 +274,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
273274 })}
274275 ${over === undefined ? null : html`<p class="muted small" role="status" data-memory-over>${over}</p>`}
275276 ${receipt(ctx, everyone)}
277 ${everyone.length === 0 ? null : html`<p class="muted small" data-week>${weekLine(everyone, now)}</p>`}

Both doors: the terminal client list has no such line. Add it in the matching src/tui/ screen from weekLine, and write docs/features/<name>.md. Also this counts everyone, not the filtered rows beneath it; the header can disagree with the list under a state filter or search. Decide and say which.

276278 ${everyone.length === 0
277279 ? html`<section class="settings-block">
278280 <h2>No forges sent yet</h2>
test/clients-week-line.test.ts added +109
@@ -0,0 +1,109 @@
1 import { afterAll, describe, expect, test } from "bun:test";
2 import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { listChildren, spawnForge } from "../src/actions/spawn.ts";
6 import { createApp, type App } from "../src/app.ts";
7 import type { Ctx } from "../src/http/context.ts";
8 import type { User } from "../src/core/users.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { hostedPlacement } from "../src/spawn/placement.ts";
11 import { clientRows } from "../src/spawn/clients.ts";
12 import { forgesPage } from "../src/web/pages/forges.ts";
13 import { forgeLines, withWeek } from "../src/tui/screens/forges.ts";
14 import { weekCounts, weekLine, weekStart, type WeekRow } from "../src/spawn/client_week.ts";
15
16 // Wednesday 2026-11-18 12:00 UTC; that week began Monday 2026-11-16 00:00 UTC.
17 const NOW = Date.parse("2026-11-18T12:00:00Z");
outdated

Only the pure functions are tested. Add a test that renders the forges page and asserts the data-week paragraph and its omission when the list is empty; today deleting the forges.ts line fails nothing.

18 const row = (sentAt: string | null, openedAt: string | null = null): WeekRow => ({
19 sentAt,
20 link: openedAt === null ? null : { openedAt, usedAt: null },
21 });
22
23 describe("the client list's week line", () => {
24 test("the week starts Monday 00:00 UTC", () => {
25 expect(new Date(weekStart(NOW)).toISOString()).toBe("2026-11-16T00:00:00.000Z");
26 expect(new Date(weekStart(Date.parse("2026-11-22T23:59:59Z"))).toISOString()).toBe("2026-11-16T00:00:00.000Z");
27 expect(new Date(weekStart(Date.parse("2026-11-23T00:00:00Z"))).toISOString()).toBe("2026-11-23T00:00:00.000Z");
28 });
29
30 test("rows across the boundary: only this week's count", () => {
31 const rows = [
32 row("2026-11-15T23:59:59Z", "2026-11-15T23:59:59Z"), // Sunday before: out
33 row("2026-11-16T00:00:00Z", "2026-11-17T08:00:00Z"), // Monday 00:00: in, opened in
34 row("2026-11-17T09:00:00Z"), // in, not opened
35 row("2026-11-10T09:00:00Z", "2026-11-16T10:00:00Z"), // sent earlier, opened this week
36 ];
37 expect(weekCounts(rows, NOW)).toEqual({ sent: 2, opened: 2 });
38 expect(weekLine(rows, NOW)).toBe("This week: 2 sent, 2 opened.");
39 });
40
41 test("nothing sent says so", () => {
42 expect(weekLine([row("2026-11-01T00:00:00Z")], NOW)).toBe("None sent this week, 0 opened.");
43 expect(weekLine([], NOW)).toContain("None sent this week");
44 });
45 });
46
47 // The page and the terminal list, over real children: one sent now, one sent a month ago.
48 const dirs: string[] = [];
49 afterAll(() => {
50 for (const d of dirs) rmSync(d, { recursive: true, force: true });
51 });
52 async function forgeWith(names: string[], old: string[]): Promise<{ app: App; admin: User }> {
53 const dir = mkdtempSync(join(tmpdir(), "forge-week-"));
54 dirs.push(dir);
55 const app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
56 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", isAdmin: true });
57 if (!made.ok) throw new Error("user");
58 for (const name of names) {
59 const s = await spawnForge(
60 app,
61 made.value,
62 { name, org: name, apps: [], carryBriefs: false, carrySubscriptions: false },
63 { catalog: [], briefs: [], subscriptions: [] },
64 {
65 placement: hostedPlacement({ host: "forge.test" }),
66 request: new Request("https://forge.test/spawn", { method: "POST", headers: { origin: "https://forge.test" } }),
67 url: new URL("https://forge.test/spawn"),
68 },
69 );
70 if (!s.ok) throw new Error(JSON.stringify(s.error));
71 }
72 for (const name of old) {
73 const file = join(dir, "spawn", `${name}.json`);
74 const ledger = JSON.parse(readFileSync(file, "utf8"));
75 ledger.createdAt = "2020-01-01T00:00:00.000Z";
76 writeFileSync(file, JSON.stringify(ledger));
77 }
78 return { app, admin: made.value };
79 }
80 const pageOf = async (app: App, user: User): Promise<string> => {
81 const request = new Request("https://forge.test/forges");
82 const ctx: Ctx = { app, request, url: new URL(request.url), params: {}, auth: { user, scope: "rw", via: "session" }, theme: undefined };
83 return (await forgesPage(ctx)).text();
84 };
85
86 describe("the week line on the page and in the terminal", () => {
87 test("/forges says the week over rows across the boundary, and says nothing when the list is empty", async () => {
88 const { app, admin } = await forgeWith(["fresh", "stale"], ["stale"]);
89 expect(await listChildren(app)).toHaveLength(2);
90 const body = await pageOf(app, admin);
91 expect(body).toMatch(/<p class="muted small" data-week>This week: 1 sent, 0 opened\.<\/p>/);
92 const empty = await forgeWith([], []);
93 expect(await pageOf(empty.app, empty.admin)).not.toContain("data-week");
94 });
95
96 test("a stale-only list says none sent this week", async () => {
97 const { app, admin } = await forgeWith(["stale"], ["stale"]);
98 expect(await pageOf(app, admin)).toContain("data-week>None sent this week, 0 opened.</p>");
99 });
100
101 test("the terminal list carries the same line, over all rows, and none when empty", async () => {
102 const { app } = await forgeWith(["fresh", "stale"], ["stale"]);
103 const rows = await clientRows(app);
104 const lines = withWeek(rows, forgeLines(rows));
105 expect(lines[0]).toEqual(["", "This week: 1 sent, 0 opened."]);
106 expect(lines).toHaveLength(forgeLines(rows).length + 1);
107 expect(withWeek([], forgeLines([]))).toEqual(forgeLines([]));
108 });
109 });
test/tui-forges.test.ts +24
@@ -4,6 +4,8 @@ import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp, type App as Forge } from "../src/app.ts";
7 import { spawnForge } from "../src/actions/spawn.ts";
8 import { hostedPlacement } from "../src/spawn/placement.ts";
79 import { createUser, getUserByName } from "../src/core/users.ts";
810 import { createForgeApp } from "../src/tui/forge.ts";
911 import { fitLines, forgeLines, stateLines } from "../src/tui/screens/forges.ts";
@@ -129,6 +131,7 @@ describe("forges you sent in the terminal", () => {
129131 expect(await h.palette()).toContain("each forge sent");
130132 await h.enter();
131133 expect(h.text()).toContain("You have not sent a forge yet");
134 expect(h.text()).not.toContain("sent this week");
132135 h.stop();
133136 });
134137
@@ -183,6 +186,27 @@ describe("forges you sent in the terminal", () => {
183186 h.stop();
184187 });
185188
189 test("with a forge sent, the screen's first line is the week's count", async () => {
190 const alice = getUserByName(forge.db, "alice")!;
191 const s = await spawnForge(
192 forge,
193 alice,
194 { name: "weekly", org: "weekly", apps: [], carryBriefs: false, carrySubscriptions: false },
195 { catalog: [], briefs: [], subscriptions: [] },
196 {
197 placement: hostedPlacement({ host: "forge.test" }),
198 request: new Request("https://forge.test/spawn", { method: "POST", headers: { origin: "https://forge.test" } }),
199 url: new URL("https://forge.test/spawn"),
200 },
201 );
202 if (!s.ok) throw new Error(JSON.stringify(s.error));
203 const h = boot("alice");
204 await h.palette();
205 await h.enter();
206 expect(h.text()).toContain("This week: 1 sent, 0 opened.");
207 h.stop();
208 });
209
186210 test("an unclaimed row says the days its link has left, and says expired", () => {
187211 const now = Date.parse("2026-11-16T12:00:00Z");
188212 const line = (link: ClientRow["link"]) => forgeLines([row({ link })], false, now)[0]![1];

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs