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

/cost shows the last 30 days as one row per day, with a link that downloads the same rows as CSV #13561

Merged opened this

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

Merged

torque/forge:torque/13546-cost-shows-the-last-30-days-as-one-row-p → main 5 commits fork 3 threads · 3 unresolved

  • Merged. torque/13546-cost-shows-the-last-30-days-as-one-row-p was merged into main as 40a857b.

Review

Sign in to review this change.
7 files changed +94 −30
docs/features/cost-days.md +3 −2
@@ -1,10 +1,11 @@
11 # Cost by day
22
3 A repository's owner (anyone `canSeeOwnerFacts` names) reads what the crew spent on it in each of the last 14 days as a table: date, dollars, runs. The page is `/:owner/:name/cost`; the terminal's "Usage of a repository" screen opens with the same rows in the same words. Anyone else gets the page's not-found.
3 A repository's owner (anyone `canSeeOwnerFacts` names) reads what the crew spent on it in each of the last 30 days as a table: date, dollars, runs. The page is `/:owner/:name/cost`; the terminal's "Usage of a repository" screen opens with the same rows in the same words. Anyone else gets the page's not-found.
44
55 - **Source**: the usage ledger (`src/core/usage.ts`), one line per ended agent run, read in one grouped query over `usage_repo(repo_id, at)` (`src/core/cost_days.ts`).
66 - **Days are UTC.** The column header says so. A run is counted on the day it ended.
77 - **Dollars** are the provider's list price, to the cent.
8 - **A day with no run shows an em dash** (—) for dollars and runs, never `$0.00`.
8 - **A day with no run shows `$0.00` and 0 runs.**
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`).
910
1011 Tests: `test/cost-days.test.ts` (fixtures across a month boundary, the page, the terminal).
src/core/cost_days.ts +12 −14
@@ -1,5 +1,5 @@
11 /**
2 * One repository's spend per day for the last 14 days (#13330): the usage
2 * One repository's spend per day for the last 30 days (#13330): the usage
33 * ledger (`usage.ts`, one line per ended agent run) summed in one grouped
44 * query that walks `usage_repo(repo_id, at)`. The page and the terminal read
55 * this module for the rows and the words, so they never disagree.
@@ -7,24 +7,23 @@
77 * Units, stated once: `usd` is US dollars of the provider's list price, as
88 * Claude Code reports it; `runs` is ledger lines; a day is a UTC calendar day
99 * (`at` is written by `toISOString()`, so its first ten characters name it).
10 * A day with no ledger line has `usd` and `runs` null, never zero: nothing
11 * ran is not the same as nothing cost.
10 * A day with no ledger line has `usd` and `runs` 0 and shows 0.00 (#13546).
1211 */
1312
1413 import type { Database } from "bun:sqlite";
1514
16 export const COST_DAYS = 14;
15 export const COST_DAYS = 30;
1716
1817 export interface CostDay {
1918 /** `YYYY-MM-DD`, UTC. */
2019 readonly day: string;
21 readonly usd: number | null;
22 readonly runs: number | null;
20 readonly usd: number;
21 readonly runs: number;
2322 }
2423
2524 const DAY_MS = 86_400_000;
2625
27 /** The 14 days ending with the UTC day of `now`, newest first, gaps null. */
26 /** The 30 days ending with the UTC day of `now`, newest first, gaps zero. */
2827 export function costDays(db: Database, repoId: string, now: Date = new Date()): CostDay[] {
2928 const midnight = Date.parse(`${now.toISOString().slice(0, 10)}T00:00:00.000Z`);
3029 const from = new Date(midnight - (COST_DAYS - 1) * DAY_MS).toISOString();
@@ -45,19 +44,18 @@ export function costDays(db: Database, repoId: string, now: Date = new Date()):
4544 for (let i = 0; i < COST_DAYS; i++) {
4645 const day = new Date(midnight - i * DAY_MS).toISOString().slice(0, 10);
4746 const r = rows.get(day);
48 out.push({ day, usd: r?.usd ?? null, runs: r?.runs ?? null });
47 out.push({ day, usd: r?.usd ?? 0, runs: r?.runs ?? 0 });
4948 }
5049 return out;
5150 }
5251
53 export const EM_DASH = "—";
54
55 /** Dollars to the cent, or an em dash for a day nothing ended. */
56 export const dayUsd = (d: CostDay): string => (d.usd === null ? EM_DASH : `$${d.usd.toFixed(2)}`);
57 export const dayRuns = (d: CostDay): string => (d.runs === null ? EM_DASH : String(d.runs));
52 /** Dollars to the cent; a day nothing ended is 0.00. */
53 export const dayAmount = (d: CostDay): string => d.usd.toFixed(2);
54 export const dayUsd = (d: CostDay): string => `$${dayAmount(d)}`;
55 export const dayRuns = (d: CostDay): string => String(d.runs);
5856
5957 /** The terminal's line for a day, aligned: `2026-11-15 $3.20 2 runs`. */
6058 export function dayLine(d: CostDay): string {
61 const runs = d.runs === null ? EM_DASH : `${d.runs} ${d.runs === 1 ? "run" : "runs"}`;
59 const runs = `${d.runs} ${d.runs === 1 ? "run" : "runs"}`;
6260 return `${d.day} ${dayUsd(d).padStart(9)} ${runs}`;
6361 }
src/data/export_csv.ts +10
@@ -5,6 +5,7 @@
55 * `source`.
66 */
77 import type { App } from "../app.ts";
8 import { type CostDay, dayAmount, dayRuns } from "../core/cost_days.ts";
89 import type { User } from "../core/users.ts";
910 import { toCsv } from "../text/csv_write.ts";
1011 import { exportRows } from "./browse.ts";
@@ -29,3 +30,12 @@ export function exportCsv(
2930 if (!found) return { ok: false, error: "not_found" };
3031 return { ok: true, csv: toCsv(found.columns, found.rows), rows: found.rows.length, truncated: found.truncated };
3132 }
33
34 /**
35 * The cost page's rows as CSV (#13546): date (UTC), dollars to the cent, runs, newest first,
36 * the same figures `dayAmount` and `dayRuns` give the page. Text cells go through `toCsv`, so
37 * one that starts with = + - @ is neutralised.
38 */
39 export function costCsv(days: readonly CostDay[]): string {
40 return toCsv(["date_utc", "usd", "runs"], days.map((d) => [d.day, dayAmount(d), dayRuns(d)]));
41 }
src/http/server.ts +2 −1
@@ -285,7 +285,7 @@ import { spaceJson, spacePage } from "../web/pages/space.ts";
285285 import { firstSubmit } from "../web/pages/first.ts";
286286 import { nextPage, nextSubmit } from "../web/pages/next.ts";
287287 import { weekPage, weekSubmit } from "../web/pages/week.ts";
288 import { costPage } from "../web/pages/cost.ts";
288 import { costCsvDownload, costPage } from "../web/pages/cost.ts";
289289 import {
290290 appMilestonesFragment,
291291 liveMilestonesFragment,
@@ -1429,6 +1429,7 @@ export function buildRouter(): Router<Handler> {
14291429 router.add("POST", "/:owner/:name/next", nextSubmit);
14301430 router.add("GET", "/:owner/:name/week", weekPage);
14311431 router.add("GET", "/:owner/:name/cost", costPage);
1432 router.add("GET", "/:owner/:name/cost.csv", costCsvDownload);
14321433 router.add("POST", "/:owner/:name/week", weekSubmit);
14331434 router.add("POST", "/:owner/:name/issues/:number/first", firstSubmit);
14341435 router.add("GET", "/:owner/:name/flows", flowsPage);
src/tui/screens/usage.ts +11 −2
@@ -17,6 +17,7 @@ import { readReturns } from "../../actions/returns.ts";
1717 import { mayManageFlags } from "../../core/flags.ts";
1818 import { ROLES, SURFACES } from "../../core/usage_count.ts";
1919 import { COST_DAYS, costDays, dayLine } from "../../core/cost_days.ts";
20 import { costCsv } from "../../data/export_csv.ts";
2021 import { usd } from "../../core/money.ts";
2122 import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
2223 import type { Returns } from "../../core/returns.ts";
@@ -89,8 +90,9 @@ export function usageScreen(f: Session, ctx: Ctx, repo?: Repo): Screen {
8990 };
9091 let returns = read();
9192 // Forge-wide only, read once when the screen opens; readForgeUsage narrows to what this user can
92 // see. A repository's: the last 14 UTC days, the page's table in the page's words (#13330), owner
93 // see. A repository's: the last 30 UTC days, the page's table in the page's words (#13330), owner
9394 // facts only.
95 const spendRows = repo !== undefined && canSeeOwnerFacts(f.db, repo, f.user) ? costDays(f.db, repo.id) : undefined;
9496 const spend =
9597 repo === undefined
9698 ? f.user !== undefined ? forgeSpendLines(readForgeUsage(f.app, f.user)) : []
@@ -103,10 +105,11 @@ export function usageScreen(f: Session, ctx: Ctx, repo?: Repo): Screen {
103105 binding(["j", "k"], "move cursor", { hidden: rows.length === 0 }),
104106 binding(["[", "]"], "returns window", { hidden: returns === undefined }),
105107 binding(["f"], "fleet graph"),
108 binding(["c"], "copy cost CSV", { hidden: spendRows === undefined }),
106109 ],
outdated

Both doors: the terminal shows the 30 rows but has no CSV export path. Add one or state it in the docs.

107110 render(area, s) {
108111 const c = ctx.theme.c;
109 const [spendArea, top, head, list] = split(area, "v", [len(spend.length), len(returns === undefined ? 0 : 1), len(1), fill(1)]);
112 const [top, head, spendArea, list] = split(area, "v", [len(returns === undefined ? 0 : 1), len(1), len(spend.length), fill(1)]);
110113 spend.forEach((line, i) => s.text(spendArea!.x, spendArea!.y + i, truncate(line, spendArea!.w), style(c.fg, c.bg), spendArea!.x + spendArea!.w));
111114 if (returns !== undefined)
112115 s.text(top!.x, top!.y, truncate(returns, top!.w), style(c.fg, c.bg), top!.x + top!.w);
@@ -127,6 +130,12 @@ export function usageScreen(f: Session, ctx: Ctx, repo?: Repo): Screen {
127130 ctx.push(fleetGraphScreen(f, ctx, scope.repo === undefined ? null : [scope.repo]));
128131 return true;
129132 }
133 if (spendRows !== undefined && !e.ctrl && !e.alt && e.key === "c") {
134 // The page's CSV download, on the reader's clipboard.
135 ctx.copy(costCsv(spendRows));
136 ctx.toast(`${spendRows.length} days of cost sent to your clipboard as CSV.`);
137 return true;
138 }
130139 if (returns !== undefined && !e.ctrl && !e.alt && (e.key === "[" || e.key === "]")) {
131140 const next = Math.max(0, Math.min(RETURNS_SPANS.length - 1, span + (e.key === "]" ? 1 : -1)));
132141 if (next === span) return true;
src/web/pages/cost.ts +20 −1
@@ -1,15 +1,17 @@
11 /**
22 * `/:owner/:name/cost` (#13330): what the crew spent on this repository each
3 * of the last 14 UTC days, date, dollars and runs, from the usage ledger.
3 * of the last 30 UTC days, date, dollars and runs, from the usage ledger.
44 * Spend is the owner's own fact (`canSeeOwnerFacts`): anyone else gets the
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 */
88 import { COST_DAYS, costDays, dayRuns, dayUsd } from "../../core/cost_days.ts";
9 import { costCsv } from "../../data/export_csv.ts";
910 import { canSeeOwnerFacts } from "../../core/repos.ts";
1011 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1112 import type { Ctx } from "../../http/context.ts";
1213 import { crumbsFor, loadRepo, notFoundPage, repoHeader, repoPalette } from "../chrome.ts";
14 import { securityFloor } from "../../http/respond.ts";
1315 import { html } from "../html.ts";
1416 import { page } from "../layout.ts";
1517
@@ -23,6 +25,7 @@ export function costPage(ctx: Ctx): Response {
2325 const body = html`${repoHeader(ctx, repo, "issues")}
2426 <div class="page-head mt">
2527 <h1>Cost, last ${String(COST_DAYS)} days</h1>
outdated

Design principle 5/1: the link sits in page-head beside the h1; confirm it uses the one accent link style and has a muted, plain label (e.g. 'CSV'); 'Download CSV' repeats the download attribute. Minor.

28 <a href="/${repo.ownerName}/${repo.name}/cost.csv" download>CSV</a>
2629 </div>
2730 <div class="table-scroll">
2831 <table class="table" aria-label="Spend per day">
@@ -54,3 +57,19 @@ export function costPage(ctx: Ctx): Response {
5457 notePhase(ctx.request, "render", performance.now() - rendering);
5558 return response;
5659 }
60
61 // GET /:owner/:name/cost.csv: the same rows, the same gate, the same numbers.
62 export function costCsvDownload(ctx: Ctx): Response {
63 const repo = loadRepo(ctx);
64 if (!repo || !canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx);
outdated

High: wrap this Response in securityFloor(...) as archive.ts does, and assert nosniff in the test. Also build the filename from a validated slug, not raw repo.name interpolated into a header.

65 const slug = repo.name.replace(/[^A-Za-z0-9._-]/g, "_");
66 return securityFloor(
67 new Response(costCsv(costDays(ctx.app.db, repo.id)), {
68 headers: {
69 "content-type": "text/csv; charset=utf-8",
70 "content-disposition": `attachment; filename="cost-${slug}.csv"`,
71 "cache-control": "private, no-store",
72 },
73 }),
74 );
75 }
test/cost-days.test.ts +36 −10
@@ -11,6 +11,7 @@ import { createRun } from "../src/core/runs.ts";
1111 import { createRepo } from "../src/actions/repos.ts";
1212 import { createApp, type App as Forge } from "../src/app.ts";
1313 import { COST_DAYS, costDays, dayLine } from "../src/core/cost_days.ts";
14 import { costCsv } from "../src/data/export_csv.ts";
1415 import type { Repo } from "../src/core/repos.ts";
1516 import { recordUsage } from "../src/core/usage.ts";
1617 import { createUser, getUserByName } from "../src/core/users.ts";
@@ -69,27 +70,27 @@ describe("cost by day", () => {
6970 await rm(dataDir, { recursive: true, force: true });
7071 });
7172
72 test("14 rows newest first across a month boundary, a gap is an em dash, sums are by UTC day", () => {
73 test("30 rows newest first across a month boundary, a gap is 0.00, sums are by UTC day", () => {
7374 const now = new Date("2026-03-02T10:00:00.000Z");
7475 line(repo, "2026-02-28T23:59:59.999Z", 1.25); // last instant of February
7576 line(repo, "2026-03-01T00:00:00.000Z", 2); // first instant of March
7677 line(repo, "2026-03-01T13:00:00.000Z", 0.5);
7778 line(repo, "2026-03-02T09:00:00.000Z", 0.1);
78 line(repo, "2026-02-16T12:00:00.000Z", 9); // 14 days back: outside
79 line(repo, "2026-02-17T00:00:00.000Z", 3); // the 14th day: inside
79 line(repo, "2026-01-31T12:00:00.000Z", 9); // 31 days back: outside
80 line(repo, "2026-02-01T00:00:00.000Z", 3); // the 30th day: inside
8081 line(other, "2026-03-01T12:00:00.000Z", 99); // another repository's
8182 const days = costDays(forge.db, repo.id, now);
8283 expect(days).toHaveLength(COST_DAYS);
8384 expect(days[0]!.day).toBe("2026-03-02");
84 expect(days[13]!.day).toBe("2026-02-17");
85 expect(days[29]!.day).toBe("2026-02-01");
8586 const by = Object.fromEntries(days.map((d) => [d.day, d]));
8687 expect(by["2026-03-02"]).toEqual({ day: "2026-03-02", usd: 0.1, runs: 1 });
8788 expect(by["2026-03-01"]).toEqual({ day: "2026-03-01", usd: 2.5, runs: 2 });
8889 expect(by["2026-02-28"]).toEqual({ day: "2026-02-28", usd: 1.25, runs: 1 });
89 expect(by["2026-02-27"]).toEqual({ day: "2026-02-27", usd: null, runs: null });
90 expect(by["2026-02-17"]!.usd).toBe(3);
91 expect(by["2026-02-16"]).toBeUndefined();
92 expect(dayLine(by["2026-02-27"]!)).toBe("2026-02-27 — —");
90 expect(by["2026-02-27"]).toEqual({ day: "2026-02-27", usd: 0, runs: 0 });
91 expect(by["2026-02-01"]!.usd).toBe(3);
92 expect(by["2026-01-31"]).toBeUndefined();
93 expect(dayLine(by["2026-02-27"]!)).toBe("2026-02-27 $0.00 0 runs");
9394 expect(dayLine(by["2026-03-01"]!)).toBe("2026-03-01 $2.50 2 runs");
9495 // One grouped query: the plan walks the repo index.
9596 const plan = forge.db
@@ -121,12 +122,33 @@ describe("cost by day", () => {
121122 expect((text.match(/data-day="/g) ?? []).length).toBe(COST_DAYS);
122123 expect(text).toContain("$4.20");
123124 expect(text).toContain("Date (UTC)");
124 expect(text).toContain("—");
125 expect(text).not.toContain("$0.00");
125 expect(text).toContain("$0.00");
126 expect(text).toContain('href="/alice/plan/cost.csv"');
126127 expect((await fetch(`${servers.url}/alice/plan/cost`, { headers: { cookie: await signIn("bob") } })).status).toBe(404);
127128 expect((await fetch(`${servers.url}/alice/plan/cost`)).status).toBe(404);
128129 });
129130
131 test("the CSV answers text/csv with the page's numbers; others get not-found", async () => {
132 const res = await fetch(`${servers.url}/alice/plan/cost.csv`, { headers: { cookie: await signIn("alice") } });
133 expect(res.status).toBe(200);
134 expect(res.headers.get("content-type")).toContain("text/csv");
135 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
136 expect(res.headers.get("referrer-policy")).toBeTruthy();
137 expect(res.headers.get("content-security-policy")).toBeTruthy();
138 expect(res.headers.get("content-disposition")).toBe('attachment; filename="cost-plan.csv"');
139 const lines = (await res.text()).trimEnd().split("\r\n");
140 expect(lines[0]).toBe("date_utc,usd,runs");
141 expect(lines).toHaveLength(COST_DAYS + 1);
142 expect(lines[1]).toBe(`${new Date().toISOString().slice(0, 10)},4.20,1`);
143 expect(lines[2]!.endsWith(",0.00,0")).toBe(true);
144 expect((await fetch(`${servers.url}/alice/plan/cost.csv`, { headers: { cookie: await signIn("bob") } })).status).toBe(404);
145 expect((await fetch(`${servers.url}/alice/plan/cost.csv`)).status).toBe(404);
146 });
147
148 test("a CSV cell that starts with a formula character is neutralised", () => {
149 expect(costCsv([{ day: "=1+1", usd: -1, runs: 2 }])).toBe("date_utc,usd,runs\r\n'=1+1,'-1.00,2\r\n");
150 });
151
130152 test("the terminal's repository usage screen carries the same rows", async () => {
131153 const terminal = headlessTerminal(140, 40);
132154 const user = getUserByName(forge.db, "alice")!;
@@ -150,7 +172,11 @@ describe("cost by day", () => {
150172 await type("alice/plan");
151173 await press("enter");
152174 const screen = app.screen.toText();
175 expect(screen).toContain("copy cost CSV");
176 await press("c");
177 const toasted = app.screen.toText();
153178 app.stop();
179 expect(toasted).toContain(`${COST_DAYS} days of cost sent to your clipboard as CSV`);
154180 expect(screen).toContain(`Cost, last ${COST_DAYS} days`);
155181 expect(screen).toContain("$4.20");
156182 expect(screen).toContain(new Date().toISOString().slice(0, 10));

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs