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

A repository whose wallet is under 20% shows one quiet line on its page and one row in /next, never a banner #13548

Merged opened this

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

Merged

mason/forge:mason/13529-a-repository-whose-wallet-is-under-20-sh → main 7 commits fork 3 threads · 3 unresolved

  • Merged. mason/13529-a-repository-whose-wallet-is-under-20-sh was merged into main as f7ab4c6.

Review

Sign in to review this change.
10 files changed +198 −11
docs/features/README.md +1
@@ -334,6 +334,7 @@ Read with the guide page [Hosting forges for others, and getting paid](../guide-
334334 - [The last Stripe event and refused signatures](stripe-events-line.md)
335335 - [The money line — cost, revenue and the gap](money.md)
336336 - [The repository wallet — the last 20 spends](wallet.md)
337 - [A wallet running low — one line for admins under 20% left](wallet-low.md)
337338 - [The page that answers "make me a forge"](forge-made.md)
338339 - [The Plan row in a forge's settings](plan-row.md)
339340 - [The selling funnel](selling-funnel.md)
docs/features/wallet-low.md added +12
@@ -0,0 +1,12 @@
1 # A wallet running low
2
3 When a repository's monthly cap has under 20% left (and more than nothing), its admins see one
4 line: "Wallet: $X left of $Y" (#13529).
5
6 - **Web.** The repository page shows the line with a link to the wallet; `/<owner>/<repo>/next`
7 shows one row below the list, "Raise the monthly cap", that links to `/<owner>/<repo>/wallet`.
8 - **Terminal.** The wallet screen (`/<owner>/<repo>` then the wallet key) shows the same line
9 under the spent total.
10 - **Who.** Admins of the repository only. No cap, plenty left, or a cap already reached (which
11 has its own sentence) shows nothing new.
12 - **Try it.** Set a cap of $10, spend over $8 of it, open the repository page and `/next`.
src/core/wallet.ts +20
@@ -40,6 +40,26 @@ export function monthSpent(db: Database, repoId: string, now: Date): number {
4040 );
4141 }
4242
43 /** The wallet counts as low once what is left is under this share of the cap (#13529). */
44 export const WALLET_LOW_SHARE = 0.2;
45
46 /** Whole dollars when whole, else cents: `$7`, `$7.50`. */
47 export function dollars(usd: number): string {
48 const cents = Math.round(usd * 100) / 100;
49 return `$${Number.isInteger(cents) ? cents : cents.toFixed(2)}`;
50 }
51
52 /**
53 * "Wallet: $X left of $Y" while the balance is above nothing and under WALLET_LOW_SHARE of the
54 * cap; undefined otherwise (no cap, plenty left, or already reached, which has its own sentence).
55 */
56 export function lowWallet(db: Database, repoId: string, now: Date, cap: number | undefined = monthCap(db, repoId)): string | undefined {
57 if (cap === undefined) return undefined;
58 const left = cap - monthSpent(db, repoId, now);
59 if (left <= 0 || left >= cap * WALLET_LOW_SHARE) return undefined;
60 return `Wallet: ${dollars(left)} left of ${dollars(cap)}`;
61 }
62
4363 /** The first day of next UTC month, as `2026-12-01`. */
4464 export const resetDate = (now: Date): string => new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)).toISOString().slice(0, 10);
4565
src/perf/page_budget.ts +9 −3
@@ -24,14 +24,17 @@ export interface PageBudget {
2424 readonly signedOut?: true;
2525 }
2626
27 /** Statement limits are today's count, signed in, plus a little: lower them as pages get cheaper, raise one only on purpose. */
27 /**
28 * Statement limits are today's count, signed in, plus a little: lower them as pages get cheaper,
29 * raise one only on purpose.
30 */
2831 export const PAGE_BUDGETS: readonly PageBudget[] = [
2932 { page: "home", pattern: "/", medianMs: 50, statements: 46 },
3033 { page: "explore", pattern: "/explore", medianMs: 50, statements: 18 },
3134 { page: "map", pattern: "/map", medianMs: 50, statements: 21 },
3235 { page: "an app page", pattern: "/:owner/:name", medianMs: 50, statements: 49 },
3336 { page: "changelog", pattern: "/changelog", medianMs: 50, statements: 20 },
34 { page: "next up", pattern: "/:owner/:name/next", medianMs: 50, statements: 64 },
37 { page: "next up", pattern: "/:owner/:name/next", medianMs: 50, statements: 65 },

A raised budget. Direction says lower these. Fold the cap read into an existing query on /next, or justify why this feature goes ahead of the pipeline work.

3538 // The space (#12770), which the owner opens to watch growth: the page and the
3639 // `space.json` it reads are two requests, so each has its own row.
3740 // Statement limits: measured warm (15 and 6) plus two, the margin the map row keeps.
@@ -44,7 +47,10 @@ export const PAGE_BUDGETS: readonly PageBudget[] = [
4447 { page: "claim", pattern: "/claim", medianMs: 50, statements: 14, signedOut: true },
4548 ];
4649
47 /** The path a budget's pattern names for one repository: `:owner` and `:name` filled, everything else as written. */
50 /**
51 * The path a budget's pattern names for one repository: `:owner` and `:name` filled, everything
52 * else as written.
53 */
4854 export function pagePath(b: PageBudget, owner: string, name: string): string {
4955 return b.pattern.replace(":owner", encodeURIComponent(owner)).replace(":name", encodeURIComponent(name));
5056 }
src/tui/screens/wallet.ts +2 −2
@@ -6,7 +6,7 @@
66
77 import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts";
88 import { canAdmin, type Repo } from "../../core/repos.ts";
9 import { capReached, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
9 import { capReached, lowWallet, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
1010 import type { Ctx, Screen } from "../app/app.ts";
1111 import { binding } from "../app/keys.ts";
1212 import type { Command } from "../app/palette.ts";
@@ -24,7 +24,7 @@ export function walletLines(f: Session, repo: Repo, now: Date): string[] {
2424 const cap = monthCap(f.db, repo.id);
2525 const spent = monthSpent(f.db, repo.id, now).toFixed(2);
2626 const lines = [`Spent this month: $${spent}${cap === undefined ? ". No cap is set." : `, cap $${cap}.`}`];
27 const paused = capReached(f.db, repo.id, now, cap);
27 const paused = capReached(f.db, repo.id, now, cap) ?? lowWallet(f.db, repo.id, now, cap);

No test covers this terminal line. Add one in test/tui-wallet.test.ts that fails without it.

2828 if (paused !== undefined) lines.push(paused);
2929 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.`);
3030 return lines;
src/web/pages/next.ts +18 −3
@@ -18,6 +18,7 @@ import { canAdmin, canWrite, type Repo } from "../../core/repos.ts";
1818 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1919 import { pillarsOf, servedBy } from "../../core/pillars.ts";
2020 import { sealedScope } from "../../core/sealed.ts";
21 import { lowWallet, monthCap } from "../../core/wallet.ts";
2122 import { notStartable } from "../../crew/not_startable.ts";
2223 import { CUT_TOP_WORDS, cutWords, paceWords, FIT_COUNT_JS, rangeWords, lineAfter, rowCosts, weekView, type Priced } from "../../flow/week.ts";
2324 import type { Ctx } from "../../http/context.ts";
@@ -25,7 +26,7 @@ import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repo
2526 import { backTo, field, readForm } from "../form.ts";
2627 import { html, raw, type Html } from "../html.ts";
2728 import { flashOrJson, page } from "../layout.ts";
28 import { btn, kbd, row } from "../ui.ts";
29 import { btn, kbd, listCard, row } from "../ui.ts";
2930 import { GROWTH_DAYS, growthLine } from "./next_growth.ts";
3031 import { listChapters } from "../../core/chapters.ts";
3132 import { chapterLine, chaptersSection } from "./next_chapters.ts";
@@ -195,13 +196,23 @@ function line(
195196 });
196197 }
197198
198 /** The cut line: everything above it fits this week's capacity, everything below reads as next week. */
199 /**
200 * The cut line: everything above it fits this week's capacity, everything below reads as next week.
201 */
199202 function cutMark(fit: number, top: boolean, byPace: boolean): Html {
200203 return html`<li class="cut-line" role="separator">${top
201204 ? CUT_TOP_WORDS
202205 : byPace ? paceWords : cutWords(fit)}</li>`;
203206 }
204207
208 /** One row, for an admin, to the page that sets the cap, while under a fifth is left (#13529). */
209 function walletRow(ctx: Ctx, repo: Repo, base: string): Html | null {
210 const cap = monthCap(ctx.app.db, repo.id);
211 if (cap === undefined || !ctx.auth.user || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return null;
212 if (lowWallet(ctx.app.db, repo.id, new Date(), cap) === undefined) return null;
213 return listCard([row({ id: "wallet-row", href: `${base}/wallet`, title: html`Raise the monthly cap`, nav: true })]);
214 }
outdated

Principles 1, 7 and 8: a hand-rolled ul and a · lead for a single row, and the meta repeats the repo page's sentence. Use the row component plainly, and word the title as what the wallet page does (it sets the cap; it doesn't top up).

215
205216 export function nextPage(ctx: Ctx): Response {
206217 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
207218 const repo = loadRepo(ctx);
@@ -273,6 +284,7 @@ export function nextPage(ctx: Ctx): Response {
273284 <p class="muted small mt" id="next-week">${sentence} <a href="${base}/week">The week</a>${writer
274285 ? " · Drag a row. Keys: t top · l Later · Shift+J/K or Alt+↓/↑ down/up · j/k choose a row."
275286 : null}</p>
287 ${walletRow(ctx, repo, base)}
276288 ${parked.length > 0
277289 ? html`<details class="mt"><summary><h2>Later · ${String(isFiltered ? parked.length : next.notNowTotal)}</h2></summary><ul class="list setting-list">
278290 ${parked.map((at) => line(base, next.notNow, at, writer, back, true))}
@@ -295,7 +307,10 @@ export function nextPage(ctx: Ctx): Response {
295307 return response;
296308 }
297309
298 /** POST /:owner/:name/next — `number` and `to` (`top`, `not-now`, `after:<number>`): one move, saved at once. */
310 /**
311 * POST /:owner/:name/next — `number` and `to` (`top`, `not-now`, `after:<number>`): one move, saved
312 * at once.
313 */
299314 export async function nextSubmit(ctx: Ctx): Promise<Response> {
300315 const repo: Repo | undefined = loadRepo(ctx);
301316 if (!repo) return notFoundPage(ctx);
src/web/pages/repo.ts +3 −2
@@ -25,7 +25,7 @@ import { lacks, NOT_A_MEMBER } from "../../core/roles.ts";
2525 import { storageLimitMessage } from "../../core/storage.ts";
2626 import { canRead, canWrite, listForks, type Repo } from "../../core/repos.ts";
2727 import { reportsClosed } from "../../core/reports.ts";
28 import { capReached, monthCap } from "../../core/wallet.ts";
28 import { capReached, lowWallet, monthCap } from "../../core/wallet.ts";
2929 import { takesOutside } from "../../actions/contribute_token.ts";
3030 import { FORKS_PER_DAY, forkRepo, repositoryLimitMessage } from "../../actions/repos.ts";
3131 import {
@@ -1396,7 +1396,8 @@ function walletLine(ctx: Ctx, repo: Repo): Html | null {
13961396 // The cheap case first: a repository with no cap row costs one primary-key read, no access check.
13971397 const cap = monthCap(ctx.app.db, repo.id);
13981398 if (cap === undefined || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return null;
1399 const said = capReached(ctx.app.db, repo.id, new Date(), cap);
1399 const now = new Date();
1400 const said = capReached(ctx.app.db, repo.id, now, cap) ?? lowWallet(ctx.app.db, repo.id, now, cap);
14001401 if (said === undefined) return null;
14011402 return html`<p class="muted small mt" id="wallet-line">${said} <a href="${repoBase(repo)}/wallet">Wallet</a></p>`;
14021403 }
test/pages-budget.test.ts +1 −1
@@ -51,7 +51,7 @@ const DEFAULT = { statements: 60, git: 8 };
5151 /** Pages that cost more today, with the most they may: lower these, never raise them. */
5252 const HEAVIER: Record<string, { statements?: number; git?: number }> = {
5353 "/:owner/:name/issues/:number": { statements: 70 },
54 "/:owner/:name/next": { statements: 65 }, // +1: the growth line, one read for the week, the open counts and the planner pause (#12290, #12867)
54 "/:owner/:name/next": { statements: 66 }, // +1: the wallet row, one read of the monthly cap (#13529); +1: the growth line, one read for the week, the open counts and the planner pause (#12290, #12867)
5555 "/:owner/:name/pulls/:number": { statements: 114 }, // +1: the desk hold on the pull, one read of the notes that link it (#12536); +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
5656 "/api/v1/asks": { statements: 61 }, // +1: the stopped apps someone asked for, one read of the viewer's archived repositories (#12277)
5757 "/board": { statements: 72 }, // +1: the forge-copy read for the tell box (#12037); +1: the vitals read the database's growth (#12025); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps
test/tui-wallet.test.ts +24
@@ -13,6 +13,8 @@ import { readWallet } from "../src/actions/wallet.ts";
1313 import { createRepo } from "../src/actions/repos.ts";
1414 import { createRun } from "../src/core/runs.ts";
1515 import type { Repo } from "../src/core/repos.ts";
16 import { setMonthCap } from "../src/core/wallet.ts";
17 import { walletLines } from "../src/tui/screens/wallet.ts";
1618 import { recordUsage } from "../src/core/usage.ts";
1719 import { createUser, type User } from "../src/core/users.ts";
1820 import { createForgeApp } from "../src/tui/forge.ts";
@@ -102,3 +104,25 @@ test("a guest who reaches the screen sees no rows", async () => {
102104 const text = await drive(undefined, [], "wallet");
103105 expect(text).not.toContain("$1.50");
104106 });
107
108 test("the screen's lines carry the low-wallet sentence under 20% left, nothing at 20%+, and the reached one at the cap", async () => {
109 const made = await createRepo(app, alice, { name: "tight", visibility: "public" });
110 if (!made.ok) throw new Error("repo");
111 const repo = made.value;
112 const run = createRun(app.db, { repoId: repo.id, kind: "agent" }).id;
113 recordUsage(app.db, {
114 runId: run, repoId: repo.id, issueId: null, agentId: null, subscriptionId: null,
115 tokensIn: 1, tokensOut: 1, costUsd: 8.5, wallMs: 1, outcome: "ok", at: "2026-11-02T10:00:00.000Z",
116 });
117 const now = new Date("2026-11-15T12:00:00.000Z");
118 const { session } = open(alice);
119 const say = (cap: number) => {
120 setMonthCap(app.db, repo.id, cap, alice.id, now);
121 return walletLines(session, repo, now);
122 };
123 expect(say(10)).toContain("Wallet: $1.50 left of $10");
124 expect(say(20).some((l) => l.startsWith("Wallet:"))).toBe(false);
125 const reached = say(8);
126 expect(reached.some((l) => l.startsWith("Wallet:"))).toBe(false);
127 expect(reached.some((l) => l.includes("monthly cap of $8 is reached"))).toBe(true);
128 });
test/wallet-low-line.test.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * A wallet under 20% left: one quiet line on the repository page, one row in /next, no banner
3 * (#13529).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { createRun } from "../src/core/runs.ts";
13 import { dollars, lowWallet, setMonthCap } from "../src/core/wallet.ts";
14 import { serve } from "../src/http/server.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dir = "";
20 let app: ReturnType<typeof createApp>;
21 let servers: Awaited<ReturnType<typeof serve>>;
22 let repoId = "";
23 let cookie = "";
24 let ownerId = "";
25
26 beforeAll(async () => {
27 dir = await mkdtemp(join(tmpdir(), "forge-wallet-low-"));
28 app = createApp({ dataDir: dir, port: 0 });
29 servers = await serve(app);
30 const made: any = await createUser(app.db, {
31 origin: "seed", trusted: true, username: "trevato", email: "[email protected]",
32 password: "a-good-passphrase", adminIfFirst: true,
33 });
34 const user = made.value ?? made;
35 ownerId = user.id;
36 const res = await fetch(servers.url + "/signin", {
37 method: "POST", redirect: "manual",
38 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
39 body: new URLSearchParams({ username: "trevato", password: "a-good-passphrase" }),
40 });
41 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
42 const r: any = await createRepo(app, user, { name: "garden", visibility: "public" });
43 repoId = (r.value ?? r).id;
44 });
45 afterAll(async () => {
46 servers.stop();
47 app.close();
48 await rm(dir, { recursive: true, force: true });
49 });
50
51 const get = async (path: string) => (await fetch(servers.url + path, { redirect: "manual", headers: { cookie } })).text();
52 const spend = (usd: number) => {
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)`).run(run.id, repoId, usd, new Date().toISOString());
55 };
56
57 test("20% or more left says nothing; under 20% says it once, in the page and in /next", async () => {
58 setMonthCap(app.db, repoId, 10, ownerId, new Date());
59 spend(8);
60 expect(lowWallet(app.db, repoId, new Date())).toBeUndefined();
61 expect(await get("/trevato/garden")).not.toContain("wallet-line");
62 expect(await get("/trevato/garden/next")).not.toContain("wallet-row");
63
64 spend(0.5);
65 expect(lowWallet(app.db, repoId, new Date())).toBe("Wallet: $1.50 left of $10");
66 const page = await get("/trevato/garden");
67 expect(page).toContain("Wallet: $1.50 left of $10");
68 expect(page.match(/id="wallet-line"/g)?.length).toBe(1);
69 const next = await get("/trevato/garden/next");
70 expect(next).toContain('id="wallet-row"');
71 expect(next).toContain("Raise the monthly cap");
72 expect(next).toContain('href="/trevato/garden/wallet"');
73 });
74
75 test("a spent wallet keeps its own sentence, with no second low line", async () => {
76 spend(5);
77 expect(lowWallet(app.db, repoId, new Date())).toBeUndefined();
78 expect(await get("/trevato/garden")).toContain("monthly cap of $10 is reached");
79 });
80
81 test("only an admin sees the line and the row: not a signed-out viewer, not a member without admin", async () => {
82 const bob: any = await createUser(app.db, {
83 origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase",
84 });
85 expect(bob.ok).toBe(true);
86 const res = await fetch(servers.url + "/signin", {
87 method: "POST", redirect: "manual",
88 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
89 body: new URLSearchParams({ username: "bob", password: "a-good-passphrase" }),
90 });
91 const bobCookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
92 expect(bobCookie).not.toBe("");
93 setMonthCap(app.db, repoId, 15, ownerId, new Date());
94 expect(lowWallet(app.db, repoId, new Date())).toBe("Wallet: $1.50 left of $15");
95 const seen = async (path: string, as: string) =>
96 (await fetch(servers.url + path, { redirect: "manual", headers: as ? { cookie: as } : {} })).text();
97 expect(await seen("/trevato/garden", cookie)).toContain('id="wallet-line"');
98 expect(await seen("/trevato/garden/next", cookie)).toContain('id="wallet-row"');
99 for (const as of ["", bobCookie]) {
100 expect(await seen("/trevato/garden", as)).not.toContain("wallet-line");
101 expect(await seen("/trevato/garden/next", as)).not.toContain("wallet-row");
102 }
103 });
104
105 test("a near-whole balance prints in whole dollars, not as float dust", () => {
106 expect(dollars(10 - 7.8 - 0.2)).toBe("$2");
107 expect(dollars(1.5)).toBe("$1.50");
108 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs