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

A repository's wallet page forecasts the day its balance runs out from the last seven days' spend #16003

Merged opened this

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

Merged

scout/forge:scout/15980-a-repository-s-wallet-page-forecasts-the → main 0 commits fork

  • Merged. scout/15980-a-repository-s-wallet-page-forecasts-the was merged into main as fbd40d3.

Review

Sign in to review this change.
7 files changed +114 −70
docs/features/wallet.md +14 −10
@@ -42,16 +42,20 @@ did not end well says so beside what it paid for.
4242 no cap, nothing is added, and the home and board gain no banner. It reads the cap and spend the
4343 pause rule reads (`spentWords` in `core/wallet.ts`); `test/wallet-threshold.test.ts` covers 79%,
4444 80%, 100% and no cap.
45 - **Days left (#14680):** one sentence at the head of the wallet, `About 9 days left.`: the month's
46 balance under the cap over the last seven UTC days' spend divided by seven, rounded down
47 (`core/wallet_days_left.ts`). The cap resets with the UTC month, so the count stops at the days to the
48 reset (the month's last day counts as one): a balance that would last 50 days says 6 on the 25th. No
49 spend in the week reads `No spending yet.`; a spent-out cap `No days left.`; spending with no cap `No
50 cap is set, so no days to count.` Everyone who may read the wallet sees it. The page, the MCP
51 `daysLeft` field (the page's sentence, character for character) and the terminal (first on the
52 `owner/name — Wallet` screen's total line, so a narrow terminal cuts the rest, and on the admin's cap
53 screen) all take it from the one `daysLeftLine`. The page and that screen take the week from the 30
54 day rows they already read, so the line costs them no extra query.
45 - **Days left (#14680, #15980):** one sentence at the head of the wallet, `At this pace the
46 balance lasts about 9 days.` (`core/wallet_days_left.ts`). The pace is the median of the last
47 seven UTC days with quiet days counted as $0, so one large one-off day does not skew it. A sparse
48 week has a median of $0, and then the week's total over seven is the pace: one $7 day is $1 a
49 day, never $7. The month's balance under the cap over that pace is rounded down. The cap resets
50 with the UTC month, so the count stops at the days to the reset (the month's last day counts as
51 one): a balance that would last 50 days says 6 on the 25th. A week with no spend reads `No spend
52 this week.`; a spent-out cap reads `No days left.`; a balance under a day `At this pace the
53 balance lasts less than a day.`; spending with no cap `No cap is set, so no days to count.`
54 Everyone who may read the wallet sees it. The page, the MCP `daysLeft` field (the page's sentence,
55 character for character) and the terminal (first on the `owner/name — Wallet` screen's total
56 line, so a narrow terminal cuts the rest, and on the admin's cap screen) all take it from the one
57 `daysLeftLine`. The page and that screen take the week from the 30 day rows they already read, so
58 the line costs them no extra query.
5559 - **Speed:** the read walks `usage_repo (repo_id, at)` for twenty rows, no
5660 scan and no sort, so it does not grow with the ledger
5761 (`test/wallet.test.ts` counts its statements at 10,000 rows and reads the plan).
src/actions/wallet.ts +3 −3
@@ -17,7 +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";
20 import { daysLeftLine, lastWeek } from "../core/wallet_days_left.ts";
2121 import { err, ok, type Result } from "../kernel/result.ts";
2222
2323 export const WALLET_ROWS = 20;
@@ -98,7 +98,7 @@ export interface WalletSummary {
9898 /** The wallet line's words. */
9999 readonly balance: string;
100100 /**
101 * The page's own sentence: `About 9 days left.`, `No spending yet.`,
101 * The page's own sentence: `At this pace the balance lasts about 9 days.`, `No spend this week.`,
102102 * `No cap is set, so no days to count.`
103103 */
104104 readonly daysLeft: string;
@@ -128,7 +128,7 @@ export function readWalletSummary(app: App, actor: User | undefined, repo: Repo,
128128 spent: money(spent),
129129 left: cap === undefined ? null : money(Math.max(0, cap - spent)),
130130 balance: balanceWords(cap, spent, now),
131 daysLeft: daysLeftLine(cap, spent, spentLastWeek(app.db, repo.id, now), now),
131 daysLeft: daysLeftLine(cap, spent, lastWeek(app.db, repo.id, now), now),
132132 latest,
133133 });
134134 }
src/core/wallet_days_left.ts +42 −24
@@ -1,8 +1,7 @@
11 /**
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
2 * How long a wallet's balance lasts (#14680, #15980): the balance over the median day of the
3 * last seven UTC days, as one sentence. Rounds down, so it never promises more days than the
4 * maths gives. The cap resets with the UTC month, so the count never
65 * runs past the month's last day: a balance that outlasts the month says the days to the reset.
76 */
87
@@ -19,39 +18,58 @@ export function daysToReset(now: Date): number {
1918 }
2019
2120 /**
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.
21 * The day's pace the forecast runs at: the median of all seven days, quiet days counted as $0, so
22 * one large one-off day does not make the balance look like it runs out fast. A sparse week has a
23 * median of $0 though it spent, and then the week's total over seven is the pace, so a repository
24 * with one $7 day reads $1 a day, never $7. A week short of seven rows is padded with $0.
2525 */
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.`;
26 export function medianDay(week: readonly number[]): number {
27 const days = Array.from({ length: DAYS_LEFT_WINDOW }, (_, i) => Math.max(0, week[i] ?? 0)).sort((a, b) => a - b);
28 const median = days[DAYS_LEFT_WINDOW >> 1]!;
29 return median > 0 ? median : days.reduce((a, n) => a + n, 0) / DAYS_LEFT_WINDOW;
3330 }
3431
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 {
32 export const NO_SPEND_WORDS = "No spend this week.";
33
34 /**
35 * `balance` is dollars left under the cap (undefined: no cap, so no balance); `week` is the last
36 * seven days' dollars; `reset` the days until the cap resets. Undefined when there is spending
37 * but no balance to measure.
38 */
39 export function daysLeftWords(balance: number | undefined, week: readonly number[], reset: number): string | undefined {
40 const pace = medianDay(week);
41 if (!(pace > 0)) return NO_SPEND_WORDS;
42 if (balance === undefined) return undefined;
43 if (!(balance > 0)) return "No days left.";
44 const days = Math.min(reset, Math.floor(balance / pace));
45 if (days < 1) return "At this pace the balance lasts less than a day.";
46 return `At this pace the balance lasts about ${days} ${days === 1 ? "day" : "days"}.`;
47 }
48
49 /**
50 * Dollars the repository's runs cost on each of the seven UTC days ending on `now`'s, today first.
51 */
52 export function lastWeek(db: Database, repoId: string, now: Date): number[] {
3753 const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
3854 const from = new Date(today - (DAYS_LEFT_WINDOW - 1) * DAY_MS).toISOString();
3955 const to = new Date(today + DAY_MS).toISOString();
40 return (
56 const sums = new Map(
4157 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",
58 .query<{ d: string; n: number }, [string, string, string]>(
59 "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",
4460 )
45 .get(repoId, from, to)?.n ?? 0
61 .all(repoId, from, to)
62 .map((r) => [r.d, r.n] as const),
4663 );
64 return Array.from({ length: DAYS_LEFT_WINDOW }, (_, i) => sums.get(new Date(today - i * DAY_MS).toISOString().slice(0, 10)) ?? 0);
4765 }
4866
4967 /**
5068 * The same week from daily rows already read, today first (the wallet's 30 days): no query, so a
5169 * page that shows the days does not read the week twice.
5270 */
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);
71 export function weekOfDays(days: readonly { readonly costUsd: number }[]): number[] {
72 return days.slice(0, DAYS_LEFT_WINDOW).map((d) => d.costUsd);
5573 }
5674
5775 export const NO_CAP_WORDS = "No cap is set, so no days to count.";
@@ -60,6 +78,6 @@ export const NO_CAP_WORDS = "No cap is set, so no days to count.";
6078 * The one sentence every door shows (page, JSON, terminal): days left under the month's cap, or
6179 * a plain note when there is spending but nothing to count down from. Plain numbers in.
6280 */
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;
81 export function daysLeftLine(cap: number | undefined, spentMonth: number, week: readonly number[], now: Date): string {
82 return daysLeftWords(cap === undefined ? undefined : cap - spentMonth, week, daysToReset(now)) ?? NO_CAP_WORDS;
6583 }
src/tui/screens/wallet.ts +2 −2
@@ -7,7 +7,7 @@
77 import { readWalletMonths } from "../../actions/wallet_months.ts";
88 import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts";
99 import { canAdmin, type Repo } from "../../core/repos.ts";
10 import { daysLeftLine, spentLastWeek } from "../../core/wallet_days_left.ts";
10 import { daysLeftLine, lastWeek } from "../../core/wallet_days_left.ts";
1111 import { capReached, lowWallet, monthCap, monthSpent, spentWords, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
1313 import { binding } from "../app/keys.ts";
@@ -31,7 +31,7 @@ export function walletLines(f: Session, repo: Repo, now: Date): string[] {
3131 if (paused !== undefined) lines.push(paused);
3232 const notice = spentWords(cap, spentUsd, now);
3333 if (notice !== undefined) lines.push(notice);
34 lines.push(daysLeftLine(cap, spentUsd, spentLastWeek(f.db, repo.id, now), now));
34 lines.push(daysLeftLine(cap, spentUsd, lastWeek(f.db, repo.id, now), now));
3535 const months = readWalletMonths(f.db, repo.id);
3636 if (months.length > 0) lines.push(`Per month, all spends, UTC: ${months.map((m) => `${m.month} $${m.costUsd.toFixed(2)}`).join(" · ")}`);
3737 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.`);
test/mcp-wallet.test.ts +3 −3
@@ -200,14 +200,14 @@ test("days left: exact words in the JSON, the page and the terminal, from the se
200200 expect(none.daysLeft).toBe("No cap is set, so no days to count.");
201201 const pageNone = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text();
202202 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.
203 // A cap near twice the spend: balance (cap - spent) over spent/7 a day (every row is today, the
204 // other six days $0), rounded down, never past the reset.
205205 const now = new Date();
206206 const cap = Math.ceil(spent * 2);
207207 setMonthCap(app.db, repoId, cap, owner.id, now);
208208 const days = Math.min(daysToReset(now), Math.floor((cap - spent) / (spent / 7)));
209209 expect(days).toBeGreaterThanOrEqual(1);
210 const words = days === 1 ? "About 1 day left." : `About ${days} days left.`;
210 const words = `At this pace the balance lasts about ${days} ${days === 1 ? "day" : "days"}.`;
211211 const v = ask(owner, {}).value;
212212 // The JSON string is the page's sentence, character for character.
213213 expect(v.daysLeft).toBe(words);
test/tui-wallet.test.ts +8 −7
@@ -137,19 +137,20 @@ test("the wallet screen heads with the days-left sentence, first, so a narrow te
137137 runId: createRun(app.db, { repoId: repo.id, kind: "agent" }).id, repoId: repo.id, issueId: null, agentId: null,
138138 subscriptionId: null, tokensIn: 1, tokensOut: 1, costUsd: 7, wallMs: 1, outcome: "ok", at: now.toISOString(),
139139 });
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]) {
140 // $30 cap, $7 spent in one day of the week: $23 left at $1 a day is 23 days, never past the
141 // month's reset.
142 setMonthCap(app.db, repo.id, 30, alice.id, now);
143 const days = Math.min(23, daysToReset(now));
144 const words = `At this pace the balance lasts about ${days} ${days === 1 ? "day" : "days"}.`;
145 for (const width of [140, 50]) {
145146 const { tui, session } = open(alice, headlessTerminal(width, 20));
146147 tui.start();
147148 tui.ctx.push(walletScreen(session, tui.ctx, repo));
148149 await settleApp(tui);
149150 const rows = tui.screen.toText().split("\n");
150151 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 "));
152 // At 50 columns the line is cut, but from the end: the sentence survives whole.
153 const line = rows.find((l) => l.includes("At this pace"));
153154 expect(line?.trim().startsWith(words)).toBe(true);
154155 if (width === 140) expect(line).toContain(`${words} $7.00 in the last 30 days · CSV: /alice/runway/wallet.csv`);
155156 }
test/wallet-days-left.test.ts +42 −21
@@ -1,49 +1,70 @@
11 import { expect, test } from "bun:test";
22 import { Database } from "bun:sqlite";
3 import { daysLeftLine, daysLeftWords, daysToReset, spentLastWeek, weekOfDays } from "../src/core/wallet_days_left.ts";
3 import { daysLeftLine, daysLeftWords, daysToReset, lastWeek, medianDay, weekOfDays } from "../src/core/wallet_days_left.ts";
44
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.");
5 const W = (n: number) => `At this pace the balance lasts about ${n} ${n === 1 ? "day" : "days"}.`;
6
7 test("an empty ledger says no spend this week, with or without a balance", () => {
8 expect(daysLeftWords(50, [0, 0, 0, 0, 0, 0, 0], 30)).toBe("No spend this week.");
9 expect(daysLeftWords(undefined, [], 30)).toBe("No spend this week.");
810 });
911
1012 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 expect(daysLeftWords(0, [1], 30)).toBe("No days left.");
14 expect(daysLeftWords(-3, [1], 30)).toBe("No days left.");
1315 });
1416
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.");
17 test("a flat ledger: the balance over the day's pace, rounded down", () => {
18 const flat = [1, 1, 1, 1, 1, 1, 1];
19 expect(daysLeftWords(9.99, flat, 30)).toBe(W(9));
20 expect(daysLeftWords(10, flat, 30)).toBe(W(10));
21 expect(daysLeftWords(1, flat, 30)).toBe(W(1));
22 expect(daysLeftWords(0.5, flat, 30)).toBe("At this pace the balance lasts less than a day.");
23 });
24
25 test("a rising ledger runs at its median day, and one large day does not skew it", () => {
26 expect(medianDay([7, 6, 5, 4, 3, 2, 1])).toBe(4);
27 expect(daysLeftWords(40, [7, 6, 5, 4, 3, 2, 1], 30)).toBe(W(10));
28 // One $100 one-off among $1 days: the mean would say 0 days; the median says the usual pace.
29 expect(medianDay([100, 1, 1, 1, 1, 1, 1])).toBe(1);
30 expect(daysLeftWords(20, [100, 1, 1, 1, 1, 1, 1], 30)).toBe(W(20));
31 // Quiet days count as $0: a median of 0 falls back to the week's total over seven.
32 expect(medianDay([4, 2, 0, 0, 0, 0, 0])).toBe(6 / 7);
33 expect(medianDay([3, 3, 3, 3, 0, 0, 0])).toBe(3);
34 });
35
36 test("one spending day is a week's average, not that day's pace; a mostly quiet week likewise", () => {
37 // $7 on one day: $1 a day, so $30 lasts 30 days (capped by the reset), never 4.
38 expect(medianDay([7, 0, 0, 0, 0, 0, 0])).toBe(1);
39 expect(daysLeftWords(30, [7, 0, 0, 0, 0, 0, 0], 30)).toBe(W(30));
40 expect(daysLeftWords(30, [7], 30)).toBe(W(30));
41 // $6 over two days of seven: 6/7 a day, $3 lasts 3.5, rounded down.
42 expect(daysLeftWords(3, [4, 2, 0, 0, 0, 0, 0], 30)).toBe(W(3));
2143 });
2244
2345 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.");
46 expect(daysLeftWords(50, [1, 1, 1, 1, 1, 1, 1], 6)).toBe(W(6));
2647 expect(daysToReset(new Date("2026-11-25T23:00:00Z"))).toBe(6);
2748 expect(daysToReset(new Date("2026-11-30T00:00:00Z"))).toBe(1);
2849 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.");
50 expect(daysLeftLine(57, 7, [1, 1, 1, 1, 1, 1, 1], new Date("2026-11-25T23:00:00Z"))).toBe(W(6));
3051 });
3152
3253 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.");
54 expect(daysLeftWords(undefined, [7], 30)).toBeUndefined();
55 expect(daysLeftLine(undefined, 7, [7], new Date("2026-11-01T00:00:00Z"))).toBe("No cap is set, so no days to count.");
3556 });
3657
37 test("spentLastWeek counts seven UTC days ending today, and the day rows give the same week", () => {
58 test("lastWeek counts seven UTC days ending today, and the day rows give the same week", () => {
3859 const db = new Database(":memory:");
3960 db.run("CREATE TABLE usage (repo_id TEXT, at TEXT, cost_usd REAL)");
4061 const put = (at: string, n: number) => db.query("INSERT INTO usage VALUES ('r', ?1, ?2)").run(at, n);
4162 put("2026-11-16T10:00:00.000Z", 1);
4263 put("2026-11-10T00:00:00.000Z", 2);
4364 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);
65 expect(lastWeek(db, "r", new Date("2026-11-16T12:00:00Z"))).toEqual([1, 0, 0, 0, 0, 0, 2]);
66 expect(lastWeek(db, "other", new Date("2026-11-16T12:00:00Z"))).toEqual([0, 0, 0, 0, 0, 0, 0]);
4667 // Today first: 16th, then 15th … 10th is the seventh row; the 9th's $100 is the eighth.
4768 const rows = [1, 0, 0, 0, 0, 0, 2, 100].map((costUsd) => ({ costUsd }));
48 expect(weekOfDays(rows)).toBe(3);
69 expect(weekOfDays(rows)).toEqual([1, 0, 0, 0, 0, 0, 2]);
4970 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs