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

The owner's home says how many days the included credit lasts at the current rate #14110

Merged opened this

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

Merged

scout/forge:scout/14072-the-owner-s-home-says-how-many-days-the → main 3 commits fork 1 thread · 1 unresolved

  • Merged. scout/14072-the-owner-s-home-says-how-many-days-the was merged into main as 323fc94.

Review

Sign in to review this change.
6 files changed +129 −1
docs/features/cost-days.md +4
@@ -9,3 +9,7 @@ A repository's owner (anyone `canSeeOwnerFacts` names) reads what the crew spent
99 - **CSV**: `/:owner/:name/cost.csv` (the page's "Download CSV" link) answers `text/csv` with `date_utc,usd,runs`, same rows and gate; a cell starting with `= + - @` gets a leading `'` (`costCsv`, `src/data/export_csv.ts`).
1010
1111 Tests: `test/cost-days.test.ts` (fixtures across a month boundary, the page, the terminal).
12
13 ## Days of credit left (#14072)
14
15 On a forge that runs on the host's included credit, the cost page (and the terminal's repository usage lines) opens with one line: "About 9 days of credit left." It is the credit left divided by the mean daily spend of the whole forge's ledger over the last 7 UTC days (`src/core/credit_days.ts`, `creditDaysLine` in `src/actions/crew_means.ts`), rounded down. With no spend in those days it says the credit is not running down; with none left, that it is spent. A forge with a model key of its own, or without included credit, shows no line. Test: `test/credit-days-left.test.ts`.
src/actions/crew_means.ts +11
@@ -4,6 +4,7 @@
44 */
55
66 import type { App } from "../app.ts";
7 import { creditDaysWords, dailyRate } from "../core/credit_days.ts";
78 import { crewHasCredential } from "../core/subscriptions.ts";
89 import { leftUsd } from "../spawn/credit.ts";
910 import { fundingOf } from "../spawn/funding.ts";
@@ -40,3 +41,13 @@ export function crewCanRun(app: App): boolean {
4041
4142 /** What a forge whose crew has nothing to run on says, on the page and in the terminal. */
4243 export const NO_CREDIT_WORDS = "The crew cannot build until you add a model key or pick a plan.";
44
45 /**
46 * The line "About 9 days of credit left" from the ledger's 7-day mean, or null on a forge with
47 * its own key (the host's credit is not drawn on) or with no included credit.
48 */
49 export function creditDaysLine(app: App, now: Date = new Date()): string | null {
50 if (crewHasCredential(app.db)) return null;
51 const c = includedCredit(app);
52 return c === undefined ? null : creditDaysWords(c.leftUsd, dailyRate(app.db, now));
53 }
src/core/credit_days.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * How many days the included credit lasts at the current rate (#14072): the
3 * credit left, divided by the 7-day mean of the whole forge's usage ledger
4 * (`usage_at(at)`; the 7 UTC days ending with today, so a rising week pulls
5 * the answer down). One sentence for the page and the terminal.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 export const RATE_DAYS = 7;
11 const DAY_MS = 86_400_000;
12
13 /** Dollars a day, the mean of the last 7 UTC days of the ledger (0 when nothing ended). */
14 export function dailyRate(db: Database, now: Date = new Date()): number {
15 const midnight = Date.parse(`${now.toISOString().slice(0, 10)}T00:00:00.000Z`);
16 const from = new Date(midnight - (RATE_DAYS - 1) * DAY_MS).toISOString();
17 const to = new Date(midnight + DAY_MS).toISOString();
18 const row = db
19 .query<{ usd: number | null }, [string, string]>("SELECT SUM(cost_usd) AS usd FROM usage WHERE at >= ?1 AND at < ?2")
20 .get(from, to);
21 return (row?.usd ?? 0) / RATE_DAYS;
22 }
23
24 /** The one line, in words, for the credit left and the daily rate. */
25 export function creditDaysWords(leftUsd: number, ratePerDay: number): string {
26 if (leftUsd <= 0) return "The included credit is spent.";
27 if (!(ratePerDay > 0)) return `No spend in the last ${RATE_DAYS} days: the credit is not running down.`;
28 const days = Math.floor(leftUsd / ratePerDay);
29 if (days < 1) return "Less than a day of credit left.";
30 return `About ${days} ${days === 1 ? "day" : "days"} of credit left.`;
31 }
src/tui/screens/usage.ts +2 −1
@@ -16,6 +16,7 @@ import { readForgeUsage, type ForgeUsage } from "../../actions/usage.ts";
1616 import { readReturns } from "../../actions/returns.ts";
1717 import { mayManageFlags } from "../../core/flags.ts";
1818 import { ROLES, SURFACES } from "../../core/usage_count.ts";
19 import { creditDaysLine } from "../../actions/crew_means.ts";
1920 import { COST_DAYS, costDays, dayLine } from "../../core/cost_days.ts";
2021 import { costCsv } from "../../data/export_csv.ts";
2122 import { usd } from "../../core/money.ts";
@@ -97,7 +98,7 @@ export function usageScreen(f: Session, ctx: Ctx, repo?: Repo): Screen {
9798 repo === undefined
9899 ? f.user !== undefined ? forgeSpendLines(readForgeUsage(f.app, f.user)) : []
99100 : canSeeOwnerFacts(f.db, repo, f.user)
100 ? [`Cost, last ${COST_DAYS} days`, ...costDays(f.db, repo.id).map(dayLine)]
101 ? [`Cost, last ${COST_DAYS} days`, ...[creditDaysLine(f.app)].filter((l): l is string => l !== null), ...costDays(f.db, repo.id).map(dayLine)]
101102 : [];
102103 return {
103104 title: repo === undefined ? "Usage" : `Usage · ${repo.ownerName}/${repo.name}`,
src/web/pages/cost.ts +3
@@ -5,6 +5,7 @@
55 * same not-found a missing repository does. Every figure is formatted in
66 * `core/cost_days.ts`, the module the terminal reads too.
77 */
8 import { creditDaysLine } from "../../actions/crew_means.ts";
89 import { COST_DAYS, costDays, dayRuns, dayUsd } from "../../core/cost_days.ts";
910 import { costCsv } from "../../data/export_csv.ts";
1011 import { canSeeOwnerFacts } from "../../core/repos.ts";
@@ -21,12 +22,14 @@ export function costPage(ctx: Ctx): Response {
2122 const repo = loadRepo(ctx);
2223 if (!repo || !canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx);
2324 const days = timePhase(ctx.request, "cost", () => costDays(ctx.app.db, repo.id));
25 const left = creditDaysLine(ctx.app);
2426 const rendering = performance.now();
2527 const body = html`${repoHeader(ctx, repo, "issues")}
2628 <div class="page-head mt">
2729 <h1>Cost, last ${String(COST_DAYS)} days</h1>
2830 <a href="/${repo.ownerName}/${repo.name}/cost.csv" download>CSV</a>
2931 </div>
32 ${left === null ? "" : html`<p class="small muted" id="credit-days">${left}</p>`}
3033 <div class="table-scroll">
3134 <table class="table" aria-label="Spend per day">
3235 <thead>
test/credit-days-left.test.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * "About 9 days of credit left" (#14072): the included credit over the
3 * ledger's 7-day mean. Zero spend, a rising rate, hidden with a key of the
4 * forge's own, shown on the cost page and in the terminal's usage lines.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { creditDaysLine } from "../src/actions/crew_means.ts";
9 import { creditDaysWords, dailyRate } from "../src/core/credit_days.ts";
10 import { createRun } from "../src/core/runs.ts";
11 import { listReposOwnedBy } from "../src/core/repos.ts";
12 import { addSubscription } from "../src/core/subscriptions.ts";
13 import { recordUsage } from "../src/core/usage.ts";
14 import { getUserByName } from "../src/core/users.ts";
15 import { fundingOf, keepFunding } from "../src/spawn/funding.ts";
16 import { claimedForge, type ClaimedForge } from "./helpers/claimed-forge.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let forge: ClaimedForge;
22 beforeAll(async () => {
23 forge = await claimedForge("forge-credit-days-");
24 const made = await createRepo(forge.child, getUserByName(forge.child.db, "maria")!, { name: "ledger", visibility: "public" });
25 if (!made.ok) throw new Error("repo");
26 }, 60_000);
27 afterAll(() => forge.stop());
28
29 const now = new Date("2026-03-10T12:00:00.000Z");
30
31 function spend(at: string, costUsd: number): void {
32 const db = forge.child.db;
33 const repo = listReposOwnedBy(db, getUserByName(db, "maria")!.id)[0]!;
34 recordUsage(db, {
35 runId: createRun(db, { repoId: repo.id, kind: "agent" }).id, repoId: repo.id, issueId: null, agentId: null,
36 subscriptionId: null, tokensIn: 1, tokensOut: 1, costUsd, wallMs: 1, outcome: "ok", at,
37 });
38 }
39
40 test("words: whole days from credit over rate; zero spend and spent credit say so", () => {
41 expect(creditDaysWords(9, 1)).toBe("About 9 days of credit left.");
42 expect(creditDaysWords(1.5, 1)).toBe("About 1 day of credit left.");
43 expect(creditDaysWords(0.5, 1)).toBe("Less than a day of credit left.");
44 expect(creditDaysWords(5, 0)).toBe("No spend in the last 7 days: the credit is not running down.");
45 expect(creditDaysWords(0, 1)).toBe("The included credit is spent.");
46 });
47
48 test("zero spend never divides by zero; a rising rate shortens the answer", () => {
49 expect(dailyRate(forge.child.db, now)).toBe(0);
50 expect(creditDaysLine(forge.child, now)).toContain("No spend");
51 const funding = fundingOf(forge.child.config.dataDir)!;
52 keepFunding(forge.child.config.dataDir, { token: funding.token, capUsd: 20, spentUsd: 6 }); // $14 left
53 try {
54 spend("2026-03-04T10:00:00.000Z", 7); // 7 days ending 03-10 start at 03-04
55 spend("2026-03-03T10:00:00.000Z", 500); // outside the window
56 expect(dailyRate(forge.child.db, now)).toBe(1);
57 expect(creditDaysLine(forge.child, now)).toBe("About 14 days of credit left.");
58 spend("2026-03-10T09:00:00.000Z", 7); // the rate rises to 2 a day
59 expect(dailyRate(forge.child.db, now)).toBe(2);
60 expect(creditDaysLine(forge.child, now)).toBe("About 7 days of credit left.");
61 } finally {
62 keepFunding(forge.child.config.dataDir, funding);
63 }
64 });
65
66 test("the cost page carries the line; a key of the forge's own hides it", async () => {
67 const maria = getUserByName(forge.child.db, "maria")!;
68 const repo = listReposOwnedBy(forge.child.db, maria.id)[0]!;
69 const url = `${forge.base}/${maria.username}/${repo.name}/cost`;
70 const read = async () => (await fetch(url, { headers: { cookie: forge.owner } })).text();
71 const before = await read();
72 expect(before).toContain('id="credit-days"');
73 expect(before).toMatch(/credit/);
74 const made = addSubscription(forge.child.db, forge.child.config.dataDir, { name: "mine", token: "sk-ant-api03-" + "a".repeat(40) });
75 expect(made.ok).toBe(true);
76 expect(creditDaysLine(forge.child)).toBeNull();
77 expect(await read()).not.toContain('id="credit-days"');
78 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs