Public: anyone can read this; the crew can change it.
The terminal shows spend, cost and returns, and those pages leave doorless-allow.json #15360
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15353-the-terminal-shows-spend-cost-and-return → main 0 commits fork
6 files
changed +187
−5
docs/features/spend-terminal.md added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | --- | |
| 2 | topic: Bring your own AI | |
| 3 | row: Spend, cost and returns in the terminal | |
| 4 | --- | |
| 5 | # Spend, cost and returns in the terminal | |
| 6 | ||
| 7 | The money pages have a terminal door. Each reads the same core function as its page, with no second query. | |
| 8 | ||
| 9 | - **Spend** (`src/web/pages/spend.ts`, `src/web/pages/spend-tab.ts`, Settings → Spend, forge admins): palette "Spend" opens `src/tui/screens/spend.ts`. It lists each span's total, then per credential, app, agent, issue and run kind the last 5 hours, today and 7 days, then the ten costliest runs, from `readSpend`, with the page's own `usd` and `tokens`. | |
| 10 | - **Cost** (`src/web/pages/cost.ts`, `/:owner/:name/cost`): a repository's Usage screen (`src/tui/screens/usage.ts`) lists its 30 days from `costDays`; `c` copies the CSV. | |
| 11 | - **Returns** (`src/web/pages/returns.ts`, `/board/returns`): Usage opens with the returns line from `readReturns`; `[` and `]` move the window. | |
| 12 | ||
| 13 | Test: `test/tui-spend.test.ts` renders Spend from a fixture and checks a figure equal to the page's. |
scripts/doorless-allow.json −4
| @@ -22,7 +22,6 @@ | ||
| 22 | 22 | "src/web/pages/build_shots.ts", |
| 23 | 23 | "src/web/pages/claim.ts", |
| 24 | 24 | "src/web/pages/config.ts", |
| 25 | "src/web/pages/cost.ts", | |
| 26 | 25 | "src/web/pages/crew-settings.ts", |
| 27 | 26 | "src/web/pages/danger.ts", |
| 28 | 27 | "src/web/pages/dep_chain.ts", |
| @@ -80,13 +79,10 @@ | ||
| 80 | 79 | "src/web/pages/pull-spec.ts", |
| 81 | 80 | "src/web/pages/pulls.ts", |
| 82 | 81 | "src/web/pages/queue.ts", |
| 83 | "src/web/pages/returns.ts", | |
| 84 | 82 | "src/web/pages/search.ts", |
| 85 | 83 | "src/web/pages/security.ts", |
| 86 | 84 | "src/web/pages/settings.ts", |
| 87 | 85 | "src/web/pages/signup-passkey.ts", |
| 88 | "src/web/pages/spend-tab.ts", | |
| 89 | "src/web/pages/spend.ts", | |
| 90 | 86 | "src/web/pages/start_claim.ts", |
| 91 | 87 | "src/web/pages/talk.ts", |
| 92 | 88 | "src/web/pages/talk_client.ts", |
src/tui/screens/spend.ts added +93
| @@ -0,0 +1,93 @@ | ||
| 1 | /** | |
| 2 | * Spend in the terminal, a forge admin's (docs/features/spend-terminal.md): what Settings → Spend | |
| 3 | * (`src/web/pages/spend.ts`, `spend-tab.ts`) shows, from the same `readSpend`: each span's total, | |
| 4 | * then per credential, app, agent, issue and run kind the last 5 hours, today and 7 days side by | |
| 5 | * side, then the week's ten costliest runs. Figures are formatted by the page's own `usd` and | |
| 6 | * `tokens`, so the two never disagree. The cost per day and the returns are on Usage. | |
| 7 | */ | |
| 8 | ||
| 9 | import { readSpend, type Spend, type SpendLine, type SpanName } from "../../actions/spend.ts"; | |
| 10 | import { tokens, usd } from "../../web/pages/spend.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import { binding } from "../app/keys.ts"; | |
| 13 | import { style } from "../term/style.ts"; | |
| 14 | import { truncate } from "../term/width.ts"; | |
| 15 | import type { Session } from "../session.ts"; | |
| 16 | import { fill, len, split } from "../ui/layout.ts"; | |
| 17 | import { ListState, drawList, type ListRow } from "./common.ts"; | |
| 18 | import type { PaletteEntry } from "./entries.ts"; | |
| 19 | ||
| 20 | const WORDS: Readonly<Record<SpanName, string>> = { "5h": "5 h", today: "today", week: "7 d" }; | |
| 21 | const DIMENSIONS = [ | |
| 22 | ["byCredential", "Credential"], | |
| 23 | ["byApp", "App"], | |
| 24 | ["byAgent", "Agent"], | |
| 25 | ["byIssue", "Issue"], | |
| 26 | ["byKind", "Run kind"], | |
| 27 | ] as const; | |
| 28 | ||
| 29 | /** | |
| 30 | * The page's tables as rows: totals first, each attribution's names by the week's cost, the top | |
| 31 | * runs. | |
| 32 | */ | |
| 33 | export function spendRows(spend: Spend): ListRow[] { | |
| 34 | const rows: ListRow[] = spend.spans.map((s) => ({ | |
| 35 | title: `Total, ${WORDS[s.span]}`, | |
| 36 | secondary: usd(s.total.costUsd), | |
| 37 | meta: `${s.total.units} runs · ${tokens(s.total.tokensIn)} in / ${tokens(s.total.tokensOut)} out`, | |
| 38 | })); | |
| 39 | for (const [dim, title] of DIMENSIONS) { | |
| 40 | const names = new Map<string, Map<SpanName, SpendLine>>(); | |
| 41 | for (const s of spend.spans) | |
| 42 | for (const line of s[dim]) { | |
| 43 | if (!names.has(line.name)) names.set(line.name, new Map()); | |
| 44 | names.get(line.name)!.set(s.span, line); | |
| 45 | } | |
| 46 | const week = (n: string) => names.get(n)!.get("week")?.costUsd ?? 0; | |
| 47 | for (const n of [...names.keys()].sort((a, b) => week(b) - week(a))) { | |
| 48 | const of = names.get(n)!; | |
| 49 | const w = of.get("week"); | |
| 50 | rows.push({ | |
| 51 | title: `${title}: ${n}`, | |
| 52 | secondary: usd(w?.costUsd ?? 0), | |
| 53 | meta: `${spend.spans.map((s) => `${WORDS[s.span]} ${usd(of.get(s.span)?.costUsd ?? 0)}`).join(" · ")} · ${w?.units ?? 0} runs, 7 d · ${tokens(w?.tokensIn ?? 0)} / ${tokens(w?.tokensOut ?? 0)}`, | |
| 54 | }); | |
| 55 | } | |
| 56 | } | |
| 57 | for (const t of spend.top) | |
| 58 | rows.push({ | |
| 59 | title: `Run: ${t.app}`, | |
| 60 | secondary: usd(t.costUsd), | |
| 61 | meta: `${t.credential} · ${t.agent} · ${t.issue} · ${t.kind}${t.outcome === "running" ? " · running" : ""} · ${tokens(t.tokensIn)} / ${tokens(t.tokensOut)}`, | |
| 62 | }); | |
| 63 | return rows; | |
| 64 | } | |
| 65 | ||
| 66 | export function spendScreen(f: Session, ctx: Ctx): Screen { | |
| 67 | const state = new ListState(); | |
| 68 | // Read once when the screen opens; a frame or a key never re-runs it. | |
| 69 | const rows = f.user?.isAdmin === true ? spendRows(readSpend(f.app, new Date())) : []; | |
| 70 | return { | |
| 71 | title: "Spend", | |
| 72 | keys: [binding(["j", "k"], "move cursor")], | |
| 73 | render(area, s) { | |
| 74 | const c = ctx.theme.c; | |
| 75 | const [head, list] = split(area, "v", [len(1), fill(1)]); | |
| 76 | const said = rows.length === 0 ? "Spend is a forge admin's." : "US dollars at list price · 7 days, most spent first · cost per day and returns: Usage"; | |
| 77 | s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 78 | drawList(s, list!, c, state, rows); | |
| 79 | }, | |
| 80 | key: (e) => state.key(e, rows.length), | |
| 81 | }; | |
| 82 | } | |
| 83 | ||
| 84 | /** Settings → Spend, for a forge admin. */ | |
| 85 | export const entry: PaletteEntry = { | |
| 86 | rank: 565, | |
| 87 | id: "spend", | |
| 88 | title: "Spend", | |
| 89 | hint: "what the crew's runs spent, by credential, app, agent, issue and kind", | |
| 90 | after: ["money"], | |
| 91 | offered: (f) => f.user?.isAdmin === true, | |
| 92 | run: (f, ctx) => ctx.push(spendScreen(f, ctx)), | |
| 93 | }; |
src/web/pages/spend.ts +1 −1
| @@ -10,7 +10,7 @@ import type { Spend, SpendLine, SpanName } from "../../actions/spend.ts"; | ||
| 10 | 10 | import { fleetGraphHref } from "../fleet-graph.ts"; |
| 11 | 11 | import { html, type Html } from "../html.ts"; |
| 12 | 12 | |
| 13 | const usd = (n: number): string => `$${n.toFixed(2)}`; | |
| 13 | export const usd = (n: number): string => `$${n.toFixed(2)}`; | |
| 14 | 14 | /** Whole tokens, shortened past a thousand: 32 120 → 32.1k. */ |
| 15 | 15 | export const tokens = (n: number): string => |
| 16 | 16 | n >= 1_000_000 |
test/palette-roster.test.ts +2
| @@ -201,6 +201,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 201 | 201 | ["money", "Money", "this month's cost, revenue and gap, and the last 30 days"], |
| 202 | 202 | ["app-templates", "App templates", "the repositories New app offers; mark or unmark one"], |
| 203 | 203 | ["devices", "Devices", "LAN printers: model, state, supplies; declare or remove one"], |
| 204 | ["spend", "Spend", "what the crew's runs spent, by credential, app, agent, issue and kind"], | |
| 204 | 205 | ["payments", "Payments", "what was charged for the forges you claimed"], |
| 205 | 206 | ["ship-time", "Ship time", "median time from the crew's first run to done"], |
| 206 | 207 | ["edge-only-accounts", "Edge-only accounts", "who would be locked out if the platform edge sign-in went off"], |
| @@ -319,6 +320,7 @@ test("a site-admin agent is offered the roster without the person-only entries", | ||
| 319 | 320 | ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"], |
| 320 | 321 | ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"], |
| 321 | 322 | ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"], |
| 323 | ["spend", "Spend", "what the crew's runs spent, by credential, app, agent, issue and kind"], | |
| 322 | 324 | ["archived", "Archived repositories", "put away, not gone: open one or restore it"], |
| 323 | 325 | ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"], |
| 324 | 326 | ["plan-row", "Plan", "this forge's plan, its last backup, and where its owner manages billing"], |
test/tui-spend.test.ts added +78
| @@ -0,0 +1,78 @@ | ||
| 1 | /** | |
| 2 | * The terminal's Spend screen (src/tui/screens/spend.ts): the page's figures from the same | |
| 3 | * readSpend. | |
| 4 | */ | |
| 5 | import { afterAll, 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 { readSpend } from "../src/actions/spend.ts"; | |
| 12 | import { createRun } from "../src/core/runs.ts"; | |
| 13 | import { recordUsage } from "../src/core/usage.ts"; | |
| 14 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 15 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 16 | import { spendRows } from "../src/tui/screens/spend.ts"; | |
| 17 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 18 | import { spendView } from "../src/web/pages/spend.ts"; | |
| 19 | import { quietLogs } from "./helpers/globals.ts"; | |
| 20 | import { settleApp } from "./helpers/tui.ts"; | |
| 21 | ||
| 22 | quietLogs(); | |
| 23 | ||
| 24 | const dir = await mkdtemp(join(tmpdir(), "forge-tui-spend-")); | |
| 25 | const app = createApp({ dataDir: dir, port: 0 }); | |
| 26 | afterAll(async () => { | |
| 27 | app.close(); | |
| 28 | await rm(dir, { recursive: true, force: true }); | |
| 29 | }); | |
| 30 | ||
| 31 | async function open(username: string): Promise<string> { | |
| 32 | const { app: tui } = createForgeApp( | |
| 33 | app, | |
| 34 | { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(app.db, username)! }, | |
| 35 | { terminal: headlessTerminal(160, 40), exitHooks: false }, | |
| 36 | ); | |
| 37 | tui.start(); | |
| 38 | const key = (k: string) => tui.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 39 | key(":"); | |
| 40 | for (const ch of "Spend") key(ch); | |
| 41 | await settleApp(tui); | |
| 42 | key("enter"); | |
| 43 | await settleApp(tui); | |
| 44 | const text = tui.screen.toText(); | |
| 45 | tui.stop(); | |
| 46 | return text; | |
| 47 | } | |
| 48 | ||
| 49 | test("Spend opens from the palette and shows the page's totals; a member is offered nothing", async () => { | |
| 50 | for (const [username, adminIfFirst] of [["ada", true], ["bob", false]] as const) { | |
| 51 | const made = await createUser(app.db, { | |
| 52 | origin: "seed", trusted: true, username, email: `${username}@forge.local`, | |
| 53 | password: "a-good-passphrase", adminIfFirst, | |
| 54 | }); | |
| 55 | if (!made.ok) throw new Error(made.error); | |
| 56 | } | |
| 57 | const repo = await createRepo(app, getUserByName(app.db, "ada"), { name: "hello", visibility: "public" }); | |
| 58 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 59 | recordUsage(app.db, { | |
| 60 | runId: createRun(app.db, { repoId: repo.value.id, kind: "agent" }).id, | |
| 61 | repoId: repo.value.id, issueId: null, agentId: null, subscriptionId: null, | |
| 62 | tokensIn: 1200, tokensOut: 300, costUsd: 4.5, wallMs: 1, outcome: "ok", | |
| 63 | at: new Date(Date.now() - 60_000).toISOString(), | |
| 64 | }); | |
| 65 | const spend = readSpend(app, new Date()); | |
| 66 | const rows = spendRows(spend); | |
| 67 | // The same figure as the page: its markup carries the week's total. | |
| 68 | const week = `$${spend.spans.find((s) => s.span === "week")!.total.costUsd.toFixed(2)}`; | |
| 69 | expect(week).toBe("$4.50"); | |
| 70 | expect(spendView(spend).toString()).toContain(`<b>${week}</b>`); | |
| 71 | expect(rows.find((r) => r.title === "Total, 7 d")?.secondary).toBe(week); | |
| 72 | expect(rows.some((r) => r.title === "App: ada/hello")).toBe(true); | |
| 73 | ||
| 74 | const text = await open("ada"); | |
| 75 | expect(text).toContain("Total, 7 d"); | |
| 76 | expect(text).toContain("$4.50"); | |
| 77 | expect(await open("bob")).not.toContain("Total, 7 d"); | |
| 78 | }); |
new above
offline