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

A repository's wallet page totals spend per month, above the ledger #14471

Merged opened this

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

Merged

mason/forge:mason/14458-a-repository-s-wallet-page-totals-spend → main 8 commits fork 2 threads · 2 unresolved

  • Merged. mason/14458-a-repository-s-wallet-page-totals-spend was merged into main as a2d1dd9.

Review

Sign in to review this change.
7 files changed +204 −4
docs/features/wallet.md +6
@@ -29,6 +29,12 @@ did not end well says so beside what it paid for.
2929 30 rows (`actions/wallet_days.ts`); `test/wallet-days.test.ts` fails if a day is dropped or the total
3030 differs from an independent sum of the ledger. Days are cut at 00:00 UTC. The terminal's wallet
3131 screen heads with the same total.
32 - **Spend per month (#14458):** above the last 30 days, one row per UTC month with spend, newest first,
33 at most 12, each with its count of spends and total dollars (`actions/wallet_months.ts`, one grouped
34 read over `usage_repo (repo_id, at)`). The totals cover every spend in those months, not only the 20
35 rows listed below, so a busy month's total is more than the rows add up to
36 (`test/wallet-months.test.ts` checks it with 25 spends). The admin's cap screen in the terminal
37 prints the same months on one line, newest first, cut at the terminal's width.
3238 - **Days left (#14680):** one sentence at the head of the wallet, `About 9 days left.`: the month's
3339 balance under the cap over the last seven UTC days' spend divided by seven, rounded down
3440 (`core/wallet_days_left.ts`). The cap resets with the UTC month, so the count stops at the days to the
src/actions/wallet_months.ts added +26
@@ -0,0 +1,26 @@
1 /**
2 * The wallet's spend per UTC month (#14458): one row per calendar month that has spends, newest
3 * first, at most 12, each with how many spends and their total dollars. Grouped by the first seven
4 * characters of `at` (an ISO 8601 UTC string, so `YYYY-MM`) over `usage_repo (repo_id, at)`.
5 * Dollars are the provider's list price, as everywhere in the wallet. Plain data in and out.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 export const WALLET_MONTHS = 12;
11
12 export interface WalletMonth {
13 /** `YYYY-MM`, UTC. */
14 readonly month: string;
15 readonly spends: number;
16 readonly costUsd: number;
17 }
18
19 export function readWalletMonths(db: Database, repoId: string): WalletMonth[] {
20 return db
21 .query<{ month: string; spends: number; costUsd: number }, [string, number]>(
22 `SELECT substr(at, 1, 7) AS month, COUNT(*) AS spends, SUM(cost_usd) AS costUsd FROM usage
23 WHERE repo_id = ?1 GROUP BY month ORDER BY month DESC LIMIT ?2`,
24 )

Totals here cover all spends in the month while the ledger and wallet.csv list only the last 20, so box 2 holds only for small wallets. Add a test with more than 20 spends or reword the table.

25 .all(repoId, WALLET_MONTHS);
26 }
src/tui/screens/wallet.ts +3
@@ -4,6 +4,7 @@
44 * monthly cap in whole dollars; an empty value removes it. Each write is a `wallet.cap` event.
55 */
66
7 import { readWalletMonths } from "../../actions/wallet_months.ts";
78 import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts";
89 import { canAdmin, type Repo } from "../../core/repos.ts";
910 import { daysLeftLine, spentLastWeek } from "../../core/wallet_days_left.ts";
@@ -29,6 +30,8 @@ export function walletLines(f: Session, repo: Repo, now: Date): string[] {
2930 const paused = capReached(f.db, repo.id, now, cap) ?? lowWallet(f.db, repo.id, now, cap);
3031 if (paused !== undefined) lines.push(paused);
3132 lines.push(daysLeftLine(cap, spentUsd, spentLastWeek(f.db, repo.id, now), now));
33 const months = readWalletMonths(f.db, repo.id);
34 if (months.length > 0) lines.push(`Per month, all spends, UTC: ${months.map((m) => `${m.month} $${m.costUsd.toFixed(2)}`).join(" · ")}`);
3235 lines.push(`c sets the cap in whole dollars, 1 to ${WALLET_CAP_MAX_USD}; empty removes it. A cap stops new runs, never one under way.`);
3336 return lines;
3437 }
src/web/pages/wallet.ts +20
@@ -8,6 +8,7 @@
88
99 import { capSpends, WALLET_CSV_READ, WALLET_CSV_ROWS, walletCsv } from "../../actions/wallet_csv.ts";
1010 import { dayBarSvg, readWalletDays, WALLET_DAYS } from "../../actions/wallet_days.ts";
11 import { readWalletMonths } from "../../actions/wallet_months.ts";
1112 import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actions/wallet.ts";
1213 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1314 import { canAdmin } from "../../core/repos.ts";
@@ -56,10 +57,29 @@ export function walletPage(ctx: Ctx): Response {
5657 the UTC calendar month.
5758 </p>`;
5859 }
60 const months = readWalletMonths(ctx.app.db, repo.id);
5961 const body = html`<section class="settings-block" data-wallet>
6062 <h2>Wallet</h2>
6163 ${capBlock}
6264 <p id="wallet-days-left">${daysLeftLine(cap, spent, weekOfDays(daily.days), now)}</p>
65 ${months.length === 0
66 ? null
67 : html`<h3>Spend per month</h3>
68 <p class="small">All spends, UTC months, newest first.</p>
outdated

Principle 1: this sentence repeats what the heading and the table already say. Shorten to "UTC months, newest first." and make clear it covers all spends, not only the 20 rows below.

69 <div class="table-scroll">
70 <table class="table" id="wallet-months">
71 <thead><tr><th>Month</th><th class="num">Spends</th><th class="num">Total (USD)</th></tr></thead>
72 <tbody>
73 ${months.map(
74 (m) => html`<tr>
75 <th scope="row" class="mono">${m.month}</th>
76 <td class="num mono">${m.spends}</td>
77 <td class="num mono">${money(m.costUsd)}</td>
78 </tr>`,
79 )}
80 </tbody>
81 </table>
82 </div>`}
6383 <h3>Last ${WALLET_DAYS} days</h3>
6484 <p class="small" id="wallet-days-total">${money(daily.totalUsd)} over the last ${WALLET_DAYS} days, days in UTC.</p>
6585 <div class="table-scroll">
test/tui-wallet.test.ts +17
@@ -154,3 +154,20 @@ test("the wallet screen heads with the days-left sentence, first, so a narrow te
154154 if (width === 140) expect(line).toContain(`${words} $7.00 in the last 30 days · CSV: /alice/runway/wallet.csv`);
155155 }
156156 });
157
158 test("the admin's cap screen lists the spend per UTC month, all spends, newest first (#14458)", async () => {
159 const made = await createRepo(app, alice, { name: "monthly", visibility: "public" });
160 if (!made.ok) throw new Error("repo");
161 const repo = made.value;
162 for (const [at, costUsd] of [["2026-11-02T10:00:00.000Z", 1.25], ["2026-10-31T23:59:59.000Z", 0.5], ["2026-10-02T10:00:00.000Z", 2]] as const) {
163 recordUsage(app.db, {
164 runId: createRun(app.db, { repoId: repo.id, kind: "agent" }).id, repoId: repo.id, issueId: null, agentId: null, subscriptionId: null,
165 tokensIn: 1, tokensOut: 1, costUsd, wallMs: 1, outcome: "ok", at,
166 });
167 }
168 const { session } = open(alice);
169 expect(walletLines(session, repo, new Date("2026-11-15T12:00:00.000Z"))).toContain("Per month, all spends, UTC: 2026-11 $1.25 · 2026-10 $2.50");
170 const quiet = await createRepo(app, alice, { name: "monthless", visibility: "public" });
171 if (!quiet.ok) throw new Error("repo");
172 expect(walletLines(session, quiet.value, new Date()).some((l) => l.startsWith("Per month"))).toBe(false);
173 });
test/wallet-months.test.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * The wallet's per-month totals (#14458): grouped in UTC, newest first, equal to the ledger's rows.
3 */
4 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { mkdtempSync, rmSync } from "node:fs";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { readWallet } from "../src/actions/wallet.ts";
10 import { readWalletMonths, WALLET_MONTHS } from "../src/actions/wallet_months.ts";
11 import { createRepo as initRepo, type Repo } from "../src/core/repos.ts";
12 import { createRun } from "../src/core/runs.ts";
13 import { recordUsage } from "../src/core/usage.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17 import { proveAll } from "./helpers/verified.ts";
18
19 quietLogs();
20 const PASS = "a-good-passphrase";
21 let root = "";
22 let app: App;
23 let servers: Servers;
24 let bob: User;
25 let repo: Repo;
26 let empty: Repo;
27
28 function spend(r: Repo, at: string, costUsd: number): void {
29 recordUsage(app.db, {
30 runId: createRun(app.db, { repoId: r.id, kind: "agent" }).id,
31 repoId: r.id,
32 issueId: null,
33 agentId: null,
34 subscriptionId: null,
35 tokensIn: 1,
36 tokensOut: 1,
37 costUsd,
38 wallMs: 1,
39 outcome: "ok",
40 at,
41 });
42 }
43
44 beforeAll(async () => {
45 root = mkdtempSync(join(tmpdir(), "forge-wallet-months-"));
46 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
47 for (const [i, username] of ["alice", "bob"].entries()) {
48 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: PASS, adminIfFirst: i === 0 });
49 if (!u.ok) throw new Error(u.error);
50 if (i === 1) bob = u.value;
51 }
52 proveAll(app);
53 const made = await initRepo(app.db, app.reposRoot, { ownerId: bob.id, name: "months-app", visibility: "public", description: "" });
54 const none = await initRepo(app.db, app.reposRoot, { ownerId: bob.id, name: "quiet-app", visibility: "public", description: "" });
55 if (!made.ok || !none.ok) throw new Error("repo");
56 repo = made.value;
57 empty = none.value;
58 spend(repo, "2026-11-01T00:00:00.000Z", 1.25);
59 spend(repo, "2026-10-31T23:59:59.999Z", 0.5);
60 spend(repo, "2026-10-02T10:00:00.000Z", 2);
61 spend(repo, "2026-09-15T10:00:00.000Z", 0.1);
62 servers = await serve(app);
63 });
64 afterAll(() => {
65 servers.stop();
66 app.close();
67 rmSync(root, { recursive: true, force: true });
68 });
69
70 test("months are UTC, newest first, with the count and total of each", () => {
71 expect(readWalletMonths(app.db, repo.id)).toEqual([
72 { month: "2026-11", spends: 1, costUsd: 1.25 },
73 { month: "2026-10", spends: 2, costUsd: 2.5 },
74 { month: "2026-09", spends: 1, costUsd: 0.1 },
75 ]);
76 expect(readWalletMonths(app.db, empty.id)).toEqual([]);
77 });
78
79 test("the monthly totals equal the sum of the rows the wallet and wallet.csv list", async () => {
80 const rows = readWallet(app, bob, repo);
81 if (!rows.ok) throw new Error("read");
82 const listed = rows.value.spends.reduce((a, s) => a + s.costUsd, 0);
83 expect(rows.value.spends.length).toBeLessThan(20);
84 const months = readWalletMonths(app.db, repo.id);
85 expect(months.reduce((a, m) => a + m.costUsd, 0)).toBeCloseTo(listed, 9);
86 expect(months.reduce((a, m) => a + m.spends, 0)).toBe(rows.value.spends.length);
87 });
88
89 test("at most 12 months, the newest", () => {
90 for (let i = 0; i < 14; i++) spend(empty, `${2025 + Math.floor(i / 12)}-${String((i % 12) + 1).padStart(2, "0")}-05T00:00:00.000Z`, 1);
91 const months = readWalletMonths(app.db, empty.id);
92 expect(months).toHaveLength(WALLET_MONTHS);
93 expect(months[0]!.month).toBe("2026-02");
94 expect(months[11]!.month).toBe("2025-03");
95 });
96
97 test("the page shows the table to the owner, says UTC, and shows none for an empty wallet", async () => {
98 const signin = await fetch(`${servers.url}/signin`, {
99 method: "POST",
100 headers: { origin: servers.url },
101 body: new URLSearchParams({ username: "bob", password: PASS }),
102 redirect: "manual",
103 });
104 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
105 const text = await (await fetch(`${servers.url}/bob/months-app/wallet`, { headers: { cookie } })).text();
106 expect(text).toContain('id="wallet-months"');
107 expect(text).toContain("2026-10");
108 expect(text).toContain("$2.50");
109 expect(text).toContain("All spends, UTC months, newest first.");
110 expect((await fetch(`${servers.url}/bob/months-app/wallet`)).status).toBe(404);
111 // a fresh repo with no spends
112 const fresh = await initRepo(app.db, app.reposRoot, { ownerId: bob.id, name: "fresh-app", visibility: "public", description: "" });
113 if (!fresh.ok) throw new Error("repo");
114 const none = await (await fetch(`${servers.url}/bob/fresh-app/wallet`, { headers: { cookie } })).text();
115 expect(none).not.toContain('id="wallet-months"');
116 });
117
118 test("with more than 20 spends the months still total every spend, not only the 20 rows listed", () => {
119 for (let i = 0; i < 25; i++) spend(empty, "2026-12-10T00:00:00.000Z", 0.5);
120 const months = readWalletMonths(app.db, empty.id);
121 const dec = months.find((m) => m.month === "2026-12")!;
122 expect(dec.spends).toBe(25);
123 expect(dec.costUsd).toBeCloseTo(12.5, 9);
124 const listed = readWallet(app, bob, empty);
125 if (!listed.ok) throw new Error("read");
126 expect(listed.value.spends.length).toBe(20);
127 });
test/wallet.test.ts +5 −4
@@ -164,10 +164,11 @@ test("with 10,000 ledger rows the page costs a few statements, not one per row",
164164 const headers = { cookie: await cookieOf("bob") };
165165 const url = `${servers.url}/bob/wallet-app/wallet`;
166166 await (await fetch(url, { headers })).text();
167 // 40, as before #14680: the days-left line reads the week from the 30 day rows the page already
168 // has, and the cap and month spend an admin's cap form already reads. A reader who is not an
169 // admin pays those two indexed reads, which no longer sit behind the admin check.
170 expectWork(await requestStatements(app.db, url, { headers }), { max: 40 });
167 // 40 as before #14680, plus one for the month totals: the days-left line reads the week from the
168 // 30 day rows the page already has, and the cap and month spend an admin's cap form already
169 // reads. A reader who is not an admin pays those two indexed reads, which no longer sit behind
170 // the admin check.
171 expectWork(await requestStatements(app.db, url, { headers }), { max: 41 });
171172 expectWork(await statements(app.db, () => void readWallet(app, bob, repo)), { max: 2 });
172173 });
173174

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs