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

The wallet page says once, in one line, when a repository has spent 80% of its month, and nothing louder #14509

Merged opened this

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

Merged

scout/forge:scout/14489-the-wallet-page-says-once-in-one-line-wh → main 11 commits fork 2 threads · 2 unresolved

  • Merged. scout/14489-the-wallet-page-says-once-in-one-line-wh was merged into main as 7698e9f.

Review

Sign in to review this change.
5 files changed +154 −3
docs/features/wallet.md +7
@@ -29,6 +29,13 @@ 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 - **80% of the month (#14489):** with a cap set, once spend reaches 80% of it an admin reads one
33 sentence under the spend line, `80% of June is spent; the crew pauses at 100%.`; from 100% that
34 sentence gives way to the existing paused line, which on the page also links to the cap field, so
35 the two never say the same thing together. Below 80%, or with
36 no cap, nothing is added, and the home and board gain no banner. It reads the cap and spend the
37 pause rule reads (`spentWords` in `core/wallet.ts`); `test/wallet-threshold.test.ts` covers 79%,
38 80%, 100% and no cap.
3239 - **Days left (#14680):** one sentence at the head of the wallet, `About 9 days left.`: the month's
3340 balance under the cap over the last seven UTC days' spend divided by seven, rounded down
3441 (`core/wallet_days_left.ts`). The cap resets with the UTC month, so the count stops at the days to the
src/core/wallet.ts +16
@@ -61,6 +61,22 @@ export function lowWallet(db: Database, repoId: string, now: Date, cap: number |
6161 return `Wallet: ${dollars(left)} left of ${dollars(cap)}`;
6262 }
6363
64 /** The wallet page says how far the month has gone once spend reaches this share of the cap. */
65 export const WALLET_SPENT_SHARE = 0.8;
66
67 const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
68
69 /**
70 * The one sentence under the balance from 80% of the cap until the cap is reached; undefined below
71 * 80%, with no cap, and from 100% on, where `capReached` already says what has paused. The share is
72 * floored from spent*100/cap, so a spend that passes the 80% test never reads 79.
73 */
74 export function spentWords(cap: number | undefined, spent: number, now: Date): string | undefined {
75 if (cap === undefined || spent < cap * WALLET_SPENT_SHARE || spent >= cap) return undefined;
76 const share = Math.max(WALLET_SPENT_SHARE * 100, Math.floor((spent * 100) / cap));
77 return `${share}% of ${MONTHS[now.getUTCMonth()]} is spent; the crew pauses at 100%.`;
outdated

Principle 1/8: the paused sentence ends in a dangling "or" that depends on the page appending a link, and the terminal appends different words. Return whole sentences, and make the spent share robust: Math.floor(spent*100/cap) avoids float error showing under 80.

78 }
79
6480 /** The first day of next UTC month, as `2026-12-01`. */
6581 export const resetDate = (now: Date): string => new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)).toISOString().slice(0, 10);
6682
src/tui/screens/wallet.ts +3 −1
@@ -7,7 +7,7 @@
77 import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts";
88 import { canAdmin, type Repo } from "../../core/repos.ts";
99 import { daysLeftLine, spentLastWeek } from "../../core/wallet_days_left.ts";
10 import { capReached, lowWallet, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
10 import { capReached, lowWallet, monthCap, monthSpent, spentWords, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
1111 import type { Ctx, Screen } from "../app/app.ts";
1212 import { binding } from "../app/keys.ts";
1313 import type { Command } from "../app/palette.ts";
@@ -28,6 +28,8 @@ export function walletLines(f: Session, repo: Repo, now: Date): string[] {
2828 const lines = [`Spent this month: $${spent}${cap === undefined ? ". No cap is set." : `, cap $${cap}.`}`];
2929 const paused = capReached(f.db, repo.id, now, cap) ?? lowWallet(f.db, repo.id, now, cap);
3030 if (paused !== undefined) lines.push(paused);
31 const notice = spentWords(cap, spentUsd, now);
32 if (notice !== undefined) lines.push(notice);
3133 lines.push(daysLeftLine(cap, spentUsd, spentLastWeek(f.db, repo.id, now), now));
3234 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.`);
3335 return lines;
src/web/pages/wallet.ts +6 −2
@@ -11,7 +11,7 @@ import { dayBarSvg, readWalletDays, WALLET_DAYS } from "../../actions/wallet_day
1111 import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actions/wallet.ts";
1212 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1313 import { canAdmin } from "../../core/repos.ts";
14 import { capReached, money, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
14 import { capReached, money, monthCap, monthSpent, spentWords, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
1515 import { daysLeftLine, weekOfDays } from "../../core/wallet_days_left.ts";
1616 import type { Ctx } from "../../http/context.ts";
1717 import { adminForm } from "../admin_form.ts";
@@ -38,9 +38,13 @@ export function walletPage(ctx: Ctx): Response {
3838 const spent = monthSpent(ctx.app.db, repo.id, now);
3939 let capBlock = null;
4040 if (canAdmin(ctx.app.db, repo, ctx.auth.user)) {
41 const notice = spentWords(cap, spent, now);
4142 const paused = capReached(ctx.app.db, repo.id, now, cap);
4243 capBlock = html`<p id="wallet-spend">Spent this month: <strong class="num">${money(spent)}</strong>.</p>
43 ${paused === undefined ? null : html`<p id="wallet-paused">${paused}</p>`}
44 ${notice === undefined
45 ? null
46 : html`<p id="wallet-spent" class="small">${notice}</p>`}
outdated

Principle 1: at 100% this paragraph and #wallet-paused right below both say new runs are paused. Show one of them.

47 ${paused === undefined ? null : html`<p id="wallet-paused">${paused} <a href="#f-cap">Raise the monthly cap</a>.</p>`}
4448 <form method="post" action="${base}/wallet" class="mt">
4549 ${formField({
4650 label: "Monthly cap (US dollars)",
test/wallet-threshold.test.ts added +122
@@ -0,0 +1,122 @@
1 /** The wallet page says once, in one sentence, when 80% of the month's cap is spent (#14489). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createUser } from "../src/core/users.ts";
9 import { createRun } from "../src/core/runs.ts";
10 import { setMonthCap, spentWords } from "../src/core/wallet.ts";
11 import { serve } from "../src/http/server.ts";
12 import { quietLogs } from "./helpers/globals.ts";
13
14 quietLogs();
15
16 let dir = "";
17 let app: ReturnType<typeof createApp>;
18 let servers: Awaited<ReturnType<typeof serve>>;
19 let repoId = "";
20 let cookie = "";
21 let ownerId = "";
22
23 beforeAll(async () => {
24 dir = await mkdtemp(join(tmpdir(), "forge-wallet-threshold-"));
25 app = createApp({ dataDir: dir, port: 0 });
26 servers = await serve(app);
27 const made: any = await createUser(app.db, {
28 origin: "seed", trusted: true, username: "trevato", email: "[email protected]",
29 password: "a-good-passphrase", adminIfFirst: true,
30 });
31 const user = made.value ?? made;
32 ownerId = user.id;
33 const res = await fetch(servers.url + "/signin", {
34 method: "POST", redirect: "manual",
35 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
36 body: new URLSearchParams({ username: "trevato", password: "a-good-passphrase" }),
37 });
38 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
39 const r: any = await createRepo(app, user, { name: "garden", visibility: "public" });
40 repoId = (r.value ?? r).id;
41 });
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dir, { recursive: true, force: true });
46 });
47
48 const get = async (path: string) => (await fetch(servers.url + path, { redirect: "manual", headers: { cookie } })).text();
49 const reset = (cap: number | undefined, spent: number) => {
50 app.db.query("DELETE FROM usage WHERE repo_id = ?1").run(repoId);
51 setMonthCap(app.db, repoId, cap, ownerId, new Date());
52 if (spent > 0) {
53 const run = createRun(app.db, { repoId, kind: "agent" });
54 app.db.query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', ?3, 'ok', ?4)`)
55 .run(run.id, repoId, spent, new Date().toISOString());
56 }
57 };
58 const wallet = () => get("/trevato/garden/wallet");
59
60 test("79% says nothing", async () => {
61 reset(100, 79);
62 expect(await wallet()).not.toContain('id="wallet-spent"');
63 });
64
65 test("80% says it once, with the pause at 100%", async () => {
66 reset(100, 80);
67 const page = await wallet();
68 expect(page.match(/id="wallet-spent"/g)?.length).toBe(1);
69 expect(page).toContain("80% of ");
70 expect(page).toContain("is spent; the crew pauses at 100%.");
71 expect(page).not.toContain("onthly cap</a>");
72 });
73
74 test("100% says what has paused once, and links to the cap", async () => {
75 reset(100, 100);
76 const page = await wallet();
77 expect(page).not.toContain('id="wallet-spent"');
78 expect(page.match(/id="wallet-paused"/g)?.length).toBe(1);
79 expect(page).toContain('<a href="#f-cap">Raise the monthly cap</a>');
80 expect(page).toContain('id="f-cap"');
81 });
82
83 test("no limit set says nothing, and home gains no banner", async () => {
84 reset(undefined, 500);
85 expect(await wallet()).not.toContain('id="wallet-spent"');
86 reset(100, 90);
87 expect(await get("/")).not.toContain("is spent; the crew pauses");
88 expect(await get("/trevato/garden")).not.toContain("is spent; the crew pauses");
89 });
90
91 test("spentWords: the same boundaries as the pause rule", () => {
92 const now = new Date("2026-06-10T00:00:00Z");
93 expect(spentWords(100, 79.99, now)).toBeUndefined();
94 expect(spentWords(100, 80, now)).toBe("80% of June is spent; the crew pauses at 100%.");
95 expect(spentWords(100, 99.9, now)).toContain("99%");
96 expect(spentWords(100, 100, now)).toBeUndefined();
97 expect(spentWords(0.3, 0.24, now)).toContain("80%");
98 expect(spentWords(undefined, 1e6, now)).toBeUndefined();
99 });
100
101 test("the terminal's wallet screen says the same sentence", async () => {
102 const { walletLines } = await import("../src/tui/screens/wallet.ts");
103 const { createForgeApp } = await import("../src/tui/forge.ts");
104 const { headlessTerminal } = await import("../src/tui/term/terminal.ts");
105 const { getRepoById } = await import("../src/core/repos.ts");
106 const user: any = app.db.query("SELECT * FROM user WHERE username = 'trevato'").get();
107 const { session } = createForgeApp(
108 app,
109 { sshUsername: "trevato", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: { ...user, id: ownerId } },
110 { terminal: headlessTerminal(140, 50), exitHooks: false },
111 );
112 const repo = getRepoById(app.db, repoId)!;
113 const now = new Date();
114 reset(100, 79);
115 expect(walletLines(session, repo, now).join("\n")).not.toContain("is spent;");
116 reset(100, 80);
117 expect(walletLines(session, repo, now).join("\n")).toContain("80% of ");
118 reset(100, 100);
119 const full = walletLines(session, repo, now).join("\n");
120 expect(full).toContain("monthly cap of $100 is reached");
121 expect(full).not.toContain("is spent; the crew pauses");
122 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs