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

The wallet page lists the last 20 spends, each as one row with the run it paid for #13324

Merged opened this

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

Merged

scout/forge:scout/13298-the-wallet-page-lists-the-last-20-spends → main 8 commits fork 4 threads · 4 unresolved

  • Merged. scout/13298-the-wallet-page-lists-the-last-20-spends was merged into main as 2dfdbeb.

Review

Sign in to review this change.
10 files changed +477 −5
docs/features/README.md +1
@@ -321,6 +321,7 @@ Read with the guide page [Hosting forges for others, and getting paid](../guide-
321321 - [The forge's spend in the terminal](forge-usage-terminal.md)
322322 - [The last Stripe event and refused signatures](stripe-events-line.md)
323323 - [The money line — cost, revenue and the gap](money.md)
324 - [The repository wallet — the last 20 spends](wallet.md)
324325 - [The page that answers "make me a forge"](forge-made.md)
325326 - [The Plan row in a forge's settings](plan-row.md)
326327 - [The selling funnel](selling-funnel.md)
docs/features/wallet.md added +19
@@ -0,0 +1,19 @@
1 # The repository wallet — the last 20 spends
2
3 `/owner/name/wallet` lists the last 20 spends of one app, newest first, one
4 row each (#13298): the date (UTC), the amount in US dollars, what it paid
5 for (`build #12 Fix the login`: the run's kind and the issue or pull it
6 worked on), and a link to the run. Rows come from the usage ledger
7 (`core/usage.ts`), the provider's list price, not money charged. A run that
8 did not end well says so beside what it paid for.
9
10 - **Who:** whoever may read the app's spend, a writer (`canSeeOwnerFacts`, as
11 the usage API). Anyone else gets the not-found page.
12 - **Where:** a link beside the statement in the app's settings → App; at the

Claims a terminal palette entry that this pull does not contain. Add the screen, or this doc is wrong. Both doors are required.

13 terminal, `owner/name — Wallet` in the `:` palette while the repository is
14 open (`j`/`k` move).
15 - **Speed:** the read walks `usage_repo (repo_id, at)` for twenty rows, no
16 scan and no sort, so it does not grow with the ledger
17 (`test/wallet.test.ts` counts its statements at 10,000 rows and reads the plan).
18 - **Left out:** paging beyond 20, and a JSON form; `GET /api/v1/repos/:owner/:name/usage`
19 already gives the recent lines.
src/actions/wallet.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * The repository wallet: its last 20 spends, one row each, newest first —
3 * the date, the dollars, what the run paid for and the run itself. Read from
4 * the usage ledger (`core/usage.ts`) through `usage_repo (repo_id, at)`, so
5 * the cost is twenty index steps however long the ledger grows. Dollars are
6 * the provider's list price (`costUsd`), not money charged.
7 *
8 * Spend is the owner's own fact, so who may read it is `canSeeOwnerFacts`
9 * (a writer), the gate `readUsage` holds; anyone else is told `not_found`.
10 * The page, the terminal and any caller get the same rows from here.
11 */
12
13 import type { App } from "../app.ts";
14 import { getIssuesByIds } from "../core/issues.ts";
15 import { canSeeOwnerFacts, type Repo } from "../core/repos.ts";
16 import type { UsageKind, UsageOutcome } from "../core/usage.ts";
17 import type { User } from "../core/users.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19
20 export const WALLET_ROWS = 20;
21
22 export interface WalletSpend {
23 readonly runId: string;
24 /** ISO 8601 UTC. */
25 readonly at: string;
26 /** `YYYY-MM-DD`, UTC. */
27 readonly date: string;
28 readonly costUsd: number;
29 readonly kind: UsageKind;
30 readonly outcome: UsageOutcome;
31 /** The issue or pull the run worked on, or null. */
32 readonly issue: number | null;
33 /** What it paid for, in words: `build #12 Fix the login`. */
34 readonly paidFor: string;
35 /** The run's page, `/owner/name/runs/<id>`. */
36 readonly runPath: string;
37 }
38
39 export interface Wallet {
40 readonly app: string;
41 readonly spends: readonly WalletSpend[];
42 }
43
44 interface Row {
45 run_id: string;
46 issue_id: string | null;
47 kind: UsageKind;
48 outcome: UsageOutcome;
49 cost_usd: number;
50 at: string;
51 }
52
53 /** `rowid` breaks ties so the sort walks the index and sorts nothing. */
54 export const LAST_SPENDS_SQL = `SELECT run_id, issue_id, kind, outcome, cost_usd, at FROM usage
55 WHERE repo_id = ?1 ORDER BY at DESC, rowid DESC LIMIT ?2`;
56
57 export function readWallet(app: App, actor: User | undefined, repo: Repo): Result<Wallet, "not_found"> {
58 if (!canSeeOwnerFacts(app.db, repo, actor)) return err("not_found");
59 const rows = app.db.query<Row, [string, number]>(LAST_SPENDS_SQL).all(repo.id, WALLET_ROWS);
60 const issues = getIssuesByIds(
61 app.db,
62 rows.flatMap((r) => (r.issue_id === null ? [] : [r.issue_id])),
63 );
64 const base = `/${repo.ownerName}/${repo.name}`;
65 return ok({
66 app: `${repo.ownerName}/${repo.name}`,
67 spends: rows.map((r) => {
68 const issue = r.issue_id === null ? undefined : issues.get(r.issue_id);
69 return {
70 runId: r.run_id,
71 at: r.at,
72 date: r.at.slice(0, 10),
73 costUsd: r.cost_usd,
74 kind: r.kind,
75 outcome: r.outcome,
76 issue: issue?.number ?? null,
77 paidFor: issue === undefined ? r.kind : `${r.kind} #${issue.number} ${issue.title}`,
78 runPath: `${base}/runs/${encodeURIComponent(r.run_id)}`,
79 };
80 }),
81 });
82 }
src/http/server.ts +2
@@ -579,6 +579,7 @@ import { startPullSchedule } from "../apps/pull_schedule.ts";
579579 import { startGithubPull } from "../perf/github_traffic.ts";
580580 import { appSourcesPage } from "../web/pages/sources.ts";
581581 import { statementPage } from "../web/pages/statement.ts";
582 import { walletPage } from "../web/pages/wallet.ts";
582583 import { createViewWriter } from "../perf/views_store.ts";
583584 import { createReadWriter, readOf } from "../perf/reads.ts";
584585 import { parseServerTiming } from "../perf/record.ts";
@@ -1699,6 +1700,7 @@ export function buildRouter(): Router<Handler> {
16991700 router.add("GET", "/:owner/:name/settings/app", appSettingsPage);
17001701 router.add("GET", "/:owner/:name/settings/app/traffic", appSourcesPage);
17011702 router.add("GET", "/:owner/:name/settings/app/statement", statementPage);
1703 router.add("GET", "/:owner/:name/wallet", walletPage);
17021704 router.add("GET", "/:owner/:name/settings/machines", machinesSettingsPage);
17031705 // The shell page; an upgrade at the same path is the socket (`machines/shell.ts`).
17041706 router.add("GET", "/:owner/:name/machines/:machine/shell", machineShellPage);
src/tui/screens/money.ts +52 −3
@@ -5,12 +5,16 @@
55 * who is a person for the forge's, the repository's admins and forge admins
66 * for an app's. The forge's is a palette entry; an app's is a command while
77 * its repository is open. Anyone else is offered neither and, were a screen
8 * reached, sees no figures. Read-only; US dollars, UTC days.
8 * reached, sees no figures. Read-only; US dollars, UTC days. The app's
9 * wallet (docs/features/wallet.md, #13298), its last 20 spends from
10 * `readWallet`, sits at the foot: the same page's rows, a command while the
11 * repository is open for whoever may read its spend.
912 */
1013
1114 import { mayReadStatement } from "../../actions/statement.ts";
15 import { readWallet, type WalletSpend } from "../../actions/wallet.ts";
1216 import { readAppMoney, readForgeMoney, type AppMoney, type ForgeMoney, type MoneyLine } from "../../actions/money.ts";
13 import type { Repo } from "../../core/repos.ts";
17 import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
1418 import type { Ctx, Screen } from "../app/app.ts";
1519 import { binding } from "../app/keys.ts";
1620 import type { Command } from "../app/palette.ts";
@@ -40,7 +44,10 @@ export function forgeMoneyRows(m: ForgeMoney): ListRow[] {
4044 ];
4145 }
4246
43 /** The app card's rows: the three numbers, where it was awake, and its share of the forge's own server. */
47 /**
48 * The app card's rows: the three numbers, where it was awake, and its share of the forge's own
49 * server.
50 */
4451 export function appMoneyRows(m: AppMoney): ListRow[] {
4552 const awake = m.ownedSeconds + m.cloudSeconds;
4653 return [
@@ -103,3 +110,45 @@ export function moneyCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Com
103110 },
104111 ];
105112 }
113
114 /** One row a spend: what it paid for, then date, dollars and the run's id. */
115 export function walletRows(spends: readonly WalletSpend[]): ListRow[] {
116 return spends.map((s) => ({
117 title: s.paidFor,
118 meta: `${s.date} · $${s.costUsd.toFixed(2)} · run ${s.runId.slice(-8)}`,
119 }));
120 }
121
122 export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
123 const state = new ListState();
124 const rows = (): ListRow[] => {
125 const w = readWallet(f.app, f.user, repo);
126 return w.ok ? walletRows(w.value.spends) : [];
127 };
128 return {
129 title: `${repo.ownerName}/${repo.name} — Wallet`,
130 keys: [binding(["j", "k"], "move cursor")],
131 render(area, s) {
132 const c = ctx.theme.c;
133 const r = rows();
134 const [head, list] = split(area, "v", [len(1), fill(1)]);
135 const said = r.length === 0 ? "nothing spent yet" : "last 20 spends · US dollars · days are UTC";
136 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
137 drawList(s, list!, c, state, r);
138 },
139 key: (e) => state.key(e, rows().length),
140 };
141 }
142
143 /** "owner/name — Wallet" while a repository is open, to whoever may read its spend. */
144 export function walletCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
145 if (repo === undefined || !canSeeOwnerFacts(f.app.db, repo, f.user)) return [];
146 return [
147 {
148 id: "app-wallet",
149 title: `${repo.ownerName}/${repo.name} — Wallet`,
150 hint: "this app's last 20 spends, each with its run",
151 run: () => ctx.push(walletScreen(f, ctx, repo)),
152 },
153 ];
154 }
src/tui/screens/workspace.ts +2 −1
@@ -196,7 +196,7 @@ import { agentsMdCommands } from "./agents_md.ts";
196196 import { queueCommands } from "./queuegrowth.ts";
197197 import { blockedCommands } from "./blocked.ts";
198198 import { statementCommands } from "./statement.ts";
199 import { moneyCommands } from "./money.ts";
199 import { moneyCommands, walletCommands } from "./money.ts";
200200 import { adapterCommands } from "./adapter.ts";
201201 import { atlasCommands } from "./atlas.ts";
202202 import { externalEditor, editorHint, hasExternalEditor } from "./external.ts";
@@ -2134,6 +2134,7 @@ export function workspaceScreen(
21342134 ...blockedCommands(f, ctx, repo),
21352135 ...statementCommands(f, ctx, repo),
21362136 ...moneyCommands(f, ctx, repo),
2137 ...walletCommands(f, ctx, repo),
21372138 ...adapterCommands(f, ctx, repo),
21382139 ...atlasCommands(f, ctx, repo),
21392140 ],
src/web/pages/settings.ts +1 −1
@@ -794,7 +794,7 @@ function appSettingsView(
794794 // What the forge would charge (#508): crew spend counts before the repository runs as an app.
795795 const statement = html`<section class="settings-block" id="statement">
796796 <h2>Statement</h2>
797 <p><a href="${base}/settings/app/statement">This month's statement</a></p>
797 <p><a href="${base}/settings/app/statement">This month's statement</a> · <a href="${base}/wallet">Wallet: the last 20 spends</a></p>
798798 </section>`;
799799 if (record === undefined) return html`${form}<div class="mt">${statement}</div>`;
800800 const domains = timePhase(ctx.request, "domains", () =>
src/web/pages/wallet.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * GET /:owner/:name/wallet — the repository's last 20 spends from the usage
3 * ledger, one row each: date, dollars, what it paid for, and a link to the
4 * run (`actions/wallet.ts`). Server-rendered, no script. For whoever may
5 * read the app's spend (a writer); anyone else gets the not-found page.
6 */
7
8 import { readWallet } from "../../actions/wallet.ts";
9 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { loadRepo, repoNotFound } from "../chrome.ts";
12 import { html } from "../html.ts";
13 import { settingsPageResponse } from "./settings.ts";
14
15 export function walletPage(ctx: Ctx): Response {
16 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
17 const repo = timePhase(ctx.request, "repo", () => loadRepo(ctx));
18 if (!repo) return repoNotFound(ctx);
19 const read = timePhase(ctx.request, "wallet", () => readWallet(ctx.app, ctx.auth.user, repo));
20 if (!read.ok) return repoNotFound(ctx);
21 const rendering = performance.now();
22 const w = read.value;
23 const body = html`<section class="settings-block" data-wallet>
24 <h2>Wallet</h2>

Principle 1: the page needs one confident sentence of purpose (e.g. what the last 20 spends of this app paid for), not a bare heading.

25 <p class="small">What ${w.app}'s last 20 spends paid for, newest first, each with the run behind it.</p>
26 ${w.spends.length === 0
27 ? html`<p class="small">Nothing spent yet: the crew's runs on ${w.app} appear here as they report their cost.</p>`
28 : html`<div class="table-scroll">
29 <table class="table">
30 <thead><tr><th>Date (UTC)</th><th class="num">Amount (USD)</th><th>Paid for</th><th>Run</th></tr></thead>
31 <tbody>
32 ${w.spends.map(
33 (s) => html`<tr>
34 <td class="mono">${s.date}</td>
35 <td class="num mono">$${s.costUsd.toFixed(2)}</td>
36 <td>${s.paidFor}${s.outcome === "ok" ? "" : html` <span class="small">(${s.outcome})</span>`}</td>
37 <td><a href="${s.runPath}">${s.runId.slice(-8)}</a></td>
38 </tr>`,
39 )}
40 </tbody>
41 </table>
outdated

Principle 1 and 8: this footer repeats what the heading and column headers ("Amount (USD)", "Date (UTC)") already say. Say it once, in plain words, and drop the footer.

42 </div>`}
43 </section>`;
44 const response = settingsPageResponse(ctx, repo, "app", "Wallet", body);
45 notePhase(ctx.request, "render", performance.now() - rendering);
46 return response;
47 }
test/tui-wallet.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * The terminal's wallet screen (src/tui/screens/money.ts, #13298): a writer
3 * opens "owner/name — Wallet" from the palette and reads the app's last
4 * spends, the page's rows from `readWallet`; a guest or non-writer is offered
5 * no entry and, were the screen reached, a guest sees no rows.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { readWallet } from "../src/actions/wallet.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { createRun } from "../src/core/runs.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { recordUsage } from "../src/core/usage.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { createForgeApp } from "../src/tui/forge.ts";
19 import { repoScreen } from "../src/tui/screens/repo.ts";
20 import { local } from "../src/tui/screens/where.ts";
21 import { walletCommands, walletRows, walletScreen } from "../src/tui/screens/money.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { settleApp } from "./helpers/tui.ts";
24
25 let dir: string;
26 let app: App;
27 let alice: User;
28 let bob: User;
29 let notes: Repo;
30
31 function open(user: User | undefined, terminal = headlessTerminal(140, 50)) {
32 const { app: tui, session } = createForgeApp(
33 app,
34 { sshUsername: user?.username ?? "guest", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
35 { terminal, exitHooks: false },
36 );
37 return { tui, session, terminal };
38 }
39
40 async function drive(user: User | undefined, keys: string[], start: "repo" | "wallet"): Promise<string> {
41 const { tui, session, terminal } = open(user);
42 tui.start();
43 if (start === "repo") tui.ctx.push(repoScreen(session, tui.ctx, local(session, notes)));
44 else tui.ctx.push(walletScreen(session, tui.ctx, notes));
45 await settleApp(tui);
46 for (const k of keys) {
47 terminal.feed(k);
48 await settleApp(tui);
49 }
50 const text = tui.screen.toText();
51 tui.stop?.();
52 return text;
53 }
54
55 beforeAll(async () => {
56 dir = await mkdtemp(join(tmpdir(), "forge-tui-wallet-"));
57 app = createApp({ dataDir: dir, port: 0 });
58 const seed = async (username: string, first: boolean): Promise<User> => {
59 const made = await createUser(app.db, {
60 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
61 password: "a-good-passphrase", adminIfFirst: first,
62 });
63 if (!made.ok) throw new Error(made.error);
64 return made.value;
65 };
66 alice = await seed("alice", true);
67 bob = await seed("bob", false);
68 const made = await createRepo(app, alice, { name: "notes", visibility: "public" });
69 if (!made.ok) throw new Error("repo");
70 notes = made.value;
71 const run = createRun(app.db, { repoId: notes.id, kind: "agent" }).id;
72 recordUsage(app.db, {
73 runId: run, repoId: notes.id, issueId: null, agentId: null, subscriptionId: null,
74 tokensIn: 1, tokensOut: 1, costUsd: 1.5, wallMs: 1, outcome: "ok", at: "2026-11-02T10:00:00.000Z",
75 });
76 });
77 afterAll(async () => {
78 app.close();
79 await rm(dir, { recursive: true, force: true });
80 });
81
82 test("a writer opens the wallet from the palette and reads the spend", async () => {
83 const text = await drive(alice, [":", "notes — Wallet", "\r"], "repo");
84 expect(text).toContain("alice/notes — Wallet");
85 expect(text).toContain("$1.50");
86 expect(text).toContain("2026-11-02");
outdated

This does not test the palette gate. Assert walletCommands(session, ctx, notes) returns [] for a guest and a non-writer and one command for a writer, so removing the canSeeOwnerFacts check fails a test.

87 const w = readWallet(app, alice, notes);
88 if (!w.ok) throw new Error("refused");
89 expect(walletRows(w.value.spends)).toHaveLength(1);
90 });
91
92 test("the palette offers the wallet to a writer only", () => {
93 for (const [user, count] of [[alice, 1], [bob, 0], [undefined, 0]] as const) {
94 const { tui, session } = open(user);
95 const commands = walletCommands(session, tui.ctx, notes);
96 expect(commands).toHaveLength(count);
97 if (count === 1) expect(commands[0]?.title).toBe("alice/notes — Wallet");
98 }
99 });
100
101 test("a guest who reaches the screen sees no rows", async () => {
102 const text = await drive(undefined, [], "wallet");
103 expect(text).not.toContain("$1.50");
104 });
test/wallet.test.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * The repository wallet (#13298): the last 20 spends, gated, escaped, indexed and fast at 10,000
3 * ledger rows.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { readWallet, LAST_SPENDS_SQL } from "../src/actions/wallet.ts";
11 import { createIssue } from "../src/core/issues.ts";
12 import { createRepo as initRepo, type Repo } from "../src/core/repos.ts";
13 import { createRun } from "../src/core/runs.ts";
14 import { recordUsage } from "../src/core/usage.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { proveAll } from "./helpers/verified.ts";
19 import { expectWork, requestStatements } from "./helpers/work.ts";
20 import { statements } from "./helpers/statements.ts";
21
22 quietLogs();
23
24 const PASS = "a-good-passphrase";
25 const ROWS = 10_000;
26 let root = "";
27 let app: App;
28 let servers: Servers;
29 let bob: User;
30 let carol: User;
31 let repo: Repo;
32 let issueRun = "";
33
34 async function cookieOf(username: string): Promise<string> {
35 const res = await fetch(`${servers.url}/signin`, {
36 method: "POST",
37 headers: { origin: servers.url },
38 body: new URLSearchParams({ username, password: PASS }),
39 redirect: "manual",
40 });
41 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
42 }
43
44 beforeAll(async () => {
45 root = mkdtempSync(join(tmpdir(), "forge-wallet-"));
46 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
47 const users: User[] = [];
48 for (const [i, username] of ["alice", "bob", "carol"].entries()) {
49 const u = await createUser(app.db, {
50 origin: "seed",
51 trusted: true,
52 username,
53 email: `${username}@forge.local`,
54 password: PASS,
55 adminIfFirst: i === 0,
56 });
57 if (!u.ok) throw new Error(u.error);
58 users.push(u.value);
59 }
60 bob = users[1]!;
61 carol = users[2]!;
62 proveAll(app);
63 const made = await initRepo(app.db, app.reposRoot, {
64 ownerId: bob.id,
65 name: "wallet-app",
66 visibility: "public",
67 description: "",
68 });
69 if (!made.ok) throw new Error("repo");
70 repo = made.value;
71 const issue = createIssue(app.db, {
72 repoId: repo.id,
73 authorId: bob.id,
74 title: "Fix <b>the</b> login",
75 body: "",
76 });
77 if (!issue.ok) throw new Error("issue");
78 // 10,000 ledger rows, one run each, a minute apart; the newest is the issue's.
79 const base = Date.parse("2026-10-01T00:00:00.000Z");
80 app.db.transaction(() => {
81 for (let i = 0; i < ROWS; i++) {
82 const run = createRun(app.db, { repoId: repo.id, kind: "agent" }).id;
83 const last = i === ROWS - 1;
84 if (last) issueRun = run;
85 recordUsage(app.db, {
86 runId: run,
87 repoId: repo.id,
88 issueId: last ? issue.value.id : null,
89 agentId: null,
90 subscriptionId: null,
91 tokensIn: 1,
92 tokensOut: 1,
93 costUsd: last ? 1.5 : 0.25,
94 wallMs: 1,
95 outcome: last ? "ok" : "failed",
96 at: new Date(base + i * 60_000).toISOString(),
97 });
98 }
99 })();
100 servers = await serve(app);
101 });
102 afterAll(() => {
103 servers.stop();
104 app.close();
105 rmSync(root, { recursive: true, force: true });
106 });
107
108 test("the wallet is the newest 20 spends, each with date, amount, what it paid for and its run", () => {
109 const w = readWallet(app, bob, repo);
110 if (!w.ok) throw new Error("refused");
111 expect(w.value.spends).toHaveLength(20);
112 const first = w.value.spends[0]!;
113 expect(first.runId).toBe(issueRun);
114 expect(first.costUsd).toBe(1.5);
115 expect(first.paidFor).toBe("build #1 Fix <b>the</b> login");
116 expect(first.runPath).toBe(`/bob/wallet-app/runs/${issueRun}`);
117 const dates = w.value.spends.map((s) => s.at);
118 expect([...dates].sort().reverse()).toEqual(dates);
119 });
120
121 test("a reader who cannot write the app is told not_found", () => {
122 expect(readWallet(app, carol, repo)).toEqual({ ok: false, error: "not_found" });
123 expect(readWallet(app, undefined, repo)).toEqual({ ok: false, error: "not_found" });
124 });
125
126 test("the page is server-rendered, escaped, and links each row's run", async () => {
127 const res = await fetch(`${servers.url}/bob/wallet-app/wallet`, { headers: { cookie: await cookieOf("bob") } });
128 const body = await res.text();
129 expect(res.status).toBe(200);
130 expect(body).toContain("data-wallet");
131 expect(body).toContain("$1.50");
132 expect(body).toContain("2026-10-07");
133 expect(body).toContain(`href="/bob/wallet-app/runs/${issueRun}"`);
134 expect(body).toContain("Fix &lt;b&gt;the&lt;/b&gt; login");
135 expect(body).not.toContain("Fix <b>the</b>");
136 expect((body.match(/<td class="mono">20\d\d-/g) ?? []).length).toBe(20);
137 });
138
139 test("a guest and a non-writer get the not-found page and no figure", async () => {
140 for (const headers of [{}, { cookie: await cookieOf("carol") }]) {
141 const res = await fetch(`${servers.url}/bob/wallet-app/wallet`, { headers, redirect: "manual" });
142 const body = await res.text();
143 expect(res.status).toBeGreaterThanOrEqual(300);
144 expect(body).not.toContain("$1.50");
145 expect(body).not.toContain("data-wallet");
146 }
147 });
148
149 test("the read walks an index: no scan, no sort", () => {
150 const plan = app.db
151 .query<{ detail: string }, [string, number]>(`EXPLAIN QUERY PLAN ${LAST_SPENDS_SQL}`)
152 .all("x", 20)
153 .map((r) => r.detail);
154 expect(plan.join("\n")).toContain("USING INDEX usage_repo");
155 for (const line of plan) {
156 expect(line).not.toMatch(/^SCAN (?!.*USING (COVERING )?INDEX)/);
157 expect(line).not.toContain("TEMP B-TREE");
158 }
159 });
160
161 test("with 10,000 ledger rows the page costs a few statements, not one per row", async () => {
162 const headers = { cookie: await cookieOf("bob") };
163 const url = `${servers.url}/bob/wallet-app/wallet`;
164 await (await fetch(url, { headers })).text();
165 expectWork(await requestStatements(app.db, url, { headers }), { max: 40 });
166 expectWork(await statements(app.db, () => void readWallet(app, bob, repo)), { max: 2 });
167 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs