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

A run shows which account it took and why, and Settings shows each account's place in the order #17837

opened this

Merged 4h 16m ago, live in production

scout/forge:scout/17828-a-run-shows-which-account-it-took-and-wh → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/17828-a-run-shows-which-account-it-took-and-wh was merged into main as 9b29938.

Review

Sign in to review this change.
12 files changed +242 −4
docs/features/crew-accounts.md +4
@@ -17,3 +17,7 @@ A run tries, in order: an admin's order first ("use espo-api-key only after espo
1717 - **Who reads what**: a repository's or owner's admin reads its accounts; an account someone else added is named only to a forge admin, else "an account of this forge's"; anyone else is told not found.
1818
1919 Proof: `test/crew-accounts.test.ts`. The rules are `core/subscriptions.ts` (`pickSubscription`, `scopeAccounts`, `reachWords`) and `actions/crew_accounts.ts`; the release is `crew/recheck_held.ts` (`recheckHeld(db, { runId } | { repoId, ownerId })`) on `releasePaused` (`crew/meter_watch.ts`), the one release.
20
21 ## Which account a run took, and its place (#17828)
22
23 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.
src/core/subscriptions.ts +59
@@ -676,6 +676,8 @@ export type Pick =
676676 * OpenAI-compatible runner at `apiBase`, and its key is never in the run's environment.
677677 */
678678 readonly connection?: PickedConnection;
679 /** Where the account stood in the order and what was passed over to reach it (#17828). */
680 readonly order?: PickOrder;
679681 }
680682 /** Every account that may be used here is resting or spent; the earliest to wake. */
681683 | {
@@ -687,6 +689,22 @@ export type Pick =
687689 readonly connection?: boolean;
688690 };
689691
692 /** An account a pick went past, and the reason in one line. */
693 export interface PassedOver {
694 readonly name: string;
695 readonly why: string;
696 }
697
698 /**
699 * The place the picked account held in the order a pick tried, 1 first, and each one before it
700 * passed over.
701 */
702 export interface PickOrder {
703 readonly place: number;
704 readonly of: number;
705 readonly passed: readonly PassedOver[];
706 }
707
690708 /** What a crew run on an OpenAI-compatible account needs beside its key and base. */
691709 export interface PickedConnection {
692710 /** The model chosen for the account, else the first listed that can do crew work; "" when it has none. */
@@ -914,6 +932,32 @@ export function crewNext(db: Database, scope: { readonly repoId: string; readonl
914932 return crewOrder(db, all, now, crew).rows.filter((r) => awakeAt(r, now)).map((r) => r.id);
915933 }
916934
935 /**
936 * What a pick went past to reach `awake`, in the order it tried them: the accounts in `rows` order,
937 * a plan whose window is full (dropped from `rows`) standing where the reach list (`all`) put it.
938 */
939 function passedInOrder(
940 all: readonly CandidateRow[],
941 rows: readonly CandidateRow[],
942 full: ReadonlyMap<string, { window: LimitWindow; resetsAt: string }>,
943 awake: CandidateRow,
944 ): PassedOver[] {
945 const at = (name: string): number => all.findIndex((r) => r.name === name);
946 const fulls = [...full.keys()].sort((x, y) => at(x) - at(y));
947 const out: PassedOver[] = [];
948 const passFull = (name: string): void => {
949 const window = full.get(name)!.window === "5h" ? "5-hour" : "weekly";
950 out.push({ name, why: `its ${window} window is full for the crew` });
951 };
952 for (const r of rows) {
953 while (fulls.length > 0 && at(fulls[0]!) < at(r.name)) passFull(fulls.shift()!);
954 if (r === awake) break;
955 const said = r.resting_said === "" ? "" : `: ${r.resting_said}`;
956 out.push({ name: r.name, why: budgetSpent(r) ? `its $${r.budget_usd} budget is spent` : `resting${said}` });
957 }
958 return out;
959 }
960
917961 /**
918962 * The account a run works on: the first in order that is awake and has budget. When every one is
919963 * resting or spent the run waits for the soonest to wake. With no account at all it is the server's
@@ -1009,6 +1053,8 @@ export function pickSubscription(
10091053 return pickSubscription(db, dataDir, scope, now, reserve, crew);
10101054 }
10111055 const subscription = toSubscription(awake);
1056 const passed = passedInOrder(all, rows, full, awake);
1057 const order: PickOrder = { place: passed.length + 1, of: full.size + rows.length, passed };
10121058 touchSubscription(db, awake.id, now);
10131059 // On a budgeted account the run may spend at most what is left, and that
10141060 // much is reserved for it now, in the same synchronous step as the
@@ -1026,6 +1072,7 @@ export function pickSubscription(
10261072 envName: envNameOf(subscription.kind),
10271073 token: opened.value,
10281074 apiBase: subscription.apiBase,
1075 order,
10291076 ...(capUsd === undefined ? {} : { capUsd }),
10301077 ...(speaksOpenAI(awake) ? { connection: { model: modelOfRow(awake), effort: awake.effort, guarded: awake.private_ok !== 1 } } : {}),
10311078 };
@@ -1136,3 +1183,15 @@ export function anyTalkConnection(db: Database): boolean {
11361183
11371184 /** A connection was added or removed: read again on the next page. */
11381185 export const forgetTalkConnections = (db: Database): void => void anyTalk.delete(db);
1186
1187 /**
1188 * Each sealed account's place in the order a run tries them, 1 first: an admin's order (`rank`),
1189 * a plan before a pay-per-token key, then by name: the forge-wide order, which a run's own place
1190 * narrows to what it can reach. The Settings list shows it (#17828).
1191 */
1192 export function accountPlaces(db: Database): Map<string, number> {
1193 const ids = db
1194 .query<{ id: string }, []>("SELECT id FROM subscription WHERE id <> 'platform' ORDER BY rank, kind = 'api_key', name COLLATE NOCASE")
1195 .all();
1196 return new Map(ids.map((r, i) => [r.id, i + 1]));
1197 }
src/crew/account_choice.ts added +29
@@ -0,0 +1,29 @@
1 /**
2 * Why a run took the account it did (#17828), in one line the run's log keeps and the run page
3 * shows: the account, its place in the order, and the reason. `account: SubQ, 2nd of 3 in order:
4 * Work passed over (resting: usage cap reached)`; first in order says only that.
5 */
6
7 import type { PickOrder } from "../core/subscriptions.ts";
8
9 export const CHOICE_PREFIX = "account: ";
10
11 /** 1st, 2nd, 3rd, 4th, 11th, 12th, 21st. */
12 export function ordinal(n: number): string {
13 const teen = n % 100 >= 11 && n % 100 <= 13;
14 return `${n}${teen ? "th" : (["th", "st", "nd", "rd"][n % 10] ?? "th")}`;
15 }
16
17 export function choiceLine(name: string, order: PickOrder): string {
18 const why =
19 order.passed.length === 0
20 ? "first in order"
21 : order.passed.map((p) => `${p.name} passed over (${p.why})`).join("; ");
22 return `${CHOICE_PREFIX}${name}, ${ordinal(order.place)} of ${order.of} in order: ${why}`;
23 }
24
25 /** The choice line of a run's log, without its prefix; undefined when the run kept none. */
26 export function choiceOf(lines: readonly string[]): string | undefined {
27 const line = lines.find((l) => l.startsWith(CHOICE_PREFIX));
28 return line === undefined ? undefined : line.slice(CHOICE_PREFIX.length);
29 }
src/crew/run_spend.ts +2
@@ -18,6 +18,7 @@ import {
1818 PLATFORM,
1919 type Pick,
2020 } from "../core/subscriptions.ts";
21 import { choiceLine } from "./account_choice.ts";
2122 import { crewPick } from "./key_fallback.ts";
2223 import { capReached } from "../core/wallet.ts";
2324 import { cappedByLent, lentCreditLeft, lentSpent, refreshFundingOnce } from "../spawn/funding.ts";
@@ -187,6 +188,7 @@ export async function settleSpend(s: SpendState): Promise<Spend> {
187188 meter.ceilingOwner = repo.ownerId;
188189 if (picked.kind === "ready") {
189190 write(`subscription: ${picked.subscription.name}`);
191 if (picked.order !== undefined) write(choiceLine(picked.subscription.name, picked.order));
190192 noteRunProgress(app.db, run.id, { subscriptionId: picked.subscription.id });
191193 meter.subscriptionId = picked.subscription.id;
192194 } else {
src/runs/run_facts.ts +6
@@ -39,6 +39,11 @@ export interface RunFactsInput {
3939 readonly writer: boolean;
4040 /** How long it took, in the run page's words (`durationText`). */
4141 readonly took?: string | undefined;
42 /**
43 * Which account the run took and why (`choiceOf` its log); none where the viewer may not read the
44 * log.
45 */
46 readonly account?: string | undefined;
4247 }
4348
4449 /**
@@ -120,6 +125,7 @@ export function runFacts(i: RunFactsInput): RunFact[] {
120125 : `a cluster job on ${node}`;
121126 facts.push({ label: "Ran on", text: where, ...(run.placement === "runner" && i.admin ? { href: "/settings/runners" } : {}) });
122127 }
128 if (i.account !== undefined) facts.push({ label: "Account", text: i.account });
123129 if (run.startedAt !== null) facts.push({ label: "Started", text: run.startedAt, at: run.startedAt });
124130 if (i.took !== undefined) facts.push({ label: run.finishedAt === null ? "Running for" : "Took", text: i.took });
125131 if (run.attempt > 0) facts.push({ label: "Attempt", text: String(run.attempt + 1) });
src/tui/screens/runlog.ts +4 −1
@@ -32,6 +32,7 @@ import { getUsage } from "../../core/usage.ts";
3232 import { jobSandboxWords, startWords } from "../../checks/placement.ts";
3333 import { runFacts, tookText } from "../../runs/run_facts.ts";
3434 import { tookParts } from "../../checks/took_line.ts";
35 import { choiceOf } from "../../crew/account_choice.ts";
3536 import { getIssueById } from "../../core/issues.ts";
3637 import { getPull, openPullsClosing } from "../../core/pulls.ts";
3738
@@ -119,9 +120,11 @@ export function runLogScreen(
119120 admin: f.user?.isAdmin === true && f.user.kind === "user",
120121 writer: canSeeOwnerFacts(f.app.db, repo, f.user),
121122 took: tookText(run, log),
123 account: choiceOf(log),
122124 }).map((x) => `${x.label}: ${x.text}${x.href === undefined ? "" : ` ${x.href}`}`);
123125 const took = run.kind === "check" ? tookParts(log) : [];
124 return [...said, ...(took.length === 0 ? [] : [`Steps took: ${took.map((p) => `${p.name} ${p.seconds.toFixed(1)}s`).join(" · ")}`])];
126 const stepsTook = took.length === 0 ? [] : [`Steps took: ${took.map((p) => `${p.name} ${p.seconds.toFixed(1)}s`).join(" · ")}`];
127 return [...said, ...stepsTook];
125128 };
126129
127130 // A person's own build held for want of an account: one step to start it on theirs (#16490).
src/tui/screens/subscriptions.ts +3 −1
@@ -11,6 +11,7 @@
1111
1212 import {
1313 addSubscription,
14 accountPlaces,
1415 budgetRefusal,
1516 budgetsOf,
1617 deleteSubscription,
@@ -51,6 +52,7 @@ export function subscriptionsScreen(f: Session, ctx: Ctx): Screen {
5152 all = admitted() ? listSubscriptions(f.app.db) : [];
5253 const budgets = budgetsOf(f.app.db);
5354 const reach = reachWords(f.app.db);
55 const places = accountPlaces(f.app.db);
5456 // What a crew run on this admin's own repositories spends right now, and the fix.
5557 rightNow = f.user !== undefined && admitted() ? crewAccountWords(f.app, f.user, { scopeId: f.user.id, repoId: "", ownerId: f.user.id, name: f.user.username }) : undefined;
5658 const seen = standings(f.app.db, all.map((a) => a.id), new Date());
@@ -61,7 +63,7 @@ export function subscriptionsScreen(f: Session, ctx: Ctx): Screen {
6163 const pays = reach.get(s.id) ?? "";
6264 const st = seen.get(s.id);
6365 return {
64 title: s.name,
66 title: places.has(s.id) ? `${places.get(s.id)}. ${s.name}` : s.name,
6567 tone: resting ? "attn" : "success",
6668 secondary: `${s.kind} ${pays}`,
6769 meta:
src/web/pages/subscriptions.ts +4 −1
@@ -10,6 +10,7 @@ import { sshOn } from "../../settings/ssh.ts";
1010 import { listAgents, type Agent } from "../../core/agents.ts";
1111 import { listConnections } from "../../core/connections.ts";
1212 import {
13 accountPlaces,
1314 addSubscription,
1415 API_BASE_MAX,
1516 budgetsOf,
@@ -60,6 +61,7 @@ import {
6061 } from "../ui.ts";
6162 import { windowParts } from "../../actions/standing_words.ts";
6263 import { whenText } from "../../crew/limits.ts";
64 import { ordinal } from "../../crew/account_choice.ts";
6365 import { editHref } from "./connections.ts";
6466 import { accountSections } from "./origins.ts";
6567 import { liveRegionsJs } from "../client.ts";
@@ -125,6 +127,7 @@ export function subscriptionsPage(ctx: Ctx): Response {
125127 listGrantPlaces(ctx.app.db),
126128 );
127129 const reach = timePhase(ctx.request, "scopes", () => reachWords(ctx.app.db));
130 const placeOf = accountPlaces(ctx.app.db);
128131 const scopeText = (s: Subscription): string => (s.id === PLATFORM ? SERVER_TOKEN_REACH : (reach.get(s.id) ?? ""));
129132 const budgets = timePhase(ctx.request, "budgets", () =>
130133 budgetsOf(ctx.app.db),
@@ -168,7 +171,7 @@ export function subscriptionsPage(ctx: Ctx): Response {
168171 return row({
169172 nav: true,
170173 lead: icon("key"),
171 title: html`${s.name}
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>`)}
outdated

This hand-rolled span (with a data-place hook nothing reads) has no test. Add a Settings page test that asserts the text. Use plain words that match what the run page says, e.g. 'Nth in the forge's order', since this number is forge-wide and a run's place is not.

172175 ${when(rests, () =>
173176 badge(`resting until ${whenText(new Date(s.restingUntil!))}`, {
174177 tone: "attn",
src/web/studio/run.ts +2
@@ -52,6 +52,7 @@ import { crewFace } from "../pixel.ts";
5252 import { unnamedRun, voiceFor, type Actor } from "./voice.ts";
5353 import { runWord, servingHistory, wordBadge, type WordCtx } from "./words.ts";
5454 import { runningCommit } from "./running.ts";
55 import { choiceOf } from "../../crew/account_choice.ts";
5556
5657 /**
5758 * The change's words that only say again what the run's own status says ("Failed" and "stopped"):
@@ -251,6 +252,7 @@ export async function runView(
251252 admin: ctx.auth.user?.isAdmin === true && ctx.auth.user.kind === "user",
252253 writer,
253254 took: duration,
255 account: logHidden ? undefined : choiceOf(lines),
254256 });
255257 const elapsed =
256258 duration === undefined
test/account-choice.test.ts added +107
@@ -0,0 +1,107 @@
1 /**
2 * A run says which account it took, its place in the order and why (#17828): a run that skipped
3 * account 1 for a cap names the cap, and Settings lists each account's place.
4 */
5
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import type { Repo } from "../src/core/repos.ts";
13 import {
14 accountPlaces,
15 addSubscription,
16 EVERYONE,
17 pickSubscription,
18 rankAfter,
19 restSubscription,
20 setGrants,
21 } from "../src/core/subscriptions.ts";
22 import { createUser } from "../src/core/users.ts";
23 import { choiceLine, choiceOf, ordinal } from "../src/crew/account_choice.ts";
24 import { serve } from "../src/http/server.ts";
25 import { signInCookie } from "./helpers/studio-signin.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 let dataDir = "";
31 let app: App;
32 let repo: Repo;
33 let one = "";
34 let two = "";
35
36 const scope = () => ({ repoId: repo.id, ownerId: repo.ownerId, agentId: "nobody" });
37 const pick = () => {
38 const p = pickSubscription(app.db, dataDir, scope(), new Date(), undefined, { fallback: true });
39 if (p.kind !== "ready") throw new Error(`picked ${p.kind}`);
40 return p;
41 };
42
43 beforeAll(async () => {
44 dataDir = await mkdtemp(join(tmpdir(), "forge-account-choice-"));
45 app = createApp({ dataDir, port: 0 });
46 const u = await createUser(app.db, {
47 origin: "seed", trusted: true, username: "ada", email: "[email protected]",
48 password: "a-good-passphrase", isAdmin: true,
49 });
50 if (!u.ok) throw new Error("user");
51 const r = await createRepo(app, u.value, { name: "mill" });
52 if (!r.ok) throw new Error("repo");
53 repo = r.value;
54 const a = addSubscription(app.db, dataDir, { name: "first", token: "sk-ant-api03-first-key-for-the-choice-test" });
55 const b = addSubscription(app.db, dataDir, { name: "second", token: "sk-ant-api03-second-key-for-the-choice-test" });
56 if (!a.ok || !b.ok) throw new Error("sub");
57 one = a.value.id;
58 two = b.value.id;
59 setGrants(app.db, repo.id, EVERYONE, [one, two]);
60 expect(rankAfter(app.db, two, one)).toBe(true);
61 }, 30_000);
62
63 afterAll(async () => {
64 app.close();
65 await rm(dataDir, { recursive: true, force: true });
66 });
67
68 test("the first in order is said to be first, with nothing passed over", () => {
69 const p = pick();
70 expect(p.subscription.name).toBe("first");
71 expect(p.order).toEqual({ place: 1, of: 2, passed: [] });
72 expect(choiceLine("first", p.order!)).toBe("account: first, 1st of 2 in order: first in order");
73 });
74
75 test("a run that skipped account 1 for a cap names that as the reason", () => {
76 restSubscription(app.db, one, new Date(Date.now() + 3_600_000).toISOString(), "usage cap reached");
77 const p = pick();
78 expect(p.subscription.name).toBe("second");
79 expect(p.order?.place).toBe(2);
80 const line = choiceLine("second", p.order!);
81 expect(line).toBe("account: second, 2nd of 2 in order: first passed over (resting: usage cap reached)");
82 expect(choiceOf(["subscription: second", line, "other"])).toBe(line.slice("account: ".length));
83 expect(choiceOf(["nothing here"])).toBeUndefined();
84 });
85
86 test("Settings places each account in the order a run tries them", () => {
87 const places = accountPlaces(app.db);
88 expect(places.get(one)).toBe(1);
89 expect(places.get(two)).toBe(2);
90 expect(places.has("platform")).toBe(false);
91 });
92
93 test("ordinals", () => {
94 expect([1, 2, 3, 4, 11, 12, 13, 21, 22].map(ordinal)).toEqual(["1st", "2nd", "3rd", "4th", "11th", "12th", "13th", "21st", "22nd"]);
95 });
96
97 test("Settings says each account's place in the forge's order", async () => {
98 const servers = await serve(app);
99 try {
100 const cookie = await signInCookie(servers.url, "ada");
101 const page = await (await fetch(`${servers.url}/settings/subscriptions`, { headers: { cookie } })).text();
102 expect(page).toContain("1st in the forge's order");
103 expect(page).toContain("2nd in the forge's order");
104 } finally {
105 servers.stop();
106 }
107 });
test/run-steps.test.ts +1 −1
@@ -390,7 +390,7 @@ describe("settleSpend", () => {
390390 if (!spend.ok) throw new Error("expected to start");
391391 expect(spend.picked.kind).toBe("ready");
392392 expect(meter.subscriptionId).toBe(subscription);
393 expect(said).toEqual(["subscription: work plan"]);
393 expect(said).toEqual(["subscription: work plan", "account: work plan, 1st of 1 in order: first in order"]);
394394 });
395395
396396 test("every account resting pauses the run with its session until the first wakes, uncounted as a failure", async () => {

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

Keyboard shortcuts

Docs