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

The wallet page shows the last 30 days of spend as a table with an inline SVG bar per day #13961

Merged opened this

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

Merged

torque/forge:torque/13939-the-wallet-page-shows-the-last-30-days-o → main 9 commits fork 7 threads · 7 unresolved

  • Merged. torque/13939-the-wallet-page-shows-the-last-30-days-o was merged into main as 640e2e7.

Review

Sign in to review this change.
8 files changed +284 −9
docs/design/areas/wallet.md added +4
@@ -0,0 +1,4 @@
1 # Wallet
2
3 - `.wallet-bar`: the filled SVG bar of one day on the wallet page's 30-day table. No outline; its
4 width is a share of 3rem to 10rem, so the three-column table does not scroll sideways at 360px.
docs/features/wallet.md +6
@@ -17,6 +17,12 @@ did not end well says so beside what it paid for.
1717 is written as text). It reads `readWallet`, so the gate and the 20-row cap are the page's: anyone
1818 else gets 404. The page links it; the terminal's wallet screen prints the path. It does not go
1919 through `exportRows`, which reads a table of an app's own database; the ledger is the forge's.
20 - **Last 30 days:** above the spends, one row per UTC day, today first, each with its dollars and a
21 server-rendered SVG bar (a share of the largest day; no script, no chart library). A day with no
22 spend reads `$0.00`, never a gap. One grouped query reads the window and the total is the sum of its
outdated

Stale: the total is now the sum of the 30 rows from one query (test compares it to an independent ledger sum), not a separate ledger read. Say that, and drop the sentence that says the page says so about UTC twice over.

23 30 rows (`actions/wallet_days.ts`); `test/wallet-days.test.ts` fails if a day is dropped or the total
24 differs from an independent sum of the ledger. Days are cut at 00:00 UTC. The terminal's wallet
25 screen heads with the same total.
2026 - **Speed:** the read walks `usage_repo (repo_id, at)` for twenty rows, no
2127 scan and no sort, so it does not grow with the ledger
2228 (`test/wallet.test.ts` counts its statements at 10,000 rows and reads the plan).
src/actions/wallet_days.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * The wallet's last 30 UTC days (#13939): one row per calendar day, today first, each with the
3 * dollars the repository's runs cost that day. A day with no spend is a row of $0.00, never a
4 * gap. Read from the usage ledger through `usage_repo (repo_id, at)`: a range walk, no scan.
5 * Days are UTC (`at` is an ISO 8601 UTC string, so its first ten characters are the day).
6 * Dollars are the provider's list price, as everywhere in the wallet. Plain data in and out.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 export const WALLET_DAYS = 30;
12
13 export interface WalletDay {
14 /** `YYYY-MM-DD`, UTC. */
15 readonly date: string;
16 readonly costUsd: number;
17 /**
18 * Bar length as a share of the largest day, 0 to 100 (one decimal); 0 for a day with no spend.
19 */
20 readonly share: number;
21 }
22
23 export interface WalletDays {
24 /** Today first, then each earlier day: exactly WALLET_DAYS rows. */
25 readonly days: readonly WalletDay[];
26 /**
27 * The sum of the rows above: the 30 days are one query, so the total cannot disagree with them.
28 */
29 readonly totalUsd: number;
30 }
31
32 const DAY_MS = 86_400_000;
33
34 /** The 30 UTC dates ending on `now`'s, newest first. */
35 export function lastDates(now: Date, count = WALLET_DAYS): string[] {
36 const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
37 return Array.from({ length: count }, (_, i) => new Date(today - i * DAY_MS).toISOString().slice(0, 10));
38 }
39
40 export function readWalletDays(db: Database, repoId: string, now: Date): WalletDays {
41 const dates = lastDates(now);
42 const from = `${dates[dates.length - 1]}T00:00:00.000Z`;
43 const to = new Date(Date.parse(`${dates[0]}T00:00:00.000Z`) + DAY_MS).toISOString();
44 const sums = new Map(
45 db
46 .query<{ d: string; n: number }, [string, string, string]>(
47 "SELECT substr(at, 1, 10) AS d, SUM(cost_usd) AS n FROM usage WHERE repo_id = ?1 AND at >= ?2 AND at < ?3 GROUP BY d",
48 )
49 .all(repoId, from, to)
50 .map((r) => [r.d, r.n] as const),
51 );
52 const biggest = Math.max(0, ...dates.map((d) => sums.get(d) ?? 0));
53 const days = dates.map((date) => {
54 const costUsd = sums.get(date) ?? 0;
55 return { date, costUsd, share: biggest > 0 ? Math.round((costUsd / biggest) * 1000) / 10 : 0 };
56 });
57 return {
58 totalUsd: days.reduce((a, d) => a + d.costUsd, 0),
59 days,
60 };
61 }
62
63 /** One day's bar: a server-rendered SVG, `share` percent of the width, with a text alternative. */
64 export function dayBarSvg(day: WalletDay): string {
65 const w = day.share.toFixed(1);
66 return `<svg class="wallet-bar" viewBox="0 0 100 10" preserveAspectRatio="none" role="img" aria-label="${day.date}: ${day.costUsd.toFixed(2)} US dollars"><rect x="0" y="0" width="${w}" height="10" fill="currentColor"/></svg>`;
67 }
68
69 /**
outdated

Principle 6: the first <rect> draws a hairline box around every bar, 30 boxes on the page. Remove it; the filled rect alone is the bar. Also keep the fixed width=160 from forcing the table to scroll at 360px: use a width in CSS tokens or a percentage.

70 * One day as text for the terminal: a bar of up to `width` block cells, at least one for any spend.
71 */
72 export function dayBarText(day: WalletDay, width: number): string {
73 const n = day.costUsd > 0 ? Math.max(1, Math.round((day.share / 100) * width)) : 0;
74 return "█".repeat(n);
75 }
src/tui/screens/money.ts +16 −7
@@ -14,6 +14,7 @@
1414 import { mayReadStatement } from "../../actions/statement.ts";
1515 import { money } from "../../core/wallet.ts";
1616 import { readWallet, type WalletSpend } from "../../actions/wallet.ts";
17 import { dayBarText, readWalletDays, type WalletDay } from "../../actions/wallet_days.ts";
1718 import { readAppMoney, readForgeMoney, type AppMoney, type ForgeMoney, type MoneyLine } from "../../actions/money.ts";
1819 import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
1920 import type { Ctx, Screen } from "../app/app.ts";
@@ -120,11 +121,18 @@ export function walletRows(spends: readonly WalletSpend[]): ListRow[] {
120121 }));
121122 }
122123
124 /** The 30 days under the spends: date, dollars, a text bar; today first. */
125 export function walletDayRows(days: readonly WalletDay[]): ListRow[] {
126 return days.map((d) => ({ title: d.date, meta: `${money(d.costUsd)} ${dayBarText(d, 20)}`.trimEnd() }));
127 }
128
123129 export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
124130 const state = new ListState();
125131 const rows = (): ListRow[] => {
126132 const w = readWallet(f.app, f.user, repo);
127 return w.ok ? walletRows(w.value.spends) : [];
133 if (!w.ok) return [];
134 const days = readWalletDays(f.app.db, repo.id, new Date());
135 return [...walletDayRows(days.days), ...walletRows(w.value.spends)];
128136 };
129137 return {
130138 title: `${repo.ownerName}/${repo.name} — Wallet`,
@@ -132,12 +140,13 @@ export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
132140 render(area, s) {
outdated

Both doors: only the total reaches the terminal. The per-day rows (date, dollars, text bar) must be on the wallet screen too. Also this header line now carries five facts and is truncated on narrow terminals; put the total on its own line.

133141 const c = ctx.theme.c;
134142 const r = rows();
135 const [head, list] = split(area, "v", [len(1), fill(1)]);
136 const said =
137 r.length === 0
138 ? "nothing spent yet"
139 : `last 20 spends · US dollars · days are UTC · as CSV: /${repo.ownerName}/${repo.name}/wallet.csv`;
140 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
143 const [head, total, list] = split(area, "v", [len(1), len(1), fill(1)]);
144 const muted = style(c.mutedFg, c.bg);
145 s.text(head!.x, head!.y, truncate(`last 30 days, then last 20 spends · US dollars · UTC`, head!.w), muted, head!.x + head!.w);
146 if (r.length > 0) {
147 const days = readWalletDays(f.app.db, repo.id, new Date());
148 s.text(total!.x, total!.y, truncate(`${money(days.totalUsd)} in the last 30 days · CSV: /${repo.ownerName}/${repo.name}/wallet.csv`, total!.w), muted, total!.x + total!.w);
149 }
141150 drawList(s, list!, c, state, r);
142151 },
143152 key: (e) => state.key(e, rows().length),
src/web/pages/wallet.ts +19 −1
@@ -7,6 +7,7 @@
77 */
88
99 import { walletCsv } from "../../actions/wallet_csv.ts";
10 import { dayBarSvg, readWalletDays, WALLET_DAYS } from "../../actions/wallet_days.ts";
1011 import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actions/wallet.ts";
1112 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1213 import { canAdmin } from "../../core/repos.ts";
@@ -15,7 +16,7 @@ import type { Ctx } from "../../http/context.ts";
1516 import { adminForm } from "../admin_form.ts";
1617 import { loadRepo, repoBase, repoNotFound } from "../chrome.ts";
1718 import { field } from "../form.ts";
18 import { html } from "../html.ts";
19 import { html, raw } from "../html.ts";
1920 import { flashTo } from "../layout.ts";
2021 import { btn, field as formField } from "../ui.ts";
2122 import { settingsPageResponse } from "./settings.ts";
@@ -53,9 +54,26 @@ export function walletPage(ctx: Ctx): Response {
5354 the UTC calendar month.
5455 </p>`;
5556 }
57 const daily = readWalletDays(ctx.app.db, repo.id, new Date());
5658 const body = html`<section class="settings-block" data-wallet>
5759 <h2>Wallet</h2>
5860 ${capBlock}
61 <h3>Last ${WALLET_DAYS} days</h3>

Principle 1: this note says the total, that days are UTC, and that a zero day reads $0.00, and the header already says (UTC) and the rows show $0.00. One sentence: the total over the last 30 days, days in UTC.

62 <p class="small" id="wallet-days-total">${money(daily.totalUsd)} over the last ${WALLET_DAYS} days, days in UTC.</p>

Principle 1: this note says the days are UTC, and the column header two lines down says (UTC) again. Say it once. Keep the one sentence and make the header plain: Day. Or drop the clause here and keep the header.

63 <div class="table-scroll">
64 <table class="table" id="wallet-days">
65 <thead><tr><th>Day</th><th class="num">Spend (USD)</th><th>Share</th></tr></thead>
outdated

Principle 1: Day (UTC) repeats the note above; and Compared with the biggest day explains the bar a second time. Use Day, Spend, and an empty or short header for the bar column (the SVG already has an aria-label).

66 <tbody>
outdated

Share column has no purpose a person needs beyond the spend figure; keep it, but the header 'Share of the largest day' is wordy. Plain words: 'Compared with the biggest day'.

67 ${daily.days.map(
68 (d) => html`<tr>
69 <th scope="row" class="mono">${d.date}</th>
70 <td class="num mono">${money(d.costUsd)}</td>
71 <td>${raw(dayBarSvg(d))}</td>
72 </tr>`,
73 )}
74 </tbody>
75 </table>
76 </div>
5977 <p class="small">What ${w.app}'s last 20 spends paid for, newest first, each with the run behind it.
6078 ${w.spends.length === 0 ? null : html`<a href="${base}/wallet.csv" download>Download as CSV</a>`}</p>
6179 ${w.spends.length === 0
src/web/style/components.ts +1
@@ -670,6 +670,7 @@ details[open] > summary.row > .row-lead { transform: rotate(90deg); }
670670 .table tbody tr:first-child td { border-top: none; }
671671 .table[data-dense] td, .table[data-dense] th { padding: 5px 10px; }
672672 .table .num { text-align: right; }
673 .wallet-bar { display: block; width: 100%; min-width: 3rem; max-width: 10rem; height: .75rem; }
673674 .table-scroll { overflow-x: auto; scrollbar-width: thin; }
674675 /* The data browser: a cell's JSON keeps its shape, and the sorted column is marked by its aria-sort. */
675676 .table td pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: inherit; }
test/wallet-days.test.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * The wallet's last 30 UTC days (#13939): thirty rows, zero days present, the total the ledger's,
3 * a bar per day, and the page's gate.
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 { lastDates, readWalletDays, WALLET_DAYS } from "../src/actions/wallet_days.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 const NOW = new Date("2026-11-16T10:00:00.000Z");
22 let root = "";
23 let app: App;
24 let servers: Servers;
25 let bob: User;
26 let repo: Repo;
27 // [ISO instant, dollars]: day 0 twice, a day 29 days back (in), one 30 days back (out), the day
28 // before the window's first midnight, and an instant just before midnight UTC.
29 const LEDGER: [string, number][] = [
30 ["2026-11-16T00:00:00.000Z", 1.25],
31 ["2026-11-16T09:59:00.000Z", 0.75],
32 ["2026-11-15T23:59:59.999Z", 0.5],
33 ["2026-10-18T00:00:00.000Z", 4],
34 ["2026-10-17T23:59:59.999Z", 100],
35 ["2026-11-10T12:00:00.000Z", 0.1],
36 ["2026-11-10T13:00:00.000Z", 0.2],
37 ];
38
39 beforeAll(async () => {
40 root = mkdtempSync(join(tmpdir(), "forge-wallet-days-"));
41 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
42 const users: User[] = [];
43 for (const [i, username] of ["alice", "bob"].entries()) {
44 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: PASS, adminIfFirst: i === 0 });
45 if (!u.ok) throw new Error(u.error);
46 users.push(u.value);
47 }
48 bob = users[1]!;
49 proveAll(app);
50 const made = await initRepo(app.db, app.reposRoot, { ownerId: bob.id, name: "days-app", visibility: "public", description: "" });
51 if (!made.ok) throw new Error("repo");
52 repo = made.value;
53 for (const [at, costUsd] of LEDGER) {
54 recordUsage(app.db, {
55 runId: createRun(app.db, { repoId: repo.id, kind: "agent" }).id,
56 repoId: repo.id,
57 issueId: null,
58 agentId: null,
59 subscriptionId: null,
60 tokensIn: 1,
61 tokensOut: 1,
62 costUsd,
63 wallMs: 1,
64 outcome: "ok",
65 at,
66 });
67 }
68 servers = await serve(app);
69 });
70 afterAll(() => {
71 servers.stop();
72 app.close();
73 rmSync(root, { recursive: true, force: true });
74 });
75
76 test("30 consecutive UTC days, today first, none dropped, across a month and a leap day", () => {
77 const dates = lastDates(NOW);
78 expect(dates).toHaveLength(WALLET_DAYS);
79 expect(dates[0]).toBe("2026-11-16");
80 expect(dates[29]).toBe("2026-10-18");
81 expect(lastDates(new Date("2028-03-01T00:00:00Z"), 3)).toEqual(["2028-03-01", "2028-02-29", "2028-02-28"]);
82 const w = readWalletDays(app.db, repo.id, NOW);
83 expect(w.days.map((d) => d.date)).toEqual(dates);
84 });
85
86 test("each day's spend is the ledger's for that UTC day; empty days are zero", () => {
87 const by = new Map(readWalletDays(app.db, repo.id, NOW).days.map((d) => [d.date, d.costUsd]));
88 expect(by.get("2026-11-16")).toBeCloseTo(2, 9);
89 expect(by.get("2026-11-15")).toBeCloseTo(0.5, 9);
90 expect(by.get("2026-11-10")).toBeCloseTo(0.3, 9);
91 expect(by.get("2026-10-18")).toBe(4);
92 expect(by.get("2026-11-12")).toBe(0);
93 expect(by.has("2026-10-17")).toBe(false);
94 });
95
96 test("the total is the ledger's over the window, and the rows add up to it", () => {
97 const w = readWalletDays(app.db, repo.id, NOW);
98 const ledger = app.db
99 .query<{ n: number }, [string, string]>("SELECT SUM(cost_usd) AS n FROM usage WHERE repo_id = ?1 AND at >= ?2 AND at < '2026-11-17'")
100 .get(repo.id, "2026-10-18")!.n;
101 expect(w.totalUsd).toBeCloseTo(6.8, 9); // 1.25+0.75+0.5+4+0.1+0.2, the 100 is outside
102 expect(w.totalUsd).toBeCloseTo(ledger, 9);
103 expect(w.days.reduce((a, d) => a + d.costUsd, 0)).toBeCloseTo(w.totalUsd, 9);
104 });
105
106 test("bars are shares of the largest day; an empty ledger gives 30 zero rows", () => {
107 const w = readWalletDays(app.db, repo.id, NOW);
108 expect(w.days.find((d) => d.date === "2026-10-18")!.share).toBe(100);
109 expect(w.days.find((d) => d.date === "2026-11-16")!.share).toBe(50);
110 expect(w.days.find((d) => d.date === "2026-11-12")!.share).toBe(0);
111 const none = readWalletDays(app.db, "no-such-repo", NOW);
112 expect(none.days).toHaveLength(30);
113 expect(none.days.every((d) => d.costUsd === 0 && d.share === 0)).toBe(true);
114 expect(none.totalUsd).toBe(0);
115 });
116
117 test("the page shows 30 rows with an SVG bar each, the UTC note and the total; guests get 404", async () => {
118 const signin = await fetch(`${servers.url}/signin`, {
119 method: "POST",
120 headers: { origin: servers.url },
121 body: new URLSearchParams({ username: "bob", password: PASS }),
122 redirect: "manual",
123 });
124 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
125 const res = await fetch(`${servers.url}/bob/days-app/wallet`, { headers: { cookie } });
126 expect(res.status).toBe(200);
127 const text = await res.text();
128 const table = text.slice(text.indexOf('id="wallet-days"'));
129 const body = table.slice(0, table.indexOf("</table>"));
130 expect(body.match(/<tr>/g)).toHaveLength(31); // 30 days and the header;
131 expect(body.match(/<svg class="wallet-bar"/g)).toHaveLength(30);
132 expect(text).toContain("days in UTC.");
133 expect(body).not.toContain("UTC"); // said once, in the sentence above the table
134 expect(body).toContain("<th>Day</th>");
135 expect(body).not.toContain("<rect x=\"0\" y=\"0\" width=\"100\" height=\"10\" fill=\"none\"");
136 expect(text).toContain('id="wallet-days-total"');
137 expect((await fetch(`${servers.url}/bob/days-app/wallet`)).status).toBe(404);
138 });
139
140 test("the day read walks usage_repo over a range: no scan of the table", () => {
141 const plan = app.db
142 .query<{ detail: string }, [string, string, string]>(
143 "EXPLAIN QUERY PLAN SELECT substr(at, 1, 10) AS d, SUM(cost_usd) FROM usage WHERE repo_id = ?1 AND at >= ?2 AND at < ?3 GROUP BY d",
144 )
145 .all("x", "a", "b")
146 .map((r) => r.detail);
147 expect(plan.join("\n")).toContain("USING INDEX usage_repo");
148 for (const line of plan) expect(line).not.toMatch(/^SCAN (?!.*USING (COVERING )?INDEX)/);
149 });
150
151 test("the terminal's day rows: date, dollars, a text bar; a zero day has no bar", async () => {
152 const { walletDayRows } = await import("../src/tui/screens/money.ts");
153 const rows = walletDayRows([
154 { date: "2026-01-02", costUsd: 4, share: 100 },
155 { date: "2026-01-01", costUsd: 1, share: 25 },
156 { date: "2025-12-31", costUsd: 0, share: 0 },
157 ]);
158 expect(rows[0]).toEqual({ title: "2026-01-02", meta: `$4.00 ${"█".repeat(20)}` });
159 expect(rows[1]!.meta).toBe(`$1.00 ${"█".repeat(5)}`);
160 expect(rows[2]!.meta).toBe("$0.00");
161 });
test/wallet.test.ts +2 −1
@@ -134,7 +134,8 @@ test("the page is server-rendered, escaped, and links each row's run", async ()
134134 expect(body).toContain(`href="/bob/wallet-app/runs/${issueRun}"`);
135135 expect(body).toContain("Fix &lt;b&gt;the&lt;/b&gt; login");
136136 expect(body).not.toContain("Fix <b>the</b>");
137 expect((body.match(/<td class="mono">20\d\d-/g) ?? []).length).toBe(20);
137 const spends = body.slice(body.indexOf("Date (UTC)"));
138 expect((spends.match(/<td class="mono">20\d\d-/g) ?? []).length).toBe(20);
138139 });
139140
140141 test("a guest and a non-writer get the not-found page and no figure", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs