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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14072-the-owner-s-home-says-how-many-days-the → main 3 commits fork 1 thread · 1 unresolved
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 | ||
| 9 | 9 | - **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`). |
| 10 | 10 | |
| 11 | 11 | 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 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import type { App } from "../app.ts"; |
| 7 | import { creditDaysWords, dailyRate } from "../core/credit_days.ts"; | |
| 7 | 8 | import { crewHasCredential } from "../core/subscriptions.ts"; |
| 8 | 9 | import { leftUsd } from "../spawn/credit.ts"; |
| 9 | 10 | import { fundingOf } from "../spawn/funding.ts"; |
| @@ -40,3 +41,13 @@ export function crewCanRun(app: App): boolean { | ||
| 40 | 41 | |
| 41 | 42 | /** What a forge whose crew has nothing to run on says, on the page and in the terminal. */ |
| 42 | 43 | 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"; | ||
| 16 | 16 | import { readReturns } from "../../actions/returns.ts"; |
| 17 | 17 | import { mayManageFlags } from "../../core/flags.ts"; |
| 18 | 18 | import { ROLES, SURFACES } from "../../core/usage_count.ts"; |
| 19 | import { creditDaysLine } from "../../actions/crew_means.ts"; | |
| 19 | 20 | import { COST_DAYS, costDays, dayLine } from "../../core/cost_days.ts"; |
| 20 | 21 | import { costCsv } from "../../data/export_csv.ts"; |
| 21 | 22 | import { usd } from "../../core/money.ts"; |
| @@ -97,7 +98,7 @@ export function usageScreen(f: Session, ctx: Ctx, repo?: Repo): Screen { | ||
| 97 | 98 | repo === undefined |
| 98 | 99 | ? f.user !== undefined ? forgeSpendLines(readForgeUsage(f.app, f.user)) : [] |
| 99 | 100 | : 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)] | |
| 101 | 102 | : []; |
| 102 | 103 | return { |
| 103 | 104 | title: repo === undefined ? "Usage" : `Usage · ${repo.ownerName}/${repo.name}`, |
src/web/pages/cost.ts +3
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * same not-found a missing repository does. Every figure is formatted in |
| 6 | 6 | * `core/cost_days.ts`, the module the terminal reads too. |
| 7 | 7 | */ |
| 8 | import { creditDaysLine } from "../../actions/crew_means.ts"; | |
| 8 | 9 | import { COST_DAYS, costDays, dayRuns, dayUsd } from "../../core/cost_days.ts"; |
| 9 | 10 | import { costCsv } from "../../data/export_csv.ts"; |
| 10 | 11 | import { canSeeOwnerFacts } from "../../core/repos.ts"; |
| @@ -21,12 +22,14 @@ export function costPage(ctx: Ctx): Response { | ||
| 21 | 22 | const repo = loadRepo(ctx); |
| 22 | 23 | if (!repo || !canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx); |
| 23 | 24 | const days = timePhase(ctx.request, "cost", () => costDays(ctx.app.db, repo.id)); |
| 25 | const left = creditDaysLine(ctx.app); | |
| 24 | 26 | const rendering = performance.now(); |
| 25 | 27 | const body = html`${repoHeader(ctx, repo, "issues")} |
| 26 | 28 | <div class="page-head mt"> |
| 27 | 29 | <h1>Cost, last ${String(COST_DAYS)} days</h1> |
| 28 | 30 | <a href="/${repo.ownerName}/${repo.name}/cost.csv" download>CSV</a> |
| 29 | 31 | </div> |
| 32 | ${left === null ? "" : html`<p class="small muted" id="credit-days">${left}</p>`} | |
| 30 | 33 | <div class="table-scroll"> |
| 31 | 34 | <table class="table" aria-label="Spend per day"> |
| 32 | 35 | <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 | }); |
new above
offline