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

/settings/runners lists the forge's check runners: name, state, last seen, jobs run, and a remove button for hand-made ones #15270

Merged opened this

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

Merged

scout/forge:scout/15252-settings-runners-lists-the-forge-s-check → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15252-settings-runners-lists-the-forge-s-check was merged into main as de73be1.

Review

Sign in to review this change.
19 files changed +577 −12
docs/design/audit.md +1
@@ -131,6 +131,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
131131 - `/settings/usage` — `pages/usage.ts` · route patterns by use, unused first · `/settings/telemetry`, `/board/returns` · none seen. Not about cost, despite the name.
132132 - `/settings/telemetry` — `pages/telemetry.ts` · which agents may read telemetry · `/settings/crew` (agent grants) · none seen.
133133 - `/settings/trusted` — `pages/trusted.ts` · who may fold in without review, until when, and the kill switch · `/review`, `/settings/crew` · none seen.
134 - `/settings/runners` — `pages/runners.ts` · the check runners with state, last asked, capacity, jobs held and jobs run, and a Remove for a hand-made one · `/settings/trusted` · none seen.
134135 - `/settings/spend` — `pages/spend-tab.ts` · what the crew's runs spent, by credential, app, agent, issue and run kind · `/settings/subscriptions`, `/board/returns` · none seen. First tab of Usage (#2692).
135136 - `/settings/resilience` — `pages/domains.ts` · failure domains and their last drill · `/resilience` · none seen.
136137 - `/settings/backups` — `pages/backups.ts` (621 lines) · backups and restore · `/settings/resilience`, `/releases` · none seen.
docs/features/runners.md +4 −2
@@ -40,8 +40,10 @@ each runner seen in the last minute adds the jobs it runs at once
4040 ceiling of 16. One that stops asking stops counting a minute later, with no
4141 restart (#15253).
4242
43 Not yet: a page for them, a job that survives a restart, caches by hash
44 (#14201's follow-ups).
43 Settings → Runners (`/settings/runners`) and the terminal's **Runners** list the same rows, with
44 a remove for a hand-made one: [settings-runners.md](settings-runners.md).
45
46 Not yet: a job that survives a restart, caches by hash (#14201's follow-ups).
4547
4648 ## Start one, in two lines
4749
docs/features/settings-runners.md added +24
@@ -0,0 +1,24 @@
1 ---
2 topic: Every setting, by topic
3 row: Runners
4 ---
5 # Settings → Runners (#15252)
6
7 A forge admin sees the machines that take this forge's checks (what a runner is and how to start
8 one is [runners.md](runners.md)). Each row is a runner: its name and id, whether it is
9 **Connected** (asked for work in the last minute), **Quiet** (asked before that) or **Never
10 asked**, when it last asked, how many jobs it runs at once (what its claim says,
11 `FORGE_RUNNER_JOBS`), how many it holds now, how many it has run (each job it reports done),
12 and when it was enrolled. The rows are
13 the ones `GET /api/v1/admin/runners` answers with.
14
15 **Remove** on a hand-made runner stops its token at once and queues again any job it held: the
16 same `remove` as `DELETE /api/v1/admin/runners/<id>`, and the same `runner.removed` event. A
17 `local-N` runner is the forge's own, started again at each boot, so it has no button and is
18 refused if asked anyway.
19
20 **Both doors.** `/settings/runners` on the web (under This forge in the settings menu), and
21 **Runners** in the terminal's command palette (`src/tui/screens/runners.ts`, a forge admin's):
22 `j`/`k` move, `x` removes the hand-made runner under the cursor after a confirm. Both go through
23 `removeHandMade` in `src/actions/runners.ts`. Anyone else gets the plain 404 on the web and is
24 not offered the screen.
src/actions/runners.ts +32
@@ -10,9 +10,11 @@ import {
1010 enrolRunner,
1111 listRunners,
1212 removeRunner,
13 SEEN_FRESH_MS,
1314 wakeClaimers,
1415 type Enrolled,
1516 } from "../checks/runner_jobs.ts";
17 import { LOCAL_PREFIX } from "../checks/runner_pool.ts";
1618 import type { User } from "../core/users.ts";
1719 import { err, ok, type Result } from "../kernel/result.ts";
1820
@@ -57,3 +59,33 @@ export function remove(
5759 });
5860 return ok();
5961 }
62
63 /**
64 * The forge's own runners are `local-<n>`, as `runner_pool.ts` names them: started again at each
65 * boot.
66 */
67 export const isLocal = (r: Pick<Enrolled, "name">): boolean =>
68 r.name.startsWith(LOCAL_PREFIX) && /^\d+$/.test(r.name.slice(LOCAL_PREFIX.length));
69
70 /** A runner's state from when it last asked for work. */
71 export function runnerState(seenAt: number, now: number): "connected" | "quiet" | "never" {
72 if (seenAt === 0) return "never";
73 return now - seenAt <= SEEN_FRESH_MS ? "connected" : "quiet";
74 }
75
76 /**
77 * Removes a hand-made runner, as Settings → Runners and the terminal screen do: a `local-N` one
78 * is refused, since the forge starts it again at its next boot.
79 */
80 export function removeHandMade(
81 app: App,
82 actor: User | undefined,
83 runnerId: string,
84 ): Result<Enrolled, "not_found" | "local"> {
85 const seen = list(app, actor);
86 const runner = seen.ok ? seen.value.find((r) => r.id === runnerId) : undefined;
87 if (runner === undefined) return err("not_found");
88 if (isLocal(runner)) return err("local");
89 const gone = remove(app, actor, runnerId);
90 return gone.ok ? ok(runner) : err("not_found");
91 }
src/checks/runner_jobs.ts +39 −7
@@ -385,19 +385,22 @@ export function settleJob(
385385 end: { done: RunnerResult } | { returned: string },
386386 ): boolean {
387387 const done = "done" in end;
388 return (
389 db
390 .query(
388 return db.transaction(() => {
389 const settled = db
390 .query<{ runner_id: string | null }, [string, string, string, string]>(
391391 `UPDATE check_job SET state = ?2, result = ?3, token_hash = NULL
392 WHERE id = ?1 AND token_hash = ?4 AND state = 'claimed'`,
392 WHERE id = ?1 AND token_hash = ?4 AND state = 'claimed' RETURNING runner_id`,
393393 )
394 .run(
394 .get(
395395 jobId,
396396 done ? "done" : "returned",
397397 done ? JSON.stringify(end.done) : end.returned.slice(0, 400),
398398 sha256(presented),
399 ).changes > 0
400 );
399 );
400 // A job done is one more the runner has run (#15252); a returned one is not.
401 if (done && settled?.runner_id) db.query("UPDATE check_runner SET ran = ran + 1 WHERE id = ?1").run(settled.runner_id);
402 return settled !== null;
403 })();
401404 }
402405
403406 /**
@@ -526,3 +529,32 @@ export function nextOffer(
526529 signal.addEventListener("abort", done, { once: true });
527530 });
528531 }
532
533 /** What a runner says of its work: how many jobs it runs at once, and how many it has run. */
534 export interface RunnerWork {
535 readonly jobs: number;
536 readonly ran: number;
537 }
538
539 /** Each runner's `RunnerWork` by id: what the runners page shows beside its load. */
540 export function workByRunner(db: Database): Map<string, RunnerWork> {
541 return new Map(
542 db
543 .query<{ id: string; jobs: number; ran: number }, []>("SELECT id, jobs, ran FROM check_runner ORDER BY id LIMIT 200")
544 .all()
545 .map((r) => [r.id, { jobs: r.jobs, ran: r.ran }]),
546 );
547 }
548
549 /** How many jobs each runner holds now, by runner id: what the runners page shows as its load. */
550 export function heldByRunner(db: Database): Map<string, number> {
551 return new Map(
552 db
553 .query<
554 { runner_id: string; n: number },
555 []
556 >("SELECT runner_id, COUNT(*) AS n FROM check_job WHERE state = 'claimed' AND runner_id IS NOT NULL GROUP BY runner_id")
557 .all()
558 .map((r) => [r.runner_id, r.n]),
559 );
560 }
src/core/migration-pins/20261121210000-check-runner-ran.pin added +1
@@ -0,0 +1,1 @@
1 06bf0e63179d50659f787569d482a7566a35f26b3e40207a8eaa9062626615f8
src/core/migrations/20261121210000-check-runner-ran.ts added +6
@@ -0,0 +1,6 @@
1 // How many jobs a runner has run (#15252): one more each time it reports a job done, so
2 // Settings → Runners can show it. A job's own row does not outlive the check it served.
3 // Additive: one column.
4 export default `
5 ALTER TABLE check_runner ADD COLUMN ran INTEGER NOT NULL DEFAULT 0;
6 `;
src/http/marks/settings.json +2
@@ -6,6 +6,8 @@
66 "/settings/trusted/stop": "admin",
77 "/settings/trusted/revert": "admin",
88 "/settings/trusted/:id/remove": "admin",
9 "/settings/runners": "open",
10 "/settings/runners/:id/remove": "open",
911 "/settings/telemetry": "admin",
1012 "/settings": "open",
1113 "/settings/notify": "open",
src/http/settings_routes.ts +3
@@ -23,6 +23,7 @@ import { paymentsPage } from "../web/pages/payments.ts";
2323 import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts";
2424 import { economicsPage, economicsSet } from "../web/pages/economics.ts";
2525 import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts";
26 import { runnerRemove, runnersPage } from "../web/pages/runners.ts";
2627 import { usagePage } from "../web/pages/usage.ts";
2728 import { spendPage } from "../web/pages/spend-tab.ts";
2829 import { securityControlsPage } from "../web/pages/security_controls.ts";
@@ -157,6 +158,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
157158 router.add("POST", "/settings/trusted/stop", trustedStop);
158159 router.add("POST", "/settings/trusted/revert", trustedRevert);
159160 router.add("POST", "/settings/trusted/:id/remove", trustedRemove);
161 router.add("GET", "/settings/runners", runnersPage);
162 router.add("POST", "/settings/runners/:id/remove", runnerRemove);
160163 router.add("GET", "/settings/telemetry", telemetryPage);
161164 router.add("POST", "/settings/telemetry", telemetrySet);
162165 router.add("GET", "/settings", accountPage);
src/spawn/preview-looks.ts +5 −1
@@ -179,7 +179,7 @@ export const PREVIEW_HELD_THEMES: readonly { readonly theme: string; readonly ti
179179
180180 /**
181181 * The owner's settings pages that list things (#9781): tokens, the crew,
182 * subscriptions and usage. The seed gives each something to show and
182 * subscriptions, usage and the check runners (#15252). The seed gives each something to show and
183183 * refuses to finish if any would answer anything but 200.
184184 */
185185 export const PREVIEW_SETTINGS_PAGES: readonly string[] = [
@@ -187,8 +187,12 @@ export const PREVIEW_SETTINGS_PAGES: readonly string[] = [
187187 "/settings/crew",
188188 "/settings/subscriptions",
189189 "/settings/usage",
190 "/settings/runners",
190191 ];
191192
193 /** The hand-made runner the seed enrols, so Settings → Runners shows a row with its Remove. */
194 export const PREVIEW_RUNNER = "preview-mac";
195
192196 /**
193197 * The sample's Settings › Machines with the disks the seed records for its
194198 * `standard` machine (#10466): healthy, alerting and behind a controller,
src/spawn/preview-seed.ts +5 −1
@@ -62,6 +62,7 @@ import { createAgent } from "../actions/crew.ts";
6262 import { getAgentByName } from "../core/agents.ts";
6363 import { createSession, destroySession } from "../core/sessions.ts";
6464 import { createToken, listTokens } from "../core/tokens.ts";
65 import { enrolRunner, listRunners } from "../checks/runner_jobs.ts";
6566 import { recordUsage } from "../core/usage.ts";
6667 import { PREVIEW_SEEDED, getUserSetting, setUserSetting } from "../core/settings.ts";
6768 import { adminOf, linkEveryday } from "../core/everyday.ts";
@@ -99,6 +100,7 @@ import {
99100 PREVIEW_NEWCOMER,
100101 PREVIEW_NEWCOMER_ORG,
101102 PREVIEW_REPO,
103 PREVIEW_RUNNER,
102104 PREVIEW_SETTINGS_PAGES,
103105 PREVIEW_TEMPLATE,
104106 PREVIEW_TEMPLATE_PAGE,
@@ -553,7 +555,8 @@ function seedGrace(app: App): void {
553555 /**
554556 * Something on each settings page the owner looks at (#9781), once: a token
555557 * whose value is plainly fake (the page shows its name, never its secret),
556 * an agent for the crew, and a subscription if none was seeded. Then each
558 * an agent for the crew, a subscription if none was seeded, and a hand-made runner that has never
559 * asked for work (its token is dropped, so it never can) for Settings → Runners (#15252). Then each
557560 * page is asked for as the admin, and any answer but 200 refuses the seed.
558561 */
559562 async function seedSettingsPages(app: App, admin: User): Promise<Result<void, string>> {
@@ -578,6 +581,7 @@ async function seedSettingsPages(app: App, admin: User): Promise<Result<void, st
578581 });
579582 if (!added.ok) return err(`the sample account: ${added.error}`);
580583 }
584 if (!listRunners(app.db).some((r) => r.name === PREVIEW_RUNNER)) enrolRunner(app.db, PREVIEW_RUNNER, admin.id);
581585 const http = forgeHttp(app);
582586 const session = createSession(app.db, admin.id);
583587 try {
src/tui/forge.ts +10
@@ -84,6 +84,7 @@ import { passkeysScreen } from "./screens/passkeys.ts";
8484 import { confirmsScreen } from "./screens/confirms.ts";
8585 import { receiptsScreen } from "./screens/receipts.ts";
8686 import { mayTrust, trustedScreen } from "./screens/trusted.ts";
87 import { mayRunners, runnersScreen } from "./screens/runners.ts";
8788 import { proposalTokensPrompt } from "./screens/proposal_tokens.ts";
8889 import { signInsScreen } from "./screens/signins.ts";
8990 import { oauthGrantsScreen } from "./screens/oauthgrants.ts";
@@ -472,6 +473,15 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
472473 hint: "who folds in without review; a trusts, x removes, s stops all, v reverts",
473474 run: () => ctx.push(trustedScreen(session, ctx)),
474475 });
476 // The machines that take the forge's checks, as Settings → Runners lists them (#15252): an
477 // admin's.
478 if (session.signedIn && mayRunners(session))
479 commands.push({
480 id: "runners",
481 title: "Runners",
482 hint: "the machines that take this forge's checks; x removes a hand-made one",
483 run: () => ctx.push(runnersScreen(session, ctx)),
484 });
475485 // The forge's agent keeps many conversations, as /talk lists them (#8814).
476486 if (session.signedIn && session.user?.kind !== "agent")
477487 commands.push({
src/tui/screens/runners.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * Runners in the terminal (#15252), a forge admin's: the list Settings → Runners has — each
3 * runner's state, when it last asked for work and the jobs it holds now — and `x` removes the
4 * hand-made one under the cursor through `actions/runners.ts` `removeHandMade`, the page's own
5 * gate and event. A `local-N` runner is the forge's own and is refused. Anyone else is not
6 * offered it.
7 */
8
9 import { isLocal, list, removeHandMade, runnerState } from "../../actions/runners.ts";
10 import { heldByRunner, workByRunner } from "../../checks/runner_jobs.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, confirmScreen, drawList, type ListRow } from "./common.ts";
18
19 /** Whether the palette offers the screen: a signed-in admin who is a person. */
20 export const mayRunners = (f: Session): boolean => f.user !== undefined && f.user.isAdmin && f.user.kind === "user";
21
22 const STATE_WORDS = { connected: "connected", quiet: "quiet", never: "never asked" } as const;
23
24 export function runnersScreen(f: Session, ctx: Ctx): Screen {
25 const state = new ListState();
26 const entries = () => {
27 const seen = list(f.app, f.user);
28 return seen.ok ? seen.value : [];
29 };
30
31 const rows = (): ListRow[] => {
32 const now = Date.now();
33 const held = heldByRunner(f.db);
34 const work = workByRunner(f.db);
35 return entries().map((r) => {
36 const n = held.get(r.id) ?? 0;
37 const w = work.get(r.id) ?? { jobs: 1, ran: 0 };
38 const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`;
39 return {
40 title: `${r.name} ${STATE_WORDS[runnerState(r.seenAt, now)]}${isLocal(r) ? " (the forge's own)" : ""}`,
41 meta: `${asked} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run`,
42 };
43 });
44 };
45
46 const screen: Screen = {
47 title: "Runners",
48 keys: [binding(["j", "k"], "move cursor"), binding(["x"], "remove")],
49 render(area, s) {
50 const c = ctx.theme.c;
51 const [head, body] = split(area, "v", [len(1), fill(1)]);
52 const text = !mayRunners(f)
53 ? "Only a forge admin sees the runners."
54 : entries().length === 0
55 ? "No runner is enrolled; checks run on the forge's own machine."
56 : "The machines that take this forge's checks; x removes a hand-made one.";
57 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
58 drawList(s, body!, c, state, rows());
59 },
60 key(e) {
61 if (!mayRunners(f) || e.ctrl || e.alt) return false;
62 const all = entries();
63 if (state.key(e, all.length)) return true;
64 const at = all[state.index];
65 if (at === undefined || e.key !== "x") return false;
66 if (isLocal(at)) {
67 ctx.toast(`${at.name} is the forge's own; it is started again at each boot.`, "danger");
68 return true;
69 }
70 ctx.push(
71 confirmScreen(ctx, screen, {
72 title: "Remove runner",
73 body: [`${at.name}'s token stops working at once, and any job it holds is queued again.`],
74 actions: [{ label: "Keep", variant: "ghost" }, { label: "Remove", variant: "default" }],
75 onChoose: (i) => {
76 if (i !== 1) return;
77 const gone = removeHandMade(f.app, f.user, at.id);
78 ctx.toast(gone.ok ? `Runner ${at.name} is removed: its token no longer works.` : "That runner is not enrolled.", gone.ok ? "success" : "danger");
79 ctx.invalidate();
80 },
81 }),
82 );
83 return true;
84 },
85 };
86 return screen;
87 }
src/web/pages/origins.ts +2
@@ -116,6 +116,7 @@ export type AccountSection =
116116 | "crew"
117117 | "accounts"
118118 | "trusted"
119 | "runners"
119120 | "people"
120121 | "subscriptions"
121122 | "backups"
@@ -183,6 +184,7 @@ const SECTION_ROWS: readonly (readonly [
183184 ["This forge", "Limits", "/admin/limits", "activity", (c) => c === "limits", true],
184185 ["This forge", "Economics", "/settings/economics", "activity", (c) => c === "economics", true],
185186 ["This forge", "Billing", "/settings/billing", "activity", (c) => c === "billing", true],
187 ["This forge", "Runners", "/settings/runners", "activity", (c) => c === "runners", true],
186188 ["This forge", "Flows", "/admin/flows", "activity", (c) => c === "adminflows", true],
187189 ["This forge", "Flags", "/settings/flags", "activity", (c) => c === "flags", true],
188190 ["This forge", "Templates", "/settings/app-templates", "rocket", (c) => c === "templates", true],
src/web/pages/runners.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * Settings → Runners (#15252), for a forge admin: the machines that take a check's steps off the
3 * forge (`checks/runner_jobs.ts`), each with its state, when it last asked for work and the jobs it
4 * holds now. The rows are the API's own (`actions/runners.ts` `list`, which
5 * `GET /api/v1/admin/runners` answers with), and a hand-made one is removed by the same `remove`
6 * `DELETE /api/v1/admin/runners/:id` calls. A `local-N` runner is the forge's own: it is started
7 * again at each boot, so it has no button. Anyone signed in but an admin gets the plain 404: both
8 * routes are marked `open` in `http/marks/settings.json`, as `/admin/flows` is, so this page's own
9 * check answers rather than the admin gate's 403.
10 */
11 import { isLocal, list, removeHandMade, runnerState } from "../../actions/runners.ts";
12 import { heldByRunner, workByRunner, type Enrolled, type RunnerWork } from "../../checks/runner_jobs.ts";
13 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
14 import type { Ctx } from "../../http/context.ts";
15 import { sshOn } from "../../settings/ssh.ts";
16 import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts";
17 import { readForm } from "../form.ts";
18 import { html } from "../html.ts";
19 import { flashTo, page } from "../layout.ts";
20 import { badge, btn, icon, row, time } from "../ui.ts";
21 import { accountSections } from "./origins.ts";
22
23 const HERE = "/settings/runners";
24
25 function admin(ctx: Ctx): Response | undefined {
outdated

Box 1: the issue wants a non-admin to get the plain 404 other admin pages give. The "admin" mark in marks/settings.json answers first with the gate's 403, so this notFoundPage is never reached for a signed-in non-admin, and the test only compares against /settings/trusted. Make the answer a 404 (or mark it so the page's own check runs) and assert 404 in test/settings-runners.test.ts.

26 if (!ctx.auth.user) return signInFirst(ctx);
27 return ctx.auth.user.isAdmin && ctx.auth.user.kind === "user" ? undefined : notFoundPage(ctx);
28 }
29
30 function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number) {
31 const state = runnerState(r.seenAt, now);
32 return row({
33 lead: icon("activity"),
34 state: state === "connected" ? "open" : "draft",
35 title: html`${r.name} <span class="muted small mono">${r.id}</span>
36 ${state === "connected"
37 ? badge("Connected", { variant: "secondary", icon: "check" })
38 : state === "quiet"
39 ? badge("Quiet", { variant: "outline", icon: "clock" })
40 : badge("Never asked", { variant: "outline", icon: "ban" })}`,
41 meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`}
outdated

Box 1 asks for capacity and the title says jobs run; the row shows neither (only jobs held now). If the runner cannot report capacity, say so on the issue and get the box reworded, rather than leave it silently unmet.

42 · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`,
43 trail: isLocal(r)
44 ? html`<span class="muted small">The forge's own: started again at each boot, so not removed here.</span>`
45 : html`<form class="row-fields" method="post" action="${HERE}/${r.id}/remove">
46 ${btn("Remove", { size: "sm", variant: "outline", label: `Remove runner ${r.name}` })}
47 </form>`,
48 });
49 }
50
51 // GET /settings/runners
52 export function runnersPage(ctx: Ctx): Response {
53 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
54 const denied = admin(ctx);
55 if (denied) return denied;
56 const seen = list(ctx.app, ctx.auth.user);
57 if (!seen.ok) return notFoundPage(ctx);
58 const rendering = performance.now();
59 const now = Date.now();
60 const held = heldByRunner(ctx.app.db);
61 const work = workByRunner(ctx.app.db);
outdated

Design principle 1: pageHead already says what the page is for in one sentence, then this paragraph explains it again, with a second <h2>Runners</h2> above it. Drop the h2 and cut the paragraph to the one fact not already said (how to enrol); the removal behaviour is already in the confirm toast and the how-to.

62 const body = html`<section class="settings-block">
63 <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>.</p>
64 ${seen.value.length === 0
65 ? html`<p class="muted small">No runner is enrolled.</p>`
66 : html`<ul class="list setting-list" id="runner-list">
67 ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now))}
68 </ul>`}
69 </section>`;
70 notePhase(ctx.request, "render", performance.now() - rendering);
71 return page({
72 ctx,
73 title: "Runners",
74 body: html`${pageHead("Runners", { sub: "The machines that take this forge's checks, and whether each is asking for work." })}
75 ${settingsLayout(accountSections("runners", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
76 });
77 }
78
79 // POST /settings/runners/:id/remove
80 export async function runnerRemove(ctx: Ctx): Promise<Response> {
81 const denied = admin(ctx);
82 if (denied) return denied;
83 const form = await readForm(ctx, "admin");
84 if (form instanceof Response) return form;
85 const gone = removeHandMade(ctx.app, ctx.auth.user, ctx.params.id ?? "");
86 return flashTo(
87 ctx,
88 HERE,
89 gone.ok
90 ? { message: `Runner ${gone.value.name} is removed: its token no longer works.` }
91 : gone.error === "local"
92 ? { tone: "danger", message: "That runner is the forge's own; it is started again at each boot." }
93 : { tone: "danger", message: "That runner is not enrolled." },
94 );
95 }
test/palette-roster.test.ts +1
@@ -106,6 +106,7 @@ test("a site-admin person is offered the whole roster", () => {
106106 ["confirms", "Confirms", "what the forge's agent asked to do; y does it once"],
107107 ["receipts", "Receipts", "what you confirmed in /talk; u undoes it once"],
108108 ["trusted", "Trusted sources", "who folds in without review; a trusts, x removes, s stops all, v reverts"],
109 ["runners", "Runners", "the machines that take this forge's checks; x removes a hand-made one"],
109110 ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"],
110111 ["build-app", "Build an app", "say what to build; versions, diff, restore and publish. n starts one"],
111112 ["ssh-keys", "Computer keys", "list, add and remove the keys that sign in as you"],
test/preview-looks.test.ts +6 −1
@@ -93,7 +93,7 @@ describe("the seeded first issue", () => {
9393 });
9494
9595 describe("the owner's settings pages (#9781)", () => {
96 const pages = ["/settings/tokens", "/settings/crew", "/settings/subscriptions", "/settings/usage"];
96 const pages = ["/settings/tokens", "/settings/crew", "/settings/subscriptions", "/settings/usage", "/settings/runners"];
9797 // One seeded preview for the tests that read a seeded one: the first seed is most of a second
9898 // (#15191), the fixture's cost and not each test's. A test that removes rows from it seeds
9999 // them back before it ends; the refusal test needs an unseeded forge and makes its own.
@@ -128,6 +128,11 @@ describe("the owner's settings pages (#9781)", () => {
128128 expect(await get("/settings/crew")).toContain("preview-agent");
129129 expect(await get("/settings/subscriptions")).toContain("preview sample");
130130 await get("/settings/usage");
131 // A hand-made runner, so the look shows its Remove beside the state badge (#15252).
132 const runners = await get("/settings/runners");
133 expect(runners).toContain("preview-mac");
134 expect(runners).toContain("Never asked");
135 expect(runners).toMatch(/action="\/settings\/runners\/[^"]+\/remove"/);
131136 });
132137
133138 test("a named page that is not 200 refuses the seed, naming the path, and a retry adds no second token", async () => {
test/settings-runners.test.ts added +148
@@ -0,0 +1,148 @@
1 // Settings → Runners (#15252): an admin sees the API's runners and removes a hand-made one.
2 import { afterAll, beforeAll, describe, 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 { list } from "../src/actions/runners.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { claimJob, enrolRunner, noteRunnerJobs, offerJob, settleJob, type RunnerJob } from "../src/checks/runner_jobs.ts";
9 import { createSession } from "../src/core/sessions.ts";
10 import { createUser, type User } from "../src/core/users.ts";
11 import { serve } from "../src/http/server.ts";
12 import { isLocal, runnerState } from "../src/actions/runners.ts";
13 import { seedAdmin } from "./helpers/admin.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 let dataDir = "";
19 let app: App;
20 let alice: User;
21 let bob: User;
22 let servers: Awaited<ReturnType<typeof serve>>;
23
24 beforeAll(async () => {
25 dataDir = await mkdtemp(join(tmpdir(), "forge-runners-page-"));
26 app = createApp({ dataDir, port: 0, host: "forge.test" });
27 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
28 if (!a.ok) throw new Error(a.error);
29 alice = a.value;
30 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "correct-horse-battery" });
31 if (!b.ok) throw new Error(b.error);
32 bob = b.value;
33 servers = await serve(app);
34 });
35
36 afterAll(async () => {
37 servers.stop();
38 app.close();
39 await rm(dataDir, { recursive: true, force: true });
40 });
41
42 const cookie = (who: User) => `forge_session=${createSession(app.db, who.id).token}`;
43 const get = (who: User) => fetch(`${servers.url}/settings/runners`, { headers: { cookie: cookie(who) } });
44 const post = (who: User, id: string, origin = servers.url) =>
45 fetch(`${servers.url}/settings/runners/${id}/remove`, {
46 method: "POST",
47 redirect: "manual",
48 headers: { cookie: cookie(who), origin, "content-type": "application/x-www-form-urlencoded" },
49 body: "",
50 });
51
52 describe("the runners page", () => {
53 test("names the forge's own runners and a runner's state", () => {
54 expect(isLocal({ name: "local-3" })).toBe(true);
55 expect(isLocal({ name: "local-mac" })).toBe(false);
56 expect(isLocal({ name: "mac" })).toBe(false);
57 expect(runnerState(0, 1e6)).toBe("never");
58 expect(runnerState(1e6 - 1_000, 1e6)).toBe("connected");
59 expect(runnerState(1, 1e9)).toBe("quiet");
60 });
61
62 test("lists the API's rows; a hand-made one has a remove button, a local one says why not", async () => {
63 const mac = enrolRunner(app.db, "mac<b>", alice.id).runner;
64 const local = enrolRunner(app.db, "local-1", alice.id).runner;
65 const res = await get(alice);
66 const page = await res.text();
67 expect(res.status).toBe(200);
68 const main = page.slice(page.indexOf("<main"), page.indexOf("</main>"));
69 // One source: every row the API lists is on the page.
70 const rows = list(app, alice);
71 if (!rows.ok) throw new Error("no list");
72 for (const r of rows.value) expect(main).toContain(r.id);
73 expect(main).toContain("mac&lt;b&gt;");
74 expect(main).not.toContain("mac<b>");
75 expect(main).toContain(`action="/settings/runners/${mac.id}/remove"`);
76 expect(main).not.toContain(`action="/settings/runners/${local.id}/remove"`);
77 expect(main).toContain("started again at each boot");
78 expect(main).toContain("Never asked");
79 expect(main).toContain("runs 1 at once · holding 0 now · 0 jobs run");
80 expect(page).toContain('href="/settings/runners"');
81 });
82
83 test("a runner's capacity and the jobs it has run are on its row", async () => {
84 const r = enrolRunner(app.db, "busy", alice.id).runner;
85 noteRunnerJobs(app.db, r.id, 4);
86 const job: Omit<RunnerJob, "id"> = {
87 run: "run-1", repo: "alice/lib", commit: "a".repeat(40), base: "b".repeat(40), depth: 1,
88 steps: [{ name: "check", command: "bun test" }], env: {}, limits: { cpus: 1, memoryMiB: 512 },
89 timeoutS: 60, egress: [], egressMode: "enforce", cell: "preferred",
90 cache: { repo: "repo-1", tree: "c".repeat(40), base: "b".repeat(40) },
91 };
92 const green = { steps: [{ name: "check", ok: true, ms: 1 }], contained: true, note: "" };
93 for (const end of [{ done: green }, { returned: "gave it back" }, { done: green }] as const) {
94 const offered = offerJob(app.db, { runId: "run-1", repoId: "repo-1", dir: "/nowhere", job });
95 const claim = claimJob(app.db, { id: r.id, cells: true }, Date.now());
96 if (claim === undefined) throw new Error("no claim");
97 expect(settleJob(app.db, offered.id, claim.token, end)).toBe(true);
98 // A second word on a settled job counts nothing.
99 expect(settleJob(app.db, offered.id, claim.token, end)).toBe(false);
100 }
101 const main = await (await get(alice)).text();
102 const at = main.indexOf(r.id);
103 expect(main.slice(at, at + 1200)).toContain("runs 4 at once · holding 0 now · 2 jobs run");
104 });
105
106 test("a signed-in non-admin gets the plain 404, and cannot remove", async () => {
107 const r = enrolRunner(app.db, "keep", alice.id).runner;
108 const res = await get(bob);
109 const text = await res.text();
110 expect(res.status).toBe(404);
111 expect(text).not.toContain(r.id);
112 const anon = await fetch(`${servers.url}/settings/runners`, { redirect: "manual" });
113 expect(await anon.text()).not.toContain(r.id);
114 expect(anon.status).not.toBe(200);
115 const p = await post(bob, r.id);
116 await p.arrayBuffer();
117 expect(p.status).toBe(404);
118 const still = list(app, alice);
119 expect(still.ok && still.value.some((x) => x.id === r.id)).toBe(true);
120 });
121
122 test("a cross-origin post removes nothing", async () => {
123 const r = enrolRunner(app.db, "cross", alice.id).runner;
124 const p = await post(alice, r.id, "https://evil.example");
125 await p.arrayBuffer();
126 expect(p.status).toBeGreaterThanOrEqual(400);
127 const rows = list(app, alice);
128 expect(rows.ok && rows.value.some((x) => x.id === r.id)).toBe(true);
129 });
130
131 test("an admin removes a hand-made runner, receipted; a local one stays", async () => {
132 const r = enrolRunner(app.db, "gone", alice.id).runner;
133 const local = enrolRunner(app.db, "local-2", alice.id).runner;
134 const p = await post(alice, r.id);
135 await p.arrayBuffer();
136 expect(p.status).toBe(303);
137 const q = await post(alice, local.id);
138 await q.arrayBuffer();
139 const rows = list(app, alice);
140 if (!rows.ok) throw new Error("no list");
141 expect(rows.value.some((x) => x.id === r.id)).toBe(false);
142 expect(rows.value.some((x) => x.id === local.id)).toBe(true);
143 const removed = app.db
144 .query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM event WHERE kind = 'runner.removed' AND payload LIKE ?1")
145 .get(`%${r.id}%`);
146 expect(removed?.n).toBe(1);
147 });
148 });
test/tui-runners.test.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * Runners in the terminal (#15252): a forge admin who is a person is offered the screen, sees
3 * each runner's state, and `x` removes a hand-made one after a confirm through
4 * `actions/runners.ts`, leaving the page's event; a `local-N` one is refused. Anyone else is not
5 * offered it, and its keys do nothing when it is pushed anyway.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { enrolRunner, listRunners } from "../src/checks/runner_jobs.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { runnersScreen } from "../src/tui/screens/runners.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 quietLogs();
21
22 const ENTER = "\r";
23 const RIGHT = "\x1b[C";
24
25 let dir: string;
26 let app: App;
27 let ada: User;
28 let bob: User;
29
30 const identity = (user: User) => ({ sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user });
31 const events = (kind: string): number =>
32 app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM event WHERE kind = ?1").get(kind)!.n;
33 const names = () => listRunners(app.db).map((r) => r.name).sort();
34
35 async function drive(user: User, keys: readonly string[] = []) {
36 const terminal = headlessTerminal(120, 30);
37 const { app: tui, session } = createForgeApp(app, identity(user), { terminal, exitHooks: false });
38 tui.start();
39 const offered = tui.commands.some((c) => c.id === "runners");
40 tui.ctx.push(runnersScreen(session, tui.ctx));
41 await settleApp(tui);
42 for (const key of keys) {
43 terminal.feed(key);
44 await settleApp(tui);
45 }
46 const text = tui.screen.toText();
47 tui.stop?.();
48 return { offered, text };
49 }
50
51 beforeAll(async () => {
52 dir = await mkdtemp(join(tmpdir(), "forge-tui-runners-"));
53 app = createApp({ dataDir: dir, port: 0 });
54 const mk = async (username: string, first = false) => {
55 const r = await createUser(app.db, {
56 origin: "seed",
57 trusted: true,
58 username,
59 email: `${username}@forge.local`,
60 password: "a-good-passphrase",
61 adminIfFirst: first,
62 });
63 if (!r.ok) throw new Error(r.error);
64 return r.value;
65 };
66 ada = await mk("ada", true);
67 bob = await mk("bob");
68 app.db.query("DELETE FROM check_runner").run();
69 enrolRunner(app.db, "local-1", ada.id);
70 enrolRunner(app.db, "mac", ada.id);
71 }, 30_000);
72
73 afterAll(async () => {
74 app.close();
75 await rm(dir, { recursive: true, force: true });
76 });
77
78 describe("runners in the terminal", () => {
79 test("a non-admin is not offered the screen, and x removes nothing", async () => {
80 const { offered, text } = await drive(bob, ["j", "x", RIGHT, ENTER]);
81 expect(offered).toBe(false);
82 expect(text).toContain("Only a forge admin sees the runners.");
83 expect(text).not.toContain("mac");
84 expect(names()).toEqual(["local-1", "mac"]);
85 expect(events("runner.removed")).toBe(0);
86 });
87
88 test("an admin sees each runner's state; a local one is refused", async () => {
89 const { offered, text } = await drive(ada, ["x"]);
90 expect(offered).toBe(true);
91 expect(text).toContain("local-1 never asked (the forge's own)");
92 expect(text).toContain("mac never asked");
93 expect(text).toContain("has not asked for work · runs 1 at once · holding 0 · 0 jobs run");
94 expect(names()).toEqual(["local-1", "mac"]);
95 expect(events("runner.removed")).toBe(0);
96 });
97
98 test("x removes a hand-made runner after a confirm", async () => {
99 await drive(ada, ["j", "x", ENTER]);
100 expect(names()).toEqual(["local-1", "mac"]);
101 const { text } = await drive(ada, ["j", "x", RIGHT, ENTER]);
102 expect(names()).toEqual(["local-1"]);
103 expect(text).not.toContain("mac never asked");
104 expect(events("runner.removed")).toBe(1);
105 });
106 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs