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

Settings shows each model account's last day: runs, failures by cause, seconds #17902

opened this

Merged 24h 48m ago, live in production

mason/forge:mason/17890-settings-shows-each-model-account-s-last → main 0 commits fork 3 threads · 3 unresolved

  • Merged. mason/17890-settings-shows-each-model-account-s-last was merged into main as b94d3fc.

Review

Sign in to review this change.
6 files changed +289 −4
docs/features/crew-accounts.md +4
@@ -21,3 +21,7 @@ Proof: `test/crew-accounts.test.ts`. The rules are `core/subscriptions.ts` (`pic
2121 ## Which account a run took, and its place (#17828)
2222
2323 A crew run's log says which account it took, where that account stood in the order a run tries them, and why: `account: SubQ, 2nd of 3 in order: Work passed over (resting: usage cap reached)`, or `first in order` when nothing was passed over (`src/crew/account_choice.ts`, written by `settleSpend`). The run page shows it as an "Account" fact beside its others (`runFacts`), and the terminal's run view (`src/tui/screens/runlog.ts`) as `Account:`; both show it only to those who may read the log, as the log itself. Settings → Subscriptions and the terminal's Crew subscriptions screen number each account in the forge's order (`accountPlaces`: an admin's order, a plan before a key, then by name); a run's "Nth of M" counts only what it could reach, so the two can differ. A run made before this has no such line, and the page says nothing.
24
25 ## Each account's last day (#17890)
26
27 Each account row in Settings → Subscriptions (and the terminal's Subscriptions screen) says: runs in the last 24 h, the failures among them by cause (rate limit, auth, timeout, other, read off the words the run wrote) and the median seconds a run held the account: `6 runs in 24 h · 4 failed (1 rate limit, 1 auth, 1 timeout, 1 other) · median 20 s`. An account that failed over half of its last ten runs says so beside its place in the order; nothing is reordered. One read for every account (`src/crew/account_day.ts`, `accountDays`); proof: `test/account-day.test.ts`.
src/crew/account_day.ts added +100
@@ -0,0 +1,100 @@
1 /**
2 * Each model account's last day (#17890), for the Subscriptions page: runs in the last 24 hours,
3 * the failures among them by cause, and the median seconds a run held the account; and whether the
4 * account failed over half of its last ten runs, so a bad account is seen before it costs a run.
5 * One definition each:
6 * - run: a usage-ledger line of the account that is not still `running`.
7 * - failure: a run whose outcome is `failed` or `paused`. Its cause is read off the words the run
8 * wrote (`error_line`, else `summary`): timeout, auth, rate limit, else other.
9 * - seconds: the median `wall_ms` of the day's runs, to a tenth; null with no run.
10 * - struggling: more than five failures among the account's last ten runs of the week (ten runs
11 * are needed; fewer says nothing).
12 * Reads: one statement over `usage_at` and the run it belongs to; never a query per account.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import { median } from "../efficiency/baseline.ts";
17
18 const DAY_MS = 86_400_000;
19 const WEEK_MS = 7 * DAY_MS;
20 const LAST = 10;
21 const SAID_MAX = 200;
22
23 export type FailureCause = "rate limit" | "auth" | "timeout" | "other";
24 export const FAILURE_CAUSES: readonly FailureCause[] = ["rate limit", "auth", "timeout", "other"];
25
26 export interface AccountDay {
27 readonly runs: number;
28 readonly failures: Readonly<Record<FailureCause, number>>;
29 readonly medianSeconds: number | null;
30 readonly struggling: boolean;
31 }
32
33 /** An account with no run in the week. */
34 export const NO_DAY: AccountDay = { runs: 0, failures: { "rate limit": 0, auth: 0, timeout: 0, other: 0 }, medianSeconds: null, struggling: false };
35
36 /**
37 * The cause of a failed run, from the words it wrote. `flow/retro.ts` `failureClass` also reads a
38 * run's words, but for a retrospective's classes (checks, tests, merge conflicts) and with no auth
39 * class; these four are the ones an account is blamed for, so the two lists differ and stay two.
40 */
41 export function failureCause(said: string): FailureCause {
42 const s = said.toLowerCase();
43 if (/time(d)?[ _-]?out|timeout|deadline/.test(s)) return "timeout";
outdated

One way to do the thing: src/flow/retro.ts failureClass also classifies a run's words by cause (timeout, usage limit). Share the common test or state in the pull why the two must differ. Also \blimit\b|\bwindow\b will file unrelated failures as rate limits.

44 if (/\b(401|403)\b|unauthori[sz]ed|forbidden|\bauth|credential|invalid[ _-]?(api[ _-]?)?(key|token)|token (expired|revoked)/.test(s)) return "auth";
45 if (/\b429\b|rate[ _-]?limit|usage limit|limit (reached|exceeded)|hit (its|a|the) limit|window is full|too many requests|overloaded|resting/.test(s)) return "rate limit";
46 return "other";
47 }
48
49 interface Row {
50 id: string;
51 outcome: string;
52 wall_ms: number;
53 at: string;
54 said: string;
55 rn: number;
56 }
57
58 /** Every account with a run in the week, by id (an older line with no account is `platform`). */
59 export function accountDays(db: Database, now: Date = new Date()): Map<string, AccountDay> {
60 const t = now.getTime();
61 const weekIso = new Date(t - WEEK_MS).toISOString();
62 const dayIso = new Date(t - DAY_MS).toISOString();
63 const rows = db
64 .query<Row, [string, number, string, number]>(
65 `SELECT id, outcome, wall_ms, at, said, rn FROM (
66 SELECT COALESCE(u.subscription_id, 'platform') AS id, u.outcome, u.wall_ms, u.at,
67 CASE WHEN u.outcome = 'ok' THEN ''
68 ELSE substr(COALESCE(NULLIF(r.error_line, ''), r.summary, ''), 1, ?2) END AS said,
69 ROW_NUMBER() OVER (PARTITION BY COALESCE(u.subscription_id, 'platform') ORDER BY u.at DESC) AS rn
70 FROM usage u INDEXED BY usage_at LEFT JOIN run r ON r.id = u.run_id
71 WHERE u.at >= ?1 AND u.outcome <> 'running')
72 WHERE rn <= ?4 OR at >= ?3`,
73 )
74 .all(weekIso, SAID_MAX, dayIso, LAST);
75 const by = new Map<string, Row[]>();
76 for (const r of rows) by.set(r.id, [...(by.get(r.id) ?? []), r]);
77 const out = new Map<string, AccountDay>();
78 for (const [id, list] of by) {
79 const failed = (r: Row): boolean => r.outcome !== "ok";
80 const day = list.filter((r) => r.at >= dayIso);
81 const failures: Record<FailureCause, number> = { "rate limit": 0, auth: 0, timeout: 0, other: 0 };
82 for (const r of day) if (failed(r)) failures[failureCause(r.said)]++;
83 const lastTen = list.filter((r) => r.rn <= LAST);
84 out.set(id, {
85 runs: day.length,
86 failures,
87 medianSeconds: day.length === 0 ? null : Math.round((median(day.map((r) => r.wall_ms)) ?? 0) / 100) / 10,
88 struggling: lastTen.length === LAST && lastTen.filter(failed).length > LAST / 2,
89 });
90 }
91 return out;
92 }
93
94 /** The row's sentence: "12 runs in 24 h · 2 failed (1 rate limit, 1 auth) · median 41.2 s". */
95 export function dayWords(d: AccountDay): string {
96 if (d.runs === 0) return "no runs in the last 24 h";
97 const n = FAILURE_CAUSES.reduce((a, c) => a + d.failures[c], 0);
98 const by = FAILURE_CAUSES.filter((c) => d.failures[c] > 0).map((c) => `${d.failures[c]} ${c}`).join(", ");
99 return `${d.runs} ${d.runs === 1 ? "run" : "runs"} in 24 h · ${n === 0 ? "none failed" : `${n} failed (${by})`} · median ${d.medianSeconds} s`;
100 }
src/tui/screens/subscriptions.ts +5 −2
@@ -9,6 +9,7 @@
99 * `subscription_delete` do; an agent is offered neither.
1010 */
1111
12 import { accountDays, dayWords, NO_DAY } from "../../crew/account_day.ts";
1213 import {
1314 addSubscription,
1415 accountPlaces,
@@ -55,6 +56,7 @@ export function subscriptionsScreen(f: Session, ctx: Ctx): Screen {
5556 const places = accountPlaces(f.app.db);
5657 // What a crew run on this admin's own repositories spends right now, and the fix.
5758 rightNow = f.user !== undefined && admitted() ? crewAccountWords(f.app, f.user, { scopeId: f.user.id, repoId: "", ownerId: f.user.id, name: f.user.username }) : undefined;
59 const days = accountDays(f.app.db, new Date());
5860 const seen = standings(f.app.db, all.map((a) => a.id), new Date());
5961 const now = Date.now();
6062 listed = all.map((s) => {
@@ -63,16 +65,17 @@ export function subscriptionsScreen(f: Session, ctx: Ctx): Screen {
6365 const pays = reach.get(s.id) ?? "";
6466 const st = seen.get(s.id);
6567 return {
66 title: places.has(s.id) ? `${places.get(s.id)}. ${s.name}` : s.name,
68 title: (places.has(s.id) ? `${places.get(s.id)}. ${s.name}` : s.name) + (days.get(s.id)?.struggling === true ? " (failed over half of its last ten runs)" : ""),

The terminal's day line and the 'failed over half of its last ten runs' note have no test. Add one that opens this screen with the seeded runs from test/account-day.test.ts and asserts both.

6769 tone: resting ? "attn" : "success",
6870 secondary: `${s.kind} ${pays}`,
6971 meta:
7072 `${b?.budgetUsd == null ? "no budget" : `budget ${money(b.budgetUsd)}`} spent ${money(b?.spentUsd ?? 0)} ` +
7173 (resting ? `resting until ${s.restingUntil}` : "awake"),
72 below:
74 below: [dayWords(days.get(s.id) ?? NO_DAY)].concat(
7375 st === undefined || st.windows.every((w) => w.cap === null && w.resetsAt === null && w.used.value === 0)
7476 ? ["windows not seen yet"]
7577 : st.windows.map(windowWords),
78 ),
7679 };
7780 });
7881 };
src/web/pages/subscriptions.ts +4 −2
@@ -62,6 +62,7 @@ import {
6262 import { windowParts } from "../../actions/standing_words.ts";
6363 import { whenText } from "../../crew/limits.ts";
6464 import { ordinal } from "../../crew/account_choice.ts";
65 import { accountDays, dayWords, NO_DAY } from "../../crew/account_day.ts";
6566 import { editHref } from "./connections.ts";
6667 import { accountSections } from "./origins.ts";
6768 import { liveRegionsJs } from "../client.ts";
@@ -139,6 +140,7 @@ export function subscriptionsPage(ctx: Ctx): Response {
139140 now,
140141 ),
141142 );
143 const days = timePhase(ctx.request, "day", () => accountDays(ctx.app.db, now));
142144 const rendering = performance.now();
143145
144146 const sealed = pool.filter((s) => s.id !== PLATFORM);
@@ -171,7 +173,7 @@ export function subscriptionsPage(ctx: Ctx): Response {
171173 return row({
172174 nav: true,
173175 lead: icon("key"),
174 title: html`${s.name}${when(placeOf.has(s.id), () => html` <span class="muted small">${ordinal(placeOf.get(s.id)!)} in the forge's order</span>`)}
176 title: html`${s.name}${when(placeOf.has(s.id), () => html` <span class="muted small">${ordinal(placeOf.get(s.id)!)} in the forge's order</span>`)}${when(days.get(s.id)?.struggling === true, () => html` <span class="muted small">failed over half of its last ten runs</span>`)}
175177 ${when(rests, () =>
176178 badge(`resting until ${whenText(new Date(s.restingUntil!))}`, {
177179 tone: "attn",
@@ -198,7 +200,7 @@ export function subscriptionsPage(ctx: Ctx): Response {
198200 ? " set by whoever made this forge; add your own key to spend more"
199201 : ""}</span
200202 >`,
201 )}${when(
203 )}<br /><span>${dayWords(days.get(s.id) ?? NO_DAY)}</span>${when(
outdated

Principle 7 (rows over boxes) and the design system's named components: this is a hand-rolled <br /> plus a span with a class (account-day) that no CSS defines. Use the row's existing detail line like the standing line after it, and drop the dead class.

202204 st !== undefined,
203205 () =>
204206 html`<br /><span
test/account-day.test.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * Settings shows each model account's last day (#17890): runs, failures by cause, median seconds.
3 */
4 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createSession } from "../src/core/sessions.ts";
11 import { accountDays, failureCause } from "../src/crew/account_day.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { seedAdmin } from "./helpers/admin.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 let dir: string;
19 let app: App;
20 let servers: Servers;
21 let cookie: string;
22 let repoId: string;
23
24 const NOW = new Date();
25 const minutesAgo = (m: number) => new Date(NOW.getTime() - m * 60_000).toISOString();
26
27 function account(id: string, name: string) {
28 app.db
29 .query(`INSERT INTO subscription (id, name, kind, token_enc, created_at) VALUES (?1, ?2, 'oauth', '', ?3)`)
30 .run(id, name, minutesAgo(60 * 24 * 30));
31 }
32
33 function ran(sub: string, outcome: "ok" | "failed" | "paused", o: { sec?: number; said?: string; min: number }) {
34 const id = crypto.randomUUID();
35 app.db
36 .query(`INSERT INTO run (id, repo_id, kind, state, summary) VALUES (?1, ?2, 'agent', ?3, ?4)`)
37 .run(id, repoId, outcome === "ok" ? "ok" : "failed", o.said ?? "");
38 app.db
39 .query(`INSERT INTO usage (run_id, repo_id, subscription_id, kind, wall_ms, outcome, at) VALUES (?1, ?2, ?3, 'build', ?4, ?5, ?6)`)
40 .run(id, repoId, sub, (o.sec ?? 10) * 1000, outcome, minutesAgo(o.min));
41 }
42
43 beforeAll(async () => {
44 dir = await mkdtemp(join(tmpdir(), "forge-account-day-"));
45 app = createApp({ dataDir: dir, port: 0 });
46 servers = await serve(app);
47 const ada = await seedAdmin(app, { username: "ada", email: "[email protected]" });
48 if (!ada.ok) throw new Error(ada.error);
49 cookie = `forge_session=${createSession(app.db, ada.value.id).token}`;
50 const repo = await createRepo(app, ada.value, { name: "hello", visibility: "public" });
51 if (!repo.ok) throw new Error(String(repo.error));
52 repoId = repo.value.id;
53 account("acct-good", "good-one");
54 account("acct-bad", "bad-one");
55 ran("acct-good", "ok", { sec: 10, min: 10 });
56 ran("acct-good", "ok", { sec: 30, min: 20 });
57 ran("acct-good", "failed", { said: "429 too many requests", min: 30, sec: 20 });
58 ran("acct-good", "failed", { said: "401 unauthorized", min: 40, sec: 20 });
59 ran("acct-good", "paused", { said: "the run timed out", min: 50, sec: 20 });
60 ran("acct-good", "failed", { said: "boom", min: 60, sec: 20 });
61 ran("acct-good", "ok", { sec: 100, min: 60 * 30 }); // older than a day: not counted in the day
62 for (let i = 0; i < 6; i++) ran("acct-bad", "failed", { said: "rate limit", min: 5 + i });
63 for (let i = 0; i < 4; i++) ran("acct-bad", "ok", { min: 20 + i });
64 });
65
66 afterAll(async () => {
67 servers.stop();
68 app.close();
69 await rm(dir, { recursive: true, force: true });
70 });
71
72 test("causes are read off the words a run wrote", () => {
73 expect(failureCause("429 too many requests")).toBe("rate limit");
74 expect(failureCause("401 Unauthorized")).toBe("auth");
75 expect(failureCause("timed out after 600 s")).toBe("timeout");
76 expect(failureCause("boom")).toBe("other");
77 expect(failureCause("output over the size limit in the window")).toBe("other");
78 });
79
80 test("one statement reads every account's day", () => {
81 let queries = 0;
82 const counted = new Proxy(app.db, {
83 get: (t, k) => {
84 if (k === "query" || k === "prepare") queries++;
85 const v = Reflect.get(t, k, t);
86 return typeof v === "function" ? v.bind(t) : v;
87 },
88 });
89 const days = accountDays(counted, NOW);
90 expect(queries).toBe(1);
91 const good = days.get("acct-good")!;
92 expect(good.runs).toBe(6);
93 expect(good.failures).toEqual({ "rate limit": 1, auth: 1, timeout: 1, other: 1 });
94 expect(good.medianSeconds).toBe(20);
95 expect(good.struggling).toBe(false);
96 expect(days.get("acct-bad")!.struggling).toBe(true);
97 });
98
99 test("the page shows each row's day and flags a failing account, in server-rendered HTML", async () => {
100 const res = await fetch(`${servers.url}/settings/subscriptions`, { headers: { cookie } });
101 const page = await res.text();
102 expect(res.status).toBe(200);
103 expect(page).toContain("6 runs in 24 h · 4 failed (1 rate limit, 1 auth, 1 timeout, 1 other) · median 20 s");
104 expect(page).toContain("10 runs in 24 h · 6 failed (6 rate limit)");
105 expect(page.match(/failed over half of its last ten runs/g)?.length).toBe(1);
106 });
test/tui-account-day.test.ts added +70
@@ -0,0 +1,70 @@
1 /** The terminal's Subscriptions screen shows each account's last day, as the page does (#17890). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App as Forge } from "../src/app.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { addSubscription, getSubscriptionByName } from "../src/core/subscriptions.ts";
9 import { createUser, getUserByName } from "../src/core/users.ts";
10 import { createForgeApp } from "../src/tui/forge.ts";
11 import { headlessTerminal } from "../src/tui/term/terminal.ts";
12 import type { TuiIdentity } from "../src/tui/session.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14 import { settleApp, settleUntil } from "./helpers/tui.ts";
15
16 quietLogs();
17
18 let dataDir: string;
19 let forge: Forge;
20
21 const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString();
22
23 function ran(repoId: string, sub: string, outcome: "ok" | "failed", said: string, min: number) {
24 const id = crypto.randomUUID();
25 forge.db
26 .query(`INSERT INTO run (id, repo_id, kind, state, summary) VALUES (?1, ?2, 'agent', ?3, ?4)`)
27 .run(id, repoId, outcome, said);
28 forge.db
29 .query(`INSERT INTO usage (run_id, repo_id, subscription_id, kind, wall_ms, outcome, at) VALUES (?1, ?2, ?3, 'build', 20000, ?4, ?5)`)
30 .run(id, repoId, sub, outcome, minutesAgo(min));
31 }
32
33 beforeAll(async () => {
34 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-day-"));
35 forge = createApp({ dataDir, port: 0 });
36 const made = await createUser(forge.db, {
37 origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true,
38 });
39 if (!made.ok) throw new Error(made.error);
40 const repo = await createRepo(forge, made.value, { name: "hello", visibility: "public" });
41 if (!repo.ok) throw new Error(String(repo.error));
42 const add = addSubscription(forge.db, dataDir, { name: "gamma", token: "sk-ant-oat01-secretgamma" });
43 if (!add.ok) throw new Error(add.error);
44 const gamma = getSubscriptionByName(forge.db, "gamma")!;
45 for (let i = 0; i < 7; i++) ran(repo.value.id, gamma.id, "failed", "429 too many requests", 5 + i);
46 for (let i = 0; i < 3; i++) ran(repo.value.id, gamma.id, "ok", "", 20 + i);
47 });
48
49 afterAll(async () => {
50 forge.close();
51 await rm(dataDir, { recursive: true, force: true });
52 });
53
54 test("the screen says the day's runs, failures by cause and median, and the struggling note", async () => {
55 const terminal = headlessTerminal(160, 32);
56 const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(forge.db, "alice")! };
57 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
58 app.start();
59 const key = (k: string, ctrl = false) => app.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
60 key("k", true);
61 for (const ch of "Crew subscriptions") key(ch);
62 await settleApp(app);
63 await settleUntil(app, "each account's budget", { timeoutMs: 4_000 });
64 key("enter");
65 await settleUntil(app, "w wakes", { timeoutMs: 4_000 });
66 const text = app.screen.toText();
67 expect(text).toContain("10 runs in 24 h · 7 failed (7 rate limit) · median 20 s");
68 expect(text).toContain("failed over half of its last ten runs");
69 app.stop();
70 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs