Public: anyone can read this; the crew can change it.
Lending speaks the versioned agent protocol, and each machine's page shows when it last used the old sync route #18521
Merged 2h 43m ago, live in production
scout/forge:scout/18515-lending-speaks-the-versioned-agent-proto → main 0 commits fork 5 threads · 5 unresolved
10 files
changed +258
−11
docs/features/lending.md +4
| @@ -97,3 +97,7 @@ offer reads _revoked by the borrower_. | ||
| 97 | 97 | - Accounting is the core-minutes your forge counts. The borrower's own ledger is on its Runners page. |
| 98 | 98 | - Burst, borrowing for yourself, is the same mechanism the other way: your forge enrols a `lent-` |
| 99 | 99 | runner, and the other machine runs it. |
| 100 | ||
| 101 | ## Which protocol a machine speaks | |
| 102 | ||
| 103 | A lending box's agent sends its claim, lines and answer as agent protocol 1 (`POST /api/v1/agent/v1/claim`, `logs`, `result`, each with `"v": 1`), with the runner token the forge handed it. A box on version 0 (`/api/v1/runner/…`) still works. Settings → Runners, the terminal's runners screen, and a game box's page say which version a machine speaks and the day it last used the old sync route; after 30 days without a call they say the alias may go. The route itself is not removed. |
src/games/agent.sh +9 −4
| @@ -1942,9 +1942,14 @@ lend_tick() { | ||
| 1942 | 1942 | return 0 |
| 1943 | 1943 | } |
| 1944 | 1944 | |
| 1945 | # POST to a held job: its answer, its lines, or nothing (a heartbeat). Non-zero when the claim is gone. | |
| 1945 | # POST to a held job (agent protocol 1): its answer is a `result`, its lines or nothing (a | |
| 1946 | # heartbeat, which renews the lease) a `logs`. Non-zero when the claim is gone. | |
| 1946 | 1947 | lend_post() { |
| 1947 | curl -sS -m 20 -o /dev/null --fail -H "@" -H 'content-type: application/json' --data "$2" "/api/v1/runner/jobs/$1" | |
| 1948 | local msg=logs | |
| 1949 | jq -e 'has("done") or has("abandon") or has("interrupted")' >/dev/null 2>&1 <<<"$2" && msg=result | |
| 1950 | curl -sS -m 20 -o /dev/null --fail -H "@" -H 'content-type: application/json' \ | |
| 1951 | --data "$(jq -c --arg j "" --arg m "" '{v: 1, job: } + (if == "logs" then {lines: []} else {} end) + .' <<<"")" \ | |
| 1952 | "/api/v1/agent/v1/" | |
| 1948 | 1953 | } |
| 1949 | 1954 | |
| 1950 | 1955 | lend_work() { |
| @@ -1952,8 +1957,8 @@ lend_work() { | ||
| 1952 | 1957 | cpus="$(nproc 2>/dev/null || echo 1)" |
| 1953 | 1958 | mem="$(awk '/^MemTotal:/ {print int($2/1024)}' "" 2>/dev/null || echo 0)" |
| 1954 | 1959 | code="$(curl -sS -m 20 -o "" -w '%{http_code}' -H "@" -H 'content-type: application/json' \ |
| 1955 | --data "$(jq -cn --argjson c "" --argjson m "" '{wait: 0, cells: true, jobs: 1, machine: {cpus: , memoryMiB: , hostCpus: }}')" \ | |
| 1956 | "/api/v1/runner/claim")" || return 0 | |
| 1960 | --data "$(jq -cn --argjson c "" --argjson m "" '{v: 1, wait: 0, cells: true, jobs: 1, machine: {cpus: , memoryMiB: , hostCpus: }}')" \ | |
| 1961 | "/api/v1/agent/v1/claim")" || return 0 | |
| 1957 | 1962 | case "" in |
| 1958 | 1963 | 200) lend_job "" ;; |
| 1959 | 1964 | # The forge does not know the token (switched off, or replaced): drop it; the next sync says which. |
src/machines/agent_use.ts +37
| @@ -20,3 +20,40 @@ export function noteUse(db: Database, machine: string, role: Role, version: numb | ||
| 20 | 20 | export function lastUse(db: Database, version: number): number { |
| 21 | 21 | return db.query<{ at: number | null }, [number]>("SELECT MAX(last_at) AS at FROM agent_use WHERE version = ?1").get(version)?.at ?? 0; |
| 22 | 22 | } |
| 23 | ||
| 24 | /** After this long without a call to the old sync route, the alias may go. */ | |
| 25 | export const ALIAS_IDLE_MS = 30 * 24 * 3_600_000; | |
| 26 | ||
| 27 | /** | |
| 28 | * What each machine's page says of the protocol (#18515): the version it spoke last, and the day it | |
| 29 | * last called the old sync route (version 0). A machine that never used version 0, or not for 30 | |
| 30 | * days, is told the alias may go. A machine that has not spoken at all has no entry. One query for | |
| 31 | * all of them. | |
| 32 | */ | |
| 33 | export function protocolWordsFor(db: Database, machines: readonly string[], now = Date.now()): Map<string, string> { | |
| 34 | const out = new Map<string, string>(); | |
| 35 | if (machines.length === 0) return out; | |
| 36 | const rows = db | |
| 37 | .query<{ machine: string; version: number; last_at: number }, string[]>( | |
| 38 | `SELECT machine, version, last_at FROM agent_use WHERE machine IN (${machines.map((_, i) => `?${i + 1}`).join(",")})`, | |
| 39 | ) | |
| 40 | .all(...machines); | |
| 41 | const by = new Map<string, { version: number; last_at: number }[]>(); | |
| 42 | for (const r of rows) by.set(r.machine, [...(by.get(r.machine) ?? []), r]); | |
| 43 | for (const [machine, mine] of by) { | |
| 44 | const speaks = Math.max(...mine.map((r) => r.version)); | |
| 45 | const old = mine.find((r) => r.version === 0)?.last_at ?? 0; | |
| 46 | const lead = `Speaks agent protocol ${speaks}.`; | |
| 47 | if (old === 0) out.set(machine, `${lead} Never used the old sync route: the alias may go.`); | |
| 48 | else { | |
| 49 | const day = new Date(old).toISOString().slice(0, 10); | |
| 50 | out.set(machine, now - old >= ALIAS_IDLE_MS ? `${lead} Last used the old sync route on ${day}, over 30 days ago: the alias may go.` : `${lead} Last used the old sync route on ${day}.`); | |
| 51 | } | |
| 52 | } | |
| 53 | return out; | |
| 54 | } | |
| 55 | ||
| 56 | /** One machine's words, or nothing for a machine that has not spoken. */ | |
| 57 | export function protocolWords(db: Database, machine: string, now = Date.now()): string | undefined { | |
| 58 | return protocolWordsFor(db, [machine], now).get(machine); | |
| 59 | } |
src/tui/screens/games.ts +2
| @@ -38,6 +38,7 @@ import { lendCannot } from "../../games/lend_why.ts"; | ||
| 38 | 38 | import { spareRow } from "../../games/spare_row.ts"; |
| 39 | 39 | import { healWords } from "../../games/heal.ts"; |
| 40 | 40 | import { planCycle, performCycle } from "../../games/cycle.ts"; |
| 41 | import { protocolWords } from "../../machines/agent_use.ts"; | |
| 41 | 42 | import { boxLive, liveHead } from "../../games/live.ts"; |
| 42 | 43 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 43 | 44 | import { pluginLines } from "../../games/plugins_loaded.ts"; |
| @@ -649,6 +650,7 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 649 | 650 | const nowLines = [ |
| 650 | 651 | ...(note === "" ? [] : wrap(note, w)), |
| 651 | 652 | ...wrap(liveHead(live), w), |
| 653 | ...wrap(protocolWords(f.app.db, b.id) ?? "", w).filter((l) => l !== ""), | |
| 652 | 654 | ...live.containers.filter((c) => mayDo(roleOn(f.app.db, f.user, b.id, c.name), "viewer")).flatMap((c) => wrap(`${c.name}: ${c.says}`, w)), |
| 653 | 655 | "", |
| 654 | 656 | ]; |
src/tui/screens/runners.ts +5 −2
| @@ -16,6 +16,7 @@ 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 | 18 | import { runnerLines } from "../../machines/live_runners.ts"; |
| 19 | import { protocolWordsFor } from "../../machines/agent_use.ts"; | |
| 19 | 20 | import { heldByRunner, lentIn, workByRunner, type Enrolled, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; |
| 20 | 21 | import type { Ctx, Screen } from "../app/app.ts"; |
| 21 | 22 | import { binding } from "../app/keys.ts"; |
| @@ -65,7 +66,9 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 65 | 66 | const work = workByRunner(f.db); |
| 66 | 67 | const proofs = proofByRunner(f.db); |
| 67 | 68 | const lines = new Map((runnerLines(f.app, f.user, now) ?? []).map((l) => [l.id, l])); |
| 68 | return entries().map((e) => { | |
| 69 | const all = entries(); | |
| 70 | const proto = protocolWordsFor(f.db, all.flatMap((e) => (e.kind === "runner" ? [e.r.id] : [])), now); | |
| 71 | return all.map((e) => { | |
| 69 | 72 | if (e.kind === "offer") { |
| 70 | 73 | const o = e.o; |
| 71 | 74 | const busy = o.inUse.length === 0 ? "none busy" : `${o.inUse.length} busy (${o.inUse.map((h) => h.repo).join(", ")})`; |
| @@ -84,7 +87,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 84 | 87 | const holds = line?.run === undefined ? "" : line.run.id === "" ? " · holds a run" : ` · holds run ${line.run.id.slice(0, 8)} of ${line.run.repo}`; |
| 85 | 88 | return { |
| 86 | 89 | title: `${r.name} ${stateWords(r, now)}${r.trusted ? " trusted for secrets" : ""}${isLocal(r) ? " (the forge's own)" : ""}`, |
| 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)}` : ""}`, | |
| 90 | meta: `${asked}${busyWord}${holds}${machine === "" ? "" : ` · ${machine}`}${proto.has(r.id) ? ` · ${proto.get(r.id)}` : ""}${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)}` : ""}`, | |
| 88 | 91 | // Under the row, where a narrow screen never gives it up as it does the meta's pieces. |
| 89 | 92 | ...(proofs.has(r.id) ? { note: proofWords(proofs.get(r.id)) } : {}), |
| 90 | 93 | }; |
src/web/games_machine.ts +3
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import type { Ctx } from "../http/context.ts"; |
| 10 | 10 | import { eventStream } from "../http/sse.ts"; |
| 11 | import { protocolWords } from "../machines/agent_use.ts"; | |
| 11 | 12 | import { boxLive, liveHead, type BoxLive } from "../games/live.ts"; |
| 12 | 13 | import { watchBox } from "../games/notify.ts"; |
| 13 | 14 | import { performCycle, planCycle } from "../games/cycle.ts"; |
| @@ -48,8 +49,10 @@ function shown(ctx: Ctx, box: GameBox, live: BoxLive): BoxLive { | ||
| 48 | 49 | |
| 49 | 50 | export function liveBlock(ctx: Ctx, box: GameBox): Html { |
| 50 | 51 | const live = shown(ctx, box, boxLive(ctx.app.db, box)); |
| 52 | const protocol = protocolWords(ctx.app.db, box.id); | |
| 51 | 53 | return html`<section class="settings-block" id="game-live" data-stream="/games/${box.name}/@live" data-silent="${live.silent ? "yes" : "no"}"> |
| 52 | 54 | <p role="status" data-live-head>${liveHead(live)}</p> |
| 55 | ${protocol === undefined ? null : html`<p class="muted small" data-protocol>${protocol}</p>`} | |
| 53 | 56 | ${live.containers.length === 0 |
| 54 | 57 | ? null |
| 55 | 58 | : rowList(live.containers.map((c) => row({ title: c.name, meta: html`<span data-live-container="${c.name}">${c.says}</span>` })))} |
src/web/pages/runners.ts +5 −3
| @@ -19,6 +19,7 @@ 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 | 21 | import { heldByRunner, lentIn, SEEN_FRESH_MS, workByRunner, type Enrolled, type RunnerWork, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; |
| 22 | import { protocolWordsFor } from "../../machines/agent_use.ts"; | |
| 22 | 23 | import { nextQuiet, runnerLines, type RunnerLine } from "../../machines/live_runners.ts"; |
| 23 | 24 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 24 | 25 | import type { Ctx } from "../../http/context.ts"; |
| @@ -78,10 +79,10 @@ function runnerOpen(line: RunnerLine, facts: { label: string; value: string }[]) | ||
| 78 | 79 | </div>`; |
| 79 | 80 | } |
| 80 | 81 | |
| 81 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string, line?: RunnerLine) { | |
| 82 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string, protocol: string, line?: RunnerLine) { | |
| 82 | 83 | const state = runnerState(r.seenAt, now); |
| 83 | 84 | 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 facts = [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...(protocol === "" ? [] : [{ label: "Protocol", value: protocol }]), ...(outsideWords(r) === "" ? [] : [{ label: "Outside", value: outsideWords(r) }]), ...scopeFacts(r, now)]; | |
| 85 | 86 | const opens = line?.run !== undefined && line.run.id !== "" && line.run.lines !== undefined; |
| 86 | 87 | return row({ |
| 87 | 88 | lead: icon("activity"), |
| @@ -295,12 +296,13 @@ function runnersLivePart(ctx: Ctx, runners: readonly Enrolled[]) { | ||
| 295 | 296 | const proofs = proofByRunner(ctx.app.db); |
| 296 | 297 | const lines = runnerLines(ctx.app, ctx.auth.user, now) ?? []; |
| 297 | 298 | const byId = new Map(lines.map((l) => [l.id, l])); |
| 299 | const proto = protocolWordsFor(ctx.app.db, runners.map((r) => r.id), now); | |
| 298 | 300 | const quiet = nextQuiet(lines, SEEN_FRESH_MS); |
| 299 | 301 | return html`<div id="runner-live" data-live="runner.*" data-live-src="${HERE}/live"${quiet === "" ? null : html` data-live-at="${quiet}"`}> |
| 300 | 302 | ${runners.length === 0 |
| 301 | 303 | ? emptyList("runners") |
| 302 | 304 | : 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)))} | |
| 305 | ${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)), proto.get(r.id) ?? "", byId.get(r.id)))} | |
| 304 | 306 | </ul>`} |
| 305 | 307 | </div>`; |
| 306 | 308 | } |
test/agent-lend-v1.test.ts added +153
| @@ -0,0 +1,153 @@ | ||
| 1 | /** | |
| 2 | * Lending speaks agent protocol 1 (#18515): a lender's heartbeat, claim, logs and result go through | |
| 3 | * `/api/v1/agent/v1/` with its token; a lender still on version 0 is answered as before and | |
| 4 | * recorded as such; the box's agent sends version 1; the pages say the last use of the old route. | |
| 5 | */ | |
| 6 | import { beforeAll, expect, test } from "bun:test"; | |
| 7 | import { readFileSync } from "node:fs"; | |
| 8 | import { deskOf, enrolRunner } from "../src/checks/runner_jobs.ts"; | |
| 9 | import { createToken } from "../src/core/tokens.ts"; | |
| 10 | import { ALIAS_IDLE_MS, noteUse, protocolWords } from "../src/machines/agent_use.ts"; | |
| 11 | import { setLoadSource } from "../src/checks/lent_yield.ts"; | |
| 12 | import { openPull } from "../src/actions/pulls.ts"; | |
| 13 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 14 | import { startChecks } from "../src/checks/service.ts"; | |
| 15 | import { checkJson, checksForge } from "./helpers/checks-forge.ts"; | |
| 16 | import { noCanary } from "./helpers/lent.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | const f = checksForge("forge-lend-v1-"); | |
| 21 | ||
| 22 | const send = (path: string, token: string, body: unknown): Promise<Response> => | |
| 23 | fetch(`${f.servers.url}${path}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) }); | |
| 24 | const v1 = (message: string, token: string, body: Record<string, unknown>) => send(`/api/v1/agent/v1/${message}`, token, { v: 1, ...body }); | |
| 25 | const uses = (machine: string, version: number): number => | |
| 26 | f.app.db.query<{ n: number }, [string, number]>("SELECT COUNT(*) AS n FROM agent_use WHERE machine = ?1 AND version = ?2").get(machine, version)!.n; | |
| 27 | const stateOf = (jobId: string): string => f.app.db.query<{ state: string }, [string]>("SELECT state FROM check_job WHERE id = ?1").get(jobId)?.state ?? "gone"; | |
| 28 | ||
| 29 | /** | |
| 30 | * A lent runner past its canary waits in its claim; a pull's check is the job it is handed, so a | |
| 31 | * check waits on it as it would in life, and its claim is a hard 200. | |
| 32 | */ | |
| 33 | async function claimed(name: string, branch: string) { | |
| 34 | const made = enrolRunner(f.app.db, name, f.alice.id, { authors: [] as string[], days: 30 }); | |
| 35 | noCanary(f.app.db, made.runner.id); | |
| 36 | const asked = v1("claim", made.token, { wait: 20, cells: true, jobs: 1, machine: { cpus: 2, memoryMiB: 4096, hostCpus: 2 } }); | |
| 37 | await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim"); | |
| 38 | const pushed = await commitToBranch(f.app, f.alice, f.repo, { branch, message: `Add ${branch}`, files: [{ path: `${branch}.txt`, content: "x\n" }] }); | |
| 39 | if (!pushed.ok) throw new Error(JSON.stringify(pushed.error)); | |
| 40 | const opened = await openPull(f.app, f.alice, f.repo, { title: branch, body: "", baseBranch: "main", headBranch: branch }); | |
| 41 | if (!opened.ok) throw new Error(JSON.stringify(opened.error)); | |
| 42 | const claim = await asked; | |
| 43 | expect(claim.status).toBe(200); | |
| 44 | const got = (await claim.json()) as { job: { id: string }; token: string }; | |
| 45 | return { ...made, got }; | |
| 46 | } | |
| 47 | ||
| 48 | beforeAll(async () => { | |
| 49 | // A lent runner waits while this machine is loaded (#16479): the test machine is idle. | |
| 50 | setLoadSource(() => 0); | |
| 51 | await f.checks.stop(); | |
| 52 | f.checks = startChecks(f.app, { forgeUrl: f.servers.url, concurrency: 1, placement: { mode: "runner", waitMs: 300 } }); | |
| 53 | const gate = await commitToBranch(f.app, f.alice, f.repo, { message: "Declare the check", files: [{ path: "forge.json", content: checkJson("echo ran") }] }); | |
| 54 | if (!gate.ok) throw new Error(JSON.stringify(gate.error)); | |
| 55 | await f.settled((r) => r.commitOid === gate.value.commitOid, 30_000); | |
| 56 | }); | |
| 57 | ||
| 58 | test("a lender's heartbeat, claim, logs and result round-trip on version 1", async () => { | |
| 59 | const { runner, token } = enrolRunner(f.app.db, "lent-box-v1", f.alice.id, { authors: [] as string[], days: 30 }); | |
| 60 | expect((await v1("heartbeat", token, { state: "idle" })).status).toBe(204); | |
| 61 | expect(uses(runner.id, 1)).toBe(1); | |
| 62 | expect(uses(runner.id, 0)).toBe(0); | |
| 63 | const c = await claimed("lent-box-rt", "rt"); | |
| 64 | // What the box's agent sends: the held job's token, an empty `logs` as a renewal, then the end. | |
| 65 | expect((await v1("logs", c.got.token, { job: c.got.job.id, lines: [] })).status).toBe(200); | |
| 66 | expect(stateOf(c.got.job.id)).toBe("claimed"); | |
| 67 | expect((await v1("result", c.got.token, { job: c.got.job.id, abandon: "no cells" })).status).toBe(200); | |
| 68 | expect(stateOf(c.got.job.id)).not.toBe("claimed"); | |
| 69 | }); | |
| 70 | ||
| 71 | /** `lend_post` as the box runs it, with `curl` standing in to print what it would send. */ | |
| 72 | async function lendPost(jobId: string, body: string): Promise<{ data: Record<string, unknown>; url: string }> { | |
| 73 | const sh = readFileSync(new URL("../src/games/agent.sh", import.meta.url), "utf8"); | |
| 74 | const fn = /^lend_post\(\) \{\n[\s\S]*?\n\}$/m.exec(sh)![0]; | |
| 75 | const script = `${fn} | |
| 76 | curl() { local a url data; while [ $# -gt 0 ]; do case "$1" in --data) data="$2"; shift;; esac; url="$1"; shift; done; jq -cn --arg u "$url" --argjson d "$data" '{url: $u, data: $d}'; } | |
| 77 | FORGE_URL=http://forge.test/ LEND_JOBAUTH=/dev/null lend_post "$1" "$2"`; | |
| 78 | const p = Bun.spawn(["bash", "-c", script, "lend", jobId, body], { stdout: "pipe", stderr: "pipe" }); | |
| 79 | const out = await new Response(p.stdout).text(); | |
| 80 | expect(await p.exited).toBe(0); | |
| 81 | return JSON.parse(out) as { data: Record<string, unknown>; url: string }; | |
| 82 | } | |
| 83 | ||
| 84 | test("lend_post's jq turns a heartbeat, a lines body and an end into valid version 1 the real routes accept", async () => { | |
| 85 | const c = await claimed("lent-box-jq", "jq"); | |
| 86 | const id = c.got.job.id; | |
| 87 | const post = async (body: string) => { | |
| 88 | const made = await lendPost(id, body); | |
| 89 | const message = made.url.replace("http://forge.test/api/v1/agent/v1/", ""); | |
| 90 | return { made, message, res: await send(`/api/v1/agent/v1/${message}`, c.got.token, made.data) }; | |
| 91 | }; | |
| 92 | expect(stateOf(id)).toBe("claimed"); | |
| 93 | const beat = await post("{}"); | |
| 94 | expect(beat.message).toBe("logs"); | |
| 95 | expect(beat.made.data).toEqual({ v: 1, job: id, lines: [] }); | |
| 96 | expect(beat.res.status).toBe(200); | |
| 97 | const said = await post(JSON.stringify({ step: "check", lines: ["one", "two"] })); | |
| 98 | expect(said.message).toBe("logs"); | |
| 99 | expect(said.made.data).toEqual({ v: 1, job: id, step: "check", lines: ["one", "two"] }); | |
| 100 | expect(said.res.status).toBe(200); | |
| 101 | const end = { done: { steps: [{ name: "check", ok: true, ms: 1 }], contained: true, note: "" } }; | |
| 102 | const ended = await post(JSON.stringify(end)); | |
| 103 | expect(ended.message).toBe("result"); | |
| 104 | expect(ended.made.data).toEqual({ v: 1, job: id, ...end }); | |
| 105 | expect(ended.made.data).not.toHaveProperty("lines"); | |
| 106 | expect(ended.res.status).toBe(200); | |
| 107 | expect(await ended.res.json()).toEqual({ ended: true }); | |
| 108 | // Held until the end; after it the check takes the job off the desk. | |
| 109 | expect(["done", "gone"]).toContain(stateOf(id)); | |
| 110 | }); | |
| 111 | ||
| 112 | test("a lender still on version 0 keeps working, and is recorded as version 0", async () => { | |
| 113 | const { runner, token } = enrolRunner(f.app.db, "lent-box-v0", f.alice.id, { authors: [] as string[], days: 30 }); | |
| 114 | expect((await send("/api/v1/runner/heartbeat", token, { state: "idle" })).status).toBe(204); | |
| 115 | const claim = await send("/api/v1/runner/claim", token, { wait: 0, cells: true, jobs: 1 }); | |
| 116 | expect([200, 204]).toContain(claim.status); | |
| 117 | expect(uses(runner.id, 0)).toBe(1); | |
| 118 | expect(f.app.db.query<{ role: string }, [string]>("SELECT role FROM agent_use WHERE machine = ?1").get(runner.id)!.role).toBe("lender"); | |
| 119 | }); | |
| 120 | ||
| 121 | test("the box's lending code sends version 1, never the old runner routes", () => { | |
| 122 | const sh = readFileSync(new URL("../src/games/agent.sh", import.meta.url), "utf8"); | |
| 123 | expect(sh).toContain("/api/v1/agent/v1/claim"); | |
| 124 | expect(sh).toContain("/api/v1/agent/v1/$msg"); | |
| 125 | expect(sh).not.toMatch(/api\/v1\/runner\/(claim|jobs\/\$1")/); | |
| 126 | }); | |
| 127 | ||
| 128 | test("a machine's words say its version and the last day it used the old sync route", () => { | |
| 129 | const db = f.app.db; | |
| 130 | const now = Date.parse("2026-12-06T12:00:00Z"); | |
| 131 | expect(protocolWords(db, "nobody", now)).toBeUndefined(); | |
| 132 | noteUse(db, "m-new", "box", 1, now); | |
| 133 | expect(protocolWords(db, "m-new", now)).toContain("Speaks agent protocol 1. Never used the old sync route: the alias may go."); | |
| 134 | noteUse(db, "m-mix", "box", 0, now - 3 * 86_400_000); | |
| 135 | noteUse(db, "m-mix", "box", 1, now); | |
| 136 | expect(protocolWords(db, "m-mix", now)).toBe("Speaks agent protocol 1. Last used the old sync route on 2026-12-03."); | |
| 137 | noteUse(db, "m-old", "box", 0, now - ALIAS_IDLE_MS - 86_400_000); | |
| 138 | noteUse(db, "m-old", "box", 1, now); | |
| 139 | expect(protocolWords(db, "m-old", now)).toContain("over 30 days ago: the alias may go."); | |
| 140 | noteUse(db, "m-v0", "box", 0, now); | |
| 141 | expect(protocolWords(db, "m-v0", now)).toBe("Speaks agent protocol 0. Last used the old sync route on 2026-12-06."); | |
| 142 | }); | |
| 143 | ||
| 144 | test("the runners page shows a machine's last use of the old route", async () => { | |
| 145 | const { runner, token } = enrolRunner(f.app.db, "r-page", f.alice.id); | |
| 146 | await send("/api/v1/runner/heartbeat", token, { state: "idle" }); | |
| 147 | const tok = createToken(f.app.db, f.alice.id, "rw", "rw").token; | |
| 148 | const res = await fetch(`${f.servers.url}/settings/runners`, { headers: { authorization: `Bearer ${tok}` } }); | |
| 149 | expect(res.status).toBe(200); | |
| 150 | const body = await res.text(); | |
| 151 | expect(body).toContain(runner.id); | |
| 152 | expect(body).toContain("Speaks agent protocol 0. Last used the old sync route on"); | |
| 153 | }); |
test/tui-games.test.ts +28
| @@ -17,6 +17,9 @@ import { readCompose, serviceEnv } from "../src/games/compose.ts"; | ||
| 17 | 17 | import { WAKE_GRACE_MS } from "../src/games/heal.ts"; |
| 18 | 18 | import { boxOfSparkSecret, keepProfile } from "../src/games/spark.ts"; |
| 19 | 19 | import { lentRunnerOf } from "../src/games/lend.ts"; |
| 20 | import { noteUse } from "../src/machines/agent_use.ts"; | |
| 21 | import { liveBlock } from "../src/web/games_machine.ts"; | |
| 22 | import type { Ctx } from "../src/http/context.ts"; | |
| 20 | 23 | import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync } from "../src/games/store.ts"; |
| 21 | 24 | import { recordMetrics } from "../src/games/metrics.ts"; |
| 22 | 25 | import { queueWorld } from "../src/games/worlds.ts"; |
| @@ -552,3 +555,28 @@ test("the Profiles screen says the slow tick in plain words and names its window | ||
| 552 | 555 | keepWith([[4, 40]]); |
| 553 | 556 | expect(await screenText()).not.toContain("slowest tick took"); |
| 554 | 557 | }); |
| 558 | ||
| 559 | test("a box's page and its terminal screen say the protocol it speaks, and say nothing before it has spoken (#18515)", async () => { | |
| 560 | const box = boxNamed(app.db, "net")!; | |
| 561 | const ctx = { app, auth: { user: alice } } as unknown as Ctx; | |
| 562 | app.db.query("DELETE FROM agent_use WHERE machine = ?1").run(box.id); | |
| 563 | expect(liveBlock(ctx, box).text).not.toContain("data-protocol"); | |
| 564 | const quiet = drive(alice, 200); | |
| 565 | try { | |
| 566 | quiet.tui.ctx.push(gameBoxScreen(quiet.session, quiet.tui.ctx, box)); | |
| 567 | await settleApp(quiet.tui); | |
| 568 | expect(quiet.tui.screen.toText()).not.toContain("Speaks agent protocol"); | |
| 569 | } finally { | |
| 570 | quiet.tui.stop?.(); | |
| 571 | } | |
| 572 | noteUse(app.db, box.id, "box", 1); | |
| 573 | expect(liveBlock(ctx, box).text).toContain("data-protocol>Speaks agent protocol 1. Never used the old sync route: the alias may go."); | |
| 574 | const loud = drive(alice, 200); | |
| 575 | try { | |
| 576 | loud.tui.ctx.push(gameBoxScreen(loud.session, loud.tui.ctx, box)); | |
| 577 | await settleApp(loud.tui); | |
| 578 | expect(loud.tui.screen.toText()).toContain("Speaks agent protocol 1."); | |
| 579 | } finally { | |
| 580 | loud.tui.stop?.(); | |
| 581 | } | |
| 582 | }); |
test/tui-runners.test.ts +12 −2
| @@ -12,6 +12,7 @@ import { createRepo } from "../src/actions/repos.ts"; | ||
| 12 | 12 | import { createApp, type App } from "../src/app.ts"; |
| 13 | 13 | import { setLoadSource } from "../src/checks/lent_yield.ts"; |
| 14 | 14 | import { enrolRunner, listRunners } from "../src/checks/runner_jobs.ts"; |
| 15 | import { noteUse } from "../src/machines/agent_use.ts"; | |
| 15 | 16 | import { listLendOffers } from "../src/core/lend_offers.ts"; |
| 16 | 17 | import { waitFor } from "./helpers/poll.ts"; |
| 17 | 18 | import { createUser, type User } from "../src/core/users.ts"; |
| @@ -36,8 +37,8 @@ const events = (kind: string): number => | ||
| 36 | 37 | app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM event WHERE kind = ?1").get(kind)!.n; |
| 37 | 38 | const names = () => listRunners(app.db).map((r) => r.name).sort(); |
| 38 | 39 | |
| 39 | async function drive(user: User, keys: readonly string[] = []) { | |
| 40 | const terminal = headlessTerminal(120, 30); | |
| 40 | async function drive(user: User, keys: readonly string[] = [], width = 120) { | |
| 41 | const terminal = headlessTerminal(width, 30); | |
| 41 | 42 | const { app: tui, session } = createForgeApp(app, identity(user), { terminal, exitHooks: false }); |
| 42 | 43 | tui.start(); |
| 43 | 44 | // The palette arrives with the screens' module (forge.ts): settle first. |
| @@ -101,6 +102,15 @@ describe("runners in the terminal", () => { | ||
| 101 | 102 | expect(events("runner.removed")).toBe(0); |
| 102 | 103 | }); |
| 103 | 104 | |
| 105 | test("a runner's row says the protocol it speaks and its last use of the old route, once per row (#18515)", async () => { | |
| 106 | const mac = listRunners(app.db).find((r) => r.name === "mac")!; | |
| 107 | noteUse(app.db, mac.id, "runner", 0, Date.parse("2026-12-03T10:00:00Z")); | |
| 108 | noteUse(app.db, mac.id, "runner", 1); | |
| 109 | const { text } = await drive(ada, [], 300); | |
| 110 | expect(text).toContain("Speaks agent protocol 1. Last used the old sync route on 2026-12-03"); | |
| 111 | expect(text.split("Speaks agent protocol").length).toBe(2); | |
| 112 | }); | |
| 113 | ||
| 104 | 114 | test("p pauses the runner under the cursor, a local one is refused, u resumes it (#18038)", async () => { |
| 105 | 115 | const { text } = await drive(ada, ["p"]); |
| 106 | 116 | expect(text).toContain("cannot be paused"); |
new above
offline
protocolWords(f.db, r.id, now)is called twice in one template, so two queries per runner on every redraw. Compute it once per row, or load all runners' rows in one query.