Public: anyone can read this; the crew can change it.
The runners page is live: connected, busy, the run it holds, its log and last seen, updated as they change #18497
Merged 2h 54m ago, live in production
torque/forge:torque/18458-the-runners-page-is-live-connected-busy → main 0 commits fork
17 files
changed +457
−27
- docs/design/audit.md
- docs/features/settings-runners.md
- src/checks/runner_jobs.ts
- src/checks/runner_step.ts
- src/core/empty_words.ts
- src/http/api/runners.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/http/sse.ts
- src/machines/live_runners.ts
- src/machines/runner_signal.ts
- src/tui/screens/runners.ts
- src/web/client.ts
- src/web/pages/runners.ts
- src/web/runner_tail.ts
- test/runners-live.test.ts
docs/design/audit.md +1
| @@ -152,6 +152,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 152 | 152 | - `/settings/telemetry` — `pages/telemetry.ts` · which agents may read telemetry · `/settings/crew` (agent grants) · none seen. |
| 153 | 153 | - `/settings/trusted` — `pages/trusted.ts` · who may fold in without review, until when, and the kill switch · `/review`, `/settings/crew` · none seen. |
| 154 | 154 | - `/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. |
| 155 | - `/settings/runners/live` — `pages/runners.ts` · the runner rows' moving part (connected, busy or idle, the run held and its log), refetched when a `runner.*` event arrives; an admin's only · `/settings/backups/live` · none seen. | |
| 155 | 156 | - `/settings/runners/lending/live` — `pages/runners.ts` · the Lending block's moving part (the room to lend and each offer), refetched when a `lending.*` event arrives; an admin's only · `/settings/backups/live` · none seen. |
| 156 | 157 | - `/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). |
| 157 | 158 | - `/settings/resilience` — `pages/domains.ts` · failure domains and their last drill · `/resilience` · none seen. |
docs/features/settings-runners.md +15 −1
| @@ -23,8 +23,22 @@ instead of Remove: its next request is refused and its row stays with its core-m | ||
| 23 | 23 | Remove clears it). A paused one has **Resume**. Any other runner that has run something shows its |
| 24 | 24 | core-minutes, and while a runner is lent to the forge the page opens with the lent-in numbers. |
| 25 | 25 | |
| 26 | **Live (#18458).** A row also says **Busy** or **Idle** (it holds a claimed job, or its last | |
| 27 | heartbeat said `busy`), when it was **last seen**, and the run it holds, linked | |
| 28 | (`/<owner>/<repo>/runs/<id>`) when you may read that run. A row that holds a run opens: the run's | |
| 29 | last 30 log lines are drawn on the server, and each new line arrives on the page's one `/events` | |
| 30 | connection and is added as text (`src/web/runner_tail.ts`); the box is a fixed window, so nothing | |
| 31 | moves. The rows are a live region (`GET /settings/runners/live`, the fragment the page swaps in | |
| 32 | place, scroll and open rows kept): a runner's first heartbeat after silence or a change of its | |
| 33 | state (`runner.seen`), a claim (`runner.claimed`) and a job's end or lapse (`runner.released`) | |
| 34 | prompt it, and one more look is taken when the first connected runner would fall quiet. A runner | |
| 35 | that only keeps asking says nothing. The facts are the agent protocol's own | |
| 36 | (`src/machines/protocol.ts`: the heartbeat's state, the claim's job), read in | |
| 37 | `src/machines/live_runners.ts`; a person who is not the forge's admin gets the plain 404 and no | |
| 38 | word of any machine. With no runner the page says what a runner is and how to add one. | |
| 39 | ||
| 26 | 40 | **Both doors.** `/settings/runners` on the web (under This forge in the settings menu), and |
| 27 | 41 | **Runners** in the terminal's command palette (`src/tui/screens/runners.ts`, a forge admin's): |
| 28 | `j`/`k` move, `x` removes the hand-made runner under the cursor after a confirm. Both go through | |
| 42 | each row says busy or idle and the run it holds; `j`/`k` move, `x` removes the hand-made runner under the cursor after a confirm. Both go through | |
| 29 | 43 | `removeHandMade` in `src/actions/runners.ts`. Anyone else gets the plain 404 on the web and is |
| 30 | 44 | not offered the screen. |
src/checks/runner_jobs.ts +4 −1
| @@ -165,6 +165,8 @@ export interface Enrolled { | ||
| 165 | 165 | readonly state: string; |
| 166 | 166 | /** Whether a site admin marked it trusted for secrets (`environment.ts`). */ |
| 167 | 167 | readonly trusted: boolean; |
| 168 | /** Set by `runnerByToken` alone: this request is the first within `SEEN_FRESH_MS` (#18458). */ | |
| 169 | readonly wasQuiet?: true; | |
| 168 | 170 | } |
| 169 | 171 | |
| 170 | 172 | type RunnerRow = { |
| @@ -417,7 +419,8 @@ export function runnerByToken( | ||
| 417 | 419 | row.id, |
| 418 | 420 | now, |
| 419 | 421 | ); |
| 420 | return toEnrolled({ ...row, seen_at: now }, now); | |
| 422 | // The page of runners is told when one comes back from silence, not at every ask. | |
| 423 | return { ...toEnrolled({ ...row, seen_at: now }, now), ...(now - row.seen_at > SEEN_FRESH_MS || row.seen_at > now ? { wasQuiet: true as const } : {}) }; | |
| 421 | 424 | } |
| 422 | 425 | |
| 423 | 426 | /** Whether any runner asked for work within `SEEN_FRESH_MS`. */ |
src/checks/runner_step.ts +4 −1
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | |
| 15 | 15 | import type { App } from "../app.ts"; |
| 16 | 16 | import { killedStep } from "../apps/process.ts"; |
| 17 | import { tellRunners } from "../machines/runner_signal.ts"; | |
| 17 | 18 | import { background } from "../perf/jobs.ts"; |
| 18 | 19 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 19 | 20 | import { parseBunTestFailure } from "./bun-test.ts"; |
| @@ -228,7 +229,9 @@ export async function runRunnerStep( | ||
| 228 | 229 | }; |
| 229 | 230 | } |
| 230 | 231 | // Every lapsed lease on the desk, this job's among them, goes back to queued. |
| 231 | for (const lapsed of lapseJobs(app.db, now())) desk.held.delete(lapsed); | |
| 232 | const lapsedJobs = lapseJobs(app.db, now()); | |
| 233 | for (const lapsed of lapsedJobs) desk.held.delete(lapsed); | |
| 234 | if (lapsedJobs.length > 0) tellRunners(app, "released"); | |
| 232 | 235 | const view = viewJob(app.db, job.id); |
| 233 | 236 | if (view === undefined) |
| 234 | 237 | return fail("the job left the desk"); |
src/core/empty_words.ts +1 −1
| @@ -75,7 +75,7 @@ const TABLE = { | ||
| 75 | 75 | heap: { sentence: "No heap census yet." }, |
| 76 | 76 | disks: { sentence: "No disks or network were read." }, |
| 77 | 77 | egress: { sentence: "No app holds an egress connection open." }, |
| 78 | runners: { sentence: "No runner is enrolled." }, | |
| 78 | runners: { sentence: "No runner is enrolled.", reason: "A runner is a machine that takes this forge's checks: each shows here, connected or not, with the run it holds and its log. Register one below, or enrol one with POST /api/v1/admin/runners, and give it the token it is shown once." }, | |
| 79 | 79 | billingCodes: { sentence: "No code yet." }, |
| 80 | 80 | trusted: { sentence: "No one is trusted, so every pull waits for review." }, |
| 81 | 81 | linkedVisitors: { sentence: "No forge has been linked to a visitor yet.", reason: "Forges started from a plan or a code are; a Stripe checkout is not yet." }, |
src/http/api/runners.ts +7
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | 12 | import { noteUse } from "../../machines/agent_use.ts"; |
| 13 | import { tellRunners } from "../../machines/runner_signal.ts"; | |
| 13 | 14 | import { dropHands, takeHand } from "../../checks/runner_hands.ts"; |
| 14 | 15 | import { HAND_BYTES_MAX } from "../../checks/hand_files.ts"; |
| 15 | 16 | import { listLending, offerLending, resumeLending, stopLending } from "../../actions/lending.ts"; |
| @@ -263,6 +264,7 @@ export function runnerRoutes(router: Router<Handler>, record = true): void { | ||
| 263 | 264 | if (state !== "idle" && state !== "busy" && state !== "paused") |
| 264 | 265 | return apiError("invalid_heartbeat", 422, "state is idle, busy or paused"); |
| 265 | 266 | noteHeartbeat(ctx.app.db, runner.id, { state }); |
| 267 | if (runner.wasQuiet === true || runner.state !== state) tellRunners(ctx.app, "seen", runner.id); | |
| 266 | 268 | wakeClaimers(ctx.app); |
| 267 | 269 | return new Response(null, { status: 204 }); |
| 268 | 270 | }, false)); |
| @@ -274,6 +276,7 @@ export function runnerRoutes(router: Router<Handler>, record = true): void { | ||
| 274 | 276 | const input = await boundedBody(ctx.request, STRANGER_MAX); |
| 275 | 277 | if (input === "too_large") |
| 276 | 278 | return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`); |
| 279 | if (runner.wasQuiet === true) tellRunners(ctx.app, "seen", runner.id); | |
| 277 | 280 | noteRunnerJobs(ctx.app.db, runner.id, input.jobs); |
| 278 | 281 | noteRunnerMachine(ctx.app.db, runner.id, input.machine); |
| 279 | 282 | const wait = |
| @@ -293,6 +296,7 @@ export function runnerRoutes(router: Router<Handler>, record = true): void { | ||
| 293 | 296 | Date.now(), |
| 294 | 297 | ); |
| 295 | 298 | if (claim !== undefined) { |
| 299 | tellRunners(ctx.app, "claimed", runner.id); | |
| 296 | 300 | if (claim.canary === true) hearCanary(ctx.app, claim.job.id); |
| 297 | 301 | // The environment's entries are opened here, for this run only, and named in its log. |
| 298 | 302 | const given = withEnvironment(ctx.app.db, ctx.app.config.dataDir, claim.job, runner.id); |
| @@ -362,12 +366,14 @@ export function runnerRoutes(router: Router<Handler>, record = true): void { | ||
| 362 | 366 | if (paused !== undefined && keepPause(ctx.app.db, mine.job, paused)) mine.ear.lines("", [pauseWords(paused)]); |
| 363 | 367 | if (typeof input.interrupted === "string") { |
| 364 | 368 | if (!interruptJob(ctx.app.db, mine.job.id, token, input.interrupted, Array.isArray(input.kept) ? input.kept : [])) return notFound(); |
| 369 | tellRunners(ctx.app, "released"); | |
| 365 | 370 | wakeClaimers(ctx.app); |
| 366 | 371 | return json({ ended: true }); |
| 367 | 372 | } |
| 368 | 373 | if (typeof input.abandon === "string") { |
| 369 | 374 | if (!settleJob(ctx.app.db, mine.job.id, token, { returned: input.abandon })) |
| 370 | 375 | return notFound(); |
| 376 | tellRunners(ctx.app, "released"); | |
| 371 | 377 | mine.ear.wake(); |
| 372 | 378 | return json({ ended: true }); |
| 373 | 379 | } |
| @@ -381,6 +387,7 @@ export function runnerRoutes(router: Router<Handler>, record = true): void { | ||
| 381 | 387 | ); |
| 382 | 388 | if (!settleJob(ctx.app.db, mine.job.id, token, { done: result })) |
| 383 | 389 | return notFound(); |
| 390 | tellRunners(ctx.app, "released"); | |
| 384 | 391 | mine.ear.wake(); |
| 385 | 392 | return json({ ended: true }); |
| 386 | 393 | } |
src/http/lazy_lists.ts +1
| @@ -27,6 +27,7 @@ export const SETTINGS_ROUTES = [ | ||
| 27 | 27 | ["POST", "/settings/trusted/revert"], |
| 28 | 28 | ["POST", "/settings/trusted/:id/remove"], |
| 29 | 29 | ["GET", "/settings/runners"], |
| 30 | ["GET", "/settings/runners/live"], | |
| 30 | 31 | ["POST", "/settings/runners/:id/remove"], |
| 31 | 32 | ["POST", "/settings/runners/:id/revoke"], |
| 32 | 33 | ["POST", "/settings/runners/:id/resume"], |
src/http/marks/settings.json +1
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | "/settings/trusted/revert": "admin", |
| 8 | 8 | "/settings/trusted/:id/remove": "admin", |
| 9 | 9 | "/settings/runners": "open", |
| 10 | "/settings/runners/live": "open", | |
| 10 | 11 | "/settings/runners/:id/trust": "admin", |
| 11 | 12 | "/settings/runners/:id/untrust": "admin", |
| 12 | 13 | "/settings/runners/:id/remove": "open", |
src/http/settings_routes.ts +2 −1
| @@ -26,7 +26,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts"; | ||
| 26 | 26 | import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; |
| 27 | 27 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 28 | 28 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 29 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTrust, runnersPage } from "../web/pages/runners.ts"; | |
| 29 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTrust, runnersLive, runnersPage } from "../web/pages/runners.ts"; | |
| 30 | 30 | import { usagePage } from "../web/pages/usage.ts"; |
| 31 | 31 | import { spendPage } from "../web/pages/spend-tab.ts"; |
| 32 | 32 | import { securityControlsPage } from "../web/pages/security_controls.ts"; |
| @@ -175,6 +175,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 175 | 175 | router.add("POST", "/settings/trusted/revert", trustedRevert); |
| 176 | 176 | router.add("POST", "/settings/trusted/:id/remove", trustedRemove); |
| 177 | 177 | router.add("GET", "/settings/runners", runnersPage); |
| 178 | router.add("GET", "/settings/runners/live", runnersLive); | |
| 178 | 179 | router.add("POST", "/settings/runners/:id/remove", runnerRemove); |
| 179 | 180 | router.add("POST", "/settings/runners/:id/revoke", runnerRevoke); |
| 180 | 181 | router.add("POST", "/settings/runners/:id/resume", runnerResume); |
src/http/sse.ts +1 −1
| @@ -292,7 +292,7 @@ export function viewerStream( | ||
| 292 | 292 | // A repo-less event reaches a page only when one listens for it; the audience filter below |
| 293 | 293 | // keeps the admins' (`infra.*` and `pinned.*`: what runs on the owner's cloud, #16696) theirs, |
| 294 | 294 | // and `game.cloud` its one box owner's. |
| 295 | if (event.repoId === null ? !(event.kind.startsWith("backup.") || event.kind.startsWith("infra.") || event.kind === "game.cloud" || event.kind.startsWith("pinned.") || event.kind === "cloud.place_pinned" || (viewer !== undefined && event.kind.startsWith("desk."))) : !visible(event.repoId)) return; | |
| 295 | if (event.repoId === null ? !(event.kind.startsWith("backup.") || event.kind.startsWith("infra.") || event.kind === "game.cloud" || event.kind.startsWith("pinned.") || event.kind === "cloud.place_pinned" || (viewer !== undefined && event.kind.startsWith("runner.")) || (viewer !== undefined && event.kind.startsWith("desk."))) : !visible(event.repoId)) return; | |
| 296 | 296 | if (!meant(event)) return; |
| 297 | 297 | send(event); |
| 298 | 298 | }, "ordered"); |
src/machines/live_runners.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * What the runners page draws for each machine (#18458): connected or not, busy or idle, the run it | |
| 3 | * holds and the tail of that run's log, plain data out. The facts are the agent protocol's own | |
| 4 | * (`protocol.ts`): a heartbeat's `state` and `seenAt` (`runners.state`, `runners.seen_at`) and a | |
| 5 | * claim's job (`check_job` rows in state `claimed`), read where the handlers wrote them. | |
| 6 | * | |
| 7 | * Who may see what is decided here and nowhere else: the machines are a forge admin's | |
| 8 | * (`actions/runners.ts` `list`); a held run is named, linked and its log read only to a viewer | |
| 9 | * who may read that run (`getRepoRun`, `mayReadLogOfRun`), so a run of a private repository is | |
| 10 | * "a run" and no more to anyone else. | |
| 11 | */ | |
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import type { App } from "../app.ts"; | |
| 14 | import { mayReadLogOfRun, getRepoRun } from "../actions/runs.ts"; | |
| 15 | import { list, runnerState } from "../actions/runners.ts"; | |
| 16 | import { getRepoById, type Repo } from "../core/repos.ts"; | |
| 17 | import type { User } from "../core/users.ts"; | |
| 18 | import { readRunLogTail } from "../runs/log.ts"; | |
| 19 | ||
| 20 | /** How many lines of a run's log the first paint carries. */ | |
| 21 | export const TAIL_LINES = 30; | |
| 22 | ||
| 23 | export interface HeldRun { | |
| 24 | readonly id: string; | |
| 25 | /** `owner/name`, or "" when the viewer may not read the run. */ | |
| 26 | readonly repo: string; | |
| 27 | /** The run's page; "" when the viewer may not read it. */ | |
| 28 | readonly href: string; | |
| 29 | /** The log's last lines; undefined when the viewer may not read this run's log. */ | |
| 30 | readonly lines?: readonly string[]; | |
| 31 | readonly truncated: boolean; | |
| 32 | } | |
| 33 | ||
| 34 | export interface RunnerLine { | |
| 35 | readonly id: string; | |
| 36 | readonly name: string; | |
| 37 | /** Asked within `SEEN_FRESH_MS` and not revoked. */ | |
| 38 | readonly connected: boolean; | |
| 39 | /** Holds a claimed job, or said `busy` in its heartbeat. */ | |
| 40 | readonly busy: boolean; | |
| 41 | /** The words of its standing: connected, quiet, never, paused or revoked. */ | |
| 42 | readonly word: "connected" | "quiet" | "never" | "paused" | "revoked"; | |
| 43 | /** When it last asked, in milliseconds; 0 for never. */ | |
| 44 | readonly seenAt: number; | |
| 45 | /** How many jobs it holds; `run` is the oldest of them. */ | |
| 46 | readonly holds: number; | |
| 47 | readonly run?: HeldRun; | |
| 48 | } | |
| 49 | ||
| 50 | interface Claimed { | |
| 51 | readonly run_id: string; | |
| 52 | readonly repo_id: string; | |
| 53 | readonly runner_id: string; | |
| 54 | } | |
| 55 | ||
| 56 | /** Every claimed job by runner, oldest claim first: one read for the whole page. */ | |
| 57 | function claimedByRunner(db: Database): Map<string, Claimed[]> { | |
| 58 | const out = new Map<string, Claimed[]>(); | |
| 59 | const rows = db | |
| 60 | .query<Claimed, []>("SELECT run_id, repo_id, runner_id FROM check_job WHERE state = 'claimed' AND runner_id IS NOT NULL ORDER BY claimed_at, id") | |
| 61 | .all(); | |
| 62 | for (const r of rows) out.set(r.runner_id, [...(out.get(r.runner_id) ?? []), r]); | |
| 63 | return out; | |
| 64 | } | |
| 65 | ||
| 66 | function heldRun(app: App, viewer: User | undefined, job: Claimed, repos: Map<string, Repo | undefined>): HeldRun { | |
| 67 | if (!repos.has(job.repo_id)) repos.set(job.repo_id, getRepoById(app.db, job.repo_id)); | |
| 68 | const repo = repos.get(job.repo_id); | |
| 69 | if (repo === undefined || !getRepoRun(app, viewer, repo, job.run_id).ok) return { id: "", repo: "", href: "", truncated: false }; | |
| 70 | const full = `${repo.ownerName}/${repo.name}`; | |
| 71 | const base = { id: job.run_id, repo: full, href: `/${full}/runs/${encodeURIComponent(job.run_id)}` }; | |
| 72 | if (!mayReadLogOfRun(app, viewer, repo, job.run_id)) return { ...base, truncated: false }; | |
| 73 | const tail = readRunLogTail(app.config.dataDir, job.run_id, TAIL_LINES); | |
| 74 | return { ...base, lines: tail.lines.slice(-TAIL_LINES), truncated: tail.truncated || tail.lines.length > TAIL_LINES }; | |
| 75 | } | |
| 76 | ||
| 77 | /** | |
| 78 | * Each enrolled runner as the page draws it, or `undefined` for a viewer who is not the forge's | |
| 79 | * admin: they are told nothing of anyone's machine. | |
| 80 | */ | |
| 81 | export function runnerLines(app: App, viewer: User | undefined, now: number): RunnerLine[] | undefined { | |
| 82 | const seen = list(app, viewer); | |
| 83 | if (!seen.ok) return undefined; | |
| 84 | const claimed = claimedByRunner(app.db); | |
| 85 | const repos = new Map<string, Repo | undefined>(); | |
| 86 | return seen.value.map((r) => { | |
| 87 | const jobs = claimed.get(r.id) ?? []; | |
| 88 | const standing = runnerState(r.seenAt, now); | |
| 89 | const word = r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : standing; | |
| 90 | const first = jobs[0]; | |
| 91 | return { | |
| 92 | id: r.id, | |
| 93 | name: r.name, | |
| 94 | connected: standing === "connected" && r.revokedAt === 0, | |
| 95 | busy: jobs.length > 0 || r.state === "busy", | |
| 96 | word, | |
| 97 | seenAt: r.seenAt, | |
| 98 | holds: jobs.length, | |
| 99 | ...(first === undefined ? {} : { run: heldRun(app, viewer, first, repos) }), | |
| 100 | }; | |
| 101 | }); | |
| 102 | } | |
| 103 | ||
| 104 | /** | |
| 105 | * When the page should look again with no event to prompt it: the instant the first connected | |
| 106 | * runner falls quiet (`SEEN_FRESH_MS` after it last asked), as an ISO time; "" when none will. | |
| 107 | */ | |
| 108 | export function nextQuiet(lines: readonly RunnerLine[], freshMs: number): string { | |
| 109 | const due = lines.filter((l) => l.connected).map((l) => l.seenAt + freshMs); | |
| 110 | return due.length === 0 ? "" : new Date(Math.min(...due)).toISOString(); | |
| 111 | } |
src/machines/runner_signal.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | /** | |
| 2 | * The one thing a runner's request says to an open runners page (#18458): something a row shows | |
| 3 | * changed. `seen` is a runner that came back (or changed its state), `claimed` one that took a | |
| 4 | * job, `released` one whose job ended or lapsed. Each is an admin's event (`runner.`, | |
| 5 | * `core/event_audience.ts`) that `/events` carries to the page's live region; a runner that merely | |
| 6 | * keeps asking says nothing, so a busy fleet adds no rows to the log. | |
| 7 | */ | |
| 8 | import type { App } from "../app.ts"; | |
| 9 | ||
| 10 | export type RunnerSignal = "seen" | "claimed" | "released"; | |
| 11 | ||
| 12 | export function tellRunners(app: App, signal: RunnerSignal, runnerId = ""): void { | |
| 13 | const payload = runnerId === "" ? {} : { id: runnerId }; | |
| 14 | if (signal === "seen") app.bus.append({ kind: "runner.seen", payload }); | |
| 15 | else if (signal === "claimed") app.bus.append({ kind: "runner.claimed", payload }); | |
| 16 | else app.bus.append({ kind: "runner.released", payload }); | |
| 17 | } |
src/tui/screens/runners.ts +7 −2
| @@ -15,6 +15,7 @@ import { cannotByRunner } from "../../games/lend_why.ts"; | ||
| 15 | 15 | import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts"; |
| 16 | 16 | import { lentLine, scopeLine } from "../../checks/lent_scope.ts"; |
| 17 | 17 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 18 | import { runnerLines } from "../../machines/live_runners.ts"; | |
| 18 | 19 | import { heldByRunner, lentIn, workByRunner, type Enrolled, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; |
| 19 | 20 | import type { Ctx, Screen } from "../app/app.ts"; |
| 20 | 21 | import { binding } from "../app/keys.ts"; |
| @@ -63,6 +64,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 63 | 64 | const cannot = cannotByRunner(f.db); |
| 64 | 65 | const work = workByRunner(f.db); |
| 65 | 66 | const proofs = proofByRunner(f.db); |
| 67 | const lines = new Map((runnerLines(f.app, f.user, now) ?? []).map((l) => [l.id, l])); | |
| 66 | 68 | return entries().map((e) => { |
| 67 | 69 | if (e.kind === "offer") { |
| 68 | 70 | const o = e.o; |
| @@ -76,10 +78,13 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 76 | 78 | const n = held.get(r.id) ?? 0; |
| 77 | 79 | const w = work.get(r.id) ?? { jobs: 1, ran: 0 }; |
| 78 | 80 | const machine = runnerMachineWords(r); |
| 79 | const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`; | |
| 81 | const asked = r.seenAt === 0 ? "has not asked for work" : `last seen ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`; | |
| 82 | const line = lines.get(r.id); | |
| 83 | const busyWord = line === undefined || r.revokedAt !== 0 ? "" : line.busy ? " · busy" : line.connected ? " · idle" : ""; | |
| 84 | const holds = line?.run === undefined ? "" : line.run.id === "" ? " · holds a run" : ` · holds run ${line.run.id.slice(0, 8)} of ${line.run.repo}`; | |
| 80 | 85 | return { |
| 81 | 86 | title: `${r.name} ${stateWords(r, now)}${r.trusted ? " trusted for secrets" : ""}${isLocal(r) ? " (the forge's own)" : ""}`, |
| 82 | meta: `${asked}${machine === "" ? "" : ` · ${machine}`}${outsideWords(r) === "" ? "" : ` · ${outsideWords(r)}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`, | |
| 87 | meta: `${asked}${busyWord}${holds}${machine === "" ? "" : ` · ${machine}`}${outsideWords(r) === "" ? "" : ` · ${outsideWords(r)}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`, | |
| 83 | 88 | // Under the row, where a narrow screen never gives it up as it does the meta's pieces. |
| 84 | 89 | ...(proofs.has(r.id) ? { note: proofWords(proofs.get(r.id)) } : {}), |
| 85 | 90 | }; |
src/web/client.ts +9 −4
| @@ -129,7 +129,7 @@ export const mirrorJs = /* js */ ` | ||
| 129 | 129 | * so a third live log never grows a third copy of it — |
| 130 | 130 | * interpolated inline, so \`who\` closes over whichever script uses it. |
| 131 | 131 | */ |
| 132 | const logLineJs = /* js */ ` | |
| 132 | export const logLineJs = /* js */ ` | |
| 133 | 133 | var FORGE = /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\\$ |session |the session|interrupted|passed in|install |test |start |ready |process |timing: )/; |
| 134 | 134 | function line(kind, speaker, fill, variant) { |
| 135 | 135 | var el = document.createElement('div'); |
| @@ -2584,6 +2584,7 @@ export const liveRegionsJs = /* js */ ` | ||
| 2584 | 2584 | opened.forEach(function (i) { var d = document.getElementById(i); if (d) d.open = true; }); |
| 2585 | 2585 | Array.prototype.forEach.call(theirs.attributes, function (a) { if (a.name !== 'id') mine.setAttribute(a.name, a.value); }); |
| 2586 | 2586 | mine.dispatchEvent(new CustomEvent('forge:swapped', { bubbles: true })); |
| 2587 | arm(mine); | |
| 2587 | 2588 | }); |
| 2588 | 2589 | } |
| 2589 | 2590 | // A region with an address of its own (data-live-src) answers for itself: |
| @@ -2707,11 +2708,15 @@ export const liveRegionsJs = /* js */ ` | ||
| 2707 | 2708 | // A region that changes with the clock, not an event (data-live-at, an |
| 2708 | 2709 | // ISO time, so the page stays the same bytes between visits): looked at |
| 2709 | 2710 | // once when the time comes. |
| 2710 | Array.prototype.forEach.call(document.querySelectorAll('[data-live-at]'), function (r) { | |
| 2711 | var ms = Date.parse(r.getAttribute('data-live-at')) - Date.now() + 1000; | |
| 2711 | // A swapped region carries its next time too (\`arm\`), so a region that changes by the clock | |
| 2712 | // keeps looking. | |
| 2713 | function arm(r) { | |
| 2714 | var at = r.getAttribute('data-live-at'); | |
| 2715 | var ms = at ? Date.parse(at) - Date.now() + 1000 : 0; | |
| 2712 | 2716 | if (!r.id || !(ms > 0) || ms > 2147483647) return; |
| 2713 | 2717 | setTimeout(function () { due[r.id] = true; if (timer === null) timer = setTimeout(refresh, 100); }, ms); |
| 2714 | }); | |
| 2718 | } | |
| 2719 | Array.prototype.forEach.call(document.querySelectorAll('[data-live-at]'), arm); | |
| 2715 | 2720 | // Back online: reconnect from the last id and look at every region once, |
| 2716 | 2721 | // in case the replay window no longer reaches back that far. |
| 2717 | 2722 | // The page moved to another repository: the stream moves its seat, resuming from the last id. |
src/web/pages/runners.ts +68 −15
| @@ -18,13 +18,18 @@ import { cannotByRunner } from "../../games/lend_why.ts"; | ||
| 18 | 18 | import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts"; |
| 19 | 19 | import { lentLine, scopeFacts } from "../../checks/lent_scope.ts"; |
| 20 | 20 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 21 | import { heldByRunner, lentIn, workByRunner, type Enrolled, type RunnerWork, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; | |
| 21 | import { heldByRunner, lentIn, SEEN_FRESH_MS, workByRunner, type Enrolled, type RunnerWork, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; | |
| 22 | import { nextQuiet, runnerLines, type RunnerLine } from "../../machines/live_runners.ts"; | |
| 22 | 23 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 23 | 24 | import type { Ctx } from "../../http/context.ts"; |
| 24 | 25 | import { sshOn } from "../../settings/ssh.ts"; |
| 26 | import { liveRegionsJs } from "../client.ts"; | |
| 27 | import { behaviorsJs } from "../behaviors.ts"; | |
| 28 | import { runnerTailJs } from "../runner_tail.ts"; | |
| 29 | import { logBox } from "../studio/log.ts"; | |
| 25 | 30 | import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts"; |
| 26 | 31 | import { readForm } from "../form.ts"; |
| 27 | import { html } from "../html.ts"; | |
| 32 | import { html, raw } from "../html.ts"; | |
| 28 | 33 | import { flashTo, fragment, page } from "../layout.ts"; |
| 29 | 34 | import { badge, btn, icon, row, rowList, time } from "../ui.ts"; |
| 30 | 35 | import { emptyList } from "../empty_words.ts"; |
| @@ -51,9 +56,33 @@ function runnerTrail(r: Enrolled) { | ||
| 51 | 56 | return html`${r.trusted ? form("untrust", "Untrust") : form("trust", "Trust")}${r.paused === "" ? form("pause", "Pause") : form("resume", "Resume")}${form("revoke", "Revoke")}`; |
| 52 | 57 | } |
| 53 | 58 | |
| 54 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string) { | |
| 59 | /** The run a runner holds, in words, linked when the viewer may read it. */ | |
| 60 | function holdsWords(line: RunnerLine | undefined) { | |
| 61 | const run = line?.run; | |
| 62 | if (line === undefined || run === undefined) return null; | |
| 63 | const more = line.holds > 1 ? ` and ${line.holds - 1} more` : ""; | |
| 64 | if (run.id === "") return html` · holds a run${more}`; | |
| 65 | return html` · holds run <a href="${run.href}" class="mono">${run.id.slice(0, 8)}</a> of ${run.repo}${more}`; | |
| 66 | } | |
| 67 | ||
| 68 | /** What opens under a row that holds a run: its facts, and the run's log as it arrives. */ | |
| 69 | function runnerOpen(line: RunnerLine, facts: { label: string; value: string }[]) { | |
| 70 | const run = line.run!; | |
| 71 | const lines = run.lines ?? []; | |
| 72 | return html`<div class="runner-open"> | |
| 73 | ${facts.length === 0 ? null : html`<dl class="row-facts">${facts.map((f) => html`<div><dt>${f.label}</dt><dd>${f.value}</dd></div>`)}</dl>`} | |
| 74 | <div data-runner-tail="${run.id}"> | |
| 75 | <p class="muted small" data-none ${lines.length === 0 ? null : raw("hidden")}>No line yet: the run's log appears here as the runner sends it.</p> | |
| 76 | ${logBox({ id: `runner-log-${line.id}`, who: "runner", cap: 200, lines, allHref: run.href, truncated: run.truncated })} | |
| 77 | </div> | |
| 78 | </div>`; | |
| 79 | } | |
| 80 | ||
| 81 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string, line?: RunnerLine) { | |
| 55 | 82 | const state = runnerState(r.seenAt, now); |
| 56 | 83 | const machine = runnerMachineWords(r); |
| 84 | const facts = [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...(outsideWords(r) === "" ? [] : [{ label: "Outside", value: outsideWords(r) }]), ...scopeFacts(r, now)]; | |
| 85 | const opens = line?.run !== undefined && line.run.id !== "" && line.run.lines !== undefined; | |
| 57 | 86 | return row({ |
| 58 | 87 | lead: icon("activity"), |
| 59 | 88 | state: state === "connected" && r.revokedAt === 0 ? "open" : "draft", |
| @@ -66,10 +95,11 @@ function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, can | ||
| 66 | 95 | ? badge("Connected", { variant: "secondary", icon: "check" }) |
| 67 | 96 | : state === "quiet" |
| 68 | 97 | ? badge("Quiet", { variant: "outline", icon: "clock" }) |
| 69 | : badge("Never asked", { variant: "outline", icon: "ban" })}`, | |
| 70 | meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`} | |
| 98 | : badge("Never asked", { variant: "outline", icon: "ban" })} | |
| 99 | ${r.revokedAt !== 0 || line === undefined ? null : line.busy ? badge("Busy", { tone: "attn" }) : badge("Idle", { variant: "outline" })}`, | |
| 100 | meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last seen ${time(new Date(r.seenAt).toISOString())}`}${holdsWords(line)} | |
| 71 | 101 | · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`, |
| 72 | facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...(outsideWords(r) === "" ? [] : [{ label: "Outside", value: outsideWords(r) }]), ...scopeFacts(r, now)], | |
| 102 | ...(opens ? { fold: { id: `runner-run-${r.id}`, open: false, body: runnerOpen(line!, facts) } } : { facts }), | |
| 73 | 103 | trail: runnerTrail(r), |
| 74 | 104 | }); |
| 75 | 105 | } |
| @@ -253,6 +283,36 @@ export async function lendingOffer(ctx: Ctx): Promise<Response> { | ||
| 253 | 283 | ); |
| 254 | 284 | } |
| 255 | 285 | |
| 286 | /** | |
| 287 | * What moves: every runner's row and the empty page. Patched in place from `runner.*` events, and | |
| 288 | * once more when the first connected runner would fall quiet (`data-live-at`). | |
| 289 | */ | |
| 290 | function runnersLivePart(ctx: Ctx, runners: readonly Enrolled[]) { | |
| 291 | const now = Date.now(); | |
| 292 | const held = heldByRunner(ctx.app.db); | |
| 293 | const cannot = cannotByRunner(ctx.app.db); | |
| 294 | const work = workByRunner(ctx.app.db); | |
| 295 | const proofs = proofByRunner(ctx.app.db); | |
| 296 | const lines = runnerLines(ctx.app, ctx.auth.user, now) ?? []; | |
| 297 | const byId = new Map(lines.map((l) => [l.id, l])); | |
| 298 | const quiet = nextQuiet(lines, SEEN_FRESH_MS); | |
| 299 | return html`<div id="runner-live" data-live="runner.*" data-live-src="${HERE}/live"${quiet === "" ? null : html` data-live-at="${quiet}"`}> | |
| 300 | ${runners.length === 0 | |
| 301 | ? emptyList("runners") | |
| 302 | : html`<ul class="list setting-list" id="runner-list"> | |
| 303 | ${runners.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, cannot.get(r.id) ?? "", proofWords(proofs.get(r.id)), byId.get(r.id)))} | |
| 304 | </ul>`} | |
| 305 | </div>`; | |
| 306 | } | |
| 307 | ||
| 308 | // GET /settings/runners/live | |
| 309 | export function runnersLive(ctx: Ctx): Response { | |
| 310 | if (!(adminPage(ctx) && ctx.auth.user.kind === "user")) return fragment(html``, { status: 404 }); | |
| 311 | const seen = list(ctx.app, ctx.auth.user); | |
| 312 | if (!seen.ok) return fragment(html``, { status: 404 }); | |
| 313 | return fragment(runnersLivePart(ctx, seen.value), { request: ctx.request }); | |
| 314 | } | |
| 315 | ||
| 256 | 316 | // GET /settings/runners |
| 257 | 317 | export function runnersPage(ctx: Ctx): Response { |
| 258 | 318 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| @@ -262,26 +322,19 @@ export function runnersPage(ctx: Ctx): Response { | ||
| 262 | 322 | if (!seen.ok) return notFoundPage(ctx); |
| 263 | 323 | const rendering = performance.now(); |
| 264 | 324 | const now = Date.now(); |
| 265 | const held = heldByRunner(ctx.app.db); | |
| 266 | const cannot = cannotByRunner(ctx.app.db); | |
| 267 | const work = workByRunner(ctx.app.db); | |
| 268 | const proofs = proofByRunner(ctx.app.db); | |
| 269 | 325 | const waiting = yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])); |
| 270 | 326 | const lent = lentLine(lentIn(ctx.app.db, now)); |
| 271 | 327 | const body = html`<section class="settings-block"> |
| 272 | 328 | ${waiting === "" ? "" : html`<p class="muted small" id="lent-waiting">${waiting}</p>`} |
| 273 | 329 | ${lent === "" ? "" : html`<p class="muted small" id="lent-line">${lent}</p>`} |
| 274 | 330 | <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>, or register a machine below.</p> |
| 275 | ${seen.value.length === 0 | |
| 276 | ? emptyList("runners") | |
| 277 | : html`<ul class="list setting-list" id="runner-list"> | |
| 278 | ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, cannot.get(r.id) ?? "", proofWords(proofs.get(r.id))))} | |
| 279 | </ul>`} | |
| 331 | ${runnersLivePart(ctx, seen.value)} | |
| 280 | 332 | </section>${registerBlock()}${lendingBlock(ctx)}`; |
| 281 | 333 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 282 | 334 | return page({ |
| 283 | 335 | ctx, |
| 284 | 336 | title: "Runners", |
| 337 | scriptJs: `${liveRegionsJs}\n${runnerTailJs}\n${behaviorsJs}`, | |
| 285 | 338 | body: html`${pageHead("Runners", { sub: "The machines that take this forge's checks, and whether each is asking for work." })} |
| 286 | 339 | ${settingsLayout(accountSections("runners", { admin: true, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`, |
| 287 | 340 | }); |
src/web/runner_tail.ts added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | /** | |
| 2 | * A runner's held run, tailed in its open row (#18458). The page carries no stream of its own: | |
| 3 | * the shared `/events` connection (`liveRegionsJs`) delivers each line the viewer may read as a | |
| 4 | * `forge:run-log` frame, and this script adds it to the log box of the row that holds that run. | |
| 5 | * A line goes in as text, never as markup; the box is a fixed window (`.run-log`), so lines | |
| 6 | * arriving move nothing around it, and at most `CAP` stay. A reader scrolled up is left where | |
| 7 | * they are. The row itself (connected, busy, the run) is swapped in place by the live region. | |
| 8 | */ | |
| 9 | import { logLineJs } from "./client.ts"; | |
| 10 | ||
| 11 | export const runnerTailJs = /* js */ ` | |
| 12 | (function () { | |
| 13 | var CAP = 200; | |
| 14 | var who = 'runner'; | |
| 15 | ${logLineJs} | |
| 16 | document.addEventListener('forge:run-log', function (event) { | |
| 17 | var d = event.detail; | |
| 18 | if (!d || typeof d.run !== 'string' || !Array.isArray(d.lines)) return; | |
| 19 | Array.prototype.forEach.call(document.querySelectorAll('[data-runner-tail]'), function (wrap) { | |
| 20 | if (wrap.getAttribute('data-runner-tail') !== d.run) return; | |
| 21 | var box = wrap.querySelector('.run-log'); | |
| 22 | if (!box) return; | |
| 23 | var atEnd = box.scrollHeight - box.scrollTop - box.clientHeight < 24; | |
| 24 | var none = wrap.querySelector('[data-none]'); | |
| 25 | if (none) none.hidden = true; | |
| 26 | d.lines.forEach(function (text) { if (typeof text === 'string') box.appendChild(draw(text)); }); | |
| 27 | var rows = box.querySelectorAll('.row[data-line]'); | |
| 28 | for (var i = 0; i < rows.length - CAP; i++) box.removeChild(rows[i]); | |
| 29 | if (atEnd) box.scrollTop = box.scrollHeight; | |
| 30 | }); | |
| 31 | }); | |
| 32 | })(); | |
| 33 | `; |
test/runners-live.test.ts added +175
| @@ -0,0 +1,175 @@ | ||
| 1 | // The runners page is live (#18458): connected, busy, the run held and its log, a row at a time. | |
| 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 { createRepo } from "../src/actions/repos.ts"; | |
| 7 | import { createApp, type App } from "../src/app.ts"; | |
| 8 | import { claimJob, enrolRunner, offerJob, SEEN_FRESH_MS, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 9 | import { createSession } from "../src/core/sessions.ts"; | |
| 10 | import { createRun } from "../src/core/runs.ts"; | |
| 11 | import { createUser, type User } from "../src/core/users.ts"; | |
| 12 | import { listEvents } from "../src/core/events.ts"; | |
| 13 | import { serve } from "../src/http/server.ts"; | |
| 14 | import { nextQuiet, runnerLines } from "../src/machines/live_runners.ts"; | |
| 15 | import { appendRunLog, flushRunLogs } from "../src/runs/log.ts"; | |
| 16 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | let dataDir = ""; | |
| 22 | let app: App; | |
| 23 | let alice: User; | |
| 24 | let bob: User; | |
| 25 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 26 | let repoId = ""; | |
| 27 | ||
| 28 | beforeAll(async () => { | |
| 29 | dataDir = await mkdtemp(join(tmpdir(), "forge-runners-live-")); | |
| 30 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 31 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 32 | if (!a.ok) throw new Error(a.error); | |
| 33 | alice = a.value; | |
| 34 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "correct-horse-battery" }); | |
| 35 | if (!b.ok) throw new Error(b.error); | |
| 36 | bob = b.value; | |
| 37 | const repo = await createRepo(app, alice, { name: "lib", visibility: "private" }); | |
| 38 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 39 | repoId = repo.value.id; | |
| 40 | servers = await serve(app); | |
| 41 | }); | |
| 42 | ||
| 43 | afterAll(async () => { | |
| 44 | servers.stop(); | |
| 45 | app.close(); | |
| 46 | await rm(dataDir, { recursive: true, force: true }); | |
| 47 | }); | |
| 48 | ||
| 49 | const cookie = (who: User) => `forge_session=${createSession(app.db, who.id).token}`; | |
| 50 | const live = (who: User) => fetch(`${servers.url}/settings/runners/live`, { headers: { cookie: cookie(who) } }); | |
| 51 | const rowOf = (html: string, name: string): string => { | |
| 52 | const at = html.indexOf(`${name} <span`); | |
| 53 | if (at === -1) return ""; | |
| 54 | return html.slice(at, html.indexOf("</li>", at)); | |
| 55 | }; | |
| 56 | const heartbeat = (token: string, state: string) => | |
| 57 | fetch(`${servers.url}/api/v1/runner/heartbeat`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ state }) }); | |
| 58 | const kinds = (): string[] => listEvents(app.db, { limit: 50 }).map((e) => e.kind); | |
| 59 | ||
| 60 | const spec = (runId: string): Omit<RunnerJob, "id"> => ({ | |
| 61 | run: runId, repo: "alice/lib", commit: "a".repeat(40), base: "b".repeat(40), depth: 1, | |
| 62 | steps: [{ name: "check", command: "bun test" }], env: {}, limits: { cpus: 1, memoryMiB: 512 }, | |
| 63 | timeoutS: 60, egress: [], egressMode: "enforce", cell: "preferred", | |
| 64 | cache: { repo: "repo-1", tree: "c".repeat(40), base: "b".repeat(40) }, | |
| 65 | }); | |
| 66 | ||
| 67 | describe("the live runners page", () => { | |
| 68 | test("a heartbeat flips a silent runner to connected and idle, and says so on the stream", async () => { | |
| 69 | const made = enrolRunner(app.db, "mac", alice.id); | |
| 70 | const before = await (await live(alice)).text(); | |
| 71 | expect(rowOf(before, "mac")).toContain("Never asked"); | |
| 72 | expect(rowOf(before, "mac")).not.toContain("Connected"); | |
| 73 | const sent = await heartbeat(made.token, "idle"); | |
| 74 | expect(sent.status).toBe(204); | |
| 75 | expect(kinds()).toContain("runner.seen"); | |
| 76 | const after = rowOf(await (await live(alice)).text(), "mac"); | |
| 77 | expect(after).toContain("Connected"); | |
| 78 | expect(after).toContain("Idle"); | |
| 79 | expect(after).toContain("Last seen"); | |
| 80 | // A second heartbeat that changes nothing is not news. | |
| 81 | const n = kinds().filter((k) => k === "runner.seen").length; | |
| 82 | await heartbeat(made.token, "idle"); | |
| 83 | expect(kinds().filter((k) => k === "runner.seen").length).toBe(n); | |
| 84 | // Saying busy is. | |
| 85 | await heartbeat(made.token, "busy"); | |
| 86 | expect(kinds().filter((k) => k === "runner.seen").length).toBe(n + 1); | |
| 87 | expect(rowOf(await (await live(alice)).text(), "mac")).toContain("Busy"); | |
| 88 | }); | |
| 89 | ||
| 90 | test("a claim shows the run it holds, linked, with its log escaped and arriving", async () => { | |
| 91 | const r = enrolRunner(app.db, "builder", alice.id).runner; | |
| 92 | const run = createRun(app.db, { repoId, kind: "check" }); | |
| 93 | offerJob(app.db, { runId: run.id, repoId, dir: "/nowhere", job: spec(run.id) }); | |
| 94 | const claim = claimJob(app.db, { id: r.id, cells: true }, Date.now()); | |
| 95 | if (claim === undefined) throw new Error("no claim"); | |
| 96 | appendRunLog(dataDir, run.id, "$ bun test <script>alert(1)</script>"); | |
| 97 | flushRunLogs(); | |
| 98 | const lines = runnerLines(app, alice, Date.now())!; | |
| 99 | const mine = lines.find((l) => l.id === r.id)!; | |
| 100 | expect(mine.busy).toBe(true); | |
| 101 | expect(mine.holds).toBe(1); | |
| 102 | expect(mine.run?.href).toBe(`/alice/lib/runs/${run.id}`); | |
| 103 | const html = rowOf(await (await live(alice)).text(), "builder"); | |
| 104 | expect(html).toContain("Busy"); | |
| 105 | expect(html).toContain(`href="/alice/lib/runs/${run.id}"`); | |
| 106 | expect(html).toContain(`data-runner-tail="${run.id}"`); | |
| 107 | expect(html).toContain("<script>alert(1)</script>"); | |
| 108 | expect(html).not.toContain("<script>alert(1)"); | |
| 109 | // The row is a fold, so opening it is the reader's. | |
| 110 | expect(await (await live(alice)).text()).toContain(`<details id="runner-run-${r.id}"`); | |
| 111 | }); | |
| 112 | ||
| 113 | test("a silent runner shows its last seen and is not connected", async () => { | |
| 114 | const made = enrolRunner(app.db, "quiet-one", alice.id).runner; | |
| 115 | const long = Date.now() - 10 * SEEN_FRESH_MS; | |
| 116 | app.db.query("UPDATE check_runner SET seen_at = ?2, state = 'idle' WHERE id = ?1").run(made.id, long); | |
| 117 | const mine = runnerLines(app, alice, Date.now())!.find((l) => l.id === made.id)!; | |
| 118 | expect(mine.connected).toBe(false); | |
| 119 | expect(mine.word).toBe("quiet"); | |
| 120 | const row = rowOf(await (await live(alice)).text(), "quiet-one"); | |
| 121 | expect(row).toContain("Quiet"); | |
| 122 | expect(row).toContain("Last seen"); | |
| 123 | expect(row).not.toContain("Connected"); | |
| 124 | // The page looks again when the first connected runner would fall quiet, and not before. | |
| 125 | const now = Date.now(); | |
| 126 | const fresh = { ...mine, connected: true, seenAt: now }; | |
| 127 | expect(nextQuiet([mine], SEEN_FRESH_MS)).toBe(""); | |
| 128 | expect(nextQuiet([fresh], SEEN_FRESH_MS)).toBe(new Date(now + SEEN_FRESH_MS).toISOString()); | |
| 129 | }); | |
| 130 | ||
| 131 | test("a person without the grant is told nothing of another's machine", async () => { | |
| 132 | enrolRunner(app.db, "secret-box", alice.id); | |
| 133 | expect(runnerLines(app, bob, Date.now())).toBeUndefined(); | |
| 134 | const res = await live(bob); | |
| 135 | expect(res.status).toBe(404); | |
| 136 | expect(await res.text()).not.toContain("secret-box"); | |
| 137 | const anon = await fetch(`${servers.url}/settings/runners/live`, { redirect: "manual" }); | |
| 138 | expect(anon.status).not.toBe(200); | |
| 139 | expect(await anon.text()).not.toContain("secret-box"); | |
| 140 | }); | |
| 141 | ||
| 142 | test("the page carries the live region and its tail script; the fragment is cut off from other origins' scripts", async () => { | |
| 143 | const page = await (await fetch(`${servers.url}/settings/runners`, { headers: { cookie: cookie(alice) } })).text(); | |
| 144 | expect(page).toContain('id="runner-live"'); | |
| 145 | expect(page).toContain('data-live="runner.*"'); | |
| 146 | expect(page).toContain('data-live-src="/settings/runners/live"'); | |
| 147 | const frag = await live(alice); | |
| 148 | expect(frag.headers.get("content-security-policy")).toContain("default-src 'none'"); | |
| 149 | expect(frag.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 150 | }); | |
| 151 | }); | |
| 152 | ||
| 153 | describe("the empty page", () => { | |
| 154 | test("says what goes here and how a machine is added", async () => { | |
| 155 | const fresh = await mkdtemp(join(tmpdir(), "forge-runners-empty-")); | |
| 156 | const own = createApp({ dataDir: fresh, port: 0, host: "forge.test" }); | |
| 157 | try { | |
| 158 | const a = await seedAdmin(own, { username: "carol", email: "[email protected]", password: "correct-horse-battery" }); | |
| 159 | if (!a.ok) throw new Error(a.error); | |
| 160 | const s = await serve(own); | |
| 161 | try { | |
| 162 | const res = await fetch(`${s.url}/settings/runners/live`, { headers: { cookie: `forge_session=${createSession(own.db, a.value.id).token}` } }); | |
| 163 | const text = await res.text(); | |
| 164 | expect(text).toContain("No runner is enrolled."); | |
| 165 | expect(text).toContain("Register one below"); | |
| 166 | expect(text).toContain("POST /api/v1/admin/runners"); | |
| 167 | } finally { | |
| 168 | s.stop(); | |
| 169 | } | |
| 170 | } finally { | |
| 171 | own.close(); | |
| 172 | await rm(fresh, { recursive: true, force: true }); | |
| 173 | } | |
| 174 | }); | |
| 175 | }); |
new above
offline