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

A repository's wallet says how many days its balance lasts at the last week's average spend #14695

Merged opened this

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

Merged

scout/forge:scout/14680-a-repository-s-wallet-says-how-many-days → main 7 commits fork 5 threads · 5 unresolved

  • Merged. scout/14680-a-repository-s-wallet-says-how-many-days was merged into main as 3242413.

Review

Sign in to review this change.
10 files changed +215 −8
docs/features/wallet.md +10
@@ -29,6 +29,16 @@ 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 - **Days left (#14680):** one sentence at the head of the wallet, `About 9 days left.`: the month's
33 balance under the cap over the last seven UTC days' spend divided by seven, rounded down
34 (`core/wallet_days_left.ts`). The cap resets with the UTC month, so the count stops at the days to the
35 reset (the month's last day counts as one): a balance that would last 50 days says 6 on the 25th. No
36 spend in the week reads `No spending yet.`; a spent-out cap `No days left.`; spending with no cap `No
37 cap is set, so no days to count.` Everyone who may read the wallet sees it. The page, the MCP
38 `daysLeft` field (the page's sentence, character for character) and the terminal (first on the
39 `owner/name — Wallet` screen's total line, so a narrow terminal cuts the rest, and on the admin's cap
40 screen) all take it from the one `daysLeftLine`. The page and that screen take the week from the 30
41 day rows they already read, so the line costs them no extra query.
3242 - **Speed:** the read walks `usage_repo (repo_id, at)` for twenty rows, no
3343 scan and no sort, so it does not grow with the ledger
3444 (`test/wallet.test.ts` counts its statements at 10,000 rows and reads the plan).
src/actions/wallet.ts +7
@@ -17,6 +17,7 @@ import { canAdmin, canSeeOwnerFacts, type Repo } from "../core/repos.ts";
1717 import type { UsageKind, UsageOutcome } from "../core/usage.ts";
1818 import type { User } from "../core/users.ts";
1919 import { balanceWords, money, monthCap, monthSpent, setMonthCap, validCap, WALLET_CAP_MAX_USD } from "../core/wallet.ts";
20 import { daysLeftLine, spentLastWeek } from "../core/wallet_days_left.ts";
2021 import { err, ok, type Result } from "../kernel/result.ts";
2122
2223 export const WALLET_ROWS = 20;
@@ -96,6 +97,11 @@ export interface WalletSummary {
9697 readonly left: string | null;
9798 /** The wallet line's words. */
9899 readonly balance: string;
100 /**
101 * The page's own sentence: `About 9 days left.`, `No spending yet.`,
102 * `No cap is set, so no days to count.`
103 */
104 readonly daysLeft: string;
99105 /**
100106 * The ten newest spends, newest first: date, dollars, what it paid for, `(outcome)` if not ok.
101107 */
@@ -122,6 +128,7 @@ export function readWalletSummary(app: App, actor: User | undefined, repo: Repo,
122128 spent: money(spent),
123129 left: cap === undefined ? null : money(Math.max(0, cap - spent)),
124130 balance: balanceWords(cap, spent, now),
131 daysLeft: daysLeftLine(cap, spent, spentLastWeek(app.db, repo.id, now), now),
125132 latest,
126133 });
127134 }
src/core/wallet_days_left.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * How long a wallet's balance lasts (#14680): the balance over the last seven UTC days' average
3 * spend, as one sentence. Rounds down, so it never promises more days than the maths gives. The
4 * average is always over seven days, so a repository with one day of history is not read as
5 * spending faster than a week would show. The cap resets with the UTC month, so the count never
6 * runs past the month's last day: a balance that outlasts the month says the days to the reset.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 export const DAYS_LEFT_WINDOW = 7;
12
13 const DAY_MS = 86_400_000;
14
15 /** Days from `now`'s UTC date to the month's last, both counted: 30 on Nov 1, 1 on Nov 30. */
16 export function daysToReset(now: Date): number {
17 const last = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
18 return last - now.getUTCDate() + 1;
19 }
20
21 /**
22 * `balance` is dollars left under the cap (undefined: no cap, so no balance); `spent7` is dollars
23 * spent over the last seven days; `reset` the days until the cap resets. Undefined when there is
24 * spending but no balance to measure.
25 */
26 export function daysLeftWords(balance: number | undefined, spent7: number, reset: number): string | undefined {
27 if (!(spent7 > 0)) return "No spending yet.";
28 if (balance === undefined) return undefined;
29 if (!(balance > 0)) return "No days left.";
30 const days = Math.min(reset, Math.floor(balance / (spent7 / DAYS_LEFT_WINDOW)));
31 if (days < 1) return "Less than a day left.";
32 return `About ${days} ${days === 1 ? "day" : "days"} left.`;
33 }
34
35 /** Dollars the repository's runs cost over the seven UTC days ending on `now`'s own. */
36 export function spentLastWeek(db: Database, repoId: string, now: Date): number {
37 const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
38 const from = new Date(today - (DAYS_LEFT_WINDOW - 1) * DAY_MS).toISOString();
39 const to = new Date(today + DAY_MS).toISOString();
40 return (
41 db
42 .query<{ n: number }, [string, string, string]>(
43 "SELECT COALESCE(SUM(cost_usd), 0) AS n FROM usage WHERE repo_id = ?1 AND at >= ?2 AND at < ?3",
44 )
45 .get(repoId, from, to)?.n ?? 0
46 );
47 }
48
49 /**
50 * The same week from daily rows already read, today first (the wallet's 30 days): no query, so a
51 * page that shows the days does not read the week twice.
52 */
53 export function weekOfDays(days: readonly { readonly costUsd: number }[]): number {
54 return days.slice(0, DAYS_LEFT_WINDOW).reduce((a, d) => a + d.costUsd, 0);
55 }
56
57 export const NO_CAP_WORDS = "No cap is set, so no days to count.";
58
59 /**
60 * The one sentence every door shows (page, JSON, terminal): days left under the month's cap, or
61 * a plain note when there is spending but nothing to count down from. Plain numbers in.
62 */
63 export function daysLeftLine(cap: number | undefined, spentMonth: number, spent7: number, now: Date): string {
64 return daysLeftWords(cap === undefined ? undefined : cap - spentMonth, spent7, daysToReset(now)) ?? NO_CAP_WORDS;
65 }
src/tui/screens/money.ts +6 −3
@@ -12,7 +12,8 @@
1212 */
1313
1414 import { mayReadStatement } from "../../actions/statement.ts";
15 import { money } from "../../core/wallet.ts";
15 import { money, monthCap, monthSpent } from "../../core/wallet.ts";
16 import { daysLeftLine, weekOfDays } from "../../core/wallet_days_left.ts";
1617 import { readWallet, type WalletSpend } from "../../actions/wallet.ts";
1718 import { dayBarText, readWalletDays, type WalletDay } from "../../actions/wallet_days.ts";
1819 import { readAppMoney, readForgeMoney, type AppMoney, type ForgeMoney, type MoneyLine } from "../../actions/money.ts";
@@ -145,8 +146,10 @@ export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
145146 const muted = style(c.mutedFg, c.bg);
146147 s.text(head!.x, head!.y, truncate(`last 30 days, then last 20 spends · US dollars · UTC`, head!.w), muted, head!.x + head!.w);
147148 if (r.length > 0) {
148 const days = readWalletDays(f.app.db, repo.id, new Date());
149 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 const now = new Date();
150 const days = readWalletDays(f.app.db, repo.id, now);
outdated

Untested door, and days-left is placed after the 30-day total so truncate drops it first on a narrow terminal. Put it first and add a test of walletScreen. Also read new Date() once instead of three times.

151 const left = daysLeftLine(monthCap(f.app.db, repo.id), monthSpent(f.app.db, repo.id, now), weekOfDays(days.days), now);
152 s.text(total!.x, total!.y, truncate(`${left} ${money(days.totalUsd)} in the last 30 days · CSV: /${repo.ownerName}/${repo.name}/wallet.csv`, total!.w), muted, total!.x + total!.w);
150153 }
151154 drawList(s, list!, c, state, r);
152155 },
src/tui/screens/wallet.ts +4 −1
@@ -6,6 +6,7 @@
66
77 import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts";
88 import { canAdmin, type Repo } from "../../core/repos.ts";
9 import { daysLeftLine, spentLastWeek } from "../../core/wallet_days_left.ts";
910 import { capReached, lowWallet, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
1011 import type { Ctx, Screen } from "../app/app.ts";
1112 import { binding } from "../app/keys.ts";
@@ -22,10 +23,12 @@ export const mayManageWallet = (f: Session, repo: Repo): boolean => f.user !== u
2223 export function walletLines(f: Session, repo: Repo, now: Date): string[] {
2324 if (!mayManageWallet(f, repo)) return ["An admin of this repository manages its wallet."];
2425 const cap = monthCap(f.db, repo.id);
25 const spent = monthSpent(f.db, repo.id, now).toFixed(2);
26 const spentUsd = monthSpent(f.db, repo.id, now);
27 const spent = spentUsd.toFixed(2);
2628 const lines = [`Spent this month: $${spent}${cap === undefined ? ". No cap is set." : `, cap $${cap}.`}`];
2729 const paused = capReached(f.db, repo.id, now, cap) ?? lowWallet(f.db, repo.id, now, cap);
2830 if (paused !== undefined) lines.push(paused);
31 lines.push(daysLeftLine(cap, spentUsd, spentLastWeek(f.db, repo.id, now), now));
2932 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.`);
3033 return lines;
3134 }
src/web/pages/wallet.ts +6 −4
@@ -12,6 +12,7 @@ import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actio
1212 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1313 import { canAdmin } from "../../core/repos.ts";
1414 import { capReached, money, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
15 import { daysLeftLine, weekOfDays } from "../../core/wallet_days_left.ts";
1516 import type { Ctx } from "../../http/context.ts";
1617 import { adminForm } from "../admin_form.ts";
1718 import { loadRepo, repoBase, repoNotFound } from "../chrome.ts";
@@ -31,11 +32,12 @@ export function walletPage(ctx: Ctx): Response {
3132 const rendering = performance.now();
3233 const w = read.value;
3334 const base = repoBase(repo);
35 const now = new Date();
36 const daily = readWalletDays(ctx.app.db, repo.id, now);
37 const cap = monthCap(ctx.app.db, repo.id);
38 const spent = monthSpent(ctx.app.db, repo.id, now);
3439 let capBlock = null;
3540 if (canAdmin(ctx.app.db, repo, ctx.auth.user)) {
36 const now = new Date();
37 const cap = monthCap(ctx.app.db, repo.id);
38 const spent = monthSpent(ctx.app.db, repo.id, now);
3941 const paused = capReached(ctx.app.db, repo.id, now, cap);
4042 capBlock = html`<p id="wallet-spend">Spent this month: <strong class="num">${money(spent)}</strong>.</p>
outdated

Principle 7/1: recomputes the fact a second way and only for admins. Use the same spentLastWeek value as the JSON, and show it outside the admin cap block.

4143 ${paused === undefined ? null : html`<p id="wallet-paused">${paused}</p>`}
@@ -54,10 +56,10 @@ export function walletPage(ctx: Ctx): Response {
5456 the UTC calendar month.
5557 </p>`;
5658 }
57 const daily = readWalletDays(ctx.app.db, repo.id, new Date());
5859 const body = html`<section class="settings-block" data-wallet>
5960 <h2>Wallet</h2>
6061 ${capBlock}
62 <p id="wallet-days-left">${daysLeftLine(cap, spent, weekOfDays(daily.days), now)}</p>
outdated

Principle 1 and 8: 'Days left: about 9 days left.' repeats itself. Drop the label so it reads 'About 9 days left.'

6163 <h3>Last ${WALLET_DAYS} days</h3>
6264 <p class="small" id="wallet-days-total">${money(daily.totalUsd)} over the last ${WALLET_DAYS} days, days in UTC.</p>
6365 <div class="table-scroll">
test/mcp-wallet.test.ts +37
@@ -14,6 +14,9 @@ import { createRun } from "../src/core/runs.ts";
1414 import { createToken, revokeToken } from "../src/core/tokens.ts";
1515 import { createUser, type User } from "../src/core/users.ts";
1616 import { balanceWords, capReached, money, setMonthCap } from "../src/core/wallet.ts";
17 import { walletLines } from "../src/tui/screens/wallet.ts";
18 import { Session } from "../src/tui/session.ts";
19 import { daysToReset } from "../src/core/wallet_days_left.ts";
1720 import { tool } from "../src/http/mcp/tools/usage.ts";
1821 import type { Ctx } from "../src/http/context.ts";
1922 import { serve, type Servers } from "../src/http/server.ts";
@@ -74,6 +77,7 @@ const ctxFor = (user: User | undefined): Ctx => ({
7477 auth: { user, scope: undefined, via: "session" },
7578 theme: undefined,
7679 });
80 const sessionOf = (user: User) => new Session(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", user });
7781 const ask = (user: User, args: Record<string, unknown>) =>
7882 tool.run(ctxFor(user), user, { repo: "trevato/garden", kind: "wallet", ...args }) as { ok: boolean; value?: any; error?: any };
7983
@@ -185,3 +189,36 @@ test("over POST /mcp a stranger's read token gets the page's not_found, not the
185189 expect(r.text).toContain("not_found");
186190 expect(r.text).not.toContain("latest");
187191 });
192
193 test("days left: exact words in the JSON, the page and the terminal, from the seeded ledger (#14680)", async () => {
194 // The ledger as it stands: every row is from today, so the month and the week agree.
195 const spent = app.db.query<{ n: number }, [string]>("SELECT SUM(cost_usd) AS n FROM usage WHERE repo_id = ?1").get(repoId)!.n;
196 expect(spent).toBeGreaterThan(7);
197 // No cap, spending: one plain sentence, never a missing line.
198 setMonthCap(app.db, repoId, undefined, owner.id, new Date());
199 const none = ask(owner, {}).value;
200 expect(none.daysLeft).toBe("No cap is set, so no days to count.");
201 const pageNone = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text();
202 expect(pageNone).toContain('<p id="wallet-days-left">No cap is set, so no days to count.</p>');
203 // A cap near twice the spend: balance (cap - spent) over spent/7 a day, rounded down, never past
204 // the reset.
205 const now = new Date();
206 const cap = Math.ceil(spent * 2);
207 setMonthCap(app.db, repoId, cap, owner.id, now);
208 const days = Math.min(daysToReset(now), Math.floor((cap - spent) / (spent / 7)));
209 expect(days).toBeGreaterThanOrEqual(1);
210 const words = days === 1 ? "About 1 day left." : `About ${days} days left.`;
211 const v = ask(owner, {}).value;
212 // The JSON string is the page's sentence, character for character.
213 expect(v.daysLeft).toBe(words);
214 const page = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text();
215 expect(page).toContain(`<p id="wallet-days-left">${words}</p>`);
216 const lines = walletLines(sessionOf(owner), getRepo(app.db, "trevato", "garden")!, now);
217 expect(lines).toContain(words);
218 });
219
220 test("a reader who may not see the wallet learns no days left, on the page or in the JSON", async () => {
221 expect(ask(stranger, {}).ok).toBe(false);
222 const page = await fetch(servers.url + "/trevato/garden/wallet");
223 expect(await page.text()).not.toContain("wallet-days-left");
224 });
test/tui-wallet.test.ts +28
@@ -15,6 +15,7 @@ import { createRun } from "../src/core/runs.ts";
1515 import type { Repo } from "../src/core/repos.ts";
1616 import { setMonthCap } from "../src/core/wallet.ts";
1717 import { walletLines } from "../src/tui/screens/wallet.ts";
18 import { daysToReset } from "../src/core/wallet_days_left.ts";
1819 import { recordUsage } from "../src/core/usage.ts";
1920 import { createUser, type User } from "../src/core/users.ts";
2021 import { createForgeApp } from "../src/tui/forge.ts";
@@ -126,3 +127,30 @@ test("the screen's lines carry the low-wallet sentence under 20% left, nothing a
126127 expect(reached.some((l) => l.startsWith("Wallet:"))).toBe(false);
127128 expect(reached.some((l) => l.includes("monthly cap of $8 is reached"))).toBe(true);
128129 });
130
131 test("the wallet screen heads with the days-left sentence, first, so a narrow terminal keeps it (#14680)", async () => {
132 const made = await createRepo(app, alice, { name: "runway", visibility: "public" });
133 if (!made.ok) throw new Error("repo");
134 const repo = made.value;
135 const now = new Date();
136 recordUsage(app.db, {
137 runId: createRun(app.db, { repoId: repo.id, kind: "agent" }).id, repoId: repo.id, issueId: null, agentId: null,
138 subscriptionId: null, tokensIn: 1, tokensOut: 1, costUsd: 7, wallMs: 1, outcome: "ok", at: now.toISOString(),
139 });
140 // $9 cap, $7 spent this week: $2 left at $1 a day, never past the month's reset.
141 setMonthCap(app.db, repo.id, 9, alice.id, now);
142 const days = Math.min(2, daysToReset(now));
143 const words = days === 1 ? "About 1 day left." : `About ${days} days left.`;
144 for (const width of [140, 40]) {
145 const { tui, session } = open(alice, headlessTerminal(width, 20));
146 tui.start();
147 tui.ctx.push(walletScreen(session, tui.ctx, repo));
148 await settleApp(tui);
149 const rows = tui.screen.toText().split("\n");
150 tui.stop?.();
151 // At 40 columns the line is cut, but from the end: the sentence survives whole.
152 const line = rows.find((l) => l.includes("About "));
153 expect(line?.trim().startsWith(words)).toBe(true);
154 if (width === 140) expect(line).toContain(`${words} $7.00 in the last 30 days · CSV: /alice/runway/wallet.csv`);
155 }
156 });
test/wallet-days-left.test.ts added +49
@@ -0,0 +1,49 @@
1 import { expect, test } from "bun:test";
2 import { Database } from "bun:sqlite";
3 import { daysLeftLine, daysLeftWords, daysToReset, spentLastWeek, weekOfDays } from "../src/core/wallet_days_left.ts";
4
5 test("zero spend says no spending yet, with or without a balance", () => {
6 expect(daysLeftWords(50, 0, 30)).toBe("No spending yet.");
7 expect(daysLeftWords(undefined, 0, 30)).toBe("No spending yet.");
8 });
9
10 test("a balance of zero has no days left", () => {
11 expect(daysLeftWords(0, 7, 30)).toBe("No days left.");
12 expect(daysLeftWords(-3, 7, 30)).toBe("No days left.");
13 });
14
15 test("one day of history is still averaged over seven days, rounded down", () => {
16 // $7 in the week is $1 a day: $9.99 lasts 9 days, never 10.
17 expect(daysLeftWords(9.99, 7, 30)).toBe("About 9 days left.");
18 expect(daysLeftWords(10, 7, 30)).toBe("About 10 days left.");
19 expect(daysLeftWords(1, 7, 30)).toBe("About 1 day left.");
20 expect(daysLeftWords(0.5, 7, 30)).toBe("Less than a day left.");
21 });
22
23 test("the count stops at the month's reset: the cap is fresh after it", () => {
24 // $50 at $1 a day is 50 days, but on Nov 25 the cap resets in 6.
25 expect(daysLeftWords(50, 7, 6)).toBe("About 6 days left.");
26 expect(daysToReset(new Date("2026-11-25T23:00:00Z"))).toBe(6);
27 expect(daysToReset(new Date("2026-11-30T00:00:00Z"))).toBe(1);
28 expect(daysToReset(new Date("2026-02-01T00:00:00Z"))).toBe(28);
29 expect(daysLeftLine(57, 7, 7, new Date("2026-11-25T23:00:00Z"))).toBe("About 6 days left.");
30 });
31
32 test("no cap with spending has nothing to count, and the line says so", () => {
33 expect(daysLeftWords(undefined, 7, 30)).toBeUndefined();
34 expect(daysLeftLine(undefined, 7, 7, new Date("2026-11-01T00:00:00Z"))).toBe("No cap is set, so no days to count.");
35 });
36
37 test("spentLastWeek counts seven UTC days ending today, and the day rows give the same week", () => {
38 const db = new Database(":memory:");
39 db.run("CREATE TABLE usage (repo_id TEXT, at TEXT, cost_usd REAL)");
40 const put = (at: string, n: number) => db.query("INSERT INTO usage VALUES ('r', ?1, ?2)").run(at, n);
41 put("2026-11-16T10:00:00.000Z", 1);
42 put("2026-11-10T00:00:00.000Z", 2);
43 put("2026-11-09T23:59:59.999Z", 100);
44 expect(spentLastWeek(db, "r", new Date("2026-11-16T12:00:00Z"))).toBe(3);
45 expect(spentLastWeek(db, "other", new Date("2026-11-16T12:00:00Z"))).toBe(0);
46 // Today first: 16th, then 15th … 10th is the seventh row; the 9th's $100 is the eighth.
47 const rows = [1, 0, 0, 0, 0, 0, 2, 100].map((costUsd) => ({ costUsd }));
48 expect(weekOfDays(rows)).toBe(3);
49 });
test/wallet.test.ts +3
@@ -164,6 +164,9 @@ 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
outdated

The budget is raised from 40 to 44 without a way to see which statements are new. Fold the week spend into an existing read, or assert the exact new count.

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.
167170 expectWork(await requestStatements(app.db, url, { headers }), { max: 40 });
168171 expectWork(await statements(app.db, () => void readWallet(app, bob, repo)), { max: 2 });
169172 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs