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

A forge with no model key runs every issue anyway, parks each one, and never tells its owner in one place #12460

Merged opened this in answer to

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

Merged

scout/forge:scout/12459-a-forge-with-no-model-key-runs-every-iss → main 11 commits fork 6 threads · 6 unresolved

  • Merged. scout/12459-a-forge-with-no-model-key-runs-every-iss was merged into main as f98636c.

Review

Sign in to review this change.
16 files changed +309 −6
docs/features/no-model-key.md added +10
@@ -0,0 +1,10 @@
1 # A forge with no model key
2
3 When no model key, account or grant reaches a repository, its crew cannot run (`src/crew/no_key.ts`, the same question the runner asks, read-only). The forge then:
4
5 - **starts no run.** The engine's tick holds every ready issue under one reason, `held="no_model_key=N"` (`src/crew/held.ts`); the issues stay ready, none is parked.
6 - **says it once.** "The crew cannot start: this forge has no model key." leads the home strip and the needs stack (`/asks`, the MCP `forge` tool, the terminal's needs screen). For an admin it links to `/settings/crew#crew-key`, whose key field takes focus; anyone else's link goes to the note that says to ask the forge's admin.

Non-blocking: this is stale. The key field no longer takes focus, and a non-admin is told nothing here (the line is admin-only), so there is no link to an ask-the-admin note. Say what the code does.

7 - **tells its host.** A hosted forge's heartbeat carries `crewHeld: "no_model_key"`; `/forges` (web, terminal) and `/family` (and the MCP `family` tool) show "crew cannot start: no model key" on its row.
8 - **starts at once when a key is added.** Nothing was parked, so the next tick picks the ready issues. Issues parked for this reason before the fix are un-parked by the key's save (`src/crew/wake.ts`).
9
10 Left out: folding the old park comments into one.
src/actions/crew_key.ts +2
@@ -11,6 +11,7 @@ import { addSubscription, getSubscriptionByName, setGrants } from "../core/subsc
1111 import type { User } from "../core/users.ts";
1212 import { spawnedOrg } from "../spawn/claim.ts";
1313 import { wakeParked } from "../crew/wake.ts";
14 import { forgetNoKey } from "../crew/no_key.ts";
1415
1516 const KEY_NAME = "my-key";
1617 /** The most bytes a key may be; the longest real one is well under it. */
@@ -42,6 +43,7 @@ export async function saveCrewKey(
4243 .map((r) => r.subscription_id);
4344 setGrants(app.db, scope, "", [...held, added.value.id]);
4445 }
46 forgetNoKey(app.db);
4547 // Issues parked for want of a key are tried again (`crew/wake.ts`).
4648 return { ok: true, woken: wakeParked(app, user, "key") };
4749 }
src/actions/health.ts +3
@@ -33,6 +33,7 @@ import {
3333 } from "../kernel/vitals.ts";
3434 import { snapshotsOf } from "../snapshot/service.ts";
3535 import { forgesMemory, memoryOverLine } from "../spawn/memory_fit.ts";
36 import { forgeHasNoKey, NO_KEY_AT, NO_KEY_LINE } from "../crew/no_key.ts";
3637
3738 /** Where this forge's snapshots go, as vitals reads it; undefined when it takes none. */
3839 export function snapshotPlace(app: App): VitalsInput["snapshots"] {
@@ -147,6 +148,8 @@ export function forgeNeedList(app: App, actor: User | undefined): ForgeNeed[] |
147148 const rollout = rolloutLine(h);
148149 const ledger = ledgerNeed();
149150 return [
151 // Nothing the crew would do starts until it is answered, and it is one setting (#12459).
152 ...(forgeHasNoKey(app) ? [{ cause: "stuck:no_model_key", line: NO_KEY_LINE, href: NO_KEY_AT }] : []),
150153 ...(rollout === null ? [] : [{ cause: "rollout", line: rollout, href: HEALTH_HREF }]),
151154 ...h.incidents.map((i) => ({ cause: `incident:${i.key}`, line: `${i.key}: ${i.message}`, href: HEALTH_HREF })),
152155 ...h.degraded.map((d) => ({ cause: d.cause, line: needLine(d), href: d.href })),
src/crew/held.ts +9
@@ -18,6 +18,9 @@
1818 * - `landed`: a merged pull closes it, but it stayed open with boxes
1919 * unticked, and no person has answered since (`landed.ts`): a builder
2020 * would only find the pull landed.
21 * - `no_model_key`: no model key or account reaches this repository, so no run
22 * would start (`no_key.ts`): every ready issue waits, ready and unparked,
23 * until a key is added.
2124 * - `stalled`: a builder ran on it and left without a pull, and nobody
2225 * who directs the crew has spoken since. The next tick parks it in the
2326 * crew's name, which frees it (`stalls.ts`).
@@ -53,6 +56,7 @@ import { freshPulls, pullFor } from "./fresh_pull.ts";
5356 import { capReached, capReachedFor, runCapOf } from "./guard.ts";
5457 import { interruptionOf } from "./interrupted.ts";
5558 import { landedUnanswered } from "./landed.ts";
59 import { NO_KEY_HELD, repoHasNoKey } from "./no_key.ts";
5660 import { PARK_STRIKES, parkedCount } from "./parks.ts";
5761 import { retryReason } from "./retry.ts";
5862 import { heldFiles, type FileHold } from "./file_holds.ts";
@@ -69,6 +73,7 @@ export const HOLDS = [
6973 "with_planner",
7074 "done_on_main",
7175 "landed",
76 NO_KEY_HELD,
7277 "stalled",
7378 "run_cap",
7479 "parked_twice",
@@ -192,6 +197,8 @@ export function heldBy(
192197 // Read once for the whole pass, matched per issue in memory (#10445).
193198 const fresh = builders.length === 0 ? [] : freshPulls(app.db, repo.id);
194199 const handed = withPlanner(app.db, repo);
200 // Asked once for the pass, and only when a builder could otherwise start something.
201 const noKey = ready.length > 0 && repoHasNoKey(app.db, repo, crew.filter((c) => c.role === "builder").map((c) => c.agent.user.id));
195202 const hot = hotFiles(repo.id, admit);
196203 const pins = new Map(heldFiles(app.db, repo.id).map((h) => [h.path, h]));
197204 const pinned = new Map<number, FileHold>();
@@ -248,6 +255,7 @@ export function heldBy(
248255 if (handed.has(issue.id)) return "with_planner";
249256 if (alreadyDone(app.db, [issue.id]).has(issue.id)) return "done_on_main";
250257 if (landedUnanswered(app.db, repo, issue) !== undefined) return "landed";
258 if (noKey) return NO_KEY_HELD;
251259 if (stalled(app, repo, issue, lastRuns)) return "stalled";
252260 if (capped().get(issue.id) ?? atRunCap(app, repo, issue)) return "run_cap";
253261 if (!isGo(repo) && parkedCount(app.db, repo, issue.id) >= PARK_STRIKES && retryReason(app.db, repo, issue, now) === undefined)
@@ -351,6 +359,7 @@ const HOLD_WORDS: Readonly<Record<HoldName, string>> = {
351359 with_planner: "its limb waits on the planner",
352360 done_on_main: "found done on the base branch; waits for a person to close it",
353361 landed: "a merged pull closes it with boxes unticked; waits for a person",
362 [NO_KEY_HELD]: "this forge has no model key; it starts when one is added",
354363 stalled: "a builder ran on it and left without a pull",
355364 run_cap: "it has used its runs for the day",
356365 parked_twice: "parked twice; it is the planner's",
src/crew/no_key.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * A crew that cannot start for want of a model key (#12459). The runner
3 * refuses every run when no grant reaches the repository and its owner is not
4 * a forge admin, and parks the issue with that as a comment; a forge with no
5 * key then parks every ready issue, one run each. This asks the same question
6 * the runner asks (`pickSubscription`'s "none"), reading only, so the tick can
7 * say one held reason, `no_model_key`, start nothing, and leave the issues
8 * ready. Plain data in, plain data out.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import type { App } from "../app.ts";
13 import { grantLeft } from "../core/model_grant.ts";
14 import { MIN_RUN_USD } from "../core/subscriptions.ts";
15
16 /** The one sentence the home page, the needs stack and the terminal say. */
17 export const NO_KEY_LINE = "The crew cannot start: this forge has no model key.";
18 /** Where the key is added, with its field focused. */
19 export const NO_KEY_AT = "/settings/crew#crew-key";
20 /** What a host's list says of a child whose crew cannot start. */
21 export const NO_KEY_HOST_LINE = "crew cannot start: no model key";
22 /** The tick's held reason. */
23 export const NO_KEY_HELD = "no_model_key" as const;
24
25 /**
26 * Whether a run on this repository by one of `agentIds` would find no key,
27 * no admin owner and no grant left.
28 */
29 export function repoHasNoKey(db: Database, repo: { id: string; ownerId: string }, agentIds: readonly string[] | undefined, now = new Date()): boolean {
30 // `undefined`: any grant of the owner's or the repository's counts, an
31 // agent's own included (the forge-wide question stays lenient and cheap).
32 const ids = agentIds === undefined ? undefined : JSON.stringify(["", ...agentIds]);
33 const granted = db
34 .query<{ n: number }, [string, string, string | null]>(
35 `SELECT COUNT(*) AS n FROM subscription_grant g
36 WHERE g.scope_id IN (?1, ?2) AND g.subscription_id <> 'platform'
37 AND (?3 IS NULL OR g.agent_id IN (SELECT value FROM json_each(?3)))`,
38 )
39 .get(repo.id, repo.ownerId, ids ?? null)?.n ?? 0;
40 if (granted > 0) return false;
41 const admin = db.query<{ is_admin: number }, [string]>("SELECT is_admin FROM user WHERE id = ?1").get(repo.ownerId);
42 if (admin?.is_admin === 1) return false;
43 const left = grantLeft(db, repo.ownerId, now);
44 return left === undefined || left < MIN_RUN_USD;
45 }
46
47 const MEMO_MS = 5000;
48 const memo = new WeakMap<Database, { at: number; says: boolean }>();
49
50 /** Forgets the answer, for the moment a key is saved or a grant changes. */
51 export function forgetNoKey(db: Database): void {
52 memo.delete(db);
53 }
54
55 /**
56 * Whether this forge has a crew and none of its repositories can start a run
57 * for want of a key. Asked by the home, the needs list and the heartbeat, so
58 * the answer is kept for a few seconds.
59 */
60 export function forgeHasNoKey(app: App, now = new Date()): boolean {
61 const kept = memo.get(app.db);
62 const t = now.getTime();
63 if (kept !== undefined && t >= kept.at && t - kept.at < MEMO_MS) return kept.says;
64 const says = readNoKey(app, now);
65 memo.set(app.db, { at: t, says });
66 return says;
67 }
68
69 function readNoKey(app: App, now: Date): boolean {
70 // One statement lists the autonomous repositories and says which already
71 // have a key (an admin owner or a grant); only owners with a monthly grant are asked further.
72 const repos = app.db
outdated

Called per request from home, strip, asks and heartbeat. Compute once per request or memoise.

73 .query<{ id: string; owner_id: string; keyed: number; monthly: number }, []>(
74 `SELECT r.id, r.owner_id,
75 (EXISTS (SELECT 1 FROM user u WHERE u.id = r.owner_id AND u.is_admin = 1)
76 OR EXISTS (SELECT 1 FROM subscription_grant g
77 WHERE g.scope_id IN (r.id, r.owner_id) AND g.subscription_id <> 'platform')) AS keyed,
78 EXISTS (SELECT 1 FROM model_grant m WHERE m.user_id = r.owner_id) AS monthly
79 FROM repo r WHERE r.autonomy = 'autonomous'`,
80 )
81 .all();
82 if (repos.length === 0 || repos.some((r) => r.keyed === 1)) return false;
83 return repos.every((r) => r.monthly === 0 || repoHasNoKey(app.db, { id: r.id, ownerId: r.owner_id }, undefined, now));
84 }
src/spawn/clients.ts +7
@@ -36,6 +36,7 @@ import { readNotices } from "./archive.ts";
3636 import { billTo, personReading } from "./person_activity.ts";
3737 import { archiveProposal, type ArchiveProposal } from "./archive_proposal.ts";
3838 import { appLinkLines, type AppLinkLine } from "./app_links.ts";
39 import { NO_KEY_HELD, NO_KEY_HOST_LINE } from "../crew/no_key.ts";
3940
4041 /** What a spawned forge says about itself to anyone: nothing more. */
4142 export interface ForgeState {
@@ -95,6 +96,8 @@ export interface ClientRow {
9596 readonly stage: Stage | null;
9697 /** Dollars the child's crew spent today, from its last heartbeat; null when it has not said. */
9798 readonly spendTodayUsd: number | null;
99 /** "crew cannot start: no model key" when its last heartbeat said so (#12459); null otherwise. */
100 readonly crewHeld?: typeof NO_KEY_HELD | null;
98101 /** This month's spend from the child's own ledger; a broken chain says where; null when none. */
99102 readonly month?: MonthSum | LedgerBroken | null;
100103 /** The child's forge cap in dollars; null when none or unsaid. */
@@ -305,6 +308,7 @@ export async function clientRows(app: App, options: { probe?: boolean } = {}): P
305308 running: hostedChildApps(app, c.name) ?? null,
306309 reach: reachOf(app, c.name) ?? null,
307310 spendTodayUsd: beats[i]?.beat.spendTodayUsd ?? null,
311 crewHeld: beats[i]?.beat.crewHeld ?? null,
308312 ceilingUsd: beats[i]?.beat.ceilingUsd ?? null,
309313 month: monthOf(app, c.bodyId, now),
310314 ...creditView(app, c.name),
@@ -607,6 +611,9 @@ export function spendWords(r: ClientRow): { words: string; warn: boolean } | nul
607611 : { words: base, warn: share >= 0.8 };
608612 }
609613
614 /** What the host reads of a child whose crew cannot start; null when it can. */
615 export const crewHeldWords = (r: Pick<ClientRow, "crewHeld">): string | null => (r.crewHeld === NO_KEY_HELD ? NO_KEY_HOST_LINE : null);
616
610617 /** "grace until 2026-11-18" for a forge whose payment is late, as /forges and the terminal say it; null otherwise. */
611618 export function graceWords(r: Pick<ClientRow, "graceUntil">): string | null {
612619 return r.graceUntil === undefined ? null : `grace until ${new Date(r.graceUntil).toISOString().slice(0, 10)}`;
src/spawn/family.ts +2
@@ -11,6 +11,7 @@ import type { ChildAppsSummary } from "./child-apps.ts";
1111 import { childStandings, parentUpstream, type ChildStanding } from "./heartbeat.ts";
1212 import { listChildren } from "../actions/spawn.ts";
1313 import { hostedChildApps } from "./host.ts";
14 import { NO_KEY_HELD, NO_KEY_HOST_LINE } from "../crew/no_key.ts";
1415
1516 /** A child as the family shows it: its standing, and what its apps are doing. */
1617 export interface FamilyChild extends ChildStanding {
@@ -102,6 +103,7 @@ export function familyLines(view: FamilyView): [string, string][] {
102103 out.push([`child ${c.name}`, bits.join(" · ")]);
103104 const follow = followLine(c);
104105 if (follow !== null) out.push(["", follow]);
106 if (c.crewHeld === NO_KEY_HELD) out.push(["", NO_KEY_HOST_LINE]);
105107 if (c.apps !== null) out.push(["", c.apps]);
106108 }
107109 if (view.more > 0) out.push(["", `${view.more} more not shown`]);
src/spawn/heartbeat.ts +9 −1
@@ -29,6 +29,7 @@ import { progress } from "../core/next-steps.ts";
2929 import { running } from "../kernel/version.ts";
3030 import { forgeCeiling } from "../flow/ceiling.ts";
3131 import { during } from "../perf/jobs.ts";
32 import { forgeHasNoKey, NO_KEY_HELD } from "../crew/no_key.ts";
3233
3334 export const SIGNATURE_HEADER = "x-forge-signature";
3435 /** A child reports this often; one silent for three beats reads as quiet. */
@@ -65,6 +66,8 @@ export interface Beat {
6566 readonly spendTodayUsd?: number;
6667 /** The child's forge cap in dollars (the daily ceiling that pauses its crew), null when it has none; absent when unsaid or bad. */
6768 readonly ceilingUsd?: number | null;
69 /** Why its crew cannot start ("no_model_key" today); absent when it can or from an old child. */
70 readonly crewHeld?: typeof NO_KEY_HELD;
6871 /** Whether its person has claimed it; absent from an older child or when the value was bad. */
6972 readonly claimed?: boolean;
7073 /** Whether it has an everyday account (or chose to go without); absent likewise. */
@@ -74,7 +77,7 @@ export interface Beat {
7477 }
7578
7679 const OPTIONAL = new Set([
77 "forgeTip", "severedAt", "mode", "upstreamBehind", "conflict", "spendTodayUsd", "ceilingUsd", "claimed", "everyday", "lastTellAt",
80 "forgeTip", "severedAt", "mode", "upstreamBehind", "conflict", "spendTodayUsd", "ceilingUsd", "crewHeld", "claimed", "everyday", "lastTellAt",
7881 ]);
7982 const USD_MAX = 1_000_000;
8083
@@ -144,6 +147,7 @@ export function parseBeat(raw: string): Beat | undefined {
144147 children,
145148 ...(spend === undefined ? {} : { spendTodayUsd: spend }),
146149 ...(ceil === undefined ? {} : { ceilingUsd: ceil }),
150 ...(d["crewHeld"] === NO_KEY_HELD ? { crewHeld: NO_KEY_HELD } : {}),
147151 ...(forgeTip === undefined ? {} : { forgeTip: forgeTip as string | null }),
148152 ...(severedAt === undefined ? {} : { severedAt: severedAt as string | null }),
149153 ...(mode === undefined ? {} : { mode: mode as FollowMode }),
@@ -314,6 +318,7 @@ export async function sendBeat(
314318 ...standing(app, link.name, lastAt),
315319 children: Math.min(own, COUNT_MAX),
316320 ...spendReport(app),
321 ...(forgeHasNoKey(app) ? { crewHeld: NO_KEY_HELD } : {}),
317322 ...progress(app),
318323 // Only a forge that carries a fork of its parent's code has these to say.
319324 ...(forge === undefined
@@ -377,6 +382,8 @@ export interface ChildStanding {
377382 readonly spendTodayUsd: number | null;
378383 /** The child's forge cap in dollars; null when it has none or did not say. */
379384 readonly ceilingUsd: number | null;
385 /** Why its crew cannot start, as last reported; null when it can or did not say. */
386 readonly crewHeld: typeof NO_KEY_HELD | null;
380387 }
381388
382389 /** How many releases of this forge are newer than `version`; null when it is not one of them. */
@@ -411,6 +418,7 @@ export async function childStandings(
411418 conflict: heard?.beat.conflict ?? false,
412419 spendTodayUsd: heard?.beat.spendTodayUsd ?? null,
413420 ceilingUsd: heard?.beat.ceilingUsd ?? null,
421 crewHeld: heard?.beat.crewHeld ?? null,
414422 };
415423 });
416424 return { items, more: Math.max(0, all.length - MAX_CHILDREN) };
src/tui/screens/forges.ts +2 −2
@@ -6,7 +6,7 @@
66
77 import type { Ctx, Screen } from "../app/app.ts";
88 import { binding } from "../app/keys.ts";
9 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, creditWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
9 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, creditWords, crewHeldWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
1010 import { useLine } from "../../spawn/usage.ts";
1111 import { timeAgo } from "../../web/ui.ts";
1212 import { card } from "../ui/widgets.ts";
@@ -30,7 +30,7 @@ export function forgeLines(rows: readonly ClientRow[]): [string, string][] {
3030 if (rows.length === 0) return [["", "You have not sent a forge yet"]];
3131 return rows.flatMap((r): [string, string][] => [[
3232 r.name,
33 [r.made ? (r.awake === true ? "awake" : "asleep") : null, r.made && r.where.inProcess ? r.where.says : null, r.stopped ?? null, r.attention === null ? null : ATTENTION_WORDS[r.attention], r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link), runningWords(r), r.stage?.words ?? null, r.nextStep.words, spendWords(r)?.words ?? null, monthWords(r)?.words ?? null, creditWords(r), graceWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, r.made ? (r.lastActivityAt === null ? "no person has done anything here" : `a person last did something ${timeAgo(r.lastActivityAt)}`) : null, claimedWords(r), keepWords(r), r.archive === null || r.archive === undefined ? null : `proposed for archive: ${r.archive.why}`, r.lastHeartbeatAt === null ? "no heartbeat yet" : `heartbeat ${timeAgo(r.lastHeartbeatAt)}`]
33 [r.made ? (r.awake === true ? "awake" : "asleep") : null, r.made && r.where.inProcess ? r.where.says : null, r.stopped ?? null, crewHeldWords(r), r.attention === null ? null : ATTENTION_WORDS[r.attention], r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link), runningWords(r), r.stage?.words ?? null, r.nextStep.words, spendWords(r)?.words ?? null, monthWords(r)?.words ?? null, creditWords(r), graceWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, r.made ? (r.lastActivityAt === null ? "no person has done anything here" : `a person last did something ${timeAgo(r.lastActivityAt)}`) : null, claimedWords(r), keepWords(r), r.archive === null || r.archive === undefined ? null : `proposed for archive: ${r.archive.why}`, r.lastHeartbeatAt === null ? "no heartbeat yet" : `heartbeat ${timeAgo(r.lastHeartbeatAt)}`]
3434 .filter((m): m is string => m !== null)
3535 .join(" · "),
3636 ], ...firstScreenLines(r), ...appLinkLines(r), ...addressLines(r)]);
src/web/pages/crew.ts +2
@@ -7,6 +7,7 @@
77 */
88
99 import { budgetsCard } from "../studio/crew_budgets.ts";
10 import { crewKeyField } from "../studio/crew_key.ts";
1011 import { fundingOf, fundingWords } from "../../spawn/funding.ts";
1112 import {
1213 createAgent,
@@ -652,6 +653,7 @@ function crewView(
652653 const handover = crewHandover(ctx.app.db);
653654 const review = readReview(ctx.app);
654655 return html`${crewReadiness(ctx)}
656 ${crewKeyField(ctx)}
655657 ${pageHelp([
656658 ["Knobs", "Dials for the crew; a change applies on the next pump."],
657659 ["New agent", "The username is its handle: the author on the pull requests it opens, and the first half of its branch names. The display name is shown beside it. A model alias names the newest of its line, so the choice does not age."],
src/web/pages/family.ts +2
@@ -19,6 +19,7 @@ import { page } from "../layout.ts";
1919 import { badge, row } from "../ui.ts";
2020 import { FOLLOW_WORD } from "../../actions/follow_words.ts";
2121 import { familyTreeJs } from "./family_tree_js.ts";
22 import { NO_KEY_HELD, NO_KEY_HOST_LINE } from "../../crew/no_key.ts";
2223
2324 export interface Node {
2425 readonly label: string;
@@ -45,6 +46,7 @@ export function standingNode(c: FamilyChild): Node {
4546 meta.push(html`${c.behind === 0 ? "up to date" : `${plural(c.behind, "release")} behind`}`);
4647 }
4748 if (c.apps !== null) meta.push(html`<span data-apps>${c.apps}</span>`);
49 if (c.crewHeld === NO_KEY_HELD) meta.push(html`<span data-crew-held="${NO_KEY_HELD}">${NO_KEY_HOST_LINE}</span>`);
4850 return {
4951 label: c.name,
5052 href: c.url,
src/web/pages/forges.ts +3 −1
@@ -9,7 +9,7 @@
99 import type { Ctx } from "../../http/context.ts";
1010 import { claimsBill } from "../../actions/forge_bill.ts";
1111 import { billRow } from "./bills.ts";
12 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, memoryOf, servedRows, dropServed, creditWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
12 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, memoryOf, servedRows, dropServed, creditWords, crewHeldWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
1313 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
1414 import { notFoundPage, pageHead } from "../chrome.ts";
1515 import { html, type Html } from "../html.ts";
@@ -35,6 +35,7 @@ import { archiveForge, archivedForges, restoreForge, type ArchiveRecord } from "
3535 import { claimedWords, isForgeSort, keepWords, SORT_WORDS, sortForges, type ForgeSort } from "../../spawn/keep_words.ts";
3636 import { CHILD_NAME } from "../../spawn/placement.ts";
3737 import { forgesMemory, memoryOverLine } from "../../spawn/memory_fit.ts";
38 import { NO_KEY_HELD } from "../../crew/no_key.ts";
3839
3940
4041 /** "3 apps running", or which one is not and why. */
@@ -72,6 +73,7 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f
7273 r.apps.length === 0 ? null : html`${r.apps.join(", ")}`,
7374 appLinkSummary(r.appLinks ?? []) === null ? null : html`<span data-app-links>${appLinkSummary(r.appLinks ?? [])}</span>`,
7475 state === "unknown" ? html`it did not answer just now` : null,
outdated

Principle 5 and 8: a second attn-toned badge on the row. Say it as muted plain words like the other facts.

76 crewHeldWords(r) === null ? null : html`<span data-crew-held="${NO_KEY_HELD}">${crewHeldWords(r)}</span>`,
7577 r.made ? badge(r.awake === true ? "awake" : "asleep", r.awake === true ? { tone: "success" } : { variant: "outline" }) : null,
7678 // Where it runs, always said: a forge inside this forge's own process is never an unmarked row.
7779 r.made ? html`<span data-placement="${r.placement}"${r.where.inProcess ? html` data-in-process` : null}>${r.where.inProcess ? badge("in this forge's process", { tone: "attn" }) : null} ${r.where.says}</span>` : null,
src/web/pages/home_flow.ts +7 −2
@@ -69,6 +69,7 @@ import { inProcessNeed, whereOf } from "../../spawn/where.ts";
6969 import { untoldAnswer, markTold } from "../../core/requests.ts";
7070 import { YOURE_IN_MESSAGE } from "../../actions/users.ts";
7171 import { spawnedForge } from "../../spawn/claim.ts";
72 import { forgeHasNoKey, NO_KEY_AT, NO_KEY_LINE } from "../../crew/no_key.ts";
7273
7374
7475 /** The events that can move work between lanes, per lane. A burst of them is one fetch of the lane. */
@@ -264,6 +265,8 @@ interface StripViewer {
264265 readonly archive?: readonly ClientRow[];
265266 /** Forges that run inside this forge's own process and could be in a sandbox; an admin's only. */
266267 readonly inProcess?: number;
268 /** No model key reaches any repository: the crew cannot start (`crew/no_key.ts`). */
269 readonly noKey?: true;
267270 }
268271
269272 /** The everyday account's one quiet line: the step is on its own page, where "Keep using admin" is remembered. */
@@ -292,6 +295,8 @@ function needsOf(picture: LanePicture, viewer: StripViewer, dataDir: string, now
292295 ...(viewer.isAdmin ? (picture.strip?.needs ?? []).map((n) => ({ says: n.says, href: n.href, tone: "alarm" as const })) : []),
293296 ];
294297 return [
298 // First of all: nothing the crew would do starts until it is answered, and it is one setting.
299 ...(viewer.noKey === true ? [{ says: NO_KEY_LINE, href: NO_KEY_AT, tone: "alarm" as const }] : []),
295300 ...alarms,
296301 // A person on a hosted forge is stopped until this is answered: first among what can wait.
297302 ...(viewer.isAdmin ? (viewer.reach ?? []).map((a, n) => ({ ...reachNeed(a, n), tone: "notice" as const })) : []),
@@ -517,7 +522,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited
517522 // A spawned forge's owner is a client: the forge-wide figures are not theirs to see, whole home or lean.
518523 const spawned = known !== undefined ? known.spawned : await timePhaseAsync(ctx.request, "spawned", () => spawnedForge(ctx.app));
519524 const wide = user.isAdmin && spawned === undefined;
520 const strip = picture === undefined ? readingStrip() : stripRegion(picture, { id: user.id, isAdmin: wide, everyday: askForEveryday(ctx.app.db, user), ...(wide ? { reach: reachNeeds(ctx.app), archive: archiveNeeds(ctx.app), inProcess: await inProcessForges(ctx.app, now) } : {}) }, ctx.app.config.dataDir, now);
525 const strip = picture === undefined ? readingStrip() : stripRegion(picture, { id: user.id, isAdmin: wide, ...(wide && forgeHasNoKey(ctx.app) ? { noKey: true as const } : {}), everyday: askForEveryday(ctx.app.db, user), ...(wide ? { reach: reachNeeds(ctx.app), archive: archiveNeeds(ctx.app), inProcess: await inProcessForges(ctx.app, now) } : {}) }, ctx.app.config.dataDir, now);
521526 // What the old home also carried and is not a lane: the box that tells the crew (with Notes and
522527 // Talk), the welcome after an account is allowed, a
523528 // spawned forge's address, and a stranger's request for an account. The everyday-account ask is
@@ -646,7 +651,7 @@ export async function liveStripFragment(ctx: Ctx): Promise<Response> {
646651 const picture = await timePhaseAsync(ctx.request, "picture", () => lanePicture(ctx.app.db, optionsOf(ctx, user), "lane", now));
647652 const rendering = performance.now();
648653 const wide = user.isAdmin && (await spawnedForge(ctx.app)) === undefined;
649 const res = fragment(picture === undefined ? readingStrip() : stripRegion(picture, { id: user.id, isAdmin: wide, everyday: askForEveryday(ctx.app.db, user), ...(wide ? { reach: reachNeeds(ctx.app), archive: archiveNeeds(ctx.app), inProcess: await inProcessForges(ctx.app, now) } : {}) }, ctx.app.config.dataDir, now), { request: ctx.request });
654 const res = fragment(picture === undefined ? readingStrip() : stripRegion(picture, { id: user.id, isAdmin: wide, ...(wide && forgeHasNoKey(ctx.app) ? { noKey: true as const } : {}), everyday: askForEveryday(ctx.app.db, user), ...(wide ? { reach: reachNeeds(ctx.app), archive: archiveNeeds(ctx.app), inProcess: await inProcessForges(ctx.app, now) } : {}) }, ctx.app.config.dataDir, now), { request: ctx.request });
650655 notePhase(ctx.request, "render", performance.now() - rendering);
651656 return res;
652657 }
src/web/studio/crew_key.ts +10
@@ -74,6 +74,16 @@ const keyField = (): Html => html`<form class="stack" method="post" action="${KE
7474 <div>${btn("Save key", { variant: "primary", size: "sm", icon: "key" })}</div>
7575 </form>`;
7676
77 /**
78 * The field alone, for an admin whose crew has no key: the target of the
79 * needs line's link (`#crew-key`), which has already said why. No sentence,
80 * no autofocus: the fragment scrolls to it and nobody's focus is moved.
81 */
82 export function crewKeyField(ctx: Ctx): Html | null {
83 if (ctx.auth.user?.isAdmin !== true || crewHasCredential(ctx.app.db)) return null;
84 return html`<section class="settings-block">${keyField()}</section>`;
85 }
86
7787 /** On a forge of its own that has its own key: which one is paying, so nobody wonders whether the host's credit is drawn on. */
7888 function payingCard(app: App, compact: boolean): Html | null {
7989 if (compact || !isHostedForge(app)) return null;
test/family-heartbeat.test.ts +1
@@ -352,6 +352,7 @@ describe("family heartbeats", () => {
352352 "ceilingUsd",
353353 "children",
354354 "claimed",
355 "crewHeld",
355356 "everyday",
356357 "lastTellAt",
357358 "name",
test/no-model-key.test.ts added +156
@@ -0,0 +1,156 @@
1 /**
2 * A forge with no model key starts no run (#12459): the tick's one held reason
3 * is `no_model_key`, the issues stay ready and unparked, the needs stack, the
4 * heartbeat and the host's family carry one line, and a key lifts it at once.
5 */
6 import { afterAll, beforeAll, describe, 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 { forgeNeeds } from "../src/actions/health.ts";
11 import { saveCrewKey } from "../src/actions/crew_key.ts";
12 import { needsStack } from "../src/actions/needs.ts";
13 import { addComment, openIssue } from "../src/actions/issues.ts";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import type { Repo } from "../src/core/repos.ts";
17 import { listSubscriptions, setGrants } from "../src/core/subscriptions.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { heldNow, heldWords } from "../src/crew/held.ts";
20 import { forgeHasNoKey, forgetNoKey, NO_KEY_HOST_LINE, NO_KEY_LINE } from "../src/crew/no_key.ts";
21 import { NO_KEY_SAID } from "../src/crew/forge_budget.ts";
22 import { createSession } from "../src/core/sessions.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24 import { forgeLines } from "../src/tui/screens/forges.ts";
25 import { forgeRow } from "../src/web/pages/forges.ts";
26 import type { ClientRow } from "../src/spawn/clients.ts";
27 import { parkedCount } from "../src/crew/parks.ts";
28 import { parseBeat } from "../src/spawn/heartbeat.ts";
29 import { crewHeldWords } from "../src/spawn/clients.ts";
30 import { familyLines, type FamilyView } from "../src/spawn/family.ts";
31 import { quietLogs } from "./helpers/globals.ts";
32
33 quietLogs();
34
35 describe("a forge with no model key", () => {
36 let dir = "";
37 let app: App;
38 let admin: User;
39 let bob: User;
40 let repo: Repo;
41 let issueId = "";
42 let servers: Servers;
43 let cookie = "";
44 const page = async (path: string) => (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
45
46 beforeAll(async () => {
47 dir = await mkdtemp(join(tmpdir(), "forge-nokey-"));
48 app = createApp({ dataDir: dir, port: 0 });
49 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-starter-passphrase", adminIfFirst: true });
50 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-starter-passphrase" });
51 if (!a.ok || !b.ok) throw new Error("user");
52 admin = a.value;
53 bob = b.value;
54 const r = await createRepo(app, admin, { name: "garden", visibility: "public" });
55 if (!r.ok) throw new Error("repo");
56 // The repository is bob's, who is not a forge admin: the forge's own token is not his to spend.
57 app.db.query("UPDATE repo SET autonomy = 'autonomous', owner_id = ?2 WHERE id = ?1").run(r.value.id, bob.id);
58 repo = { ...r.value, ownerId: bob.id };
59 const i = openIssue(app, admin, repo, { title: "water the plants", body: "x" });
60 if (!i.ok) throw new Error("issue");
61 issueId = i.value.id;
62 });
63 beforeAll(async () => {
64 servers = await serve(app);
65 cookie = `forge_session=${createSession(app.db, admin.id).token}`;
66 });
67 afterAll(async () => {
68 servers.stop();
69 await rm(dir, { recursive: true, force: true });
70 });
71
72 test("the tick holds every ready issue under one reason and parks none", () => {
73 const held = heldNow(app, repo);
74 expect(held.startable).toHaveLength(0);
75 expect(heldWords(held)).toBe("no_model_key=1");
76 expect(parkedCount(app.db, repo, issueId)).toBe(0);
77 });
78
79 test("the needs list leads with one line for an admin; anyone else is told nothing and the link goes to the key field", () => {
80 expect(forgeHasNoKey(app)).toBe(true);
81 const forAdmin = needsStack({ app }, admin)[0]!;
82 expect(forAdmin.sentence).toBe(NO_KEY_LINE);
83 expect(forAdmin.link).toBe("/settings/crew#crew-key");
84 expect(forgeNeeds(app, admin)![0]).toBe(NO_KEY_LINE);
85 expect(forgeNeeds(app, bob)).toBeUndefined();
86 expect(needsStack({ app }, bob).some((n) => n.sentence === NO_KEY_LINE)).toBe(false);
87 });
88
89 test("the home strip says it to the admin, and the link's target is a field that does not take focus", async () => {
90 const home = await page("/");
91 expect(home).toContain(NO_KEY_LINE);
92 expect(home).toContain('href="/settings/crew#crew-key"');
93 const crew = await page("/settings/crew");
94 expect(crew).toContain('id="crew-key"');
95 expect(crew).not.toContain("autofocus");
96 });
97
98 test("the answer is kept for a few seconds and forgotten when a key is saved", () => {
99 app.db.query("UPDATE repo SET owner_id = ?2 WHERE id = ?1").run(repo.id, admin.id);
100 expect(forgeHasNoKey(app)).toBe(true);
101 forgetNoKey(app.db);
102 expect(forgeHasNoKey(app)).toBe(false);
103 app.db.query("UPDATE repo SET owner_id = ?2 WHERE id = ?1").run(repo.id, bob.id);
104 expect(forgeHasNoKey(app)).toBe(false);
105 forgetNoKey(app.db);
106 expect(forgeHasNoKey(app)).toBe(true);
107 });
108
109 test("the heartbeat carries it and the host's family says it", () => {
110 const beat = parseBeat(JSON.stringify({ name: "glint", at: 1, version: "1.0.0", openProposals: 0, children: 0, crewHeld: "no_model_key" }));
111 expect(beat?.crewHeld).toBe("no_model_key");
112 expect(parseBeat(JSON.stringify({ name: "glint", at: 1, version: "1.0.0", openProposals: 0, children: 0, crewHeld: "x<b>" }))?.crewHeld).toBeUndefined();
113 expect(crewHeldWords({ crewHeld: "no_model_key" })).toBe(NO_KEY_HOST_LINE);
114 expect(crewHeldWords({ crewHeld: null })).toBeNull();
115 const view = { parent: null, here: { host: null, version: "1" }, more: 0, children: [{ name: "glint", state: "reporting", version: null, forgeTip: null, severedAt: null, openProposals: null, mode: null, upstreamBehind: null, conflict: false, apps: null, placement: null, crewHeld: "no_model_key" }] } as unknown as FamilyView;
116 expect(familyLines(view).some(([, v]) => v === NO_KEY_HOST_LINE)).toBe(true);
117 });
118
119 test("/forges says it as plain words, not a badge, and the terminal says it too", () => {
120 const base = {
121 name: "glint", placement: "cell", where: { placement: "cell", inProcess: false, says: "runs in its own sandbox", movable: false, held: false },
122 url: "https://glint.test", for: null, apps: [], stage: null, sentAt: null, made: true, claimed: false, lastActivityAt: null, running: null,
123 reach: null, link: null, attention: null, spendTodayUsd: null, ceilingUsd: null, size: "small", use: { kind: "shared" },
124 disk: { own: false, path: "/d/children/c" }, lastHeartbeatAt: null, nextStep: { key: "unreported", words: "has not reported yet", lastTellAt: null },
125 } as unknown as ClientRow;
126 const held = String(forgeRow({ ...base, crewHeld: "no_model_key" }, Date.now()));
127 expect(held).toContain(`<span data-crew-held="no_model_key">${NO_KEY_HOST_LINE}</span>`);
128 expect(held).not.toMatch(/badge[^>]*>[^<]*crew cannot start/);
129 expect(String(forgeRow(base, Date.now()))).not.toContain("data-crew-held");
130 expect(forgeLines([{ ...base, crewHeld: "no_model_key" }])[0]![1]).toContain(NO_KEY_HOST_LINE);
131 expect(forgeLines([base])[0]![1]).not.toContain(NO_KEY_HOST_LINE);
132 });
133
134 test("saving a key wakes the issues parked earlier for want of one, and the hold lifts", async () => {
135 const parked = openIssue(app, admin, repo, { title: "feed the cat", body: "x" });
136 if (!parked.ok) throw new Error("issue");
137 addComment(app, admin, repo, parked.value, `Parked by the crew: ${NO_KEY_SAID}.`);
138 forgetNoKey(app.db);
139 expect(forgeHasNoKey(app)).toBe(true);
140 const saved = await saveCrewKey(app, admin, "sk-ant-api03-abcdefghijklmnop");
141 expect(saved).toMatchObject({ ok: true });
142 expect(saved.ok && saved.woken).toBe(1);
143 // The key is offered to the admin's apps; bob's repository gets it by a grant of his own.
144 setGrants(app.db, bob.id, "", listSubscriptions(app.db).map((x) => x.id));
145 forgetNoKey(app.db);
146 expect(forgeHasNoKey(app)).toBe(false);
147 expect(heldNow(app, repo).startable.length).toBeGreaterThan(0);
148 });
149
150 test("a key lifts the hold: the issue starts and the line is gone", () => {
151 expect(forgeHasNoKey(app)).toBe(false);
152 const held = heldNow(app, repo);
153 expect(held.startable.map((r) => r.issue.id)).toContain(issueId);
154 expect(needsStack({ app }, bob).some((n) => n.sentence === NO_KEY_LINE)).toBe(false);
155 });
156 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs