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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14680-a-repository-s-wallet-says-how-many-days → main 7 commits fork 5 threads · 5 unresolved
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. | ||
| 29 | 29 | 30 rows (`actions/wallet_days.ts`); `test/wallet-days.test.ts` fails if a day is dropped or the total |
| 30 | 30 | differs from an independent sum of the ledger. Days are cut at 00:00 UTC. The terminal's wallet |
| 31 | 31 | 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. | |
| 32 | 42 | - **Speed:** the read walks `usage_repo (repo_id, at)` for twenty rows, no |
| 33 | 43 | scan and no sort, so it does not grow with the ledger |
| 34 | 44 | (`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"; | ||
| 17 | 17 | import type { UsageKind, UsageOutcome } from "../core/usage.ts"; |
| 18 | 18 | import type { User } from "../core/users.ts"; |
| 19 | 19 | 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 | 21 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 21 | 22 | |
| 22 | 23 | export const WALLET_ROWS = 20; |
| @@ -96,6 +97,11 @@ export interface WalletSummary { | ||
| 96 | 97 | readonly left: string | null; |
| 97 | 98 | /** The wallet line's words. */ |
| 98 | 99 | 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; | |
| 99 | 105 | /** |
| 100 | 106 | * The ten newest spends, newest first: date, dollars, what it paid for, `(outcome)` if not ok. |
| 101 | 107 | */ |
| @@ -122,6 +128,7 @@ export function readWalletSummary(app: App, actor: User | undefined, repo: Repo, | ||
| 122 | 128 | spent: money(spent), |
| 123 | 129 | left: cap === undefined ? null : money(Math.max(0, cap - spent)), |
| 124 | 130 | balance: balanceWords(cap, spent, now), |
| 131 | daysLeft: daysLeftLine(cap, spent, spentLastWeek(app.db, repo.id, now), now), | |
| 125 | 132 | latest, |
| 126 | 133 | }); |
| 127 | 134 | } |
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 @@ | ||
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | 14 | 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"; | |
| 16 | 17 | import { readWallet, type WalletSpend } from "../../actions/wallet.ts"; |
| 17 | 18 | import { dayBarText, readWalletDays, type WalletDay } from "../../actions/wallet_days.ts"; |
| 18 | 19 | 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 { | ||
| 145 | 146 | const muted = style(c.mutedFg, c.bg); |
| 146 | 147 | s.text(head!.x, head!.y, truncate(`last 30 days, then last 20 spends · US dollars · UTC`, head!.w), muted, head!.x + head!.w); |
| 147 | 148 | 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); | |
| 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); | |
| 150 | 153 | } |
| 151 | 154 | drawList(s, list!, c, state, r); |
| 152 | 155 | }, |
src/tui/screens/wallet.ts +4 −1
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts"; |
| 8 | 8 | import { canAdmin, type Repo } from "../../core/repos.ts"; |
| 9 | import { daysLeftLine, spentLastWeek } from "../../core/wallet_days_left.ts"; | |
| 9 | 10 | import { capReached, lowWallet, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts"; |
| 10 | 11 | import type { Ctx, Screen } from "../app/app.ts"; |
| 11 | 12 | import { binding } from "../app/keys.ts"; |
| @@ -22,10 +23,12 @@ export const mayManageWallet = (f: Session, repo: Repo): boolean => f.user !== u | ||
| 22 | 23 | export function walletLines(f: Session, repo: Repo, now: Date): string[] { |
| 23 | 24 | if (!mayManageWallet(f, repo)) return ["An admin of this repository manages its wallet."]; |
| 24 | 25 | 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); | |
| 26 | 28 | const lines = [`Spent this month: $${spent}${cap === undefined ? ". No cap is set." : `, cap $${cap}.`}`]; |
| 27 | 29 | const paused = capReached(f.db, repo.id, now, cap) ?? lowWallet(f.db, repo.id, now, cap); |
| 28 | 30 | if (paused !== undefined) lines.push(paused); |
| 31 | lines.push(daysLeftLine(cap, spentUsd, spentLastWeek(f.db, repo.id, now), now)); | |
| 29 | 32 | 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.`); |
| 30 | 33 | return lines; |
| 31 | 34 | } |
src/web/pages/wallet.ts +6 −4
| @@ -12,6 +12,7 @@ import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actio | ||
| 12 | 12 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 13 | 13 | import { canAdmin } from "../../core/repos.ts"; |
| 14 | 14 | import { capReached, money, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts"; |
| 15 | import { daysLeftLine, weekOfDays } from "../../core/wallet_days_left.ts"; | |
| 15 | 16 | import type { Ctx } from "../../http/context.ts"; |
| 16 | 17 | import { adminForm } from "../admin_form.ts"; |
| 17 | 18 | import { loadRepo, repoBase, repoNotFound } from "../chrome.ts"; |
| @@ -31,11 +32,12 @@ export function walletPage(ctx: Ctx): Response { | ||
| 31 | 32 | const rendering = performance.now(); |
| 32 | 33 | const w = read.value; |
| 33 | 34 | 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); | |
| 34 | 39 | let capBlock = null; |
| 35 | 40 | 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); | |
| 39 | 41 | const paused = capReached(ctx.app.db, repo.id, now, cap); |
| 40 | 42 | 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. |
||
| 41 | 43 | ${paused === undefined ? null : html`<p id="wallet-paused">${paused}</p>`} |
| @@ -54,10 +56,10 @@ export function walletPage(ctx: Ctx): Response { | ||
| 54 | 56 | the UTC calendar month. |
| 55 | 57 | </p>`; |
| 56 | 58 | } |
| 57 | const daily = readWalletDays(ctx.app.db, repo.id, new Date()); | |
| 58 | 59 | const body = html`<section class="settings-block" data-wallet> |
| 59 | 60 | <h2>Wallet</h2> |
| 60 | 61 | ${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.' |
||
| 61 | 63 | <h3>Last ${WALLET_DAYS} days</h3> |
| 62 | 64 | <p class="small" id="wallet-days-total">${money(daily.totalUsd)} over the last ${WALLET_DAYS} days, days in UTC.</p> |
| 63 | 65 | <div class="table-scroll"> |
test/mcp-wallet.test.ts +37
| @@ -14,6 +14,9 @@ import { createRun } from "../src/core/runs.ts"; | ||
| 14 | 14 | import { createToken, revokeToken } from "../src/core/tokens.ts"; |
| 15 | 15 | import { createUser, type User } from "../src/core/users.ts"; |
| 16 | 16 | 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"; | |
| 17 | 20 | import { tool } from "../src/http/mcp/tools/usage.ts"; |
| 18 | 21 | import type { Ctx } from "../src/http/context.ts"; |
| 19 | 22 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -74,6 +77,7 @@ const ctxFor = (user: User | undefined): Ctx => ({ | ||
| 74 | 77 | auth: { user, scope: undefined, via: "session" }, |
| 75 | 78 | theme: undefined, |
| 76 | 79 | }); |
| 80 | const sessionOf = (user: User) => new Session(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", user }); | |
| 77 | 81 | const ask = (user: User, args: Record<string, unknown>) => |
| 78 | 82 | tool.run(ctxFor(user), user, { repo: "trevato/garden", kind: "wallet", ...args }) as { ok: boolean; value?: any; error?: any }; |
| 79 | 83 | |
| @@ -185,3 +189,36 @@ test("over POST /mcp a stranger's read token gets the page's not_found, not the | ||
| 185 | 189 | expect(r.text).toContain("not_found"); |
| 186 | 190 | expect(r.text).not.toContain("latest"); |
| 187 | 191 | }); |
| 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"; | ||
| 15 | 15 | import type { Repo } from "../src/core/repos.ts"; |
| 16 | 16 | import { setMonthCap } from "../src/core/wallet.ts"; |
| 17 | 17 | import { walletLines } from "../src/tui/screens/wallet.ts"; |
| 18 | import { daysToReset } from "../src/core/wallet_days_left.ts"; | |
| 18 | 19 | import { recordUsage } from "../src/core/usage.ts"; |
| 19 | 20 | import { createUser, type User } from "../src/core/users.ts"; |
| 20 | 21 | 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 | ||
| 126 | 127 | expect(reached.some((l) => l.startsWith("Wallet:"))).toBe(false); |
| 127 | 128 | expect(reached.some((l) => l.includes("monthly cap of $8 is reached"))).toBe(true); |
| 128 | 129 | }); |
| 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", | ||
| 164 | 164 | const headers = { cookie: await cookieOf("bob") }; |
| 165 | 165 | const url = `${servers.url}/bob/wallet-app/wallet`; |
| 166 | 166 | 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. | |
| 167 | 170 | expectWork(await requestStatements(app.db, url, { headers }), { max: 40 }); |
| 168 | 171 | expectWork(await statements(app.db, () => void readWallet(app, bob, repo)), { max: 2 }); |
| 169 | 172 | }); |
new above
offline
Untested door, and days-left is placed after the 30-day total so
truncatedrops it first on a narrow terminal. Put it first and add a test ofwalletScreen. Also readnew Date()once instead of three times.