From 3df14397251fec3614ef7c9cec00cb5530e7ce7e Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 21:00:28 -0700 Subject: [PATCH 001/642] Prototype enrolled remote Dispatch agent runners --- apps/server/src/agents/acp/host-client.ts | 75 +++- apps/server/src/agents/acp/host-protocol.ts | 13 +- apps/server/src/agents/acp/host/main.ts | 45 ++- apps/server/src/agents/acp/runtime.ts | 164 ++++++++- apps/server/src/agents/lifecycle-hooks.ts | 2 + apps/server/src/agents/manager.ts | 150 ++++++-- apps/server/src/agents/remote/protocol.ts | 88 +++++ apps/server/src/agents/remote/runner.ts | 345 ++++++++++++++++++ apps/server/src/agents/remote/service.ts | 198 ++++++++++ apps/server/src/agents/runtime.ts | 7 +- apps/server/src/agents/workspace-target.ts | 3 + apps/server/src/main.ts | 3 + apps/server/src/routes/mcp.ts | 17 +- apps/server/src/routes/system.ts | 12 + apps/server/src/server.ts | 7 + apps/server/src/shared/mcp/server.ts | 18 + apps/server/test/acp-host.test.ts | 76 ++++ .../server/test/helpers/remote-acp-fixture.ts | 98 +++++ docs/design/remote-runner-prototype.md | 144 ++++++++ 19 files changed, 1402 insertions(+), 63 deletions(-) create mode 100644 apps/server/src/agents/remote/protocol.ts create mode 100644 apps/server/src/agents/remote/runner.ts create mode 100644 apps/server/src/agents/remote/service.ts create mode 100644 apps/server/test/helpers/remote-acp-fixture.ts create mode 100644 docs/design/remote-runner-prototype.md diff --git a/apps/server/src/agents/acp/host-client.ts b/apps/server/src/agents/acp/host-client.ts index 423f8ca63..9aee2f6b6 100644 --- a/apps/server/src/agents/acp/host-client.ts +++ b/apps/server/src/agents/acp/host-client.ts @@ -6,6 +6,7 @@ import type { } from "@dispatch/shared"; import type { PromptImage, PromptSource } from "./prompt-source.js"; import net from "node:net"; +import type { Duplex } from "node:stream"; import type { SessionConfigOption } from "@agentclientprotocol/sdk"; @@ -27,6 +28,9 @@ export type HostWelcome = Extract; export type HostClientDeps = { agentId: string; socketPath: string; + openSocket?: () => Promise; + reconnectError?: (error: unknown) => "retry" | "gone" | undefined; + onReady?: () => void; logger: DriverLogger; /** The newest journal seq already applied; the host replays after it. */ fromSeq: () => number; @@ -76,7 +80,7 @@ export class HostClient { string, { resolve: () => void; reject: (err: Error) => void } >(); - private socket: net.Socket | null = null; + private socket: Duplex | null = null; private closed = false; private reconnectTimer: NodeJS.Timeout | null = null; private attempts = 0; @@ -100,6 +104,7 @@ export class HostClient { }> = []; private lastWelcome: HostWelcome | null = null; private sentFromSeq = 0; + private replayReady = false; private reconnectingForLegacyReplay = false; constructor(private readonly deps: HostClientDeps) {} @@ -174,7 +179,16 @@ export class HostClient { }); } - private dial(): Promise { + private async dial(): Promise { + if (this.deps.openSocket) { + const socket = await this.deps.openSocket(); + if (this.closed) { + socket.destroy(); + throw new Error("the agent host client was closed"); + } + this.connected(socket); + return; + } return new Promise((resolve, reject) => { const socket = net.createConnection(this.deps.socketPath); const timer = setTimeout(() => { @@ -182,17 +196,7 @@ export class HostClient { }, CONNECT_TIMEOUT_MS); socket.once("connect", () => { clearTimeout(timer); - this.attempts = 0; - this.socket = socket; - this.wire(socket); - this.sentFromSeq = this.deps.fromSeq(); - socket.write( - encodeMessage({ - type: "hello", - fromSeq: this.sentFromSeq, - journalId: this.deps.journalId(), - } satisfies ClientMessage) - ); + this.connected(socket); resolve(); }); socket.once("error", (err) => { @@ -202,7 +206,22 @@ export class HostClient { }); } - private wire(socket: net.Socket): void { + private connected(socket: Duplex): void { + this.attempts = 0; + this.lastWelcome = null; + this.replayReady = !this.deps.openSocket; + this.socket = socket; + this.wire(socket); + this.sentFromSeq = this.deps.fromSeq(); + this.send({ + type: "hello", + fromSeq: this.sentFromSeq, + journalId: this.deps.journalId(), + ...(this.deps.openSocket ? { replayComplete: true } : {}), + }); + } + + private wire(socket: Duplex): void { const decode = ndjsonDecoder(); socket.on("data", (chunk) => { for (const message of decode(chunk)) this.handle(message); @@ -216,7 +235,13 @@ export class HostClient { socket.on("close", () => { if (this.socket !== socket) return; this.socket = null; - this.failPending(new Error("the agent host connection closed")); + this.failPending( + new Error( + this.deps.openSocket + ? "Runner connection dropped before acknowledgement; execution is unknown." + : "the agent host connection closed" + ) + ); if (this.closed) return; this.scheduleReconnect(); }); @@ -248,9 +273,14 @@ export class HostClient { for (const w of waiters) w.resolve(message); } this.deps.onWelcome(message); + if (this.permissions.length || previousPermissions.length) this.deps.onPermissions?.(this.permissions); return; + case "replay_complete": + this.replayReady = true; + this.deps.onReady?.(); + return; case "event": if (this.reconnectingForLegacyReplay) return; this.deps.onEvent({ @@ -358,7 +388,11 @@ export class HostClient { this.reconnectTimer = null; if (this.closed) return; this.dial().catch((err) => { - if (this.attempts >= 6) { + const disposition = this.deps.reconnectError?.(err); + if ( + disposition === "gone" || + (this.attempts >= 6 && disposition !== "retry") + ) { this.deps.onGone(err instanceof Error ? err.message : String(err)); return; } @@ -498,6 +532,9 @@ export class HostClient { type: "prompt", id, text, + ...(this.deps.openSocket + ? { journalId: this.lastWelcome?.journalId } + : {}), ...(source ? { source } : {}), ...(images?.length ? { images } : {}), }); @@ -588,6 +625,12 @@ export class HostClient { this.send({ type: "shutdown", force }); } + isReady(): boolean { + return ( + this.replayReady && this.isConnected() && !!this.lastWelcome?.running + ); + } + isConnected(): boolean { return this.socket !== null && !this.socket.destroyed; } diff --git a/apps/server/src/agents/acp/host-protocol.ts b/apps/server/src/agents/acp/host-protocol.ts index 149922120..3a21b8654 100644 --- a/apps/server/src/agents/acp/host-protocol.ts +++ b/apps/server/src/agents/acp/host-protocol.ts @@ -4,6 +4,7 @@ import type { AgentMcpInventoryResponse } from "@dispatch/shared"; import type { AgentPermissionRequest } from "@dispatch/shared"; import type { PromptImage, PromptSource } from "./prompt-source.js"; import path from "node:path"; +import { StringDecoder } from "node:string_decoder"; import type { DriverEvent } from "./driver.js"; import type { @@ -70,11 +71,17 @@ export type JournalEntry = { }; export type ClientMessage = - | { type: "hello"; fromSeq: number; journalId?: string | null } + | { + type: "hello"; + fromSeq: number; + journalId?: string | null; + replayComplete?: boolean; + } | { type: "prompt"; id: string; text: string; + journalId?: string; source?: PromptSource; images?: PromptImage[]; } @@ -124,6 +131,7 @@ export type HostMessage = permissions?: AgentPermissionRequest[]; } | ({ type: "event" } & JournalEntry) + | { type: "replay_complete" } | { type: "prompt_accepted"; id: string } /** Not submitted: the engine's own turn is open. Send it again after it settles. */ | { type: "prompt_deferred"; id: string } @@ -149,8 +157,9 @@ export type HostMessage = */ export function ndjsonDecoder(): (chunk: Buffer | string) => T[] { let buffer = ""; + const decoder = new StringDecoder("utf8"); return (chunk) => { - buffer += chunk.toString(); + buffer += typeof chunk === "string" ? chunk : decoder.write(chunk); const out: T[] = []; let index: number; while ((index = buffer.indexOf("\n")) !== -1) { diff --git a/apps/server/src/agents/acp/host/main.ts b/apps/server/src/agents/acp/host/main.ts index 3d3a5c70b..85950b8ec 100644 --- a/apps/server/src/agents/acp/host/main.ts +++ b/apps/server/src/agents/acp/host/main.ts @@ -168,6 +168,29 @@ async function main(): Promise { hostFile(stateDir, "journalId") ); + // These receipts belong to this journal. A claimed operation may have + // reached the provider even if the adapter never acknowledged pickup. + const receipts = new Map(); + const receiptFile = path.join(stateDir, "prompt-receipts.jsonl"); + function recordReceipt(id: string, state: "claimed" | "accepted") { + appendFileSync( + receiptFile, + JSON.stringify({ journalId: journal.id, id, state }) + "\n", + { mode: 0o600, flush: true } + ); + receipts.set(id, state); + } + try { + for (const line of readFileSync(receiptFile, "utf8").trim().split("\n")) { + if (!line) continue; + const receipt = JSON.parse(line); + if (receipt.journalId === journal.id) + receipts.set(receipt.id, receipt.state); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + // The engine child's environment: the host's own (a login shell's), the // launch's additions, and Dispatch's bin directories ahead on PATH. const childEnv = buildHostEnv(launch, stateDir); @@ -302,6 +325,7 @@ async function main(): Promise { for (const entry of journal.after(fromSeq)) { send(socket, { type: "event", ...entry }); } + if (message.replayComplete) send(socket, { type: "replay_complete" }); if (startupError) send(socket, { type: "error", message: startupError }); return; @@ -330,6 +354,21 @@ async function main(): Promise { send(socket, { type: "pong" }); return; case "prompt": { + if (message.journalId) { + const previous = receipts.get(message.id); + if (message.journalId !== journal.id || previous === "claimed") { + send(socket, { + type: "error", + id: message.id, + message: "Prompt execution is unknown; do not resubmit.", + }); + return; + } + if (previous === "accepted") { + send(socket, { type: "prompt_accepted", id: message.id }); + return; + } + } if (!running) { send(socket, { type: "error", @@ -350,11 +389,15 @@ async function main(): Promise { } // The driver emits the turn's start, settle and error events; the // ack only says the adapter has the request. + if (message.journalId) recordReceipt(message.id, "claimed"); driver .prompt( agentId, message.text, - () => send(client, { type: "prompt_accepted", id: message.id }), + () => { + if (message.journalId) recordReceipt(message.id, "accepted"); + send(socket, { type: "prompt_accepted", id: message.id }); + }, message.source, message.images ) diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 6fe65d8e6..c23d0a804 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -7,6 +7,7 @@ import { sameConversation, type PromptConversation } from "@dispatch/shared"; import { spawn } from "node:child_process"; import { existsSync, openSync } from "node:fs"; import { + appendFile, mkdir, readdir, readFile, @@ -35,6 +36,12 @@ import type { SteeringDecision, SteeringOutcome, } from "../steering.js"; +import { + RunnerUnavailable, + RunnerHostGone, + type RemoteRunnerService, +} from "../remote/service.js"; +import type { Placement } from "../remote/protocol.js"; import { HostClient } from "./host-client.js"; import { type HostLaunch, @@ -227,6 +234,7 @@ type Waiting = { }; type Live = { + remote?: boolean; client: HostClient; commands: AvailableCommand[]; configOptions: SessionConfigOption[]; @@ -358,6 +366,8 @@ function sourceBlockIds(source?: PromptSource): string[] { } export type AcpRuntimeDeps = { + remote?: RemoteRunnerService; + placement?: (agentId: string) => Promise; classifySteering?: ClassifySteering; config: Pick; logger: FastifyBaseLogger; @@ -383,8 +393,16 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { // Assigned below; launch() refers back to it to tear down a failed host. let runtime: AgentRuntime; const live = new Map(); + const connecting = new Map>(); const listeners = new Set(); + const placementOf = async (agentId: string) => + deps.placement?.(agentId) ?? null; + const remoteService = () => { + if (!deps.remote) throw new RunnerUnavailable("Remote runner is disabled."); + return deps.remote; + }; + const stateDir = (agentId: string) => path.join(config.agentStateRoot, agentId); @@ -441,6 +459,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { try { while ( entry.waiting.length && + (!entry.remote || entry.client.isReady()) && !entry.deliveryInterrupts.size && live.get(agentId) === entry ) { @@ -612,6 +631,19 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { : "default" ); } else { + if (entry.remote) { + const dir = stateDir(agentId); + await mkdir(dir, { recursive: true, mode: 0o700 }); + await appendFile( + path.join(dir, "remote-prompts.jsonl"), + JSON.stringify({ + id, + journalId: entry.journalId, + blocks: sourceBlockIds(source), + }) + "\n", + { mode: 0o600, flush: true } + ); + } // Set this before submitting: ack and settle can arrive together. entry.turnOpen = true; entry.turnBlockIds = new Set(sourceBlockIds(source)); @@ -711,7 +743,21 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }); } - async function connect( + function connect( + agentId: string, + timeoutMs: number, + abandoned?: () => boolean + ): Promise { + const pending = connecting.get(agentId); + if (pending) return pending; + const request = openHost(agentId, timeoutMs, abandoned).finally(() => + connecting.delete(agentId) + ); + connecting.set(agentId, request); + return request; + } + + async function openHost( agentId: string, timeoutMs: number, abandoned: () => boolean = () => false @@ -719,7 +765,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const existing = live.get(agentId); if (existing) return existing; const cursor = await deps.hostSeq(agentId); + const placement = await placementOf(agentId); const entry: Live = { + remote: Boolean(placement), client: null as unknown as HostClient, commands: [], configOptions: [], @@ -741,6 +789,29 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { entry.client = new HostClient({ agentId, socketPath: hostFile(stateDir(agentId), "socket"), + ...(placement + ? { + openSocket: async () => + ( + await remoteService().request( + placement, + { + kind: "attach", + agentId, + workspace: placement.workspace, + }, + true + ) + ).channel!, + reconnectError: (error: unknown) => + error instanceof RunnerUnavailable + ? "retry" + : error instanceof RunnerHostGone + ? "gone" + : undefined, + onReady: () => void pump(agentId, entry), + } + : {}), logger, fromSeq: () => entry.lastSeq, journalId: () => entry.journalId, @@ -824,6 +895,17 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { } async function readLogTail(agentId: string): Promise { + const placement = await placementOf(agentId); + if (placement) { + const response = await remoteService() + .request(placement, { + kind: "log", + agentId, + workspace: placement.workspace, + }) + .catch(() => null); + return String(response?.value ?? ""); + } try { const log = await readFile(hostFile(stateDir(agentId), "log"), "utf8"); const tail = log.trim().split("\n").slice(-LOG_TAIL_LINES).join("\n"); @@ -887,6 +969,26 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }, async launch(input) { + const placement = input.placement; + if (placement) { + const { + cwd, + bins, + env, + pathPrefix, + placement: _placement, + ...launch + } = input; + await remoteService().request(placement, { + kind: "launch", + agentId: input.agentId, + workspace: placement.workspace, + launch, + }); + const entry = await connect(input.agentId, LAUNCH_TIMEOUT_MS); + const welcome = entry.client.welcome!; + return { sessionId: welcome.sessionId, resumed: welcome.resumed }; + } const dir = stateDir(input.agentId); await mkdir(dir, { recursive: true, mode: 0o700 }); const launch: HostLaunch = { @@ -976,7 +1078,29 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }, async attach(agentId) { + if (connecting.has(agentId)) { + try { + await connecting.get(agentId); + return true; + } catch { + return false; + } + } if (live.has(agentId)) return true; + const placement = await placementOf(agentId); + if (placement) { + if ( + !deps.remote?.available(placement) || + !(await runtime.isAlive(agentId)) + ) + return false; + try { + await connect(agentId, ATTACH_TIMEOUT_MS); + return true; + } catch { + return false; + } + } const dir = stateDir(agentId); const pid = await readPid(dir); if (!pid || !pidAlive(pid)) return false; @@ -992,6 +1116,20 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { async isAlive(agentId) { const entry = live.get(agentId); if (entry?.client.isConnected()) return true; + const placement = await placementOf(agentId); + if (placement) { + try { + const { value } = await remoteService().request(placement, { + kind: "alive", + agentId, + workspace: placement.workspace, + }); + return value === true; + } catch (error) { + if (error instanceof RunnerUnavailable) return true; // Disconnected is not host death. + throw error; + } + } const pid = await readPid(stateDir(agentId)); return pid !== null && pidAlive(pid); }, @@ -1317,6 +1455,22 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }, async stop(agentId, force) { + const placement = await placementOf(agentId); + if (placement) { + await remoteService().request(placement, { + kind: "stop", + agentId, + workspace: placement.workspace, + force, + }); + const entry = live.get(agentId); + live.delete(agentId); + if (entry) { + failWaiting(entry, new Error("The agent stopped before delivery.")); + entry.client.close(); + } + return; + } const dir = stateDir(agentId); const entry = live.get(agentId); const pid = await readPid(dir); @@ -1386,6 +1540,14 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { readLogTail, async discard(agentId) { + const placement = await placementOf(agentId); + if (placement) { + await remoteService().request(placement, { + kind: "discard", + agentId, + workspace: placement.workspace, + }); + } const entry = live.get(agentId); if (entry) { live.delete(agentId); diff --git a/apps/server/src/agents/lifecycle-hooks.ts b/apps/server/src/agents/lifecycle-hooks.ts index fd0648267..97ba4f8e2 100644 --- a/apps/server/src/agents/lifecycle-hooks.ts +++ b/apps/server/src/agents/lifecycle-hooks.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "./remote/protocol.js"; import type { FastifyBaseLogger } from "fastify"; import { repoCommandEnvironment } from "../shared/lib/tool-environment.js"; @@ -36,6 +37,7 @@ export async function runLifecycleHook( agent: AgentRecord, logger: FastifyBaseLogger ): Promise { + if (remotePlacement(agent.cwd)) return; // An agent that moved runs the hook in both places: what it started in // the launch checkout and what it started in its workspace (a dev stack, // say) each belong to that checkout's own hook. diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index a7c3928d7..475b271ca 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -72,6 +72,8 @@ import type { PromptImage, } from "./acp/prompt-source.js"; import { type EngineBins, isAcpEngine } from "./acp/engine-spec.js"; +import { remotePlacement } from "./remote/protocol.js"; +import type { RemoteRunnerService } from "./remote/service.js"; import { buildLaunchEnv } from "./acp/launch-env.js"; import { dispatchMcpUrl } from "./acp/mcp-url.js"; import { @@ -337,6 +339,7 @@ export class AgentManager { } private readonly logger: FastifyBaseLogger; private readonly config: AppConfig; + private readonly remote?: RemoteRunnerService; private readonly diagnostics: DiagnosticsRecorder; private readonly eventBus: AgentEventBus; private readonly runtime: AgentRuntime; @@ -383,6 +386,7 @@ export class AgentManager { /** Tests inject a fake runtime; the server takes the configured one. */ options: { runtime?: AgentRuntime; + remote?: RemoteRunnerService; classifySteering?: import("./steering.js").ClassifySteering; } = {} ) { @@ -392,6 +396,7 @@ export class AgentManager { }); this.logger = logger; this.config = config; + this.remote = options.remote; this.diagnostics = createDiagnosticsRecorder(logger); this.eventBus = createAgentEventBus(logger); this.streamStore = new StreamStore(pool); @@ -400,6 +405,16 @@ export class AgentManager { options.runtime ?? createAgentRuntime(config, logger, { classifySteering: options.classifySteering, + remote: this.remote, + placement: async (id) => { + const row = ( + await pool.query<{ cwd: string }>( + "SELECT cwd FROM agents WHERE id = $1", + [id] + ) + ).rows[0]; + return row ? remotePlacement(row.cwd) : null; + }, hostSeq: async (agentId) => { const result = await pool.query<{ host_seq: number; @@ -1213,6 +1228,7 @@ export class AgentManager { const agent = await this.getAgent(id); if (!agent) return; + if (remotePlacement(agent.cwd)) return; const result = agent.workspacePath ? await probeGitContext(agent.workspacePath) : agent.worktreePath && agent.worktreeBranch @@ -1295,6 +1311,8 @@ export class AgentManager { input: { path: string | null; baseBranch?: string | null } ): Promise { const agent = await this.getRequiredAgent(id); + if (remotePlacement(agent.cwd)) + throw new AgentError("Runner workspace is fixed for this agent.", 409); const resolved = await resolveWorkspace(agent, input); await this.pool.query( @@ -1332,6 +1350,33 @@ export class AgentManager { } = {} ): Promise { input = { ...input }; + const placement = remotePlacement(input.cwd); + if (placement) { + if ( + !this.remote?.available(placement) || + this.config.agentRuntime !== "acp" + ) { + throw new AgentError( + "The enrolled runner workspace is unavailable.", + 409 + ); + } + if ( + input.projectId || + input.parentAgentId || + input.templateId || + input.persona || + input.jobRunId || + input.initialFiles?.length || + input.useWorktree + ) { + throw new AgentError( + "Runner launches currently require a standalone agent in a pre-provisioned workspace.", + 400 + ); + } + input.useWorktree = false; + } if (input.templateId) { const template = ( await this.pool.query("SELECT project_id FROM templates WHERE id=$1", [ @@ -1376,7 +1421,7 @@ export class AgentManager { } // Resolve only new, unscoped launches. Membership inherited from a parent // (including no project) and explicit/template selections remain authoritative. - if (!input.projectId && !input.parentAgentId) { + if (!placement && !input.projectId && !input.parentAgentId) { const projects = ( await this.pool.query( 'SELECT id, name, repo_root AS "repoRoot" FROM projects' @@ -1657,10 +1702,13 @@ export class AgentManager { private async prepareCreateInputs( input: CreateAgentInput ): Promise { - const originalCwd = await this.validateWorkingDirectory(input.cwd); + const placement = remotePlacement(input.cwd); + const originalCwd = placement + ? input.cwd + : await this.validateWorkingDirectory(input.cwd); // Remember the icon of the directory the user chose, before a managed // worktree can change the agent's effective cwd. - await getDirectoryIconPath(this.pool, originalCwd); + if (!placement) await getDirectoryIconPath(this.pool, originalCwd); const id = this.newAgentId(); const type: AgentType = input.type ?? "claude"; const effort = validateAgentEffort(type, input.effort, input.model); @@ -1821,31 +1869,37 @@ export class AgentManager { const { id } = opts; try { await opts.preparePersona?.(); - const workspace = await prepareWorkspace( - { - agentName: opts.name, - originalCwd: opts.originalCwd, - useWorktree: opts.useWorktree, - createNewBranch: opts.createNewBranch, - worktreeBranchName: opts.worktreeBranchName, - baseBranch: opts.normalizedBaseBranch, - worktreePathOverride: opts.worktreePathOverride, - onStepResult: async (progress) => { - await this.recordStartup(() => - this.launchContextRecorder?.recordStartupStep?.({ - agentId: id, - label: "Installing dependencies", - ...progress, - }) - ); - }, - onPhase: async (phase) => { - await this.setSetupPhase(id, phase); - await this.reportStartupPhase(id, phase, opts.type); - }, - }, - this.logger - ); + const workspace = remotePlacement(opts.originalCwd) + ? { + effectiveCwd: opts.originalCwd, + worktreePath: null, + worktreeBranch: null, + } + : await prepareWorkspace( + { + agentName: opts.name, + originalCwd: opts.originalCwd, + useWorktree: opts.useWorktree, + createNewBranch: opts.createNewBranch, + worktreeBranchName: opts.worktreeBranchName, + baseBranch: opts.normalizedBaseBranch, + worktreePathOverride: opts.worktreePathOverride, + onStepResult: async (progress) => { + await this.recordStartup(() => + this.launchContextRecorder?.recordStartupStep?.({ + agentId: id, + label: "Installing dependencies", + ...progress, + }) + ); + }, + onPhase: async (phase) => { + await this.setSetupPhase(id, phase); + await this.reportStartupPhase(id, phase, opts.type); + }, + }, + this.logger + ); await this.pool.query( `UPDATE agents SET cwd = $2, worktree_path = $3, worktree_branch = $4, updated_at = NOW() WHERE id = $1`, [ @@ -2020,15 +2074,17 @@ export class AgentManager { // person's: say so plainly here rather than letting the spawn fail with // ENOENT once the host is already up. The inert runtime spawns nothing, // so it needs no engine. - const engine = this.runtime.tracksProcesses() - ? ( - await engineStatuses({ - claude: this.config.claudeBin, - codex: this.config.codexBin ?? undefined, - opencode: this.config.opencodeBin, - }) - ).find((status) => status.id === agent.type) - : undefined; + const placement = remotePlacement(agent.cwd) ?? undefined; + const engine = + !placement && this.runtime.tracksProcesses() + ? ( + await engineStatuses({ + claude: this.config.claudeBin, + codex: this.config.codexBin ?? undefined, + opencode: this.config.opencodeBin, + }) + ).find((status) => status.id === agent.type) + : undefined; if (engine && !engine.installed) { throw new AgentError(missingEngineMessage(engine), 422); } @@ -2067,6 +2123,7 @@ export class AgentManager { return this.runtime.launch({ agentId: agent.id, cwd: agent.cwd, + placement, engine: agent.type, fullAccess: agent.fullAccess, bins, @@ -2075,7 +2132,9 @@ export class AgentManager { systemPrompt, personaContext: extractPersonaContext(agent.agentArgs ?? []), mcp: { - url: dispatchMcpUrl(this.config, agent.id, opts.jobRunId), + url: placement + ? `${this.remote!.origin}/api/mcp/${agent.id}` + : dispatchMcpUrl(this.config, agent.id, opts.jobRunId), token, }, env, @@ -2339,6 +2398,21 @@ export class AgentManager { return this.reconciler.reconcileAgentStatuses(); } + remoteRepoOperation(agent: AgentRecord): (() => Promise) | undefined { + const placement = remotePlacement(agent.cwd); + if (!placement || !this.remote?.repoTool) return undefined; + return async () => + String( + ( + await this.remote!.request(placement, { + kind: "repo", + agentId: agent.id, + workspace: placement.workspace, + }) + ).value ?? "" + ); + } + /** The agent's working directory: the worktree when it has one. */ async resolveRuntimeCwd(agent: AgentRecord): Promise { return agent.cwd; diff --git a/apps/server/src/agents/remote/protocol.ts b/apps/server/src/agents/remote/protocol.ts new file mode 100644 index 000000000..2e566bdfc --- /dev/null +++ b/apps/server/src/agents/remote/protocol.ts @@ -0,0 +1,88 @@ +import { Duplex } from "node:stream"; +import { StringDecoder } from "node:string_decoder"; +import type { HostLaunch } from "../acp/host-protocol.js"; + +export function remotePlacement(cwd: string) { + const match = /^runner:\/\/([a-z0-9-]+)\/([a-z0-9-]+)$/.exec(cwd); + return match ? { runner: match[1]!, workspace: match[2]! } : null; +} + +export type Placement = NonNullable>; +export type RemoteLaunch = Omit< + HostLaunch, + "cwd" | "bins" | "env" | "pathPrefix" +>; + +export type Command = { agentId: string; workspace: string } & ( + | { kind: "launch"; launch: RemoteLaunch } + | { kind: "attach" | "alive" | "discard" | "log" | "repo" } + | { kind: "stop"; force: boolean } +); +export type Frame = + | { type: "ready"; version: 1; workspaces: string[] } + | { type: "request"; id: string; command: Command } + | { + type: "result"; + id: string; + value?: boolean | string; + error?: string; + code?: "host-gone"; + } + | { type: "data"; id: string; data: string } + | { type: "close"; id: string }; + +type Send = (frame: Frame) => void; + +export function wireFrames( + socket: Duplex, + receive: (frame: Frame) => void +): Send { + const decoder = new StringDecoder("utf8"); + let pending = ""; + socket.on("data", (chunk: Buffer) => { + pending += decoder.write(chunk); + let newline: number; + while ((newline = pending.indexOf("\n")) >= 0) { + if (newline > 32 * 1024 * 1024) return socket.destroy(); + const line = pending.slice(0, newline); + pending = pending.slice(newline + 1); + try { + receive(JSON.parse(line) as Frame); + } catch { + return socket.destroy(); + } + } + if (pending.length > 32 * 1024 * 1024) socket.destroy(); + }); + return (frame) => { + if (socket.destroyed || socket.writableLength > 32 * 1024 * 1024) { + socket.destroy(); + throw new Error("Runner connection is unavailable"); + } + socket.write(JSON.stringify(frame) + "\n"); + }; +} + +export function hostChannel(id: string, send: Send, dispose: () => void) { + return new Duplex({ + allowHalfOpen: false, + read() {}, + write(chunk: Buffer, _encoding, callback) { + try { + send({ type: "data", id, data: chunk.toString("base64") }); + callback(); + } catch (error) { + callback(error as Error); + } + }, + destroy(error, callback) { + dispose(); + try { + send({ type: "close", id }); + } catch { + /* transport already closed */ + } + callback(error); + }, + }); +} diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts new file mode 100644 index 000000000..157e31d1e --- /dev/null +++ b/apps/server/src/agents/remote/runner.ts @@ -0,0 +1,345 @@ +import { spawn, execFile, type ChildProcess } from "node:child_process"; +import { closeSync, openSync, readFileSync } from "node:fs"; +import { + mkdir, + writeFile, + readFile, + rm, + chown, + chmod, + stat, +} from "node:fs/promises"; +import { createConnection } from "node:net"; +import path from "node:path"; +import { connect } from "node:tls"; +import { promisify } from "node:util"; +import { hostFile, type HostLaunch } from "../acp/host-protocol.js"; +import { + ownedEnvironment, + killOwnedProcesses, +} from "../../shared/process/owned-processes.js"; +import { hostCommand } from "../acp/runtime.js"; +import { wireFrames, type Command, type Frame } from "./protocol.js"; + +type RunnerConfig = { + endpoint: string; + ca: string; + trustBundle?: string; + cert: string; + key: string; + state: string; + uid: number; + gid: number; + home: string; + path: string; + bins: HostLaunch["bins"]; + adapter?: string[]; + workspaces: Record; +}; + +const execute = promisify(execFile); + +export async function runRemoteRunner(filename: string) { + const config: RunnerConfig = JSON.parse(readFileSync(filename, "utf8")); + const endpoint = new URL(config.endpoint); + if ( + endpoint.protocol !== "https:" || + !config.uid || + !config.gid || + process.getuid?.() !== 0 + ) { + throw new Error( + "Runner requires an HTTPS endpoint and a separate, non-root execution account." + ); + } + const credentials = { + ca: readFileSync(config.ca), + cert: readFileSync(config.cert), + key: readFileSync(config.key), + }; + const bindings = path.join(config.state, "bindings"); + const hostRoot = path.join(config.state, "hosts"); + const logs = path.join(bindings, "logs"); + await mkdir(logs, { recursive: true, mode: 0o700 }); + await chmod(config.state, 0o711); + await mkdir(hostRoot, { recursive: true, mode: 0o711 }); + const identity = { uid: config.uid, gid: config.gid }; + const env = { + HOME: config.home, + PATH: config.path, + SHELL: "/bin/bash", + NODE_EXTRA_CA_CERTS: config.ca, + ...(config.trustBundle ? { SSL_CERT_FILE: config.trustBundle } : {}), + ...(config.adapter + ? { DISPATCH_ACP_ADAPTER_COMMAND: JSON.stringify(config.adapter) } + : {}), + }; + const hosts = new Map(); + const active = new Set(); + const owns = async (id: string, workspace: string) => + (await readFile(path.join(bindings, id), "utf8").catch(() => null)) === + workspace; + + async function launch( + command: Extract, + cwd: string + ) { + const { agentId, workspace } = command; + if (hosts.has(agentId) || active.has(agentId)) + throw new Error("Runner already has a host for this agent"); + active.add(agentId); + try { + const binding = path.join(bindings, agentId); + await writeFile(binding, workspace, { flag: "wx", mode: 0o600 }).catch( + async (error) => { + if (error.code !== "EEXIST" || !(await owns(agentId, workspace))) + throw error; + } + ); + if (!(await stat(cwd)).isDirectory()) + throw new Error("Guest workspace is unavailable"); + const dir = path.join(hostRoot, agentId); + const files = path.join(dir, "files"); + const launch: HostLaunch = { + ...command.launch, + agentId, + cwd, + bins: config.bins, + env: { + DISPATCH_AGENT_ID: agentId, + DISPATCH_FILES_DIR: files, + DISPATCH_API_URL: new URL(command.launch.mcp.url).origin, + NODE_EXTRA_CA_CERTS: config.ca, + }, + pathPrefix: [], + }; + // Write only into a fresh directory: a previous CLI account could have + // replaced anything under its old host directory with symlinks. + await rm(dir, { force: true, recursive: true }); + await mkdir(dir, { mode: 0o700 }); + await mkdir(files, { mode: 0o700 }); + await chown(files, config.uid, config.gid); + await writeFile(hostFile(dir, "launch"), JSON.stringify(launch), { + mode: 0o600, + }); + await chown(hostFile(dir, "launch"), config.uid, config.gid); + await chown(dir, config.uid, config.gid); + const log = openSync(path.join(logs, agentId), "a", 0o600); + try { + const [bin, ...args] = hostCommand(); + if (!bin) throw new Error("Runner host executable is missing"); + const owned = ownedEnvironment(env); + const child = spawn(bin, [...args, "--state", dir], { + ...identity, + cwd, + env: owned.env, + detached: true, + stdio: ["ignore", log, log], + }); + hosts.set(agentId, child); + const forget = () => { + if (hosts.get(agentId) === child) hosts.delete(agentId); + }; + child.on("exit", () => { + try { + killOwnedProcesses(owned.marker); + } catch (error) { + console.error( + "Guest host descendant cleanup:", + (error as Error).message + ); + } finally { + forget(); + } + }); + child.on("error", forget); + await new Promise((resolve, reject) => { + child.once("spawn", resolve); + child.once("error", reject); + }); + child.unref(); + } finally { + closeSync(log); + } + } finally { + active.delete(agentId); + } + } + + while (true) { + await new Promise((finished) => { + const socket = connect({ + ...credentials, + host: endpoint.hostname, + port: Number(endpoint.port || 443), + servername: endpoint.hostname, + rejectUnauthorized: true, + }); + const channels = new Map>(); + const timeout = setTimeout(() => socket.destroy(), 5000); + socket.on("error", (error: Error) => + console.error("Runner transport:", error.message) + ); + socket.on("close", () => { + clearTimeout(timeout); + for (const channel of channels.values()) channel.destroy(); + finished(); + }); + const safeSend = (frame: Frame) => { + if (!socket.destroyed) { + try { + send(frame); + } catch { + socket.destroy(); + } + } + }; + + async function request(id: string, command: Command) { + if (!/^[a-f0-9-]{36}$/.test(id)) + throw new Error("Invalid runner request ID"); + if (socket.destroyed) return; + const { agentId, workspace } = command; + const target = Object.hasOwn(config.workspaces, workspace) + ? config.workspaces[workspace] + : undefined; + if (!/^agt_[a-z0-9]+$/.test(agentId) || !target) + throw new Error("Unknown runner workspace or agent"); + const result = (value?: string | boolean) => + safeSend({ type: "result", id, value }); + if (command.kind === "launch") { + await launch(command, target.cwd); + result(true); + return; + } + if (!(await owns(agentId, workspace))) { + if (command.kind === "alive") return result(false); + throw new Error("Agent is not bound to this workspace"); + } + if (socket.destroyed) return; + const host = hosts.get(agentId); + const dir = path.join(hostRoot, agentId); + switch (command.kind) { + case "attach": { + if (!host) { + safeSend({ + type: "result", + id, + code: "host-gone", + error: "Guest agent host has exited.", + }); + break; + } + const channel = createConnection(hostFile(dir, "socket")); + channels.set(id, channel); + channel.once("connect", () => result(true)); + channel.on("data", (chunk: Buffer) => + safeSend({ type: "data", id, data: chunk.toString("base64") }) + ); + channel.on("error", () => { + safeSend({ + type: "result", + id, + error: "Guest host socket is unavailable", + }); + channel.destroy(); + }); + channel.on("close", () => { + channels.delete(id); + safeSend({ type: "close", id }); + }); + break; + } + case "alive": + result(Boolean(host)); + break; + case "stop": + if (host?.pid) { + const exited = new Promise((resolve) => + host.once("exit", () => resolve()) + ); + const signal = (value: NodeJS.Signals) => { + try { + process.kill(-host.pid!, value); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") + throw error; + } + }; + const timer = setTimeout(() => signal("SIGKILL"), 8_000); + signal(command.force ? "SIGKILL" : "SIGTERM"); + try { + await exited; + } finally { + clearTimeout(timer); + } + } + result(true); + break; + case "discard": + if (host || active.has(agentId)) + throw new Error("Stop the guest host before discarding it"); + await rm(dir, { force: true, recursive: true }); + await rm(path.join(bindings, agentId), { force: true }); + result(true); + break; + case "log": { + const log = await readFile(path.join(logs, agentId), "utf8").catch( + () => "" + ); + result( + `Guest agent host ${host ? "log" : "exited"}.${log ? "\n" + log.slice(-2048) : ""}` + ); + break; + } + case "repo": { + const [bin, ...args] = target.repoTool ?? []; + if (!bin) + throw new Error( + "Runner workspace has no approved repo operation" + ); + const { stdout } = await execute(bin, args, { + ...identity, + cwd: target.cwd, + env, + timeout: 10_000, + maxBuffer: 64 * 1024, + }); + result(stdout); + break; + } + } + } + + const send = wireFrames(socket, (frame) => { + if (frame.type === "request") { + void request(frame.id, frame.command).catch((error) => + safeSend({ + type: "result", + id: frame.id, + error: + error instanceof Error + ? error.message + : "Runner command failed", + }) + ); + } else if (frame.type === "data") { + const channel = channels.get(frame.id); + if (channel && channel.writableLength > 32 * 1024 * 1024) + channel.destroy(); + else channel?.write(Buffer.from(frame.data, "base64")); + } else if (frame.type === "close") channels.get(frame.id)?.destroy(); + else socket.destroy(); + }); + socket.once("secureConnect", () => { + clearTimeout(timeout); + safeSend({ + type: "ready", + version: 1, + workspaces: Object.keys(config.workspaces), + }); + }); + }); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } +} diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts new file mode 100644 index 000000000..2dc423cd4 --- /dev/null +++ b/apps/server/src/agents/remote/service.ts @@ -0,0 +1,198 @@ +import { readFileSync, watchFile, unwatchFile } from "node:fs"; +import { createServer, type TLSSocket } from "node:tls"; +import type { Duplex } from "node:stream"; +import { + hostChannel, + wireFrames, + type Command, + type Frame, + type Placement, +} from "./protocol.js"; + +type Config = { + id: string; + host: string; + port: number; + cert: string; + key: string; + ca: string; + approval: string; + workspaces: string[]; + mcpOrigin: string; + repoTool?: boolean; +}; + +export class RunnerUnavailable extends Error {} +export class RunnerHostGone extends Error {} + +export function configuredRunner() { + const filename = process.env.DISPATCH_REMOTE_SERVICE_CONFIG; + return filename + ? new RemoteRunnerService(JSON.parse(readFileSync(filename, "utf8"))) + : undefined; +} + +export class RemoteRunnerService { + private peer?: { + socket: TLSSocket; + send: (frame: Frame) => void; + workspaces: Set; + }; + private readonly sockets = new Set(); + private readonly channels = new Map(); + private readonly pending = new Map< + string, + (frame?: Extract) => void + >(); + private listener?: ReturnType; + + constructor(private readonly config: Config) { + if (new URL(config.mcpOrigin).protocol !== "https:") + throw new Error("Runner MCP origin must use HTTPS"); + } + + get origin() { + return this.config.mcpOrigin.replace(/\/$/, ""); + } + get repoTool() { + return this.config.repoTool === true; + } + + private approved(socket: TLSSocket) { + try { + return ( + socket.authorized && + socket.getPeerCertificate().fingerprint256 === + readFileSync(this.config.approval, "utf8").trim() + ); + } catch { + return false; + } + } + + async start() { + const { host, port, ca, cert, key, approval } = this.config; + const listener = createServer( + { + ca: readFileSync(ca), + cert: readFileSync(cert), + key: readFileSync(key), + requestCert: true, + rejectUnauthorized: true, + }, + (socket) => this.accept(socket) + ); + this.listener = listener; + await new Promise((resolve, reject) => { + listener.once("error", reject); + listener.listen(port, host, resolve); + }); + watchFile(approval, { interval: 500, persistent: false }, this.recheck); + } + + private recheck = () => { + for (const socket of this.sockets) + if (!this.approved(socket)) socket.destroy(); + }; + + private accept(socket: TLSSocket) { + socket.on("error", () => socket.destroy()); + if (!this.approved(socket) || this.sockets.size) return socket.destroy(); + this.sockets.add(socket); + const deadline = setTimeout(() => socket.destroy(), 5000); + socket.on("close", () => { + clearTimeout(deadline); + this.sockets.delete(socket); + this.peer = undefined; + for (const settle of this.pending.values()) settle(); + for (const channel of this.channels.values()) channel.push(null); + }); + const send = wireFrames(socket, (frame) => { + if (!this.approved(socket)) return socket.destroy(); + if (!this.peer) { + if ( + frame.type !== "ready" || + frame.version !== 1 || + !Array.isArray(frame.workspaces) + ) + return socket.destroy(); + clearTimeout(deadline); + this.peer = { socket, send, workspaces: new Set(frame.workspaces) }; + return; + } + if (frame.type === "result") this.pending.get(frame.id)?.(frame); + else if (frame.type === "data") + this.channels.get(frame.id)?.push(Buffer.from(frame.data, "base64")); + else if (frame.type === "close") this.channels.get(frame.id)?.push(null); + else socket.destroy(); + }); + } + + available(placement: Placement) { + return ( + placement.runner === this.config.id && + this.config.workspaces.includes(placement.workspace) && + Boolean( + this.peer?.workspaces.has(placement.workspace) && + this.approved(this.peer.socket) + ) + ); + } + + async request(placement: Placement, command: Command, open = false) { + const peer = this.peer; + if ( + !peer || + !this.available(placement) || + command.workspace !== placement.workspace + ) { + throw new RunnerUnavailable( + "The enrolled runner is disconnected or the workspace is unavailable." + ); + } + const id = crypto.randomUUID(); + const channel = open + ? hostChannel(id, peer.send, () => this.channels.delete(id)) + : undefined; + // The HostClient takes over error handling after the attach acknowledgement. + channel?.on("error", () => {}); + if (channel) this.channels.set(id, channel); + try { + const value = await new Promise( + (resolve, reject) => { + const finish = (frame?: Extract) => { + clearTimeout(timer); + this.pending.delete(id); + if (!frame) + reject( + new RunnerUnavailable( + "Runner acknowledgement was lost; execution is unknown." + ) + ); + else if (frame.code === "host-gone") + reject(new RunnerHostGone(frame.error)); + else if (frame.error) reject(new Error(frame.error)); + else resolve(frame.value); + }; + const timer = setTimeout(() => finish(), 20_000); + this.pending.set(id, finish); + try { + peer.send({ type: "request", id, command }); + } catch { + finish(); + } + } + ); + return { value, channel }; + } catch (error) { + channel?.destroy(); + throw error; + } + } + + close() { + unwatchFile(this.config.approval, this.recheck); + for (const socket of this.sockets) socket.destroy(); + this.listener?.close(); + } +} diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index c342ad72c..0bf8e4c23 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -6,6 +6,7 @@ import type { AgentPermissionsResponse } from "@dispatch/shared"; import type { PromptSource, PromptOptions } from "./acp/prompt-source.js"; import type { FastifyBaseLogger } from "fastify"; +import type { Placement } from "./remote/protocol.js"; import type { AppConfig } from "../config.js"; import type { DriverEvent } from "./acp/driver.js"; import type { @@ -23,6 +24,7 @@ import { createAcpRuntime, type AcpRuntimeDeps } from "./acp/runtime.js"; export type RuntimeLaunch = { agentId: string; cwd: string; + placement?: Placement; engine: AcpEngineId; /** Missing only in launch files written before permission support (full access). */ fullAccess?: boolean; @@ -144,7 +146,10 @@ export type AgentRuntime = { export function createAgentRuntime( config: AppConfig, logger: FastifyBaseLogger, - deps: Pick + deps: Pick< + AcpRuntimeDeps, + "hostSeq" | "syncJournal" | "classifySteering" | "remote" | "placement" + > ): AgentRuntime { if (config.agentRuntime === "inert") { return createInertRuntime(); diff --git a/apps/server/src/agents/workspace-target.ts b/apps/server/src/agents/workspace-target.ts index 3cfd1977c..b6681562c 100644 --- a/apps/server/src/agents/workspace-target.ts +++ b/apps/server/src/agents/workspace-target.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "./remote/protocol.js"; import { realpath, stat } from "node:fs/promises"; import path from "node:path"; @@ -35,6 +36,7 @@ export type WorkspaceTargetAgent = { const DEFAULT_WORKTREE_BASE_BRANCH = "main"; export function agentWorkspaceDir(agent: WorkspaceTargetAgent): string | null { + if (agent.cwd && remotePlacement(agent.cwd)) return null; return agent.workspacePath ?? agent.worktreePath ?? agent.cwd ?? null; } @@ -47,6 +49,7 @@ export function agentWorkspaceDir(agent: WorkspaceTargetAgent): string | null { export function agentDiffTarget( agent: WorkspaceTargetAgent ): { path: string; baseRef: string | null } | null { + if (agent.cwd && remotePlacement(agent.cwd)) return null; if (agent.workspacePath) { return { path: agent.workspacePath, diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 3f2465d19..d1d14c6fa 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -37,6 +37,9 @@ if (process.argv[2]?.startsWith("recovery-")) { process.env.DISPATCH_HOST ?? "127.0.0.1", ] ); +} else if (process.argv[2] === "remote-runner") { + const { runRemoteRunner } = await import("./agents/remote/runner.js"); + await runRemoteRunner(process.argv[3]!); } else if (process.argv[2] === "agent-host") { await import("./agents/acp/host/main.js"); } else if (process.argv[2] === "claude-acp") { diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index 7a0ef45f3..a46e10c4e 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -12,6 +12,7 @@ import { getEnabledAgentTypes } from "../agent-type-settings.js"; import { createProviderPlansReporter } from "../agents/provider-plans.js"; import type { UsageCallbacks } from "../shared/mcp/usage-tools.js"; import type { AgentManager } from "../agents/manager.js"; +import { remotePlacement } from "../agents/remote/protocol.js"; import { agentWorkspaceDir } from "../agents/workspace-target.js"; import * as telemetry from "../agents/telemetry.js"; import type { LoginLinkStore } from "../auth.js"; @@ -207,8 +208,10 @@ export async function registerMcpRoutes( // Repo tools, brain and job defaults follow a moved workspace. const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; try { - repoRoot = await resolveRepoRoot(workspaceDir); - worktreeRoot = await resolveWorktreeRoot(workspaceDir); + if (!remotePlacement(agent.cwd)) { + repoRoot = await resolveRepoRoot(workspaceDir); + worktreeRoot = await resolveWorktreeRoot(workspaceDir); + } } catch {} const jobTools = run @@ -332,8 +335,10 @@ export async function registerMcpRoutes( // Repo tools, brain and job defaults follow a moved workspace. const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; try { - repoRoot = await resolveRepoRoot(workspaceDir); - worktreeRoot = await resolveWorktreeRoot(workspaceDir); + if (!remotePlacement(agent.cwd)) { + repoRoot = await resolveRepoRoot(workspaceDir); + worktreeRoot = await resolveWorktreeRoot(workspaceDir); + } } catch {} reply.hijack(); @@ -372,6 +377,10 @@ export async function registerMcpRoutes( }, repoRoot, worktreeRoot, + remoteRepoOperation: + bearerToken && remotePlacement(agent.cwd) + ? deps.agentManager.remoteRepoOperation(agent) + : undefined, sendNotify: deps.mcpSendNotify, renameSession: deps.mcpRenameSession, setWorkspace: deps.mcpSetWorkspace, diff --git a/apps/server/src/routes/system.ts b/apps/server/src/routes/system.ts index eda53296b..e5c68ca36 100644 --- a/apps/server/src/routes/system.ts +++ b/apps/server/src/routes/system.ts @@ -1,3 +1,4 @@ +import { remotePlacement, type Placement } from "../agents/remote/protocol.js"; import { isAllowedSlackLinkOrigin, type SlackLinkOrigins, @@ -56,6 +57,7 @@ import { ACP_ENGINE_IDS, type AcpEngineId } from "../agents/acp/engine-spec.js"; const INSTANCE_NAME_KEY = "instance_name"; type SystemRouteDeps = { + runnerWorkspaceAvailable?: (placement: Placement) => boolean; notificationLinkOrigins?: () => Promise; slackAnswers?: Pick< SlackAnswers, @@ -196,6 +198,16 @@ export async function registerSystemRoutes( .send({ error: "path query parameter is required." }); } const resolved = resolveTilde(query.path.trim()); + const placement = remotePlacement(resolved); + if (placement) { + const available = deps.runnerWorkspaceAvailable?.(placement) ?? false; + return { + exists: available, + isDirectory: available, + isGitRepo: false, + resolvedPath: resolved, + }; + } if (!path.isAbsolute(resolved)) { return { exists: false, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 4e89f0472..e7d44d72e 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -121,6 +121,7 @@ import { registerTemplateRoutes } from "./routes/templates.js"; import { registerFileRoutes } from "./routes/files.js"; import { registerStreamRoutes } from "./routes/streams.js"; import { StreamService, type TaskStreamRoot } from "./chat/service.js"; +import { configuredRunner } from "./agents/remote/service.js"; import { registerMcpRoutes } from "./routes/mcp.js"; import { registerPersonaRoutes } from "./routes/personas.js"; import { registerPersonalityRoutes } from "./routes/personalities.js"; @@ -204,7 +205,9 @@ const pool = createPool(config); const serviceResourcesProbePool = createServiceResourcesProbePool(config); const routingSettings = new RoutingSettings(pool); const steeringDecisions = new SteeringDecisions(pool, routingSettings); +const remoteRunner = configuredRunner(); const agentManager = new AgentManager(pool, app.log, config, { + remote: remoteRunner, classifySteering: steeringDecisions.classify, }); const focusTracker = new FocusTracker(); @@ -1080,6 +1083,8 @@ async function registerRoutes() { await registerScheduledMessageRoutes(app, scheduledMessages); await registerSystemRoutes(app, { + runnerWorkspaceAvailable: (placement) => + remoteRunner?.available(placement) ?? false, slackAnswers, notificationLinkOrigins: () => { const primary = app.server.address(); @@ -1409,6 +1414,7 @@ let closeAdditionalListeners: (() => Promise) | undefined; let stopLocalTlsWatch: (() => void) | undefined; export async function start() { + await remoteRunner?.start(); await initializeApp(); const protocol = config.tls ? "https" : "http"; @@ -1480,6 +1486,7 @@ async function cleanupAppResources(): Promise { return; } shuttingDown = true; + remoteRunner?.close(); const stage = async (name: string, close: () => Promise) => { app.log.info({ stage: name }, "Shutdown stage started"); await close(); diff --git a/apps/server/src/shared/mcp/server.ts b/apps/server/src/shared/mcp/server.ts index 19964941b..1de2ba56e 100644 --- a/apps/server/src/shared/mcp/server.ts +++ b/apps/server/src/shared/mcp/server.ts @@ -276,6 +276,7 @@ export type McpRequestContext = UsageCallbacks & { scheduledMessages?: ScheduledMessageService; agent: McpAgent | null; repoRoot: string | null; + remoteRepoOperation?: () => Promise; worktreeRoot: string | null; /** * Publishes `agent.tool_invoked` for every tool call on this server @@ -624,6 +625,23 @@ export async function createDispatchMcpServer( registerJobTools(server, context.agent.id, context.jobTools); } + if (context.remoteRepoOperation) { + const run = context.remoteRepoOperation; + server.registerTool( + "repo_runner_workspace", + { + description: + "Run the enrolled workspace's approved repository operation.", + }, + async () => { + try { + return { content: [{ type: "text", text: await run() }] }; + } catch (error) { + return toToolError(error); + } + } + ); + } const toolsRoot = context.worktreeRoot ?? context.repoRoot; if (context.agent && toolsRoot) { const allRepoTools = await loadRepoTools(toolsRoot); diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index 179db2f30..875e85eee 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -13,6 +13,8 @@ import { writeFileSync, } from "node:fs"; import os from "node:os"; +import net from "node:net"; +import { once } from "node:events"; import { spawn, execFileSync } from "node:child_process"; import { pathToFileURL } from "node:url"; import path from "node:path"; @@ -20,6 +22,11 @@ import { fileURLToPath } from "node:url"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + encodeMessage, + ndjsonDecoder, + type HostMessage, +} from "../src/agents/acp/host-protocol.js"; import type { DriverEvent } from "../src/agents/acp/driver.js"; import { createAcpRuntime } from "../src/agents/acp/runtime.js"; import { buildSystemPrompt } from "../src/agents/acp/system-prompt.js"; @@ -591,6 +598,75 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); expect(await replacement.runtime.listHosted()).toEqual([]); }, 60_000); + it("replays a remote prompt receipt after a lost acknowledgement without invoking the provider again", async () => { + const id = "agt_host_receipt"; + const { runtime } = runtimeWith(stateRoot, () => 0); + const launch = launchFor(id, cwd); + launch.bins.adapter = { + bin: "bun", + args: [path.join(here, "helpers/remote-acp-fixture.ts")], + }; + await runtime.launch(launch); + const dir = path.join(stateRoot, id); + async function attach() { + const messages: HostMessage[] = []; + const socket = net.createConnection(path.join(dir, "host.sock")); + const decode = ndjsonDecoder(); + socket.on("data", (chunk) => messages.push(...decode(chunk))); + await once(socket, "connect"); + socket.write( + encodeMessage({ type: "hello", fromSeq: 0, replayComplete: true }) + ); + await until(() => + messages.some((message) => message.type === "replay_complete") + ); + return { socket, messages }; + } + const first = await attach(); + const welcome = first.messages.find( + (message) => message.type === "welcome" + )!; + const command = { + type: "prompt", + id: "first-operation", + text: "proof-count proof-delay:150", + journalId: welcome.journalId, + }; + // Keep the write but discard the response, as a transport that loses the ack. + first.socket.removeAllListeners("data"); + first.socket.write(encodeMessage(command)); + await until(() => { + try { + return readFileSync(path.join(dir, "journal.jsonl"), "utf8").includes( + '"state":"settled"' + ); + } catch { + return false; + } + }); + first.socket.destroy(); + + const second = await attach(); + try { + second.socket.write(encodeMessage(command)); + await until(() => + second.messages.some((message) => message.type === "prompt_accepted") + ); + expect(readFileSync(path.join(cwd, "provider-invocations"), "utf8")).toBe( + "called\n" + ); + const turns = second.messages.flatMap((message) => + message.type === "event" && message.event.type === "turn" + ? [message.event.state] + : [] + ); + expect(turns).toEqual(["started", "settled"]); + } finally { + second.socket.destroy(); + await runtime.stop(id, true); + } + }, 15_000); + it("reads structured inventory through the host and runtime without journalling a turn", async () => { const id = "agt_host_inventory"; const { runtime, seen } = runtimeWith(stateRoot, () => 0); diff --git a/apps/server/test/helpers/remote-acp-fixture.ts b/apps/server/test/helpers/remote-acp-fixture.ts new file mode 100644 index 000000000..41fe5d5cd --- /dev/null +++ b/apps/server/test/helpers/remote-acp-fixture.ts @@ -0,0 +1,98 @@ +// A standalone deterministic ACP provider for the isolated runner proof. +import { appendFile, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { createFakeAcpAgent } from "./fake-acp-agent.js"; + +const fake = createFakeAcpAgent({ + async turn(prompt, emit, ask) { + const session = + fake.seen.newSession.at(-1) ?? fake.seen.resumeSession.at(-1)!; + const report = (text: string) => + emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text }, + }); + if ( + session.cwd.startsWith("/opt/dispatch-guest-") || + prompt.includes("proof-count") + ) { + await appendFile( + path.join(session.cwd, "provider-invocations"), + "called\n" + ); + } + const sleep = /proof-delay:(\d+)/.exec(prompt); + if (sleep) { + await report("Guest turn waiting for reconnect."); + await new Promise((resolve) => setTimeout(resolve, Number(sleep[1]))); + } + if (prompt.includes("prove-permission")) { + const answer = await ask({ + options: [ + { kind: "allow_once", name: "Allow once", optionId: "allow" }, + { kind: "reject_once", name: "Deny", optionId: "deny" }, + ], + }); + if ( + answer.outcome.outcome === "selected" && + answer.outcome.optionId === "allow" + ) { + await writeFile( + path.join(session.cwd, "protected-action"), + "allowed\n" + ); + } + await report("Guest permission answered."); + } + if (prompt.includes("prove-marker")) { + const marker = ( + await readFile(path.join(session.cwd, "marker.txt"), "utf8") + ).trim(); + await report(`Guest marker ${marker}`); + const endpoint = session.mcpServers.find( + (entry) => "url" in entry && "headers" in entry + ); + if (!endpoint || !("url" in endpoint) || !("headers" in endpoint)) + throw new Error("Missing Dispatch MCP endpoint"); + const client = new Client({ + name: "dispatch-runner-fixture", + version: "1", + }); + await client.connect( + new StreamableHTTPClientTransport(new URL(endpoint.url), { + requestInit: { + headers: Object.fromEntries( + endpoint.headers.map(({ name, value }) => [name, value]) + ), + }, + }) + ); + try { + const post = await client.callTool({ + name: "post", + arguments: { text: `Posted from Lima: ${marker}` }, + }); + if (post.isError) throw new Error(JSON.stringify(post.content)); + const repo = await client.callTool({ + name: "repo_runner_workspace", + arguments: {}, + }); + if (repo.isError) throw new Error(JSON.stringify(repo.content)); + await report( + ` Approved repo operation: ${JSON.stringify(repo.content)}` + ); + } finally { + await client.close(); + } + } else if (!sleep) { + await report("Local or guest fixture turn completed."); + } else { + await report(" Guest turn completed after reconnect."); + } + return "end_turn"; + }, +}); +process.stdin.pipe(fake.child.stdin); +fake.child.stdout.pipe(process.stdout); diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md new file mode 100644 index 000000000..d50507476 --- /dev/null +++ b/docs/design/remote-runner-prototype.md @@ -0,0 +1,144 @@ +# Dispatch remote runner prototype + +Dispatch keeps the agent row, conversation, prompt queue, MCP authorization, and +stream projection. The runner opens an outbound mTLS connection and owns the +workspace, ACP host, engine executable, and guest process lifecycle. The normal +Create Agent dialog accepts a pre-approved workspace locator such as +`runner://lima/proof` in Folder. Dispatch stores that locator in the agent's +existing `cwd` field. The runner resolves the locator to a guest-local absolute +path. The Create with context action creates the normal launch post and first +turn. + +## Setup + +Build the Linux artifact from this checkout. For x86-64 use the matching Bun +target. The server and runner use the same source entry point. + +```sh +bun scripts/generate-server-runtime-assets.mjs +bun build --compile --target=bun-linux-arm64 apps/server/src/main.ts \ + --outfile /tmp/dispatch-runner +``` + +Set `DISPATCH_REMOTE_SERVICE_CONFIG` on an isolated Dispatch service. The +service JSON names one registration `id`, listener `host` and `port`, PEM +paths `ca`, `cert`, and `key`, an `approval` file containing the approved +client certificate's SHA-256 fingerprint, a list of approved `workspaces`, and +the guest-reachable HTTPS `mcpOrigin`. Set `repoTool` to true to expose the +approved repository operation. For the Lima proof the API stayed on the dev +stack's own loopback port and a scoped HTTPS front end forwarded `/ping` and +agent MCP routes. The server certificate included `host.lima.internal` in its +SAN. Empty the approval file to revoke the live connection and prevent further +attachment. Reapproval restores access to the same registration. + +Run `dispatch-runner remote-runner /etc/dispatch-proof/runner.json` under a +Linux service supervisor. The root-owned runner JSON names the HTTPS +`endpoint`, trust and enrollment PEM paths `ca`, `cert`, and `key`, the +dedicated `state` directory, guest CLI `uid`, `gid`, `home`, and `path`, +engine `bins`, and a `workspaces` object keyed by handle. Each workspace +defines its guest `cwd` and can define a fixed `repoTool` argv array. The +optional `trustBundle` supplies a combined system and test trust bundle for +clients that use `SSL_CERT_FILE`. There is a guest-local `adapter` override +for the fake provider. Keep the enrollment key and runner settings root-only +and the CA certificate readable by the CLI. The child starts under the +configured non-root account with a constructed environment and receives only +the scoped MCP credential and guest paths. Use test credentials, disable VM +mounts and SSH-agent forwarding, and keep the VM and dev data disposable. + +## Wire contract + +The runner sends `ready` with protocol version 1 and its workspace handles. +The service requires a trusted client certificate, a matching manual approval +fingerprint, and a workspace in both sides' configuration. A service request +names an agent ID, workspace, operation, and a per-connection correlation ID. +The runner stores the agent-to-workspace binding in its private state and +rechecks it on every attach and workspace operation. Reply frames correlate +results or errors to the request. Transport close drops channels, while +established guest hosts continue. The client checks the service hostname. + +- `launch` sends engine, model and effort, access and prompt metadata, and + agent-scoped MCP URL and token. Guest configuration supplies the checkout, + binary, environment, and writable state. The launch receipt means the host + was spawned. The host's running `welcome` confirms the ACP session. +- `attach` opens a channel to the bound guest host's Unix socket. The host + protocol is carried as opaque bytes in `data` frames. `hello` names the + last applied sequence and journal identity, and `welcome` reports the + running session, journal head, open turn, capabilities, and permissions. + Replay follows in sequence and ends with `replay_complete`. A different + identity or a cursor past the head restarts replay. Dispatch stores the + journal ID and cursor in PostgreSQL and drops repeated sequences. +- `prompt` uses an operation ID and journal ID. Dispatch flushes the ID and + source blocks to its scoped agent state before sending. The host flushes its + claim before handing the prompt to ACP and its accepted receipt before + replying. Acceptance confirms handoff to ACP. Retrying an accepted ID on the + same journal returns its receipt without invoking the provider. A claimed + ID without a receipt or an ID addressed to the wrong journal reports an + unknown outcome. Dispatch surfaces a lost acknowledgement and never + automatically resubmits that prompt. A terminal event independently settles + the projected turn. +- Pending permissions appear as `permissions` messages and are also included + in `welcome`. `answer_permission` is scoped to the pending request and + returns `permission_answered`. `cancel` and the sequence-targeted + `interrupt` use the existing host handlers. `interrupt_result` confirms + the cancel call returned. The turn's terminal event reports the outcome. +- `alive`, `stop`, `log`, and `discard` operate at the runner. A missing + transport is an unknown liveness result. A connected runner can report a + known missing host. On host exit the runner cleans up remaining processes + with the launch's inherited ownership marker. +- `repo_runner_workspace` is available only on the authenticated agent MCP + route for a remote placement and an explicitly enabled service. It has no + caller-controlled arguments. The runner executes the approved workspace + command as the guest CLI account and returns its bounded stdout. Product + `post` runs through the usual Dispatch MCP route and permissions. + +## Observed traces + +The initial fake-agent turn ran as `agt_4643ddec746a`. The UI showed +`3ce751fe-1cda-42fe-9c7a-cdf03b4b0a92` from the guest-only marker and the +same value in its MCP post. On the restricted launch +`agt_240a31e28e6a`, Dispatch showed the permission request. Denying it left +the protected action file absent. The approved repo operation wrote +`/opt/dispatch-guest-b87cc218` to a file in the guest checkout. The ordinary +Mac launch path completed before and after the guest proof. + +For service restart, the guest journal opened the turn at sequence 7 and +produced its first chunk at 8. A scoped Dispatch restart replaced the service +process. The guest retained PID 1917, session `sess_1`, and journal +`1c98b164-0222-4d67-8c56-172f8819e496`. The resumed projection showed one +completion. A separate guest network interruption reset the connection and +briefly blocked only the runner port while the HTTPS MCP listener stayed +reachable. The same guest showed one completed turn after reconnect. Killing +the guest host during another turn caused Dispatch to mark that turn interrupted. +The certificate proof observed the established connection disappear on +revocation, rejected both a CA-signed unapproved certificate and a peer with no +certificate, and showed that the revoked client could reconnect only after +reapproval. + +A separate wire probe dropped the return path immediately after writing prompt +`6869a0de-ea67-470b-9376-737431421dd5` to the Lima guest host. Retrying that ID +on the same journal returned `prompt_accepted`. The fake provider counter +increased by exactly one and the journal contained one terminal event. The +regression test in `test/acp-host.test.ts` repeats the receipt and counter check +with the real ACP host and fake provider. + +Real CLI acceptance used OpenCode 1.19.6 on Linux arm64 with the anonymous +`opencode/glm-5.3-flash-free` model and synthetic fixture data. The CLI read a +fresh marker `e065e5ae-2f73-4d65-a88b-1f2ed704fa4e` in +`agt_d8b725faeaae`, posted it into the launch discussion and ran the approved +repo operation. A later stop from the normal Dispatch composer settled with +`stopReason: cancelled` in the same guest journal. The provider reported zero +cost. The installed runner's SHA-256 +was `6f168024ce1d1db0d0a2c07039f6836fb070b0d0d6aa4d5b71aea56b141baedd`. + +## Exit decision + +The Lima slice supports bounded operations for launching, attaching, prompting, +permissions, stopping, and invoking an approved repo tool. It supports trying the +same Linux artifact on a second host. General scheduling, checkout provisioning, +arbitrary repo tool manifests, file transfer and git views are still machine-local +features outside this slice. The implementation supports one manually enrolled +runner and pre-provisioned standalone workspaces. Full restart recovery of the +runner daemon itself requires work beyond the service and network reconnect +tested here. The guest connection uses Lima's host-loopback reachability and +establishes process and filesystem separation. A second host and a Hangar adapter +are separate acceptance gates. From 1ec3b7b17d2dddeb46798aca49eb7d4f8c3848d5 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 21:12:58 -0700 Subject: [PATCH 002/642] Enforce Linux runner privilege separation before enrollment --- apps/server/src/agents/remote/runner.ts | 128 +++++++++++++++++++----- docs/design/remote-runner-prototype.md | 12 ++- 2 files changed, 110 insertions(+), 30 deletions(-) diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 157e31d1e..3707c90c8 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -38,20 +38,97 @@ type RunnerConfig = { }; const execute = promisify(execFile); +const setpriv = "/usr/bin/setpriv"; + +function validExecutionId(value: number) { + return Number.isInteger(value) && value > 0 && value < 0xffffffff; +} + +// Bun versions disagree on whether spawn and execFile apply uid/gid. Make +// the kernel privilege transition the same for the ACP host and repo tools. +function executionArgs(uid: number, gid: number) { + return [ + `--reuid=${uid}`, + `--regid=${gid}`, + "--clear-groups", + "--no-new-privs", + "--inh-caps=-all", + "--ambient-caps=-all", + "--bounding-set=-all", + "--", + ]; +} + +async function verifyExecutionIdentity( + uid: number, + gid: number, + args: string[], + env: NodeJS.ProcessEnv +) { + try { + const { stdout } = await execute( + setpriv, + [...args, "/bin/cat", "/proc/self/status"], + { + env, + timeout: 5000, + } + ); + const fields = new Map( + stdout.split("\n").map((line) => { + const [key, value] = line.split(":", 2); + return [key, (value ?? "").trim()]; + }) + ); + const matchesId = (key: string, expected: number) => + fields.get(key)?.split(/\s+/).join(" ") === + Array(4).fill(expected).join(" "); + const capabilityFields = ["CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb"]; + if ( + !matchesId("Uid", uid) || + !matchesId("Gid", gid) || + fields.get("Groups") !== "" || + fields.get("NoNewPrivs") !== "1" || + !capabilityFields.every((key) => /^0+$/.test(fields.get(key) ?? "")) + ) { + throw new Error( + "the child retained privileges or used the wrong UID/GID" + ); + } + } catch (error) { + throw new Error( + "Runner cannot verify unprivileged execution with /usr/bin/setpriv.", + { cause: error } + ); + } +} export async function runRemoteRunner(filename: string) { const config: RunnerConfig = JSON.parse(readFileSync(filename, "utf8")); const endpoint = new URL(config.endpoint); if ( endpoint.protocol !== "https:" || - !config.uid || - !config.gid || + process.platform !== "linux" || + !validExecutionId(config.uid) || + !validExecutionId(config.gid) || process.getuid?.() !== 0 ) { throw new Error( "Runner requires an HTTPS endpoint and a separate, non-root execution account." ); } + const env = { + HOME: config.home, + PATH: config.path, + SHELL: "/bin/bash", + NODE_EXTRA_CA_CERTS: config.ca, + ...(config.trustBundle ? { SSL_CERT_FILE: config.trustBundle } : {}), + ...(config.adapter + ? { DISPATCH_ACP_ADAPTER_COMMAND: JSON.stringify(config.adapter) } + : {}), + }; + const childArgs = executionArgs(config.uid, config.gid); + await verifyExecutionIdentity(config.uid, config.gid, childArgs, env); const credentials = { ca: readFileSync(config.ca), cert: readFileSync(config.cert), @@ -63,17 +140,8 @@ export async function runRemoteRunner(filename: string) { await mkdir(logs, { recursive: true, mode: 0o700 }); await chmod(config.state, 0o711); await mkdir(hostRoot, { recursive: true, mode: 0o711 }); - const identity = { uid: config.uid, gid: config.gid }; - const env = { - HOME: config.home, - PATH: config.path, - SHELL: "/bin/bash", - NODE_EXTRA_CA_CERTS: config.ca, - ...(config.trustBundle ? { SSL_CERT_FILE: config.trustBundle } : {}), - ...(config.adapter - ? { DISPATCH_ACP_ADAPTER_COMMAND: JSON.stringify(config.adapter) } - : {}), - }; + await chmod(hostRoot, 0o711); + const hosts = new Map(); const active = new Set(); const owns = async (id: string, workspace: string) => @@ -129,13 +197,16 @@ export async function runRemoteRunner(filename: string) { const [bin, ...args] = hostCommand(); if (!bin) throw new Error("Runner host executable is missing"); const owned = ownedEnvironment(env); - const child = spawn(bin, [...args, "--state", dir], { - ...identity, - cwd, - env: owned.env, - detached: true, - stdio: ["ignore", log, log], - }); + const child = spawn( + setpriv, + [...childArgs, bin, ...args, "--state", dir], + { + cwd, + env: owned.env, + detached: true, + stdio: ["ignore", log, log], + } + ); hosts.set(agentId, child); const forget = () => { if (hosts.get(agentId) === child) hosts.delete(agentId); @@ -298,13 +369,16 @@ export async function runRemoteRunner(filename: string) { throw new Error( "Runner workspace has no approved repo operation" ); - const { stdout } = await execute(bin, args, { - ...identity, - cwd: target.cwd, - env, - timeout: 10_000, - maxBuffer: 64 * 1024, - }); + const { stdout } = await execute( + setpriv, + [...childArgs, bin, ...args], + { + cwd: target.cwd, + env, + timeout: 10_000, + maxBuffer: 64 * 1024, + } + ); result(stdout); break; } diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index d50507476..4e47f7c36 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -40,9 +40,15 @@ defines its guest `cwd` and can define a fixed `repoTool` argv array. The optional `trustBundle` supplies a combined system and test trust bundle for clients that use `SSL_CERT_FILE`. There is a guest-local `adapter` override for the fake provider. Keep the enrollment key and runner settings root-only -and the CA certificate readable by the CLI. The child starts under the -configured non-root account with a constructed environment and receives only -the scoped MCP credential and guest paths. Use test credentials, disable VM +and the CA certificate readable by the CLI. The supervisor needs Linux +util-linux `/usr/bin/setpriv` and permission to change identity and remove +capabilities (`CAP_SETUID`, `CAP_SETGID`, and `CAP_SETPCAP`). Before enrollment, +the runner verifies the kernel-reported non-root UID/GID, empty supplementary +groups, zero capabilities, and `no_new_privs` through the same wrapper used +for both the ACP host and repo operations. The runner grants traversal on its +root and host-state parent even when the supervisor uses umask `0077`. +Bindings and logs remain private. The child receives its scoped MCP credential +and guest paths through a constructed environment. Use test credentials, disable VM mounts and SSH-agent forwarding, and keep the VM and dev data disposable. ## Wire contract From cffe980fc7b65e2c430f886b1541f45f47fe344d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 21:17:20 -0700 Subject: [PATCH 003/642] Regress runner enrollment privilege and private umask checks --- apps/server/src/agents/remote/runner.ts | 1 + .../server/test/remote-runner-startup.test.ts | 163 ++++++++++++++++++ 2 files changed, 164 insertions(+) create mode 100644 apps/server/test/remote-runner-startup.test.ts diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 3707c90c8..cde887d3d 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -11,6 +11,7 @@ import { } from "node:fs/promises"; import { createConnection } from "node:net"; import path from "node:path"; +import process from "node:process"; import { connect } from "node:tls"; import { promisify } from "node:util"; import { hostFile, type HostLaunch } from "../acp/host-protocol.js"; diff --git a/apps/server/test/remote-runner-startup.test.ts b/apps/server/test/remote-runner-startup.test.ts new file mode 100644 index 000000000..f8712a1f9 --- /dev/null +++ b/apps/server/test/remote-runner-startup.test.ts @@ -0,0 +1,163 @@ +import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const { reportIdentity, dial } = vi.hoisted(() => { + const reportIdentity = vi.fn(); + // Preserve execFile's custom promisify return shape. + Object.defineProperty( + reportIdentity, + Symbol.for("nodejs.util.promisify.custom"), + { + value: (...args: unknown[]) => + new Promise((resolve, reject) => { + reportIdentity( + ...args, + (error: Error | null, stdout: string, stderr: string) => { + if (error) reject(error); + else resolve({ stdout, stderr }); + } + ); + }), + } + ); + return { reportIdentity, dial: vi.fn() }; +}); + +// Exercise the real runner startup on every test platform. The kernel probe +// and TLS dial are the only external operations replaced by the test. +vi.mock("node:process", async (original) => { + const { default: process } = await original(); + return { + default: Object.create(process, { + platform: { value: "linux" }, + getuid: { value: () => 0 }, + }), + }; +}); +vi.mock("node:child_process", async (original) => ({ + ...(await original()), + execFile: reportIdentity, +})); +vi.mock("node:tls", async (original) => ({ + ...(await original()), + connect: dial, +})); + +import { runRemoteRunner } from "../src/agents/remote/runner.js"; + +const unprivilegedStatus = [ + "Uid:\t1000\t1000\t1000\t1000", + "Gid:\t1001\t1001\t1001\t1001", + "Groups:\t ", + "CapInh:\t0000000000000000", + "CapPrm:\t0000000000000000", + "CapEff:\t0000000000000000", + "CapBnd:\t0000000000000000", + "CapAmb:\t0000000000000000", + "NoNewPrivs:\t1", +].join("\n"); + +describe("remote runner startup", () => { + let root: string; + let config: string; + let state: string; + let key: string; + + beforeEach(async () => { + vi.resetAllMocks(); + root = await mkdtemp(path.join(os.tmpdir(), "dispatch-runner-startup-")); + config = path.join(root, "runner.json"); + state = path.join(root, "state"); + key = path.join(root, "key"); + await writeFile(key, "unused test credential", { mode: 0o600 }); + await writeFile( + config, + JSON.stringify({ + endpoint: "https://fixture.invalid", + key, + cert: key, + ca: key, + state, + uid: 1000, + gid: 1001, + home: root, + path: "/usr/bin:/bin", + bins: {}, + workspaces: {}, + }) + ); + }); + + afterEach(async () => { + await rm(root, { recursive: true, force: true }); + }); + + it.each([ + ["root UID", "Uid:\t1000\t1000\t1000\t1000", "Uid:\t0\t0\t0\t0"], + ["root GID", "Gid:\t1001\t1001\t1001\t1001", "Gid:\t0\t0\t0\t0"], + ["supplementary root group", "Groups:\t ", "Groups:\t0"], + [ + "retained capability", + "CapBnd:\t0000000000000000", + "CapBnd:\t0000000000000001", + ], + ["later privilege gain", "NoNewPrivs:\t1", "NoNewPrivs:\t0"], + ])("refuses enrollment with %s", async (_label, from, to) => { + reportIdentity.mockImplementation((_command, _args, _options, callback) => + callback(null, unprivilegedStatus.replace(from, to), "") + ); + await expect(runRemoteRunner(config)).rejects.toThrow( + "cannot verify unprivileged execution" + ); + expect(dial).not.toHaveBeenCalled(); + await expect(stat(state)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("refuses enrollment when setpriv cannot change identity", async () => { + reportIdentity.mockImplementation((_command, _args, _options, callback) => + callback(new Error("Operation not permitted")) + ); + await expect(runRemoteRunner(config)).rejects.toThrow( + "cannot verify unprivileged execution" + ); + expect(dial).not.toHaveBeenCalled(); + await expect(stat(state)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("leaves the host parent traversable and keeps enrollment state private", async () => { + // A retained host directory created with umask 0077 has mode 0700. + await mkdir(path.join(state, "hosts"), { recursive: true, mode: 0o700 }); + reportIdentity.mockImplementation((_command, _args, _options, callback) => + callback(null, unprivilegedStatus, "") + ); + const stopAtDial = new Error("stop the test before the network dial"); + dial.mockImplementation(() => { + throw stopAtDial; + }); + + await expect(runRemoteRunner(config)).rejects.toBe(stopAtDial); + expect(reportIdentity).toHaveBeenCalledWith( + "/usr/bin/setpriv", + [ + "--reuid=1000", + "--regid=1001", + "--clear-groups", + "--no-new-privs", + "--inh-caps=-all", + "--ambient-caps=-all", + "--bounding-set=-all", + "--", + "/bin/cat", + "/proc/self/status", + ], + expect.any(Object), + expect.any(Function) + ); + expect((await stat(state)).mode & 0o777).toBe(0o711); + expect((await stat(path.join(state, "hosts"))).mode & 0o777).toBe(0o711); + expect((await stat(path.join(state, "bindings"))).mode & 0o777).toBe(0o700); + expect((await stat(key)).mode & 0o777).toBe(0o600); + }); +}); From 789c1d837a7a44780576ebfba0de5bc9916b16b4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:13:09 -0700 Subject: [PATCH 004/642] Document remote runner acceptance and Dispatch implementation handoff --- docs/design/remote-runner-handoff.md | 40 +++++ docs/design/remote-runner-prototype.md | 4 +- .../remote-runner/codex-offline-preflight.sh | 167 ++++++++++++++++++ 3 files changed, 209 insertions(+), 2 deletions(-) create mode 100644 docs/design/remote-runner-handoff.md create mode 100644 scripts/remote-runner/codex-offline-preflight.sh diff --git a/docs/design/remote-runner-handoff.md b/docs/design/remote-runner-handoff.md new file mode 100644 index 000000000..1fd6cf565 --- /dev/null +++ b/docs/design/remote-runner-handoff.md @@ -0,0 +1,40 @@ +# Remote runners in Dispatch + +Start here when picking up the prototype. The branch `prototype/remote-runner` contains the Dispatch implementation, regression tests and design notes. The tested implementation is `cffe980f`, based on Dispatch main `65eefba8`. Read [setup and wire traces](remote-runner-prototype.md) for the current manual enrollment and launch procedure. The design below describes the next product milestone. + +## First hour on another host + +1. Check out the branch and install the locked dependencies with `pnpm install --frozen-lockfile` (pnpm 9.15.9). +2. Run `pnpm run check` from the root. From `apps/server`, run `pnpm exec vitest run test/acp-host.test.ts test/remote-runner-startup.test.ts`. +3. Follow the prototype setup using Bun 1.4.2 and the Linux compile target matching the execution host. Supply an isolated Dispatch instance, one test CA, one manually approved runner certificate, a pre-provisioned guest checkout and a non-root workload account. Supply an HTTPS MCP origin reachable from the runner. Keep the enrollment private key outside the workload account. +4. Launch from Create Agent using the approved runner workspace locator. Start with the deterministic fixture at `apps/server/test/helpers/remote-acp-fixture.ts`. For Codex, install the complete published distribution, including its Code Mode companion. The [offline preflight](../../scripts/remote-runner/codex-offline-preflight.sh) takes the pinned Codex 0.167.1 Linux x86-64 package tarball as its sole argument and runs on Linux with Docker. It uses no account or provider. Its container image supplies the script interpreter; the verified compiled runner used Bun 1.4.2. + +## Acceptance evidence at handoff + +| Run | Observed result | +| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Dispatch on macOS and a runner in ARM64 Lima | A released OpenCode CLI read a guest-only marker and posted it through Dispatch MCP. Separate tests exercised permission denial, cancellation, local launch regression, service restart, a broken transport and a lost prompt acknowledgement. A same-ID retry invoked the deterministic provider once. | +| Dispatch on macOS and Cloudy Linux x86-64 | A real ChatGPT-authenticated Codex turn on the canonical cffe980f runner read a fresh guest marker and posted it once through product MCP. The journal recorded one terminal result. The temporary login was removed. The in-flight reconnect proof used a deterministic engine on hardened revision 1ec3b7b1. | +| Privilege boundary | The final runner validates the kernel-reported workload identity before enrollment. The live workload ran non-root with no supplementary groups. The signed-in test used the existing full-access agent mode inside an isolated container. Codex modes that require nested bubblewrap user namespaces need separate proof. | +| Second service | A scoped local Hangar Worker used the same cffe980f ARM64 binary. Its adapter replayed the journal after disconnect and the product API served one completed answer from stored data with both transports closed. One pre-provisioned workspace, deterministic engine, no product MCP call or permission prompt. The proof fixture lives in Hangar commit ac4f6d74. | + +The canonical Linux ARM64 runner SHA-256 was `40c85e711f1e916edf7f78d3b48eb2e52a6d66ca73d194c4fb8f5fa3495ab019`. The x86-64 runner SHA-256 was `450b9418d06efb53e8ede22ab5602dbb7fce2e00f5dd13e24facacfdcf015848`. These identify tested artifacts; independent rebuilds can differ. + +## First product milestone + +**One Dispatch instance can run a local agent and agents on two named remote runners at the same time.** Start in `apps/server/src/agents/remote/{service,runner,protocol}.ts`. Trace placement through the manager, workspace target, and ACP runtime. The prototype configures one registration and uses a runner locator in the existing cwd field. + +1. Model runner registrations and workspace handles explicitly. Persist enrollment, revocation and last reported capabilities. Bind every command to its registration and workspace. Support certificate renewal and loss of a runner connection while local agents continue operating. +2. Add pairing, runner status and workspace selection to the usual Dispatch launch flow. Preserve the local default. Show pending permission, stopped, disconnected and recovered states accurately. Test two runners exposing identically named workspaces. +3. Persist enough operation and replay state to recover from service or runner restart. Exercise a crash between receiving an event and storing it, duplicate command delivery, journal replacement, host death and independent revocation. Verify one provider invocation and one visible completion where a receipt establishes acceptance; represent uncertain outcomes explicitly. +4. Acceptance run: start a local agent and two remote agents, disconnect one runner mid-turn, continue work on the other two, reconnect the first, then revoke it. Confirm correct output ownership throughout and no cross-runner workspace access. + +## Keep the execution contract portable + +Start with a package boundary in Dispatch. Keep registration identity, workspace binding, process supervision, permissions, operation receipts and stream replay independent of the Dispatch server. Keep boards, messages, personas and UI in Dispatch. Let service and runner negotiate supported operations. The Hangar experiment identified three specific changes: + +- Accept opaque IDs and distinguish spawn receipt, ready session, accepted prompt and completed turn. Hangar needed an alias to satisfy the current Dispatch agent-ID format. +- Make service-owned MCP optional and independently scoped. The Hangar proof needed a dummy HTTPS URL and token even for an engine that never called a product tool. +- Specify stream identity, contiguous sequence, replay boundary, persistence and acknowledgement. Hangar has its own activity cursor. Advancing a cursor before its payload is durably recorded can lose output. + +Keep a small independent consumer test that imports no Dispatch server code. Run the scoped Hangar proof when changing wire semantics. Treat remote file publishing, Git/worktree management and preview relaying as separate feature slices. For previews, the runner can report an approved workspace-local endpoint under an opaque ID. Dispatch owns browser URLs, access and revocation. A later acceptance test should open two previews on the same guest port, exercise live reload, and disconnect either runner independently. diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 4e47f7c36..b072e6910 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -146,5 +146,5 @@ features outside this slice. The implementation supports one manually enrolled runner and pre-provisioned standalone workspaces. Full restart recovery of the runner daemon itself requires work beyond the service and network reconnect tested here. The guest connection uses Lima's host-loopback reachability and -establishes process and filesystem separation. A second host and a Hangar adapter -are separate acceptance gates. +establishes process and filesystem separation. Subsequent Cloudy and scoped Hangar runs are recorded in the +[implementation handoff](remote-runner-handoff.md). diff --git a/scripts/remote-runner/codex-offline-preflight.sh b/scripts/remote-runner/codex-offline-preflight.sh new file mode 100644 index 000000000..102eb4140 --- /dev/null +++ b/scripts/remote-runner/codex-offline-preflight.sh @@ -0,0 +1,167 @@ +#!/usr/bin/env bash +set -euo pipefail + +archive=${1:?Usage: codex-cloudy-toolcheck.sh CODEX_LINUX_X64_TGZ} +image=${CODEX_PREFLIGHT_IMAGE:-oven/bun:1.3.13} +expected=944cbabe58a2c599a30141bc0220c31963205c33e69b43b414dd5da6adaf957f +digest=$(sha256sum "$archive" | cut -d ' ' -f1) +test "$digest" = "$expected" +printf 'Codex package SHA-256 %s\n' "$digest" + +# An independent disposable container. Never mount a host home or supply auth. +container=$(docker create --network none --security-opt no-new-privileges \ + --cap-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID \ + --cap-add SETPCAP --pids-limit 64 --memory 1g --user 0 \ + --entrypoint /bin/sleep "$image" 120) +trap 'docker rm -f "$container" >/dev/null' EXIT +docker cp "$archive" "$container:/codex-linux-x64.tgz" +docker start "$container" >/dev/null +test "$(docker inspect --format '{{.HostConfig.NetworkMode}}' "$container")" = none +echo 'Container network mode: none' + +docker exec -i "$container" /bin/sh -se <<'CONTAINER' +umask 022 +mkdir -p /proof/home/.codex /proof/app/codex-distribution +chmod 700 /proof/home /proof/home/.codex +chown 1000:1000 /proof/home/.codex /proof/home +workspace=/opt/dispatch-guest-codex-preflight +mkdir -m 755 "$workspace" +marker=$(cat /proc/sys/kernel/random/uuid) +printf '%s\n' "$marker" > "$workspace/marker.txt" +# Keep the complete published layout. Codex resolves resources beside its binary. +tar --no-same-owner -xzf /codex-linux-x64.tgz -C /proof/app/codex-distribution +vendor=/proof/app/codex-distribution/package/vendor/x86_64-unknown-linux-musl +test -x "$vendor/bin/codex" +test -x "$vendor/bin/codex-code-mode-host" +test -x "$vendor/codex-resources/bwrap" +test -x "$vendor/codex-path/rg" +cat > /proof/preflight.mjs <<'JS' +import { readFile } from "node:fs/promises"; + +const vendor = process.argv[2]; +const env = { + HOME: "/proof/home", + CODEX_HOME: "/proof/home/.codex", + PATH: `${vendor}/bin:${vendor}/codex-path:${vendor}/codex-resources:/usr/bin:/bin` +}; +async function verifyIdentity(path) { + const status = await readFile(path, "utf8"); + checkIdentity(status); +} +function checkIdentity(status) { + const kernelIdentity = Object.fromEntries(status.split("\n").map(line => { + const [key, value] = line.split(":", 2); + return [key, (value ?? "").trim().replace(/\s+/g, " ")]; + })); + for (const [key, wanted] of Object.entries({ + Uid: "1000 1000 1000 1000", + Gid: "1000 1000 1000 1000", + Groups: "", + NoNewPrivs: "1", + CapInh: "0000000000000000", + CapPrm: "0000000000000000", + CapEff: "0000000000000000", + CapBnd: "0000000000000000", + CapAmb: "0000000000000000" + })) { + if (kernelIdentity[key] !== wanted) throw new Error(`Unexpected ${key}`); + } +} +await verifyIdentity("/proc/self/status"); +console.log("Preflight kernel identity: UID/GID 1000; empty groups; no capabilities; NoNewPrivs=1"); + +const spawn = (binary, ...args) => Bun.spawn([vendor + "/bin/" + binary, ...args], { + cwd: env.HOME, env, stdin: "pipe", stdout: "pipe", stderr: "inherit" +}); +const version = spawn("codex", "--version"); +version.stdin.end(); +const versionText = (await new Response(version.stdout).text()).trim(); +if (await version.exited || versionText !== "codex-cli 0.167.1") { + throw new Error("Unexpected Codex CLI version"); +} +console.log(versionText); + +const companion = spawn("codex-code-mode-host", "--listen", "stdio"); +try { + // Hold stdin open to distinguish the running IPC host from a process that + // merely parsed --help, exited on startup, or did not load its executable. + await Promise.race([ + companion.exited.then(code => { throw new Error(`Companion exited during startup: ${code}`); }), + Bun.sleep(350) + ]); + await verifyIdentity(`/proc/${companion.pid}/status`); + companion.stdin.end(); + if (await companion.exited) throw new Error("Code Mode companion failed on EOF"); + console.log("Code Mode companion opened stdio and shut down cleanly on EOF"); +} finally { + companion.kill(); +} + +const appServer = spawn( + "codex", "app-server", "--listen", "stdio://", + "-c", 'approval_policy="never"', "-c", 'sandbox_mode="danger-full-access"' +); +const reader = appServer.stdout.pipeThrough(new TextDecoderStream()).getReader(); +let pending = ""; +function send(message) { + appServer.stdin.write(JSON.stringify({jsonrpc: "2.0", ...message}) + "\n"); + appServer.stdin.flush(); +} +async function readResponse(id) { + while (true) { + const end = pending.indexOf("\n"); + if (end >= 0) { + const message = JSON.parse(pending.slice(0, end)); + pending = pending.slice(end + 1); + if (message.id === id) { + if (message.error) throw new Error(JSON.stringify(message.error)); + return message.result; + } + continue; + } + const { value, done } = await reader.read(); + if (done) throw new Error("App server stream closed"); + pending += value; + } +} +async function request(id, method, params) { + send({id, method, params}); + return await Promise.race([ + readResponse(id), + Bun.sleep(8000).then(() => { throw new Error(method + " timed out"); }) + ]); +} +try { + await request(1, "initialize", { + clientInfo: {name: "cloudy-offline-toolcheck", version: "1"} + }); + send({method:"initialized"}); + console.log("Codex app-server returned local initialize response"); + const result = await request(2, "command/exec", { + cwd: "/opt/dispatch-guest-codex-preflight", + command: ["/bin/sh", "-ec", 'cat marker.txt; cat "/proc/$$/status"'], + sandboxPolicy: {type: "dangerFullAccess"}, + timeoutMs: 5000 + }); + if (result.exitCode !== 0) throw new Error("command/exec failed: " + result.stderr); + const end = result.stdout.indexOf("\n"); + if (result.stdout.slice(0, end) !== process.argv[3]) { + throw new Error("command/exec did not return the matching guest-only marker"); + } + checkIdentity(result.stdout.slice(end + 1)); + console.log("command/exec returned matching guest-only marker: " + process.argv[3]); + console.log("Command kernel identity: UID/GID 1000; empty groups; no capabilities; NoNewPrivs=1"); + console.log("Policy: dangerFullAccess with approval_policy=never; no turn or provider call"); +} finally { + appServer.stdin.end(); + appServer.kill(); + await appServer.exited; +} + +JS +chmod 644 /proof/preflight.mjs +/usr/bin/setpriv --reuid=1000 --regid=1000 --clear-groups --no-new-privs \ + --inh-caps=-all --ambient-caps=-all --bounding-set=-all -- \ + /usr/bin/env -i HOME=/proof/home PATH=/usr/local/bin:/usr/bin:/bin \ + /usr/local/bin/bun /proof/preflight.mjs "$vendor" "$marker" +CONTAINER From 8ca91606ec6b5c1e188f6a7cf8a46d834c3a2265 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:42:26 -0700 Subject: [PATCH 005/642] Add runner management and runner selection to Create Agent Co-Authored-By: Claude Sonnet 5.5 --- .../components/app/create-agent-dialog.tsx | 50 ++-- apps/web/src/components/app/runner-picker.tsx | 105 ++++++++ .../src/components/app/runner-settings.tsx | 253 ++++++++++++++++++ .../src/components/app/settings-pane.test.tsx | 3 +- apps/web/src/components/app/settings-pane.tsx | 10 +- .../components/app/use-create-agent-form.ts | 40 ++- apps/web/src/hooks/use-runners.test.ts | 11 + apps/web/src/hooks/use-runners.ts | 50 ++++ 8 files changed, 493 insertions(+), 29 deletions(-) create mode 100644 apps/web/src/components/app/runner-picker.tsx create mode 100644 apps/web/src/components/app/runner-settings.tsx create mode 100644 apps/web/src/hooks/use-runners.test.ts create mode 100644 apps/web/src/hooks/use-runners.ts diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index c61582026..28391b783 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -11,6 +11,7 @@ import { AgentEngineFields } from "@/components/app/agent-engine-fields"; import { ContextPicker } from "@/components/app/context-picker"; import { CONTEXT_PROMPT_ID } from "@/components/app/create-agent-dialog-utils"; import { WorktreeSection } from "@/components/app/create-agent-worktree-section"; +import { RunnerPicker } from "@/components/app/runner-picker"; import { PathInput } from "@/components/app/path-input"; import { useCreateAgentForm } from "@/components/app/use-create-agent-form"; import { ActivityBars } from "@/components/ui/activity-bars"; @@ -152,30 +153,39 @@ function CreateAgentDialogContent({ ) : (
- { - form.setCreateProjectId(p?.id ?? null); - }} - > - - + +
)} diff --git a/apps/web/src/components/app/runner-picker.tsx b/apps/web/src/components/app/runner-picker.tsx new file mode 100644 index 000000000..1e76b0934 --- /dev/null +++ b/apps/web/src/components/app/runner-picker.tsx @@ -0,0 +1,105 @@ +import { useId } from "react"; + +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { type Runner } from "@/hooks/use-runners"; + +const THIS_MAC = "__local__"; + +/** "Runs on" picker: This Mac by default, or a paired runner + workspace. */ +export function RunnerPicker({ + runners, + runnerId, + onRunnerChange, + workspace, + onWorkspaceChange, +}: { + runners: Runner[]; + runnerId: string | null; + onRunnerChange: (id: string | null) => void; + workspace: string | null; + onWorkspaceChange: (workspace: string) => void; +}): JSX.Element | null { + const runnerLabelId = useId(); + const workspaceLabelId = useId(); + const usable = runners.filter((r) => r.status !== "revoked"); + if (usable.length === 0) return null; + const selected = usable.find((r) => r.id === runnerId); + return ( +
+
+ + +
+ {selected ? ( +
+ + {selected.workspaces.length === 0 ? ( +

+ This runner has not reported any workspaces. +

+ ) : ( + + )} +
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx new file mode 100644 index 000000000..b3a802dd0 --- /dev/null +++ b/apps/web/src/components/app/runner-settings.tsx @@ -0,0 +1,253 @@ +import { useState, type FormEvent } from "react"; +import { Copy, Server, Unplug } from "lucide-react"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { useCopyText } from "@/hooks/use-copy"; +import { + useRunnerMutations, + useRunners, + type RunnerPairing, + type RunnerStatus, +} from "@/hooks/use-runners"; +import { formatDateTime } from "@/lib/format"; +import { cn } from "@/lib/utils"; + +const STATUS_LABEL: Record = { + pending: "Waiting to pair", + online: "Online", + offline: "Offline", + revoked: "Revoked", +}; + +const STATUS_DOT: Record = { + pending: "bg-amber-400", + online: "bg-emerald-500", + offline: "bg-muted-foreground/60", + revoked: "bg-destructive", +}; + +export function RunnerSettings(): JSX.Element { + const runners = useRunners({ poll: true }); + const { pair, revoke } = useRunnerMutations(); + const [name, setName] = useState(""); + const [pairing, setPairing] = useState(null); + const [copied, copyText] = useCopyText(); + const [confirmId, setConfirmId] = useState(null); + + const submit = (event: FormEvent) => { + event.preventDefault(); + const trimmed = name.trim(); + if (!trimmed || pair.isPending) return; + pair.mutate(trimmed, { + onSuccess: (result) => { + setPairing(result); + setName(""); + }, + }); + }; + + const list = runners.data ?? []; + + return ( + + + Remote runners + + Run agents on another machine. Pair a runner, then pick it in Create + Agent. Local agents keep working if a runner disconnects. + + + +
+ setName(event.target.value)} + placeholder="Runner name, e.g. lima" + aria-label="Runner name" + data-testid="runner-name-input" + /> + +
+ {pair.isError && ( +

+ {pair.error instanceof Error + ? pair.error.message + : "Could not start pairing."} +

+ )} + + {pairing && ( +
+

+ Run this on the runner machine. It expires{" "} + {formatDateTime(pairing.expiresAt)}. +

+
+              {pairing.command}
+            
+
+ + +
+
+ )} + + {runners.isPending ? ( +

+ Loading runners... +

+ ) : runners.isError ? ( +
+

+ Could not load runners. +

+ +
+ ) : list.length === 0 ? ( +

+ No runners yet. Agents run on this Mac. +

+ ) : ( +
    + {list.map((runner) => ( +
  • +
  • + ))} +
+ )} + {revoke.isError && ( +

+ Could not revoke that runner. Try again. +

+ )} +
+
+ ); +} diff --git a/apps/web/src/components/app/settings-pane.test.tsx b/apps/web/src/components/app/settings-pane.test.tsx index 69af24ae0..4d869ba8f 100644 --- a/apps/web/src/components/app/settings-pane.test.tsx +++ b/apps/web/src/components/app/settings-pane.test.tsx @@ -59,6 +59,7 @@ vi.mock( ); vi.mock("@/components/app/ide-settings", stubModule("IdeSettings")); vi.mock("./routing-settings", stubModule("RoutingSettings")); +vi.mock("./runner-settings", stubModule("RunnerSettings")); vi.mock( "@/components/app/instance-name-settings", stubModule("InstanceNameSettings") @@ -280,7 +281,7 @@ describe("SettingsContent", () => { ["workspace", ["IdeSettings", "WorktreeLocationSettings"]], ["security", ["SecuritySettings"]], ["notifications", ["NotificationSettings"]], - ["connections", ["BrowserExtensionSettings"]], + ["connections", ["BrowserExtensionSettings", "RunnerSettings"]], ["resources", ["ServiceResourcesSettings"]], ["updates", ["UpdatesSection", "PluginUpdateSettings"]], ["help", ["DocsContent"]], diff --git a/apps/web/src/components/app/settings-pane.tsx b/apps/web/src/components/app/settings-pane.tsx index 6ad2abef4..3e6464865 100644 --- a/apps/web/src/components/app/settings-pane.tsx +++ b/apps/web/src/components/app/settings-pane.tsx @@ -1,3 +1,4 @@ +import { RunnerSettings } from "./runner-settings"; import { RoutingSettings } from "./routing-settings"; import { lazy, Suspense } from "react"; import { Database, Server, Settings } from "lucide-react"; @@ -231,7 +232,14 @@ export function SettingsContent({ )} {activeSection === "notifications" && } - {activeSection === "connections" && } + {activeSection === "connections" && ( + <> + +
+ +
+ + )} {activeSection === "resources" && } {activeSection === "updates" && (
diff --git a/apps/web/src/components/app/use-create-agent-form.ts b/apps/web/src/components/app/use-create-agent-form.ts index ffaecf5ed..511b9d4f5 100644 --- a/apps/web/src/components/app/use-create-agent-form.ts +++ b/apps/web/src/components/app/use-create-agent-form.ts @@ -2,6 +2,7 @@ import type { Effort } from "@dispatch/shared"; import { useAtom } from "jotai"; import { useProjects } from "@/hooks/use-projects"; import { createAgentLocationPrefAtom } from "@/lib/store"; +import { runnerLocator, useRunners } from "@/hooks/use-runners"; import { type ClipboardEvent, type FormEvent, @@ -61,6 +62,21 @@ export function useCreateAgentForm({ task = null, onCreated, }: UseCreateAgentFormOptions) { + // null runner = this Mac (the default). A runner swaps the folder for one + // of its approved workspaces, addressed by a runner:// locator. + const { data: runners = [] } = useRunners(); + const [runnerId, setRunnerId] = useState(null); + const [runnerWorkspace, setRunnerWorkspace] = useState(null); + const runner = runnerId ? runners.find((r) => r.id === runnerId) : undefined; + const remote = Boolean(runnerId); + const remoteCwd = + runner && runnerWorkspace + ? runnerLocator(runner.name, runnerWorkspace) + : ""; + const selectRunner = (id: string | null) => { + setRunnerId(id); + setRunnerWorkspace(null); + }; const [locationPref, setLocationPref] = useAtom(createAgentLocationPrefAtom); const { data: projects = [], isSuccess: projectsLoaded } = useProjects(); // The scope seeds this opening, but a picker choice (including Folder) @@ -76,10 +92,14 @@ export function useCreateAgentForm({ (locationPref?.mode === "project" ? locationPref.projectId : null)); const project = projects.find((p) => p.id === selectedProjectId); // Keep a pending choice while loading, but never submit an unavailable ID. - const createProjectId = projectsLoaded - ? (project?.id ?? null) - : selectedProjectId; - const locationReady = !selectedProjectId || projectsLoaded; + const createProjectId = runnerId + ? null + : projectsLoaded + ? (project?.id ?? null) + : selectedProjectId; + const locationReady = runnerId + ? Boolean(remoteCwd) + : !selectedProjectId || projectsLoaded; const setCreateProjectId = (id: string | null) => { setLocationChoice({ projectId: id }); setLocationPref({ @@ -103,7 +123,7 @@ export function useCreateAgentForm({ const resolved = resolveDefaultCwd().trim(); return resolved || readLastUsedCwd(); }); - const createCwd = project?.repoRoot ?? folderCwd; + const createCwd = remote ? remoteCwd : (project?.repoRoot ?? folderCwd); const [createCwdInitialized, setCreateCwdInitialized] = useState( () => createCwd.trim().length > 0 ); @@ -334,10 +354,10 @@ export function useCreateAgentForm({ }); if (typeof window !== "undefined") { - window.localStorage.setItem(LAST_USED_CWD_KEY, cwd); + if (!remote) window.localStorage.setItem(LAST_USED_CWD_KEY, cwd); window.localStorage.setItem(LAST_USED_TYPE_KEY, createType); } - addCwdHistory(cwd); + if (!remote) addCwdHistory(cwd); await onCreated(payload.agent, createType); } catch (err) { const message = @@ -351,6 +371,7 @@ export function useCreateAgentForm({ createBaseBranch, locationReady, createCwd, + remote, createProjectId, createFullAccess, createName, @@ -373,6 +394,11 @@ export function useCreateAgentForm({ ); return { + runners, + runnerId, + selectRunner, + runnerWorkspace, + setRunnerWorkspace, createProjectId, locationReady, lastProjectId: locationPref?.projectId, diff --git a/apps/web/src/hooks/use-runners.test.ts b/apps/web/src/hooks/use-runners.test.ts new file mode 100644 index 000000000..b4cbc3cfb --- /dev/null +++ b/apps/web/src/hooks/use-runners.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from "vitest"; + +import { runnerLocator } from "./use-runners"; + +describe("runnerLocator", () => { + it("encodes both components", () => { + expect(runnerLocator("a/b", "my proof#1")).toBe( + "runner://a%2Fb/my%20proof%231" + ); + }); +}); diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts new file mode 100644 index 000000000..ce3cf7692 --- /dev/null +++ b/apps/web/src/hooks/use-runners.ts @@ -0,0 +1,50 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +import { api } from "@/lib/api"; + +export type RunnerStatus = "pending" | "online" | "offline" | "revoked"; + +export type Runner = { + id: string; + name: string; + status: RunnerStatus; + workspaces: string[]; +}; + +export type RunnerPairing = { id: string; command: string; expiresAt: string }; + +export const runnersQueryKey = ["runners"] as const; + +/** Locator the server stores in an agent's cwd; both parts are encoded. */ +export function runnerLocator(name: string, workspace: string): string { + return `runner://${encodeURIComponent(name)}/${encodeURIComponent(workspace)}`; +} + +export function useRunners(options: { poll?: boolean } = {}) { + return useQuery({ + queryKey: runnersQueryKey, + queryFn: async () => + (await api<{ runners: Runner[] }>("/api/runners")).runners, + refetchInterval: options.poll ? 5000 : false, + }); +} + +export function useRunnerMutations() { + const queryClient = useQueryClient(); + const invalidate = () => + queryClient.invalidateQueries({ queryKey: runnersQueryKey }); + const pair = useMutation({ + mutationFn: (name: string) => + api("/api/runners", { + method: "POST", + body: JSON.stringify({ name }), + }), + onSuccess: invalidate, + }); + const revoke = useMutation({ + mutationFn: (id: string) => + api(`/api/runners/${encodeURIComponent(id)}`, { method: "DELETE" }), + onSuccess: invalidate, + }); + return { pair, revoke }; +} From 350d91dd34a476bd4b9d1e5c31aa21ebb1389da5 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:44:39 -0700 Subject: [PATCH 006/642] Extract portable remote runner protocol and optional service MCP --- apps/server/package.json | 1 + apps/server/src/agents/acp/driver.ts | 26 ++-- apps/server/src/agents/acp/host-protocol.ts | 78 +++-------- apps/server/src/agents/manager.ts | 25 ++-- apps/server/src/agents/remote/protocol.ts | 90 +----------- apps/server/src/agents/remote/runner.ts | 65 ++++++--- apps/server/src/agents/runtime.ts | 27 +--- apps/server/test/acp-host.test.ts | 1 + apps/server/test/db/agent-manager.test.ts | 14 +- .../server/test/remote-runner-startup.test.ts | 14 +- .../test/runner-protocol-consumer.test.ts | 77 +++++++++++ docs/design/remote-runner-prototype.md | 5 + packages/runner-protocol/README.md | 77 +++++++++++ packages/runner-protocol/package.json | 13 ++ packages/runner-protocol/src/index.ts | 130 ++++++++++++++++++ packages/runner-protocol/src/node.ts | 59 ++++++++ pnpm-lock.yaml | 5 + 17 files changed, 490 insertions(+), 217 deletions(-) create mode 100644 apps/server/test/runner-protocol-consumer.test.ts create mode 100644 packages/runner-protocol/README.md create mode 100644 packages/runner-protocol/package.json create mode 100644 packages/runner-protocol/src/index.ts create mode 100644 packages/runner-protocol/src/node.ts diff --git a/apps/server/package.json b/apps/server/package.json index 2ca1f4d9c..3affba639 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -19,6 +19,7 @@ "@agentclientprotocol/claude-agent-acp": "0.100.0", "@agentclientprotocol/codex-acp": "2.5.0", "@agentclientprotocol/sdk": "1.8.0", + "@dispatch/runner-protocol": "workspace:*", "@dispatch/shared": "workspace:*", "@fastify/compress": "^9.2.0", "@fastify/cookie": "^11.0.2", diff --git a/apps/server/src/agents/acp/driver.ts b/apps/server/src/agents/acp/driver.ts index b32827dc8..a5ecc441f 100644 --- a/apps/server/src/agents/acp/driver.ts +++ b/apps/server/src/agents/acp/driver.ts @@ -1,3 +1,4 @@ +import type { ServiceMcp } from "@dispatch/runner-protocol"; import { backgroundIngress, backgroundCapability, @@ -57,7 +58,7 @@ export type DriverLaunch = { systemPromptAppend: string | null; /** Task context plus any first-message guidance, once per host start. */ firstPromptAppend?: string | null; - mcp: { url: string; token: string }; + mcp?: ServiceMcp; /** Resume this ACP session when set; falls back to a new one if the engine lost it. */ sessionId: string | null; env: NodeJS.ProcessEnv; @@ -833,16 +834,19 @@ export class AcpDriver { !!steering && typeof steering === "object" && (steering as { supported?: unknown }).supported === true; - const mcpServers: acp.McpServer[] = [ - { - type: "http", - name: "dispatch", - url: launch.mcp.url, - headers: [ - { name: "Authorization", value: `Bearer ${launch.mcp.token}` }, - ], - }, - ]; + const { mcp } = launch; + const mcpServers: acp.McpServer[] = mcp + ? [ + { + type: "http", + name: mcp.name ?? "dispatch", + url: mcp.url, + headers: [ + { name: "Authorization", value: `Bearer ${mcp.token}` }, + ], + }, + ] + : []; let session: { sessionId: string; resumed: boolean } | null = null; if (launch.sessionId) { try { diff --git a/apps/server/src/agents/acp/host-protocol.ts b/apps/server/src/agents/acp/host-protocol.ts index 3a21b8654..8aa7dd99a 100644 --- a/apps/server/src/agents/acp/host-protocol.ts +++ b/apps/server/src/agents/acp/host-protocol.ts @@ -1,5 +1,14 @@ +import type { + HostEvent, + HostPrompt, + HostWelcome, + JournalEntry as RunnerJournalEntry, + PromptReceipt, + RemoteLaunch, + ReplayComplete, + ReplayHello, +} from "@dispatch/runner-protocol"; import type { BackgroundSnapshot } from "@dispatch/shared"; -import type { Effort } from "@dispatch/shared"; import type { AgentMcpInventoryResponse } from "@dispatch/shared"; import type { AgentPermissionRequest } from "@dispatch/shared"; import type { PromptImage, PromptSource } from "./prompt-source.js"; @@ -11,7 +20,7 @@ import type { AvailableCommand, SessionConfigOption, } from "@agentclientprotocol/sdk"; -import type { AcpEngineId, EngineBins } from "./engine-spec.js"; +import type { EngineBins } from "./engine-spec.js"; /** * What the server writes into an agent's state directory before spawning @@ -19,28 +28,13 @@ import type { AcpEngineId, EngineBins } from "./engine-spec.js"; * host takes no arguments beyond the directory. Mode 0600: it carries the * MCP token and the system prompt. */ -export type HostLaunch = { - agentId: string; +export type HostLaunch = RemoteLaunch & { cwd: string; - engine: AcpEngineId; - /** Missing only in launch files written before permission support (full access). */ - fullAccess?: boolean; bins: EngineBins; - /** The model to select through the engine's model config option; null keeps its default. */ - model: string | null; - /** Resolved launch effort; null leaves the CLI settings in control. */ - effort?: Effort | null; - /** Delivered as `_meta.systemPrompt.append` for engines that take one. */ - systemPrompt: string | null; - /** Persona task context delivered with the first ordinary prompt, including on resume. */ - personaContext?: string | null; - mcp: { url: string; token: string }; /** Environment the engine child gets on top of the host's own. */ env: Record; /** Directories prepended to the engine child's PATH. */ pathPrefix: string[]; - /** The ACP session to resume when the host starts fresh; null for a new one. */ - resumeSessionId: string | null; }; /** Files inside an agent's state directory. */ @@ -62,29 +56,11 @@ export function hostFile( } /** One journal line: an event with its position in the host's stream. */ -export type JournalEntry = { - seq: number; - at: string; - event: DriverEvent; - /** Lets a surviving journal recover its identity if journal.id is lost. */ - journalId?: string; -}; +export type JournalEntry = RunnerJournalEntry; export type ClientMessage = - | { - type: "hello"; - fromSeq: number; - journalId?: string | null; - replayComplete?: boolean; - } - | { - type: "prompt"; - id: string; - text: string; - journalId?: string; - source?: PromptSource; - images?: PromptImage[]; - } + | ReplayHello + | HostPrompt | { type: "steer"; id: string; text: string; source?: PromptSource } | { type: "cancel" } | { type: "interrupt"; id: string; turnSeq: number } @@ -102,15 +78,7 @@ export type ClientMessage = | { type: "ping" }; export type HostMessage = - | { - type: "welcome"; - agentId: string; - engine: AcpEngineId; - sessionId: string; - /** Whether the session was resumed from a stored id. */ - resumed: boolean; - /** Whether the engine child is alive. */ - running: boolean; + | (HostWelcome & { /** Absent on older hosts: keep queuing when they cannot steer. */ mcpInventorySupported?: boolean; /** Host snapshot RPC, absent on older hosts. */ @@ -120,21 +88,15 @@ export type HostMessage = interruptSupported?: boolean; /** The open turn, if one is running. */ turn: { seq: number; startedAt: string; source?: PromptSource } | null; - /** The newest journal seq; replay follows up to here. */ - journalSeq: number; - /** Identity of the journal whose sequence numbers are being reported. */ - journalId?: string; /** Current ACP commands, including skills; refreshed on each reconnect. */ commands: AvailableCommand[]; /** The session's config options as they stand; absent from older hosts. */ configOptions?: SessionConfigOption[]; permissions?: AgentPermissionRequest[]; - } - | ({ type: "event" } & JournalEntry) - | { type: "replay_complete" } - | { type: "prompt_accepted"; id: string } - /** Not submitted: the engine's own turn is open. Send it again after it settles. */ - | { type: "prompt_deferred"; id: string } + }) + | HostEvent + | ReplayComplete + | PromptReceipt | { type: "interrupt_result"; id: string } | { type: "steer_result"; id: string; outcome: "injected" | "promptRequired" } /** A set_config took; the engine's options after it. */ diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 475b271ca..20a08910f 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -2117,9 +2117,10 @@ export class AgentManager { // Rows a previous host left open (a crash mid-turn) settle first, so the // feed never shows a turn that can no longer finish. await this.streamRecorder.reconcile(agent.id); - const token = opts.jobRunId - ? createJobMcpToken(this.config.authToken, opts.jobRunId, agent.id) - : createAgentMcpToken(this.config.authToken, agent.id); + const remoteMcpOrigin = placement ? this.remote?.origin : undefined; + const mcpUrl = placement + ? remoteMcpOrigin && `${remoteMcpOrigin}/api/mcp/${agent.id}` + : dispatchMcpUrl(this.config, agent.id, opts.jobRunId); return this.runtime.launch({ agentId: agent.id, cwd: agent.cwd, @@ -2131,12 +2132,18 @@ export class AgentManager { effort: agent.effort ?? null, systemPrompt, personaContext: extractPersonaContext(agent.agentArgs ?? []), - mcp: { - url: placement - ? `${this.remote!.origin}/api/mcp/${agent.id}` - : dispatchMcpUrl(this.config, agent.id, opts.jobRunId), - token, - }, + mcp: mcpUrl + ? { + url: mcpUrl, + token: opts.jobRunId + ? createJobMcpToken( + this.config.authToken, + opts.jobRunId, + agent.id + ) + : createAgentMcpToken(this.config.authToken, agent.id), + } + : undefined, env, pathPrefix, resumeSessionId: opts.resumeSessionId, diff --git a/apps/server/src/agents/remote/protocol.ts b/apps/server/src/agents/remote/protocol.ts index 2e566bdfc..9f91aca01 100644 --- a/apps/server/src/agents/remote/protocol.ts +++ b/apps/server/src/agents/remote/protocol.ts @@ -1,88 +1,2 @@ -import { Duplex } from "node:stream"; -import { StringDecoder } from "node:string_decoder"; -import type { HostLaunch } from "../acp/host-protocol.js"; - -export function remotePlacement(cwd: string) { - const match = /^runner:\/\/([a-z0-9-]+)\/([a-z0-9-]+)$/.exec(cwd); - return match ? { runner: match[1]!, workspace: match[2]! } : null; -} - -export type Placement = NonNullable>; -export type RemoteLaunch = Omit< - HostLaunch, - "cwd" | "bins" | "env" | "pathPrefix" ->; - -export type Command = { agentId: string; workspace: string } & ( - | { kind: "launch"; launch: RemoteLaunch } - | { kind: "attach" | "alive" | "discard" | "log" | "repo" } - | { kind: "stop"; force: boolean } -); -export type Frame = - | { type: "ready"; version: 1; workspaces: string[] } - | { type: "request"; id: string; command: Command } - | { - type: "result"; - id: string; - value?: boolean | string; - error?: string; - code?: "host-gone"; - } - | { type: "data"; id: string; data: string } - | { type: "close"; id: string }; - -type Send = (frame: Frame) => void; - -export function wireFrames( - socket: Duplex, - receive: (frame: Frame) => void -): Send { - const decoder = new StringDecoder("utf8"); - let pending = ""; - socket.on("data", (chunk: Buffer) => { - pending += decoder.write(chunk); - let newline: number; - while ((newline = pending.indexOf("\n")) >= 0) { - if (newline > 32 * 1024 * 1024) return socket.destroy(); - const line = pending.slice(0, newline); - pending = pending.slice(newline + 1); - try { - receive(JSON.parse(line) as Frame); - } catch { - return socket.destroy(); - } - } - if (pending.length > 32 * 1024 * 1024) socket.destroy(); - }); - return (frame) => { - if (socket.destroyed || socket.writableLength > 32 * 1024 * 1024) { - socket.destroy(); - throw new Error("Runner connection is unavailable"); - } - socket.write(JSON.stringify(frame) + "\n"); - }; -} - -export function hostChannel(id: string, send: Send, dispose: () => void) { - return new Duplex({ - allowHalfOpen: false, - read() {}, - write(chunk: Buffer, _encoding, callback) { - try { - send({ type: "data", id, data: chunk.toString("base64") }); - callback(); - } catch (error) { - callback(error as Error); - } - }, - destroy(error, callback) { - dispose(); - try { - send({ type: "close", id }); - } catch { - /* transport already closed */ - } - callback(error); - }, - }); -} +export * from "@dispatch/runner-protocol"; +export { hostChannel, wireFrames } from "@dispatch/runner-protocol/node"; diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index cde887d3d..a9d0d9c86 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -1,4 +1,5 @@ import { spawn, execFile, type ChildProcess } from "node:child_process"; +import { createHash } from "node:crypto"; import { closeSync, openSync, readFileSync } from "node:fs"; import { mkdir, @@ -20,7 +21,13 @@ import { killOwnedProcesses, } from "../../shared/process/owned-processes.js"; import { hostCommand } from "../acp/runtime.js"; -import { wireFrames, type Command, type Frame } from "./protocol.js"; +import { + isOpaqueId, + RUNNER_WIRE_VERSION, + wireFrames, + type Command, + type Frame, +} from "./protocol.js"; type RunnerConfig = { endpoint: string; @@ -41,6 +48,14 @@ type RunnerConfig = { const execute = promisify(execFile); const setpriv = "/usr/bin/setpriv"; +// Use the old storage name for existing prototype bindings. Other wire IDs +// never enter a filesystem path, even when they look like a relative path. +export function runnerStorageKey(agentId: string): string { + return /^agt_[a-z0-9]+$/.test(agentId) + ? agentId + : `opaque-${createHash("sha256").update(agentId).digest("base64url")}`; +} + function validExecutionId(value: number) { return Number.isInteger(value) && value > 0 && value < 0xffffffff; } @@ -118,6 +133,9 @@ export async function runRemoteRunner(filename: string) { "Runner requires an HTTPS endpoint and a separate, non-root execution account." ); } + if (!Object.keys(config.workspaces).every(isOpaqueId)) { + throw new Error("Runner workspace IDs must be valid opaque identifiers."); + } const env = { HOME: config.home, PATH: config.path, @@ -151,23 +169,31 @@ export async function runRemoteRunner(filename: string) { async function launch( command: Extract, - cwd: string + cwd: string, + key: string ) { const { agentId, workspace } = command; if (hosts.has(agentId) || active.has(agentId)) throw new Error("Runner already has a host for this agent"); active.add(agentId); try { - const binding = path.join(bindings, agentId); + const { mcp } = command.launch; + const mcpUrl = mcp === undefined ? undefined : new URL(mcp.url); + if (mcpUrl && (mcpUrl.protocol !== "https:" || !mcp?.token)) { + throw new Error( + "Remote service MCP requires HTTPS and a scoped token." + ); + } + const binding = path.join(bindings, key); await writeFile(binding, workspace, { flag: "wx", mode: 0o600 }).catch( async (error) => { - if (error.code !== "EEXIST" || !(await owns(agentId, workspace))) + if (error.code !== "EEXIST" || !(await owns(key, workspace))) throw error; } ); if (!(await stat(cwd)).isDirectory()) throw new Error("Guest workspace is unavailable"); - const dir = path.join(hostRoot, agentId); + const dir = path.join(hostRoot, key); const files = path.join(dir, "files"); const launch: HostLaunch = { ...command.launch, @@ -177,7 +203,7 @@ export async function runRemoteRunner(filename: string) { env: { DISPATCH_AGENT_ID: agentId, DISPATCH_FILES_DIR: files, - DISPATCH_API_URL: new URL(command.launch.mcp.url).origin, + ...(mcpUrl ? { DISPATCH_API_URL: mcpUrl.origin } : {}), NODE_EXTRA_CA_CERTS: config.ca, }, pathPrefix: [], @@ -193,7 +219,7 @@ export async function runRemoteRunner(filename: string) { }); await chown(hostFile(dir, "launch"), config.uid, config.gid); await chown(dir, config.uid, config.gid); - const log = openSync(path.join(logs, agentId), "a", 0o600); + const log = openSync(path.join(logs, key), "a", 0o600); try { const [bin, ...args] = hostCommand(); if (!bin) throw new Error("Runner host executable is missing"); @@ -268,29 +294,30 @@ export async function runRemoteRunner(filename: string) { }; async function request(id: string, command: Command) { - if (!/^[a-f0-9-]{36}$/.test(id)) - throw new Error("Invalid runner request ID"); + if (!isOpaqueId(id)) throw new Error("Invalid runner request ID"); if (socket.destroyed) return; const { agentId, workspace } = command; - const target = Object.hasOwn(config.workspaces, workspace) - ? config.workspaces[workspace] - : undefined; - if (!/^agt_[a-z0-9]+$/.test(agentId) || !target) + const target = + isOpaqueId(workspace) && Object.hasOwn(config.workspaces, workspace) + ? config.workspaces[workspace] + : undefined; + if (!isOpaqueId(agentId) || !target) throw new Error("Unknown runner workspace or agent"); + const key = runnerStorageKey(agentId); const result = (value?: string | boolean) => safeSend({ type: "result", id, value }); if (command.kind === "launch") { - await launch(command, target.cwd); + await launch(command, target.cwd, key); result(true); return; } - if (!(await owns(agentId, workspace))) { + if (!(await owns(key, workspace))) { if (command.kind === "alive") return result(false); throw new Error("Agent is not bound to this workspace"); } if (socket.destroyed) return; const host = hosts.get(agentId); - const dir = path.join(hostRoot, agentId); + const dir = path.join(hostRoot, key); switch (command.kind) { case "attach": { if (!host) { @@ -352,11 +379,11 @@ export async function runRemoteRunner(filename: string) { if (host || active.has(agentId)) throw new Error("Stop the guest host before discarding it"); await rm(dir, { force: true, recursive: true }); - await rm(path.join(bindings, agentId), { force: true }); + await rm(path.join(bindings, key), { force: true }); result(true); break; case "log": { - const log = await readFile(path.join(logs, agentId), "utf8").catch( + const log = await readFile(path.join(logs, key), "utf8").catch( () => "" ); result( @@ -410,7 +437,7 @@ export async function runRemoteRunner(filename: string) { clearTimeout(timeout); safeSend({ type: "ready", - version: 1, + version: RUNNER_WIRE_VERSION, workspaces: Object.keys(config.workspaces), }); }); diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index 0bf8e4c23..ceeea7af0 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -1,5 +1,4 @@ import type { BackgroundSnapshot } from "@dispatch/shared"; -import type { Effort } from "@dispatch/shared"; import type { AgentMcpInventoryResponse } from "@dispatch/shared"; import type { AgentInputState } from "@dispatch/shared"; import type { AgentPermissionsResponse } from "@dispatch/shared"; @@ -7,13 +6,13 @@ import type { PromptSource, PromptOptions } from "./acp/prompt-source.js"; import type { FastifyBaseLogger } from "fastify"; import type { Placement } from "./remote/protocol.js"; +import type { HostLaunch } from "./acp/host-protocol.js"; import type { AppConfig } from "../config.js"; import type { DriverEvent } from "./acp/driver.js"; import type { AvailableCommand, SessionConfigOption, } from "@agentclientprotocol/sdk"; -import type { AcpEngineId, EngineBins } from "./acp/engine-spec.js"; import { createAcpRuntime, type AcpRuntimeDeps } from "./acp/runtime.js"; /** @@ -21,29 +20,7 @@ import { createAcpRuntime, type AcpRuntimeDeps } from "./acp/runtime.js"; * The workspace (worktree, deps) already exists; this is only about the * process. See docs/design/acp-runtime.md. */ -export type RuntimeLaunch = { - agentId: string; - cwd: string; - placement?: Placement; - engine: AcpEngineId; - /** Missing only in launch files written before permission support (full access). */ - fullAccess?: boolean; - bins: EngineBins; - /** The model to select after the session opens; null keeps the engine's default. */ - model: string | null; - /** Resolved launch effort; null leaves the CLI settings in control. */ - effort?: Effort | null; - systemPrompt: string | null; - /** Persona task context delivered with the first ordinary prompt, including on resume. */ - personaContext?: string | null; - mcp: { url: string; token: string }; - /** Environment additions for the engine child (DISPATCH_*, files dir). */ - env: Record; - /** Directories the engine child's PATH is prefixed with. */ - pathPrefix: string[]; - /** Resume this ACP session; null opens a new one. */ - resumeSessionId: string | null; -}; +export type RuntimeLaunch = HostLaunch & { placement?: Placement }; export type RuntimeEventListener = ( agentId: string, diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index 875e85eee..1636240ba 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -602,6 +602,7 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); const id = "agt_host_receipt"; const { runtime } = runtimeWith(stateRoot, () => 0); const launch = launchFor(id, cwd); + delete launch.mcp; launch.bins.adapter = { bin: "bun", args: [path.join(here, "helpers/remote-acp-fixture.ts")], diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index b32517c7a..2b2cdc183 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -330,10 +330,11 @@ describe("AgentManager", () => { useWorktree: false, jobRunId: "run_1", }); - expect(lastLaunch().mcp.url).toBe( + expect(lastLaunch().mcp?.url).toBe( `http://127.0.0.1:6767/api/mcp/jobs/run_1/${agent.id}` ); - expect(lastLaunch().mcp.token).not.toBe( + expect(lastLaunch().mcp?.token).toEqual(expect.any(String)); + expect(lastLaunch().mcp?.token).not.toBe( createAgentMcpToken("test-token", agent.id) ); }); @@ -2415,10 +2416,11 @@ describe("AgentManager", () => { ); runtime.prompt.mockClear(); await manager.startAgent(agent.id); - expect(lastLaunch().mcp.url).toBe( + expect(lastLaunch().mcp?.url).toBe( `http://127.0.0.1:6767/api/mcp/jobs/run_resume/${agent.id}` ); - expect(lastLaunch().mcp.token).not.toBe( + expect(lastLaunch().mcp?.token).toEqual(expect.any(String)); + expect(lastLaunch().mcp?.token).not.toBe( createAgentMcpToken("test-token", agent.id) ); expect(lastLaunch().systemPrompt).toContain( @@ -2457,10 +2459,10 @@ describe("AgentManager", () => { ); runtime.prompt.mockClear(); await manager.startAgent(agent.id); - expect(lastLaunch().mcp.url).toBe( + expect(lastLaunch().mcp?.url).toBe( `http://127.0.0.1:6767/api/mcp/${agent.id}` ); - expect(lastLaunch().mcp.token).toBe( + expect(lastLaunch().mcp?.token).toBe( createAgentMcpToken("test-token", agent.id) ); expect(lastLaunch().systemPrompt).not.toContain("job_complete"); diff --git a/apps/server/test/remote-runner-startup.test.ts b/apps/server/test/remote-runner-startup.test.ts index f8712a1f9..3499bb318 100644 --- a/apps/server/test/remote-runner-startup.test.ts +++ b/apps/server/test/remote-runner-startup.test.ts @@ -45,7 +45,19 @@ vi.mock("node:tls", async (original) => ({ connect: dial, })); -import { runRemoteRunner } from "../src/agents/remote/runner.js"; +import { + runnerStorageKey, + runRemoteRunner, +} from "../src/agents/remote/runner.js"; + +it("preserves prototype storage while keeping opaque wire IDs out of paths", () => { + expect(runnerStorageKey("agt_123456")).toBe("agt_123456"); + const key = runnerStorageKey("../tenant/Agent:42"); + expect(key).toMatch(/^opaque-[A-Za-z0-9_-]{43}$/); + expect(runnerStorageKey("../tenant/Agent:42")).toBe(key); + expect(runnerStorageKey("../tenant/agent:42")).not.toBe(key); + expect(runnerStorageKey("logs")).not.toBe("logs"); +}); const unprivilegedStatus = [ "Uid:\t1000\t1000\t1000\t1000", diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts new file mode 100644 index 000000000..b1ba321ca --- /dev/null +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -0,0 +1,77 @@ +import { Duplex } from "node:stream"; +import { + type Frame, + isOpaqueId, + remotePlacement, + workspaceLocator, +} from "@dispatch/runner-protocol"; +import { hostChannel, wireFrames } from "@dispatch/runner-protocol/node"; +import { expect, it } from "vitest"; + +it("round-trips opaque locator components without URL normalization", () => { + const placement = { runner: "Runner/β", workspace: "../repo?x=%2F#main" }; + const locator = workspaceLocator(placement); + expect(locator).toBe("runner://Runner%2F%CE%B2/..%2Frepo%3Fx%3D%252F%23main"); + expect(remotePlacement(locator)).toEqual(placement); + expect(remotePlacement("runner://lima/proof")).toEqual({ + runner: "lima", + workspace: "proof", + }); + for (const invalid of [ + "runner://lima/", + "runner://lima/raw/slash", + "runner://lima/raw?query", + "runner://lima/%FF", + "runner://lima/%00", + "runner://lima/proof\n", + ]) { + expect(remotePlacement(invalid)).toBeNull(); + } + expect(isOpaqueId("provider/act:42")).toBe(true); + expect(isOpaqueId("a".repeat(129))).toBe(false); + expect(isOpaqueId("\ud800")).toBe(false); +}); + +it("consumes the v1 launch and channel framing without Dispatch server imports", async () => { + const received: Frame[] = []; + // Feed each write to the decoder a byte at a time, including split UTF-8. + const transport = new Duplex({ + read() {}, + write(chunk: Buffer, _encoding, done) { + for (const byte of chunk) transport.emit("data", Buffer.from([byte])); + done(); + }, + }); + const send = wireFrames(transport, (frame) => received.push(frame)); + const launch: Frame = { + type: "request", + id: "provider:launch/42", + command: { + kind: "launch", + agentId: "provider:agent/42", + workspace: "workspace:β", + launch: { + agentId: "provider:agent/42", + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + }, + }, + }; + send(launch); + const channel = hostChannel("provider:attach/42", send, () => {}); + await new Promise((resolve, reject) => { + channel.write(Buffer.from([0, 255]), (error) => { + if (error) reject(error); + else resolve(); + }); + }); + channel.destroy(); + expect(received).toEqual([ + launch, + { type: "data", id: "provider:attach/42", data: "AP8=" }, + { type: "close", id: "provider:attach/42" }, + ]); + transport.destroy(); +}); diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index b072e6910..de249980e 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -53,6 +53,11 @@ mounts and SSH-agent forwarding, and keep the VM and dev data disposable. ## Wire contract +The [portable protocol package](../../packages/runner-protocol/README.md) +defines the v1 wire types, opaque locators, optional service MCP, and +consumer receipt and replay semantics. The setup and traces below describe +the prototype artifact. + The runner sends `ready` with protocol version 1 and its workspace handles. The service requires a trusted client certificate, a matching manual approval fingerprint, and a workspace in both sides' configuration. A service request diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md new file mode 100644 index 000000000..efc2cc803 --- /dev/null +++ b/packages/runner-protocol/README.md @@ -0,0 +1,77 @@ +# Remote runner protocol v1 + +`@dispatch/runner-protocol` exports transport frame types, host replay and +receipt types, and workspace locator helpers. It has no dependencies outside +the package. The separate `@dispatch/runner-protocol/node` entry point provides +NDJSON framing and a `Duplex` channel for Node-compatible runtimes. The package +ships TypeScript source for Bun or a TypeScript-aware bundler. + +## Identity and transport + +Runner registration is a service-side identity bound to its authenticated +connection. The runner's `ready` frame advertises version 1 and the workspace +handles available on that connection. Route an operation by registration and +workspace, then send the selected workspace and agent IDs in the command. A +runner binds an agent to a workspace and checks the binding on later commands. +The command's agent ID is authoritative for a launch. + +Identifiers are case-sensitive strings of 1 to 128 UTF-16 code units and +exclude control characters and unpaired surrogates. Treat them as opaque, +including those containing slashes or percent signs. Build +`runner:///` using `workspaceLocator`. Decode each component +once after splitting, as in `remotePlacement`. For example, +`runner://Fleet%2FNorth/Team%20A%2Frepo` names `Fleet/North` and `Team A/repo`. +Legacy locators such as `runner://lima/proof` are still accepted. + +Each outer frame is JSON followed by a newline, encoded in UTF-8. A request +ID correlates a `request` with its `result` within the connection. For +`attach`, that ID also names the channel for base64 `data` and `close` +frames. The decoded channel bytes carry a separate NDJSON stream. A +transport close ends its channels, and a reconnect can attach to an +existing host. Use unique request IDs within each connection. These IDs +provide correlation only. + +The guest resolves the working directory, executable and environment. +The optional launch field `mcp` supplies one service-scoped MCP endpoint +using an HTTPS `url`, bearer `token`, and optional `name`. Absence starts the +ACP session with an empty service MCP list. v1 launches with the original +`{ url, token }` shape use the server name `dispatch`. Prototype runner +binaries require that shape, so keep sending it when interoperating with +those binaries. + +## Receipts and replay + +| Signal | Meaning | +| ----------------------------------- | ----------------------------------------------------- | +| Launch `result` with `value: true` | The runner spawned the guest host process. | +| Host `welcome` with `running: true` | The host reports a ready ACP session. | +| `prompt_accepted` | The host confirmed handoff to ACP for that operation. | +| Journaled terminal turn event | The turn settled, with its reported outcome. | + +An outer request timeout or dropped result may leave execution unknown. +After attaching, send `hello` with the last durably applied `fromSeq`, its +`journalId`, and `replayComplete: true`. Use sequence 0 on the first attach. +`welcome` gives the current journal identity and the inclusive replay head. +The host sends events strictly after the resume position through that head, +then sends `replay_complete` when requested. Later events are live. If the +journal identity changed or the cursor exceeds the new head, the host starts +replay from 0. Reset the receiver's stream position before accepting the +replacement. An omitted journal identity is supported for legacy clients. + +Deduplicate by journal ID and sequence within the bound agent. Sequences +start at 1 and increase contiguously. A gap prevents advancing the contiguous +cursor. Persist each payload or its projection atomically with that cursor, +or persist the payload first with idempotent application on retry. +`replay_complete` marks the sender's replay boundary. The receiver's next +`hello` advertises the prefix it committed. + +For prompts, persist the operation ID and selected journal ID before +sending, and include both in the host prompt. The host records a claim +before submission and an accepted receipt before sending +`prompt_accepted`. Repeating an accepted operation on the same journal +returns its receipt without submitting again. A recorded claim without an +accepted receipt, or a request for a different journal, yields an unknown +outcome. Reconcile such an operation from journal evidence and avoid automatic +resubmission. A legacy prompt with no journal ID bypasses receipt +deduplication. `prompt_deferred` explicitly indicates the host held back +submission because an engine-initiated turn was already open. diff --git a/packages/runner-protocol/package.json b/packages/runner-protocol/package.json new file mode 100644 index 000000000..1da5efc48 --- /dev/null +++ b/packages/runner-protocol/package.json @@ -0,0 +1,13 @@ +{ + "name": "@dispatch/runner-protocol", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./node": "./src/node.ts" + }, + "files": [ + "src" + ] +} diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts new file mode 100644 index 000000000..4c6f66870 --- /dev/null +++ b/packages/runner-protocol/src/index.ts @@ -0,0 +1,130 @@ +export type Placement = { runner: string; workspace: string }; + +/** Wire identities are case-sensitive and are not paths. */ +export function isOpaqueId(value: unknown): value is string { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > 128 || + /[\x00-\x1f\x7f-\x9f]/u.test(value) + ) { + return false; + } + try { + // Reject lone UTF-16 surrogates, which have no UTF-8 representation. + encodeURIComponent(value); + return true; + } catch { + return false; + } +} + +/** Split first and decode each component exactly once. URL parsers can normalize IDs. */ +export function remotePlacement(cwd: string): Placement | null { + const match = /^runner:\/\/([\w.!~*'()%+-]+)\/([\w.!~*'()%+-]+)$/.exec(cwd); + if (!match || match[0] !== cwd) return null; + try { + const runner = decodeURIComponent(match[1]!); + const workspace = decodeURIComponent(match[2]!); + return isOpaqueId(runner) && isOpaqueId(workspace) + ? { runner, workspace } + : null; + } catch { + return null; + } +} + +export function workspaceLocator({ runner, workspace }: Placement): string { + if (!isOpaqueId(runner) || !isOpaqueId(workspace)) { + throw new Error("Invalid runner or workspace ID"); + } + return `runner://${encodeURIComponent(runner)}/${encodeURIComponent(workspace)}`; +} + +export const RUNNER_WIRE_VERSION = 1; + +export type RunnerEngine = "claude" | "codex" | "opencode"; + +export type ServiceMcp = { + url: string; + token: string; + /** Legacy launchers omit the name and use "dispatch". */ + name?: string; +}; + +/** The guest supplies all machine-local execution settings. */ +export type RemoteLaunch = { + agentId: string; + engine: RunnerEngine; + fullAccess?: boolean; + model: string | null; + effort?: string | null; + systemPrompt: string | null; + personaContext?: string | null; + mcp?: ServiceMcp; + resumeSessionId: string | null; +}; + +export type Command = { agentId: string; workspace: string } & ( + | { kind: "launch"; launch: RemoteLaunch } + | { kind: "attach" | "alive" | "discard" | "log" | "repo" } + | { kind: "stop"; force: boolean } +); +export type Frame = + | { type: "ready"; version: typeof RUNNER_WIRE_VERSION; workspaces: string[] } + | { type: "request"; id: string; command: Command } + | { + type: "result"; + id: string; + value?: boolean | string; + error?: string; + code?: "host-gone"; + } + | { type: "data"; id: string; data: string } + | { type: "close"; id: string }; + +/** The last durably applied position in the named host journal. */ +export type ReplayHello = { + type: "hello"; + fromSeq: number; + journalId?: string | null; + replayComplete?: boolean; +}; + +export type HostWelcome = { + type: "welcome"; + agentId: string; + engine: RunnerEngine; + sessionId: string; + resumed: boolean; + running: boolean; + journalSeq: number; + journalId?: string; +}; + +export type JournalEntry = { + seq: number; + at: string; + event: Event; + /** Absent on entries written by older hosts. */ + journalId?: string; +}; + +export type HostEvent = { + type: "event"; +} & JournalEntry; +export type ReplayComplete = { type: "replay_complete" }; + +export type HostPrompt = { + type: "prompt"; + id: string; + text: string; + journalId?: string; + source?: Source; + images?: Image[]; +}; + +export type PromptReceipt = + | { type: "prompt_accepted"; id: string } + /** An engine-initiated turn is open and the host did not submit this prompt. */ + | { type: "prompt_deferred"; id: string }; diff --git a/packages/runner-protocol/src/node.ts b/packages/runner-protocol/src/node.ts new file mode 100644 index 000000000..f2ec198c2 --- /dev/null +++ b/packages/runner-protocol/src/node.ts @@ -0,0 +1,59 @@ +import { Duplex } from "node:stream"; +import { StringDecoder } from "node:string_decoder"; +import type { Frame } from "./index.js"; + +type Send = (frame: Frame) => void; + +export function wireFrames( + socket: Duplex, + receive: (frame: Frame) => void +): Send { + const decoder = new StringDecoder("utf8"); + let pending = ""; + socket.on("data", (chunk: Buffer) => { + pending += decoder.write(chunk); + let newline: number; + while ((newline = pending.indexOf("\n")) >= 0) { + if (newline > 32 * 1024 * 1024) return socket.destroy(); + const line = pending.slice(0, newline); + pending = pending.slice(newline + 1); + try { + receive(JSON.parse(line) as Frame); + } catch { + return socket.destroy(); + } + } + if (pending.length > 32 * 1024 * 1024) socket.destroy(); + }); + return (frame) => { + if (socket.destroyed || socket.writableLength > 32 * 1024 * 1024) { + socket.destroy(); + throw new Error("Runner connection is unavailable"); + } + socket.write(JSON.stringify(frame) + "\n"); + }; +} + +export function hostChannel(id: string, send: Send, dispose: () => void) { + return new Duplex({ + allowHalfOpen: false, + read() {}, + write(chunk: Buffer, _encoding, callback) { + try { + send({ type: "data", id, data: chunk.toString("base64") }); + callback(); + } catch (error) { + callback(error as Error); + } + }, + destroy(error, callback) { + dispose(); + try { + send({ type: "close", id }); + } catch { + /* transport already closed */ + } + callback(error); + }, + }); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8f5434c88..f6febd538 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -74,6 +74,9 @@ importers: '@agentclientprotocol/sdk': specifier: 1.8.0 version: 1.8.0(zod@4.3.6) + '@dispatch/runner-protocol': + specifier: workspace:* + version: link:../../packages/runner-protocol '@dispatch/shared': specifier: workspace:* version: link:../../packages/shared @@ -392,6 +395,8 @@ importers: specifier: ^2.1.0 version: 2.1.9(@types/node@24.12.0)(happy-dom@18.0.1)(jsdom@29.1.1)(sass@1.51.0)(terser@5.46.1) + packages/runner-protocol: {} + packages/shared: {} packages: From b78ca4b923d05a111cfa9375bd93d8c15e00b9d9 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:46:07 -0700 Subject: [PATCH 007/642] Clarify Dispatch durable receive cursor semantics --- packages/runner-protocol/README.md | 27 +++++++++++++++------------ packages/runner-protocol/src/index.ts | 2 +- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index efc2cc803..01162e31d 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -49,21 +49,24 @@ those binaries. | Journaled terminal turn event | The turn settled, with its reported outcome. | An outer request timeout or dropped result may leave execution unknown. -After attaching, send `hello` with the last durably applied `fromSeq`, its -`journalId`, and `replayComplete: true`. Use sequence 0 on the first attach. +After attaching, send `hello` with `fromSeq`, its `journalId`, and +`replayComplete: true`. Dispatch sets `fromSeq` to the last contiguous +sequence whose full event payload and receive cursor committed together in +PostgreSQL. Use sequence 0 on the first attach. + `welcome` gives the current journal identity and the inclusive replay head. -The host sends events strictly after the resume position through that head, -then sends `replay_complete` when requested. Later events are live. If the -journal identity changed or the cursor exceeds the new head, the host starts -replay from 0. Reset the receiver's stream position before accepting the -replacement. An omitted journal identity is supported for legacy clients. +For the same journal, replay starts strictly after `fromSeq` and continues +through that head. The host then sends `replay_complete` when requested. +Later events are live. If the journal identity changed or the cursor exceeds +the new head, the host starts replay from 0. Reset the receiver's cursor +before recording the replacement stream. An omitted journal identity is +supported for legacy clients. Deduplicate by journal ID and sequence within the bound agent. Sequences -start at 1 and increase contiguously. A gap prevents advancing the contiguous -cursor. Persist each payload or its projection atomically with that cursor, -or persist the payload first with idempotent application on retry. -`replay_complete` marks the sender's replay boundary. The receiver's next -`hello` advertises the prefix it committed. +start at 1 and increase contiguously. A gap prevents advancing the receive +cursor. `replay_complete` marks the sender's replay boundary. The receiver's +next `hello` acknowledges the prefix it committed. Projection of stored +events and prompt delivery receipts have separate state from this cursor. For prompts, persist the operation ID and selected journal ID before sending, and include both in the host prompt. The host records a claim diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index 4c6f66870..d62f77bc3 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -83,7 +83,7 @@ export type Frame = | { type: "data"; id: string; data: string } | { type: "close"; id: string }; -/** The last durably applied position in the named host journal. */ +/** The last contiguous position durably received in the named host journal. */ export type ReplayHello = { type: "hello"; fromSeq: number; From f63685123a40314919243f4cdb80c37ecdc872e8 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:48:44 -0700 Subject: [PATCH 008/642] Commit remote host payload and contiguous replay cursor together --- apps/server/src/agents/acp/host-client.ts | 23 ++++++- apps/server/src/agents/acp/runtime.ts | 67 ++++++++++++++----- apps/server/src/agents/manager.ts | 17 +++-- apps/server/src/agents/remote/event-inbox.ts | 48 +++++++++++++ apps/server/src/agents/runtime.ts | 11 ++- .../db/migrations/0052_remote_host_event.sql | 3 + apps/server/test/remote-event-inbox.test.ts | 48 +++++++++++++ 7 files changed, 194 insertions(+), 23 deletions(-) create mode 100644 apps/server/src/agents/remote/event-inbox.ts create mode 100644 apps/server/src/db/migrations/0052_remote_host_event.sql create mode 100644 apps/server/test/remote-event-inbox.test.ts diff --git a/apps/server/src/agents/acp/host-client.ts b/apps/server/src/agents/acp/host-client.ts index 9aee2f6b6..734a4a0fb 100644 --- a/apps/server/src/agents/acp/host-client.ts +++ b/apps/server/src/agents/acp/host-client.ts @@ -224,7 +224,23 @@ export class HostClient { private wire(socket: Duplex): void { const decode = ndjsonDecoder(); socket.on("data", (chunk) => { - for (const message of decode(chunk)) this.handle(message); + for (const message of decode(chunk)) { + if (socket.destroyed || this.socket !== socket) break; + if ( + this.deps.openSocket && + ((message.type === "welcome" && + (message.agentId !== this.deps.agentId || !message.journalId)) || + (message.type === "event" && + (!this.lastWelcome || + message.event?.agentId !== this.deps.agentId || + !Number.isSafeInteger(message.seq) || + message.seq < 1))) + ) { + socket.destroy(); + break; + } + this.handle(message); + } }); socket.on("error", (err) => { this.deps.logger.debug( @@ -635,6 +651,11 @@ export class HostClient { return this.socket !== null && !this.socket.destroyed; } + /** Reject an incomplete journal suffix and ask for replay on a fresh channel. */ + replay(): void { + this.socket?.destroy(); + } + /** Stop reconnecting and drop the socket. */ close(): void { this.closed = true; diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index c23d0a804..6f346eac0 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -42,6 +42,7 @@ import { type RemoteRunnerService, } from "../remote/service.js"; import type { Placement } from "../remote/protocol.js"; +import type { RemoteEventInbox } from "../remote/event-inbox.js"; import { HostClient } from "./host-client.js"; import { type HostLaunch, @@ -255,6 +256,7 @@ type Live = { /** Event handling is serialized per agent so rows land in seq order. */ events: Promise; lastSeq: number; + durableSeq: number; journalId: string | null; /** Resolvers for turns waiting on their settle event. */ settleWaiters: Array<() => void>; @@ -367,6 +369,8 @@ function sourceBlockIds(source?: PromptSource): string[] { export type AcpRuntimeDeps = { remote?: RemoteRunnerService; + remoteInbox?: Pick; + recoverRemoteEvent?: (agentId: string) => Promise; placement?: (agentId: string) => Promise; classifySteering?: ClassifySteering; config: Pick; @@ -415,6 +419,10 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { function dispatchEntry(agentId: string, entry: Live, journal: JournalEntry) { if (journal.seq <= entry.lastSeq) return; // replayed, already applied + if (entry.remote && journal.seq !== entry.lastSeq + 1) { + entry.client.replay(); + return; + } entry.lastSeq = journal.seq; emit(agentId, entry, journal.event, journal.seq); } @@ -730,17 +738,37 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { entry.settleWaiters = []; for (const resolve of waiters) resolve(); } - entry.events = entry.events - .catch(() => {}) - .then(async () => { - for (const listener of listeners) { - try { - await listener(agentId, event, seq); - } catch (err) { - logger.warn({ err, agentId }, "runtime event listener failed"); - } + const journalId = entry.journalId; + const inbox = + entry.remote && seq > 0 && journalId ? deps.remoteInbox : undefined; + entry.events = entry.events.then(async () => { + if (inbox && journalId) { + await inbox.receive(agentId, { journalId, seq, event }); + entry.durableSeq = seq; + } + for (const listener of listeners) { + try { + await listener(agentId, event, seq, Boolean(inbox)); + } catch (err) { + if (inbox) throw err; + logger.warn({ err, agentId }, "runtime event listener failed"); } - }); + } + if (inbox && journalId) await inbox.projected(agentId, journalId, seq); + }); + // Leave a failed projection recoverable in the inbox. Never apply later + // events over a partial projection. The service reopens it on attach. + void entry.events.catch((err) => { + if (live.get(agentId) !== entry) return; + logger.error( + { err, agentId, seq }, + "remote event projection interrupted" + ); + entry.client.close(); + live.delete(agentId); + failWaiting(entry, new Error("Remote output projection interrupted")); + for (const resolve of entry.settleWaiters.splice(0)) resolve(); + }); } function connect( @@ -764,8 +792,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { ): Promise { const existing = live.get(agentId); if (existing) return existing; - const cursor = await deps.hostSeq(agentId); const placement = await placementOf(agentId); + if (placement) await deps.recoverRemoteEvent?.(agentId); + const cursor = await deps.hostSeq(agentId); const entry: Live = { remote: Boolean(placement), client: null as unknown as HostClient, @@ -783,6 +812,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { conversation: undefined, events: Promise.resolve(), lastSeq: cursor.seq, + durableSeq: cursor.seq, journalId: cursor.journalId, settleWaiters: [], }; @@ -791,8 +821,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { socketPath: hostFile(stateDir(agentId), "socket"), ...(placement ? { - openSocket: async () => - ( + openSocket: async () => { + await entry.events; + return ( await remoteService().request( placement, { @@ -802,7 +833,8 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }, true ) - ).channel!, + ).channel!; + }, reconnectError: (error: unknown) => error instanceof RunnerUnavailable ? "retry" @@ -813,7 +845,8 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { } : {}), logger, - fromSeq: () => entry.lastSeq, + fromSeq: () => + entry.remote && deps.remoteInbox ? entry.durableSeq : entry.lastSeq, journalId: () => entry.journalId, onEvent: (journal) => dispatchEntry(agentId, entry, journal), onPermissions: (requests) => @@ -837,6 +870,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { "agent host journal changed; replaying from the beginning" ); entry.lastSeq = 0; + entry.durableSeq = 0; } if ( welcome.journalId && @@ -1086,7 +1120,8 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { return false; } } - if (live.has(agentId)) return true; + const current = live.get(agentId); + if (current) return !current.remote || current.client.isReady(); const placement = await placementOf(agentId); if (placement) { if ( diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 475b271ca..e52ad16f2 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -72,6 +72,7 @@ import type { PromptImage, } from "./acp/prompt-source.js"; import { type EngineBins, isAcpEngine } from "./acp/engine-spec.js"; +import { RemoteEventInbox } from "./remote/event-inbox.js"; import { remotePlacement } from "./remote/protocol.js"; import type { RemoteRunnerService } from "./remote/service.js"; import { buildLaunchEnv } from "./acp/launch-env.js"; @@ -401,11 +402,17 @@ export class AgentManager { this.eventBus = createAgentEventBus(logger); this.streamStore = new StreamStore(pool); this.streamRecorder = new StreamRecorder(this.streamStore, logger); + const remoteInbox = new RemoteEventInbox(pool); this.runtime = options.runtime ?? createAgentRuntime(config, logger, { classifySteering: options.classifySteering, remote: this.remote, + remoteInbox, + recoverRemoteEvent: (agentId) => + remoteInbox.recover(agentId, (event) => + this.handleRuntimeEvent(agentId, event, 0, true) + ), placement: async (id) => { const row = ( await pool.query<{ cwd: string }>( @@ -436,8 +443,8 @@ export class AgentManager { ); }, }); - this.runtime.onEvent((agentId, event, seq) => - this.handleRuntimeEvent(agentId, event, seq) + this.runtime.onEvent((agentId, event, seq, receivedRemotely) => + this.handleRuntimeEvent(agentId, event, seq, receivedRemotely) ); this.reconciler = createReconciler({ pool, @@ -472,7 +479,8 @@ export class AgentManager { private async handleRuntimeEvent( agentId: string, event: DriverEvent, - seq: number + seq: number, + receivedRemotely = false ): Promise { if (event.type === "permissions") { this.attentionHistory.permissions(agentId, event.requests); @@ -503,6 +511,7 @@ export class AgentManager { if (event.type === "turn" && event.state !== "settled") this.attentionHistory.settleBlocked(agentId); await this.streamRecorder.handle(event); + if (receivedRemotely) await this.streamRecorder.flush(agentId); if (event.type === "turn" && event.state === "settled" && event.usage) { await this.recordUsage(agentId); } @@ -517,7 +526,7 @@ export class AgentManager { this.logger.warn({ err, agentId }, "Git context refresh failed") ); } - if (seq > 0) { + if (seq > 0 && !receivedRemotely) { await this.pool.query( "UPDATE agents SET host_seq = GREATEST(host_seq, $2) WHERE id = $1", [agentId, seq] diff --git a/apps/server/src/agents/remote/event-inbox.ts b/apps/server/src/agents/remote/event-inbox.ts new file mode 100644 index 000000000..8c5ab7ea3 --- /dev/null +++ b/apps/server/src/agents/remote/event-inbox.ts @@ -0,0 +1,48 @@ +import type { Pool } from "pg"; +import type { DriverEvent } from "../acp/driver.js"; + +type Receipt = { journalId: string; seq: number; event: DriverEvent }; + +/** The host cursor acknowledges storage; product projection can recover from this row. */ +export class RemoteEventInbox { + constructor(private readonly pool: Pool) {} + + async receive(agentId: string, receipt: Receipt): Promise { + const result = await this.pool.query( + `UPDATE agents SET host_seq = $3, host_pending_event = $4::jsonb + WHERE id = $1 AND host_journal_id = $2 + AND ((host_seq = $3::integer - 1 AND host_pending_event IS NULL) + OR (host_seq = $3 AND host_pending_event = $4::jsonb))`, + [agentId, receipt.journalId, receipt.seq, JSON.stringify(receipt.event)] + ); + if (!result.rowCount) + throw new Error("Remote journal cursor or session changed"); + } + + async projected( + agentId: string, + journalId: string, + seq: number + ): Promise { + await this.pool.query( + `UPDATE agents SET host_pending_event = NULL + WHERE id = $1 AND host_journal_id = $2 AND host_seq = $3`, + [agentId, journalId, seq] + ); + } + + async recover( + agentId: string, + project: (event: DriverEvent) => Promise + ): Promise { + const { rows } = await this.pool.query( + `SELECT host_journal_id AS "journalId", host_seq AS seq, host_pending_event AS event + FROM agents WHERE id = $1 AND host_pending_event IS NOT NULL`, + [agentId] + ); + const pending = rows[0]; + if (!pending) return; + await project(pending.event); + await this.projected(agentId, pending.journalId, pending.seq); + } +} diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index 0bf8e4c23..a361a6fb0 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -48,7 +48,8 @@ export type RuntimeLaunch = { export type RuntimeEventListener = ( agentId: string, event: DriverEvent, - seq: number + seq: number, + receivedRemotely?: boolean ) => Promise | void; /** @@ -148,7 +149,13 @@ export function createAgentRuntime( logger: FastifyBaseLogger, deps: Pick< AcpRuntimeDeps, - "hostSeq" | "syncJournal" | "classifySteering" | "remote" | "placement" + | "hostSeq" + | "syncJournal" + | "remoteInbox" + | "recoverRemoteEvent" + | "classifySteering" + | "remote" + | "placement" > ): AgentRuntime { if (config.agentRuntime === "inert") { diff --git a/apps/server/src/db/migrations/0052_remote_host_event.sql b/apps/server/src/db/migrations/0052_remote_host_event.sql new file mode 100644 index 000000000..24966d1e3 --- /dev/null +++ b/apps/server/src/db/migrations/0052_remote_host_event.sql @@ -0,0 +1,3 @@ +-- Receiving a remote event and advancing its journal cursor are one row write. +-- At most one event per session is awaiting Dispatch projection. +ALTER TABLE agents ADD COLUMN host_pending_event jsonb; diff --git a/apps/server/test/remote-event-inbox.test.ts b/apps/server/test/remote-event-inbox.test.ts new file mode 100644 index 000000000..6629457fa --- /dev/null +++ b/apps/server/test/remote-event-inbox.test.ts @@ -0,0 +1,48 @@ +import { afterAll, beforeAll, expect, it, vi } from "vitest"; +import type { Pool } from "pg"; +import { RemoteEventInbox } from "../src/agents/remote/event-inbox.js"; +import { runTestMigrations, setupTestDb, teardownTestDb } from "./db/setup.js"; + +let pool: Pool; +const agentId = "agt_remote_receipt"; +const journalId = "first journal"; +const event = { + type: "turn", + agentId, + state: "settled", + stopReason: "end_turn", +} as const; + +beforeAll(async () => { + pool = await setupTestDb(); + await runTestMigrations(); + await pool.query( + "INSERT INTO agents (id, name, cwd, status, host_journal_id) VALUES ($1, 'Receipt', 'runner://a/proof', 'running', $2)", + [agentId, journalId] + ); +}); +afterAll(teardownTestDb); + +it("recovers the last contiguous committed payload across service restart", async () => { + const first = new RemoteEventInbox(pool); + const input = { journalId, seq: 1, event }; + await expect(first.receive(agentId, { ...input, seq: 2 })).rejects.toThrow(); + await expect( + first.receive(agentId, { ...input, journalId: "replaced" }) + ).rejects.toThrow(); + await first.receive(agentId, input); + // Lost SQL reply after commit. Same receipt is idempotent, a newer event + // cannot overwrite the pending payload. + await first.receive(agentId, input); + await expect(first.receive(agentId, { ...input, seq: 2 })).rejects.toThrow(); + const restarted = new RemoteEventInbox(pool); + const project = vi.fn(async () => {}); + await restarted.recover(agentId, project); + await restarted.recover(agentId, project); + expect(project).toHaveBeenCalledExactlyOnceWith(event); + await restarted.receive(agentId, { ...input, seq: 2 }); + expect( + (await pool.query("SELECT host_seq FROM agents WHERE id=$1", [agentId])) + .rows[0].host_seq + ).toBe(2); +}); From fe993aa5477276864fbf95a34890efa63db7f82d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:52:31 -0700 Subject: [PATCH 009/642] Address runners by opaque id; fall back to This Mac when selection goes stale Co-Authored-By: Claude Sonnet 5.5 --- .../components/app/use-create-agent-form.ts | 21 +++++++++++++------ apps/web/src/hooks/use-runners.test.ts | 4 ++-- apps/web/src/hooks/use-runners.ts | 6 +++--- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/app/use-create-agent-form.ts b/apps/web/src/components/app/use-create-agent-form.ts index 511b9d4f5..d8df76dc1 100644 --- a/apps/web/src/components/app/use-create-agent-form.ts +++ b/apps/web/src/components/app/use-create-agent-form.ts @@ -65,13 +65,22 @@ export function useCreateAgentForm({ // null runner = this Mac (the default). A runner swaps the folder for one // of its approved workspaces, addressed by a runner:// locator. const { data: runners = [] } = useRunners(); - const [runnerId, setRunnerId] = useState(null); - const [runnerWorkspace, setRunnerWorkspace] = useState(null); - const runner = runnerId ? runners.find((r) => r.id === runnerId) : undefined; - const remote = Boolean(runnerId); + const [pickedRunnerId, setRunnerId] = useState(null); + const [pickedWorkspace, setRunnerWorkspace] = useState(null); + // A runner that vanished or was revoked falls back to This Mac. + const runner = runners.find( + (r) => r.id === pickedRunnerId && r.status !== "revoked" + ); + const runnerId = runner?.id ?? null; + const remote = Boolean(runner); + // Only a workspace the runner reports now, on an online runner, can submit. + const runnerWorkspace = + runner && pickedWorkspace && runner.workspaces.includes(pickedWorkspace) + ? pickedWorkspace + : null; const remoteCwd = - runner && runnerWorkspace - ? runnerLocator(runner.name, runnerWorkspace) + runner?.status === "online" && runnerWorkspace + ? runnerLocator(runner.id, runnerWorkspace) : ""; const selectRunner = (id: string | null) => { setRunnerId(id); diff --git a/apps/web/src/hooks/use-runners.test.ts b/apps/web/src/hooks/use-runners.test.ts index b4cbc3cfb..6763d4168 100644 --- a/apps/web/src/hooks/use-runners.test.ts +++ b/apps/web/src/hooks/use-runners.test.ts @@ -4,8 +4,8 @@ import { runnerLocator } from "./use-runners"; describe("runnerLocator", () => { it("encodes both components", () => { - expect(runnerLocator("a/b", "my proof#1")).toBe( - "runner://a%2Fb/my%20proof%231" + expect(runnerLocator("rn_a/b", "my proof#1")).toBe( + "runner://rn_a%2Fb/my%20proof%231" ); }); }); diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index ce3cf7692..0366d462d 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -15,9 +15,9 @@ export type RunnerPairing = { id: string; command: string; expiresAt: string }; export const runnersQueryKey = ["runners"] as const; -/** Locator the server stores in an agent's cwd; both parts are encoded. */ -export function runnerLocator(name: string, workspace: string): string { - return `runner://${encodeURIComponent(name)}/${encodeURIComponent(workspace)}`; +/** Locator the server stores in an agent's cwd: opaque runner id, both parts encoded. */ +export function runnerLocator(runnerId: string, workspace: string): string { + return `runner://${encodeURIComponent(runnerId)}/${encodeURIComponent(workspace)}`; } export function useRunners(options: { poll?: boolean } = {}) { From b494690c57feb81a6161706adc5aaf42f2bcb81b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:55:53 -0700 Subject: [PATCH 010/642] Enroll remote runners with one-time pairing and per-runner mTLS peers Dispatch now issues its own runner CA and listener certificate (stored in PostgreSQL) and pairs runners with a one-time code over a CA-pinned TLS exchange; the runner generates its key locally. Each registration is an independent mTLS peer addressed by runner name, persisted with its last reported workspaces and revocable via DELETE /api/runners/:id, which drops its live connection. The runner listener also proxies bearer-authenticated agent MCP calls so an external MCP origin is optional. The legacy single-registration config keeps working. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/manager.ts | 2 +- apps/server/src/agents/remote/enrollment.ts | 267 +++++++ apps/server/src/agents/remote/registry.ts | 281 +++++++ apps/server/src/agents/remote/service.ts | 720 ++++++++++++++++-- apps/server/src/agents/remote/x509.ts | 262 +++++++ .../migrations/0052_runner_registrations.sql | 34 + apps/server/src/main.ts | 3 + apps/server/src/routes/runners.ts | 69 ++ apps/server/src/server.ts | 15 +- apps/server/test/migrations.test.ts | 6 + .../test/remote-runner-enrollment.test.ts | 422 ++++++++++ apps/server/test/runner-routes.test.ts | 97 +++ docs/design/remote-runner-prototype.md | 31 + 13 files changed, 2136 insertions(+), 73 deletions(-) create mode 100644 apps/server/src/agents/remote/enrollment.ts create mode 100644 apps/server/src/agents/remote/registry.ts create mode 100644 apps/server/src/agents/remote/x509.ts create mode 100644 apps/server/src/db/migrations/0052_runner_registrations.sql create mode 100644 apps/server/src/routes/runners.ts create mode 100644 apps/server/test/remote-runner-enrollment.test.ts create mode 100644 apps/server/test/runner-routes.test.ts diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 475b271ca..e36f972d1 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -2133,7 +2133,7 @@ export class AgentManager { personaContext: extractPersonaContext(agent.agentArgs ?? []), mcp: { url: placement - ? `${this.remote!.origin}/api/mcp/${agent.id}` + ? `${this.remote!.originFor(placement)}/api/mcp/${agent.id}` : dispatchMcpUrl(this.config, agent.id, opts.jobRunId), token, }, diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts new file mode 100644 index 000000000..87b20fe11 --- /dev/null +++ b/apps/server/src/agents/remote/enrollment.ts @@ -0,0 +1,267 @@ +import { X509Certificate } from "node:crypto"; +import { existsSync, readFileSync, statSync } from "node:fs"; +import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises"; +import { isIP } from "node:net"; +import path from "node:path"; +import { connect, type PeerCertificate, type TLSSocket } from "node:tls"; +import { wireFrames } from "./protocol.js"; +import { generateRunnerKey, normalizeFingerprint } from "./x509.js"; + +/* + * One-time-code pairing. An unauthenticated TLS client on the runner port + * may send exactly one `enroll` frame. The runner pins the service CA by + * its SHA-256 fingerprint (carried in the pairing command) before it reveals + * the code, generates its private key locally and only sends the public key. + */ + +export type EnrollFrame = + | { type: "enroll"; version: 1; code: string; publicKey: string } + | { type: "enrolled"; id: string; name: string; cert: string; ca: string } + | { type: "enroll_error"; error: string }; + +export const RUNNER_NAME = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/; + +export function formatHost(host: string) { + return isIP(host) === 6 ? `[${host}]` : host; +} + +export function pairingCommand(input: { + host: string; + port: number; + caFingerprint: string; + code: string; +}) { + const pin = normalizeFingerprint(input.caFingerprint) + .replace(/:/g, "") + .toLowerCase(); + return [ + "dispatch-runner remote-runner-pair", + `--endpoint https://${formatHost(input.host)}:${input.port}`, + `--ca-sha256 ${pin}`, + `--code ${input.code}`, + ].join(" "); +} + +/** + * Verify a TLS peer against a pinned CA without any prior trust store: the + * chain must contain the pinned CA, the leaf must be issued and signed by it, + * be currently valid, and name the dialed host. + */ +export function verifyPinnedPeer( + socket: TLSSocket, + host: string, + pin: string +): X509Certificate { + const expected = normalizeFingerprint(pin); + const leafInfo = socket.getPeerCertificate(true); + if (!leafInfo?.raw) throw new Error("The service sent no certificate."); + const chain: X509Certificate[] = []; + const seen = new Set(); + for ( + let entry: PeerCertificate | undefined = leafInfo; + entry?.raw && !seen.has(entry.fingerprint256); + entry = (entry as { issuerCertificate?: PeerCertificate }).issuerCertificate + ) { + seen.add(entry.fingerprint256); + chain.push(new X509Certificate(entry.raw)); + } + const leaf = chain[0]!; + const ca = chain.find((cert) => cert.fingerprint256 === expected); + const now = Date.now(); + const current = (cert: X509Certificate) => + new Date(cert.validFrom).getTime() <= now && + now <= new Date(cert.validTo).getTime(); + const names = isIP(host) ? leaf.checkIP(host) : leaf.checkHost(host); + if ( + !ca || + !ca.ca || + ca === leaf || + !leaf.checkIssued(ca) || + !leaf.verify(ca.publicKey) || + !current(ca) || + !current(leaf) || + !names + ) { + throw new Error( + "The service certificate does not match the pinned Dispatch runner CA." + ); + } + return ca; +} + +type PairOptions = { + endpoint: string; + pin: string; + code: string; + dir: string; + config?: string; + timeoutMs?: number; +}; + +function parseArgs(argv: string[]): PairOptions { + const values = new Map(); + for (let index = 0; index < argv.length; index += 2) { + const flag = argv[index]; + const value = argv[index + 1]; + if (!flag?.startsWith("--") || value === undefined) + throw new Error(`Unexpected argument: ${flag ?? ""}`); + values.set(flag.slice(2), value); + } + const endpoint = values.get("endpoint"); + const pin = values.get("ca-sha256"); + const code = values.get("code"); + if (!endpoint || !pin || !code) + throw new Error( + "Usage: dispatch-runner remote-runner-pair --endpoint https://HOST:PORT --ca-sha256 HEX --code CODE [--dir /etc/dispatch-runner] [--config FILE]" + ); + const dir = path.resolve(values.get("dir") ?? "/etc/dispatch-runner"); + return { + endpoint, + pin, + code, + dir, + config: values.get("config"), + }; +} + +async function writeAtomic(file: string, data: string, mode: number) { + const temporary = `${file}.${process.pid}.tmp`; + await rm(temporary, { force: true }); + try { + await writeFile(temporary, data, { mode, flag: "wx" }); + await chmod(temporary, mode); + await rename(temporary, file); + } finally { + await rm(temporary, { force: true }); + } +} + +/** Dial the service, verify the pin, and exchange the code for a cert. */ +export async function exchangeCode(input: { + endpoint: string; + pin: string; + code: string; + publicKey: string; + timeoutMs?: number; +}) { + const url = new URL(input.endpoint); + if (url.protocol !== "https:") + throw new Error("The pairing endpoint must use https."); + const host = url.hostname.replace(/^\[|\]$/g, ""); + const port = Number(url.port || 443); + return new Promise>( + (resolve, reject) => { + let settled = false; + const socket = connect({ + host, + port, + ...(isIP(host) ? {} : { servername: host }), + // Trust comes only from the pinned CA, checked before sending the code. + rejectUnauthorized: false, + }); + const finish = (error?: Error, value?: unknown) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + if (error) reject(error); + else resolve(value as Extract); + }; + const timer = setTimeout( + () => finish(new Error("Pairing timed out.")), + input.timeoutMs ?? 15_000 + ); + socket.on("error", (error: Error) => finish(error)); + socket.on("close", () => + finish(new Error("The service closed the pairing connection.")) + ); + socket.once("secureConnect", () => { + let ca: X509Certificate; + try { + ca = verifyPinnedPeer(socket, host, input.pin); + } catch (error) { + return finish(error as Error); + } + const send = wireFrames(socket, (frame) => { + const reply = frame as unknown as EnrollFrame; + if (reply.type === "enroll_error") + return finish(new Error(reply.error)); + if (reply.type !== "enrolled") + return finish(new Error("Unexpected pairing reply.")); + try { + const issuedCa = new X509Certificate(reply.ca); + const cert = new X509Certificate(reply.cert); + if ( + issuedCa.fingerprint256 !== ca.fingerprint256 || + !cert.checkIssued(issuedCa) || + !cert.verify(issuedCa.publicKey) || + cert.publicKey.export({ type: "spki", format: "pem" }) !== + input.publicKey + ) + throw new Error("The issued certificate does not match."); + } catch (error) { + return finish(error as Error); + } + finish(undefined, reply); + }); + send({ + type: "enroll", + version: 1, + code: input.code, + publicKey: input.publicKey, + } as never); + }); + } + ); +} + +/** `dispatch-runner remote-runner-pair …`: enroll this host as a runner. */ +export async function runRunnerPairing(argv: string[]) { + const options = parseArgs(argv); + const { key, publicKey } = generateRunnerKey(); + const enrolled = await exchangeCode({ + endpoint: options.endpoint, + pin: options.pin, + code: options.code, + publicKey, + }); + await mkdir(options.dir, { recursive: true, mode: 0o755 }); + const files = { + ca: path.join(options.dir, "ca.pem"), + cert: path.join(options.dir, "cert.pem"), + key: path.join(options.dir, "key.pem"), + }; + // The key stays root-only; the CLI account reads only the CA. + await writeAtomic(files.key, key, 0o600); + await writeAtomic(files.cert, enrolled.cert, 0o644); + await writeAtomic(files.ca, enrolled.ca, 0o644); + + const configFile = + options.config ?? + (existsSync(path.join(options.dir, "runner.json")) + ? path.join(options.dir, "runner.json") + : undefined); + if (configFile) { + const current = JSON.parse(readFileSync(configFile, "utf8")); + const mode = statSync(configFile).mode & 0o777; + await writeAtomic( + configFile, + JSON.stringify( + { ...current, endpoint: options.endpoint, ...files }, + null, + 2 + ) + "\n", + mode & 0o077 ? 0o600 : mode + ); + } + process.stdout.write( + [ + `Enrolled runner "${enrolled.name}" (${enrolled.id}).`, + `Credentials: ${options.dir}`, + configFile + ? `Updated ${configFile}.` + : `Add to runner.json: ${JSON.stringify({ endpoint: options.endpoint, ...files })}`, + "", + ].join("\n") + ); +} diff --git a/apps/server/src/agents/remote/registry.ts b/apps/server/src/agents/remote/registry.ts new file mode 100644 index 000000000..1e05d68b4 --- /dev/null +++ b/apps/server/src/agents/remote/registry.ts @@ -0,0 +1,281 @@ +import { createHash, randomBytes } from "node:crypto"; +import { X509Certificate } from "node:crypto"; +import type { Pool } from "pg"; +import { + issueAuthority, + issueClient, + issueServer, + runnerPublicKey, + type Issued, +} from "./x509.js"; + +export type Authority = { + ca: Required; + server: Required; + hosts: string[]; + port: number | null; +}; + +export type Registration = { + id: string; + name: string; + endpointHost: string; + fingerprint: string | null; + workspaces: string[]; + enrolled: boolean; + revoked: boolean; + codeExpiresAt: Date | null; +}; + +type Row = { + id: string; + name: string; + endpoint_host: string; + cert_fingerprint: string | null; + workspaces: string[]; + enrolled_at: Date | null; + revoked_at: Date | null; + code_expires_at: Date | null; +}; + +const PAIRING_TTL_MS = 10 * 60 * 1000; + +export class RunnerNameTaken extends Error {} +export class PairingRejected extends Error {} + +function hashCode(code: string) { + return createHash("sha256").update(code).digest("hex"); +} + +function registration(row: Row): Registration { + return { + id: row.id, + name: row.name, + endpointHost: row.endpoint_host, + fingerprint: row.cert_fingerprint, + workspaces: row.workspaces, + enrolled: Boolean(row.enrolled_at), + revoked: Boolean(row.revoked_at), + codeExpiresAt: row.code_expires_at, + }; +} + +/** PostgreSQL persistence for the runner CA, registrations and pairing codes. */ +export class RunnerRegistry { + constructor(private readonly pool: Pool) {} + + /** Load the authority, creating the CA on first use and widening SANs. */ + async authority(hosts: string[] = []): Promise { + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + const { rows } = await client.query( + `SELECT ca_cert, ca_key, server_cert, server_key, server_hosts, port + FROM runner_authority WHERE id = 1 FOR UPDATE` + ); + let row = rows[0] as + | { + ca_cert: string; + ca_key: string; + server_cert: string; + server_key: string; + server_hosts: string[]; + port: number | null; + } + | undefined; + const ca = row + ? { cert: row.ca_cert, key: row.ca_key } + : issueAuthority( + `Dispatch runner CA ${randomBytes(4).toString("hex")}` + ); + const known = row?.server_hosts ?? []; + const wanted = [...new Set([...known, ...hosts])]; + const renew = + !row || + wanted.length !== known.length || + new Date(new X509Certificate(row.server_cert).validTo).getTime() - + Date.now() < + 30 * 24 * 60 * 60 * 1000; + if (renew) { + const server = issueServer(ca, wanted.length ? wanted : ["localhost"]); + await client.query( + `INSERT INTO runner_authority + (id, ca_cert, ca_key, server_cert, server_key, server_hosts) + VALUES (1, $1, $2, $3, $4, $5::jsonb) + ON CONFLICT (id) DO UPDATE SET + server_cert = EXCLUDED.server_cert, + server_key = EXCLUDED.server_key, + server_hosts = EXCLUDED.server_hosts, + updated_at = now()`, + [ca.cert, ca.key, server.cert, server.key, JSON.stringify(wanted)] + ); + row = { + ca_cert: ca.cert, + ca_key: ca.key, + server_cert: server.cert, + server_key: server.key, + server_hosts: wanted, + port: row?.port ?? null, + }; + } + await client.query("COMMIT"); + const stored = row!; + return { + ca, + server: { cert: stored.server_cert, key: stored.server_key }, + hosts: stored.server_hosts, + port: stored.port, + }; + } catch (error) { + await client.query("ROLLBACK").catch(() => {}); + throw error; + } finally { + client.release(); + } + } + + async savePort(port: number) { + await this.pool.query( + `UPDATE runner_authority SET port = $1, updated_at = now() WHERE id = 1`, + [port] + ); + } + + /** Never-redeemed codes stop holding their name once they expire. */ + private async pruneExpired() { + await this.pool.query( + `DELETE FROM runner_registrations + WHERE enrolled_at IS NULL AND code_expires_at <= now()` + ); + } + + async list(): Promise { + await this.pruneExpired(); + const { rows } = await this.pool.query( + `SELECT * FROM runner_registrations ORDER BY created_at, id` + ); + return rows.map(registration); + } + + async active(): Promise { + const { rows } = await this.pool.query( + `SELECT * FROM runner_registrations + WHERE revoked_at IS NULL AND cert_fingerprint IS NOT NULL` + ); + return rows.map(registration); + } + + async hasActive() { + await this.pruneExpired(); + const { rows } = await this.pool.query( + `SELECT 1 FROM runner_registrations WHERE revoked_at IS NULL LIMIT 1` + ); + return rows.length > 0; + } + + async create(name: string, endpointHost: string) { + await this.pruneExpired(); + const id = `rnr_${randomBytes(6).toString("hex")}`; + const code = randomBytes(20).toString("base64url"); + const expiresAt = new Date(Date.now() + PAIRING_TTL_MS); + try { + await this.pool.query( + `INSERT INTO runner_registrations + (id, name, endpoint_host, code_hash, code_expires_at) + VALUES ($1, $2, $3, $4, $5)`, + [id, name, endpointHost, hashCode(code), expiresAt] + ); + } catch (error) { + if ((error as { code?: string }).code === "23505") + throw new RunnerNameTaken(`A runner named "${name}" already exists.`); + throw error; + } + return { id, code, expiresAt }; + } + + /** + * Redeem a one-time code: issue a client certificate for the runner's own + * public key and bind the registration to that certificate's fingerprint. + */ + async redeem(code: string, publicKeyPem: string) { + const publicKey = (() => { + try { + return runnerPublicKey(publicKeyPem); + } catch { + throw new PairingRejected("The runner key is not supported."); + } + })(); + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + const { rows } = await client.query( + `SELECT * FROM runner_registrations + WHERE code_hash = $1 AND enrolled_at IS NULL AND revoked_at IS NULL + AND code_expires_at > now() + FOR UPDATE`, + [hashCode(code)] + ); + const row = rows[0]; + if (!row) + throw new PairingRejected( + "The pairing code is invalid, expired or already used." + ); + const { rows: authority } = await client.query( + `SELECT ca_cert, ca_key FROM runner_authority WHERE id = 1` + ); + const ca = { cert: authority[0].ca_cert, key: authority[0].ca_key }; + const cert = issueClient(ca, row.id, publicKey); + const parsed = new X509Certificate(cert); + await client.query( + `UPDATE runner_registrations + SET code_hash = NULL, code_expires_at = NULL, enrolled_at = now(), + cert_fingerprint = $2, cert_expires_at = $3 + WHERE id = $1`, + [row.id, parsed.fingerprint256, new Date(parsed.validTo)] + ); + await client.query("COMMIT"); + return { + registration: registration({ + ...row, + cert_fingerprint: parsed.fingerprint256, + enrolled_at: new Date(), + }), + cert, + ca: ca.cert, + }; + } catch (error) { + await client.query("ROLLBACK").catch(() => {}); + throw error; + } finally { + client.release(); + } + } + + async connected(id: string, workspaces: string[]) { + await this.pool.query( + `UPDATE runner_registrations + SET workspaces = $2::jsonb, last_seen_at = now() + WHERE id = $1 AND revoked_at IS NULL`, + [id, JSON.stringify(workspaces)] + ); + } + + async seen(id: string) { + await this.pool.query( + `UPDATE runner_registrations SET last_seen_at = now() WHERE id = $1`, + [id] + ); + } + + /** Revoke a registration; its code and certificate stop working at once. */ + async revoke(id: string): Promise { + const { rows } = await this.pool.query( + `UPDATE runner_registrations + SET revoked_at = COALESCE(revoked_at, now()), code_hash = NULL + WHERE id = $1 + RETURNING *`, + [id] + ); + return rows[0] ? registration(rows[0]) : undefined; + } +} diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 2dc423cd4..3c2bc1021 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1,6 +1,12 @@ +import { X509Certificate } from "node:crypto"; import { readFileSync, watchFile, unwatchFile } from "node:fs"; -import { createServer, type TLSSocket } from "node:tls"; +import http from "node:http"; +import https from "node:https"; +import { connect as connectTcp, isIP } from "node:net"; +import os from "node:os"; +import { createServer, type Server, type TLSSocket } from "node:tls"; import type { Duplex } from "node:stream"; +import type { Pool } from "pg"; import { hostChannel, wireFrames, @@ -8,8 +14,21 @@ import { type Frame, type Placement, } from "./protocol.js"; +import { + formatHost, + pairingCommand, + RUNNER_NAME, + type EnrollFrame, +} from "./enrollment.js"; +import { + PairingRejected, + RunnerNameTaken, + RunnerRegistry, + type Registration, +} from "./registry.js"; -type Config = { +/** The single manually approved registration of the original prototype. */ +export type LegacyConfig = { id: string; host: string; port: number; @@ -18,129 +37,686 @@ type Config = { ca: string; approval: string; workspaces: string[]; - mcpOrigin: string; + /** Guest-reachable HTTPS MCP origin. Defaults to this listener's proxy. */ + mcpOrigin?: string; + /** Host the guest dials for the default MCP origin. */ + endpointHost?: string; + repoTool?: boolean; +}; + +export type EnrollmentOptions = { + registry: RunnerRegistry; + /** Bind address for the runner listener. */ + host: string; + /** Fixed listener port; otherwise the persisted (or first free) port. */ + port?: number; + /** Host written into pairing commands and the listener certificate. */ + endpointHost?: string; + /** External HTTPS MCP origin; defaults to the runner listener's proxy. */ + mcpOrigin?: string; repoTool?: boolean; + log?: Pick; +}; + +export type RunnerStatus = "pending" | "online" | "offline" | "revoked"; +export type RunnerSummary = { + id: string; + name: string; + status: RunnerStatus; + workspaces: string[]; }; export class RunnerUnavailable extends Error {} export class RunnerHostGone extends Error {} +export class RunnerRequestError extends Error { + constructor( + readonly status: number, + message: string + ) { + super(message); + } +} -export function configuredRunner() { +type Gate = { + /** Runner name addressed by placements. */ + name: string; + registrationId?: string; + approved(): boolean; + allows(workspace: string): boolean; + ready?(workspaces: string[]): void; +}; + +type Settle = (frame?: Extract) => void; + +type Peer = { + socket: TLSSocket; + send: (frame: Frame) => void; + workspaces: Set; + gate: Gate; + pending: Map; + channels: Map; +}; + +const WORKSPACE = /^[a-z0-9-]+$/; +const LEGACY_PREFIX = "legacy-"; +const MAX_UNAUTHENTICATED = 64; + +function validHost(host: string) { + return ( + isIP(host) > 0 || + /^[a-zA-Z0-9](?:[a-zA-Z0-9.-]{0,251}[a-zA-Z0-9])?$/.test(host) + ); +} + +function httpsOrigin(value: string | undefined, label: string) { + if (!value) return undefined; + if (new URL(value).protocol !== "https:") + throw new Error(`${label} must use HTTPS`); + return value.replace(/\/$/, ""); +} + +export function configuredRunner(input?: { + pool: Pool; + host: string; + apiPort: number; + apiTls: boolean; +}) { const filename = process.env.DISPATCH_REMOTE_SERVICE_CONFIG; - return filename - ? new RemoteRunnerService(JSON.parse(readFileSync(filename, "utf8"))) + const legacy: LegacyConfig | undefined = filename + ? JSON.parse(readFileSync(filename, "utf8")) + : undefined; + const enrollment: EnrollmentOptions | undefined = + input && process.env.DISPATCH_RUNNERS !== "0" + ? { + registry: new RunnerRegistry(input.pool), + host: process.env.DISPATCH_RUNNER_HOST ?? input.host, + port: process.env.DISPATCH_RUNNER_PORT + ? Number(process.env.DISPATCH_RUNNER_PORT) + : undefined, + endpointHost: process.env.DISPATCH_RUNNER_ENDPOINT_HOST, + mcpOrigin: process.env.DISPATCH_RUNNER_MCP_ORIGIN, + repoTool: process.env.DISPATCH_RUNNER_REPO_TOOL === "1", + log: console, + } + : undefined; + return legacy || enrollment + ? new RemoteRunnerService( + legacy, + enrollment, + input && { host: input.host, port: input.apiPort, tls: input.apiTls } + ) : undefined; } export class RemoteRunnerService { - private peer?: { - socket: TLSSocket; - send: (frame: Frame) => void; - workspaces: Set; - }; + /** Connected runners by placement name; each is an independent peer. */ + private readonly peers = new Map(); + /** Enrolled, unrevoked registrations by client certificate fingerprint. */ + private readonly enrolled = new Map(); + private readonly legacySockets = new Set(); private readonly sockets = new Set(); - private readonly channels = new Map(); - private readonly pending = new Map< - string, - (frame?: Extract) => void - >(); - private listener?: ReturnType; + private unauthenticated = 0; + private legacyListener?: Server; + private listener?: Server; + private listening?: Promise; + private authority?: { caFingerprint: string; serverCert: string }; + private port?: number; + private readonly proxy: http.Server; + private proxyPort?: Promise; - constructor(private readonly config: Config) { - if (new URL(config.mcpOrigin).protocol !== "https:") - throw new Error("Runner MCP origin must use HTTPS"); + constructor( + private readonly legacy?: LegacyConfig, + private readonly enrollment?: EnrollmentOptions, + /** Local Dispatch API that the listeners proxy agent MCP requests to. */ + private readonly api?: { host: string; port: number; tls: boolean } + ) { + if (legacy) { + httpsOrigin(legacy.mcpOrigin, "Runner MCP origin"); + if (!legacy.mcpOrigin && !legacy.endpointHost) + throw new Error( + "Runner service config needs mcpOrigin or endpointHost for MCP." + ); + } + if (enrollment) { + httpsOrigin(enrollment.mcpOrigin, "DISPATCH_RUNNER_MCP_ORIGIN"); + if (enrollment.endpointHost && !validHost(enrollment.endpointHost)) + throw new Error("DISPATCH_RUNNER_ENDPOINT_HOST is not a valid host"); + } + this.proxy = http.createServer((request, response) => + this.forward(request, response) + ); + // MCP tool calls may legitimately run for a long time. + this.proxy.requestTimeout = 0; + this.proxy.headersTimeout = 30_000; } + /** Origin for an agent's MCP URL as seen from the runner it is placed on. */ + originFor(placement: Placement) { + if (this.legacy && placement.runner === this.legacy.id) + return ( + httpsOrigin(this.legacy.mcpOrigin, "Runner MCP origin") ?? + `https://${formatHost(this.legacy.endpointHost!)}:${this.legacy.port}` + ); + const configured = httpsOrigin( + this.enrollment?.mcpOrigin, + "DISPATCH_RUNNER_MCP_ORIGIN" + ); + if (configured) return configured; + const registration = this.registrationNamed(placement.runner); + if (!registration || !this.port) + throw new RunnerUnavailable("The runner is not enrolled."); + return `https://${formatHost(registration.endpointHost)}:${this.port}`; + } + + /** @deprecated Single-runner origin; prefer {@link originFor}. */ get origin() { - return this.config.mcpOrigin.replace(/\/$/, ""); + if (this.legacy) + return this.originFor({ runner: this.legacy.id, workspace: "" }); + const first = [...this.enrolled.values()][0]; + if (!first) throw new RunnerUnavailable("No runner is enrolled."); + return this.originFor({ runner: first.name, workspace: "" }); } + get repoTool() { - return this.config.repoTool === true; + return this.legacy?.repoTool === true || this.enrollment?.repoTool === true; } - private approved(socket: TLSSocket) { - try { - return ( - socket.authorized && - socket.getPeerCertificate().fingerprint256 === - readFileSync(this.config.approval, "utf8").trim() - ); - } catch { - return false; - } + private registrationNamed(name: string) { + for (const registration of this.enrolled.values()) + if (registration.name === name) return registration; + return undefined; } + // --------------------------------------------------------------------------- + // Listeners + // --------------------------------------------------------------------------- + + /** Start the legacy listener (no database needed). */ async start() { - const { host, port, ca, cert, key, approval } = this.config; + const legacy = this.legacy; + if (!legacy || this.legacyListener) return; const listener = createServer( { - ca: readFileSync(ca), - cert: readFileSync(cert), - key: readFileSync(key), + ca: readFileSync(legacy.ca), + cert: readFileSync(legacy.cert), + key: readFileSync(legacy.key), requestCert: true, - rejectUnauthorized: true, + rejectUnauthorized: false, }, - (socket) => this.accept(socket) + (socket) => this.accept(socket, "legacy") ); - this.listener = listener; + this.legacyListener = listener; await new Promise((resolve, reject) => { listener.once("error", reject); - listener.listen(port, host, resolve); + listener.listen(legacy.port, legacy.host, resolve); }); - watchFile(approval, { interval: 500, persistent: false }, this.recheck); + watchFile( + legacy.approval, + { interval: 500, persistent: false }, + this.recheckLegacy + ); + } + + /** Start the enrolled listener when any registration exists. */ + async startEnrolled() { + if (this.enrollment && (await this.enrollment.registry.hasActive())) + await this.ensureListening(); } - private recheck = () => { - for (const socket of this.sockets) - if (!this.approved(socket)) socket.destroy(); + private legacyApproved(socket: TLSSocket) { + try { + return ( + socket.authorized && + socket.getPeerCertificate().fingerprint256 === + readFileSync(this.legacy!.approval, "utf8").trim() + ); + } catch { + return false; + } + } + + private recheckLegacy = () => { + for (const socket of this.legacySockets) + if (!this.legacyApproved(socket)) socket.destroy(); }; - private accept(socket: TLSSocket) { + private ensureListening(host?: string): Promise { + const run = async () => { + const options = this.enrollment!; + const authority = await options.registry.authority( + host ? [host] : [options.endpointHost ?? "localhost"] + ); + const context = { + ca: authority.ca.cert, + cert: authority.server.cert + authority.ca.cert, + key: authority.server.key, + }; + this.authority = { + caFingerprint: new X509Certificate(authority.ca.cert).fingerprint256, + serverCert: authority.server.cert, + }; + for (const registration of await options.registry.active()) + this.enrolled.set(registration.fingerprint!, registration); + if (this.listener) { + this.listener.setSecureContext(context); + return; + } + const listener = createServer( + { ...context, requestCert: true, rejectUnauthorized: false }, + (socket) => this.accept(socket, "enrolled") + ); + const listen = (port: number) => + new Promise((resolve, reject) => { + listener.once("error", reject); + listener.listen(port, options.host, () => { + listener.off("error", reject); + resolve(); + }); + }); + const preferred = options.port ?? authority.port ?? 0; + try { + await listen(preferred); + } catch (error) { + if ( + options.port !== undefined || + preferred === 0 || + (error as NodeJS.ErrnoException).code !== "EADDRINUSE" + ) + throw error; + options.log?.warn( + `Runner port ${preferred} is in use; enrolled runners must be re-paired.` + ); + await listen(0); + } + this.listener = listener; + const address = listener.address(); + this.port = typeof address === "object" && address ? address.port : 0; + if (this.port !== authority.port) + await options.registry.savePort(this.port); + options.log?.info( + `Dispatch runner listener on ${formatHost(options.host)}:${this.port}` + ); + }; + const next = (this.listening ?? Promise.resolve()) + .catch(() => {}) + .then(run); + this.listening = next; + return next; + } + + // --------------------------------------------------------------------------- + // Connections + // --------------------------------------------------------------------------- + + private accept(socket: TLSSocket, kind: "legacy" | "enrolled") { socket.on("error", () => socket.destroy()); - if (!this.approved(socket) || this.sockets.size) return socket.destroy(); this.sockets.add(socket); + socket.on("close", () => this.sockets.delete(socket)); + if (socket.authorized) { + const gate = this.gateFor(socket, kind); + return gate ? this.attachPeer(socket, gate) : socket.destroy(); + } + // Unauthenticated peers may pair once or reach the scoped MCP proxy. + if (this.unauthenticated >= MAX_UNAUTHENTICATED) return socket.destroy(); + this.unauthenticated++; + socket.once("close", () => this.unauthenticated--); + const deadline = setTimeout(() => socket.destroy(), 10_000); + socket.once("data", (chunk: Buffer) => { + clearTimeout(deadline); + if (chunk[0] === 0x7b && kind === "enrolled") { + socket.pause(); + socket.unshift(chunk); + this.pair(socket); + socket.resume(); + } else if ( + /^[A-Z]{3,7} \//.test(chunk.subarray(0, 9).toString("latin1")) + ) { + void this.relay(socket, chunk); + } else socket.destroy(); + }); + } + + /** + * Hand an HTTP connection to the loopback proxy server, which checks every + * request on it. Piping (rather than emitting the TLS socket into an + * http.Server) works the same under Node and Bun. + */ + private async relay(socket: TLSSocket, head: Buffer) { + socket.pause(); + try { + const port = await this.ensureProxy(); + if (socket.destroyed) return; + const upstream = connectTcp(port, "127.0.0.1"); + upstream.on("error", () => socket.destroy()); + socket.on("close", () => upstream.destroy()); + upstream.on("close", () => socket.destroy()); + upstream.write(head); + socket.pipe(upstream).pipe(socket); + socket.resume(); + } catch { + socket.destroy(); + } + } + + private ensureProxy() { + this.proxyPort ??= new Promise((resolve, reject) => { + this.proxy.once("error", reject); + this.proxy.listen(0, "127.0.0.1", () => { + const address = this.proxy.address(); + resolve(typeof address === "object" && address ? address.port : 0); + }); + }); + return this.proxyPort; + } + + private gateFor( + socket: TLSSocket, + kind: "legacy" | "enrolled" + ): Gate | undefined { + if (kind === "legacy") { + const legacy = this.legacy!; + if (!this.legacyApproved(socket)) return undefined; + this.legacySockets.add(socket); + socket.once("close", () => this.legacySockets.delete(socket)); + return { + name: legacy.id, + approved: () => this.legacyApproved(socket), + allows: (workspace) => legacy.workspaces.includes(workspace), + }; + } + const fingerprint = socket.getPeerCertificate().fingerprint256; + const registration = this.enrolled.get(fingerprint); + if (!registration) return undefined; + const registry = this.enrollment!.registry; + return { + name: registration.name, + registrationId: registration.id, + approved: () => this.enrolled.get(fingerprint)?.id === registration.id, + allows: () => true, + ready: (workspaces) => { + registration.workspaces = workspaces; + void registry.connected(registration.id, workspaces).catch(() => {}); + }, + }; + } + + private attachPeer(socket: TLSSocket, gate: Gate) { const deadline = setTimeout(() => socket.destroy(), 5000); + let peer: Peer | undefined; socket.on("close", () => { clearTimeout(deadline); - this.sockets.delete(socket); - this.peer = undefined; - for (const settle of this.pending.values()) settle(); - for (const channel of this.channels.values()) channel.push(null); + if (!peer) return; + if (this.peers.get(gate.name) === peer) this.peers.delete(gate.name); + for (const settle of peer.pending.values()) settle(); + for (const channel of peer.channels.values()) channel.push(null); + if (gate.registrationId) + void this.enrollment?.registry + .seen(gate.registrationId) + .catch(() => {}); }); const send = wireFrames(socket, (frame) => { - if (!this.approved(socket)) return socket.destroy(); - if (!this.peer) { + if (!gate.approved()) return socket.destroy(); + if (!peer) { if ( frame.type !== "ready" || frame.version !== 1 || - !Array.isArray(frame.workspaces) + !Array.isArray(frame.workspaces) || + frame.workspaces.length > 256 || + !frame.workspaces.every( + (workspace) => + typeof workspace === "string" && WORKSPACE.test(workspace) + ) ) return socket.destroy(); clearTimeout(deadline); - this.peer = { socket, send, workspaces: new Set(frame.workspaces) }; + peer = { + socket, + send, + workspaces: new Set(frame.workspaces), + gate, + pending: new Map(), + channels: new Map(), + }; + // A reconnect replaces a half-open predecessor for the same runner. + const previous = this.peers.get(gate.name); + this.peers.set(gate.name, peer); + previous?.socket.destroy(); + gate.ready?.(frame.workspaces); return; } - if (frame.type === "result") this.pending.get(frame.id)?.(frame); + if (frame.type === "result") peer.pending.get(frame.id)?.(frame); else if (frame.type === "data") - this.channels.get(frame.id)?.push(Buffer.from(frame.data, "base64")); - else if (frame.type === "close") this.channels.get(frame.id)?.push(null); + peer.channels.get(frame.id)?.push(Buffer.from(frame.data, "base64")); + else if (frame.type === "close") peer.channels.get(frame.id)?.push(null); else socket.destroy(); }); } - available(placement: Placement) { - return ( - placement.runner === this.config.id && - this.config.workspaces.includes(placement.workspace) && - Boolean( - this.peer?.workspaces.has(placement.workspace) && - this.approved(this.peer.socket) + private pair(socket: TLSSocket) { + let used = false; + const reply = (frame: EnrollFrame) => { + try { + send(frame as unknown as Frame); + } catch { + /* closed */ + } + socket.end(); + }; + const send = wireFrames(socket, (frame) => { + if (used) return socket.destroy(); + used = true; + const request = frame as unknown as EnrollFrame; + if ( + request.type !== "enroll" || + request.version !== 1 || + typeof request.code !== "string" || + request.code.length > 128 || + typeof request.publicKey !== "string" || + request.publicKey.length > 8192 ) + return reply({ + type: "enroll_error", + error: "Invalid pairing request.", + }); + this.enrollment!.registry.redeem(request.code, request.publicKey).then( + ({ registration, cert, ca }) => { + this.enrolled.set(registration.fingerprint!, registration); + reply({ + type: "enrolled", + id: registration.id, + name: registration.name, + cert, + ca, + }); + }, + (error) => { + // Slow down code guessing; codes carry 160 bits regardless. + setTimeout( + () => + reply({ + type: "enroll_error", + error: + error instanceof PairingRejected + ? error.message + : "Pairing failed.", + }), + 500 + ); + } + ); + }); + } + + /** Forward only bearer-authenticated agent MCP calls to the local API. */ + private forward( + request: http.IncomingMessage, + response: http.ServerResponse + ) { + const url = request.url ?? ""; + const ping = url === "/ping" && request.method === "GET"; + const mcp = + /^\/api\/mcp\/agt_[a-z0-9]+$/.test(url) && + /^Bearer \S+$/.test(request.headers.authorization ?? ""); + const target = this.api; + if ((!ping && !mcp) || !target) { + response.writeHead(ping || mcp ? 503 : 404).end(); + return; + } + const host = + target.host === "0.0.0.0" + ? "127.0.0.1" + : target.host === "::" + ? "::1" + : target.host; + const headers = { ...request.headers }; + for (const name of [ + "cookie", + "host", + "origin", + "referer", + "forwarded", + "x-forwarded-for", + "x-forwarded-host", + "x-forwarded-proto", + ]) + delete headers[name]; + const upstream = (target.tls ? https : http).request( + { + host, + port: target.port, + method: request.method, + path: url, + headers: { ...headers, host: `${formatHost(host)}:${target.port}` }, + // The API is on this machine; its certificate names its LAN hosts. + rejectUnauthorized: false, + }, + (reply) => { + response.writeHead(reply.statusCode ?? 502, reply.headers); + reply.pipe(response); + } + ); + upstream.on("error", () => { + if (!response.headersSent) response.writeHead(502); + response.end(); + }); + response.on("close", () => upstream.destroy()); + request.pipe(upstream); + } + + // --------------------------------------------------------------------------- + // Registration management (control API) + // --------------------------------------------------------------------------- + + async list(): Promise { + const runners: RunnerSummary[] = []; + if (this.legacy) { + const peer = this.peers.get(this.legacy.id); + runners.push({ + id: `${LEGACY_PREFIX}${this.legacy.id}`, + name: this.legacy.id, + status: peer?.gate.approved() ? "online" : "offline", + workspaces: peer + ? [...peer.workspaces].filter((w) => + this.legacy!.workspaces.includes(w) + ) + : [...this.legacy.workspaces], + }); + } + if (!this.enrollment) return runners; + for (const registration of await this.enrollment.registry.list()) { + const peer = this.peers.get(registration.name); + const online = + !registration.revoked && + peer?.gate.registrationId === registration.id && + peer.gate.approved(); + runners.push({ + id: registration.id, + name: registration.name, + status: registration.revoked + ? "revoked" + : !registration.enrolled + ? "pending" + : online + ? "online" + : "offline", + workspaces: online ? [...peer!.workspaces] : registration.workspaces, + }); + } + return runners; + } + + async createRegistration(name: unknown, hostHint?: string) { + if (!this.enrollment) + throw new RunnerRequestError(409, "Runner enrollment is disabled."); + if (typeof name !== "string" || !RUNNER_NAME.test(name)) + throw new RunnerRequestError( + 400, + "Runner names use lowercase letters, digits and hyphens (1-40 characters)." + ); + if (this.legacy?.id === name) + throw new RunnerRequestError( + 409, + `A runner named "${name}" already exists.` + ); + const host = this.enrollment.endpointHost ?? hostHint ?? os.hostname(); + if (!validHost(host)) + throw new RunnerRequestError(400, "The runner endpoint host is invalid."); + await this.ensureListening(host); + try { + const { id, code, expiresAt } = await this.enrollment.registry.create( + name, + host + ); + return { + id, + command: pairingCommand({ + host, + port: this.port!, + caFingerprint: this.authority!.caFingerprint, + code, + }), + expiresAt: expiresAt.toISOString(), + }; + } catch (error) { + if (error instanceof RunnerNameTaken) + throw new RunnerRequestError(409, error.message); + throw error; + } + } + + /** Revoke a registration and drop its live connection immediately. */ + async revoke(id: string) { + if (id.startsWith(LEGACY_PREFIX) && this.legacy) + throw new RunnerRequestError( + 409, + "This runner is configured by DISPATCH_REMOTE_SERVICE_CONFIG; empty its approval file to revoke it." + ); + if (!this.enrollment) + throw new RunnerRequestError(404, "Runner not found."); + const registration = await this.enrollment.registry.revoke(id); + if (!registration) throw new RunnerRequestError(404, "Runner not found."); + for (const [fingerprint, entry] of this.enrolled) + if (entry.id === id) this.enrolled.delete(fingerprint); + for (const peer of this.peers.values()) + if (peer.gate.registrationId === id) peer.socket.destroy(); + } + + // --------------------------------------------------------------------------- + // Agent operations + // --------------------------------------------------------------------------- + + available(placement: Placement) { + const peer = this.peers.get(placement.runner); + return Boolean( + peer && + peer.gate.approved() && + peer.gate.allows(placement.workspace) && + peer.workspaces.has(placement.workspace) ); } async request(placement: Placement, command: Command, open = false) { - const peer = this.peer; + const peer = this.peers.get(placement.runner); if ( !peer || !this.available(placement) || @@ -152,17 +728,17 @@ export class RemoteRunnerService { } const id = crypto.randomUUID(); const channel = open - ? hostChannel(id, peer.send, () => this.channels.delete(id)) + ? hostChannel(id, peer.send, () => peer.channels.delete(id)) : undefined; // The HostClient takes over error handling after the attach acknowledgement. channel?.on("error", () => {}); - if (channel) this.channels.set(id, channel); + if (channel) peer.channels.set(id, channel); try { const value = await new Promise( (resolve, reject) => { - const finish = (frame?: Extract) => { + const finish: Settle = (frame) => { clearTimeout(timer); - this.pending.delete(id); + peer.pending.delete(id); if (!frame) reject( new RunnerUnavailable( @@ -175,7 +751,7 @@ export class RemoteRunnerService { else resolve(frame.value); }; const timer = setTimeout(() => finish(), 20_000); - this.pending.set(id, finish); + peer.pending.set(id, finish); try { peer.send({ type: "request", id, command }); } catch { @@ -191,8 +767,10 @@ export class RemoteRunnerService { } close() { - unwatchFile(this.config.approval, this.recheck); + if (this.legacy) unwatchFile(this.legacy.approval, this.recheckLegacy); for (const socket of this.sockets) socket.destroy(); + this.legacyListener?.close(); this.listener?.close(); + if (this.proxyPort) this.proxy.close(); } } diff --git a/apps/server/src/agents/remote/x509.ts b/apps/server/src/agents/remote/x509.ts new file mode 100644 index 000000000..95adfd7a3 --- /dev/null +++ b/apps/server/src/agents/remote/x509.ts @@ -0,0 +1,262 @@ +import { + createHash, + createPrivateKey, + createPublicKey, + generateKeyPairSync, + randomBytes, + sign, + X509Certificate, + type KeyObject, +} from "node:crypto"; +import { isIP } from "node:net"; + +/* + * A minimal DER encoder for the three certificate shapes the runner service + * issues: its CA, its TLS server leaf and enrolled runner client leaves. It + * avoids depending on an openssl binary on either host (macOS ships + * LibreSSL, and minimal runner images often ship none). + */ + +function length(n: number) { + if (n < 0x80) return Buffer.from([n]); + const bytes: number[] = []; + for (let value = n; value > 0; value >>= 8) bytes.unshift(value & 0xff); + return Buffer.from([0x80 | bytes.length, ...bytes]); +} + +function tlv(tag: number, ...parts: Buffer[]) { + const body = Buffer.concat(parts); + return Buffer.concat([Buffer.from([tag]), length(body.length), body]); +} + +const sequence = (...parts: Buffer[]) => tlv(0x30, ...parts); +const set = (...parts: Buffer[]) => tlv(0x31, ...parts); +const octets = (value: Buffer) => tlv(0x04, value); +const TRUE = Buffer.from([0x01, 0x01, 0xff]); + +function integer(value: Buffer) { + let start = 0; + while (start < value.length - 1 && value[start] === 0) start++; + const trimmed = value.subarray(start); + return tlv( + 0x02, + trimmed[0]! & 0x80 ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed + ); +} + +function oid(dotted: string) { + const [first, second, ...rest] = dotted.split(".").map(Number); + const bytes = [first! * 40 + second!]; + for (const component of rest) { + const chunk = [component & 0x7f]; + for (let value = component >>> 7; value > 0; value >>>= 7) + chunk.unshift((value & 0x7f) | 0x80); + bytes.push(...chunk); + } + return tlv(0x06, Buffer.from(bytes)); +} + +/** A whole-byte BIT STRING (keys and signatures). */ +const bits = (value: Buffer) => tlv(0x03, Buffer.from([0]), value); + +/** A named-bit BIT STRING such as KeyUsage; DER drops trailing zero bits. */ +function flags(value: number) { + let unused = 0; + while (unused < 7 && !(value & (1 << unused))) unused++; + return tlv(0x03, Buffer.from([unused, value])); +} + +function time(date: Date) { + const iso = date.toISOString().replace(/[-:T]/g, "").slice(0, 14) + "Z"; + return date.getUTCFullYear() < 2050 + ? tlv(0x17, Buffer.from(iso.slice(2))) + : tlv(0x18, Buffer.from(iso)); +} + +function name(commonName: string) { + return sequence( + set(sequence(oid("2.5.4.3"), tlv(0x0c, Buffer.from(commonName)))) + ); +} + +function extension(id: string, value: Buffer, critical = false) { + return sequence(oid(id), ...(critical ? [TRUE] : []), octets(value)); +} + +function ipBytes(address: string) { + if (isIP(address) === 4) + return Buffer.from(address.split(".").map((part) => Number(part))); + const [head = "", tail = ""] = address.split("::"); + const groups = (part: string) => (part ? part.split(":") : []); + const left = groups(head); + const right = address.includes("::") ? groups(tail) : []; + const words = [ + ...left, + ...Array(8 - left.length - right.length).fill("0"), + ...right, + ]; + const out = Buffer.alloc(16); + words.forEach((word, index) => + out.writeUInt16BE(parseInt(word, 16), index * 2) + ); + return out; +} + +function subjectAltNames(hosts: string[]) { + return sequence( + ...hosts.map((host) => + isIP(host) ? tlv(0x87, ipBytes(host)) : tlv(0x82, Buffer.from(host)) + ) + ); +} + +const ECDSA_SHA256 = sequence(oid("1.2.840.10045.4.3.2")); + +function keyId(publicKey: KeyObject) { + return createHash("sha1") + .update(publicKey.export({ type: "spki", format: "der" })) + .digest(); +} + +export type Issued = { cert: string; key?: string }; + +type Issue = { + subject: string; + publicKey: KeyObject; + issuer: { name: string; key: KeyObject; publicKey: KeyObject }; + days: number; + extensions: Buffer[]; +}; + +function issue({ subject, publicKey, issuer, days, extensions }: Issue) { + const notBefore = new Date(Date.now() - 5 * 60 * 1000); + const notAfter = new Date(Date.now() + days * 24 * 60 * 60 * 1000); + const serial = randomBytes(16); + serial[0]! &= 0x7f; + const tbs = sequence( + tlv(0xa0, integer(Buffer.from([2]))), + integer(serial), + ECDSA_SHA256, + name(issuer.name), + sequence(time(notBefore), time(notAfter)), + name(subject), + publicKey.export({ type: "spki", format: "der" }), + tlv( + 0xa3, + sequence( + ...extensions, + extension("2.5.29.14", octets(keyId(publicKey))), + extension("2.5.29.35", sequence(tlv(0x80, keyId(issuer.publicKey)))) + ) + ) + ); + const der = sequence( + tbs, + ECDSA_SHA256, + bits(sign("sha256", tbs, issuer.key)) + ); + const body = der.toString("base64").replace(/.{1,64}/g, "$&\n"); + return `-----BEGIN CERTIFICATE-----\n${body}-----END CERTIFICATE-----\n`; +} + +function ecKeyPair() { + return generateKeyPairSync("ec", { namedCurve: "prime256v1" }); +} + +function pem(key: KeyObject) { + return key.export({ type: "pkcs8", format: "pem" }).toString(); +} + +export function issueAuthority(commonName: string): Required { + const { privateKey, publicKey } = ecKeyPair(); + const cert = issue({ + subject: commonName, + publicKey, + issuer: { name: commonName, key: privateKey, publicKey }, + days: 3650, + extensions: [ + extension("2.5.29.19", sequence(TRUE), true), + // keyCertSign | cRLSign + extension("2.5.29.15", flags(0x06), true), + ], + }); + return { cert, key: pem(privateKey) }; +} + +function signer(authority: Required) { + const ca = new X509Certificate(authority.cert); + return { + name: ca.subject.replace(/^CN=/, ""), + key: createPrivateKey(authority.key), + publicKey: ca.publicKey, + }; +} + +export function issueServer( + authority: Required, + hosts: string[] +): Required { + const { privateKey, publicKey } = ecKeyPair(); + const cert = issue({ + subject: hosts[0] ?? "dispatch-runner-service", + publicKey, + issuer: signer(authority), + days: 397, + extensions: [ + extension("2.5.29.19", sequence(), true), + // digitalSignature + extension("2.5.29.15", flags(0x80), true), + extension("2.5.29.37", sequence(oid("1.3.6.1.5.5.7.3.1"))), + extension("2.5.29.17", subjectAltNames(hosts)), + ], + }); + return { cert, key: pem(privateKey) }; +} + +/** Accept only modern keys the runner generated itself. */ +export function runnerPublicKey(pemText: string) { + const key = createPublicKey(pemText); + const details = key.asymmetricKeyDetails; + if ( + key.asymmetricKeyType === "ec" && + ["prime256v1", "secp384r1"].includes(details?.namedCurve ?? "") + ) + return key; + if (key.asymmetricKeyType === "ed25519") return key; + if (key.asymmetricKeyType === "rsa" && (details?.modulusLength ?? 0) >= 2048) + return key; + throw new Error("Unsupported runner key"); +} + +export function issueClient( + authority: Required, + registrationId: string, + publicKey: KeyObject +): string { + return issue({ + subject: registrationId, + publicKey, + issuer: signer(authority), + days: 365, + extensions: [ + extension("2.5.29.19", sequence(), true), + extension("2.5.29.15", flags(0x80), true), + extension("2.5.29.37", sequence(oid("1.3.6.1.5.5.7.3.2"))), + ], + }); +} + +export function generateRunnerKey() { + const { privateKey, publicKey } = ecKeyPair(); + return { + key: pem(privateKey), + publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(), + }; +} + +/** Normalize `AB:CD:…` and bare hex to the colon form Node reports. */ +export function normalizeFingerprint(value: string) { + const hex = value.replace(/[^a-fA-F0-9]/g, "").toUpperCase(); + if (hex.length !== 64) throw new Error("Expected a SHA-256 fingerprint"); + return hex.match(/../g)!.join(":"); +} diff --git a/apps/server/src/db/migrations/0052_runner_registrations.sql b/apps/server/src/db/migrations/0052_runner_registrations.sql new file mode 100644 index 000000000..7e2cb3133 --- /dev/null +++ b/apps/server/src/db/migrations/0052_runner_registrations.sql @@ -0,0 +1,34 @@ +-- Enrolled remote runners. The service authority holds the CA that issues the +-- runner listener certificate and every enrolled runner's client certificate. +-- One-time pairing codes are stored only as SHA-256 hashes. +CREATE TABLE runner_authority ( + id smallint PRIMARY KEY CHECK (id = 1), + ca_cert text NOT NULL, + ca_key text NOT NULL, + server_cert text NOT NULL, + server_key text NOT NULL, + server_hosts jsonb NOT NULL DEFAULT '[]'::jsonb, + port integer, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE runner_registrations ( + id text PRIMARY KEY, + name text NOT NULL, + endpoint_host text NOT NULL, + code_hash text UNIQUE, + code_expires_at timestamptz, + cert_fingerprint text UNIQUE, + cert_expires_at timestamptz, + workspaces jsonb NOT NULL DEFAULT '[]'::jsonb, + created_at timestamptz NOT NULL DEFAULT now(), + enrolled_at timestamptz, + last_seen_at timestamptz, + revoked_at timestamptz +); + +-- A name addresses placements (runner:///), so only one +-- unrevoked registration may hold it. +CREATE UNIQUE INDEX runner_registrations_active_name + ON runner_registrations (name) WHERE revoked_at IS NULL; diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index d1d14c6fa..3f015510b 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -37,6 +37,9 @@ if (process.argv[2]?.startsWith("recovery-")) { process.env.DISPATCH_HOST ?? "127.0.0.1", ] ); +} else if (process.argv[2] === "remote-runner-pair") { + const { runRunnerPairing } = await import("./agents/remote/enrollment.js"); + await runRunnerPairing(process.argv.slice(3)); } else if (process.argv[2] === "remote-runner") { const { runRemoteRunner } = await import("./agents/remote/runner.js"); await runRemoteRunner(process.argv[3]!); diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts new file mode 100644 index 000000000..644aecda5 --- /dev/null +++ b/apps/server/src/routes/runners.ts @@ -0,0 +1,69 @@ +import type { FastifyInstance, FastifyReply } from "fastify"; +import { + RunnerRequestError, + type RemoteRunnerService, +} from "../agents/remote/service.js"; + +type RunnerRouteDeps = { runners?: RemoteRunnerService }; + +function hostHint(host: string | undefined) { + if (!host) return undefined; + try { + return new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, ""); + } catch { + return undefined; + } +} + +function fail(reply: FastifyReply, error: unknown) { + if (error instanceof RunnerRequestError) + return reply.code(error.status).send({ error: error.message }); + throw error; +} + +/** + * Runner enrollment control API. These are ordinary /api routes, so the + * global auth hook protects them like every other control route. + */ +export async function registerRunnerRoutes( + app: FastifyInstance, + deps: RunnerRouteDeps +): Promise { + for (const base of ["/api/runners", "/api/v1/runners"]) { + app.get(base, async () => ({ + runners: (await deps.runners?.list()) ?? [], + })); + + app.post(base, async (request, reply) => { + if (!deps.runners) + return reply + .code(409) + .send({ error: "Runner enrollment is disabled." }); + const body = (request.body ?? {}) as { name?: unknown }; + try { + return reply + .code(201) + .send( + await deps.runners.createRegistration( + body.name, + hostHint(request.headers.host) + ) + ); + } catch (error) { + return fail(reply, error); + } + }); + + app.delete(`${base}/:id`, async (request, reply) => { + const { id } = request.params as { id: string }; + if (!deps.runners) + return reply.code(404).send({ error: "Runner not found." }); + try { + await deps.runners.revoke(id); + return { ok: true }; + } catch (error) { + return fail(reply, error); + } + }); + } +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index e7d44d72e..35345e843 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -126,6 +126,7 @@ import { registerMcpRoutes } from "./routes/mcp.js"; import { registerPersonaRoutes } from "./routes/personas.js"; import { registerPersonalityRoutes } from "./routes/personalities.js"; import { registerQuickPhraseRoutes } from "./routes/quick-phrases.js"; +import { registerRunnerRoutes } from "./routes/runners.js"; import { registerReleaseRoutes } from "./routes/release.js"; import { registerMacAppRoutes } from "./routes/mac-app.js"; import { MacAppUpdateBridge } from "./mac-app-update-bridge.js"; @@ -205,7 +206,12 @@ const pool = createPool(config); const serviceResourcesProbePool = createServiceResourcesProbePool(config); const routingSettings = new RoutingSettings(pool); const steeringDecisions = new SteeringDecisions(pool, routingSettings); -const remoteRunner = configuredRunner(); +const remoteRunner = configuredRunner({ + pool, + host: config.listenHosts?.[0] ?? config.host, + apiPort: config.port, + apiTls: Boolean(config.tls), +}); const agentManager = new AgentManager(pool, app.log, config, { remote: remoteRunner, classifySteering: steeringDecisions.classify, @@ -1313,6 +1319,7 @@ async function registerRoutes() { // --- Quick Phrases --- await registerQuickPhraseRoutes(app, { pool }); + await registerRunnerRoutes(app, { runners: remoteRunner }); } async function waitForDatabase(maxAttempts = 15, delayMs = 2000) { @@ -1346,6 +1353,12 @@ export async function initializeApp(options?: { await runMigrations(); } config.authToken = await getOrCreateAuthToken(pool); + // Enrolled runners reconnect before agents are restored and reconciled. + try { + await remoteRunner?.startEnrolled(); + } catch (error) { + app.log.error({ err: error }, "Runner listener failed to start"); + } // The model lists engines published in earlier sessions, for the pickers. await loadLearnedAgentModels(pool); serviceResources.setCollectionEnabled( diff --git a/apps/server/test/migrations.test.ts b/apps/server/test/migrations.test.ts index dab3167f1..4c21da5b8 100644 --- a/apps/server/test/migrations.test.ts +++ b/apps/server/test/migrations.test.ts @@ -75,6 +75,12 @@ describe("block_reactions uniqueness migration", () => { /** Rewinds task migrations, which depend on projects and agents, so older eras can replay. */ async function dropTasks(): Promise { + await pool.query( + "DROP TABLE IF EXISTS runner_registrations, runner_authority" + ); + await pool.query( + "DELETE FROM pgmigrations WHERE name = '0052_runner_registrations'" + ); await pool.query( "DELETE FROM pgmigrations WHERE name = '0051_attention_stream_events'" ); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts new file mode 100644 index 000000000..d18fa676e --- /dev/null +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -0,0 +1,422 @@ +import { X509Certificate } from "node:crypto"; +import http from "node:http"; +import https from "node:https"; +import type { AddressInfo } from "node:net"; +import { connect, type TLSSocket } from "node:tls"; +import type { Pool } from "pg"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { exchangeCode } from "../src/agents/remote/enrollment.js"; +import { wireFrames, type Frame } from "../src/agents/remote/protocol.js"; +import { RunnerRegistry } from "../src/agents/remote/registry.js"; +import { + RemoteRunnerService, + RunnerRequestError, + RunnerUnavailable, +} from "../src/agents/remote/service.js"; +import { + generateRunnerKey, + issueAuthority, + issueClient, + issueServer, + runnerPublicKey, +} from "../src/agents/remote/x509.js"; +import { runTestMigrations, setupTestDb, teardownTestDb } from "./db/setup.js"; + +const HOST = "127.0.0.1"; + +function parseCommand(command: string) { + const value = (flag: string) => + new RegExp(`--${flag} (\\S+)`).exec(command)?.[1] ?? ""; + return { + endpoint: value("endpoint"), + pin: value("ca-sha256"), + code: value("code"), + }; +} + +type FakeRunner = { + socket: TLSSocket; + closed: Promise; + requests: Frame[]; +}; + +/** A minimal runner peer: mTLS, `ready`, and replies naming itself. */ +function dialRunner(input: { + endpoint: string; + ca: string; + cert: string; + key: string; + label: string; + workspaces: string[]; + answer?: boolean; +}): Promise { + const url = new URL(input.endpoint); + return new Promise((resolve, reject) => { + const requests: Frame[] = []; + const socket = connect({ + host: url.hostname, + port: Number(url.port), + ca: input.ca, + cert: input.cert, + key: input.key, + rejectUnauthorized: true, + }); + const closed = new Promise((done) => socket.on("close", done)); + socket.on("error", reject); + const send = wireFrames(socket, (frame) => { + requests.push(frame); + if (frame.type === "request" && input.answer !== false) + send({ type: "result", id: frame.id, value: input.label }); + }); + socket.once("secureConnect", () => { + send({ type: "ready", version: 1, workspaces: input.workspaces }); + resolve({ socket, closed, requests }); + }); + }); +} + +async function waitFor(check: () => boolean | Promise) { + for (let i = 0; i < 100; i++) { + if (await check()) return; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + throw new Error("condition not reached"); +} + +describe("certificate issuance", () => { + it("issues a CA, a server leaf with SANs and a client leaf", () => { + const ca = issueAuthority("test CA"); + const caCert = new X509Certificate(ca.cert); + const server = new X509Certificate( + issueServer(ca, ["runner.example", "10.1.2.3", "::1"]).cert + ); + const runner = generateRunnerKey(); + const client = new X509Certificate( + issueClient(ca, "rnr_1", runnerPublicKey(runner.publicKey)) + ); + expect(caCert.ca).toBe(true); + expect(server.ca).toBe(false); + expect(server.verify(caCert.publicKey)).toBe(true); + expect(server.checkHost("runner.example")).toBe("runner.example"); + expect(server.checkIP("10.1.2.3")).toBe("10.1.2.3"); + expect(server.checkIP("::1")).toBe("::1"); + expect(client.verify(caCert.publicKey)).toBe(true); + expect(client.subject).toBe("CN=rnr_1"); + expect(client.keyUsage).toEqual(["1.3.6.1.5.5.7.3.2"]); + }); + + it("rejects weak runner keys", () => { + expect(() => + runnerPublicKey( + "-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL\n-----END PUBLIC KEY-----" + ) + ).toThrow(); + }); +}); + +describe("runner enrollment service", () => { + let pool: Pool; + let api: http.Server; + let apiRequests: http.IncomingMessage[]; + const services: RemoteRunnerService[] = []; + const runners: FakeRunner[] = []; + + const makeService = (port?: number) => { + const service = new RemoteRunnerService( + undefined, + { + registry: new RunnerRegistry(pool), + host: HOST, + port, + endpointHost: HOST, + }, + { host: HOST, port: (api.address() as AddressInfo).port, tls: false } + ); + services.push(service); + return service; + }; + + async function enroll(service: RemoteRunnerService, name: string) { + const created = await service.createRegistration(name); + const { endpoint, pin, code } = parseCommand(created.command); + const runnerKey = generateRunnerKey(); + const enrolled = await exchangeCode({ + endpoint, + pin, + code, + publicKey: runnerKey.publicKey, + }); + return { created, endpoint, pin, code, key: runnerKey.key, ...enrolled }; + } + + beforeAll(async () => { + pool = await setupTestDb(); + await runTestMigrations(); + apiRequests = []; + api = http.createServer((request, response) => { + apiRequests.push(request); + response.end(`api:${request.url}`); + }); + await new Promise((resolve) => api.listen(0, HOST, resolve)); + }, 60_000); + + afterEach(async () => { + for (const runner of runners.splice(0)) runner.socket.destroy(); + for (const service of services.splice(0)) service.close(); + await pool.query("DELETE FROM runner_registrations"); + await pool.query("DELETE FROM runner_authority"); + }); + + afterAll(async () => { + api?.close(); + await teardownTestDb(); + }); + + it("pairs with a one-time code over a pinned CA and lists the runner", async () => { + const service = makeService(); + const created = await service.createRegistration("alpha"); + expect(created.id).toMatch(/^rnr_[a-f0-9]+$/); + expect(new Date(created.expiresAt).getTime()).toBeGreaterThan(Date.now()); + expect(created.command).toMatch( + /^dispatch-runner remote-runner-pair --endpoint https:\/\/127\.0\.0\.1:\d+ --ca-sha256 [a-f0-9]{64} --code \S+$/ + ); + expect(await service.list()).toEqual([ + { id: created.id, name: "alpha", status: "pending", workspaces: [] }, + ]); + + const { endpoint, pin, code } = parseCommand(created.command); + const wrongPin = "0".repeat(64); + const runnerKey = generateRunnerKey(); + await expect( + exchangeCode({ + endpoint, + pin: wrongPin, + code, + publicKey: runnerKey.publicKey, + }) + ).rejects.toThrow(/pinned/); + // The wrong pin aborted before the code was sent, so it still works. + const enrolled = await exchangeCode({ + endpoint, + pin, + code, + publicKey: runnerKey.publicKey, + }); + expect(enrolled).toMatchObject({ id: created.id, name: "alpha" }); + await expect( + exchangeCode({ + endpoint, + pin, + code, + publicKey: generateRunnerKey().publicKey, + }) + ).rejects.toThrow(/invalid, expired or already used/); + + expect((await service.list())[0]?.status).toBe("offline"); + runners.push( + await dialRunner({ + endpoint, + ca: enrolled.ca, + cert: enrolled.cert, + key: runnerKey.key, + label: "alpha", + workspaces: ["proof"], + }) + ); + await waitFor(() => + service.available({ runner: "alpha", workspace: "proof" }) + ); + expect(await service.list()).toEqual([ + { + id: created.id, + name: "alpha", + status: "online", + workspaces: ["proof"], + }, + ]); + }); + + it("validates names and rejects duplicates", async () => { + const service = makeService(); + await expect(service.createRegistration("Bad Name")).rejects.toMatchObject({ + status: 400, + }); + await service.createRegistration("dup"); + await expect(service.createRegistration("dup")).rejects.toBeInstanceOf( + RunnerRequestError + ); + }); + + it("routes identically named workspaces to independent peers and revokes one", async () => { + const service = makeService(); + const a = await enroll(service, "alpha"); + const b = await enroll(service, "beta"); + const alpha = await dialRunner({ + endpoint: a.endpoint, + ca: a.ca, + cert: a.cert, + key: a.key, + label: "alpha", + workspaces: ["proof"], + answer: false, + }); + const beta = await dialRunner({ + endpoint: b.endpoint, + ca: b.ca, + cert: b.cert, + key: b.key, + label: "beta", + workspaces: ["proof"], + }); + runners.push(alpha, beta); + const alphaPlace = { runner: "alpha", workspace: "proof" }; + const betaPlace = { runner: "beta", workspace: "proof" }; + await waitFor( + () => service.available(alphaPlace) && service.available(betaPlace) + ); + const command = { + kind: "alive", + agentId: "agt_x", + workspace: "proof", + } as const; + expect((await service.request(betaPlace, command)).value).toBe("beta"); + expect(alpha.requests.filter((f) => f.type === "request")).toHaveLength(0); + + // Alpha holds a request open; revoking it fails only alpha's request. + const inFlight = service.request(alphaPlace, command); + await waitFor(() => alpha.requests.some((f) => f.type === "request")); + await service.revoke(a.id); + await expect(inFlight).rejects.toBeInstanceOf(RunnerUnavailable); + await alpha.closed; + expect(service.available(alphaPlace)).toBe(false); + expect((await service.request(betaPlace, command)).value).toBe("beta"); + + // The revoked certificate cannot attach again. + const again = await dialRunner({ + endpoint: a.endpoint, + ca: a.ca, + cert: a.cert, + key: a.key, + label: "alpha", + workspaces: ["proof"], + }).catch(() => undefined); + if (again) { + runners.push(again); + await again.closed; + } + expect(service.available(alphaPlace)).toBe(false); + const listed = await service.list(); + expect(listed.find((r) => r.id === a.id)?.status).toBe("revoked"); + expect(listed.find((r) => r.id === b.id)?.status).toBe("online"); + await expect(service.revoke("rnr_missing")).rejects.toMatchObject({ + status: 404, + }); + }); + + it("rejects a client certificate from another CA", async () => { + const service = makeService(); + const a = await enroll(service, "alpha"); + const rogueCa = issueAuthority("rogue"); + const key = generateRunnerKey(); + const cert = issueClient(rogueCa, a.id, runnerPublicKey(key.publicKey)); + const rogue = await dialRunner({ + endpoint: a.endpoint, + ca: a.ca, + cert, + key: key.key, + label: "rogue", + workspaces: ["proof"], + }); + runners.push(rogue); + await rogue.closed; + expect(service.available({ runner: "alpha", workspace: "proof" })).toBe( + false + ); + }); + + it("persists the CA, port and registrations across a service restart", async () => { + const first = makeService(); + const a = await enroll(first, "alpha"); + const port = Number(new URL(a.endpoint).port); + first.close(); + services.splice(services.indexOf(first), 1); + + const second = makeService(); + await second.startEnrolled(); + expect(second.originFor({ runner: "alpha", workspace: "proof" })).toBe( + `https://127.0.0.1:${port}` + ); + runners.push( + await dialRunner({ + endpoint: a.endpoint, + ca: a.ca, + cert: a.cert, + key: a.key, + label: "alpha", + workspaces: ["proof", "other"], + }) + ); + await waitFor(() => + second.available({ runner: "alpha", workspace: "other" }) + ); + second.close(); + services.splice(services.indexOf(second), 1); + // Last reported workspaces survive while offline. + const third = makeService(); + await third.startEnrolled(); + await waitFor( + async () => (await third.list())[0]?.workspaces.includes("other") ?? false + ); + expect((await third.list())[0]).toMatchObject({ + status: "offline", + workspaces: ["proof", "other"], + }); + }); + + it("proxies only bearer-authenticated agent MCP routes to the API", async () => { + const service = makeService(); + const a = await enroll(service, "alpha"); + const origin = new URL(a.endpoint); + const get = ( + path: string, + headers: Record = {}, + method = "GET" + ) => + new Promise<{ status: number; body: string }>((resolve, reject) => { + const request = https.request( + { + host: origin.hostname, + port: origin.port, + path, + method, + headers, + ca: a.ca, + }, + (response) => { + let body = ""; + response.on("data", (chunk) => (body += chunk)); + response.on("end", () => + resolve({ status: response.statusCode ?? 0, body }) + ); + } + ); + request.on("error", reject); + request.end(); + }); + expect(await get("/ping")).toEqual({ status: 200, body: "api:/ping" }); + expect( + (await get("/api/v1/agents", { authorization: "Bearer x" })).status + ).toBe(404); + expect((await get("/api/mcp/agt_abc")).status).toBe(404); + apiRequests.length = 0; + expect( + await get( + "/api/mcp/agt_abc", + { authorization: "Bearer token", cookie: "dispatch_session=secret" }, + "POST" + ) + ).toEqual({ status: 200, body: "api:/api/mcp/agt_abc" }); + expect(apiRequests[0]?.headers.authorization).toBe("Bearer token"); + expect(apiRequests[0]?.headers.cookie).toBeUndefined(); + }); +}); diff --git a/apps/server/test/runner-routes.test.ts b/apps/server/test/runner-routes.test.ts new file mode 100644 index 000000000..0575f48f1 --- /dev/null +++ b/apps/server/test/runner-routes.test.ts @@ -0,0 +1,97 @@ +import { afterAll, describe, expect, it } from "vitest"; +import { useInjectApp } from "./helpers/inject-app.js"; + +const ctx = useInjectApp({ + env: { + DISPATCH_RUNNER_HOST: "127.0.0.1", + DISPATCH_RUNNER_PORT: "0", + DISPATCH_RUNNER_ENDPOINT_HOST: "127.0.0.1", + }, +}); + +afterAll(() => { + delete process.env.DISPATCH_RUNNER_HOST; + delete process.env.DISPATCH_RUNNER_PORT; + delete process.env.DISPATCH_RUNNER_ENDPOINT_HOST; +}); + +describe("runner control API", () => { + it("requires normal API authentication", async () => { + for (const [method, url] of [ + ["GET", "/api/runners"], + ["POST", "/api/runners"], + ["DELETE", "/api/runners/rnr_x"], + ["GET", "/api/v1/runners"], + ] as const) { + const response = await ctx.app.inject({ + method, + url, + payload: method === "POST" ? { name: "a" } : undefined, + }); + expect(response.statusCode, `${method} ${url}`).toBe(401); + } + }); + + it("creates, lists and revokes a registration", async () => { + const cookie = await ctx.sessionCookie(); + const created = await ctx.app.inject({ + method: "POST", + url: "/api/runners", + headers: { cookie }, + payload: { name: "lima" }, + }); + expect(created.statusCode).toBe(201); + const body = created.json() as { + id: string; + command: string; + expiresAt: string; + }; + expect(Object.keys(body).sort()).toEqual(["command", "expiresAt", "id"]); + expect(body.command).toContain("--endpoint https://127.0.0.1:"); + + const bad = await ctx.app.inject({ + method: "POST", + url: "/api/runners", + headers: { cookie }, + payload: { name: "../x" }, + }); + expect(bad.statusCode).toBe(400); + const duplicate = await ctx.app.inject({ + method: "POST", + url: "/api/runners", + headers: { cookie }, + payload: { name: "lima" }, + }); + expect(duplicate.statusCode).toBe(409); + + const listed = await ctx.app.inject({ + method: "GET", + url: "/api/runners", + headers: { cookie }, + }); + expect(listed.json()).toEqual({ + runners: [ + { id: body.id, name: "lima", status: "pending", workspaces: [] }, + ], + }); + + const revoked = await ctx.app.inject({ + method: "DELETE", + url: `/api/runners/${body.id}`, + headers: { cookie }, + }); + expect(revoked.json()).toEqual({ ok: true }); + const after = await ctx.app.inject({ + method: "GET", + url: "/api/runners", + headers: { cookie }, + }); + expect(after.json().runners[0].status).toBe("revoked"); + const missing = await ctx.app.inject({ + method: "DELETE", + url: "/api/runners/rnr_missing", + headers: { cookie }, + }); + expect(missing.statusCode).toBe(404); + }); +}); diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index b072e6910..866633961 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -51,6 +51,37 @@ Bindings and logs remain private. The child receives its scoped MCP credential and guest paths through a constructed environment. Use test credentials, disable VM mounts and SSH-agent forwarding, and keep the VM and dev data disposable. +## Enrolled runners + +Enrollment replaces the manual certificates and approval file. On first use +Dispatch creates a runner CA and a listener certificate and stores them in +PostgreSQL (`runner_authority`). `POST /api/runners {name}` returns +`{id, command, expiresAt}`. The command looks like +`dispatch-runner remote-runner-pair --endpoint https://HOST:PORT --ca-sha256 HEX --code CODE`. +The code is single-use, expires after ten minutes, and is stored only as a +hash. Run the command as root on the runner host. Add `--dir` (default +`/etc/dispatch-runner`) or `--config FILE` as needed. The CLI pins the CA +fingerprint before it sends the code. It generates the private key locally and +writes `key.pem` (0600), `cert.pem` and `ca.pem`. It also sets `endpoint`, `ca`, +`cert` and `key` in `runner.json` and leaves the rest of that file untouched. +`GET /api/runners` lists `pending`, `online`, `offline` and `revoked` +registrations along with their last reported workspaces. +`DELETE /api/runners/:id` revokes a registration and drops its connection +immediately. Each registration is an independent mTLS peer, addressed as +`runner:///`. + +The listener binds `DISPATCH_RUNNER_HOST`, which defaults to the API host. It +uses `DISPATCH_RUNNER_PORT` when set. Otherwise it uses the persisted port, and +on first start a free port. `DISPATCH_RUNNER_ENDPOINT_HOST` overrides the host +written into commands, which otherwise comes from the request's Host header. +The listener certificate gains each advertised host automatically. Unless +`DISPATCH_RUNNER_MCP_ORIGIN` is set, the agent MCP origin is the runner +listener itself. It forwards only bearer-authenticated `/api/mcp/agt_*` +requests and `GET /ping` to the local API, with cookies removed. +`DISPATCH_RUNNERS=0` disables enrollment. The legacy +`DISPATCH_REMOTE_SERVICE_CONFIG` below still works. Its `mcpOrigin` is now +optional when `endpointHost` is given. + ## Wire contract The runner sends `ready` with protocol version 1 and its workspace handles. From c017511b45a107dfa1bb9f6ad2f720e6f4a84b31 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 22:56:42 -0700 Subject: [PATCH 011/642] Add integrated remote runner acceptance harness and spec Docker-hosted runners behind a TCP chaos proxy; local plus two runners with identical workspace names; disconnect, reconnect, revoke and failure suite. Co-Authored-By: Claude Sonnet 5.5 --- e2e/remote-runner/acceptance.spec.ts | 309 +++++++++++++++++++++++++ e2e/remote-runner/chaos-proxy.mjs | 52 +++++ e2e/remote-runner/entrypoint.sh | 14 ++ e2e/remote-runner/harness.ts | 260 +++++++++++++++++++++ e2e/remote-runner/playwright.config.ts | 28 +++ e2e/remote-runner/setup.mjs | 121 ++++++++++ package.json | 1 + playwright.config.ts | 2 + scripts/e2e-remote-runners.sh | 17 ++ 9 files changed, 804 insertions(+) create mode 100644 e2e/remote-runner/acceptance.spec.ts create mode 100755 e2e/remote-runner/chaos-proxy.mjs create mode 100755 e2e/remote-runner/entrypoint.sh create mode 100644 e2e/remote-runner/harness.ts create mode 100644 e2e/remote-runner/playwright.config.ts create mode 100644 e2e/remote-runner/setup.mjs create mode 100755 scripts/e2e-remote-runners.sh diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts new file mode 100644 index 000000000..f75e1deb7 --- /dev/null +++ b/e2e/remote-runner/acceptance.spec.ts @@ -0,0 +1,309 @@ +import { expect, test, type Page } from "@playwright/test"; +import { authHeaders, cleanupE2EAgents } from "../helpers"; +import { + agentInfo, + chat, + createPairing, + enrollViaUi, + revokeViaUi, + guestOk, + invocations, + lane, + launchViaApi, + launchViaUi, + marker, + runnerOptionEnabled, + pairInContainer, + runnerRow, + runnerRows, + state, + type RunnerName, +} from "./harness"; + +// One serial fleet: a local agent plus two Docker runners that both expose a +// workspace named "proof". Marker files differ per runner, so any output or +// file landing on the wrong side is visible. +test.describe.configure({ mode: "serial" }); +const WS = state.workspace; +const loc = (r: RunnerName) => `runner://${r}/${WS}`; +const runnerIds: Partial> = {}; +const agents: Record<"local" | RunnerName, string> = { + local: "", + alpha: "", + beta: "", +}; +const pages: Partial> = {}; + +test.beforeAll(() => { + expect(process.env.DISPATCH_AGENT_RUNTIME).toBe("acp"); +}); +test.afterAll(async ({ request }) => { + await cleanupE2EAgents(request); +}); + +const text = (p: Page) => p.locator("body"); +const answers = (p: Page, s: string) => p.getByText(s, { exact: false }); + +test("enroll two runners with identical workspace names", async ({ + page, + request, +}) => { + runnerIds.alpha = await enrollViaUi(page, request, "alpha"); + runnerIds.beta = await enrollViaUi(page, request, "beta"); + const rows = await runnerRows(request); + for (const n of ["alpha", "beta"]) { + const row = rows.find((r) => r.name === n)!; + expect(row.status).toBe("online"); + expect(row.workspaces).toContain(WS); + } + expect(marker("alpha")).not.toBe(marker("beta")); +}); + +test("UI launches local, alpha and beta; each answer comes from its own side", async ({ + browser, +}, testInfo) => { + for (const [key, prompt] of [ + ["local", "local-start"], + ["alpha", "prove-marker proof-count"], + ["beta", "prove-marker proof-count"], + ] as const) { + const page = await (await browser.newContext()).newPage(); + pages[key] = page; + const { status, id } = await launchViaUi( + page, + key === "local" + ? { name: `e2e-rr-${key}`, cwd: "/tmp", prompt } + : { name: `e2e-rr-${key}`, runnerId: runnerIds[key], prompt } + ); + expect(status).toBe(201); + agents[key] = id!; + await expect(page).toHaveURL((u) => u.pathname === `/agents/${id}`, { + timeout: 15_000, + }); + } + await expect(answers(pages.local!, "You said:")).toBeVisible({ + timeout: 45_000, + }); + for (const r of ["alpha", "beta"] as const) { + const other: RunnerName = r === "alpha" ? "beta" : "alpha"; + await expect(answers(pages[r]!, `Guest marker ${marker(r)}`)).toBeVisible({ + timeout: 45_000, + }); + await expect(text(pages[r]!)).not.toContainText(marker(other)); + expect(invocations(r)).toBe(1); + // The approved repo operation ran in this runner's workspace only. + expect(guestOk(r, `test -f ${state.runners[r].workspaceDir}/repo-op`)).toBe( + true + ); + expect( + guestOk( + other, + `test -f ${state.runners[other].workspaceDir}/provider-invocations && test "$(wc -l < ${state.runners[other].workspaceDir}/provider-invocations)" -gt 1` + ) + ).toBe(false); + } + await testInfo.attach("three agents", { + body: await pages.alpha!.screenshot(), + contentType: "image/png", + }); +}); + +test("permissions are answered per runner and never cross", async () => { + for (const r of ["alpha", "beta"] as const) + await chat(pages[r]!, "prove-permission"); + const ask = (r: RunnerName) => pages[r]!.getByTestId("permission-requests"); + await expect(ask("alpha")).toBeVisible({ timeout: 30_000 }); + await expect(ask("beta")).toBeVisible({ timeout: 30_000 }); + await ask("alpha") + .getByRole("button", { name: "Allow once", exact: true }) + .click(); + await expect(ask("alpha")).toHaveCount(0); + // Alpha's approval wrote only alpha's file; beta is still waiting. + await expect + .poll(() => + guestOk( + "alpha", + `test -f ${state.runners.alpha.workspaceDir}/protected-action` + ) + ) + .toBe(true); + expect( + guestOk( + "beta", + `test -f ${state.runners.beta.workspaceDir}/protected-action` + ) + ).toBe(false); + await expect(ask("beta")).toBeVisible(); + await ask("beta") + .getByRole("button", { name: "Reject", exact: true }) + .click(); + await expect( + answers(pages.beta!, "Guest permission answered.").last() + ).toBeVisible({ timeout: 30_000 }); + expect( + guestOk( + "beta", + `test -f ${state.runners.beta.workspaceDir}/protected-action` + ) + ).toBe(false); +}); + +test("disconnect alpha mid-turn: others continue; reconnect gives one invocation and one completion", async ({ + request, +}, testInfo) => { + const before = invocations("alpha"); + await chat(pages.alpha!, "proof-delay:25000 proof-count"); + await expect( + answers(pages.alpha!, "Guest turn waiting for reconnect.") + ).toBeVisible({ timeout: 30_000 }); + await lane("alpha", "block"); // sever now, refuse reconnects + await expect + .poll(async () => (await runnerRow(request, "alpha"))?.status, { + timeout: 30_000, + }) + .toBe("offline"); + await testInfo.attach("alpha disconnected", { + body: await pages.alpha!.screenshot(), + contentType: "image/png", + }); + + // Beta and local keep working while alpha is away. + await chat(pages.beta!, "proof-count after-alpha-lost"); + await expect( + answers(pages.beta!, "Local or guest fixture turn completed.").last() + ).toBeVisible({ timeout: 30_000 }); + await chat(pages.local!, "sleep:500 still-local"); + await expect(answers(pages.local!, "still-local").last()).toBeVisible({ + timeout: 30_000, + }); + expect((await runnerRow(request, "beta"))?.status).toBe("online"); + + await lane("alpha", "allow"); + await expect + .poll(async () => (await runnerRow(request, "alpha"))?.status, { + timeout: 60_000, + }) + .toBe("online"); + await expect( + answers(pages.alpha!, "Guest turn completed after reconnect.") + ).toHaveCount(1, { timeout: 60_000 }); + expect(invocations("alpha")).toBe(before + 1); + await expect( + answers(pages.alpha!, "Guest turn completed after reconnect.") + ).toHaveCount(1); + await testInfo.attach("alpha recovered", { + body: await pages.alpha!.screenshot(), + contentType: "image/png", + }); +}); + +test("revoke alpha: it cannot return, beta and local are unaffected", async ({ + page, + request, +}, testInfo) => { + await revokeViaUi(page, runnerIds.alpha!); + await expect + .poll(async () => (await runnerRow(request, "alpha"))?.status) + .toBe("revoked"); + // The runner process keeps retrying; it must stay out. + await new Promise((r) => setTimeout(r, 4000)); + expect((await runnerRow(request, "alpha"))?.status).toBe("revoked"); + const alphaInvocations = invocations("alpha"); + await chat(pages.alpha!, "proof-count after-revoke").catch(() => undefined); + await new Promise((r) => setTimeout(r, 3000)); + expect(invocations("alpha")).toBe(alphaInvocations); + await testInfo.attach("alpha revoked", { + body: await pages.alpha!.screenshot(), + contentType: "image/png", + }); + + await chat(pages.beta!, `proof-count after-revoke ${marker("beta")}`); + await expect( + answers(pages.beta!, "Local or guest fixture turn completed.").last() + ).toBeVisible({ timeout: 30_000 }); + await chat(pages.local!, "after-revoke-local"); + await expect(answers(pages.local!, "after-revoke-local").last()).toBeVisible({ + timeout: 30_000, + }); + expect((await runnerRow(request, "beta"))?.status).toBe("online"); + expect((await agentInfo(request, agents.beta)).cwd).toBe(loc("beta")); +}); + +// ---------------------------------------------------------------- failures +test.describe("failure suite", () => { + test("pairing codes are single-use and wrong codes are refused", async ({ + request, + }) => { + const { body } = await createPairing(request, "gamma"); + expect(body).not.toBeNull(); + const bad = body!.command.replace(/--code\s+\S+/, "--code WRONGCODE"); + expect(() => pairInContainer("beta", bad)).toThrow(); + pairInContainer("beta", body!.command); // would overwrite beta's creds; restored below + expect(() => pairInContainer("beta", body!.command)).toThrow(); // replay + const row = await runnerRow(request, "gamma"); + expect(["pending", "online", "offline"]).toContain(row?.status); + }); + + test("unknown runner and workspace are refused; revoked runner is not selectable", async ({ + page, + request, + }) => { + for (const cwd of [ + "runner://nobody/proof", + "runner://beta/not-a-workspace", + loc("alpha"), + ]) + expect(await launchViaApi(request, cwd), cwd).toBeGreaterThanOrEqual(400); + expect(await runnerOptionEnabled(page, runnerIds.alpha!)).toBe(false); + expect(await runnerOptionEnabled(page, runnerIds.beta!)).toBe(true); + }); + + test("flapping transport does not duplicate prompts or completions", async ({ + request, + }) => { + const before = invocations("beta"); + await chat(pages.beta!, "proof-delay:12000 proof-count flap"); + await expect( + answers(pages.beta!, "Guest turn waiting for reconnect.").last() + ).toBeVisible({ timeout: 30_000 }); + for (let i = 0; i < 3; i++) { + await lane("beta", "sever"); + await new Promise((r) => setTimeout(r, 1500)); + } + await expect + .poll(async () => (await runnerRow(request, "beta"))?.status, { + timeout: 60_000, + }) + .toBe("online"); + await expect( + answers(pages.beta!, "Guest turn completed after reconnect.").last() + ).toBeVisible({ timeout: 60_000 }); + expect(invocations("beta")).toBe(before + 1); + }); + + test("launch while a runner is unreachable fails cleanly and leaves others alone", async ({ + page, + request, + }) => { + await lane("beta", "block"); + await expect + .poll(async () => (await runnerRow(request, "beta"))?.status, { + timeout: 30_000, + }) + .toBe("offline"); + expect(await launchViaApi(request, loc("beta"))).toBeGreaterThanOrEqual( + 400 + ); + expect(await runnerOptionEnabled(page, runnerIds.beta!)).toBe(false); + await chat(pages.local!, "local-while-beta-down"); + await expect( + answers(pages.local!, "local-while-beta-down").last() + ).toBeVisible({ timeout: 30_000 }); + await lane("beta", "allow"); + await expect + .poll(async () => (await runnerRow(request, "beta"))?.status, { + timeout: 60_000, + }) + .toBe("online"); + }); +}); diff --git a/e2e/remote-runner/chaos-proxy.mjs b/e2e/remote-runner/chaos-proxy.mjs new file mode 100755 index 000000000..17ba0345a --- /dev/null +++ b/e2e/remote-runner/chaos-proxy.mjs @@ -0,0 +1,52 @@ +#!/usr/bin/env node +// Deterministic TCP fault injector between each runner container and the +// service listener. TLS stays end to end; this only moves bytes. +// node chaos-proxy.mjs name=listenPort:targetPort ... +// Control (127.0.0.1): POST //sever | /block | /allow, GET //status +import { createServer as tcp, connect } from "node:net"; +import { createServer as http } from "node:http"; + +const [controlPort, ...specs] = process.argv.slice(2); +const lanes = new Map(); +for (const spec of specs) { + const [name, ports] = spec.split("="); + const [listen, target] = ports.split(":").map(Number); + const lane = { name, target, blocked: false, pairs: new Set(), accepted: 0 }; + lane.server = tcp((client) => { + lane.accepted += 1; + if (lane.blocked) return client.destroy(); + const upstream = connect(lane.target, "127.0.0.1"); + const pair = [client, upstream]; + lane.pairs.add(pair); + const end = () => { + lane.pairs.delete(pair); + client.destroy(); + upstream.destroy(); + }; + client.on("error", end).on("close", end); + upstream.on("error", end).on("close", end); + client.pipe(upstream); + upstream.pipe(client); + }).listen(listen, "0.0.0.0"); + lanes.set(name, lane); +} +const sever = (lane) => { + for (const [a, b] of lane.pairs) (a.destroy(), b.destroy()); + lane.pairs.clear(); +}; +http((req, res) => { + const [, name, action] = req.url.split("/"); + const lane = lanes.get(name); + if (!lane) return res.writeHead(404).end(); + if (action === "sever") sever(lane); + else if (action === "block") ((lane.blocked = true), sever(lane)); + else if (action === "allow") lane.blocked = false; + else if (action !== "status") return res.writeHead(404).end(); + res.writeHead(200, { "content-type": "application/json" }).end( + JSON.stringify({ + blocked: lane.blocked, + open: lane.pairs.size, + accepted: lane.accepted, + }) + ); +}).listen(Number(controlPort), "127.0.0.1", () => console.log("ready")); diff --git a/e2e/remote-runner/entrypoint.sh b/e2e/remote-runner/entrypoint.sh new file mode 100755 index 000000000..ae9aed8fb --- /dev/null +++ b/e2e/remote-runner/entrypoint.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Container entrypoint: stage a pre-provisioned guest workspace with a +# runner-unique marker and a writable runner.json, then idle. The harness +# pairs and starts the runner with `docker exec` so tests control timing. +set -eu +NAME="$1" +install -d -m 700 /run/cfg /var/lib/runner +install -d -m 755 /home/guest /etc/dispatch-runner +cp /etc/runner/runner.json /run/cfg/runner.json && chmod 600 /run/cfg/runner.json +WS="/opt/dispatch-guest-$NAME-proof" +mkdir -p "$WS" +echo "marker-$NAME-$(cat /proc/sys/kernel/random/uuid)" > "$WS/marker.txt" +chown -R 1500:1500 "$WS" /home/guest +exec sleep infinity diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts new file mode 100644 index 000000000..4150b2cba --- /dev/null +++ b/e2e/remote-runner/harness.ts @@ -0,0 +1,260 @@ +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { expect, type APIRequestContext, type Page } from "@playwright/test"; +import { authHeaders, trackAgent } from "../helpers"; + +export type RunnerName = "alpha" | "beta"; +type State = { + controlPort: number; + runnerPort: number; + endpointHost: string; + workspace: string; + runners: Record< + RunnerName, + { container: string; proxyPort: number; workspaceDir: string } + >; +}; + +// Assumption (enrollment slice): runner registry lives at /api/runners. +export const RUNNERS_API = "/api/runners"; + +export const state: State = JSON.parse( + readFileSync(process.env.REMOTE_E2E_STATE ?? "/nonexistent", "utf8") +); + +const docker = (...args: string[]) => + execFileSync("docker", args, { encoding: "utf8" }); + +/** Run a shell command inside a runner container as root. */ +export function guest(name: RunnerName, script: string) { + return docker("exec", state.runners[name].container, "sh", "-c", script); +} +export function guestOk(name: RunnerName, script: string) { + try { + guest(name, script); + return true; + } catch { + return false; + } +} +export const marker = (name: RunnerName) => + guest(name, `cat ${state.runners[name].workspaceDir}/marker.txt`).trim(); +export const invocations = (name: RunnerName) => + Number( + guest( + name, + `cat ${state.runners[name].workspaceDir}/provider-invocations 2>/dev/null | wc -l` + ).trim() + ); + +/** Fault injection on the runner's TCP path (TLS stays end to end). */ +export async function lane( + name: RunnerName, + action: "sever" | "block" | "allow" | "status" +) { + const res = await fetch( + `http://127.0.0.1:${state.controlPort}/${name}/${action}`, + { method: action === "status" ? "GET" : "POST" } + ); + return (await res.json()) as { + blocked: boolean; + open: number; + accepted: number; + }; +} + +export type RunnerRow = { + id: string; + name: string; + status: string; + workspaces?: string[]; +}; +export async function runnerRows(request: APIRequestContext) { + const res = await request.get(RUNNERS_API, { headers: authHeaders() }); + expect(res.ok(), await res.text()).toBe(true); + return ((await res.json()) as { runners: RunnerRow[] }).runners; +} +export const runnerRow = async (request: APIRequestContext, name: string) => + (await runnerRows(request)).find((r) => r.name === name); + +/** Route the runner's whole path (pairing and mTLS) through its chaos lane. */ +const viaLane = (name: RunnerName, command: string) => + command.replace( + /--endpoint\s+https:\/\/\S+/, + `--endpoint https://${state.endpointHost}:${state.runners[name].proxyPort}` + ); + +export async function createPairing(request: APIRequestContext, name: string) { + const res = await request.post(RUNNERS_API, { + headers: authHeaders(), + data: { name }, + }); + return { res, body: res.ok() ? await res.json() : null } as { + res: typeof res; + body: { id: string; command: string; expiresAt: string } | null; + }; +} + +/** Pair inside the container (key generated there), then start the runner. */ +export function pairInContainer(name: RunnerName, command: string) { + const c = state.runners[name].container; + const pair = viaLane(name, command).replace( + /^dispatch-runner/, + "/opt/bin/dispatch-runner" + ); + return docker( + "exec", + c, + "sh", + "-c", + `${pair} --dir /etc/dispatch-runner --config /run/cfg/runner.json 2>&1` + ); +} +export function startRunner(name: RunnerName) { + docker( + "exec", + "-d", + state.runners[name].container, + "sh", + "-c", + "/opt/bin/dispatch-runner remote-runner /run/cfg/runner.json >/var/log/runner.log 2>&1" + ); +} +export const runnerLog = (name: RunnerName) => + guest(name, "cat /var/log/runner.log 2>/dev/null || true"); + +/** Pair through Settings → Connections → Remote runners (the normal UI). */ +export async function enrollViaUi( + page: Page, + request: APIRequestContext, + name: RunnerName +) { + await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.getByTestId("runner-name-input").fill(name); + await page.getByTestId("runner-pair-submit").click(); + const command = (await page.getByTestId("runner-command").innerText()).trim(); + pairInContainer(name, command); + startRunner(name); + await expect + .poll(async () => (await runnerRow(request, name))?.status, { + timeout: 30_000, + }) + .toBe("online"); + const id = (await runnerRow(request, name))!.id; + await expect(page.getByTestId(`runner-status-${id}`)).toHaveText("Online", { + timeout: 15_000, + }); + return id; +} + +export async function revokeViaUi(page: Page, id: string) { + await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.getByTestId(`runner-revoke-${id}`).click(); + await page.getByTestId(`runner-revoke-confirm-${id}`).click(); + await expect(page.getByTestId(`runner-status-${id}`)).toHaveText("Revoked", { + timeout: 15_000, + }); +} + +export async function enroll(request: APIRequestContext, name: RunnerName) { + const { res, body } = await createPairing(request, name); + expect(res.ok(), await res.text()).toBe(true); + pairInContainer(name, body!.command); + startRunner(name); + await expect + .poll(async () => (await runnerRow(request, name))?.status, { + timeout: 30_000, + }) + .toBe("online"); + return body!.id; +} + +/** Launch through the normal Create Agent dialog (Folder = runner locator). */ +export async function launchViaUi( + page: Page, + opts: { name: string; cwd?: string; runnerId?: string; prompt: string } +) { + await page.goto("/", { waitUntil: "domcontentloaded" }); + await page.getByTestId("create-agent-button").click(); + await expect(page.getByTestId("create-agent-form")).toBeVisible(); + if (opts.runnerId) + await expect(page.getByTestId("runner-picker")).toBeVisible({ + timeout: 15_000, + }); + await page.getByTestId("create-agent-name").fill(opts.name); + if (opts.runnerId) { + // Runner picker (runner-picker.tsx): "Runs on" then "Workspace". + await page.getByTestId("create-agent-runner").click(); + await page + .getByTestId(`create-agent-runner-option-${opts.runnerId}`) + .click(); + await page.getByTestId("create-agent-runner-workspace").click(); + await page + .getByRole("option", { name: state.workspace, exact: true }) + .click(); + } else await page.getByTestId("create-agent-cwd").fill(opts.cwd ?? "/tmp"); + await page.getByTestId("create-agent-with-context").click(); + await page.getByTestId("create-agent-initial-prompt").fill(opts.prompt); + const created = page.waitForResponse( + (r) => + r.request().method() === "POST" && + new URL(r.url()).pathname === "/api/v1/agents" + ); + await page.getByTestId("create-agent-context-submit").click(); + const response = await created; + const body = (await response.json()) as { agent?: { id: string } }; + if (body.agent) trackAgent(body.agent.id); + return { status: response.status(), id: body.agent?.id }; +} + +export async function agentInfo(request: APIRequestContext, id: string) { + const res = await request.get(`/api/v1/agents/${id}`, { + headers: authHeaders(), + }); + return (await res.json()).agent as { + status: string; + activity?: string; + cwd: string; + }; +} + +/** Send a follow-up chat message through the composer. */ +export async function chat(page: Page, text: string) { + const input = page.getByTestId("chat-composer-input"); + await expect(input).toBeEnabled({ timeout: 30_000 }); + await input.fill(text); + await page.getByTestId("chat-composer-send").click(); + await expect(input).toHaveText(""); +} + +/** Open the dialog and report whether a runner option can be selected. */ +export async function runnerOptionEnabled(page: Page, runnerId: string) { + await page.goto("/", { waitUntil: "domcontentloaded" }); + await page.getByTestId("create-agent-button").click(); + await page.getByTestId("create-agent-runner").click(); + const option = page.getByTestId(`create-agent-runner-option-${runnerId}`); + const enabled = + (await option.count()) > 0 && + (await option.getAttribute("aria-disabled")) !== "true" && + (await option.getAttribute("data-disabled")) === null; + await page.keyboard.press("Escape"); + await page.keyboard.press("Escape"); + return enabled; +} + +/** Direct API launch, for placements the dialog deliberately cannot express. */ +export async function launchViaApi(request: APIRequestContext, cwd: string) { + const res = await request.post("/api/v1/agents", { + headers: authHeaders(), + data: { + name: `e2e-rr-api-${Date.now()}`, + type: "codex", + cwd, + useWorktree: false, + initialPrompt: "x", + }, + }); + if (res.ok()) + trackAgent(((await res.json()) as { agent: { id: string } }).agent.id); + return res.status(); +} diff --git a/e2e/remote-runner/playwright.config.ts b/e2e/remote-runner/playwright.config.ts new file mode 100644 index 000000000..e9d6792fa --- /dev/null +++ b/e2e/remote-runner/playwright.config.ts @@ -0,0 +1,28 @@ +import { defineConfig } from "@playwright/test"; +import base from "../../playwright.config"; + +// Remote runner acceptance: serial (one shared fleet of Docker runners), +// longer timeouts. Launched by scripts/e2e-remote-runners.sh, which exports +// REMOTE_E2E_STATE and the enrolled-mode DISPATCH_RUNNER_* service settings. +export default defineConfig({ + ...base, + testDir: ".", + testIgnore: [], + testMatch: "*.spec.ts", + workers: 1, + timeout: 180_000, + retries: 0, + failOnFlakyTests: false, + webServer: + base.webServer && + ({ + ...(base.webServer as object), + env: { + ...((base.webServer as { env?: Record }).env ?? {}), + DISPATCH_RUNNER_HOST: process.env.DISPATCH_RUNNER_HOST ?? "", + DISPATCH_RUNNER_PORT: process.env.DISPATCH_RUNNER_PORT ?? "", + DISPATCH_RUNNER_ENDPOINT_HOST: + process.env.DISPATCH_RUNNER_ENDPOINT_HOST ?? "", + }, + } as never), +}); diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs new file mode 100644 index 000000000..e97f47eaf --- /dev/null +++ b/e2e/remote-runner/setup.mjs @@ -0,0 +1,121 @@ +#!/usr/bin/env node +// Reproducible setup/teardown for the remote runner acceptance run. +// node setup.mjs up build artifacts, chaos proxy, idle runner containers +// node setup.mjs down remove containers and processes +// No VMs, no production data: everything lives under and in +// containers labelled dispatch-remote-e2e=. +import { execFileSync, spawn } from "node:child_process"; +import { + chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, +} from "node:fs"; +import { createHash } from "node:crypto"; +import { createServer } from "node:net"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const root = path.resolve(here, "../.."); +const RUNNERS = ["alpha", "beta"]; +const WORKSPACE = "proof"; // identical handle on every runner, on purpose +// Colima/Docker Desktop share $HOME, not /tmp, with the VM; bind mounts must live here. +export const base = process.env.REMOTE_E2E_ROOT ?? path.join(process.env.HOME, ".cache", "dispatch-remote-e2e"); +const IMAGE = process.env.REMOTE_E2E_IMAGE ?? "debian:bookworm-slim"; +const sh = (cmd, args, opts = {}) => + execFileSync(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], ...opts }); + +const freePort = () => + new Promise((resolve) => { + const s = createServer().listen(0, "127.0.0.1", () => { + const { port } = s.address(); + s.close(() => resolve(port)); + }); + }); + +function artifacts(arch) { + const hash = createHash("sha256") + .update(sh("git", ["ls-files", "-s", "apps/server/src", "apps/server/test/helpers"], { cwd: root })) + .update(sh("git", ["diff", "HEAD", "--", "apps/server/src", "apps/server/test/helpers"], { cwd: root })) + .digest("hex").slice(0, 16); + const dir = path.join(base, `bin-${arch}-${hash}`); + const runner = path.join(dir, "dispatch-runner"); + const adapter = path.join(dir, "remote-acp-fixture"); + if (!existsSync(runner) || !existsSync(adapter)) { + mkdirSync(dir, { recursive: true }); + sh("bun", ["scripts/generate-server-runtime-assets.mjs"], { cwd: root }); + const target = `bun-linux-${arch === "arm64" ? "arm64" : "x64"}`; + sh("bun", ["build", "--compile", `--target=${target}`, "apps/server/src/main.ts", "--outfile", runner], { cwd: root }); + sh("bun", ["build", "--compile", `--target=${target}`, "apps/server/test/helpers/remote-acp-fixture.ts", "--outfile", adapter], { cwd: root }); + } + return { runner, adapter }; +} + +async function up(run) { + const id = path.basename(run); + mkdirSync(run, { recursive: true, mode: 0o700 }); + const arch = sh("docker", ["version", "--format", "{{.Server.Arch}}"]).trim() === "arm64" ? "arm64" : "x64"; + const bin = artifacts(arch); + const runnerPort = await freePort(); // DISPATCH_RUNNER_PORT: the service's enrolled-mode listener + const controlPort = await freePort(); + const lanes = []; + const state = { id, controlPort, runnerPort, endpointHost: "host.docker.internal", workspace: WORKSPACE, runners: {} }; + for (const name of RUNNERS) { + const proxyPort = await freePort(); + const dir = path.join(run, name); + mkdirSync(dir); + writeFileSync(path.join(dir, "runner.json"), JSON.stringify({ + endpoint: "https://placeholder.invalid", ca: "/etc/dispatch-runner/ca.pem", + cert: "/etc/dispatch-runner/cert.pem", key: "/etc/dispatch-runner/key.pem", + state: "/var/lib/runner", uid: 1500, gid: 1500, home: "/home/guest", + path: "/usr/local/bin:/usr/bin:/bin", + bins: { claudeBin: "/bin/false", codexBin: null }, + adapter: ["/opt/bin/remote-acp-fixture"], + workspaces: { [WORKSPACE]: { cwd: `/opt/dispatch-guest-${name}-proof`, repoTool: ["/bin/sh", "-c", "echo ran > repo-op"] } }, + })); + copyFileSync(path.join(here, "entrypoint.sh"), path.join(dir, "entrypoint.sh")); + chmodSync(path.join(dir, "entrypoint.sh"), 0o755); + lanes.push(`${name}=${proxyPort}:${runnerPort}`); + state.runners[name] = { container: `dispatch-remote-e2e-${id}-${name}`, proxyPort, workspaceDir: `/opt/dispatch-guest-${name}-proof` }; + } + const child = spawn(process.execPath, [path.join(here, "chaos-proxy.mjs"), String(controlPort), ...lanes], { detached: true, stdio: ["ignore", "pipe", "inherit"] }); + await new Promise((resolve, reject) => { + child.stdout.once("data", () => (child.unref(), resolve())); + child.once("exit", () => reject(new Error("chaos proxy exited"))); + }); + writeFileSync(path.join(run, "pids"), String(child.pid)); + for (const name of RUNNERS) { + sh("docker", ["run", "-d", "--name", state.runners[name].container, "--label", `dispatch-remote-e2e=${id}`, + "--add-host", "host.docker.internal:host-gateway", + "-v", `${path.join(run, name)}:/etc/runner:ro`, + "-v", `${bin.runner}:/opt/bin/dispatch-runner:ro`, + "-v", `${bin.adapter}:/opt/bin/remote-acp-fixture:ro`, + "--entrypoint", "/bin/sh", IMAGE, "/etc/runner/entrypoint.sh", name]); + } + writeFileSync(path.join(run, "state.json"), JSON.stringify(state, null, 2)); + // Enrolled-mode service settings (no registration file; see enrollment slice). + writeFileSync(path.join(run, "env"), [ + "export DISPATCH_RUNNER_HOST=0.0.0.0", + `export DISPATCH_RUNNER_PORT=${runnerPort}`, + "export DISPATCH_RUNNER_ENDPOINT_HOST=host.docker.internal", + `export REMOTE_E2E_STATE='${path.join(run, "state.json")}'`, "", + ].join("\n")); + console.log(`remote e2e ready: ${run}`); +} + +function down(run) { + const id = path.basename(run); + try { + const ids = sh("docker", ["ps", "-aq", "--filter", `label=dispatch-remote-e2e=${id}`]).split(/\s+/).filter(Boolean); + if (ids.length) sh("docker", ["rm", "-f", ...ids]); + } catch (e) { console.error("container cleanup:", e.message); } + try { + for (const pid of readFileSync(path.join(run, "pids"), "utf8").split("\n").filter(Boolean)) + try { process.kill(Number(pid), "SIGTERM"); } catch {} + } catch {} +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const [cmd, run] = process.argv.slice(2); + if (cmd === "up") await up(path.resolve(run)); + else if (cmd === "down") down(path.resolve(run)); + else { console.error("usage: setup.mjs up|down [api-port]"); process.exit(2); } +} diff --git a/package.json b/package.json index 5dd391e88..38e92b3d3 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "test": "pnpm --filter @dispatch/server test && pnpm --filter @dispatch/web test && pnpm --filter @dispatch/browser-extension test", "test:watch": "pnpm --filter @dispatch/server test:watch", "test:e2e": "bash scripts/e2e-isolated.sh", + "test:e2e:remote-runners": "bash scripts/e2e-remote-runners.sh", "test:e2e:live": "pnpm run test:e2e e2e/agent-live.spec.ts", "prepare": "husky", "test:unit": "pnpm --filter @dispatch/server test:unit && pnpm --filter @dispatch/web test && pnpm --filter @dispatch/browser-extension test" diff --git a/playwright.config.ts b/playwright.config.ts index 694e1dbc3..d33be9b08 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -19,6 +19,8 @@ const agentRuntime = export default defineConfig({ testDir: "./e2e", + // The remote-runner acceptance needs Docker runners; it has its own config. + testIgnore: "**/remote-runner/**", forbidOnly: !!process.env.CI, retries: process.env.CI ? 1 : 0, // The retry is diagnostic: a retry-pass must still fail CI. diff --git a/scripts/e2e-remote-runners.sh b/scripts/e2e-remote-runners.sh new file mode 100755 index 000000000..ecf3ba985 --- /dev/null +++ b/scripts/e2e-remote-runners.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Integrated remote-runner acceptance: local agent + two Docker-hosted runners +# with the same workspace name. Requires docker and bun. No VMs, no prod data. +# pnpm run test:e2e:remote-runners [extra playwright args] +set -euo pipefail +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +BASE="${REMOTE_E2E_ROOT:-$HOME/.cache/dispatch-remote-e2e}" # must be shared with the Docker VM (not /tmp on Colima) +mkdir -p "$BASE" +RUN_DIR="$BASE/run-$$-$(date +%s)" +cleanup() { node "$ROOT_DIR/e2e/remote-runner/setup.mjs" down "$RUN_DIR" || true; rm -rf "$RUN_DIR"; } +trap cleanup EXIT +node "$ROOT_DIR/e2e/remote-runner/setup.mjs" up "$RUN_DIR" +# shellcheck disable=SC1091 +. "$RUN_DIR/env" +exec_status=0 +bash "$ROOT_DIR/scripts/e2e-isolated.sh" -c e2e/remote-runner/playwright.config.ts "$@" || exec_status=$? +exit "$exec_status" From 0e448d62d6b28731939c88ea5a7fcb02091a3ebc Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 23:04:31 -0700 Subject: [PATCH 012/642] Address enrolled runners by registration id and scope MCP and repo access Placements, peers, origins and revocation now key on the opaque registration id, so a re-paired runner with a reused name never receives an old agent's work. Adds permitsAgentMcp(placement) and repoToolFor(placement), renewal by re-pairing under the same id, opaque workspace ids, and an MCP proxy that forwards only allow-listed headers with a valid agent-scoped token. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/remote/enrollment.ts | 28 +- apps/server/src/agents/remote/registry.ts | 24 +- apps/server/src/agents/remote/service.ts | 208 +++++++++++---- apps/server/src/routes/runners.ts | 19 ++ apps/server/src/server.ts | 3 + .../test/remote-runner-enrollment.test.ts | 246 ++++++++++++++++-- apps/server/test/runner-routes.test.ts | 15 +- docs/design/remote-runner-prototype.md | 14 +- 8 files changed, 478 insertions(+), 79 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 87b20fe11..0617c72b4 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -19,7 +19,33 @@ export type EnrollFrame = | { type: "enrolled"; id: string; name: string; cert: string; ca: string } | { type: "enroll_error"; error: string }; -export const RUNNER_NAME = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/; +/** Display names only; placements address runners by registration id. */ +export function validRunnerName(name: unknown): name is string { + return ( + typeof name === "string" && + name === name.trim() && + name.length > 0 && + name.length <= 64 && + !/[\x00-\x1f\x7f-\x9f]/u.test(name) + ); +} + +/** Mirrors the runner protocol's opaque workspace identity rule. */ +export function validWorkspaceId(value: unknown): value is string { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > 128 || + /[\x00-\x1f\x7f-\x9f]/u.test(value) + ) + return false; + try { + encodeURIComponent(value); + return true; + } catch { + return false; + } +} export function formatHost(host: string) { return isIP(host) === 6 ? `[${host}]` : host; diff --git a/apps/server/src/agents/remote/registry.ts b/apps/server/src/agents/remote/registry.ts index 1e05d68b4..eaceae6f6 100644 --- a/apps/server/src/agents/remote/registry.ts +++ b/apps/server/src/agents/remote/registry.ts @@ -208,9 +208,10 @@ export class RunnerRegistry { const client = await this.pool.connect(); try { await client.query("BEGIN"); + // A code may enroll a pending registration or re-key an enrolled one. const { rows } = await client.query( `SELECT * FROM runner_registrations - WHERE code_hash = $1 AND enrolled_at IS NULL AND revoked_at IS NULL + WHERE code_hash = $1 AND revoked_at IS NULL AND code_expires_at > now() FOR UPDATE`, [hashCode(code)] @@ -228,13 +229,15 @@ export class RunnerRegistry { const parsed = new X509Certificate(cert); await client.query( `UPDATE runner_registrations - SET code_hash = NULL, code_expires_at = NULL, enrolled_at = now(), + SET code_hash = NULL, code_expires_at = NULL, + enrolled_at = COALESCE(enrolled_at, now()), cert_fingerprint = $2, cert_expires_at = $3 WHERE id = $1`, [row.id, parsed.fingerprint256, new Date(parsed.validTo)] ); await client.query("COMMIT"); return { + previousFingerprint: row.cert_fingerprint, registration: registration({ ...row, cert_fingerprint: parsed.fingerprint256, @@ -251,6 +254,23 @@ export class RunnerRegistry { } } + /** + * Issue a fresh one-time code for an existing registration. Redeeming it + * replaces the client certificate (renewal or re-key) and keeps the id, so + * placements keep addressing the same runner. + */ + async reissue(id: string, endpointHost: string) { + const code = randomBytes(20).toString("base64url"); + const expiresAt = new Date(Date.now() + PAIRING_TTL_MS); + const { rowCount } = await this.pool.query( + `UPDATE runner_registrations + SET code_hash = $2, code_expires_at = $3, endpoint_host = $4 + WHERE id = $1 AND revoked_at IS NULL`, + [id, hashCode(code), expiresAt, endpointHost] + ); + return rowCount ? { id, code, expiresAt } : undefined; + } + async connected(id: string, workspaces: string[]) { await this.pool.query( `UPDATE runner_registrations diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 3c2bc1021..ca84ce3c9 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -17,7 +17,8 @@ import { import { formatHost, pairingCommand, - RUNNER_NAME, + validRunnerName, + validWorkspaceId, type EnrollFrame, } from "./enrollment.js"; import { @@ -54,7 +55,11 @@ export type EnrollmentOptions = { endpointHost?: string; /** External HTTPS MCP origin; defaults to the runner listener's proxy. */ mcpOrigin?: string; - repoTool?: boolean; + /** + * Service-side approval for the runner's fixed repo operation: true for + * every placement, or a list of `` / `/`. + */ + repoTool?: boolean | string[]; log?: Pick; }; @@ -78,8 +83,8 @@ export class RunnerRequestError extends Error { } type Gate = { - /** Runner name addressed by placements. */ - name: string; + /** Runner component of placements: the registration id (or legacy id). */ + key: string; registrationId?: string; approved(): boolean; allows(workspace: string): boolean; @@ -97,8 +102,6 @@ type Peer = { channels: Map; }; -const WORKSPACE = /^[a-z0-9-]+$/; -const LEGACY_PREFIX = "legacy-"; const MAX_UNAUTHENTICATED = 64; function validHost(host: string) { @@ -115,11 +118,21 @@ function httpsOrigin(value: string | undefined, label: string) { return value.replace(/\/$/, ""); } +function parseRepoTool(value: string | undefined): boolean | string[] { + if (!value || value === "0") return false; + if (value === "1" || value === "*") return true; + return value + .split(",") + .map((entry) => entry.trim()) + .filter(Boolean); +} + export function configuredRunner(input?: { pool: Pool; host: string; apiPort: number; apiTls: boolean; + validAgentToken?: (token: string, agentId: string) => boolean; }) { const filename = process.env.DISPATCH_REMOTE_SERVICE_CONFIG; const legacy: LegacyConfig | undefined = filename @@ -135,7 +148,7 @@ export function configuredRunner(input?: { : undefined, endpointHost: process.env.DISPATCH_RUNNER_ENDPOINT_HOST, mcpOrigin: process.env.DISPATCH_RUNNER_MCP_ORIGIN, - repoTool: process.env.DISPATCH_RUNNER_REPO_TOOL === "1", + repoTool: parseRepoTool(process.env.DISPATCH_RUNNER_REPO_TOOL), log: console, } : undefined; @@ -143,7 +156,12 @@ export function configuredRunner(input?: { ? new RemoteRunnerService( legacy, enrollment, - input && { host: input.host, port: input.apiPort, tls: input.apiTls } + input && { + host: input.host, + port: input.apiPort, + tls: input.apiTls, + validAgentToken: input.validAgentToken, + } ) : undefined; } @@ -168,7 +186,13 @@ export class RemoteRunnerService { private readonly legacy?: LegacyConfig, private readonly enrollment?: EnrollmentOptions, /** Local Dispatch API that the listeners proxy agent MCP requests to. */ - private readonly api?: { host: string; port: number; tls: boolean } + private readonly api?: { + host: string; + port: number; + tls: boolean; + /** Accept only agent-scoped MCP credentials through the proxy. */ + validAgentToken?: (token: string, agentId: string) => boolean; + } ) { if (legacy) { httpsOrigin(legacy.mcpOrigin, "Runner MCP origin"); @@ -202,7 +226,7 @@ export class RemoteRunnerService { "DISPATCH_RUNNER_MCP_ORIGIN" ); if (configured) return configured; - const registration = this.registrationNamed(placement.runner); + const registration = this.registrationById(placement.runner); if (!registration || !this.port) throw new RunnerUnavailable("The runner is not enrolled."); return `https://${formatHost(registration.endpointHost)}:${this.port}`; @@ -214,16 +238,60 @@ export class RemoteRunnerService { return this.originFor({ runner: this.legacy.id, workspace: "" }); const first = [...this.enrolled.values()][0]; if (!first) throw new RunnerUnavailable("No runner is enrolled."); - return this.originFor({ runner: first.name, workspace: "" }); + return this.originFor({ runner: first.id, workspace: "" }); } + /** @deprecated Whether any placement may use the repo operation. */ get repoTool() { - return this.legacy?.repoTool === true || this.enrollment?.repoTool === true; + const enrolled = this.enrollment?.repoTool; + return ( + this.legacy?.repoTool === true || + enrolled === true || + (Array.isArray(enrolled) && enrolled.length > 0) + ); + } + + /** + * Whether the service approves the runner's fixed repo operation for this + * placement. Requires an agent-MCP-eligible registration; the runner still + * requires its own per-workspace `repoTool`. + */ + repoToolFor(placement: Placement) { + if (!this.permitsAgentMcp(placement)) return false; + if (this.legacy && placement.runner === this.legacy.id) + return this.legacy.repoTool === true; + const approval = this.enrollment?.repoTool; + if (approval === true) return true; + return ( + Array.isArray(approval) && + (approval.includes(placement.runner) || + approval.includes(`${placement.runner}/${placement.workspace}`)) + ); + } + + /** + * Whether an agent placed here may still use its MCP credential: an + * active (enrolled, unrevoked) registration, online or offline. A legacy + * placement needs a currently non-empty approval file and a configured + * workspace. Revoked and unknown runners are refused. + */ + permitsAgentMcp(placement: Placement) { + if (this.legacy && placement.runner === this.legacy.id) { + try { + return ( + this.legacy.workspaces.includes(placement.workspace) && + readFileSync(this.legacy.approval, "utf8").trim().length > 0 + ); + } catch { + return false; + } + } + return Boolean(this.registrationById(placement.runner)); } - private registrationNamed(name: string) { + private registrationById(id: string) { for (const registration of this.enrolled.values()) - if (registration.name === name) return registration; + if (registration.id === id) return registration; return undefined; } @@ -419,7 +487,7 @@ export class RemoteRunnerService { this.legacySockets.add(socket); socket.once("close", () => this.legacySockets.delete(socket)); return { - name: legacy.id, + key: legacy.id, approved: () => this.legacyApproved(socket), allows: (workspace) => legacy.workspaces.includes(workspace), }; @@ -429,7 +497,7 @@ export class RemoteRunnerService { if (!registration) return undefined; const registry = this.enrollment!.registry; return { - name: registration.name, + key: registration.id, registrationId: registration.id, approved: () => this.enrolled.get(fingerprint)?.id === registration.id, allows: () => true, @@ -446,7 +514,7 @@ export class RemoteRunnerService { socket.on("close", () => { clearTimeout(deadline); if (!peer) return; - if (this.peers.get(gate.name) === peer) this.peers.delete(gate.name); + if (this.peers.get(gate.key) === peer) this.peers.delete(gate.key); for (const settle of peer.pending.values()) settle(); for (const channel of peer.channels.values()) channel.push(null); if (gate.registrationId) @@ -462,10 +530,7 @@ export class RemoteRunnerService { frame.version !== 1 || !Array.isArray(frame.workspaces) || frame.workspaces.length > 256 || - !frame.workspaces.every( - (workspace) => - typeof workspace === "string" && WORKSPACE.test(workspace) - ) + !frame.workspaces.every((workspace) => validWorkspaceId(workspace)) ) return socket.destroy(); clearTimeout(deadline); @@ -478,8 +543,8 @@ export class RemoteRunnerService { channels: new Map(), }; // A reconnect replaces a half-open predecessor for the same runner. - const previous = this.peers.get(gate.name); - this.peers.set(gate.name, peer); + const previous = this.peers.get(gate.key); + this.peers.set(gate.key, peer); previous?.socket.destroy(); gate.ready?.(frame.workspaces); return; @@ -519,7 +584,12 @@ export class RemoteRunnerService { error: "Invalid pairing request.", }); this.enrollment!.registry.redeem(request.code, request.publicKey).then( - ({ registration, cert, ca }) => { + ({ registration, cert, ca, previousFingerprint }) => { + // A re-key retires the old certificate and its live connection. + if (previousFingerprint) { + this.enrolled.delete(previousFingerprint); + this.peers.get(registration.id)?.socket.destroy(); + } this.enrolled.set(registration.fingerprint!, registration); reply({ type: "enrolled", @@ -553,11 +623,18 @@ export class RemoteRunnerService { response: http.ServerResponse ) { const url = request.url ?? ""; - const ping = url === "/ping" && request.method === "GET"; - const mcp = - /^\/api\/mcp\/agt_[a-z0-9]+$/.test(url) && - /^Bearer \S+$/.test(request.headers.authorization ?? ""); const target = this.api; + const ping = url === "/ping" && request.method === "GET"; + const agentId = /^\/api\/mcp\/(agt_[a-z0-9]+)$/.exec(url)?.[1]; + const token = /^Bearer (\S+)$/.exec( + request.headers.authorization ?? "" + )?.[1]; + const mcp = Boolean( + agentId && + token && + ["GET", "POST", "DELETE"].includes(request.method ?? "") && + target?.validAgentToken?.(token, agentId) + ); if ((!ping && !mcp) || !target) { response.writeHead(ping || mcp ? 503 : 404).end(); return; @@ -568,18 +645,21 @@ export class RemoteRunnerService { : target.host === "::" ? "::1" : target.host; - const headers = { ...request.headers }; + // Allow-list: nothing ambient (cookies, forwarding, origin) crosses. + const headers: http.OutgoingHttpHeaders = {}; for (const name of [ - "cookie", - "host", - "origin", - "referer", - "forwarded", - "x-forwarded-for", - "x-forwarded-host", - "x-forwarded-proto", + "accept", + "content-type", + "content-length", + "transfer-encoding", + "user-agent", + "last-event-id", + "mcp-session-id", + "mcp-protocol-version", + ...(mcp ? ["authorization"] : []), ]) - delete headers[name]; + if (request.headers[name] !== undefined) + headers[name] = request.headers[name]; const upstream = (target.tls ? https : http).request( { host, @@ -612,7 +692,8 @@ export class RemoteRunnerService { if (this.legacy) { const peer = this.peers.get(this.legacy.id); runners.push({ - id: `${LEGACY_PREFIX}${this.legacy.id}`, + // Legacy locators keep addressing the configured id. + id: this.legacy.id, name: this.legacy.id, status: peer?.gate.approved() ? "online" : "offline", workspaces: peer @@ -624,7 +705,7 @@ export class RemoteRunnerService { } if (!this.enrollment) return runners; for (const registration of await this.enrollment.registry.list()) { - const peer = this.peers.get(registration.name); + const peer = this.peers.get(registration.id); const online = !registration.revoked && peer?.gate.registrationId === registration.id && @@ -648,20 +729,12 @@ export class RemoteRunnerService { async createRegistration(name: unknown, hostHint?: string) { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); - if (typeof name !== "string" || !RUNNER_NAME.test(name)) + if (!validRunnerName(name)) throw new RunnerRequestError( 400, - "Runner names use lowercase letters, digits and hyphens (1-40 characters)." - ); - if (this.legacy?.id === name) - throw new RunnerRequestError( - 409, - `A runner named "${name}" already exists.` + "Runner names are 1-64 characters without control characters or surrounding spaces." ); - const host = this.enrollment.endpointHost ?? hostHint ?? os.hostname(); - if (!validHost(host)) - throw new RunnerRequestError(400, "The runner endpoint host is invalid."); - await this.ensureListening(host); + const host = await this.prepareEndpoint(hostHint); try { const { id, code, expiresAt } = await this.enrollment.registry.create( name, @@ -684,9 +757,40 @@ export class RemoteRunnerService { } } + private async prepareEndpoint(hostHint?: string) { + const host = this.enrollment!.endpointHost ?? hostHint ?? os.hostname(); + if (!validHost(host)) + throw new RunnerRequestError(400, "The runner endpoint host is invalid."); + await this.ensureListening(host); + return host; + } + + /** + * Renewal and re-keying: a fresh one-time code for an existing + * registration. Pairing with it replaces the certificate, keeps the id + * (so agent placements are unchanged), and drops the old connection. + */ + async reissueRegistration(id: string, hostHint?: string) { + if (!this.enrollment || this.legacy?.id === id) + throw new RunnerRequestError(404, "Runner not found."); + const host = await this.prepareEndpoint(hostHint); + const issued = await this.enrollment.registry.reissue(id, host); + if (!issued) throw new RunnerRequestError(404, "Runner not found."); + return { + id, + command: pairingCommand({ + host, + port: this.port!, + caFingerprint: this.authority!.caFingerprint, + code: issued.code, + }), + expiresAt: issued.expiresAt.toISOString(), + }; + } + /** Revoke a registration and drop its live connection immediately. */ async revoke(id: string) { - if (id.startsWith(LEGACY_PREFIX) && this.legacy) + if (this.legacy?.id === id) throw new RunnerRequestError( 409, "This runner is configured by DISPATCH_REMOTE_SERVICE_CONFIG; empty its approval file to revoke it." diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts index 644aecda5..ea024929e 100644 --- a/apps/server/src/routes/runners.ts +++ b/apps/server/src/routes/runners.ts @@ -54,6 +54,25 @@ export async function registerRunnerRoutes( } }); + // Renew or re-key: a new one-time pairing command for the same id. + app.post(`${base}/:id/pair`, async (request, reply) => { + const { id } = request.params as { id: string }; + if (!deps.runners) + return reply.code(404).send({ error: "Runner not found." }); + try { + return reply + .code(201) + .send( + await deps.runners.reissueRegistration( + id, + hostHint(request.headers.host) + ) + ); + } catch (error) { + return fail(reply, error); + } + }); + app.delete(`${base}/:id`, async (request, reply) => { const { id } = request.params as { id: string }; if (!deps.runners) diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 35345e843..1159cd6cc 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -211,6 +211,9 @@ const remoteRunner = configuredRunner({ host: config.listenHosts?.[0] ?? config.host, apiPort: config.port, apiTls: Boolean(config.tls), + // authToken is resolved at startup; read it per request. + validAgentToken: (token, agentId) => + validateAgentMcpToken(config.authToken, token, agentId), }); const agentManager = new AgentManager(pool, app.log, config, { remote: remoteRunner, diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index d18fa676e..06a58fbc4 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -121,16 +121,21 @@ describe("runner enrollment service", () => { const services: RemoteRunnerService[] = []; const runners: FakeRunner[] = []; - const makeService = (port?: number) => { + const makeService = (repoTool?: boolean | string[]) => { const service = new RemoteRunnerService( undefined, { registry: new RunnerRegistry(pool), host: HOST, - port, endpointHost: HOST, + repoTool, }, - { host: HOST, port: (api.address() as AddressInfo).port, tls: false } + { + host: HOST, + port: (api.address() as AddressInfo).port, + tls: false, + validAgentToken: (token, agentId) => token === `agent-token:${agentId}`, + } ); services.push(service); return service; @@ -224,7 +229,11 @@ describe("runner enrollment service", () => { }) ); await waitFor(() => - service.available({ runner: "alpha", workspace: "proof" }) + service.available({ runner: created.id, workspace: "proof" }) + ); + // Placements address the opaque registration id, never the name. + expect(service.available({ runner: "alpha", workspace: "proof" })).toBe( + false ); expect(await service.list()).toEqual([ { @@ -238,9 +247,12 @@ describe("runner enrollment service", () => { it("validates names and rejects duplicates", async () => { const service = makeService(); - await expect(service.createRegistration("Bad Name")).rejects.toMatchObject({ - status: 400, - }); + for (const bad of [" padded", "", "x".repeat(65), "tab\tname", 7]) + await expect(service.createRegistration(bad)).rejects.toMatchObject({ + status: 400, + }); + // Display names are free-form; only the id addresses placements. + await service.createRegistration("Lima VM (arm64)"); await service.createRegistration("dup"); await expect(service.createRegistration("dup")).rejects.toBeInstanceOf( RunnerRequestError @@ -269,8 +281,8 @@ describe("runner enrollment service", () => { workspaces: ["proof"], }); runners.push(alpha, beta); - const alphaPlace = { runner: "alpha", workspace: "proof" }; - const betaPlace = { runner: "beta", workspace: "proof" }; + const alphaPlace = { runner: a.id, workspace: "proof" }; + const betaPlace = { runner: b.id, workspace: "proof" }; await waitFor( () => service.available(alphaPlace) && service.available(betaPlace) ); @@ -329,7 +341,133 @@ describe("runner enrollment service", () => { }); runners.push(rogue); await rogue.closed; - expect(service.available({ runner: "alpha", workspace: "proof" })).toBe( + expect(service.available({ runner: a.id, workspace: "proof" })).toBe(false); + }); + + it("never routes an old placement to a re-paired runner with the same name", async () => { + const service = makeService(true); + const old = await enroll(service, "lima"); + const oldPlace = { runner: old.id, workspace: "proof" }; + expect(service.permitsAgentMcp(oldPlace)).toBe(true); + await service.revoke(old.id); + expect(service.permitsAgentMcp(oldPlace)).toBe(false); + expect(service.repoToolFor(oldPlace)).toBe(false); + + const fresh = await enroll(service, "lima"); + expect(fresh.id).not.toBe(old.id); + const freshPlace = { runner: fresh.id, workspace: "proof" }; + // Offline but active: the agent's MCP credential stays valid. + expect(service.permitsAgentMcp(freshPlace)).toBe(true); + const runner = await dialRunner({ + endpoint: fresh.endpoint, + ca: fresh.ca, + cert: fresh.cert, + key: fresh.key, + label: "fresh", + workspaces: ["proof"], + }); + runners.push(runner); + await waitFor(() => service.available(freshPlace)); + expect(service.available(oldPlace)).toBe(false); + await expect( + service.request(oldPlace, { + kind: "alive", + agentId: "agt_old", + workspace: "proof", + }) + ).rejects.toBeInstanceOf(RunnerUnavailable); + expect(runner.requests.some((f) => f.type === "request")).toBe(false); + expect( + service.permitsAgentMcp({ runner: "rnr_unknown", workspace: "proof" }) + ).toBe(false); + const listed = await service.list(); + expect(listed.map((r) => [r.name, r.status])).toEqual([ + ["lima", "revoked"], + ["lima", "online"], + ]); + }); + + it("renews a certificate under the same id and retires the old one", async () => { + const service = makeService(); + const a = await enroll(service, "alpha"); + const place = { runner: a.id, workspace: "proof" }; + const before = await dialRunner({ + endpoint: a.endpoint, + ca: a.ca, + cert: a.cert, + key: a.key, + label: "old", + workspaces: ["proof"], + }); + runners.push(before); + await waitFor(() => service.available(place)); + + const renewal = await service.reissueRegistration(a.id); + expect(renewal.id).toBe(a.id); + const { endpoint, pin, code } = parseCommand(renewal.command); + const key = generateRunnerKey(); + const renewed = await exchangeCode({ + endpoint, + pin, + code, + publicKey: key.publicKey, + }); + expect(renewed.id).toBe(a.id); + await before.closed; + + const stale = await dialRunner({ + endpoint: a.endpoint, + ca: a.ca, + cert: a.cert, + key: a.key, + label: "old", + workspaces: ["proof"], + }); + runners.push(stale); + await stale.closed; + const after = await dialRunner({ + endpoint, + ca: renewed.ca, + cert: renewed.cert, + key: key.key, + label: "new", + workspaces: ["proof"], + }); + runners.push(after); + await waitFor(() => service.available(place)); + expect( + ( + await service.request(place, { + kind: "alive", + agentId: "agt_x", + workspace: "proof", + }) + ).value + ).toBe("new"); + await service.revoke(a.id); + await expect(service.reissueRegistration(a.id)).rejects.toMatchObject({ + status: 404, + }); + }); + + it("scopes the repo operation to approved placements", async () => { + const service = makeService(); + const a = await enroll(service, "alpha"); + const b = await enroll(service, "beta"); + const scoped = makeService([`${a.id}/proof`, b.id]); + await scoped.startEnrolled(); + expect(service.repoToolFor({ runner: a.id, workspace: "proof" })).toBe( + false + ); + expect(scoped.repoToolFor({ runner: a.id, workspace: "proof" })).toBe(true); + expect(scoped.repoToolFor({ runner: a.id, workspace: "other" })).toBe( + false + ); + expect(scoped.repoToolFor({ runner: b.id, workspace: "anything" })).toBe( + true + ); + await scoped.revoke(b.id); + expect(scoped.repoToolFor({ runner: b.id, workspace: "anything" })).toBe( false ); }); @@ -337,15 +475,14 @@ describe("runner enrollment service", () => { it("persists the CA, port and registrations across a service restart", async () => { const first = makeService(); const a = await enroll(first, "alpha"); + const place = (workspace: string) => ({ runner: a.id, workspace }); const port = Number(new URL(a.endpoint).port); first.close(); services.splice(services.indexOf(first), 1); const second = makeService(); await second.startEnrolled(); - expect(second.originFor({ runner: "alpha", workspace: "proof" })).toBe( - `https://127.0.0.1:${port}` - ); + expect(second.originFor(place("proof"))).toBe(`https://127.0.0.1:${port}`); runners.push( await dialRunner({ endpoint: a.endpoint, @@ -356,9 +493,7 @@ describe("runner enrollment service", () => { workspaces: ["proof", "other"], }) ); - await waitFor(() => - second.available({ runner: "alpha", workspace: "other" }) - ); + await waitFor(() => second.available(place("other"))); second.close(); services.splice(services.indexOf(second), 1); // Last reported workspaces survive while offline. @@ -373,7 +508,7 @@ describe("runner enrollment service", () => { }); }); - it("proxies only bearer-authenticated agent MCP routes to the API", async () => { + it("proxies only agent-token MCP routes with allow-listed headers", async () => { const service = makeService(); const a = await enroll(service, "alpha"); const origin = new URL(a.endpoint); @@ -408,15 +543,86 @@ describe("runner enrollment service", () => { (await get("/api/v1/agents", { authorization: "Bearer x" })).status ).toBe(404); expect((await get("/api/mcp/agt_abc")).status).toBe(404); + // Non-agent credentials (e.g. the admin API token) never pass. + expect( + (await get("/api/mcp/agt_abc", { authorization: "Bearer admin" }, "POST")) + .status + ).toBe(404); + expect( + ( + await get( + "/api/mcp/agt_abc", + { authorization: "Bearer agent-token:agt_other" }, + "POST" + ) + ).status + ).toBe(404); apiRequests.length = 0; expect( await get( "/api/mcp/agt_abc", - { authorization: "Bearer token", cookie: "dispatch_session=secret" }, + { + authorization: "Bearer agent-token:agt_abc", + cookie: "dispatch_session=secret", + "x-forwarded-for": "10.0.0.1", + "x-dispatch-admin": "1", + origin: "https://evil.example", + "mcp-session-id": "s1", + }, "POST" ) ).toEqual({ status: 200, body: "api:/api/mcp/agt_abc" }); - expect(apiRequests[0]?.headers.authorization).toBe("Bearer token"); - expect(apiRequests[0]?.headers.cookie).toBeUndefined(); + const forwarded = apiRequests[0]!.headers; + expect(forwarded.authorization).toBe("Bearer agent-token:agt_abc"); + expect(forwarded["mcp-session-id"]).toBe("s1"); + for (const name of [ + "cookie", + "x-forwarded-for", + "x-dispatch-admin", + "origin", + ]) + expect(forwarded[name], name).toBeUndefined(); + // /ping carries no credentials upstream. + apiRequests.length = 0; + await get("/ping", { authorization: "Bearer agent-token:agt_abc" }); + expect(apiRequests[0]?.headers.authorization).toBeUndefined(); + }); +}); + +describe("legacy runner config", () => { + it("keeps its locator and gates MCP on the live approval file", async () => { + const { mkdtemp, writeFile } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const path = await import("node:path"); + const dir = await mkdtemp(path.join(tmpdir(), "legacy-runner-")); + const approval = path.join(dir, "approval"); + await writeFile(approval, "AA:BB\n"); + const service = new RemoteRunnerService({ + id: "lima", + host: HOST, + port: 0, + cert: "", + key: "", + ca: "", + approval, + workspaces: ["proof"], + endpointHost: "host.lima.internal", + repoTool: true, + }); + const place = { runner: "lima", workspace: "proof" }; + expect(service.permitsAgentMcp(place)).toBe(true); + expect(service.repoToolFor(place)).toBe(true); + expect(service.permitsAgentMcp({ runner: "lima", workspace: "x" })).toBe( + false + ); + expect(service.originFor(place)).toBe("https://host.lima.internal:0"); + expect((await service.list())[0]).toMatchObject({ + id: "lima", + name: "lima", + }); + await expect(service.revoke("lima")).rejects.toMatchObject({ status: 409 }); + await writeFile(approval, ""); + expect(service.permitsAgentMcp(place)).toBe(false); + expect(service.repoToolFor(place)).toBe(false); }); }); diff --git a/apps/server/test/runner-routes.test.ts b/apps/server/test/runner-routes.test.ts index 0575f48f1..20c720e87 100644 --- a/apps/server/test/runner-routes.test.ts +++ b/apps/server/test/runner-routes.test.ts @@ -53,7 +53,7 @@ describe("runner control API", () => { method: "POST", url: "/api/runners", headers: { cookie }, - payload: { name: "../x" }, + payload: { name: " padded" }, }); expect(bad.statusCode).toBe(400); const duplicate = await ctx.app.inject({ @@ -75,6 +75,19 @@ describe("runner control API", () => { ], }); + const renewal = await ctx.app.inject({ + method: "POST", + url: `/api/runners/${body.id}/pair`, + headers: { cookie }, + }); + expect(renewal.statusCode).toBe(201); + expect(renewal.json().id).toBe(body.id); + const unauthenticatedRenewal = await ctx.app.inject({ + method: "POST", + url: `/api/runners/${body.id}/pair`, + }); + expect(unauthenticatedRenewal.statusCode).toBe(401); + const revoked = await ctx.app.inject({ method: "DELETE", url: `/api/runners/${body.id}`, diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 866633961..bd2b30444 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -68,7 +68,11 @@ writes `key.pem` (0600), `cert.pem` and `ca.pem`. It also sets `endpoint`, `ca`, registrations along with their last reported workspaces. `DELETE /api/runners/:id` revokes a registration and drops its connection immediately. Each registration is an independent mTLS peer, addressed as -`runner:///`. +`runner:///`. Names are display labels and can +be reused after revocation. A replacement gets a new id, so an old agent never +reaches it. `POST /api/runners/:id/pair` renews or re-keys a runner. It issues +a new one-time command for the same id, and pairing with it retires the old +certificate and connection. Restart the runner service afterwards. The listener binds `DISPATCH_RUNNER_HOST`, which defaults to the API host. It uses `DISPATCH_RUNNER_PORT` when set. Otherwise it uses the persisted port, and @@ -76,8 +80,12 @@ on first start a free port. `DISPATCH_RUNNER_ENDPOINT_HOST` overrides the host written into commands, which otherwise comes from the request's Host header. The listener certificate gains each advertised host automatically. Unless `DISPATCH_RUNNER_MCP_ORIGIN` is set, the agent MCP origin is the runner -listener itself. It forwards only bearer-authenticated `/api/mcp/agt_*` -requests and `GET /ping` to the local API, with cookies removed. +listener itself. It forwards `/api/mcp/` only with that agent's +own MCP token, and forwards `GET /ping`. It passes on only allow-listed +headers, so no cookies, origin, forwarding or admin headers. It refuses +every other path, including the admin API token. +`DISPATCH_RUNNER_REPO_TOOL` approves the repo operation for `1` (every placement) or a +comma list of `` or `/`. `DISPATCH_RUNNERS=0` disables enrollment. The legacy `DISPATCH_REMOTE_SERVICE_CONFIG` below still works. Its `mcpOrigin` is now optional when `endpointHost` is given. From 7744d4cf0c231fe86da97eb43bf66c5126e84acd Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 23:05:06 -0700 Subject: [PATCH 013/642] Harden remote runner acceptance: new-turn assertions, id placement, redaction, cleanup check Co-Authored-By: Claude Sonnet 5.5 --- e2e/remote-runner/acceptance.spec.ts | 12 +++++++++--- e2e/remote-runner/harness.ts | 26 ++++++++++++++++++++++++-- e2e/remote-runner/playwright.config.ts | 1 + e2e/remote-runner/setup.mjs | 1 + scripts/e2e-remote-runners.sh | 8 +++++++- 5 files changed, 42 insertions(+), 6 deletions(-) diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index f75e1deb7..37bde4dc2 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -25,8 +25,9 @@ import { // file landing on the wrong side is visible. test.describe.configure({ mode: "serial" }); const WS = state.workspace; -const loc = (r: RunnerName) => `runner://${r}/${WS}`; const runnerIds: Partial> = {}; +// Placement is keyed by the opaque registration id, never the display name. +const loc = (r: RunnerName) => `runner://${runnerIds[r]}/${WS}`; const agents: Record<"local" | RunnerName, string> = { local: "", alpha: "", @@ -77,6 +78,8 @@ test("UI launches local, alpha and beta; each answer comes from its own side", a ); expect(status).toBe(201); agents[key] = id!; + if (key !== "local") + expect((await agentInfo(page.request, id!)).cwd).toBe(loc(key)); await expect(page).toHaveURL((u) => u.pathname === `/agents/${id}`, { timeout: 15_000, }); @@ -238,8 +241,11 @@ test.describe("failure suite", () => { expect(body).not.toBeNull(); const bad = body!.command.replace(/--code\s+\S+/, "--code WRONGCODE"); expect(() => pairInContainer("beta", bad)).toThrow(); - pairInContainer("beta", body!.command); // would overwrite beta's creds; restored below - expect(() => pairInContainer("beta", body!.command)).toThrow(); // replay + // Pair the unused code into a throwaway dir so beta's live credentials stay intact. + pairInContainer("beta", body!.command, "/tmp/gamma-creds"); + expect(() => + pairInContainer("beta", body!.command, "/tmp/gamma-creds-2") + ).toThrow(); // replay const row = await runnerRow(request, "gamma"); expect(["pending", "online", "offline"]).toContain(row?.status); }); diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 4150b2cba..5d4652ce8 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -96,7 +96,11 @@ export async function createPairing(request: APIRequestContext, name: string) { } /** Pair inside the container (key generated there), then start the runner. */ -export function pairInContainer(name: RunnerName, command: string) { +export function pairInContainer( + name: RunnerName, + command: string, + dir = "/etc/dispatch-runner" +) { const c = state.runners[name].container; const pair = viaLane(name, command).replace( /^dispatch-runner/, @@ -107,7 +111,7 @@ export function pairInContainer(name: RunnerName, command: string) { c, "sh", "-c", - `${pair} --dir /etc/dispatch-runner --config /run/cfg/runner.json 2>&1` + `${pair} --dir ${dir} ${dir === "/etc/dispatch-runner" ? "--config /run/cfg/runner.json" : ""} 2>&1` ); } export function startRunner(name: RunnerName) { @@ -258,3 +262,21 @@ export async function launchViaApi(request: APIRequestContext, cwd: string) { trackAgent(((await res.json()) as { agent: { id: string } }).agent.id); return res.status(); } + +/** Settled-turn counter: proves a NEW provider turn, not an old or echoed reply. */ +export const settledTurns = (page: Page) => + page.locator('[data-testid="chat-turn"][data-settled="true"]'); + +/** Send `prompt` and require one additional settled turn whose answer contains `expected`. */ +export async function newSettledTurn( + page: Page, + prompt: string, + expected: string +) { + const before = await settledTurns(page).count(); + await chat(page, prompt); + await expect(settledTurns(page)).toHaveCount(before + 1, { timeout: 45_000 }); + await expect( + settledTurns(page).last().getByTestId("harness-result") + ).toContainText(expected); +} diff --git a/e2e/remote-runner/playwright.config.ts b/e2e/remote-runner/playwright.config.ts index e9d6792fa..bd00053a5 100644 --- a/e2e/remote-runner/playwright.config.ts +++ b/e2e/remote-runner/playwright.config.ts @@ -20,6 +20,7 @@ export default defineConfig({ env: { ...((base.webServer as { env?: Record }).env ?? {}), DISPATCH_RUNNER_HOST: process.env.DISPATCH_RUNNER_HOST ?? "", + DISPATCH_RUNNER_REPO_TOOL: process.env.DISPATCH_RUNNER_REPO_TOOL ?? "", DISPATCH_RUNNER_PORT: process.env.DISPATCH_RUNNER_PORT ?? "", DISPATCH_RUNNER_ENDPOINT_HOST: process.env.DISPATCH_RUNNER_ENDPOINT_HOST ?? "", diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs index e97f47eaf..35c42ac25 100644 --- a/e2e/remote-runner/setup.mjs +++ b/e2e/remote-runner/setup.mjs @@ -94,6 +94,7 @@ async function up(run) { // Enrolled-mode service settings (no registration file; see enrollment slice). writeFileSync(path.join(run, "env"), [ "export DISPATCH_RUNNER_HOST=0.0.0.0", + "export DISPATCH_RUNNER_REPO_TOOL=1", // approved repo operation for every placement `export DISPATCH_RUNNER_PORT=${runnerPort}`, "export DISPATCH_RUNNER_ENDPOINT_HOST=host.docker.internal", `export REMOTE_E2E_STATE='${path.join(run, "state.json")}'`, "", diff --git a/scripts/e2e-remote-runners.sh b/scripts/e2e-remote-runners.sh index ecf3ba985..21a1ca167 100755 --- a/scripts/e2e-remote-runners.sh +++ b/scripts/e2e-remote-runners.sh @@ -7,7 +7,13 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" BASE="${REMOTE_E2E_ROOT:-$HOME/.cache/dispatch-remote-e2e}" # must be shared with the Docker VM (not /tmp on Colima) mkdir -p "$BASE" RUN_DIR="$BASE/run-$$-$(date +%s)" -cleanup() { node "$ROOT_DIR/e2e/remote-runner/setup.mjs" down "$RUN_DIR" || true; rm -rf "$RUN_DIR"; } +cleanup() { + node "$ROOT_DIR/e2e/remote-runner/setup.mjs" down "$RUN_DIR" || true + rm -rf "$RUN_DIR" + # Credentials live only inside the containers; prove none survive. + left="$(docker ps -aq --filter "label=dispatch-remote-e2e=$(basename "$RUN_DIR")")" + [ -z "$left" ] || { echo "LEAK: runner containers remain: $left" >&2; exit 1; } +} trap cleanup EXIT node "$ROOT_DIR/e2e/remote-runner/setup.mjs" up "$RUN_DIR" # shellcheck disable=SC1091 From bbf98daf34a036fefaa43c812d5fc710ba29654f Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Tue, 17 Nov 2026 23:05:48 -0700 Subject: [PATCH 014/642] Keep revoked or missing runner selected as unavailable; poll runners in Create Agent Co-Authored-By: Claude Sonnet 5.5 --- .../components/app/create-agent-dialog.tsx | 1 + apps/web/src/components/app/runner-picker.tsx | 22 +++++++++++++++++-- .../components/app/use-create-agent-form.ts | 16 +++++++------- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index 28391b783..c9e024e20 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -156,6 +156,7 @@ function CreateAgentDialogContent({ void; workspace: string | null; onWorkspaceChange: (workspace: string) => void; + unavailable: boolean; }): JSX.Element | null { const runnerLabelId = useId(); const workspaceLabelId = useId(); const usable = runners.filter((r) => r.status !== "revoked"); - if (usable.length === 0) return null; + if (usable.length === 0 && !runnerId) return null; const selected = usable.find((r) => r.id === runnerId); return (
@@ -50,6 +52,12 @@ export function RunnerPicker({ This Mac + {unavailable && runnerId ? ( + + {runners.find((r) => r.id === runnerId)?.name ?? "Runner"}{" "} + (unavailable) + + ) : null} {usable.map((runner) => (
- {selected ? ( + {unavailable ? ( +

+ This runner is revoked or gone. Choose This Mac or another runner to + continue. +

+ ) : null} + {selected && !unavailable ? (
+

{runner.workspaces.length > 0 ? `Workspaces: ${runner.workspaces.join(", ")}` diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index 0366d462d..ca2b14419 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -1,3 +1,4 @@ +import type { RunnerHealth } from "@dispatch/runner-protocol"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "@/lib/api"; @@ -9,6 +10,8 @@ export type Runner = { name: string; status: RunnerStatus; workspaces: string[]; + health?: RunnerHealth; + healthReceivedAt?: string; }; export type RunnerPairing = { id: string; command: string; expiresAt: string }; diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 01162e31d..43ef6d3b1 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -78,3 +78,18 @@ outcome. Reconcile such an operation from journal evidence and avoid automatic resubmission. A legacy prompt with no journal ID bypasses receipt deduplication. `prompt_deferred` explicitly indicates the host held back submission because an engine-initiated turn was already open. + +## Runner health + +A runner can advertise `health: true` in its v1 ready frame. A service that +wants reports replies once with `{"type":"accept_health"}`. The runner pushes +a `health` frame containing its latest sample immediately and every 30 seconds +while connected. Older services ignore the advertisement. A service chooses +what to retain. Samples have no journal cursor, acknowledgement or replay. +Reconnection starts a fresh reporting interval. + +Session and working counts describe live agent hosts and hosts with an open +turn. CPU is a percentage over two samples (null until available), and memory +is reported in bytes. Version identifies the runner build. Dispatch binds each +report to its authenticated registration and stores the last snapshot with a +service-side receipt time so stale measurements can be labeled after disconnect. diff --git a/packages/runner-protocol/src/health.ts b/packages/runner-protocol/src/health.ts new file mode 100644 index 000000000..3e2d1c4f8 --- /dev/null +++ b/packages/runner-protocol/src/health.ts @@ -0,0 +1,34 @@ +/** An instantaneous, replaceable sample. Capacity is relative to the runner environment. */ +export type RunnerHealth = { + version: string; + sessions: number; + working: number; + cpuPercent: number | null; + memoryUsed: number; + memoryTotal: number; +}; + +export function parseRunnerHealth(input: unknown): RunnerHealth | null { + if (!input || typeof input !== "object") return null; + const { version, sessions, working, cpuPercent, memoryUsed, memoryTotal } = + input as Record; + const count = (n: unknown): n is number => + typeof n === "number" && Number.isSafeInteger(n) && n >= 0; + if ( + typeof version !== "string" || + !/^[\w.+-]{1,80}$/.test(version) || + !count(sessions) || + !count(working) || + working > sessions || + !count(memoryUsed) || + !count(memoryTotal) || + memoryUsed > memoryTotal || + (cpuPercent !== null && + (typeof cpuPercent !== "number" || + !Number.isFinite(cpuPercent) || + cpuPercent < 0 || + cpuPercent > 100)) + ) + return null; + return { version, sessions, working, cpuPercent, memoryUsed, memoryTotal }; +} diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index d62f77bc3..eaad74776 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -1,3 +1,5 @@ +import type { RunnerHealth } from "./health.js"; +export { type RunnerHealth, parseRunnerHealth } from "./health.js"; export type Placement = { runner: string; workspace: string }; /** Wire identities are case-sensitive and are not paths. */ @@ -71,7 +73,14 @@ export type Command = { agentId: string; workspace: string } & ( | { kind: "stop"; force: boolean } ); export type Frame = - | { type: "ready"; version: typeof RUNNER_WIRE_VERSION; workspaces: string[] } + | { + type: "ready"; + version: typeof RUNNER_WIRE_VERSION; + workspaces: string[]; + health?: true; + } + | { type: "accept_health" } + | { type: "health"; sample: RunnerHealth } | { type: "request"; id: string; command: Command } | { type: "result"; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f6febd538..afa5a4500 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -177,6 +177,9 @@ importers: apps/web: dependencies: + '@dispatch/runner-protocol': + specifier: workspace:* + version: link:../../packages/runner-protocol '@dispatch/shared': specifier: workspace:* version: link:../../packages/shared From 94981e1587425f5b4a1fc3cbf499ba3639dbf176 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 08:35:00 -0700 Subject: [PATCH 031/642] Add private managed runner scratch sessions and durable archive retry --- apps/server/src/agents/archive.ts | 17 ++-- apps/server/src/agents/manager.ts | 47 +++++++++-- apps/server/src/agents/remote/runner.ts | 81 ++++++++++++++++--- .../src/agents/remote/session-storage.ts | 15 ++++ .../0056_managed_runner_sessions.sql | 6 ++ apps/server/src/routes/agents/crud-routes.ts | 9 ++- .../test/remote-session-storage.test.ts | 41 ++++++++++ packages/runner-protocol/src/index.ts | 6 +- 8 files changed, 199 insertions(+), 23 deletions(-) create mode 100644 apps/server/src/agents/remote/session-storage.ts create mode 100644 apps/server/src/db/migrations/0056_managed_runner_sessions.sql create mode 100644 apps/server/test/remote-session-storage.test.ts diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index 70c28215d..b3d4093f0 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -11,6 +11,7 @@ import { getUnmergedChanges, } from "../shared/git/worktree-status.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; +import { MANAGED_WORKSPACE, remotePlacement } from "./remote/protocol.js"; import { AgentError } from "./errors.js"; import type { AgentRuntime } from "./runtime.js"; import type { @@ -264,6 +265,8 @@ export async function executeArchive( try { const agent = await deps.getRequiredAgent(id); const cleanupWorktree = agent.archiveCleanupMode ?? "auto"; + let runnerCleanupPending = + remotePlacement(agent.cwd)?.workspace === MANAGED_WORKSPACE; // Phase: stopping — tear down session without changing agent status const t = Date.now(); @@ -280,6 +283,7 @@ export async function executeArchive( // The state directory holds the launch file with the MCP token; the // stream is already in the database. await runtime.discard(id); + runnerCleanupPending = false; } catch (err) { logger.warn( { err, agentId: id }, @@ -338,8 +342,8 @@ export async function executeArchive( const tDb = Date.now(); await pool.query( - "UPDATE agents SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = NULL, updated_at = NOW() WHERE id = $1", - [id] + "UPDATE agents SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = NULL, runner_cleanup_pending = $2, updated_at = NOW() WHERE id = $1", + [id, runnerCleanupPending] ); durations.db = Date.now() - tDb; diffStatsRefresher?.clear(id); @@ -399,7 +403,9 @@ export async function deleteAgentDirect( return []; } - if (agent.status !== "stopped") { + let runnerCleanupPending = + remotePlacement(agent.cwd)?.workspace === MANAGED_WORKSPACE; + if (agent.status !== "stopped" || runnerCleanupPending) { const t = Date.now(); // Not stopAgent: it writes `stopping`/`stopped`, releasing the claim above // and letting a fresh archive take this agent mid-teardown. @@ -416,6 +422,7 @@ export async function deleteAgentDirect( // The state directory holds the launch file with the MCP token; the // stream is already in the database. await runtime.discard(id); + runnerCleanupPending = false; } catch (err) { logger.warn( { err, agentId: id }, @@ -466,9 +473,9 @@ export async function deleteAgentDirect( await pool.query( `UPDATE agents - SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = NULL, updated_at = NOW() + SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = NULL, runner_cleanup_pending = $2, updated_at = NOW() WHERE id = $1`, - [id] + [id, runnerCleanupPending] ); durations.db = Date.now() - tDb; diffStatsRefresher?.clear(id); diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index d5f7cb4dc..391ad1903 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -73,7 +73,7 @@ import type { } from "./acp/prompt-source.js"; import { type EngineBins, isAcpEngine } from "./acp/engine-spec.js"; import { RemoteEventInbox } from "./remote/event-inbox.js"; -import { remotePlacement } from "./remote/protocol.js"; +import { MANAGED_WORKSPACE, remotePlacement } from "./remote/protocol.js"; import { RunnerRevoked, type RemoteRunnerService } from "./remote/service.js"; import { buildLaunchEnv } from "./acp/launch-env.js"; import { dispatchMcpUrl } from "./acp/mcp-url.js"; @@ -1376,7 +1376,7 @@ export class AgentManager { ); } if ( - input.projectId || + (input.projectId && placement.workspace !== MANAGED_WORKSPACE) || input.parentAgentId || input.templateId || input.persona || @@ -1385,7 +1385,7 @@ export class AgentManager { input.useWorktree ) { throw new AgentError( - "Runner launches currently require a standalone agent in a pre-provisioned workspace.", + "Runner launches require a standalone agent and runner-managed storage.", 400 ); } @@ -1422,7 +1422,7 @@ export class AgentManager { ).rows[0]; if (!project) throw new AgentError("Project not found.", 404); // A child can use its parent's worktree while retaining explicit membership. - if (!input.parentAgentId) { + if (!placement && !input.parentAgentId) { input.cwd = project.repo_root; // Plain-folder projects have no Git to branch from; only an explicit // useWorktree: true should attempt (and fail) a worktree there. @@ -2410,6 +2410,7 @@ export class AgentManager { // entry point, so we drop the return value. await this.reconciler.reconcileAgentStatuses(); await this.reconciler.cleanupOrphanedHosts(); + await this.retryRunnerCleanup(); } /** @@ -2418,7 +2419,43 @@ export class AgentManager { * the orphan-session cleanup too should call `reconcileAgents()`. */ async reconcileAgentStatuses(): Promise { - return this.reconciler.reconcileAgentStatuses(); + const changed = await this.reconciler.reconcileAgentStatuses(); + void this.retryRunnerCleanup().catch((err) => + this.logger.warn({ err }, "Could not retry runner cleanup") + ); + return changed; + } + + private runnerCleanupRunning = false; + + private async retryRunnerCleanup(): Promise { + if (!this.remote || this.runnerCleanupRunning) return; + this.runnerCleanupRunning = true; + try { + const { rows } = await this.pool.query<{ id: string; cwd: string }>( + "SELECT id, cwd FROM agents WHERE runner_cleanup_pending AND deleted_at IS NOT NULL ORDER BY id" + ); + for (const { id, cwd } of rows) { + const placement = remotePlacement(cwd); + if (!placement || !this.remote.available(placement)) continue; + try { + await this.runtime.stop(id, true); + await this.streamRecorder.settleStopped(id); + await this.runtime.discard(id); + await this.pool.query( + "UPDATE agents SET runner_cleanup_pending = false WHERE id = $1", + [id] + ); + } catch (err) { + this.logger.warn( + { err, agentId: id }, + "Runner cleanup remains pending" + ); + } + } + } finally { + this.runnerCleanupRunning = false; + } } permitsRemoteAgentMcp( diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index b11932828..f79342179 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -21,9 +21,11 @@ import { ownedEnvironment, killOwnedProcesses, } from "../../shared/process/owned-processes.js"; +import { prepareScratchSession } from "./session-storage.js"; import { hostCommand } from "../acp/runtime.js"; import { isOpaqueId, + MANAGED_WORKSPACE, RUNNER_WIRE_VERSION, wireFrames, type Command, @@ -135,7 +137,10 @@ export async function runRemoteRunner(filename: string) { "Runner requires an HTTPS endpoint and a separate, non-root execution account." ); } - if (!Object.keys(config.workspaces).every(isOpaqueId)) { + if ( + Object.hasOwn(config.workspaces, MANAGED_WORKSPACE) || + !Object.keys(config.workspaces).every(isOpaqueId) + ) { throw new Error("Runner workspace IDs must be valid opaque identifiers."); } const env = { @@ -158,12 +163,16 @@ export async function runRemoteRunner(filename: string) { const bindings = path.join(config.state, "bindings"); const hostRoot = path.join(config.state, "hosts"); const logs = path.join(bindings, "logs"); + const sessions = path.join(config.state, "sessions"); await mkdir(logs, { recursive: true, mode: 0o700 }); await chmod(config.state, 0o711); await mkdir(hostRoot, { recursive: true, mode: 0o711 }); await chmod(hostRoot, 0o711); const sampleHealth = runnerHealthSampler(); + await mkdir(sessions, { mode: 0o711, recursive: true }); + await chmod(sessions, 0o711); + const hosts = new Map(); const active = new Set(); const owns = async (id: string, workspace: string) => @@ -172,7 +181,7 @@ export async function runRemoteRunner(filename: string) { async function launch( command: Extract, - cwd: string, + cwd: string | undefined, key: string ) { const { agentId, workspace } = command; @@ -194,7 +203,23 @@ export async function runRemoteRunner(filename: string) { throw error; } ); - if (!(await stat(cwd)).isDirectory()) + const markerFile = path.join(bindings, `${key}.owner`); + const previousMarker = await readFile(markerFile, "utf8").catch( + (error) => { + if (error.code !== "ENOENT") throw error; + return null; + } + ); + if (previousMarker) killOwnedProcesses(previousMarker); + if (workspace === MANAGED_WORKSPACE) { + cwd = await prepareScratchSession( + sessions, + key, + config.uid, + config.gid + ); + } + if (!cwd || !(await stat(cwd)).isDirectory()) throw new Error("Guest workspace is unavailable"); const dir = path.join(hostRoot, key); const files = path.join(dir, "files"); @@ -228,6 +253,8 @@ export async function runRemoteRunner(filename: string) { const [bin, ...args] = hostCommand(); if (!bin) throw new Error("Runner host executable is missing"); const owned = ownedEnvironment(env); + if (workspace === MANAGED_WORKSPACE) + await writeFile(markerFile, owned.marker, { mode: 0o600 }); const child = spawn( setpriv, [...childArgs, bin, ...args, "--state", dir], @@ -326,18 +353,31 @@ export async function runRemoteRunner(filename: string) { isOpaqueId(workspace) && Object.hasOwn(config.workspaces, workspace) ? config.workspaces[workspace] : undefined; - if (!isOpaqueId(agentId) || !target) + const managed = workspace === MANAGED_WORKSPACE; + if (!isOpaqueId(agentId) || (!target && !managed)) throw new Error("Unknown runner workspace or agent"); const key = runnerStorageKey(agentId); const result = (value?: string | boolean) => safeSend({ type: "result", id, value }); if (command.kind === "launch") { - await launch(command, target.cwd, key); + await launch(command, target?.cwd, key); result(true); return; } if (!(await owns(key, workspace))) { if (command.kind === "alive") return result(false); + if ( + managed && + (command.kind === "discard" || command.kind === "stop") && + !(await readFile(path.join(bindings, key), "utf8").catch( + (error) => { + if (error.code !== "ENOENT") throw error; + return null; + } + )) && + !active.has(agentId) + ) + return result(true); throw new Error("Agent is not bound to this workspace"); } if (socket.destroyed) return; @@ -403,8 +443,29 @@ export async function runRemoteRunner(filename: string) { case "discard": if (host || active.has(agentId)) throw new Error("Stop the guest host before discarding it"); - await rm(dir, { force: true, recursive: true }); - await rm(path.join(bindings, key), { force: true }); + active.add(agentId); + try { + if (managed) { + const markerPath = path.join(bindings, `${key}.owner`); + const marker = await readFile(markerPath, "utf8").catch( + (error) => { + if (error.code !== "ENOENT") throw error; + return null; + } + ); + if (marker) killOwnedProcesses(marker); + await rm(path.join(sessions, key), { + force: true, + recursive: true, + }); + await rm(markerPath, { force: true }); + await rm(path.join(logs, key), { force: true }); + } + await rm(dir, { force: true, recursive: true }); + await rm(path.join(bindings, key), { force: true }); + } finally { + active.delete(agentId); + } result(true); break; case "log": { @@ -417,7 +478,7 @@ export async function runRemoteRunner(filename: string) { break; } case "repo": { - const [bin, ...args] = target.repoTool ?? []; + const [bin, ...args] = target?.repoTool ?? []; if (!bin) throw new Error( "Runner workspace has no approved repo operation" @@ -426,7 +487,7 @@ export async function runRemoteRunner(filename: string) { setpriv, [...childArgs, bin, ...args], { - cwd: target.cwd, + cwd: target?.cwd, env, timeout: 10_000, maxBuffer: 64 * 1024, @@ -467,7 +528,7 @@ export async function runRemoteRunner(filename: string) { type: "ready", version: RUNNER_WIRE_VERSION, health: true, - workspaces: Object.keys(config.workspaces), + workspaces: [...Object.keys(config.workspaces), MANAGED_WORKSPACE], }); }); }); diff --git a/apps/server/src/agents/remote/session-storage.ts b/apps/server/src/agents/remote/session-storage.ts new file mode 100644 index 000000000..b7ba6f153 --- /dev/null +++ b/apps/server/src/agents/remote/session-storage.ts @@ -0,0 +1,15 @@ +import { chown, mkdir } from "node:fs/promises"; +import path from "node:path"; + +/** The supervisor-owned parent prevents workloads from replacing session roots. */ +export async function prepareScratchSession( + sessions: string, + key: string, + uid: number, + gid: number +): Promise { + const cwd = path.join(sessions, key); + await mkdir(cwd, { mode: 0o700, recursive: true }); + await chown(cwd, uid, gid); + return cwd; +} diff --git a/apps/server/src/db/migrations/0056_managed_runner_sessions.sql b/apps/server/src/db/migrations/0056_managed_runner_sessions.sql new file mode 100644 index 000000000..1cd1f8a83 --- /dev/null +++ b/apps/server/src/db/migrations/0056_managed_runner_sessions.sql @@ -0,0 +1,6 @@ +ALTER TABLE agents + ADD COLUMN runner_repository jsonb, + ADD COLUMN runner_cleanup_pending boolean NOT NULL DEFAULT false; + +CREATE INDEX agents_runner_cleanup_pending + ON agents (id) WHERE runner_cleanup_pending AND deleted_at IS NOT NULL; diff --git a/apps/server/src/routes/agents/crud-routes.ts b/apps/server/src/routes/agents/crud-routes.ts index f0762d77f..eef0caa77 100644 --- a/apps/server/src/routes/agents/crud-routes.ts +++ b/apps/server/src/routes/agents/crud-routes.ts @@ -1,3 +1,7 @@ +import { + MANAGED_WORKSPACE, + remotePlacement, +} from "../../agents/remote/protocol.js"; import { validateAgentEffort } from "../../shared/agent-effort.js"; import type { Effort } from "@dispatch/shared"; import { createReadStream } from "node:fs"; @@ -232,7 +236,10 @@ export async function registerAgentCrudRoutes( } if (!body.projectId && !body.cwd) body.projectId = taskBriefing.projectId; } - if (body.projectId && body.cwd) + const managed = + typeof body.cwd === "string" && + remotePlacement(body.cwd)?.workspace === MANAGED_WORKSPACE; + if (body.projectId && body.cwd && !managed) return reply .code(400) .send({ error: "Choose a project or a folder, not both." }); diff --git a/apps/server/test/remote-session-storage.test.ts b/apps/server/test/remote-session-storage.test.ts new file mode 100644 index 000000000..648d8c372 --- /dev/null +++ b/apps/server/test/remote-session-storage.test.ts @@ -0,0 +1,41 @@ +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { expect, it } from "vitest"; +import { prepareScratchSession } from "../src/agents/remote/session-storage.js"; +import { + MANAGED_WORKSPACE, + remotePlacement, + workspaceLocator, +} from "../src/agents/remote/protocol.js"; + +it("round trips the reserved workspace and recognizes its encoded form", () => { + const placement = { runner: "test", workspace: MANAGED_WORKSPACE }; + expect(workspaceLocator(placement)).toBe("runner://test/@session"); + expect(remotePlacement("runner://test/@session")).toEqual(placement); + expect(remotePlacement("runner://test/%40session")).toEqual(placement); +}); + +it("gives each session private scratch storage and reuses it when restarted", async () => { + const root = await mkdtemp( + path.join(os.tmpdir(), "dispatch-runner-session-") + ); + try { + const uid = process.getuid!(); + const gid = process.getgid!(); + const first = await prepareScratchSession(root, "first", uid, gid); + const second = await prepareScratchSession(root, "second", uid, gid); + expect(first).not.toBe(second); + expect((await stat(first)).mode & 0o777).toBe(0o700); + await writeFile(path.join(first, "marker"), "session data"); + expect(await prepareScratchSession(root, "first", uid, gid)).toBe(first); + expect(await readFile(path.join(first, "marker"), "utf8")).toBe( + "session data" + ); + await expect(readFile(path.join(second, "marker"))).rejects.toMatchObject({ + code: "ENOENT", + }); + } finally { + await rm(root, { force: true, recursive: true }); + } +}); diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index eaad74776..93db11f3d 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -1,5 +1,7 @@ import type { RunnerHealth } from "./health.js"; export { type RunnerHealth, parseRunnerHealth } from "./health.js"; +export const MANAGED_WORKSPACE = "@session"; + export type Placement = { runner: string; workspace: string }; /** Wire identities are case-sensitive and are not paths. */ @@ -23,7 +25,7 @@ export function isOpaqueId(value: unknown): value is string { /** Split first and decode each component exactly once. URL parsers can normalize IDs. */ export function remotePlacement(cwd: string): Placement | null { - const match = /^runner:\/\/([\w.!~*'()%+-]+)\/([\w.!~*'()%+-]+)$/.exec(cwd); + const match = /^runner:\/\/([\w.!~*'()%+-]+)\/([\w.!~*'()%+@-]+)$/.exec(cwd); if (!match || match[0] !== cwd) return null; try { const runner = decodeURIComponent(match[1]!); @@ -40,7 +42,7 @@ export function workspaceLocator({ runner, workspace }: Placement): string { if (!isOpaqueId(runner) || !isOpaqueId(workspace)) { throw new Error("Invalid runner or workspace ID"); } - return `runner://${encodeURIComponent(runner)}/${encodeURIComponent(workspace)}`; + return `runner://${encodeURIComponent(runner)}/${workspace === MANAGED_WORKSPACE ? workspace : encodeURIComponent(workspace)}`; } export const RUNNER_WIRE_VERSION = 1; From 3787dc7e9caea22c536c472e7d3d80298c47b69c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 08:47:28 -0700 Subject: [PATCH 032/642] Launch remote scratch or repository sessions from Create Agent --- apps/server/src/routes/runner-repositories.ts | 106 +++++++++++ apps/server/src/server.ts | 2 + .../components/app/create-agent-dialog.tsx | 89 ++++++---- apps/web/src/components/app/runner-picker.tsx | 5 +- .../app/runner-repository-fields.tsx | 166 ++++++++++++++++++ .../app/use-create-agent-form.test.tsx | 45 +++++ .../components/app/use-create-agent-form.ts | 124 +++++++++++-- apps/web/src/hooks/use-runners.ts | 4 +- 8 files changed, 490 insertions(+), 51 deletions(-) create mode 100644 apps/server/src/routes/runner-repositories.ts create mode 100644 apps/web/src/components/app/runner-repository-fields.tsx diff --git a/apps/server/src/routes/runner-repositories.ts b/apps/server/src/routes/runner-repositories.ts new file mode 100644 index 000000000..22d562860 --- /dev/null +++ b/apps/server/src/routes/runner-repositories.ts @@ -0,0 +1,106 @@ +import type { FastifyInstance } from "fastify"; +import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; + +/** Search with the service user's gh account. Only the repository address leaves the service. */ +export function registerRunnerRepositorySearch( + app: FastifyInstance, + run: CommandRunner = runCommand +) { + app.get<{ Querystring: { q?: string } }>( + "/api/v1/runners/repository-search", + async (req, reply) => { + const q = req.query.q; + if ( + typeof q !== "string" || + !/^[a-zA-Z0-9_.-][a-zA-Z0-9_./ -]{1,99}$/.test(q) + ) + return reply + .code(400) + .send({ error: "Enter a repository name or owner/name." }); + try { + const { stdout } = await run( + "gh", + [ + "search", + "repos", + "--match", + "name", + "--limit", + "12", + "--json", + "fullName,url", + "--", + q, + ], + { + timeoutMs: 8000, + env: { GH_PROMPT_DISABLED: "1" }, + } + ); + const rows: unknown = JSON.parse(stdout); + if (!Array.isArray(rows)) throw new Error("Invalid repository list"); + const repositories = rows.flatMap((row) => + typeof row?.fullName === "string" && + typeof row.url === "string" && + /^https:\/\//.test(row.url) + ? [{ name: row.fullName, url: row.url }] + : [] + ); + return { repositories }; + } catch { + return reply.code(503).send({ + error: "GitHub search is unavailable. Paste an HTTPS repository URL.", + }); + } + } + ); + app.get<{ Querystring: { url?: string } }>( + "/api/v1/runners/pull-request-head", + async (req, reply) => { + const match = + typeof req.query.url === "string" && + /^https:\/\/github\.com\/([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.-]+)\/pull\/([1-9][0-9]{0,9})\/?$/.exec( + req.query.url + ); + if (!match || [match[1], match[2]].some((v) => v === "." || v === "..")) + return reply + .code(400) + .send({ error: "Enter a GitHub pull request URL." }); + try { + // The pull ref in the base repo is read-only. Resolve the actual contributor branch. + const { stdout } = await run( + "gh", + [ + "api", + "--hostname", + "github.com", + `repos/${match[1]}/${match[2]}/pulls/${match[3]}`, + "--jq", + "{url:.head.repo.clone_url,branch:.head.ref}", + ], + { timeoutMs: 8000, env: { GH_PROMPT_DISABLED: "1" } } + ); + const head: unknown = JSON.parse(stdout); + if ( + !head || + typeof head !== "object" || + !("url" in head) || + !("branch" in head) || + typeof head.branch !== "string" || + !head.branch || + typeof head.url !== "string" || + !/^https:\/\/github\.com\/[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+(?:\.git)?$/.test( + head.url + ) + ) + throw new Error("Unavailable head"); + return { url: head.url, branch: head.branch }; + } catch { + return reply.code(422).send({ + error: + "Could not resolve the PR’s source branch. Check GitHub access or enter the source repository and branch.", + }); + } + } + ); +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1159cd6cc..7451e7249 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -126,6 +126,7 @@ import { registerMcpRoutes } from "./routes/mcp.js"; import { registerPersonaRoutes } from "./routes/personas.js"; import { registerPersonalityRoutes } from "./routes/personalities.js"; import { registerQuickPhraseRoutes } from "./routes/quick-phrases.js"; +import { registerRunnerRepositorySearch } from "./routes/runner-repositories.js"; import { registerRunnerRoutes } from "./routes/runners.js"; import { registerReleaseRoutes } from "./routes/release.js"; import { registerMacAppRoutes } from "./routes/mac-app.js"; @@ -1322,6 +1323,7 @@ async function registerRoutes() { // --- Quick Phrases --- await registerQuickPhraseRoutes(app, { pool }); + if (remoteRunner) registerRunnerRepositorySearch(app); await registerRunnerRoutes(app, { runners: remoteRunner }); } diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index 9877ab97b..d9fc41d39 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -1,3 +1,5 @@ +import { MANAGED_WORKSPACE } from "@dispatch/runner-protocol"; +import { RunnerRepositoryFields } from "./runner-repository-fields"; import { taskAgentName } from "@dispatch/shared"; import { ProjectLocation } from "./project-location"; import { useProjectScope, useProjects } from "@/hooks/use-projects"; @@ -150,43 +152,58 @@ function CreateAgentDialogContent({ />

- {task ? ( - - ) : ( -
- } +
+ + r.workspaces.includes(MANAGED_WORKSPACE) + ) + : form.runners + } + runnerId={form.runnerId} + unavailable={form.runnerUnavailable} + onRunnerChange={form.selectRunner} + workspace={form.runnerWorkspace} + onWorkspaceChange={form.setRunnerWorkspace} + /> + {form.managedSession && ( + - {form.runnerId ? null : ( - <> - { - form.setCreateProjectId(p?.id ?? null); - }} - > - - - - )} -
- )} + )} + {form.runnerId || task ? null : ( + <> + { + form.setCreateProjectId(p?.id ?? null); + }} + > + + + + )} +
{form.runnerId ? null : ( ) : null} - {selected && !unavailable ? ( + {selected && + !unavailable && + !selected.workspaces.includes(MANAGED_WORKSPACE) ? (
-

- {runner.workspaces.length > 0 - ? `Workspaces: ${runner.workspaces.join(", ")}` - : "No workspaces reported"} -

+ {runner.workspaces.length > 0 && + !runner.workspaces.includes(MANAGED_WORKSPACE) && ( +

+ Folders: {runner.workspaces.join(", ")} +

+ )} {runner.status !== "revoked" && (confirmId === runner.id ? ( From 78881f809dd210313d50a275067e2a97176945e6 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 08:52:51 -0700 Subject: [PATCH 038/642] Preserve configured runner workspaces and support authenticated GitHub checkouts --- apps/server/src/agents/archive.ts | 7 +- apps/server/src/agents/manager.ts | 41 ++++--- apps/server/src/agents/remote/registry.ts | 9 +- apps/server/src/agents/remote/runner.ts | 65 +++++----- apps/server/src/agents/remote/service.ts | 40 +++++-- .../src/agents/remote/session-storage.ts | 32 ++++- apps/server/src/agents/retention.ts | 1 + .../0056_managed_runner_sessions.sql | 4 + apps/server/src/routes/agents/crud-routes.ts | 17 ++- apps/server/src/routes/projects.ts | 12 ++ apps/server/test/agent-archive.test.ts | 1 + apps/server/test/agent-retention.test.ts | 16 +++ apps/server/test/agents-routes.test.ts | 85 +++++++++++++ apps/server/test/db/agent-manager.test.ts | 1 + apps/server/test/migrations.test.ts | 2 +- .../test/remote-runner-enrollment.test.ts | 48 ++++++++ .../server/test/remote-runner-startup.test.ts | 81 ++++++++++++- .../test/remote-session-storage.test.ts | 113 +++++++++++++++++- packages/runner-protocol/README.md | 6 +- packages/runner-protocol/src/index.ts | 1 + packages/shared/src/agent-record.ts | 2 + 21 files changed, 510 insertions(+), 74 deletions(-) diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index b3d4093f0..94594dd9f 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -11,7 +11,6 @@ import { getUnmergedChanges, } from "../shared/git/worktree-status.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; -import { MANAGED_WORKSPACE, remotePlacement } from "./remote/protocol.js"; import { AgentError } from "./errors.js"; import type { AgentRuntime } from "./runtime.js"; import type { @@ -265,8 +264,7 @@ export async function executeArchive( try { const agent = await deps.getRequiredAgent(id); const cleanupWorktree = agent.archiveCleanupMode ?? "auto"; - let runnerCleanupPending = - remotePlacement(agent.cwd)?.workspace === MANAGED_WORKSPACE; + let runnerCleanupPending = Boolean(agent.runnerManaged); // Phase: stopping — tear down session without changing agent status const t = Date.now(); @@ -403,8 +401,7 @@ export async function deleteAgentDirect( return []; } - let runnerCleanupPending = - remotePlacement(agent.cwd)?.workspace === MANAGED_WORKSPACE; + let runnerCleanupPending = Boolean(agent.runnerManaged); if (agent.status !== "stopped" || runnerCleanupPending) { const t = Date.now(); // Not stopAgent: it writes `stopping`/`stopped`, releasing the claim above diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 9ba88556b..e9ea0c7b9 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1371,7 +1371,9 @@ export class AgentManager { ): Promise { input = { ...input }; const placement = remotePlacement(input.cwd); - const managed = placement?.workspace === MANAGED_WORKSPACE; + const managed = placement + ? (this.remote?.isManagedWorkspace(placement) ?? false) + : false; const repository = (() => { if (input.repository === undefined) return undefined; if (!managed) @@ -1506,7 +1508,7 @@ export class AgentManager { 400 ); const p = await this.prepareCreateInputs(input); - await this.insertAgentRecord(p, input, runnerRepository); + await this.insertAgentRecord(p, input, runnerRepository, managed); const createdAgent = await this.getAgent(p.id); if (createdAgent) { @@ -1861,12 +1863,13 @@ export class AgentManager { private async insertAgentRecord( p: PreparedCreateInputs, input: CreateAgentInput, - repository: RunnerRepository | null + repository: RunnerRepository | null, + runnerManaged: boolean ): Promise { await this.pool.query( ` - INSERT INTO agents (id, name, type, role, status, cwd, launch_cwd, files_dir, agent_args, model, full_access, setup_phase, persona, parent_agent_id, launched_by_agent_id, persona_context, review_agent_type, cli_session_id, base_branch, template_id, project_id, effort, runner_repository, updated_at) - VALUES ($1, $2, $3, $4, 'creating', $5, $6, $7, $8::jsonb, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22::jsonb, NOW()) + INSERT INTO agents (id, name, type, role, status, cwd, launch_cwd, files_dir, agent_args, model, full_access, setup_phase, persona, parent_agent_id, launched_by_agent_id, persona_context, review_agent_type, cli_session_id, base_branch, template_id, project_id, effort, runner_repository, runner_managed, updated_at) + VALUES ($1, $2, $3, $4, 'creating', $5, $6, $7, $8::jsonb, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22::jsonb, $23, NOW()) `, [ p.id, @@ -1891,6 +1894,7 @@ export class AgentManager { input.projectId ?? null, p.effort, repository ? JSON.stringify(repository) : null, + runnerManaged, ] ); } @@ -2175,14 +2179,22 @@ export class AgentManager { const mcpUrl = placement ? remoteMcpOrigin && `${remoteMcpOrigin}/api/mcp/${agent.id}` : dispatchMcpUrl(this.config, agent.id, opts.jobRunId); - const repository = - placement?.workspace === MANAGED_WORKSPACE - ? (( - await this.pool.query<{ - runner_repository: RunnerRepository | null; - }>("SELECT runner_repository FROM agents WHERE id = $1", [agent.id]) - ).rows[0]?.runner_repository ?? undefined) - : undefined; + if ( + placement?.workspace === MANAGED_WORKSPACE && + this.remote?.available(placement) && + this.remote.isManagedWorkspace(placement) !== Boolean(agent.runnerManaged) + ) + throw new AgentError( + "The runner workspace mode changed since this agent was created.", + 409 + ); + const repository = agent.runnerManaged + ? (( + await this.pool.query<{ + runner_repository: RunnerRepository | null; + }>("SELECT runner_repository FROM agents WHERE id = $1", [agent.id]) + ).rows[0]?.runner_repository ?? undefined) + : undefined; return this.runtime.launch({ agentId: agent.id, repository, @@ -2484,7 +2496,7 @@ export class AgentManager { ); for (const { id, cwd } of rows) { const placement = remotePlacement(cwd); - if (!placement || !this.remote.available(placement)) continue; + if (!placement || !this.remote.isManagedWorkspace(placement)) continue; try { await this.runtime.stop(id, true); await this.streamRecorder.settleStopped(id); @@ -2634,6 +2646,7 @@ export class AgentManager { setup_phase AS "setupPhase", archive_phase AS "archivePhase", archive_cleanup_mode AS "archiveCleanupMode", + runner_managed AS "runnerManaged", last_error AS "lastError", ${ACTIVITY_SQL} AS activity, ${CURRENT_TURN_SQL} AS "currentTurn", diff --git a/apps/server/src/agents/remote/registry.ts b/apps/server/src/agents/remote/registry.ts index 17c073f6e..a4bb5a49b 100644 --- a/apps/server/src/agents/remote/registry.ts +++ b/apps/server/src/agents/remote/registry.ts @@ -23,6 +23,7 @@ export type Registration = { endpointHost: string; fingerprint: string | null; workspaces: string[]; + managedWorkspace: boolean; enrolled: boolean; revoked: boolean; codeExpiresAt: Date | null; @@ -36,6 +37,7 @@ type Row = { endpoint_host: string; cert_fingerprint: string | null; workspaces: string[]; + managed_workspace: boolean; enrolled_at: Date | null; revoked_at: Date | null; code_expires_at: Date | null; @@ -59,6 +61,7 @@ function registration(row: Row): Registration { endpointHost: row.endpoint_host, fingerprint: row.cert_fingerprint, workspaces: row.workspaces, + managedWorkspace: row.managed_workspace, enrolled: Boolean(row.enrolled_at), revoked: Boolean(row.revoked_at), codeExpiresAt: row.code_expires_at, @@ -286,12 +289,12 @@ export class RunnerRegistry { return rowCount ? { id, code, expiresAt } : undefined; } - async connected(id: string, workspaces: string[]) { + async connected(id: string, workspaces: string[], managedWorkspace = false) { await this.pool.query( `UPDATE runner_registrations - SET workspaces = $2::jsonb, last_seen_at = now() + SET workspaces = $2::jsonb, managed_workspace = $3, last_seen_at = now() WHERE id = $1 AND revoked_at IS NULL`, - [id, JSON.stringify(workspaces)] + [id, JSON.stringify(workspaces), managedWorkspace] ); } diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 4f8a42fb1..4b9305532 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -56,9 +56,24 @@ type RunnerConfig = { path: string; bins: HostLaunch["bins"]; adapter?: string[]; - workspaces: Record; + workspaces?: Record; }; +export const runnerGitArgs = [ + "-c", + "protocol.allow=never", + "-c", + "protocol.https.allow=always", + "-c", + "http.followRedirects=false", + "-c", + "credential.helper=", + "-c", + "credential.https://github.com.helper=!/usr/bin/gh auth git-credential", + "-c", + "core.hooksPath=/dev/null", +]; + const execute = promisify(execFile); const setpriv = "/usr/bin/setpriv"; @@ -148,12 +163,12 @@ export async function runRemoteRunner(filename: string) { "Runner requires an HTTPS endpoint and a separate, non-root execution account." ); } - if ( - Object.hasOwn(config.workspaces, MANAGED_WORKSPACE) || - !Object.keys(config.workspaces).every(isOpaqueId) - ) { + const workspaces = config.workspaces ?? {}; + const configuredHandles = Object.keys(workspaces); + if (!configuredHandles.every(isOpaqueId)) throw new Error("Runner workspace IDs must be valid opaque identifiers."); - } + const managedWorkspace = configuredHandles.length === 0; + const managedBinding = "\0managed"; const env = { HOME: config.home, PATH: config.path, @@ -189,27 +204,16 @@ export async function runRemoteRunner(filename: string) { await chmod(root, 0o711); } const asWorkload: WorkloadCommand = async (bin, args, opts) => { - const gitArgs = [ - "-c", - "protocol.allow=never", - "-c", - "protocol.https.allow=always", - "-c", - "http.followRedirects=false", - "-c", - "credential.helper=", - "-c", - "core.hooksPath=/dev/null", - ]; const { stdout } = await execute( setpriv, - [...childArgs, bin, ...(opts?.git ? gitArgs : []), ...args], + [...childArgs, bin, ...(opts?.git ? runnerGitArgs : []), ...args], { env: { ...env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0", + GH_PROMPT_DISABLED: "1", ...(config.trustBundle ? { GIT_SSL_CAINFO: config.trustBundle } : {}), }, timeout: opts?.git ? 90_000 : 20_000, @@ -295,7 +299,7 @@ export async function runRemoteRunner(filename: string) { "Remote service MCP requires HTTPS and a scoped token." ); } - const managed = workspace === MANAGED_WORKSPACE; + const managed = managedWorkspace && workspace === MANAGED_WORKSPACE; if (!managed && command.launch.repository !== undefined) throw new Error( "Repository checkout requires a managed runner session." @@ -304,9 +308,13 @@ export async function runRemoteRunner(filename: string) { throw new Error("This runner session has been archived."); const binding = path.join(bindings, key); - await writeFile(binding, workspace, { flag: "wx", mode: 0o600 }).catch( + const bindingValue = managed ? managedBinding : workspace; + await writeFile(binding, bindingValue, { flag: "wx", mode: 0o600 }).catch( async (error) => { - if (error.code !== "EEXIST" || (await readBinding(key)) !== workspace) + if ( + error.code !== "EEXIST" || + (await readBinding(key)) !== bindingValue + ) throw error; } ); @@ -469,10 +477,10 @@ export async function runRemoteRunner(filename: string) { if (socket.destroyed) return; const { agentId, workspace } = command; const target = - isOpaqueId(workspace) && Object.hasOwn(config.workspaces, workspace) - ? config.workspaces[workspace] + isOpaqueId(workspace) && Object.hasOwn(workspaces, workspace) + ? workspaces[workspace] : undefined; - const managed = workspace === MANAGED_WORKSPACE; + const managed = managedWorkspace && workspace === MANAGED_WORKSPACE; if (!isOpaqueId(agentId) || (!target && !managed)) throw new Error("Unknown runner workspace or agent"); const key = runnerStorageKey(agentId); @@ -484,7 +492,7 @@ export async function runRemoteRunner(filename: string) { return; } const binding = await readBinding(key); - if (binding !== workspace) { + if (binding !== (managed ? managedBinding : workspace)) { if (command.kind === "alive") return result(false); if (managed && binding === null && !active.has(agentId)) { if (command.kind === "stop") return result(true); @@ -634,7 +642,10 @@ export async function runRemoteRunner(filename: string) { type: "ready", version: RUNNER_WIRE_VERSION, health: true, - workspaces: [...Object.keys(config.workspaces), MANAGED_WORKSPACE], + workspaces: managedWorkspace + ? [MANAGED_WORKSPACE] + : configuredHandles, + ...(managedWorkspace ? { managedWorkspace: true } : {}), }); }); }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index a1364f6df..1f708a26d 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -74,6 +74,7 @@ export type RunnerSummary = { health?: RunnerHealth; healthReceivedAt?: string; workspaces: string[]; + managedWorkspace?: true; }; export class RunnerUnavailable extends Error {} @@ -100,7 +101,7 @@ type Gate = { registrationId?: string; approved(): boolean; allows(workspace: string): boolean; - ready?(workspaces: string[]): void; + ready?(workspaces: string[], managedWorkspace: boolean): void; }; type Settle = (frame?: Extract) => void; @@ -109,6 +110,7 @@ type Peer = { socket: TLSSocket; send: (frame: Frame) => void; workspaces: Set; + managedWorkspace: boolean; gate: Gate; health?: { sample: RunnerHealth; receivedAt: Date }; reportsHealth?: boolean; @@ -319,10 +321,7 @@ export class RemoteRunnerService { * requires its own per-workspace `repoTool`. */ repoToolFor(placement: Placement) { - if ( - placement.workspace === MANAGED_WORKSPACE || - !this.permitsAgentMcp(placement) - ) + if (this.isManagedWorkspace(placement) || !this.permitsAgentMcp(placement)) return false; if (this.legacy && placement.runner === this.legacy.id) return this.legacy.repoTool === true; @@ -568,9 +567,12 @@ export class RemoteRunnerService { registrationId: registration.id, approved: () => this.enrolled.get(fingerprint)?.id === registration.id, allows: () => true, - ready: (workspaces) => { + ready: (workspaces, managedWorkspace) => { registration.workspaces = workspaces; - void registry.connected(registration.id, workspaces).catch(() => {}); + registration.managedWorkspace = managedWorkspace; + void registry + .connected(registration.id, workspaces, managedWorkspace) + .catch(() => {}); }, }; } @@ -596,8 +598,11 @@ export class RemoteRunnerService { frame.type !== "ready" || frame.version !== 1 || !Array.isArray(frame.workspaces) || - frame.workspaces.length > - (frame.workspaces.includes(MANAGED_WORKSPACE) ? 257 : 256) || + frame.workspaces.length > 256 || + (frame.managedWorkspace !== undefined && + (frame.managedWorkspace !== true || + frame.workspaces.length !== 1 || + frame.workspaces[0] !== MANAGED_WORKSPACE)) || !frame.workspaces.every((workspace) => validWorkspaceId(workspace)) ) return socket.destroy(); @@ -607,6 +612,7 @@ export class RemoteRunnerService { reportsHealth: frame.health === true, send, workspaces: new Set(frame.workspaces), + managedWorkspace: frame.managedWorkspace === true, gate, pending: new Map(), channels: new Map(), @@ -615,7 +621,7 @@ export class RemoteRunnerService { const previous = this.peers.get(gate.key); this.peers.set(gate.key, peer); previous?.socket.destroy(); - gate.ready?.(frame.workspaces); + gate.ready?.(frame.workspaces, peer.managedWorkspace); if (peer.reportsHealth) send({ type: "accept_health" }); return; } @@ -805,6 +811,9 @@ export class RemoteRunnerService { this.legacy!.workspaces.includes(w) ) : [...this.legacy.workspaces], + ...(peer?.managedWorkspace && peer.gate.allows(MANAGED_WORKSPACE) + ? { managedWorkspace: true } + : {}), }); } if (!this.enrollment) return runners; @@ -836,6 +845,9 @@ export class RemoteRunnerService { } : {}), workspaces: online ? [...peer!.workspaces] : registration.workspaces, + ...((online ? peer!.managedWorkspace : registration.managedWorkspace) + ? { managedWorkspace: true } + : {}), }); } return runners; @@ -924,6 +936,14 @@ export class RemoteRunnerService { // Agent operations // --------------------------------------------------------------------------- + isManagedWorkspace(placement: Placement) { + return ( + placement.workspace === MANAGED_WORKSPACE && + this.peers.get(placement.runner)?.managedWorkspace === true && + this.available(placement) + ); + } + available(placement: Placement) { const peer = this.peers.get(placement.runner); return Boolean( diff --git a/apps/server/src/agents/remote/session-storage.ts b/apps/server/src/agents/remote/session-storage.ts index e7db723c0..6cd6281a3 100644 --- a/apps/server/src/agents/remote/session-storage.ts +++ b/apps/server/src/agents/remote/session-storage.ts @@ -181,13 +181,17 @@ export class RunnerRepositories { } if (!commit) throw new Error("The requested checkout branch was not found."); - if (local && local !== commit) - throw new Error( - "The runner branch has a different head; choose another branch." - ); + const needsFastForward = Boolean(local && local !== commit); + if (needsFastForward) { + await git("merge-base", "--is-ancestor", local!, commit).catch(() => { + throw new Error( + "The runner branch has local work; choose another branch." + ); + }); + } - // Git rejects a branch already held by another worktree. Never force - // this operation or reset a cached branch to a different commit. + // Git rejects a branch already held by another worktree. Only update + // the branch after Git has reserved it for this checkout. const args = local ? ["--", cwd, branch] : ["--no-track", "-b", branch, "--", cwd, commit]; @@ -196,6 +200,22 @@ export class RunnerRepositories { "Could not create the session checkout. The branch may already be occupied." ); }); + try { + if (needsFastForward) + await this.git("-C", cwd, "merge", "--ff-only", "--", commit); + if (checkout.kind !== "new" && remote) + await git( + "branch", + `--set-upstream-to=refs/remotes/origin/${branch}`, + "--", + branch + ); + } catch (error) { + await git("worktree", "remove", "--force", "--", cwd); + throw new Error("Could not update the runner session branch.", { + cause: error, + }); + } return cwd; }); } diff --git a/apps/server/src/agents/retention.ts b/apps/server/src/agents/retention.ts index 168b8aff8..7d0a2acf7 100644 --- a/apps/server/src/agents/retention.ts +++ b/apps/server/src/agents/retention.ts @@ -56,6 +56,7 @@ export async function purgeExpiredArchivedAgents( `SELECT id, files_dir FROM agents WHERE deleted_at IS NOT NULL + AND NOT runner_cleanup_pending AND deleted_at < now() - ($1::int * interval '1 day') ORDER BY deleted_at LIMIT $2`, diff --git a/apps/server/src/db/migrations/0056_managed_runner_sessions.sql b/apps/server/src/db/migrations/0056_managed_runner_sessions.sql index 1cd1f8a83..417104da9 100644 --- a/apps/server/src/db/migrations/0056_managed_runner_sessions.sql +++ b/apps/server/src/db/migrations/0056_managed_runner_sessions.sql @@ -1,6 +1,10 @@ ALTER TABLE agents + ADD COLUMN runner_managed boolean NOT NULL DEFAULT false, ADD COLUMN runner_repository jsonb, ADD COLUMN runner_cleanup_pending boolean NOT NULL DEFAULT false; CREATE INDEX agents_runner_cleanup_pending ON agents (id) WHERE runner_cleanup_pending AND deleted_at IS NOT NULL; + +ALTER TABLE runner_registrations + ADD COLUMN managed_workspace boolean NOT NULL DEFAULT false; diff --git a/apps/server/src/routes/agents/crud-routes.ts b/apps/server/src/routes/agents/crud-routes.ts index cc7afa87d..93e42fd88 100644 --- a/apps/server/src/routes/agents/crud-routes.ts +++ b/apps/server/src/routes/agents/crud-routes.ts @@ -220,6 +220,9 @@ export async function registerAgentCrudRoutes( (typeof body.projectId !== "string" || !body.projectId) ) return reply.code(400).send({ error: "Invalid project." }); + const managed = + typeof body.cwd === "string" && + remotePlacement(body.cwd)?.workspace === MANAGED_WORKSPACE; // Created for a task: briefed on it in its prompt, placed in its // project unless a location was chosen, and assigned once it exists. let taskBriefing: { projectId: string; text: string; name: string } | null = @@ -234,11 +237,17 @@ export async function registerAgentCrudRoutes( } catch (error) { return reply.code(400).send({ error: errorMessage(error) }); } - if (!body.projectId && !body.cwd) body.projectId = taskBriefing.projectId; + if ( + managed && + body.projectId && + body.projectId !== taskBriefing.projectId + ) + return reply + .code(400) + .send({ error: "Choose the task’s project for its runner session." }); + if (!body.projectId && (managed || !body.cwd)) + body.projectId = taskBriefing.projectId; } - const managed = - typeof body.cwd === "string" && - remotePlacement(body.cwd)?.workspace === MANAGED_WORKSPACE; if (body.projectId && body.cwd && !managed) return reply .code(400) diff --git a/apps/server/src/routes/projects.ts b/apps/server/src/routes/projects.ts index ac6476b28..71cb95653 100644 --- a/apps/server/src/routes/projects.ts +++ b/apps/server/src/routes/projects.ts @@ -5,6 +5,7 @@ import path from "node:path"; import type { FastifyInstance } from "fastify"; import type { Pool } from "pg"; import * as z from "zod/v4"; +import { inferRepositoryUrl } from "../agents/remote/repository.js"; import { ProjectStore } from "../projects/store.js"; import { parseInput } from "../shared/lib/parse-input.js"; import { resolveTilde } from "../shared/lib/resolve-tilde.js"; @@ -78,6 +79,17 @@ export async function registerProjectRoutes( ); }; app.get("/api/v1/projects", () => store.list()); + app.get<{ Params: { id: string } }>( + "/api/v1/projects/:id/repository", + async (request, reply) => { + const project = await store.get(request.params.id); + if (!project) + return reply.code(404).send({ error: "Project not found." }); + return { + url: await inferRepositoryUrl(project.repoRoot).catch(() => null), + }; + } + ); app.get<{ Querystring: { repoRoot?: string; projectId?: string } }>( "/api/v1/projects/icon-preview", async (request, reply) => { diff --git a/apps/server/test/agent-archive.test.ts b/apps/server/test/agent-archive.test.ts index 8344320ae..1dd97e4d1 100644 --- a/apps/server/test/agent-archive.test.ts +++ b/apps/server/test/agent-archive.test.ts @@ -1294,6 +1294,7 @@ it("archives an offline managed session with pending cleanup recorded in the sam getRequiredAgent: vi.fn().mockResolvedValue( makeAgent("remote", { cwd: "runner://runner/@session", + runnerManaged: true, status: "archiving", }) ), diff --git a/apps/server/test/agent-retention.test.ts b/apps/server/test/agent-retention.test.ts index 6d6127f5a..eb3adfaf4 100644 --- a/apps/server/test/agent-retention.test.ts +++ b/apps/server/test/agent-retention.test.ts @@ -124,6 +124,22 @@ describe("purgeExpiredArchivedAgents", () => { expect(await count("blocks", "stream_id", "live")).toBe(1); }); + it("holds archived rows while their runner cleanup is pending", async () => { + await seedAgent("offline", { archivedDaysAgo: 40 }); + await pool.query( + "UPDATE agents SET runner_cleanup_pending = true WHERE id = 'offline'" + ); + expect( + await purgeExpiredArchivedAgents({ pool, logger, filesRoot }) + ).toEqual([]); + await pool.query( + "UPDATE agents SET runner_cleanup_pending = false WHERE id = 'offline'" + ); + expect( + await purgeExpiredArchivedAgents({ pool, logger, filesRoot }) + ).toEqual(["offline"]); + }); + it("purges a child home while retaining its parent's conversation and legacy child history", async () => { await seedAgent("parent"); await seedAgent("expired-child", { archivedDaysAgo: 40, parent: "parent" }); diff --git a/apps/server/test/agents-routes.test.ts b/apps/server/test/agents-routes.test.ts index c25887731..d9275bf8a 100644 --- a/apps/server/test/agents-routes.test.ts +++ b/apps/server/test/agents-routes.test.ts @@ -1,3 +1,4 @@ +import { execFileSync } from "node:child_process"; import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -779,6 +780,90 @@ describe("agent permissions API", () => { }); }); +it("provides a credential-free project repository origin and null for a plain folder", async () => { + const root = await mkdtemp( + path.join(os.tmpdir(), "dispatch-project-origin-") + ); + try { + const { ProjectStore } = await import("../src/projects/store.js"); + const projects = new ProjectStore(ctx.pool); + const plain = path.join(root, "plain"); + const repo = path.join(root, "repo"); + await mkdir(plain); + execFileSync("git", ["init", repo]); + execFileSync("git", [ + "-C", + repo, + "remote", + "add", + "origin", + "https://fixture:secret@example.test/repo.git", + ]); + for (const [repoRoot, url] of [ + [plain, null], + [repo, "https://example.test/repo.git"], + ] as const) { + const project = await projects.create({ + name: "Origin", + repoRoot, + color: "#123456", + }); + const response = await authedInject( + "GET", + `/api/v1/projects/${project.id}/repository` + ); + expect(response.statusCode).toBe(200); + expect(response.json()).toEqual({ url }); + await projects.delete(project.id); + } + expect( + (await authedInject("GET", "/api/v1/projects/missing/repository")) + .statusCode + ).toBe(404); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +it("accepts a same-project task runner locator and rejects cross-project input", async () => { + const { ProjectStore } = await import("../src/projects/store.js"); + const projects = new ProjectStore(ctx.pool); + const project = await projects.create({ + name: "Task launch", + repoRoot: "/tmp", + color: "#123456", + }); + try { + const created = await authedInject("POST", "/api/v1/tasks", { + projectId: project.id, + title: "Try runner", + }); + expect(created.statusCode).toBe(200); + const base = { + taskId: created.json().id, + cwd: "runner://offline/@session", + }; + for (const projectId of [undefined, project.id]) { + const response = await authedInject("POST", "/api/v1/agents", { + ...base, + projectId, + }); + expect(response.statusCode).toBe(409); + expect(response.json().error).toContain( + "runner workspace is unavailable" + ); + } + const mismatched = await authedInject("POST", "/api/v1/agents", { + ...base, + projectId: "other", + }); + expect(mismatched.statusCode).toBe(400); + expect(mismatched.json().error).toContain("task’s project"); + } finally { + await projects.delete(project.id); + } +}); + describe("task agent names", () => { it.each([undefined, "", " ", "My chosen name"])( "uses the task title unless name %j is explicit", diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index 0a691f85b..443d85bd3 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -246,6 +246,7 @@ describe("AgentManager", () => { const available = vi.fn(() => true); const remote = { available, + isManagedWorkspace: available, originFor: () => "https://example.test", } as unknown as RemoteRunnerService; const first = new AgentManager(pool, noopLogger, testConfig, { diff --git a/apps/server/test/migrations.test.ts b/apps/server/test/migrations.test.ts index e7cde17d1..e4d1efff5 100644 --- a/apps/server/test/migrations.test.ts +++ b/apps/server/test/migrations.test.ts @@ -76,7 +76,7 @@ describe("block_reactions uniqueness migration", () => { /** Rewinds task migrations, which depend on projects and agents, so older eras can replay. */ async function dropTasks(): Promise { await pool.query( - "ALTER TABLE agents DROP COLUMN IF EXISTS runner_repository, DROP COLUMN IF EXISTS runner_cleanup_pending" + "ALTER TABLE agents DROP COLUMN IF EXISTS runner_managed, DROP COLUMN IF EXISTS runner_repository, DROP COLUMN IF EXISTS runner_cleanup_pending" ); await pool.query( "DELETE FROM pgmigrations WHERE name = '0056_managed_runner_sessions'" diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index fe4aa9fc8..b44d5ebc4 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -52,6 +52,7 @@ function dialRunner(input: { workspaces: string[]; answer?: boolean; health?: Extract["sample"]; + managedWorkspace?: true; }): Promise { const url = new URL(input.endpoint); return new Promise((resolve, reject) => { @@ -79,6 +80,7 @@ function dialRunner(input: { version: 1, workspaces: input.workspaces, ...(input.health ? { health: true as const } : {}), + managedWorkspace: input.managedWorkspace, }); resolve({ socket, closed, requests }); }); @@ -523,6 +525,52 @@ describe("runner enrollment service", () => { ); }); + it("distinguishes a configured @session handle from managed mode and retains the mode offline", async () => { + const service = makeService(); + const a = await enroll(service, "alpha"); + const placement = { runner: a.id, workspace: "@session" }; + const connectSession = async (managedWorkspace?: true) => { + const session = await dialRunner({ + endpoint: a.endpoint, + ca: a.ca, + cert: a.cert, + key: a.key, + label: "alpha", + workspaces: ["@session"], + managedWorkspace, + }); + runners.push(session); + return session; + }; + await connectSession(); + await waitFor(() => service.available(placement)); + expect(service.isManagedWorkspace(placement)).toBe(false); + expect((await service.list())[0]).not.toHaveProperty("managedWorkspace"); + + const managed = await connectSession(true); + await waitFor(() => service.isManagedWorkspace(placement)); + expect((await service.list())[0]).toMatchObject({ + workspaces: ["@session"], + managedWorkspace: true, + }); + await waitFor( + async () => + ( + await pool.query( + "SELECT managed_workspace FROM runner_registrations WHERE id = $1", + [a.id] + ) + ).rows[0]?.managed_workspace === true + ); + managed.socket.destroy(); + await waitFor(() => !service.available(placement)); + expect((await service.list())[0]).toMatchObject({ + status: "offline", + workspaces: ["@session"], + managedWorkspace: true, + }); + }); + it("persists the CA, port and registrations across a service restart", async () => { const first = makeService(); const a = await enroll(first, "alpha"); diff --git a/apps/server/test/remote-runner-startup.test.ts b/apps/server/test/remote-runner-startup.test.ts index de659c1a7..1175bdaeb 100644 --- a/apps/server/test/remote-runner-startup.test.ts +++ b/apps/server/test/remote-runner-startup.test.ts @@ -1,4 +1,12 @@ -import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"; +import { EventEmitter } from "node:events"; +import { + mkdir, + mkdtemp, + readFile, + rm, + stat, + writeFile, +} from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -138,6 +146,77 @@ describe("remote runner startup", () => { await expect(stat(state)).rejects.toMatchObject({ code: "ENOENT" }); }); + it.each([ + { workspaces: undefined, handles: ["@session"], managed: true }, + { workspaces: {}, handles: ["@session"], managed: true }, + { + workspaces: { proof: { cwd: "/fixture" } }, + handles: ["proof"], + managed: false, + }, + { + workspaces: { "@session": { cwd: "/fixture" } }, + handles: ["@session"], + managed: false, + }, + ])( + "advertises only the configured workspace mode: $workspaces", + async ({ workspaces, handles, managed }) => { + const input = JSON.parse(await readFile(config, "utf8")); + await writeFile(config, JSON.stringify({ ...input, workspaces })); + reportIdentity.mockImplementation((_command, _args, _options, callback) => + callback(null, unprivilegedStatus, "") + ); + const socket = Object.assign(new EventEmitter(), { + write: vi.fn(), + destroy: vi.fn(), + writableLength: 0, + destroyed: false, + }); + const end = new Error("end simulated runner after reconnect"); + dial.mockReturnValueOnce(socket).mockImplementation(() => { + throw end; + }); + vi.useFakeTimers(); + const running = runRemoteRunner(config).catch((error) => error); + try { + await vi.waitFor(() => expect(dial).toHaveBeenCalledTimes(1)); + socket.emit("secureConnect"); + expect(JSON.parse(socket.write.mock.calls[0]![0])).toEqual({ + type: "ready", + version: 1, + workspaces: handles, + ...(managed ? { managedWorkspace: true } : {}), + }); + socket.emit( + "data", + Buffer.from( + JSON.stringify({ + type: "request", + id: "discard-test", + command: { + kind: "discard", + agentId: "fixture", + workspace: "@session", + }, + }) + "\n" + ) + ); + await vi.waitFor(() => expect(socket.write).toHaveBeenCalledTimes(2)); + expect(JSON.parse(socket.write.mock.calls[1]![0])).toMatchObject({ + type: "result", + id: "discard-test", + ...(managed ? { value: true } : { error: expect.any(String) }), + }); + } finally { + socket.emit("close"); + await vi.advanceTimersByTimeAsync(1000); + await expect(running).resolves.toBe(end); + vi.useRealTimers(); + } + } + ); + it("leaves the host parent traversable and keeps enrollment state private", async () => { // A retained host directory created with umask 0077 has mode 0700. await mkdir(path.join(state, "hosts"), { recursive: true, mode: 0o700 }); diff --git a/apps/server/test/remote-session-storage.test.ts b/apps/server/test/remote-session-storage.test.ts index 80187f874..05daf1d02 100644 --- a/apps/server/test/remote-session-storage.test.ts +++ b/apps/server/test/remote-session-storage.test.ts @@ -1,3 +1,5 @@ +import { spawn } from "node:child_process"; +import { runnerGitArgs } from "../src/agents/remote/runner.js"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { @@ -208,6 +210,43 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e ).trim() ).toBe(topic); await repositories.remove(c, pr); + await git("-C", origin, "switch", "topic"); + const updatedTopic = await commit("updated PR head"); + await git("-C", origin, "update-ref", "refs/pull/1/head", updatedTopic); + await git("-C", origin, "switch", "main"); + const updated = await repositories.prepare(c, pr); + expect((await git("-C", updated, "rev-parse", "HEAD")).trim()).toBe( + updatedTopic + ); + expect( + ( + await git("-C", updated, "rev-parse", "--abbrev-ref", "@{upstream}") + ).trim() + ).toBe("origin/topic"); + await git( + "-C", + updated, + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.test", + "commit", + "--allow-empty", + "-m", + "local-only work" + ); + const localHead = (await git("-C", updated, "rev-parse", "HEAD")).trim(); + await repositories.remove(c, pr); + await git("-C", origin, "switch", "topic"); + const divergent = await commit("different remote work"); + await git("-C", origin, "switch", "main"); + await expect(repositories.prepare(c, existing)).rejects.toThrow( + "has local work" + ); + expect( + (await git("-C", first, "rev-parse", "refs/heads/topic")).trim() + ).toBe(localHead); + await expect( repositories.prepare(c, spec({ kind: "pr", branch: "topic", number: 2 })) ).rejects.toThrow("does not match"); @@ -225,8 +264,80 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e "HEAD" ) ).trim() - ).toBe(topic); + ).toBe(divergent); } finally { await rm(root, { force: true, recursive: true }); } }); + +it("uses only the runner GitHub helper for a private repository credential request", async () => { + const root = await mkdtemp( + path.join(os.tmpdir(), "dispatch-runner-credential-") + ); + try { + const gh = path.join(root, "gh"); + const calls = path.join(root, "calls"); + const global = path.join(root, "gitconfig"); + await writeFile( + gh, + '#!/bin/sh\nprintf \'%s\\n\' "$*" > "$FIXTURE_CALLS"\ncat >> "$FIXTURE_CALLS"\nprintf \'username=fixture\\npassword=synthetic-token\\n\'\n', + { mode: 0o700 } + ); + await writeFile( + global, + "[credential]\n helper = !echo unsafe-helper >&2\n" + ); + const args = runnerGitArgs.map((arg) => arg.replace("/usr/bin/gh", gh)); + const credential = (host: string) => + new Promise<{ status: number | null; out: string; err: string }>( + (resolve, reject) => { + const child = spawn( + "git", + [ + "-C", + root, + ...args, + "-c", + "credential.useHttpPath=true", + "credential", + "fill", + ], + { + env: { + PATH: process.env.PATH, + HOME: root, + GIT_CONFIG_GLOBAL: global, + GIT_CONFIG_NOSYSTEM: "1", + GIT_TERMINAL_PROMPT: "0", + FIXTURE_CALLS: calls, + }, + } + ); + let out = "", + err = ""; + child.stdout.on("data", (chunk) => (out += chunk)); + child.stderr.on("data", (chunk) => (err += chunk)); + child.once("error", reject); + child.once("close", (status) => resolve({ status, out, err })); + child.stdin.end( + `protocol=https\nhost=${host}\npath=fixture/managed-private.git\n\n` + ); + } + ); + expect(await credential("github.com")).toMatchObject({ + status: 0, + out: expect.stringContaining("password=synthetic-token"), + err: "", + }); + expect(await readFile(calls, "utf8")).toContain( + "path=fixture/managed-private.git" + ); + await rm(calls); + const rejected = await credential("example.test"); + expect(rejected.status).not.toBe(0); + expect(rejected.err).not.toContain("unsafe-helper"); + await expect(readFile(calls)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index ad9641535..fbe90a90a 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -32,10 +32,12 @@ existing host. Use unique request IDs within each connection. These IDs provide correlation only. The guest resolves the working directory, executable and environment. -A runner that advertises the reserved workspace `@session` provides private +A runner that advertises `managedWorkspace: true` with the reserved workspace +`@session` provides private storage for each agent ID. Launch uses an empty scratch directory by default. The optional `repository` launch field selects a credential-free HTTPS Git URL -and a checkout instead: +and a checkout instead. A runner with `/usr/bin/gh` can use credentials from the +workload account’s GitHub login for `https://github.com`: - `{ kind: "new", branch, base? }` creates a branch from the named or default remote branch. diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index c303a5253..b40e274cd 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -88,6 +88,7 @@ export type Frame = version: typeof RUNNER_WIRE_VERSION; workspaces: string[]; health?: true; + managedWorkspace?: true; } | { type: "accept_health" } | { type: "health"; sample: RunnerHealth } diff --git a/packages/shared/src/agent-record.ts b/packages/shared/src/agent-record.ts index a15280729..af9858dce 100644 --- a/packages/shared/src/agent-record.ts +++ b/packages/shared/src/agent-record.ts @@ -71,6 +71,8 @@ export type AgentRecord = { cwd: string; /** Directory requested at creation, before any managed worktree changed cwd. */ launchCwd?: string | null; + /** Whether the runner owns an isolated session for this agent. */ + runnerManaged?: boolean; worktreePath: string | null; worktreeBranch: string | null; /** From 87534218db5613174225712f4f703b1ff19f6cfa Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 08:53:24 -0700 Subject: [PATCH 039/642] Add runner-scoped engine management: protocol, manager, executor, UI Introduces the portable wire types for engine install/update/sign-in (packages/runner-protocol/src/engine-management.ts), a scope-aware EngineManager that reuses the existing EngineLogins/EngineUpdateOperations for local engines and forwards to an injected transport for runner workspaces, and an EngineRunnerExecutor that runs those operations under a runner's non-root workload account (setpriv-wrapped, managed install paths only, reusing EngineLogins/loginScript for sign-in including staged Codex credentials). Adds a self-contained RunnerEngines component + hook on the web side. No changes to local agent execution behavior; service.ts, runner.ts, routes and health-publisher wiring are left for integration. Co-Authored-By: Claude Sonnet 5 --- .../src/agents/remote/engine-manager.ts | 246 +++++++++++++ .../agents/remote/engine-runner-executor.ts | 307 +++++++++++++++++ apps/server/test/engine-manager.test.ts | 285 +++++++++++++++ .../test/engine-runner-executor.test.ts | 172 +++++++++ .../runner-engines/runner-engines.test.tsx | 134 ++++++++ .../runner-engines/runner-engines.tsx | 325 ++++++++++++++++++ apps/web/src/hooks/use-runner-engines.ts | 74 ++++ packages/runner-protocol/package.json | 3 +- .../runner-protocol/src/engine-management.ts | 117 +++++++ 9 files changed, 1662 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/agents/remote/engine-manager.ts create mode 100644 apps/server/src/agents/remote/engine-runner-executor.ts create mode 100644 apps/server/test/engine-manager.test.ts create mode 100644 apps/server/test/engine-runner-executor.test.ts create mode 100644 apps/web/src/components/runner-engines/runner-engines.test.tsx create mode 100644 apps/web/src/components/runner-engines/runner-engines.tsx create mode 100644 apps/web/src/hooks/use-runner-engines.ts create mode 100644 packages/runner-protocol/src/engine-management.ts diff --git a/apps/server/src/agents/remote/engine-manager.ts b/apps/server/src/agents/remote/engine-manager.ts new file mode 100644 index 000000000..7e50d740a --- /dev/null +++ b/apps/server/src/agents/remote/engine-manager.ts @@ -0,0 +1,246 @@ +import { EventEmitter } from "node:events"; + +import type { RunnerEngine } from "@dispatch/runner-protocol"; +import { + RUNNER_ENGINES, + engineScopeKey, + type EngineInventoryEntry, + type EngineOperation, + type EngineOperationAck, + type EngineOperationEvent, + type EngineScope, + type EngineSupportedAction, +} from "@dispatch/runner-protocol/engine-management"; + +import type { AcpEngineId } from "../acp/engine-spec.js"; +import { + engineStatuses, + withEngineVersions, + type EngineStatus, +} from "../engine-availability.js"; +import { withEngineUpdates } from "../engine-updates.js"; +import type { EngineLogins } from "../engine-login.js"; +import type { EngineUpdateOperations } from "../engine-updates.js"; + +/** + * One place to read engine status and run install/update/sign-in, whether + * the engine runs on this machine or on a named runner workspace. Local + * scope wraps the existing `EngineLogins`/`EngineUpdateOperations` + * untouched — this adds a scope-aware read model and dispatch on top, it + * never changes what those run or how. Remote scope forwards to whatever + * transport the caller supplies; this class has no socket of its own. + */ + +export type { EngineScope }; + +/** What a runner's connection exposes for engine management; supplied by the caller. */ +export interface RunnerEngineTransport { + /** + * Send one operation to the named runner workspace. `onEvent` receives + * any progress frames the runner streams before its ack. Reject (or + * resolve `{ ok: false, unsupported: true }`) for an offline runner or + * one that predates engine management. + */ + send( + runnerId: string, + workspace: string, + operation: EngineOperation, + onEvent?: (event: EngineOperationEvent) => void + ): Promise; +} + +export type LocalEngineDeps = { + logins: EngineLogins; + updates: EngineUpdateOperations; + overrides?: Partial>; +}; + +const LABELS: Record = { + claude: "Claude Code", + codex: "Codex", + opencode: "OpenCode", +}; + +export type EngineManagerChangeListener = ( + entries: EngineInventoryEntry[] +) => void; + +export class EngineManager { + private readonly events = new EventEmitter(); + + constructor( + private readonly deps: { + local: LocalEngineDeps; + remote: RunnerEngineTransport; + } + ) {} + + /** Subscribe to inventory changes for one scope; call the returned function to stop. */ + onChanged( + scope: EngineScope, + listener: EngineManagerChangeListener + ): () => void { + const key = engineScopeKey(scope); + this.events.on(key, listener); + return () => this.events.off(key, listener); + } + + private emitChanged( + scope: EngineScope, + entries: EngineInventoryEntry[] + ): void { + this.events.emit(engineScopeKey(scope), entries); + } + + async inventory(scope: EngineScope): Promise { + const entries = + scope.kind === "local" + ? await this.localInventory() + : await this.remoteInventory(scope); + this.emitChanged(scope, entries); + return entries; + } + + async rpc( + scope: EngineScope, + operation: EngineOperation, + onEvent?: (event: EngineOperationEvent) => void + ): Promise { + const ack = + scope.kind === "local" + ? await this.localRpc(operation) + : await this.deps.remote.send( + scope.runnerId, + scope.workspace, + operation, + onEvent + ); + // Refresh before returning, so a caller that awaits `rpc` sees the + // change notification fire no later than its own result. + if (operation.type !== "status") + await this.inventory(scope).catch(() => {}); + return ack; + } + + private async localInventory(): Promise { + const { logins, overrides } = this.deps.local; + const statuses = await withEngineUpdates( + await withEngineVersions(await engineStatuses(overrides)) + ); + return Promise.all( + statuses.map(async (status) => { + let signedIn: boolean | null = null; + let detail: string | undefined; + if (status.installed && isLoginSupported(status.id)) { + const auth = await logins.status(status.id); + signedIn = auth.signedIn; + detail = auth.detail; + } + const actions: EngineSupportedAction[] = []; + // Local install is always manual (see missingEngineMessage); this + // view never offers an automatic install, matching current behavior. + if (status.installed && status.update.canUpdate) actions.push("update"); + if (status.installed && isLoginSupported(status.id)) + actions.push("login", "login_cancel"); + return { + id: status.id, + label: LABELS[status.id], + installed: status.installed, + signedIn, + version: status.version, + ...(detail ? { detail } : {}), + actions, + }; + }) + ); + } + + private async remoteInventory( + scope: Extract + ): Promise { + let result: EngineInventoryEntry[] = []; + const ack = await this.deps.remote.send( + scope.runnerId, + scope.workspace, + { type: "status" }, + (event) => { + if (event.type === "inventory") result = event.entries; + } + ); + if (!ack.ok) { + // Unsupported or offline: report every engine as unknown rather than + // throwing, so the UI can show "unavailable" instead of an error page. + return RUNNER_ENGINES.map((id) => ({ + id, + label: LABELS[id], + installed: false, + signedIn: null, + version: null, + actions: [], + })); + } + return result; + } + + private async localRpc( + operation: EngineOperation + ): Promise { + const { logins, updates, overrides } = this.deps.local; + switch (operation.type) { + case "status": + return { ok: true }; + case "install": + return { + ok: false, + error: `${LABELS[operation.engine]} is installed manually on this machine; there is no automatic install here.`, + unsupported: true, + }; + case "update": { + if (!isAcpEngine(operation.engine)) { + return { + ok: false, + error: `${LABELS[operation.engine]} has no update path.`, + }; + } + try { + const op = await updates.start(operation.engine, overrides ?? {}); + return { ok: true, operationId: op.id }; + } catch (error) { + return { ok: false, error: (error as Error).message }; + } + } + case "login_start": { + if (!isLoginSupported(operation.engine)) { + return { + ok: false, + error: `${LABELS[operation.engine]} has no sign-in flow.`, + }; + } + const login = await logins.start(operation.engine, { + restart: operation.restart, + }); + return { ok: true, login }; + } + case "login_submit": { + const login = logins.submitCode(operation.loginId, operation.code); + if (!login) return { ok: false, error: "Sign-in not found." }; + return { ok: true, login }; + } + case "login_cancel": { + const login = logins.cancel(operation.loginId); + if (!login) return { ok: false, error: "Sign-in not found." }; + return { ok: true, login }; + } + } + } +} + +function isAcpEngine(engine: RunnerEngine): engine is AcpEngineId { + return engine === "claude" || engine === "codex" || engine === "opencode"; +} + +function isLoginSupported(engine: RunnerEngine): engine is "claude" | "codex" { + return engine === "claude" || engine === "codex"; +} + +export type { EngineStatus }; diff --git a/apps/server/src/agents/remote/engine-runner-executor.ts b/apps/server/src/agents/remote/engine-runner-executor.ts new file mode 100644 index 000000000..826aef534 --- /dev/null +++ b/apps/server/src/agents/remote/engine-runner-executor.ts @@ -0,0 +1,307 @@ +import { spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; + +import type { RunnerEngine } from "@dispatch/runner-protocol"; +import { + RUNNER_ENGINES, + type EngineInventoryEntry, + type EngineLoginView, + type EngineOperation, + type EngineOperationAck, + type EngineOperationEvent, + type EngineSupportedAction, +} from "@dispatch/runner-protocol/engine-management"; + +import { compareVersions } from "../engine-availability.js"; +import { EngineLogins, isLoginEngine, loginScript } from "../engine-login.js"; + +/** + * Runs engine install/update/sign-in on a runner's non-root workload + * account. Self-contained: `runner.ts` constructs this from its own + * `RunnerConfig` and calls `handle()` for the `"engine"` command kind — this + * module never reads `runner.json` or touches the wire transport itself. + * + * Every spawned process goes through the same `setpriv` privilege drop the + * guest ACP host and repo tool already use, so an engine's CLI always runs + * as the workload identity, never as this (root) process. + */ + +const LABELS: Record = { + claude: "Claude Code", + codex: "Codex", + opencode: "OpenCode", +}; + +export type ManagedCommand = { + executable: string; + args: string[]; + env?: NodeJS.ProcessEnv; +}; + +/** + * One engine's configuration on this runner: its enforced launch path (the + * same absolute path the ACP host launches, or null when not installed), + * and the operator-approved commands that install or update whatever lives + * at that path. Omitting `install`/`update` disables that action — there is + * no ambiguous ownership detection here, only configured, scoped commands. + */ +export type RunnerEngineConfig = { + bin: string | null; + install?: ManagedCommand; + update?: ManagedCommand; +}; + +export type EngineRunnerExecutorConfig = { + uid: number; + gid: number; + /** Merged into every spawned process's environment (HOME, PATH, CA, …). */ + env: NodeJS.ProcessEnv; + engines: Partial>; + /** + * Test seam: how a command is wrapped to run as the workload identity. + * Defaults to the same `setpriv` drop the guest ACP host and repo tool + * use. Never overridden outside tests — production always drops privileges. + */ + wrap?: (bin: string, args: string[]) => { bin: string; args: string[] }; +}; + +function setprivWrap( + uid: number, + gid: number +): (bin: string, args: string[]) => { bin: string; args: string[] } { + const privArgs = [ + `--reuid=${uid}`, + `--regid=${gid}`, + "--clear-groups", + "--no-new-privs", + "--inh-caps=-all", + "--ambient-caps=-all", + "--bounding-set=-all", + "--", + ]; + return (bin, args) => ({ + bin: "/usr/bin/setpriv", + args: [...privArgs, bin, ...args], + }); +} + +type RunResult = { code: number | null }; + +export class EngineRunnerExecutor { + private readonly logins: EngineLogins; + private readonly wrap: NonNullable; + + constructor(private readonly config: EngineRunnerExecutorConfig) { + this.wrap = config.wrap ?? setprivWrap(config.uid, config.gid); + this.logins = new EngineLogins({ + resolveBin: async (engine) => config.engines[engine]?.bin ?? null, + // loginScript's own argv already starts with "/bin/sh"; wrap that + // whole command behind the same privilege drop every runner exec uses. + command: (bin, args, opts) => { + const [shBin, ...shArgs] = loginScript(bin, args, opts); + return this.wrap(shBin!, shArgs); + }, + env: config.env, + }); + } + + private run( + executable: string, + args: string[], + env: NodeJS.ProcessEnv, + timeoutMs: number, + onChunk?: (chunk: string) => void + ): Promise { + return new Promise((resolve) => { + const command = this.wrap(executable, args); + const child = spawn(command.bin, command.args, { + env, + stdio: ["ignore", "pipe", "pipe"], + }); + const timer = setTimeout(() => { + try { + child.kill("SIGKILL"); + } catch { + /* already gone */ + } + }, timeoutMs); + const read = (chunk: Buffer) => onChunk?.(chunk.toString("utf8")); + child.stdout?.on("data", read); + child.stderr?.on("data", read); + child.on("close", (code) => { + clearTimeout(timer); + resolve({ code }); + }); + child.on("error", () => { + clearTimeout(timer); + resolve({ code: null }); + }); + }); + } + + private async readVersion(bin: string): Promise { + let output = ""; + const { code } = await this.run( + bin, + ["--version"], + this.config.env, + 5_000, + (chunk) => { + output = (output + chunk).slice(-2_000); + } + ); + if (code !== 0) return null; + const line = output.trim().split("\n")[0]?.trim() ?? ""; + if (!line) return null; + return /\d+\.\d+(?:\.\d+)?[\w.+-]*/.exec(line)?.[0] ?? line; + } + + /** The scope-aware engine list and supported actions, for a snapshot view. */ + async inventory(): Promise { + return Promise.all( + RUNNER_ENGINES.map(async (engine) => { + const cfg = this.config.engines[engine]; + const bin = cfg?.bin ?? null; + const installed = Boolean(bin); + const version = installed ? await this.readVersion(bin!) : null; + let signedIn: boolean | null = null; + let detail: string | undefined; + if (installed && isLoginEngine(engine)) { + const status = await this.logins.status(engine); + signedIn = status.signedIn; + detail = status.detail; + } + const actions: EngineSupportedAction[] = []; + if (!installed && cfg?.install) actions.push("install"); + if (installed && cfg?.update) actions.push("update"); + if (installed && isLoginEngine(engine)) + actions.push("login", "login_cancel"); + return { + id: engine, + label: LABELS[engine], + installed, + signedIn, + version, + ...(detail ? { detail } : {}), + actions, + }; + }) + ); + } + + /** Run one operation; `onEvent` receives any progress before the ack returns. */ + async handle( + operation: EngineOperation, + onEvent?: (event: EngineOperationEvent) => void + ): Promise { + switch (operation.type) { + case "status": + return { ok: true }; + case "install": + return this.runManaged(operation.engine, "install", onEvent); + case "update": + return this.runManaged(operation.engine, "update", onEvent); + case "login_start": { + if (!isLoginEngine(operation.engine)) { + return { + ok: false, + error: `${LABELS[operation.engine]} has no sign-in flow.`, + }; + } + const login = await this.logins.start(operation.engine, { + restart: operation.restart, + }); + const view = toLoginView(login); + onEvent?.({ type: "login_update", login: view }); + return { ok: true, login: view }; + } + case "login_submit": { + const login = this.logins.submitCode(operation.loginId, operation.code); + if (!login) return { ok: false, error: "Sign-in not found." }; + const view = toLoginView(login); + onEvent?.({ type: "login_update", login: view }); + return { ok: true, login: view }; + } + case "login_cancel": { + const login = this.logins.cancel(operation.loginId); + if (!login) return { ok: false, error: "Sign-in not found." }; + return { ok: true, login: toLoginView(login) }; + } + } + } + + private async runManaged( + engine: RunnerEngine, + kind: "install" | "update", + onEvent?: (event: EngineOperationEvent) => void + ): Promise { + const cfg = this.config.engines[engine]; + const step = kind === "install" ? cfg?.install : cfg?.update; + if (!step) { + return { + ok: false, + error: `No managed ${kind} command is configured for ${LABELS[engine]} on this runner.`, + }; + } + const operationId = randomUUID(); + onEvent?.({ + type: "operation_progress", + operationId, + engine, + phase: kind, + message: kind === "install" ? "Installing…" : "Updating…", + }); + const before = cfg?.bin ? await this.readVersion(cfg.bin) : null; + await this.run( + step.executable, + step.args, + { ...this.config.env, ...step.env }, + 180_000, + (chunk) => { + onEvent?.({ + type: "operation_progress", + operationId, + engine, + phase: kind, + message: "", + outputChunk: chunk.slice(0, 4_000), + }); + } + ); + const after = cfg?.bin ? await this.readVersion(cfg.bin) : null; + const success = + kind === "install" + ? Boolean(after) + : Boolean(before && after && compareVersions(after, before) > 0); + onEvent?.({ + type: "operation_complete", + operationId, + engine, + success, + message: success + ? `${kind === "install" ? "Install" : "Update"} completed. Verified installed version ${after}.` + : `${kind === "install" ? "Install" : "Update"} command completed, but a ${kind === "install" ? "new" : "newer"} installed version could not be verified.`, + }); + return { ok: true, operationId }; + } + + /** Stop every sign-in under way; for shutdown. */ + close(): void { + this.logins.close(); + } +} + +function toLoginView(login: { + id: string; + engine: RunnerEngine; + status: EngineLoginView["status"]; + url?: string; + userCode?: string; + needsCode: boolean; + detail?: string; + error?: string; + expiresAt?: string; + finishedAt?: string; +}): EngineLoginView { + return login; +} diff --git a/apps/server/test/engine-manager.test.ts b/apps/server/test/engine-manager.test.ts new file mode 100644 index 000000000..060b2e2a9 --- /dev/null +++ b/apps/server/test/engine-manager.test.ts @@ -0,0 +1,285 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { EngineLogin, EngineAuthStatus } from "@dispatch/shared"; +import type { EngineOperationEvent } from "@dispatch/runner-protocol/engine-management"; + +import { + EngineManager, + type RunnerEngineTransport, +} from "../src/agents/remote/engine-manager.js"; +import type { EngineLogins } from "../src/agents/engine-login.js"; +import type { EngineUpdateOperations } from "../src/agents/engine-updates.js"; + +vi.mock("../src/agents/engine-availability.js", async () => { + const actual = await vi.importActual< + typeof import("../src/agents/engine-availability.js") + >("../src/agents/engine-availability.js"); + return { + ...actual, + engineStatuses: vi.fn(async () => [ + { + id: "claude", + label: "Claude Code", + installed: true, + path: "/bin/claude", + version: null, + install: "", + }, + { + id: "codex", + label: "Codex", + installed: false, + path: null, + version: null, + install: "", + }, + { + id: "opencode", + label: "OpenCode", + installed: false, + path: null, + version: null, + install: "", + }, + ]), + withEngineVersions: vi.fn(async (statuses) => + statuses.map((s: any) => ({ + ...s, + version: s.installed ? "1.2.3" : null, + })) + ), + }; +}); + +vi.mock("../src/agents/engine-updates.js", async () => { + const actual = await vi.importActual< + typeof import("../src/agents/engine-updates.js") + >("../src/agents/engine-updates.js"); + return { + ...actual, + withEngineUpdates: vi.fn(async (statuses) => + statuses.map((s: any) => ({ + ...s, + update: { + canUpdate: s.installed, + available: false, + reason: "", + command: "", + latestVersion: null, + latestPending: false, + }, + })) + ), + }; +}); + +function fakeLogins(overrides: Partial = {}): EngineLogins { + return { + status: vi.fn( + async (): Promise => ({ + engine: "claude", + installed: true, + signedIn: true, + detail: "me@example.com", + }) + ), + start: vi.fn( + async (): Promise => ({ + id: "login-1", + engine: "claude", + status: "waiting", + needsCode: true, + url: "https://example.com", + expiresAt: new Date().toISOString(), + }) + ), + submitCode: vi.fn(() => null), + cancel: vi.fn(() => null), + get: vi.fn(() => null), + current: vi.fn(() => null), + close: vi.fn(), + ...overrides, + } as unknown as EngineLogins; +} + +function fakeUpdates( + overrides: Partial = {} +): EngineUpdateOperations { + return { + start: vi.fn(async () => ({ id: "op-1" })), + read: vi.fn(async () => ({})), + ...overrides, + } as unknown as EngineUpdateOperations; +} + +function fakeTransport( + overrides: Partial = {} +): RunnerEngineTransport { + return { + send: vi.fn(async () => ({ ok: true }) as const), + ...overrides, + }; +} + +describe("EngineManager local scope", () => { + it("builds inventory from existing engine-availability/engine-login collaborators", async () => { + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: fakeTransport(), + }); + const inventory = await manager.inventory({ kind: "local" }); + const claude = inventory.find((e) => e.id === "claude")!; + expect(claude.installed).toBe(true); + expect(claude.version).toBe("1.2.3"); + expect(claude.signedIn).toBe(true); + expect(claude.actions).toEqual(["update", "login", "login_cancel"]); + + const codex = inventory.find((e) => e.id === "codex")!; + expect(codex.installed).toBe(false); + expect(codex.actions).toEqual([]); + }); + + it("never offers automatic install locally", async () => { + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: fakeTransport(), + }); + const ack = await manager.rpc( + { kind: "local" }, + { type: "install", engine: "claude" } + ); + expect(ack).toMatchObject({ ok: false, unsupported: true }); + }); + + it("routes update through the existing EngineUpdateOperations", async () => { + const updates = fakeUpdates(); + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates }, + remote: fakeTransport(), + }); + const ack = await manager.rpc( + { kind: "local" }, + { type: "update", engine: "claude" } + ); + expect(ack).toMatchObject({ ok: true, operationId: "op-1" }); + expect(updates.start).toHaveBeenCalledWith("claude", {}); + }); + + it("routes sign-in through the existing EngineLogins", async () => { + const logins = fakeLogins(); + const manager = new EngineManager({ + local: { logins, updates: fakeUpdates() }, + remote: fakeTransport(), + }); + const ack = await manager.rpc( + { kind: "local" }, + { type: "login_start", engine: "claude" } + ); + expect(ack.ok).toBe(true); + expect(logins.start).toHaveBeenCalledWith("claude", { restart: undefined }); + }); +}); + +describe("EngineManager runner scope", () => { + it("forwards operations to the injected transport", async () => { + const transport = fakeTransport(); + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: transport, + }); + await manager.rpc( + { kind: "runner", runnerId: "r1", workspace: "w1" }, + { type: "login_start", engine: "claude" } + ); + expect(transport.send).toHaveBeenCalledWith( + "r1", + "w1", + { type: "login_start", engine: "claude" }, + undefined + ); + }); + + it("reads inventory from the runner's streamed inventory event", async () => { + const transport = fakeTransport({ + send: vi.fn(async (_r, _w, _op, onEvent) => { + onEvent?.({ + type: "inventory", + entries: [ + { + id: "claude", + label: "Claude Code", + installed: true, + signedIn: true, + version: "9.9.9", + actions: ["login"], + }, + ], + } satisfies EngineOperationEvent); + return { ok: true }; + }), + }); + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: transport, + }); + const inventory = await manager.inventory({ + kind: "runner", + runnerId: "r1", + workspace: "w1", + }); + expect(inventory).toEqual([ + { + id: "claude", + label: "Claude Code", + installed: true, + signedIn: true, + version: "9.9.9", + actions: ["login"], + }, + ]); + }); + + it("falls back to unknown entries when a runner doesn't support engine management", async () => { + const transport = fakeTransport({ + send: vi.fn(async () => ({ + ok: false, + error: "unknown command", + unsupported: true, + })), + }); + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: transport, + }); + const inventory = await manager.inventory({ + kind: "runner", + runnerId: "r1", + workspace: "w1", + }); + expect(inventory.every((e) => !e.installed && e.signedIn === null)).toBe( + true + ); + expect(inventory).toHaveLength(3); + }); + + it("notifies onChanged listeners after a state-changing operation", async () => { + const transport = fakeTransport({ + send: vi.fn(async (_r, _w, op) => { + if (op.type === "status") { + return { ok: true }; + } + return { ok: true }; + }), + }); + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: transport, + }); + const scope = { kind: "runner" as const, runnerId: "r1", workspace: "w1" }; + const listener = vi.fn(); + const unsubscribe = manager.onChanged(scope, listener); + await manager.rpc(scope, { type: "login_start", engine: "claude" }); + expect(listener).toHaveBeenCalled(); + unsubscribe(); + }); +}); diff --git a/apps/server/test/engine-runner-executor.test.ts b/apps/server/test/engine-runner-executor.test.ts new file mode 100644 index 000000000..b24c3abdd --- /dev/null +++ b/apps/server/test/engine-runner-executor.test.ts @@ -0,0 +1,172 @@ +import { mkdtempSync, rmSync, writeFileSync, chmodSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; + +import { EngineRunnerExecutor } from "../src/agents/remote/engine-runner-executor.js"; + +// No real `setpriv` in CI; the executor's `wrap` seam is exercised with a +// pass-through that proves the production code *calls* it for every spawn, +// without needing real privilege-drop capabilities on the test machine. +const passthroughWrap = (bin: string, args: string[]) => ({ bin, args }); + +describe("EngineRunnerExecutor", () => { + let dir: string; + let fake: string; + let executor: EngineRunnerExecutor | null; + + beforeAll(() => { + dir = mkdtempSync(path.join(os.tmpdir(), "dispatch-engine-runner-")); + fake = path.join(dir, "fake-cli.mjs"); + writeFileSync( + fake, + `#!/usr/bin/env node +const mode = process.env.FAKE_ENGINE_MODE || ""; +const args = process.argv.slice(2).join(" "); +if (args === "--version") { + console.log(mode === "updated" ? "2.0.0 (Fake)" : "1.0.0 (Fake)"); + process.exit(0); +} else if (args === "auth status --json") { + console.log(JSON.stringify({ loggedIn: true, email: "me@example.com" })); +} else if (args === "install") { + process.exit(mode === "fail-install" ? 1 : 0); +} else if (args === "update") { + process.exit(0); +} else { + process.exit(2); +} +` + ); + chmodSync(fake, 0o755); + }); + + afterAll(() => rmSync(dir, { recursive: true, force: true })); + afterEach(() => executor?.close()); + + it("reports an installed engine's version and sign-in status", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { claude: { bin: fake } }, + }); + const inventory = await executor.inventory(); + const claude = inventory.find((entry) => entry.id === "claude")!; + expect(claude.installed).toBe(true); + expect(claude.version).toBe("1.0.0"); + expect(claude.signedIn).toBe(true); + expect(claude.detail).toBe("me@example.com"); + expect(claude.actions).toEqual(["login", "login_cancel"]); + + const codex = inventory.find((entry) => entry.id === "codex")!; + expect(codex.installed).toBe(false); + expect(codex.signedIn).toBeNull(); + expect(codex.actions).toEqual([]); + }); + + it("offers install only when a managed install command is configured", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { + codex: { bin: null, install: { executable: fake, args: ["install"] } }, + }, + }); + const inventory = await executor.inventory(); + expect(inventory.find((entry) => entry.id === "codex")?.actions).toEqual([ + "install", + ]); + }); + + it("runs a configured update and verifies the version advanced", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: { ...process.env, FAKE_ENGINE_MODE: "updated" }, + wrap: passthroughWrap, + engines: { + claude: { bin: fake, update: { executable: fake, args: ["update"] } }, + }, + }); + const events: string[] = []; + const ack = await executor.handle( + { type: "update", engine: "claude" }, + (event) => events.push(event.type) + ); + expect(ack.ok).toBe(true); + expect(events).toContain("operation_progress"); + expect(events[events.length - 1]).toBe("operation_complete"); + }); + + it("rejects an operation with no configured managed command", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { claude: { bin: fake } }, + }); + const ack = await executor.handle({ type: "update", engine: "claude" }); + expect(ack).toMatchObject({ ok: false }); + }); + + it("runs sign-in through the same EngineLogins flow, wrapped", async () => { + const loginFake = path.join(dir, "fake-login.mjs"); + writeFileSync( + loginFake, + `#!/usr/bin/env node +const args = process.argv.slice(2).join(" "); +if (args === "auth login") { + process.stdout.write("Visit: https://claude.com/cai/oauth/authorize?code=1\\nPaste code here if prompted > "); + process.stdin.once("data", (chunk) => { + process.exit(chunk.toString().trim() === "good" ? 0 : 1); + }); +} else if (args === "auth status --json") { + console.log(JSON.stringify({ loggedIn: true, email: "me@example.com" })); +} else { + process.exit(2); +} +` + ); + chmodSync(loginFake, 0o755); + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { claude: { bin: loginFake } }, + }); + const started = await executor.handle({ + type: "login_start", + engine: "claude", + }); + expect(started.ok).toBe(true); + expect(started.login?.status).toBe("waiting"); + expect(started.login?.url).toContain("https://claude.com"); + const submitted = await executor.handle({ + type: "login_submit", + loginId: started.login!.id, + code: "good", + }); + expect(submitted.ok).toBe(true); + }); + + it("refuses sign-in for an engine with no login flow", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { opencode: { bin: fake } }, + }); + const ack = await executor.handle({ + type: "login_start", + engine: "opencode", + }); + expect(ack).toMatchObject({ ok: false }); + }); +}); diff --git a/apps/web/src/components/runner-engines/runner-engines.test.tsx b/apps/web/src/components/runner-engines/runner-engines.test.tsx new file mode 100644 index 000000000..bbf353c8c --- /dev/null +++ b/apps/web/src/components/runner-engines/runner-engines.test.tsx @@ -0,0 +1,134 @@ +// @vitest-environment jsdom +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +import { api } from "@/lib/api"; +import type { + EngineInventoryEntry, + EngineOperationAck, +} from "@dispatch/runner-protocol/engine-management"; + +import { RunnerEngines } from "./runner-engines"; + +vi.mock("@/lib/api", () => ({ api: vi.fn() })); + +const baseEntries: EngineInventoryEntry[] = [ + { + id: "claude", + label: "Claude Code", + installed: true, + signedIn: true, + version: "1.2.3", + detail: "me@example.com", + actions: ["update", "login", "login_cancel"], + }, + { + id: "codex", + label: "Codex", + installed: false, + signedIn: null, + version: null, + actions: ["install"], + }, +]; + +function renderWithClient(scope: Parameters[0]["scope"]) { + const client = new QueryClient(); + return render( + + + + ); +} + +beforeEach(() => { + vi.mocked(api).mockReset(); +}); + +afterEach(cleanup); + +it("renders each engine's installed/signed-in state and available actions", async () => { + vi.mocked(api).mockResolvedValue({ entries: baseEntries }); + renderWithClient({ kind: "local" }); + + await waitFor(() => screen.getByTestId("runner-engine-claude")); + expect(screen.getByTestId("runner-engine-claude").textContent).toContain( + "v1.2.3" + ); + expect(screen.getByTestId("runner-engine-claude").textContent).toContain( + "signed in" + ); + expect(screen.queryByTestId("runner-engine-claude-install")).toBeNull(); + expect(screen.getByTestId("runner-engine-claude-update")).toBeTruthy(); + + expect(screen.getByTestId("runner-engine-codex").textContent).toContain( + "not installed" + ); + expect(screen.getByTestId("runner-engine-codex-install")).toBeTruthy(); +}); + +it("posts an install operation scoped to a runner workspace and refreshes", async () => { + const ack: EngineOperationAck = { ok: true, operationId: "op-1" }; + vi.mocked(api).mockImplementation( + async (path: string, init?: RequestInit) => { + if (init?.method === "POST") { + expect(JSON.parse(init.body as string)).toMatchObject({ + scope: { kind: "runner", runnerId: "r1", workspace: "w1" }, + operation: { type: "install", engine: "codex" }, + }); + return { ack }; + } + expect(path).toContain("scope=runner"); + expect(path).toContain("runnerId=r1"); + expect(path).toContain("workspace=w1"); + return { entries: baseEntries }; + } + ); + + renderWithClient({ kind: "runner", runnerId: "r1", workspace: "w1" }); + await waitFor(() => screen.getByTestId("runner-engine-codex-install")); + fireEvent.click(screen.getByTestId("runner-engine-codex-install")); + + await waitFor(() => + expect( + vi.mocked(api).mock.calls.filter(([, init]) => init?.method === "POST") + ).toHaveLength(1) + ); +}); + +it("walks a Codex-style device sign-in to the waiting state", async () => { + vi.mocked(api).mockImplementation( + async (path: string, init?: RequestInit) => { + if (init?.method === "POST") { + const ack: EngineOperationAck = { + ok: true, + login: { + id: "login-1", + engine: "claude", + status: "waiting", + needsCode: false, + url: "https://auth.example.com/device", + userCode: "ABCD-1234", + expiresAt: new Date().toISOString(), + }, + }; + return { ack }; + } + return { entries: [{ ...baseEntries[0]!, signedIn: false }] }; + } + ); + + renderWithClient({ kind: "local" }); + await waitFor(() => screen.getByTestId("runner-engine-claude-sign-in")); + fireEvent.click(screen.getByTestId("runner-engine-claude-sign-in")); + + await waitFor(() => expect(screen.getByText("ABCD-1234")).toBeTruthy()); + expect(screen.getByText("https://auth.example.com/device")).toBeTruthy(); +}); diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx new file mode 100644 index 000000000..4ee1f9087 --- /dev/null +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -0,0 +1,325 @@ +import { useState } from "react"; +import { CheckCircle2, Loader2 } from "lucide-react"; + +import type { + EngineInventoryEntry, + EngineLoginView, +} from "@dispatch/runner-protocol/engine-management"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { CopyButton } from "@/components/ui/copy-button"; +import { Input } from "@/components/ui/input"; +import { + useRunnerEngineInventory, + useRunnerEngineOperation, +} from "@/hooks/use-runner-engines"; +import type { EngineScope } from "@dispatch/runner-protocol/engine-management"; + +/** + * Engine install/update/sign-in for one scope: this machine, or a named + * runner workspace. Self-contained — the caller only supplies `scope` + * (and, for a runner, the surrounding "which runner/workspace" picker). + * See `use-runner-engines.ts` for the HTTP contract this expects. + */ +export function RunnerEngines({ scope }: { scope: EngineScope }): JSX.Element { + const inventory = useRunnerEngineInventory(scope); + const entries = inventory.data?.entries ?? []; + const [activeLogin, setActiveLogin] = useState(null); + + if (inventory.isLoading) { + return ( +

+

+ ); + } + + if (inventory.isError) { + return ( +

+ Could not load engines for this scope. +

+ ); + } + + return ( +
+ {entries.map((entry) => ( + + setActiveLogin(login && login.engine === entry.id ? login : null) + } + /> + ))} +
+ ); +} + +function isLoginActive(login: EngineLoginView | null): boolean { + return ( + login?.status === "starting" || + login?.status === "waiting" || + login?.status === "verifying" + ); +} + +function EngineRow({ + scope, + entry, + activeLogin, + onLoginChange, +}: { + scope: EngineScope; + entry: EngineInventoryEntry; + activeLogin: EngineLoginView | null; + onLoginChange: (login: EngineLoginView | null) => void; +}): JSX.Element { + const operation = useRunnerEngineOperation(scope); + const [code, setCode] = useState(""); + + const run = ( + op: Parameters["mutate"]>[0] + ) => + operation.mutate(op, { + onSuccess: ({ ack }) => { + if (ack.ok && ack.login) onLoginChange(ack.login); + }, + }); + + const canInstall = entry.actions.includes("install"); + const canUpdate = entry.actions.includes("update"); + const canLogin = entry.actions.includes("login"); + + return ( +
+
+
+ + {entry.label} + + {entry.installed ? ( + + {entry.version ? `v${entry.version}` : "installed"} + + ) : ( + not installed + )} + {entry.installed && entry.signedIn !== null && ( + + {entry.signedIn ? "signed in" : "signed out"} + + )} +
+
+ {canInstall && ( + + )} + {canUpdate && ( + + )} + {canLogin && + entry.signedIn !== true && + !isLoginActive(activeLogin) && ( + + )} +
+
+ + {entry.detail && entry.signedIn && ( +

{entry.detail}

+ )} + + {operation.isError && ( +

+ {operation.error.message} +

+ )} + + {isLoginActive(activeLogin) && activeLogin && ( + + run({ + type: "login_submit", + loginId: activeLogin.id, + code, + }) + } + onCancel={() => { + run({ type: "login_cancel", loginId: activeLogin.id }); + onLoginChange(null); + }} + submitting={operation.isPending} + /> + )} + + {activeLogin?.status === "succeeded" && ( +

+

+ )} + {activeLogin?.status === "failed" && ( +

+ {activeLogin.error ?? "The sign-in failed."} +

+ )} +
+ ); +} + +function LoginFlow({ + login, + code, + onCodeChange, + onSubmit, + onCancel, + submitting, +}: { + login: EngineLoginView; + code: string; + onCodeChange: (value: string) => void; + onSubmit: () => void; + onCancel: () => void; + submitting: boolean; +}): JSX.Element { + if (login.status !== "waiting" || !login.url) { + return ( +
+

+

+ +
+ ); + } + + return ( +
+
+ + {login.url} + + +
+ {login.userCode ? ( +
+
+ + {login.userCode} + + +
+
+

+

+ +
+
+ ) : ( +
{ + event.preventDefault(); + if (code.trim()) onSubmit(); + }} + > + onCodeChange(event.target.value)} + placeholder="Paste code" + autoComplete="off" + autoCapitalize="off" + spellCheck={false} + aria-label="Sign-in code" + className="h-8 text-xs" + /> + + +
+ )} +
+ ); +} diff --git a/apps/web/src/hooks/use-runner-engines.ts b/apps/web/src/hooks/use-runner-engines.ts new file mode 100644 index 000000000..804b55740 --- /dev/null +++ b/apps/web/src/hooks/use-runner-engines.ts @@ -0,0 +1,74 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +import { + engineScopeKey, + type EngineInventoryEntry, + type EngineOperation, + type EngineOperationAck, + type EngineScope, +} from "@dispatch/runner-protocol/engine-management"; + +import { api } from "@/lib/api"; + +/** + * Scope-aware engine inventory and install/update/sign-in, for an engine + * running locally or on a named runner workspace. Expects the HTTP routes: + * + * - `GET /api/v1/engine-management/inventory?{scope query}` → `{ entries }` + * - `POST /api/v1/engine-management/operations` with `{ scope, operation }` + * body → `{ ack }` + * + * where the scope query is `scope=local` or + * `scope=runner&runnerId=&workspace=`. Both routes back onto + * `EngineManager` (`apps/server/src/agents/remote/engine-manager.ts`). + */ + +function scopeQuery(scope: EngineScope): string { + const params = new URLSearchParams({ scope: scope.kind }); + if (scope.kind === "runner") { + params.set("runnerId", scope.runnerId); + params.set("workspace", scope.workspace); + } + return params.toString(); +} + +export function runnerEnginesKey(scope: EngineScope) { + return ["runner-engines", engineScopeKey(scope)] as const; +} + +/** Whether an operation leaves something still running, worth polling for. */ +function hasPendingWork(entries: EngineInventoryEntry[] | undefined): boolean { + // Sign-in is the only state this inventory can't settle on its own; an + // install/update's completion is the inventory's own version/installed + // change, so no separate "pending" flag is needed here. + return ( + entries?.some((entry) => entry.signedIn === null && entry.installed) ?? + false + ); +} + +export function useRunnerEngineInventory(scope: EngineScope) { + return useQuery<{ entries: EngineInventoryEntry[] }>({ + queryKey: runnerEnginesKey(scope), + queryFn: () => + api(`/api/v1/engine-management/inventory?${scopeQuery(scope)}`), + refetchInterval: (query) => + hasPendingWork(query.state.data?.entries) ? 2_000 : 10_000, + }); +} + +/** Run one operation against a scope and refresh its inventory on completion. */ +export function useRunnerEngineOperation(scope: EngineScope) { + const queryClient = useQueryClient(); + const key = runnerEnginesKey(scope); + return useMutation<{ ack: EngineOperationAck }, Error, EngineOperation>({ + mutationFn: (operation) => + api(`/api/v1/engine-management/operations`, { + method: "POST", + body: JSON.stringify({ scope, operation }), + }), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: key }); + }, + }); +} diff --git a/packages/runner-protocol/package.json b/packages/runner-protocol/package.json index 1da5efc48..4276e85eb 100644 --- a/packages/runner-protocol/package.json +++ b/packages/runner-protocol/package.json @@ -5,7 +5,8 @@ "type": "module", "exports": { ".": "./src/index.ts", - "./node": "./src/node.ts" + "./node": "./src/node.ts", + "./engine-management": "./src/engine-management.ts" }, "files": [ "src" diff --git a/packages/runner-protocol/src/engine-management.ts b/packages/runner-protocol/src/engine-management.ts new file mode 100644 index 000000000..a8ee1fc69 --- /dev/null +++ b/packages/runner-protocol/src/engine-management.ts @@ -0,0 +1,117 @@ +import type { RunnerEngine } from "./index.js"; + +/** + * Engine install/update/sign-in, scoped to wherever an engine's CLI runs: + * this machine or a named runner workspace. Self-contained wire types; a + * runner that predates this module simply never answers an `"engine"` + * command, which callers treat as `{ ok: false, unsupported: true }`. + */ + +export type EngineSupportedAction = + | "install" + | "update" + | "login" + | "login_cancel"; + +/** What a scope reports about one engine, for an inventory list. */ +export type EngineInventoryEntry = { + id: RunnerEngine; + label: string; + installed: boolean; + /** Null when signed-in status could not be determined (e.g. CLI missing). */ + signedIn: boolean | null; + version: string | null; + /** Who it's signed in as, or how; never a token, URL or code. */ + detail?: string; + actions: EngineSupportedAction[]; +}; + +/** Mirrors `@dispatch/shared`'s `EngineLogin`, generalized over `RunnerEngine`. */ +export type EngineLoginView = { + id: string; + engine: RunnerEngine; + status: + | "starting" + | "waiting" + | "verifying" + | "succeeded" + | "failed" + | "cancelled"; + needsCode: boolean; + /** The sign-in link; present only while the sign-in is active. */ + url?: string; + /** Codex's one-time device code; present only while the sign-in is active. */ + userCode?: string; + detail?: string; + error?: string; + expiresAt?: string; + finishedAt?: string; +}; + +export type EngineOperation = + | { type: "status" } + | { type: "install"; engine: RunnerEngine } + | { type: "update"; engine: RunnerEngine } + | { type: "login_start"; engine: RunnerEngine; restart?: boolean } + | { type: "login_submit"; loginId: string; code: string } + | { type: "login_cancel"; loginId: string }; + +/** + * Progress for a long-running operation. Sent as they happen; a scope may + * send zero or more before its terminal `operation_complete`. `outputChunk` + * is bounded CLI output for display, never a secret, URL or code — those + * travel only in `login_update`'s `url`/`userCode`, which are never logged. + */ +export type EngineOperationEvent = + | { type: "inventory"; entries: EngineInventoryEntry[] } + | { + type: "operation_progress"; + operationId: string; + engine: RunnerEngine; + phase: string; + message: string; + outputChunk?: string; + } + | { + type: "operation_complete"; + operationId: string; + engine: RunnerEngine; + success: boolean; + message: string; + } + | { type: "login_update"; login: EngineLoginView }; + +export type EngineOperationAck = + | { ok: true; operationId?: string; login?: EngineLoginView } + | { ok: false; error: string; unsupported?: boolean }; + +export const RUNNER_ENGINES: readonly RunnerEngine[] = [ + "claude", + "codex", + "opencode", +]; + +/** Where an engine's CLI runs: this machine, or a named runner workspace. */ +export type EngineScope = + | { kind: "local" } + | { kind: "runner"; runnerId: string; workspace: string }; + +/** A stable string key for a scope, for query params, cache keys and event names. */ +export function engineScopeKey(scope: EngineScope): string { + return scope.kind === "local" + ? "local" + : `runner:${scope.runnerId}/${scope.workspace}`; +} + +export function isEngineOperation(value: unknown): value is EngineOperation { + if (!value || typeof value !== "object") return false; + const type = (value as { type?: unknown }).type; + return ( + type === "status" || + type === "install" || + type === "update" || + type === "login_start" || + type === "login_submit" || + type === "login_cancel" + ); +} From 9e6cb1c172bf40461e3ba2fca97da644b698dc07 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 08:53:50 -0700 Subject: [PATCH 040/642] Add runner-initiated enrollment (dispatch-runner connect) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The runner can now dial the Dispatch service itself instead of an operator running a pairing command on it: `dispatch-runner connect --service [--ca-sha256 PIN]` generates a keypair locally, submits only the public key to POST /api/runners/connect, and prints a short code plus an approval URL. An operator approves through the authenticated API with that code and a name; approval is key-bound (the certificate is issued only for the key already on file), the code is a bounded-attempt 10-minute one-time value, and the client certificate is issued automatically. Pinning (--ca-sha256) is checked inside the single connection that carries the request, with no separate unauthenticated round trip first. Adds migration 0054 (runner_connect_requests), registry/service methods and routes for create/poll/list/approve/deny, and a runnerConnectBootstrap route flag so the create/poll endpoints — which carry no Dispatch credentials yet — bypass the global auth hook. The existing operator-initiated pairing flow is unchanged. Co-Authored-By: Claude Sonnet 5 --- apps/server/src/agents/remote/enrollment.ts | 313 ++++++++++++++++-- apps/server/src/agents/remote/registry.ts | 233 +++++++++++++ apps/server/src/agents/remote/service.ts | 117 +++++++ .../0054_runner_connect_requests.sql | 25 ++ apps/server/src/main.ts | 3 + apps/server/src/routes/runners.ts | 107 ++++++ apps/server/src/server.ts | 5 + apps/server/test/migrations.test.ts | 4 +- .../server/test/remote-runner-connect.test.ts | 253 ++++++++++++++ docs/design/remote-runner-prototype.md | 36 ++ 10 files changed, 1072 insertions(+), 24 deletions(-) create mode 100644 apps/server/src/db/migrations/0054_runner_connect_requests.sql create mode 100644 apps/server/test/remote-runner-connect.test.ts diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index ac1b353d6..39062962e 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -1,6 +1,7 @@ import { X509Certificate } from "node:crypto"; import { existsSync, readFileSync, statSync } from "node:fs"; import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises"; +import https from "node:https"; import { isIP } from "node:net"; import path from "node:path"; import { connect, type TLSSocket } from "node:tls"; @@ -299,31 +300,34 @@ export async function exchangeCode(input: { )) as Extract; } -/** `dispatch-runner remote-runner-pair …`: enroll this host as a runner. */ -export async function runRunnerPairing(argv: string[]) { - const options = parseArgs(argv); - const { key, publicKey } = generateRunnerKey(); - const enrolled = await exchangeCode({ - endpoint: options.endpoint, - pin: options.pin, - code: options.code, - publicKey, - }); - await mkdir(options.dir, { recursive: true, mode: 0o755 }); +/** + * Write the enrolled key, certificate and CA to disk and, when a runner.json + * already exists (or was named with `--config`), update its credential + * paths and endpoint in place. Shared by both enrollment CLIs. + */ +async function persistRunnerCredentials(input: { + dir: string; + config?: string; + endpoint: string; + key: string; + cert: string; + ca: string; +}) { + await mkdir(input.dir, { recursive: true, mode: 0o755 }); const files = { - ca: path.join(options.dir, "ca.pem"), - cert: path.join(options.dir, "cert.pem"), - key: path.join(options.dir, "key.pem"), + ca: path.join(input.dir, "ca.pem"), + cert: path.join(input.dir, "cert.pem"), + key: path.join(input.dir, "key.pem"), }; // The key stays root-only; the CLI account reads only the CA. - await writeAtomic(files.key, key, 0o600); - await writeAtomic(files.cert, enrolled.cert, 0o644); - await writeAtomic(files.ca, enrolled.ca, 0o644); + await writeAtomic(files.key, input.key, 0o600); + await writeAtomic(files.cert, input.cert, 0o644); + await writeAtomic(files.ca, input.ca, 0o644); const configFile = - options.config ?? - (existsSync(path.join(options.dir, "runner.json")) - ? path.join(options.dir, "runner.json") + input.config ?? + (existsSync(path.join(input.dir, "runner.json")) + ? path.join(input.dir, "runner.json") : undefined); if (configFile) { const current = JSON.parse(readFileSync(configFile, "utf8")); @@ -331,21 +335,286 @@ export async function runRunnerPairing(argv: string[]) { await writeAtomic( configFile, JSON.stringify( - { ...current, endpoint: options.endpoint, ...files }, + { ...current, endpoint: input.endpoint, ...files }, null, 2 ) + "\n", mode & 0o077 ? 0o600 : mode ); } + return { files, configFile }; +} + +/** `dispatch-runner remote-runner-pair …`: enroll this host as a runner. */ +export async function runRunnerPairing(argv: string[]) { + const options = parseArgs(argv); + const { key, publicKey } = generateRunnerKey(); + const enrolled = await exchangeCode({ + endpoint: options.endpoint, + pin: options.pin, + code: options.code, + publicKey, + }); + const { configFile } = await persistRunnerCredentials({ + dir: options.dir, + config: options.config, + endpoint: options.endpoint, + key, + cert: enrolled.cert, + ca: enrolled.ca, + }); process.stdout.write( [ `Enrolled runner "${enrolled.name}" (${enrolled.id}).`, `Credentials: ${options.dir}`, configFile ? `Updated ${configFile}.` - : `Add to runner.json: ${JSON.stringify({ endpoint: options.endpoint, ...files })}`, + : `Add to runner.json: ${JSON.stringify({ + endpoint: options.endpoint, + ca: path.join(options.dir, "ca.pem"), + cert: path.join(options.dir, "cert.pem"), + key: path.join(options.dir, "key.pem"), + })}`, "", ].join("\n") ); } + +/* + * Runner-initiated ("connect") enrollment. The runner dials the Dispatch + * service itself — no pairing command to copy — and shows its operator a + * short code plus a service-provided approval URL. The operator approves + * through the authenticated Dispatch API with that code and a name; the + * client certificate is issued automatically for the public key this CLI + * already submitted, so the code alone can never redeem a different key. + */ + +type ConnectOptions = { + service: string; + pin?: string; + dir: string; + config?: string; + timeoutMs?: number; +}; + +function parseConnectArgs(argv: string[]): ConnectOptions { + const values = new Map(); + for (let index = 0; index < argv.length; index += 2) { + const flag = argv[index]; + const value = argv[index + 1]; + if (!flag?.startsWith("--") || value === undefined) + throw new Error(`Unexpected argument: ${flag ?? ""}`); + values.set(flag.slice(2), value); + } + const service = values.get("service"); + if (!service) + throw new Error( + "Usage: dispatch-runner connect --service https://HOST:PORT [--ca-sha256 HEX] [--dir /etc/dispatch-runner] [--config FILE]" + ); + return { + service, + pin: values.get("ca-sha256"), + dir: path.resolve(values.get("dir") ?? "/etc/dispatch-runner"), + config: values.get("config"), + }; +} + +/** Whether the pin matches any certificate up the peer's presented chain. */ +function pinnedChainMatches(socket: TLSSocket, pin: string) { + const expected = normalizeFingerprint(pin); + let cert = socket.getPeerCertificate(true) as + | (ReturnType & { + issuerCertificate?: ReturnType; + }) + | undefined; + for (let hop = 0; cert && hop < 8; hop++) { + if (cert.fingerprint256 === expected) return true; + const issuer = cert.issuerCertificate; + if (!issuer || issuer === cert) break; + cert = issuer as typeof cert; + } + return false; +} + +/** + * One HTTPS round trip to the service's ordinary API — never a separate + * unauthenticated connection to fetch its CA first. With `pin`, the single + * TLS connection itself gates the request: nothing is written to the socket + * until the presented chain matches the pinned fingerprint. Without `pin`, + * the service is expected to hold an ordinarily trusted certificate. + */ +function requestJson( + serviceUrl: string, + method: string, + requestPath: string, + body: unknown, + options: { pin?: string; timeoutMs?: number } = {} +): Promise { + const url = new URL(requestPath, serviceUrl); + if (url.protocol !== "https:") + throw new Error("--service must be an https URL."); + const hostname = url.hostname.replace(/^\[|\]$/g, ""); + const payload = + body === undefined ? undefined : Buffer.from(JSON.stringify(body)); + return new Promise((resolve, reject) => { + let settled = false; + const finish = (error?: Error, value?: unknown) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (error) reject(error); + else resolve(value); + }; + const timer = setTimeout(() => { + request.destroy(); + finish(new Error("The request to the service timed out.")); + }, options.timeoutMs ?? 15_000); + const request = https.request( + { + hostname, + port: Number(url.port || 443), + path: url.pathname + url.search, + method, + servername: isIP(hostname) ? undefined : hostname, + headers: payload + ? { + "content-type": "application/json", + "content-length": payload.length, + } + : undefined, + // Pinned mode validates the chain itself (see pinnedChainMatches) + // before any request data is sent; it does not otherwise weaken + // verification of what the peer is allowed to claim. + rejectUnauthorized: options.pin === undefined, + }, + (response) => { + let data = ""; + response.on("data", (chunk) => (data += chunk)); + response.on("end", () => { + let parsed: unknown; + try { + parsed = data ? JSON.parse(data) : undefined; + } catch { + return finish( + new Error("The service sent an unreadable response.") + ); + } + if ((response.statusCode ?? 0) >= 400) { + return finish( + new Error( + (parsed as { error?: string } | undefined)?.error ?? + `The service returned ${response.statusCode}.` + ) + ); + } + finish(undefined, parsed); + }); + } + ); + request.on("error", (error) => finish(error as Error)); + const send = () => { + if (payload) request.write(payload); + request.end(); + }; + if (options.pin === undefined) { + send(); + return; + } + request.on("socket", (socket: TLSSocket) => { + socket.once("secureConnect", () => { + if (!pinnedChainMatches(socket, options.pin!)) { + finish( + new Error( + "The service certificate does not match the pinned Dispatch runner CA." + ) + ); + request.destroy(); + return; + } + send(); + }); + }); + }); +} + +type ConnectCreated = { id: string; code: string; expiresAt: string }; +type ConnectPoll = + | { status: "pending" } + | { + status: "approved"; + id: string; + name: string; + endpoint: string; + cert: string; + ca: string; + } + | { status: "denied" } + | { status: "expired" }; + +/** `dispatch-runner connect …`: ask an operator to approve this runner. */ +export async function runRunnerConnect(argv: string[]) { + const options = parseConnectArgs(argv); + const { key, publicKey } = generateRunnerKey(); + const created = (await requestJson( + options.service, + "POST", + "/api/runners/connect", + { publicKey }, + { pin: options.pin, timeoutMs: options.timeoutMs } + )) as ConnectCreated; + + process.stdout.write( + [ + `Code: ${created.code}`, + `Ask an operator to approve this runner in Dispatch (Settings → Connections → Remote runners) using this code.`, + `This code expires at ${created.expiresAt}.`, + "Waiting for approval…", + "", + ].join("\n") + ); + + const deadline = new Date(created.expiresAt).getTime(); + const pollIntervalMs = 2_000; + for (;;) { + if (Date.now() > deadline) + throw new Error("The connect request expired before it was approved."); + const polled = (await requestJson( + options.service, + "GET", + `/api/runners/connect/${created.id}`, + undefined, + { pin: options.pin, timeoutMs: options.timeoutMs } + )) as ConnectPoll; + if (polled.status === "denied") + throw new Error("The connect request was denied."); + if (polled.status === "expired") + throw new Error("The connect request expired before it was approved."); + if (polled.status === "approved") { + const { configFile } = await persistRunnerCredentials({ + dir: options.dir, + config: options.config, + endpoint: polled.endpoint, + key, + cert: polled.cert, + ca: polled.ca, + }); + process.stdout.write( + [ + `Enrolled runner "${polled.name}" (${polled.id}).`, + `Credentials: ${options.dir}`, + configFile + ? `Updated ${configFile}.` + : `Add to runner.json: ${JSON.stringify({ + endpoint: polled.endpoint, + ca: path.join(options.dir, "ca.pem"), + cert: path.join(options.dir, "cert.pem"), + key: path.join(options.dir, "key.pem"), + })}`, + "", + ].join("\n") + ); + return; + } + await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + } +} diff --git a/apps/server/src/agents/remote/registry.ts b/apps/server/src/agents/remote/registry.ts index a4bb5a49b..66acdf8ad 100644 --- a/apps/server/src/agents/remote/registry.ts +++ b/apps/server/src/agents/remote/registry.ts @@ -2,6 +2,7 @@ import type { RunnerHealth } from "./protocol.js"; import { createHash, randomBytes } from "node:crypto"; import { X509Certificate } from "node:crypto"; import type { Pool } from "pg"; +import { validRunnerName } from "./enrollment.js"; import { issueAuthority, issueClient, @@ -46,14 +47,67 @@ type Row = { }; const PAIRING_TTL_MS = 10 * 60 * 1000; +const CONNECT_CODE_TTL_MS = 10 * 60 * 1000; +/** Wrong-code attempts a pending connect request tolerates before it is void. */ +const MAX_CONNECT_ATTEMPTS = 5; export class RunnerNameTaken extends Error {} export class PairingRejected extends Error {} +export class ConnectRequestInvalid extends Error {} function hashCode(code: string) { return createHash("sha256").update(code).digest("hex"); } +/** An 8-character, human-typeable code (Crockford base32, no padding). */ +function connectCode() { + const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + const bytes = randomBytes(8); + let code = ""; + for (const byte of bytes) code += alphabet[byte % alphabet.length]; + return `${code.slice(0, 4)}-${code.slice(4)}`; +} + +export type ConnectRequest = { + id: string; + createdAt: Date; + codeExpiresAt: Date; + approved: boolean; + denied: boolean; + registrationId: string | null; + /** Set once approved: the registration's display name. */ + name: string | null; + /** Set once approved: the runner's own client certificate, until consumed. */ + cert: string | null; +}; + +type ConnectRow = { + id: string; + public_key_pem: string; + code_hash: string; + code_expires_at: Date; + attempts: number; + created_at: Date; + approved_at: Date | null; + denied_at: Date | null; + registration_id: string | null; + issued_cert: string | null; + registration_name?: string | null; +}; + +function connectRequest(row: ConnectRow): ConnectRequest { + return { + id: row.id, + createdAt: row.created_at, + codeExpiresAt: row.code_expires_at, + approved: Boolean(row.approved_at), + denied: Boolean(row.denied_at), + registrationId: row.registration_id, + name: row.registration_name ?? null, + cert: row.issued_cert, + }; +} + function registration(row: Row): Registration { return { id: row.id, @@ -324,4 +378,183 @@ export class RunnerRegistry { ); return rows[0] ? registration(rows[0]) : undefined; } + + // --------------------------------------------------------------------------- + // Runner-initiated ("connect") enrollment. The runner submits its public + // key before any human approval; the user code is shown only to the + // runner's operator and is redeemed through the authenticated API, never + // sent back by the runner itself. + // --------------------------------------------------------------------------- + + private async pruneExpiredConnectRequests() { + await this.pool.query( + `DELETE FROM runner_connect_requests + WHERE (approved_at IS NULL AND denied_at IS NULL + AND code_expires_at <= now()) + OR denied_at <= now() - interval '1 day' + OR approved_at <= now() - interval '1 day'` + ); + } + + /** Record a fresh request for the runner's own public key. */ + async createConnectRequest(publicKeyPem: string) { + try { + runnerPublicKey(publicKeyPem); + } catch { + throw new PairingRejected("The runner key is not supported."); + } + await this.pruneExpiredConnectRequests(); + const id = `conn_${randomBytes(18).toString("base64url")}`; + const code = connectCode(); + const expiresAt = new Date(Date.now() + CONNECT_CODE_TTL_MS); + await this.pool.query( + `INSERT INTO runner_connect_requests + (id, public_key_pem, code_hash, code_expires_at) + VALUES ($1, $2, $3, $4)`, + [id, publicKeyPem, hashCode(code), expiresAt] + ); + return { id, code, expiresAt }; + } + + /** + * The runner's own poll, addressed by its high-entropy request id (the + * runner's only credential until approval). Never exposes the code or key. + */ + async pollConnectRequest(id: string): Promise { + await this.pruneExpiredConnectRequests(); + const { rows } = await this.pool.query( + `SELECT r.*, g.name AS registration_name + FROM runner_connect_requests r + LEFT JOIN runner_registrations g ON g.id = r.registration_id + WHERE r.id = $1`, + [id] + ); + return rows[0] ? connectRequest(rows[0]) : undefined; + } + + /** The authenticated list for the approval UI: no code or key material. */ + async listConnectRequests(): Promise { + await this.pruneExpiredConnectRequests(); + const { rows } = await this.pool.query( + `SELECT * FROM runner_connect_requests + WHERE approved_at IS NULL AND denied_at IS NULL + ORDER BY created_at` + ); + return rows.map(connectRequest); + } + + /** + * Approve a pending request: verify the code (bounded attempts), issue a + * client certificate for the key already on file, and create the runner's + * registration under the given name. Key-bound — the stored public key + * from request time is the only one that can ever be issued a certificate + * for this request, regardless of what the code alone would otherwise let + * a caller claim. + */ + async approveConnectRequest( + id: string, + code: string, + name: string, + endpointHost: string + ) { + if (!validRunnerName(name)) + throw new PairingRejected( + "Runner names are 1-64 characters without control characters or surrounding spaces." + ); + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + const { rows } = await client.query( + `SELECT * FROM runner_connect_requests WHERE id = $1 FOR UPDATE`, + [id] + ); + const row = rows[0]; + if (!row || row.approved_at || row.denied_at) + throw new ConnectRequestInvalid("The connect request was not found."); + if (row.code_expires_at.getTime() <= Date.now()) + throw new ConnectRequestInvalid("The connect request has expired."); + if (hashCode(code) !== row.code_hash) { + const attempts = row.attempts + 1; + if (attempts >= MAX_CONNECT_ATTEMPTS) { + await client.query( + `UPDATE runner_connect_requests + SET denied_at = now(), attempts = $2 + WHERE id = $1`, + [id, attempts] + ); + await client.query("COMMIT"); + throw new ConnectRequestInvalid( + "Too many incorrect codes; the runner must connect again." + ); + } + await client.query( + `UPDATE runner_connect_requests SET attempts = $2 WHERE id = $1`, + [id, attempts] + ); + await client.query("COMMIT"); + throw new PairingRejected("The code is incorrect."); + } + const { rows: authority } = await client.query( + `SELECT ca_cert, ca_key FROM runner_authority WHERE id = 1` + ); + const ca = { cert: authority[0].ca_cert, key: authority[0].ca_key }; + const registrationId = `rnr_${randomBytes(6).toString("hex")}`; + const publicKey = runnerPublicKey(row.public_key_pem); + const cert = issueClient(ca, registrationId, publicKey); + const parsed = new X509Certificate(cert); + try { + await client.query( + `INSERT INTO runner_registrations + (id, name, endpoint_host, cert_fingerprint, cert_expires_at, enrolled_at) + VALUES ($1, $2, $3, $4, $5, now())`, + [ + registrationId, + name, + endpointHost, + parsed.fingerprint256, + new Date(parsed.validTo), + ] + ); + } catch (error) { + if ((error as { code?: string }).code === "23505") + throw new RunnerNameTaken(`A runner named "${name}" already exists.`); + throw error; + } + await client.query( + `UPDATE runner_connect_requests + SET approved_at = now(), registration_id = $2, issued_cert = $3 + WHERE id = $1`, + [id, registrationId, cert] + ); + await client.query("COMMIT"); + const issued: Registration = { + id: registrationId, + name, + endpointHost, + fingerprint: parsed.fingerprint256, + workspaces: [], + managedWorkspace: false, + enrolled: true, + revoked: false, + codeExpiresAt: null, + }; + return { registration: issued, cert, ca: ca.cert }; + } catch (error) { + await client.query("ROLLBACK").catch(() => {}); + throw error; + } finally { + client.release(); + } + } + + /** Deny (or cancel) a pending request; the runner's poll stops waiting. */ + async denyConnectRequest(id: string): Promise { + const { rowCount } = await this.pool.query( + `UPDATE runner_connect_requests + SET denied_at = now() + WHERE id = $1 AND approved_at IS NULL AND denied_at IS NULL`, + [id] + ); + return Boolean(rowCount); + } } diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 1f708a26d..767420594 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -25,6 +25,7 @@ import { type EnrollFrame, } from "./enrollment.js"; import { + ConnectRequestInvalid, PairingRejected, RunnerNameTaken, RunnerRegistry, @@ -932,6 +933,122 @@ export class RemoteRunnerService { if (peer.gate.registrationId === id) peer.socket.destroy(); } + // --------------------------------------------------------------------------- + // Runner-initiated ("connect") enrollment + // --------------------------------------------------------------------------- + + /** `POST /api/runners/connect`: an unauthenticated runner requests pairing. */ + async createConnectRequest(publicKey: unknown, serviceOrigin?: string) { + if (!this.enrollment) + throw new RunnerRequestError(409, "Runner enrollment is disabled."); + if (typeof publicKey !== "string" || publicKey.length === 0) + throw new RunnerRequestError(400, "A public key is required."); + try { + const { id, code, expiresAt } = + await this.enrollment.registry.createConnectRequest(publicKey); + return { + id, + code, + approveUrl: serviceOrigin + ? `https://${serviceOrigin}/settings/connections` + : undefined, + expiresAt: expiresAt.toISOString(), + }; + } catch (error) { + if (error instanceof PairingRejected) + throw new RunnerRequestError(400, error.message); + throw error; + } + } + + /** `GET /api/runners/connect/:id`: the runner's own unauthenticated poll. */ + async pollConnectRequest(id: string) { + if (!this.enrollment) + throw new RunnerRequestError(409, "Runner enrollment is disabled."); + const request = await this.enrollment.registry.pollConnectRequest(id); + if (!request) return { status: "expired" as const }; + if (request.denied) return { status: "denied" as const }; + if (!request.approved || !request.registrationId || !request.cert) + return { status: "pending" as const }; + const authority = await this.enrollment.registry.authority(); + if (!authority.port) return { status: "pending" as const }; + const registration = (await this.enrollment.registry.list()).find( + (entry) => entry.id === request.registrationId + ); + if (!registration) return { status: "pending" as const }; + return { + status: "approved" as const, + id: request.registrationId, + name: request.name ?? registration.name, + endpoint: `https://${formatHost(registration.endpointHost)}:${authority.port}`, + cert: request.cert, + ca: authority.ca.cert, + }; + } + + /** The authenticated list for the approval UI. */ + async listConnectRequests() { + if (!this.enrollment) return []; + return (await this.enrollment.registry.listConnectRequests()).map( + (request) => ({ + id: request.id, + createdAt: request.createdAt.toISOString(), + expiresAt: request.codeExpiresAt.toISOString(), + }) + ); + } + + /** `POST /api/runners/connect/:id/approve`: the authenticated operator. */ + async approveConnectRequest( + id: string, + code: unknown, + name: unknown, + hostHint?: string + ) { + if (!this.enrollment) + throw new RunnerRequestError(409, "Runner enrollment is disabled."); + if (typeof code !== "string" || code.length === 0) + throw new RunnerRequestError(400, "A code is required."); + if (!validRunnerName(name)) + throw new RunnerRequestError( + 400, + "Runner names are 1-64 characters without control characters or surrounding spaces." + ); + const host = await this.prepareEndpoint(hostHint); + try { + const approved = await this.enrollment.registry.approveConnectRequest( + id, + code, + name, + host + ); + // Mirror the legacy pairing frame handler: a runner dialing the + // listener immediately after approval must already resolve to a gate. + this.enrolled.set( + approved.registration.fingerprint!, + approved.registration + ); + return { id: approved.registration.id, name: approved.registration.name }; + } catch (error) { + if (error instanceof RunnerNameTaken) + throw new RunnerRequestError(409, error.message); + if (error instanceof ConnectRequestInvalid) + throw new RunnerRequestError(404, error.message); + if (error instanceof PairingRejected) + throw new RunnerRequestError(400, error.message); + throw error; + } + } + + /** `DELETE /api/runners/connect/:id`: deny or cancel a pending request. */ + async denyConnectRequest(id: string) { + if (!this.enrollment) + throw new RunnerRequestError(409, "Runner enrollment is disabled."); + const denied = await this.enrollment.registry.denyConnectRequest(id); + if (!denied) + throw new RunnerRequestError(404, "Connect request not found."); + } + // --------------------------------------------------------------------------- // Agent operations // --------------------------------------------------------------------------- diff --git a/apps/server/src/db/migrations/0054_runner_connect_requests.sql b/apps/server/src/db/migrations/0054_runner_connect_requests.sql new file mode 100644 index 000000000..d51aa4780 --- /dev/null +++ b/apps/server/src/db/migrations/0054_runner_connect_requests.sql @@ -0,0 +1,25 @@ +-- Runner-initiated enrollment ("dispatch-runner connect"). The runner +-- generates its keypair and submits only the public key before any human +-- approval; the one-time code is shown to the operator by the runner and +-- typed into the authenticated Dispatch API, never sent by the runner. The +-- client certificate issued on approval is bound to this stored public key, +-- so a code observed in transit cannot redeem a different key. +CREATE TABLE runner_connect_requests ( + id text PRIMARY KEY, + public_key_pem text NOT NULL, + code_hash text NOT NULL, + code_expires_at timestamptz NOT NULL, + attempts integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT now(), + approved_at timestamptz, + denied_at timestamptz, + registration_id text REFERENCES runner_registrations (id), + -- Not a secret on its own (the private key never leaves the runner); kept + -- so a repeated poll (retry, slow network) returns the same certificate + -- idempotently. Reachable only through the request id, a bearer-strength + -- token the runner alone holds. + issued_cert text +); + +CREATE INDEX runner_connect_requests_expires_idx + ON runner_connect_requests (code_expires_at); diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 3f015510b..c611bc329 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -40,6 +40,9 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "remote-runner-pair") { const { runRunnerPairing } = await import("./agents/remote/enrollment.js"); await runRunnerPairing(process.argv.slice(3)); +} else if (process.argv[2] === "connect") { + const { runRunnerConnect } = await import("./agents/remote/enrollment.js"); + await runRunnerConnect(process.argv.slice(3)); } else if (process.argv[2] === "remote-runner") { const { runRemoteRunner } = await import("./agents/remote/runner.js"); await runRemoteRunner(process.argv[3]!); diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts index ea024929e..034853f47 100644 --- a/apps/server/src/routes/runners.ts +++ b/apps/server/src/routes/runners.ts @@ -6,6 +6,17 @@ import { type RunnerRouteDeps = { runners?: RemoteRunnerService }; +declare module "fastify" { + interface FastifyContextConfig { + /** + * Runner-initiated enrollment create/poll: no Dispatch credentials + * exist yet, so the route gates itself (code, attempts, rate limit) + * instead of going through the global auth hook. + */ + runnerConnectBootstrap?: boolean; + } +} + function hostHint(host: string | undefined) { if (!host) return undefined; try { @@ -84,5 +95,101 @@ export async function registerRunnerRoutes( return fail(reply, error); } }); + + // Runner-initiated ("connect") enrollment. The create and poll routes + // carry no Dispatch credentials — the runner has none yet — so they + // are exempted from the global auth hook by `runnerConnectBootstrap` + // (see server.ts) and rate-limited instead. Approve and deny are + // ordinary authenticated control routes, like every route above. + app.post( + `${base}/connect`, + { + config: { + runnerConnectBootstrap: true, + rateLimit: { max: 20, timeWindow: "1 minute" }, + }, + }, + async (request, reply) => { + if (!deps.runners) + return reply + .code(409) + .send({ error: "Runner enrollment is disabled." }); + const body = (request.body ?? {}) as { publicKey?: unknown }; + try { + return reply + .code(201) + .send( + await deps.runners.createConnectRequest( + body.publicKey, + request.headers.host + ) + ); + } catch (error) { + return fail(reply, error); + } + } + ); + + app.get( + `${base}/connect/:id`, + { + config: { + runnerConnectBootstrap: true, + rateLimit: { max: 60, timeWindow: "1 minute" }, + }, + }, + async (request, reply) => { + const { id } = request.params as { id: string }; + if (!deps.runners) + return reply + .code(409) + .send({ error: "Runner enrollment is disabled." }); + try { + return await deps.runners.pollConnectRequest(id); + } catch (error) { + return fail(reply, error); + } + } + ); + + app.get(`${base}/connect`, async () => ({ + requests: (await deps.runners?.listConnectRequests()) ?? [], + })); + + app.post(`${base}/connect/:id/approve`, async (request, reply) => { + const { id } = request.params as { id: string }; + if (!deps.runners) + return reply.code(404).send({ error: "Connect request not found." }); + const body = (request.body ?? {}) as { + code?: unknown; + name?: unknown; + }; + try { + return reply + .code(201) + .send( + await deps.runners.approveConnectRequest( + id, + body.code, + body.name, + hostHint(request.headers.host) + ) + ); + } catch (error) { + return fail(reply, error); + } + }); + + app.delete(`${base}/connect/:id`, async (request, reply) => { + const { id } = request.params as { id: string }; + if (!deps.runners) + return reply.code(404).send({ error: "Connect request not found." }); + try { + await deps.runners.denyConnectRequest(id); + return { ok: true }; + } catch (error) { + return fail(reply, error); + } + }); } } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 772896ca4..58638f17b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -933,6 +933,11 @@ async function registerRoutes() { if (request.routeOptions.config.browserExtensionBearer) return; // The menu app's control routes check its per-launch token themselves. if (request.routeOptions.config.macAppBearer) return; + // Runner-initiated enrollment: the runner has no Dispatch credentials + // until an operator approves it. These routes gate themselves with a + // short, bounded-attempt code and a key-bound certificate; approval and + // denial are ordinary authenticated routes alongside them. + if (request.routeOptions.config.runnerConnectBootstrap) return; // The recovery helper authenticates with its enrollment key, loopback-only. if (request.routeOptions.config.updateRecovery) return; // If no password is set, all routes are open (first-run mode). diff --git a/apps/server/test/migrations.test.ts b/apps/server/test/migrations.test.ts index e4d1efff5..4b06fe5cf 100644 --- a/apps/server/test/migrations.test.ts +++ b/apps/server/test/migrations.test.ts @@ -88,10 +88,10 @@ async function dropTasks(): Promise { "DELETE FROM pgmigrations WHERE name = '0052_remote_host_event'" ); await pool.query( - "DROP TABLE IF EXISTS runner_registrations, runner_authority" + "DROP TABLE IF EXISTS runner_connect_requests, runner_registrations, runner_authority" ); await pool.query( - "DELETE FROM pgmigrations WHERE name IN ('0053_runner_registrations', '0055_runner_health')" + "DELETE FROM pgmigrations WHERE name IN ('0053_runner_registrations', '0054_runner_connect_requests', '0055_runner_health')" ); await pool.query( "DELETE FROM pgmigrations WHERE name = '0051_attention_stream_events'" diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts new file mode 100644 index 000000000..2c82cacd0 --- /dev/null +++ b/apps/server/test/remote-runner-connect.test.ts @@ -0,0 +1,253 @@ +import { X509Certificate } from "node:crypto"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import { connect, type TLSSocket } from "node:tls"; +import type { Pool } from "pg"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { RunnerRegistry } from "../src/agents/remote/registry.js"; +import { RemoteRunnerService } from "../src/agents/remote/service.js"; +import { + generateRunnerKey, + runnerPublicKey, +} from "../src/agents/remote/x509.js"; +import { wireFrames, type Frame } from "../src/agents/remote/protocol.js"; +import { runTestMigrations, setupTestDb, teardownTestDb } from "./db/setup.js"; + +const HOST = "127.0.0.1"; + +type FakeRunner = { + socket: TLSSocket; + closed: Promise; +}; + +function dialRunner(input: { + endpoint: string; + ca: string; + cert: string; + key: string; + workspaces: string[]; +}): Promise { + const url = new URL(input.endpoint); + return new Promise((resolve, reject) => { + const socket = connect({ + host: url.hostname, + port: Number(url.port), + ca: input.ca, + cert: input.cert, + key: input.key, + rejectUnauthorized: true, + }); + const closed = new Promise((done) => socket.on("close", done)); + socket.on("error", reject); + const send = wireFrames(socket, () => {}); + socket.once("secureConnect", () => { + send({ + type: "ready", + version: 1, + workspaces: input.workspaces, + } as Frame); + resolve({ socket, closed }); + }); + }); +} + +async function waitFor(check: () => boolean | Promise) { + for (let i = 0; i < 150; i++) { + if (await check()) return; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + throw new Error("condition not reached"); +} + +describe("runner-initiated connect enrollment", () => { + let pool: Pool; + let api: http.Server; + const services: RemoteRunnerService[] = []; + const runners: FakeRunner[] = []; + + const makeService = () => { + const service = new RemoteRunnerService( + undefined, + { registry: new RunnerRegistry(pool), host: HOST, endpointHost: HOST }, + { + host: HOST, + port: (api.address() as AddressInfo).port, + tls: false, + } + ); + services.push(service); + return service; + }; + + beforeAll(async () => { + pool = await setupTestDb(); + await runTestMigrations(); + api = http.createServer((_request, response) => response.end("api")); + await new Promise((resolve) => api.listen(0, HOST, resolve)); + }, 60_000); + + afterEach(async () => { + for (const runner of runners.splice(0)) runner.socket.destroy(); + for (const service of services.splice(0)) service.close(); + await pool.query("DELETE FROM runner_connect_requests"); + await pool.query("DELETE FROM runner_registrations"); + await pool.query("DELETE FROM runner_authority"); + }); + + afterAll(async () => { + api?.close(); + await teardownTestDb(); + }); + + it("creates a pending request the runner can poll before approval", async () => { + const service = makeService(); + const { publicKey } = generateRunnerKey(); + const created = await service.createConnectRequest( + publicKey, + `${HOST}:9999` + ); + expect(created.id).toMatch(/^conn_/); + expect(created.code).toMatch(/^[0-9A-Z]{4}-[0-9A-Z]{4}$/); + expect(created.approveUrl).toBe( + `https://${HOST}:9999/settings/connections` + ); + expect(new Date(created.expiresAt).getTime()).toBeGreaterThan(Date.now()); + + expect(await service.pollConnectRequest(created.id)).toEqual({ + status: "pending", + }); + const pending = await service.listConnectRequests(); + expect(pending).toEqual([ + { + id: created.id, + createdAt: expect.any(String), + expiresAt: created.expiresAt, + }, + ]); + }); + + it("rejects a malformed public key", async () => { + const service = makeService(); + await expect( + service.createConnectRequest("not a key", undefined) + ).rejects.toMatchObject({ status: 400 }); + }); + + it("approves with the correct code, binds the key, and lets the runner connect", async () => { + const service = makeService(); + const { key, publicKey } = generateRunnerKey(); + const created = await service.createConnectRequest(publicKey); + + const approved = await service.approveConnectRequest( + created.id, + created.code, + "alpha", + HOST + ); + expect(approved.name).toBe("alpha"); + expect(approved.id).toMatch(/^rnr_[a-f0-9]+$/); + + const polled = await service.pollConnectRequest(created.id); + expect(polled).toMatchObject({ + status: "approved", + id: approved.id, + name: "alpha", + }); + const { cert, ca, endpoint } = polled as Extract< + typeof polled, + { status: "approved" } + >; + // Key-bound: the issued leaf is for the key submitted at request time. + const leaf = new X509Certificate(cert); + expect( + leaf.publicKey.export({ type: "spki", format: "pem" }).toString() + ).toBe(publicKey); + expect(leaf.subject).toBe(`CN=${approved.id}`); + + // Repeated polls after approval are idempotent. + expect(await service.pollConnectRequest(created.id)).toEqual(polled); + + runners.push( + await dialRunner({ endpoint, ca, cert, key, workspaces: ["proof"] }) + ); + await waitFor(() => + service.available({ runner: approved.id, workspace: "proof" }) + ); + }); + + it("rejects an unsupported key before any code exists", () => { + expect(() => runnerPublicKey("not a key")).toThrow(); + }); + + it("bounds wrong-code attempts and then voids the request", async () => { + const service = makeService(); + const { publicKey } = generateRunnerKey(); + const created = await service.createConnectRequest(publicKey); + + for (let attempt = 0; attempt < 4; attempt++) { + await expect( + service.approveConnectRequest(created.id, "0000-0000", "alpha", HOST) + ).rejects.toMatchObject({ status: 400 }); + } + // The 5th wrong attempt voids the request outright. + await expect( + service.approveConnectRequest(created.id, "0000-0000", "alpha", HOST) + ).rejects.toMatchObject({ status: 404 }); + // Even the correct code no longer works. + await expect( + service.approveConnectRequest(created.id, created.code, "alpha", HOST) + ).rejects.toMatchObject({ status: 404 }); + expect(await service.pollConnectRequest(created.id)).toEqual({ + status: "denied", + }); + }); + + it("rejects duplicate names the same way ordinary registration does", async () => { + const service = makeService(); + await service.createRegistration("dup"); + const { publicKey } = generateRunnerKey(); + const created = await service.createConnectRequest(publicKey); + await expect( + service.approveConnectRequest(created.id, created.code, "dup", HOST) + ).rejects.toMatchObject({ status: 409 }); + }); + + it("denies a pending request and stops the runner's poll from ever approving", async () => { + const service = makeService(); + const { publicKey } = generateRunnerKey(); + const created = await service.createConnectRequest(publicKey); + await service.denyConnectRequest(created.id); + expect(await service.pollConnectRequest(created.id)).toEqual({ + status: "denied", + }); + await expect( + service.approveConnectRequest(created.id, created.code, "alpha", HOST) + ).rejects.toMatchObject({ status: 404 }); + }); + + it("reports an expired request once its code has timed out", async () => { + const service = makeService(); + const { publicKey } = generateRunnerKey(); + const created = await service.createConnectRequest(publicKey); + await pool.query( + `UPDATE runner_connect_requests SET code_expires_at = now() - interval '1 minute' WHERE id = $1`, + [created.id] + ); + expect(await service.pollConnectRequest(created.id)).toEqual({ + status: "expired", + }); + await expect( + service.approveConnectRequest(created.id, created.code, "alpha", HOST) + ).rejects.toMatchObject({ status: 404 }); + }); + + it("404s approving or denying an unknown request id", async () => { + const service = makeService(); + await expect( + service.approveConnectRequest("conn_missing", "x", "alpha", HOST) + ).rejects.toMatchObject({ status: 404 }); + await expect( + service.denyConnectRequest("conn_missing") + ).rejects.toMatchObject({ status: 404 }); + }); +}); diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 8f82c7fe6..020df9387 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -103,6 +103,42 @@ comma list of `` or `/`. `DISPATCH_REMOTE_SERVICE_CONFIG` below still works. Its `mcpOrigin` is now optional when `endpointHost` is given. +## Runner-initiated enrollment + +`dispatch-runner connect --service https://HOST:PORT [--ca-sha256 HEX] +[--dir /etc/dispatch-runner] [--config FILE]` enrolls without a pairing +command typed on the runner: the runner dials the Dispatch service itself. +It generates its keypair locally (the private key never leaves the host, as +with the operator-initiated flow above) and `POST /api/runners/connect` +with only its public key. The service returns a short operator-facing code, +an opaque high-entropy request id for the CLI's own polling, and, when the +request carried a usable `Host` header, an `approveUrl` pointing at +**Settings → Connections → Remote runners** on that same origin. The CLI +prints the code and URL and polls `GET /api/runners/connect/:id` (addressed +only by that same opaque id) until an operator approves it. + +The operator reads the code off the runner's own terminal or logs — it is +never sent back by the runner — and calls the authenticated +`POST /api/runners/connect/:id/approve {code, name}`. Approval is key-bound: +it issues a client certificate only for the public key submitted when the +request was created, so a code observed or guessed in transit can never +redeem a different key. The code is a 10-minute, 8-character one-time value; +five wrong attempts void the request outright, forcing the runner to connect +again. `DELETE /api/runners/connect/:id` denies a pending request. +`GET /api/runners/connect` (authenticated) lists pending requests without +exposing their code or key. + +Approval issues the same kind of mTLS client certificate as pairing above, +automatically and without a second step, and the poll response that follows +carries the certificate, the CA, and the `endpoint` to dial — the same +`runner.json` fields `remote-runner-pair` writes. `--ca-sha256` pins the +service's certificate chain for a self-signed deployment; unlike pairing, +pinning happens inside the single connection that carries the actual +request — nothing is written to the socket until the presented chain +matches, and there is no separate unauthenticated round trip first. Without +`--ca-sha256`, the service is expected to hold an ordinarily trusted +certificate. + ## Legacy manual enrollment Set `DISPATCH_REMOTE_SERVICE_CONFIG` on an isolated Dispatch service. The From 06a600d92c8689912dcf4a5b9b11136ff01a81c9 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 08:55:52 -0700 Subject: [PATCH 041/642] Start the managed runner after successful enrollment --- apps/server/test/pack-release.test.ts | 1 + bin/dispatch-runner | 19 +++++++++++++ bin/install-dispatch-runner.sh | 8 ++++-- docs/remote-runner-linux.md | 8 ++++-- scripts/remote-runner/test-installer.sh | 38 +++++++++++++++++-------- 5 files changed, 57 insertions(+), 17 deletions(-) create mode 100755 bin/dispatch-runner diff --git a/apps/server/test/pack-release.test.ts b/apps/server/test/pack-release.test.ts index 74f769543..f57925950 100644 --- a/apps/server/test/pack-release.test.ts +++ b/apps/server/test/pack-release.test.ts @@ -56,6 +56,7 @@ describe.skipIf(!BUILDS_EXIST)("pack-release", () => { expect(files.some((f) => f.startsWith("bin/"))).toBe(true); expect(files).toContain("bin/install-dispatch.sh"); expect(files).toContain("bin/install-dispatch-runner.sh"); + expect(files).toContain("bin/dispatch-runner"); expect(files).toContain("bin/dispatch-runner.service"); }); diff --git a/bin/dispatch-runner b/bin/dispatch-runner new file mode 100755 index 000000000..f8dbaf9a4 --- /dev/null +++ b/bin/dispatch-runner @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Public entry point for the managed Linux installation. +set -euo pipefail + +runtime=$(dirname "$(readlink -f "$0")") +if [[ "${1:-}" != connect ]]; then + exec "$runtime/dispatch" "$@" +fi +# Custom config paths are managed by the caller. The unit always reads the +# managed config, so enrolling a different one must not start this unit. +for argument in "${@:2}"; do + case "$argument" in + -h|--help|--dir|--dir=*|--config|--config=*) exec "$runtime/dispatch" "$@" ;; + esac +done +exec 9>"$runtime/install.lock" +flock -n 9 || { printf 'Another runner install, update, or connection is running.\n' >&2; exit 1; } +"$runtime/dispatch" "$@" +systemctl enable --now dispatch-runner.service diff --git a/bin/install-dispatch-runner.sh b/bin/install-dispatch-runner.sh index e9a14f3d8..8b412acb5 100755 --- a/bin/install-dispatch-runner.sh +++ b/bin/install-dispatch-runner.sh @@ -80,7 +80,7 @@ CONFIG install_runner() { local account_entry account_home account_shell if [[ -e "$command_path" || -L "$command_path" ]]; then - [[ -L "$command_path" && "$(readlink "$command_path")" == "$runtime/dispatch" ]] || + [[ -L "$command_path" && "$(readlink "$command_path")" == "$runtime/runner-cli" ]] || error "Another dispatch-runner command already occupies $command_path" fi if [[ ! -f "$runtime/managed-install" ]]; then @@ -125,11 +125,15 @@ install_runner() { [[ -s "$stage/updater" ]] || error "Missing updater from $tag" chmod 0755 "$stage/updater" mv -fT "$stage/updater" "$runtime/install-dispatch-runner.sh" + tar -xOzf "$stage/dispatch-server.tar.gz" bin/dispatch-runner > "$stage/runner-cli" + [[ -s "$stage/runner-cli" ]] || error "Missing runner command from $tag" + chmod 0755 "$stage/runner-cli" + mv -fT "$stage/runner-cli" "$runtime/runner-cli" if [[ ! -L "$command_path" ]]; then if [[ ! -d "$(dirname "$command_path")" ]]; then install -d -m 0755 "$(dirname "$command_path")" fi - ln -s "$runtime/dispatch" "$command_path" + ln -s "$runtime/runner-cli" "$command_path" fi systemctl daemon-reload printf 'Runner installed. Use the connect command from Dispatch Settings to enroll.\n' diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index 8933234fc..b3c8736b0 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -18,9 +18,11 @@ The runner must be able to reach the HTTPS address in the pairing command. sudo dispatch-runner connect --service 'https://dispatch.example' ``` - Enter the code shown in the terminal into Dispatch and approve the - connection there. The CLI completes enrollment and starts the service - after approval. Wait for **Online** in Settings. + Add `--ca-sha256 HEX` if Settings includes a CA fingerprint for a + privately trusted service. Enter the code shown in the terminal into + Dispatch and approve the connection there. The installed command enables + and starts the service once enrollment succeeds. Wait for **Online** in + Settings. 3. Install the engines you plan to use according to their Linux instructions. The default runner configuration looks for `claude`, `codex`, and diff --git a/scripts/remote-runner/test-installer.sh b/scripts/remote-runner/test-installer.sh index 7ea5e03d9..fdbe4991b 100755 --- a/scripts/remote-runner/test-installer.sh +++ b/scripts/remote-runner/test-installer.sh @@ -48,6 +48,12 @@ systemctl() { fi : > "$root/running" ;; + enable) + [[ "$*" == 'enable --now dispatch-runner.service' ]] || return 1 + [[ -s "$settings/key.pem" && -s "$settings/cert.pem" && -s "$settings/ca.pem" ]] || return 1 + : > "$root/enabled" + : > "$root/running" + ;; is-active) [[ -e "$root/running" ]];; is-enabled) if [[ -e "$root/enabled" ]]; then @@ -105,9 +111,15 @@ mv() { } sleep() { :; } sync() { :; } +flock() { [[ "$*" == '-n 9' ]]; } case "$action" in install) stage_release; install_runner ;; + connect) + export root settings + export -f systemctl flock + "$command_path" connect --service "$tag" + ;; *) update_runner ;; esac HARNESS @@ -115,7 +127,7 @@ HARNESS openssl genrsa -out "$root/private.pem" 2048 2>/dev/null openssl rsa -in "$root/private.pem" -pubout -out "$root/public.pem" 2>/dev/null mkdir -p "$root/archive/dist/bun" "$root/archive/bin" -cp bin/{dispatch-runner.service,install-dispatch-runner.sh,pack-release} "$root/archive/bin/" +cp bin/{dispatch-runner,dispatch-runner.service,install-dispatch-runner.sh,pack-release} "$root/archive/bin/" touch "$root/archive/README.md" "$root/archive/.env.example" for version in 1.0.0 1.0.1; do release="$root/releases/v$version" @@ -123,8 +135,10 @@ for version in 1.0.0 1.0.1; do for arch in x64 arm64; do cat > "$root/archive/dist/bun/dispatch-$version-bun-linux-$arch" <<'RUNNER' #!/usr/bin/env bash -printf 'connect fixture binary\n' -exit 1 +[[ "$*" == 'connect --service https://dispatch.example' ]] || exit 1 +printf 'fixture-key\n' > "$settings/key.pem" +printf 'fixture-cert\n' > "$settings/cert.pem" +printf 'fixture-ca\n' > "$settings/ca.pem" RUNNER if [[ "$version" == 1.0.1 ]]; then printf '# release-new %s\n' "$arch" >> "$root/archive/dist/bun/dispatch-$version-bun-linux-$arch" @@ -150,7 +164,7 @@ expect_status() { run install v1.0.0 run install v1.0.0 -[[ "$(readlink "$root/bin/dispatch-runner")" == "$root/runtime/dispatch" ]] +[[ "$(readlink "$root/bin/dispatch-runner")" == "$root/runtime/runner-cli" ]] [[ ! -e "$root/running" && ! -e "$root/settings/key.pem" ]] ! grep -Eq '^(start|enable) ' "$root/systemctl" [[ "$(find "$root/settings/runner.json" -perm 0600 -print)" == "$root/settings/runner.json" ]] @@ -158,18 +172,18 @@ grep -q '"workspaces": {}' "$root/settings/runner.json" cp "$root/runtime/dispatch" "$root/original" run update v1.0.1 -grep -q 'release-new x64' "$root/bin/dispatch-runner" +grep -q 'release-new x64' "$root/runtime/dispatch" [[ ! -e "$root/running" && ! -e "$root/settings/key.pem" ]] -# Model a successful separate connect, with credentials and an enabled service. +# Verify the wrapper starts the service only after a successful connect. cp "$root/original" "$root/runtime/dispatch" -printf 'fixture-key\n' > "$root/settings/key.pem" -printf 'fixture-cert\n' > "$root/settings/cert.pem" -printf 'fixture-ca\n' > "$root/settings/ca.pem" -: > "$root/enabled" -: > "$root/running" +expect_status 1 connect https://unapproved.example +[[ ! -e "$root/running" && ! -e "$root/enabled" ]] +run connect https://dispatch.example +[[ $(grep -c '^enable --now ' "$root/systemctl") == 1 ]] +[[ -e "$root/running" && -e "$root/enabled" ]] run install v1.0.0 -! grep -Eq '^(start|enable) ' "$root/systemctl" +[[ $(grep -c '^enable --now ' "$root/systemctl") == 1 ]] cp -R "$root/settings" "$root/original-settings" : > "$root/busy" From e6a1a85d9f6d079586d5cfc56e63f7d5ac4fad59 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 08:59:51 -0700 Subject: [PATCH 042/642] Approve runner requests and select a Dispatch project on remote launches --- .../components/app/create-agent-dialog.tsx | 35 ++++++++++++++-- .../src/components/app/runner-onboarding.tsx | 40 ++++++++++++++----- apps/web/src/components/app/runner-picker.tsx | 5 +-- .../src/components/app/runner-settings.tsx | 12 +++--- .../app/use-create-agent-form.test.tsx | 1 + .../components/app/use-create-agent-form.ts | 24 ++++++++--- apps/web/src/hooks/use-runners.ts | 1 + 7 files changed, 87 insertions(+), 31 deletions(-) diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index d9fc41d39..0ea854648 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -1,4 +1,3 @@ -import { MANAGED_WORKSPACE } from "@dispatch/runner-protocol"; import { RunnerRepositoryFields } from "./runner-repository-fields"; import { taskAgentName } from "@dispatch/shared"; import { ProjectLocation } from "./project-location"; @@ -26,6 +25,13 @@ import { DialogHeader, DialogTitle, } from "@/components/ui/dialog"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; import { Input } from "@/components/ui/input"; import { type Agent } from "@/components/app/types"; import { useRadixPopoverZFix } from "@/hooks/use-radix-popover-z-fix"; @@ -157,9 +163,7 @@ function CreateAgentDialogContent({ - r.workspaces.includes(MANAGED_WORKSPACE) - ) + ? form.runners.filter((r) => r.managedWorkspace) : form.runners } runnerId={form.runnerId} @@ -168,6 +172,29 @@ function CreateAgentDialogContent({ workspace={form.runnerWorkspace} onWorkspaceChange={form.setRunnerWorkspace} /> + {form.managedSession && !task && form.projects.length > 0 && ( +
+ + +
+ )} {form.managedSession && ( api( - "/api/v1/runners/pairing-requests/" + + "/api/v1/runners/connect/" + encodeURIComponent(request.id) + "/approve", { @@ -65,6 +65,14 @@ function ApproveRunner({ request }: { request: PairRequest }) { ]); }, }); + const dismiss = useMutation({ + mutationFn: () => + api("/api/v1/runners/connect/" + encodeURIComponent(request.id), { + method: "DELETE", + }), + onSuccess: () => + queryClient.invalidateQueries({ queryKey: ["runner-pairing-requests"] }), + }); return (
-

Approve {request.hostname}

+

+ Connection request · {request.id.slice(-8)} +

- Enter the code printed on that machine to grant it access. + Match the request reference and enter the code printed on the runner.

{runner.status !== "revoked" && (confirmId === runner.id ? ( diff --git a/apps/web/src/components/app/use-create-agent-form.test.tsx b/apps/web/src/components/app/use-create-agent-form.test.tsx index b0cf2dbb5..f955bec6e 100644 --- a/apps/web/src/components/app/use-create-agent-form.test.tsx +++ b/apps/web/src/components/app/use-create-agent-form.test.tsx @@ -217,6 +217,7 @@ describe("launch location preference", () => { name: "Lima", status: "online", workspaces: ["@session"], + managedWorkspace: true, }, ] ); diff --git a/apps/web/src/components/app/use-create-agent-form.ts b/apps/web/src/components/app/use-create-agent-form.ts index bfc5c3c8c..5fda1803b 100644 --- a/apps/web/src/components/app/use-create-agent-form.ts +++ b/apps/web/src/components/app/use-create-agent-form.ts @@ -80,8 +80,7 @@ export function useCreateAgentForm({ const remote = Boolean(runnerId); const runnerUnavailable = remote && (!runner || runner.status === "revoked"); // Only a workspace the runner reports now, on an online runner, can submit. - const managedSession = - runner?.workspaces.includes(MANAGED_WORKSPACE) ?? false; + const managedSession = runner?.managedWorkspace === true; const runnerWorkspace = managedSession ? MANAGED_WORKSPACE : runner && pickedWorkspace && runner.workspaces.includes(pickedWorkspace) @@ -102,12 +101,17 @@ export function useCreateAgentForm({ const [locationChoice, setLocationChoice] = useState<{ projectId: string | null; } | null>(null); + const [runnerProjectId, setRunnerProjectId] = useState< + string | null | undefined + >(undefined); const selectedProjectId = task ? task.projectId - : locationChoice - ? locationChoice.projectId - : (initialProjectId ?? - (locationPref?.mode === "project" ? locationPref.projectId : null)); + : managedSession && runnerProjectId !== undefined + ? runnerProjectId + : locationChoice + ? locationChoice.projectId + : (initialProjectId ?? + (locationPref?.mode === "project" ? locationPref.projectId : null)); const project = projects.find((p) => p.id === selectedProjectId); // Keep a pending choice while loading, but never submit an unavailable ID. const createProjectId = @@ -153,6 +157,13 @@ export function useCreateAgentForm({ ? Boolean(remoteCwd) && repoReady && (!selectedProjectId || projectsLoaded) : !selectedProjectId || projectsLoaded; const setCreateProjectId = (id: string | null) => { + if (managedSession) { + setRunnerProjectId(id); + setChosenRepo(null); + setBranchMode("new"); + setRunnerBranch(""); + return; + } setLocationChoice({ projectId: id }); setLocationPref({ mode: id ? "project" : "folder", @@ -494,6 +505,7 @@ export function useCreateAgentForm({ ); return { + projects, runners, runnerId, runnerUnavailable, diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index 47ebe26fd..89b39fba0 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -10,6 +10,7 @@ export type Runner = { name: string; status: RunnerStatus; workspaces: string[]; + managedWorkspace?: true; health?: RunnerHealth; healthReceivedAt?: string; }; From 1e8e7a079143e522052a507db4ba1eedf53c3d8b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:02:48 -0700 Subject: [PATCH 043/642] Explain runner session cleanup at launch and archive --- apps/web/src/components/app/delete-agent-dialog.tsx | 8 +++++--- apps/web/src/components/app/runner-repository-fields.tsx | 4 ++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/app/delete-agent-dialog.tsx b/apps/web/src/components/app/delete-agent-dialog.tsx index 02ab30c48..ac16951cf 100644 --- a/apps/web/src/components/app/delete-agent-dialog.tsx +++ b/apps/web/src/components/app/delete-agent-dialog.tsx @@ -243,9 +243,11 @@ export function DeleteAgentDialog({ Archive Agent - {deleteTarget - ? `Archive "${deleteTarget.name}"? This removes the agent record and all files.${cascadeNote}` - : "Archive this agent?"} + {deleteTarget?.runnerManaged + ? `Archive "${deleteTarget.name}"? The runner will delete its session folder, including uncommitted files. If the runner is offline, cleanup happens when it reconnects.${cascadeNote}` + : deleteTarget + ? `Archive "${deleteTarget.name}"? This removes the agent record and all files.${cascadeNote}` + : "Archive this agent?"}
diff --git a/apps/web/src/components/app/runner-repository-fields.tsx b/apps/web/src/components/app/runner-repository-fields.tsx index 98d78ac51..243b8776f 100644 --- a/apps/web/src/components/app/runner-repository-fields.tsx +++ b/apps/web/src/components/app/runner-repository-fields.tsx @@ -159,6 +159,10 @@ export function RunnerRepositoryFields({ } /> +

+ Archiving removes the session worktree. Commit and push changes you + want to keep. +

)} From 8d5cabad7f3dde322979a640c84552f42fe867e3 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:04:05 -0700 Subject: [PATCH 044/642] Check health and workspace capabilities together at runner startup --- apps/server/test/remote-runner-startup.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/server/test/remote-runner-startup.test.ts b/apps/server/test/remote-runner-startup.test.ts index 1175bdaeb..ce45ec570 100644 --- a/apps/server/test/remote-runner-startup.test.ts +++ b/apps/server/test/remote-runner-startup.test.ts @@ -182,11 +182,13 @@ describe("remote runner startup", () => { try { await vi.waitFor(() => expect(dial).toHaveBeenCalledTimes(1)); socket.emit("secureConnect"); - expect(JSON.parse(socket.write.mock.calls[0]![0])).toEqual({ + const ready = JSON.parse(socket.write.mock.calls[0]![0]); + expect(ready.managedWorkspace).toBe(managed ? true : undefined); + expect(ready).toMatchObject({ type: "ready", version: 1, workspaces: handles, - ...(managed ? { managedWorkspace: true } : {}), + health: true, }); socket.emit( "data", From b2ee8807f92e4b454ce0933430ba534eba9cd8a4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:05:05 -0700 Subject: [PATCH 045/642] Exercise runner-initiated approval and managed scratch in E2E --- e2e/remote-runner/acceptance.spec.ts | 119 +++++++++++++++++--- e2e/remote-runner/entrypoint.sh | 15 +-- e2e/remote-runner/harness.ts | 155 ++++++++++++++++----------- e2e/remote-runner/setup.mjs | 40 ++++--- scripts/e2e-remote-runners.sh | 3 +- 5 files changed, 228 insertions(+), 104 deletions(-) diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index b98aeedd2..b16a193a4 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -3,9 +3,9 @@ import { authHeaders, cleanupE2EAgents } from "../helpers"; import { agentInfo, chat, - createPairing, enrollViaUi, revokeViaUi, + guest, guestOk, invocations, lane, @@ -14,10 +14,11 @@ import { marker, newSettledTurn, runnerOptionEnabled, - pairInContainer, + requestConnection, runnerRow, runnerRows, state, + settledTurns, type RunnerName, } from "./harness"; @@ -41,6 +42,9 @@ test.beforeAll(() => { }); test.afterAll(async ({ request }) => { await cleanupE2EAgents(request); + await Promise.all( + Object.values(pages).map((page) => page?.context().close()) + ); }); const text = (p: Page) => p.locator("body"); @@ -62,6 +66,7 @@ test("enroll two runners with identical workspace names", async ({ }); test("UI launches local, alpha and beta; each answer comes from its own side", async ({ + baseURL, browser, }, testInfo) => { for (const [key, prompt] of [ @@ -69,7 +74,7 @@ test("UI launches local, alpha and beta; each answer comes from its own side", a ["alpha", "prove-marker proof-count"], ["beta", "prove-marker proof-count"], ] as const) { - const page = await (await browser.newContext()).newPage(); + const page = await (await browser.newContext({ baseURL })).newPage(); pages[key] = page; const { status, id } = await launchViaUi( page, @@ -247,20 +252,40 @@ test("revoke alpha: it cannot return, beta and local are unaffected", async ({ // ---------------------------------------------------------------- failures test.describe("failure suite", () => { - test("pairing codes are single-use and wrong codes are refused", async ({ + test("approval codes are single-use and wrong codes are refused", async ({ + page, request, }) => { - const { body } = await createPairing(request, "gamma"); - expect(body).not.toBeNull(); - const bad = body!.command.replace(/--code\s+\S+/, "--code WRONGCODE"); - expect(() => pairInContainer("beta", bad)).toThrow(); - // Pair the unused code into a throwaway dir so beta's live credentials stay intact. - pairInContainer("beta", body!.command, "/tmp/gamma-creds"); - expect(() => - pairInContainer("beta", body!.command, "/tmp/gamma-creds-2") - ).toThrow(); // replay - const row = await runnerRow(request, "gamma"); - expect(["pending", "online", "offline"]).toContain(row?.status); + const { form, code, finished } = await requestConnection( + page, + "beta", + "/tmp/gamma-creds" + ); + await form.getByLabel("Runner name").fill("gamma"); + const approve = async (value: string) => { + await form.getByLabel("Pairing code").fill(value); + const response = page.waitForResponse( + (r) => + r.request().method() === "POST" && + new URL(r.url()).pathname.endsWith("/approve") + ); + await form.getByRole("button", { name: "Approve runner" }).click(); + return response; + }; + expect((await approve("WRONGCODE")).status()).toBeGreaterThanOrEqual(400); + await expect(form.getByRole("alert")).toBeVisible(); + const approved = await approve(code); + expect(approved.ok(), await approved.text()).toBe(true); + expect(await finished).toBe(true); + await expect(form).toHaveCount(0); + const replay = await request.post(approved.url(), { + headers: authHeaders(), + data: { name: "gamma", code }, + }); + expect(replay.status()).toBeGreaterThanOrEqual(400); + expect( + (await runnerRows(request)).filter((row) => row.name === "gamma") + ).toHaveLength(1); }); test("unknown runner and workspace are refused; revoked runner is not selectable", async ({ @@ -326,3 +351,67 @@ test.describe("failure suite", () => { .toBe("online"); }); }); + +test("managed scratch launch reports health and archive removes the guest session folder", async ({ + page, + request, +}, testInfo) => { + const runnerId = await enrollViaUi(page, request, "scratch"); + expect((await runnerRow(request, "scratch"))?.workspaces).toEqual([ + "@session", + ]); + const { status, id } = await launchViaUi(page, { + name: "e2e-rr-managed-scratch", + runnerId, + managedScratch: true, + prompt: "proof-count scratch-start", + }); + expect(status).toBe(201); + expect(id).toMatch(/^agt_[a-z0-9]+$/); + expect((await agentInfo(request, id!)).cwd).toBe( + `runner://${runnerId}/@session` + ); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + await expect( + settledTurns(page).last().getByTestId("harness-result") + ).toContainText("Local or guest fixture turn completed."); + const directory = `/var/lib/runner/sessions/${id}`; + expect(guest("scratch", `stat -c '%u:%g %a' ${directory}`).trim()).toBe( + "1500:1500 700" + ); + expect(guest("scratch", `cat ${directory}/provider-invocations`).trim()).toBe( + "called" + ); + + await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + const health = page + .getByTestId(`runner-${runnerId}`) + .getByTestId("runner-health"); + const summary = health.locator("summary"); + await expect(summary).toContainText("1 session", { timeout: 45_000 }); + await summary.click(); + await expect(health.getByText("Memory", { exact: true })).toBeVisible(); + await expect( + health.getByText("Runner version", { exact: true }) + ).toBeVisible(); + await testInfo.attach("managed scratch health", { + body: await page.getByTestId(`runner-${runnerId}`).screenshot(), + contentType: "image/png", + }); + + await page.goto("/", { waitUntil: "domcontentloaded" }); + const archive = page.getByTestId(`agent-archive-${id}`); + if (!(await archive.isVisible())) + await page.getByTestId(`agent-expand-toggle-${id}`).click(); + await archive.click(); + await expect( + page.getByRole("dialog", { name: "Archive Agent" }) + ).toContainText("The runner will delete its session folder"); + await page.getByTestId("delete-agent-confirm").click(); + await expect(page.getByTestId(`agent-card-${id}`)).toHaveCount(0); + await expect + .poll(() => guestOk("scratch", `test ! -e ${directory}`), { + timeout: 30_000, + }) + .toBe(true); +}); diff --git a/e2e/remote-runner/entrypoint.sh b/e2e/remote-runner/entrypoint.sh index ae9aed8fb..43977bb6b 100755 --- a/e2e/remote-runner/entrypoint.sh +++ b/e2e/remote-runner/entrypoint.sh @@ -1,14 +1,17 @@ #!/bin/sh # Container entrypoint: stage a pre-provisioned guest workspace with a -# runner-unique marker and a writable runner.json, then idle. The harness -# pairs and starts the runner with `docker exec` so tests control timing. +# runner-unique marker for configured runners, then idle. The harness +# connects and starts the runners with `docker exec` so tests control timing. set -eu NAME="$1" install -d -m 700 /run/cfg /var/lib/runner install -d -m 755 /home/guest /etc/dispatch-runner cp /etc/runner/runner.json /run/cfg/runner.json && chmod 600 /run/cfg/runner.json -WS="/opt/dispatch-guest-$NAME-proof" -mkdir -p "$WS" -echo "marker-$NAME-$(cat /proc/sys/kernel/random/uuid)" > "$WS/marker.txt" -chown -R 1500:1500 "$WS" /home/guest +if [ "$NAME" != scratch ]; then + WS="/opt/dispatch-guest-$NAME-proof" + mkdir -p "$WS" + echo "marker-$NAME-$(cat /proc/sys/kernel/random/uuid)" > "$WS/marker.txt" + chown -R 1500:1500 "$WS" +fi +chown 1500:1500 /home/guest exec sleep infinity diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 31c410bc7..2e155822d 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -1,16 +1,17 @@ -import { execFileSync } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { expect, type APIRequestContext, type Page } from "@playwright/test"; import { authHeaders, trackAgent } from "../helpers"; export type RunnerName = "alpha" | "beta"; +type GuestName = RunnerName | "scratch"; type State = { controlPort: number; runnerPort: number; endpointHost: string; workspace: string; runners: Record< - RunnerName, + GuestName, { container: string; proxyPort: number; workspaceDir: string } >; }; @@ -26,10 +27,10 @@ const docker = (...args: string[]) => execFileSync("docker", args, { encoding: "utf8" }); /** Run a shell command inside a runner container as root. */ -export function guest(name: RunnerName, script: string) { +export function guest(name: GuestName, script: string) { return docker("exec", state.runners[name].container, "sh", "-c", script); } -export function guestOk(name: RunnerName, script: string) { +export function guestOk(name: GuestName, script: string) { try { guest(name, script); return true; @@ -77,44 +78,84 @@ export async function runnerRows(request: APIRequestContext) { export const runnerRow = async (request: APIRequestContext, name: string) => (await runnerRows(request)).find((r) => r.name === name); -/** Route the runner's whole path (pairing and mTLS) through its chaos lane. */ -const viaLane = (name: RunnerName, command: string) => - command.replace( - /--endpoint\s+https:\/\/\S+/, - `--endpoint https://${state.endpointHost}:${state.runners[name].proxyPort}` - ); +async function connectCommand(page: Page) { + await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.getByRole("button", { name: "Add runner", exact: true }).click(); + const command = page.getByTestId("runner-connect-command"); + await expect(command).toContainText("dispatch-runner connect"); + return (await command.innerText()).trim(); +} -export async function createPairing(request: APIRequestContext, name: string) { - const res = await request.post(RUNNERS_API, { - headers: authHeaders(), - data: { name }, - }); - return { res, body: res.ok() ? await res.json() : null } as { - res: typeof res; - body: { id: string; command: string; expiresAt: string } | null; - }; +function commandOption(command: string, flag: string) { + const match = new RegExp(flag + " +(?:'([^']+)'|([^\\s]+))").exec(command); + return match?.[1] ?? match?.[2]; } -/** Pair inside the container (key generated there), then start the runner. */ -export function pairInContainer( - name: RunnerName, - command: string, +export async function requestConnection( + page: Page, + name: GuestName, dir = "/etc/dispatch-runner" ) { - const c = state.runners[name].container; - const pair = viaLane(name, command).replace( - /^dispatch-runner/, - "/opt/bin/dispatch-runner" - ); - return docker( + const command = await connectCommand(page); + const service = new URL(commandOption(command, "--service")!); + const pin = commandOption(command, "--ca-sha256"); + if (Number(service.port) === state.runnerPort) + service.port = String(state.runners[name].proxyPort); + const args = [ "exec", - c, - "sh", - "-c", - `${pair} --dir ${dir} ${dir === "/etc/dispatch-runner" ? "--config /run/cfg/runner.json" : ""} 2>&1` - ); + state.runners[name].container, + "/opt/bin/dispatch-runner", + "connect", + "--service", + service.href, + "--dir", + dir, + ...(pin ? ["--ca-sha256", pin] : []), + ...(dir === "/etc/dispatch-runner" + ? ["--config", "/run/cfg/runner.json"] + : []), + ]; + let output = ""; + let failure: Error | null = null; + const finished = new Promise((resolve) => { + const child = execFile( + "docker", + args, + { timeout: 75_000 }, + (error, _stdout, stderr) => { + failure = error + ? new Error(`Runner connect failed: ${stderr.trim() || error.code}`) + : null; + resolve(error === null); + } + ); + child.stdout?.on("data", (chunk: string) => { + output += chunk; + }); + }); + const pairingCode = () => /^Code: ([A-Z0-9_-]+)\r?$/im.exec(output)?.[1]; + await expect + .poll( + () => { + if (failure) throw failure; + return pairingCode(); + }, + { timeout: 20_000 } + ) + .toBeTruthy(); + const form = page.getByTestId("runner-approval"); + await expect(form).toHaveCount(1, { timeout: 15_000 }); + return { form, code: pairingCode()!, finished }; } -export function startRunner(name: RunnerName) { + +export function startRunner(name: GuestName) { + const proxyPort = state.runners[name].proxyPort; + // The approved config records the advertised service port. Redirect only + // that endpoint so chaos injection still covers the mTLS supervisor. + guest( + name, + `sed -i -E '/"endpoint":/s/:${state.runnerPort}"/:${proxyPort}"/' /run/cfg/runner.json && grep -q ':${proxyPort}"' /run/cfg/runner.json` + ); docker( "exec", "-d", @@ -124,20 +165,17 @@ export function startRunner(name: RunnerName) { "/opt/bin/dispatch-runner remote-runner /run/cfg/runner.json >/var/log/runner.log 2>&1" ); } -export const runnerLog = (name: RunnerName) => - guest(name, "cat /var/log/runner.log 2>/dev/null || true"); -/** Pair through Settings → Connections → Remote runners (the normal UI). */ export async function enrollViaUi( page: Page, request: APIRequestContext, - name: RunnerName + name: GuestName ) { - await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); - await page.getByTestId("runner-name-input").fill(name); - await page.getByTestId("runner-pair-submit").click(); - const command = (await page.getByTestId("runner-command").innerText()).trim(); - pairInContainer(name, command); + const { form, code, finished } = await requestConnection(page, name); + await form.getByLabel("Runner name").fill(name); + await form.getByLabel("Pairing code").fill(code); + await form.getByRole("button", { name: "Approve runner" }).click(); + expect(await finished).toBe(true); startRunner(name); await expect .poll(async () => (await runnerRow(request, name))?.status, { @@ -160,19 +198,6 @@ export async function revokeViaUi(page: Page, id: string) { }); } -export async function enroll(request: APIRequestContext, name: RunnerName) { - const { res, body } = await createPairing(request, name); - expect(res.ok(), await res.text()).toBe(true); - pairInContainer(name, body!.command); - startRunner(name); - await expect - .poll(async () => (await runnerRow(request, name))?.status, { - timeout: 30_000, - }) - .toBe("online"); - return body!.id; -} - /** Launch through the normal Create Agent dialog (Folder = runner locator). */ export async function launchViaUi( page: Page, @@ -180,6 +205,7 @@ export async function launchViaUi( name: string; cwd?: string; runnerId?: string; + managedScratch?: boolean; prompt: string; restricted?: boolean; } @@ -198,10 +224,17 @@ export async function launchViaUi( await page .getByTestId(`create-agent-runner-option-${opts.runnerId}`) .click(); - await page.getByTestId("create-agent-runner-workspace").click(); - await page - .getByRole("option", { name: state.workspace, exact: true }) - .click(); + if (opts.managedScratch) { + await expect( + page.getByTestId("create-agent-runner-workspace") + ).toHaveCount(0); + await expect(page.getByTestId("runner-repository")).toHaveValue(""); + } else { + await page.getByTestId("create-agent-runner-workspace").click(); + await page + .getByRole("option", { name: state.workspace, exact: true }) + .click(); + } } else await page.getByTestId("create-agent-cwd").fill(opts.cwd ?? "/tmp"); if (opts.restricted) { // "Start in full access mode" is on by default; permission prompts need it off. diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs index 94c834a99..36e168728 100644 --- a/e2e/remote-runner/setup.mjs +++ b/e2e/remote-runner/setup.mjs @@ -20,7 +20,7 @@ import { fileURLToPath } from "node:url"; const here = path.dirname(fileURLToPath(import.meta.url)); const root = path.resolve(here, "../.."); -const RUNNERS = ["alpha", "beta"]; +const RUNNERS = ["alpha", "beta", "scratch"]; const WORKSPACE = "proof"; // identical handle on every runner, on purpose // Colima/Docker Desktop share $HOME, not /tmp, with the VM; bind mounts must live here. export const base = @@ -43,21 +43,16 @@ const freePort = () => }); function artifacts(arch) { + const inputs = [ + "apps/server/src", + "apps/server/test/helpers", + "packages/runner-protocol", + "pnpm-lock.yaml", + ]; const hash = createHash("sha256") - .update( - sh( - "git", - ["ls-files", "-s", "apps/server/src", "apps/server/test/helpers"], - { cwd: root } - ) - ) - .update( - sh( - "git", - ["diff", "HEAD", "--", "apps/server/src", "apps/server/test/helpers"], - { cwd: root } - ) - ) + .update(sh("bun", ["--version"])) + .update(sh("git", ["ls-files", "-s", "--", ...inputs], { cwd: root })) + .update(sh("git", ["diff", "HEAD", "--", ...inputs], { cwd: root })) .digest("hex") .slice(0, 16); const dir = path.join(base, `bin-${arch}-${hash}`); @@ -132,12 +127,15 @@ async function up(run) { path: "/usr/local/bin:/usr/bin:/bin", bins: { claudeBin: "/bin/false", codexBin: null }, adapter: ["/opt/bin/remote-acp-fixture"], - workspaces: { - [WORKSPACE]: { - cwd: `/opt/dispatch-guest-${name}-proof`, - repoTool: ["/bin/sh", "-c", "echo ran > repo-op"], - }, - }, + workspaces: + name === "scratch" + ? {} + : { + [WORKSPACE]: { + cwd: `/opt/dispatch-guest-${name}-proof`, + repoTool: ["/bin/sh", "-c", "echo ran > repo-op"], + }, + }, }) ); copyFileSync( diff --git a/scripts/e2e-remote-runners.sh b/scripts/e2e-remote-runners.sh index 21a1ca167..9438d55af 100755 --- a/scripts/e2e-remote-runners.sh +++ b/scripts/e2e-remote-runners.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # Integrated remote-runner acceptance: local agent + two Docker-hosted runners -# with the same workspace name. Requires docker and bun. No VMs, no prod data. +# with the same workspace name, plus an independently enrolled scratch runner. +# Requires Docker and Bun. # pnpm run test:e2e:remote-runners [extra playwright args] set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" From e2cde799e8681c16a64fe0a37ca43f80c96b2cf2 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:09:41 -0700 Subject: [PATCH 046/642] Reuse release version comparison for runner updates --- apps/web/src/components/app/runner-health.tsx | 15 ++++----------- apps/web/src/components/app/runner-onboarding.tsx | 8 +++++++- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index 8e99aadec..90e173234 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -1,6 +1,7 @@ import { useState } from "react"; import { RunnerCommand, useRunnerInstaller } from "./runner-onboarding"; import type { Runner } from "@/hooks/use-runners"; +import { isVersionNewer } from "@/lib/tips/version-compare"; import { formatRelativeTime } from "@/lib/format"; const memory = (bytes: number) => @@ -13,19 +14,11 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) { const [open, setOpen] = useState(false); const installer = useRunnerInstaller(open); const tag = installer.data?.tag; - // Release tags are validated semantic versions at the service. - const numeric = (v: string) => v.replace(/^v/, "").split(".").map(Number); - const installed = numeric(health?.version ?? ""); - const firstDifference = - tag && - numeric(tag) - .map((n, i) => n - (installed[i] ?? 0)) - .find((d) => d !== 0); + if (!health || !healthReceivedAt) return null; const update = tag && - /^v?\d+\.\d+\.\d+$/.test(health?.version ?? "") && - Number(firstDifference) > 0; - if (!health || !healthReceivedAt) return null; + /^v?\d+\.\d+\.\d+$/.test(health.version) && + isVersionNewer(tag, health.version); const stale = runner.status !== "online" || Date.now() - Date.parse(healthReceivedAt) > 90_000; diff --git a/apps/web/src/components/app/runner-onboarding.tsx b/apps/web/src/components/app/runner-onboarding.tsx index d1bd1dbc8..257f0420c 100644 --- a/apps/web/src/components/app/runner-onboarding.tsx +++ b/apps/web/src/components/app/runner-onboarding.tsx @@ -78,7 +78,13 @@ function ApproveRunner({ request }: { request: PairRequest }) { className="space-y-2 rounded-md border border-primary/40 p-3" onSubmit={(e) => { e.preventDefault(); - if (name.trim() && code.trim() && !approve.isPending) approve.mutate(); + if ( + name.trim() && + code.trim() && + !approve.isPending && + !dismiss.isPending + ) + approve.mutate(); }} data-testid="runner-approval" > From db1234123440de5f257d2d36cf8f87a34e3537fa Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:10:48 -0700 Subject: [PATCH 047/642] Document procps requirement for Linux runner archive --- docs/design/remote-runner-prototype.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 020df9387..8c9e79954 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -53,7 +53,9 @@ clients that use `SSL_CERT_FILE`. There is a guest-local `adapter` override for the fake provider. Keep the enrollment key and runner settings root-only and the CA certificate readable by the CLI. The supervisor needs Linux util-linux `/usr/bin/setpriv` and permission to change identity and remove -capabilities (`CAP_SETUID`, `CAP_SETGID`, and `CAP_SETPCAP`). Before accepting execution commands, +capabilities (`CAP_SETUID`, `CAP_SETGID`, and `CAP_SETPCAP`). Install `procps` +to provide `ps` on the supervisor’s PATH for stopping agents and cleaning up +their processes during archive. Before accepting execution commands, the runner verifies the kernel-reported non-root UID/GID, empty supplementary groups, zero capabilities, and `no_new_privs` through the same wrapper used for both the ACP host and repo operations. The runner grants traversal on its From 7bc67c7b0b4f9d317e3db67687326d6536cd835c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:10:57 -0700 Subject: [PATCH 048/642] Give acceptance runners the process tools used during archive --- e2e/remote-runner/entrypoint.sh | 4 ++++ e2e/remote-runner/setup.mjs | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/e2e/remote-runner/entrypoint.sh b/e2e/remote-runner/entrypoint.sh index 43977bb6b..a47a01d83 100755 --- a/e2e/remote-runner/entrypoint.sh +++ b/e2e/remote-runner/entrypoint.sh @@ -4,6 +4,10 @@ # connects and starts the runners with `docker exec` so tests control timing. set -eu NAME="$1" +if ! command -v ps >/dev/null || ! command -v setpriv >/dev/null; then + echo "Runner fixture image needs procps and util-linux." >&2 + exit 1 +fi install -d -m 700 /run/cfg /var/lib/runner install -d -m 755 /home/guest /etc/dispatch-runner cp /etc/runner/runner.json /run/cfg/runner.json && chmod 600 /run/cfg/runner.json diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs index 36e168728..a7c5c4a2c 100644 --- a/e2e/remote-runner/setup.mjs +++ b/e2e/remote-runner/setup.mjs @@ -26,7 +26,8 @@ const WORKSPACE = "proof"; // identical handle on every runner, on purpose export const base = process.env.REMOTE_E2E_ROOT ?? path.join(process.env.HOME, ".cache", "dispatch-remote-e2e"); -const IMAGE = process.env.REMOTE_E2E_IMAGE ?? "debian:bookworm-slim"; +// The supervisor uses procps to reap engine descendants during archive. +const IMAGE = process.env.REMOTE_E2E_IMAGE ?? "node:22-bookworm"; const sh = (cmd, args, opts = {}) => execFileSync(cmd, args, { encoding: "utf8", From 01d6ed6b8c696257afba97a7af3ce1145b9805ce Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:11:35 -0700 Subject: [PATCH 049/642] Check required process and Git tools during runner installation --- bin/install-dispatch-runner.sh | 2 +- docs/remote-runner-linux.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/install-dispatch-runner.sh b/bin/install-dispatch-runner.sh index 8b412acb5..cfda7c4b2 100755 --- a/bin/install-dispatch-runner.sh +++ b/bin/install-dispatch-runner.sh @@ -267,7 +267,7 @@ main() { error "The managed runner needs systemd and cgroup v2" [[ -x /usr/bin/setpriv ]] || error "Install util-linux with /usr/bin/setpriv" if [[ "$action" != recover ]]; then - for command in curl gh tar; do + for command in curl gh tar ps find git; do command -v "$command" >/dev/null || error "Install $command" done fi diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index b3c8736b0..56549b440 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -2,7 +2,7 @@ Use a supported Dispatch release and a Linux x86-64 or ARM64 host with systemd, the unified cgroup v2 hierarchy, and systemd's `freeze` and `thaw` commands. -Install Bash, curl, tar, util-linux (including `/usr/bin/setpriv` and `flock`), +Install Git, procps (ps), findutils, Bash, curl, tar, util-linux (including `/usr/bin/setpriv` and `flock`), `useradd`, GNU coreutils, and a GitHub CLI with `gh attestation verify --bundle`. GitHub CLI verifies the published bundles without a GitHub login. The runner must be able to reach the HTTPS address in the pairing command. From a575dbf4f014426449622c896cb921b558f767ad Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:14:40 -0700 Subject: [PATCH 050/642] Expose engine management on runners that advertise support --- .../src/components/app/runner-settings.tsx | 29 +++++++++++++++++++ apps/web/src/hooks/use-runners.ts | 1 + 2 files changed, 30 insertions(+) diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index 33a75e738..406f47832 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -1,3 +1,4 @@ +import { RunnerEngines } from "@/components/runner-engines/runner-engines"; import { RunnerHealthDetails } from "./runner-health"; import { useState } from "react"; import { Server, Unplug } from "lucide-react"; @@ -36,6 +37,7 @@ const STATUS_DOT: Record = { export function RunnerSettings(): JSX.Element { const runners = useRunners({ poll: true }); const { revoke } = useRunnerMutations(); + const [expandedEngines, setExpandedEngines] = useState(null); const [confirmId, setConfirmId] = useState(null); const list = runners.data ?? []; @@ -109,6 +111,33 @@ export function RunnerSettings(): JSX.Element { + {runner.status === "online" && runner.engineManagement && ( +
+ + {expandedEngines === runner.id && ( + + )} +
+ )} {runner.workspaces.length > 0 && !runner.managedWorkspace && (

Folders: {runner.workspaces.join(", ")} diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index 89b39fba0..6875f8957 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -11,6 +11,7 @@ export type Runner = { status: RunnerStatus; workspaces: string[]; managedWorkspace?: true; + engineManagement?: true; health?: RunnerHealth; healthReceivedAt?: string; }; From 1eadbe3fea3294e6f9d0e23a36fb144da2332d0b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:14:29 -0700 Subject: [PATCH 051/642] Isolate runner acceptance credentials and retain guest failure logs --- e2e/remote-runner/acceptance.spec.ts | 16 ++++++++++++++++ e2e/remote-runner/setup.mjs | 13 +++++++++++++ 2 files changed, 29 insertions(+) diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index b16a193a4..dfef95d24 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -47,6 +47,21 @@ test.afterAll(async ({ request }) => { ); }); +test.afterEach(async ({}, testInfo) => { + if (testInfo.status === testInfo.expectedStatus) return; + for (const name of ["alpha", "beta", "scratch"] as const) { + const logs = guest( + name, + 'for file in /var/log/runner.log /var/lib/runner/bindings/logs/*; do [ ! -f "$file" ] || { printf "\\n%s\\n" "$file"; tail -60 "$file"; }; done' + ); + if (logs.trim()) + await testInfo.attach(`${name} runner logs`, { + body: logs, + contentType: "text/plain", + }); + } +}); + const text = (p: Page) => p.locator("body"); const answers = (p: Page, s: string) => p.getByText(s, { exact: false }); @@ -371,6 +386,7 @@ test("managed scratch launch reports health and archive removes the guest sessio expect((await agentInfo(request, id!)).cwd).toBe( `runner://${runnerId}/@session` ); + await expect(page).toHaveURL((url) => url.pathname === `/agents/${id}`); await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); await expect( settledTurns(page).last().getByTestId("harness-result") diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs index a7c5c4a2c..f65eab367 100644 --- a/e2e/remote-runner/setup.mjs +++ b/e2e/remote-runner/setup.mjs @@ -94,6 +94,17 @@ function artifacts(arch) { async function up(run) { const id = path.basename(run); mkdirSync(run, { recursive: true, mode: 0o700 }); + const providerFixture = path.join(run, "provider-fixture"); + mkdirSync(providerFixture, { mode: 0o700 }); + // An expired synthetic Claude login also prevents the macOS Keychain + // fallback. The adapter itself never needs a provider login. + writeFileSync( + path.join(providerFixture, ".credentials.json"), + JSON.stringify({ + claudeAiOauth: { accessToken: "fake-expired-e2e-token", expiresAt: 1 }, + }), + { mode: 0o600 } + ); const arch = sh("docker", ["version", "--format", "{{.Server.Arch}}"]).trim() === "arm64" ? "arm64" @@ -198,6 +209,8 @@ async function up(run) { "export DISPATCH_RUNNER_REPO_TOOL=1", // approved repo operation for every placement `export DISPATCH_RUNNER_PORT=${runnerPort}`, "export DISPATCH_RUNNER_ENDPOINT_HOST=host.docker.internal", + `export CLAUDE_CONFIG_DIR='${providerFixture}'`, + `export CODEX_HOME='${providerFixture}'`, `export REMOTE_E2E_STATE='${path.join(run, "state.json")}'`, "", ].join("\n") From 23716ff363eba7d3461956964180c933400e2fba Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:11:28 -0700 Subject: [PATCH 052/642] Keep the isolated runner entry point unchanged --- scripts/e2e-remote-runners.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scripts/e2e-remote-runners.sh b/scripts/e2e-remote-runners.sh index 9438d55af..21a1ca167 100755 --- a/scripts/e2e-remote-runners.sh +++ b/scripts/e2e-remote-runners.sh @@ -1,7 +1,6 @@ #!/usr/bin/env bash # Integrated remote-runner acceptance: local agent + two Docker-hosted runners -# with the same workspace name, plus an independently enrolled scratch runner. -# Requires Docker and Bun. +# with the same workspace name. Requires docker and bun. No VMs, no prod data. # pnpm run test:e2e:remote-runners [extra playwright args] set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" From ca7ad0cf0f49244719d4a2934bd38a57d2daa20c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:15:20 -0700 Subject: [PATCH 053/642] Add connect-command endpoint, fix Bun-unsafe pin verification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /api/runners/connect-command (authenticated): returns a reusable dispatch-runner connect invocation targeting the runner listener's own pinned CA/port, plus a browser approval URL built from the operator's own (unproxied) request — reachable and verifiable even when the ordinary Dispatch API is loopback-only or plain HTTP. The create/poll bootstrap routes are now also forwarded through the runner listener's existing proxy (alongside /ping and agent MCP), so a clean runner can reach them through that same pinned HTTPS even without main-API HTTPS. - Replaced the pinned-chain verification in dispatch-runner connect: it walked getPeerCertificate(true).issuerCertificate, which Bun's TLS implementation doesn't populate. Now pins the CA via the same ca_request/ca wire-protocol bootstrap the operator-initiated pairing flow already uses (Bun-proven), then makes the real request over an ordinary, fully chain-verified TLS connection trusting only that CA. - Added local validation of an approved reply before anything is persisted: issued-cert-matches-generated-key, cert-issued-by-stated-CA, https endpoint, and (when pinned) CA-matches-the-pin — independent of, not instead of, the TLS verification already performed to receive it. - CLI now also prints the pending-request's last-8-characters reference (matching what the Settings UI shows) and an actionable systemd step. - Forced a fresh (non-pooled) connection per CLI request: Node's default agent could reuse a socket while a prior request's own delayed-send verification was still deciding whether to write to it, surfacing as a spurious "socket hang up" on the next call. - New tests: connect-command's command/approval-link shape, full CLI end-to-end through the runner listener's proxy, and a rogue-leaf rejection even when the peer correctly echoes the pinned CA. Co-Authored-By: Claude Sonnet 5 --- apps/server/src/agents/remote/enrollment.ts | 166 +++++++++++---- apps/server/src/agents/remote/service.ts | 64 ++++-- apps/server/src/routes/runners.ts | 25 ++- .../server/test/remote-runner-connect.test.ts | 197 +++++++++++++++++- 4 files changed, 384 insertions(+), 68 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 39062962e..2c2a172a8 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -71,6 +71,29 @@ export function pairingCommand(input: { ].join(" "); } +/** + * Unlike `pairingCommand`, this is not single-use: the runner supplies its + * own one-time code at connect time, so the same invocation can be copied + * onto any number of clean runners. The target is always this listener's + * own pinned CA and port — reachable and verifiable even when the ordinary + * Dispatch API is loopback-only or plain HTTP, since nothing about it + * depends on the main API's own binding or certificate. + */ +export function connectCliCommand(input: { + host: string; + port: number; + caFingerprint: string; +}) { + const pin = normalizeFingerprint(input.caFingerprint) + .replace(/:/g, "") + .toLowerCase(); + return [ + "dispatch-runner connect", + `--service https://${formatHost(input.host)}:${input.port}`, + `--ca-sha256 ${pin}`, + ].join(" "); +} + /** * Check a CA certificate the service presented against the pinned SHA-256 * fingerprint of its DER bytes. Only public bytes are involved. @@ -419,31 +442,44 @@ function parseConnectArgs(argv: string[]): ConnectOptions { }; } -/** Whether the pin matches any certificate up the peer's presented chain. */ -function pinnedChainMatches(socket: TLSSocket, pin: string) { - const expected = normalizeFingerprint(pin); - let cert = socket.getPeerCertificate(true) as - | (ReturnType & { - issuerCertificate?: ReturnType; - }) - | undefined; - for (let hop = 0; cert && hop < 8; hop++) { - if (cert.fingerprint256 === expected) return true; - const issuer = cert.issuerCertificate; - if (!issuer || issuer === cert) break; - cert = issuer as typeof cert; - } - return false; +/** + * Fetch and pin the service's CA, the same way `exchangeCode` does for the + * operator-initiated flow and over the same wire-protocol port (`connect` + * targets the runner listener, which answers `ca_request` directly — see + * `connectCommand` in service.ts). A single connection cannot both ignore + * the chain *and* let the caller inspect it: Node exposes a verified peer + * leaf (`getPeerX509Certificate`) but not the full chain, and that API + * differs again under Bun. Confirming the CA's own fingerprint this way, + * then trusting only that CA for the real request, needs neither. + */ +async function fetchPinnedCa( + endpoint: Endpoint, + pin: string, + timeoutMs: number +): Promise<{ caPem: string; ca: X509Certificate }> { + const caPem = (await roundTrip( + endpoint, + {}, + timeoutMs, + () => ({ type: "ca_request", version: 1 }), + (reply) => { + if (reply.type !== "ca") throw new Error("Unexpected pairing reply."); + pinnedAuthority(reply.ca, pin); + return reply.ca; + } + )) as string; + return { caPem, ca: pinnedAuthority(caPem, pin) }; } /** - * One HTTPS round trip to the service's ordinary API — never a separate - * unauthenticated connection to fetch its CA first. With `pin`, the single - * TLS connection itself gates the request: nothing is written to the socket - * until the presented chain matches the pinned fingerprint. Without `pin`, - * the service is expected to hold an ordinarily trusted certificate. + * One HTTPS request to the service. With `pin`, first confirms the pinned + * CA over the runner listener's own wire-protocol bootstrap (see + * `fetchPinnedCa`), then makes the real request trusting only that CA — + * ordinary, fully-verified TLS from there, not a from-scratch chain check. + * Without `pin`, the service is expected to hold an ordinarily trusted + * certificate. */ -function requestJson( +async function requestJson( serviceUrl: string, method: string, requestPath: string, @@ -454,6 +490,12 @@ function requestJson( if (url.protocol !== "https:") throw new Error("--service must be an https URL."); const hostname = url.hostname.replace(/^\[|\]$/g, ""); + const port = Number(url.port || 443); + const timeoutMs = options.timeoutMs ?? 15_000; + const pinned = + options.pin !== undefined + ? await fetchPinnedCa({ host: hostname, port }, options.pin, timeoutMs) + : undefined; const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body)); return new Promise((resolve, reject) => { @@ -468,11 +510,11 @@ function requestJson( const timer = setTimeout(() => { request.destroy(); finish(new Error("The request to the service timed out.")); - }, options.timeoutMs ?? 15_000); + }, timeoutMs); const request = https.request( { hostname, - port: Number(url.port || 443), + port, path: url.pathname + url.search, method, servername: isIP(hostname) ? undefined : hostname, @@ -482,10 +524,15 @@ function requestJson( "content-length": payload.length, } : undefined, - // Pinned mode validates the chain itself (see pinnedChainMatches) - // before any request data is sent; it does not otherwise weaken - // verification of what the peer is allowed to claim. - rejectUnauthorized: options.pin === undefined, + // A fresh connection every call: this CLI makes only a handful of + // requests total, and Node's default agent can try to reuse a + // pooled socket while this request's own TLS verification is still + // deciding whether to send anything on it, surfacing as a spurious + // "socket hang up" on the next call. + agent: false, + ...(pinned + ? { ca: pinned.caPem, rejectUnauthorized: true } + : { rejectUnauthorized: true }), }, (response) => { let data = ""; @@ -512,26 +559,24 @@ function requestJson( } ); request.on("error", (error) => finish(error as Error)); - const send = () => { + if (!pinned) { if (payload) request.write(payload); request.end(); - }; - if (options.pin === undefined) { - send(); return; } + // Defense in depth, as exchangeCode also does: re-check the leaf itself + // against the now-confirmed CA before the request body goes out. request.on("socket", (socket: TLSSocket) => { socket.once("secureConnect", () => { - if (!pinnedChainMatches(socket, options.pin!)) { - finish( - new Error( - "The service certificate does not match the pinned Dispatch runner CA." - ) - ); + try { + verifyServiceLeaf(socket, hostname, pinned.ca); + } catch (error) { + finish(error as Error); request.destroy(); return; } - send(); + if (payload) request.write(payload); + request.end(); }); }); }); @@ -551,6 +596,41 @@ type ConnectPoll = | { status: "denied" } | { status: "expired" }; +/** + * Independent, local checks on an approved reply before anything from it + * is trusted enough to write to disk — on top of, not instead of, the TLS + * verification `requestJson` already did to receive it. + */ +function verifyIssuedConnectCredentials( + polled: Extract, + publicKey: string, + pin: string | undefined +) { + if (new URL(polled.endpoint).protocol !== "https:") + throw new Error("The service returned a non-HTTPS runner endpoint."); + const issuedCa = new X509Certificate(polled.ca); + const cert = new X509Certificate(polled.cert); + if ( + !issuedCa.ca || + !cert.checkIssued(issuedCa) || + !cert.verify(issuedCa.publicKey) || + cert.publicKey.export({ type: "spki", format: "pem" }).toString() !== + publicKey + ) + throw new Error( + "The issued certificate does not match the key this runner generated." + ); + // The connect endpoint and the runner listener share one CA; a pin + // checked only at the TLS layer still leaves the two free to disagree. + if ( + pin !== undefined && + issuedCa.fingerprint256 !== normalizeFingerprint(pin) + ) + throw new Error( + "The issued CA does not match the pinned Dispatch runner CA." + ); +} + /** `dispatch-runner connect …`: ask an operator to approve this runner. */ export async function runRunnerConnect(argv: string[]) { const options = parseConnectArgs(argv); @@ -566,7 +646,10 @@ export async function runRunnerConnect(argv: string[]) { process.stdout.write( [ `Code: ${created.code}`, - `Ask an operator to approve this runner in Dispatch (Settings → Connections → Remote runners) using this code.`, + // Same reference the pending-requests list shows in Settings, so an + // operator juggling more than one pending runner can tell them apart. + `Request: ${created.id.slice(-8)}`, + "Ask an operator to approve this runner in Dispatch (Settings → Connections → Remote runners) using this code and request reference.", `This code expires at ${created.expiresAt}.`, "Waiting for approval…", "", @@ -590,6 +673,7 @@ export async function runRunnerConnect(argv: string[]) { if (polled.status === "expired") throw new Error("The connect request expired before it was approved."); if (polled.status === "approved") { + verifyIssuedConnectCredentials(polled, publicKey, options.pin); const { configFile } = await persistRunnerCredentials({ dir: options.dir, config: options.config, @@ -610,6 +694,10 @@ export async function runRunnerConnect(argv: string[]) { cert: path.join(options.dir, "cert.pem"), key: path.join(options.dir, "key.pem"), })}`, + // This CLI never touches systemd itself (see persistRunnerCredentials); + // the installer only installs and daemon-reloads, so enrollment is + // the last step that needs telling the operator what to do next. + "Start it: sudo systemctl enable --now dispatch-runner.service", "", ].join("\n") ); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 767420594..cd0f1d7f2 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -18,6 +18,7 @@ import { type Placement, } from "./protocol.js"; import { + connectCliCommand, formatHost, pairingCommand, validRunnerName, @@ -722,7 +723,14 @@ export class RemoteRunnerService { }); } - /** Forward only bearer-authenticated agent MCP calls to the local API. */ + /** + * Forward bearer-authenticated agent MCP calls, `/ping`, and the two + * runner-initiated ("connect") bootstrap calls to the local API. The + * bootstrap calls carry no Dispatch credentials — none exist yet — so + * they are allow-listed by path and method alone, exactly like `/ping`; + * this is what lets a clean runner reach them through this listener's own + * pinned CA even when the ordinary API is loopback-only or plain HTTP. + */ private forward( request: http.IncomingMessage, response: http.ServerResponse @@ -730,6 +738,12 @@ export class RemoteRunnerService { const url = request.url ?? ""; const target = this.api; const ping = url === "/ping" && request.method === "GET"; + const connectCreate = + /^\/api\/(?:v1\/)?runners\/connect$/.test(url) && + request.method === "POST"; + const connectPoll = + /^\/api\/(?:v1\/)?runners\/connect\/[^/]+$/.test(url) && + request.method === "GET"; const agentId = /^\/api\/mcp\/(agt_[a-z0-9]+)$/.exec(url)?.[1]; const token = /^Bearer (\S+)$/.exec( request.headers.authorization ?? "" @@ -740,8 +754,9 @@ export class RemoteRunnerService { ["GET", "POST", "DELETE"].includes(request.method ?? "") && target?.validAgentToken?.(token, agentId) ); - if ((!ping && !mcp) || !target) { - response.writeHead(ping || mcp ? 503 : 404).end(); + const allowed = ping || mcp || connectCreate || connectPoll; + if (!allowed || !target) { + response.writeHead(allowed ? 503 : 404).end(); return; } const host = @@ -937,8 +952,38 @@ export class RemoteRunnerService { // Runner-initiated ("connect") enrollment // --------------------------------------------------------------------------- - /** `POST /api/runners/connect`: an unauthenticated runner requests pairing. */ - async createConnectRequest(publicKey: unknown, serviceOrigin?: string) { + /** + * `GET /api/runners/connect-command`: the authenticated operator's copy + * of the invocation to run on the runner. Unlike pairing, this is not + * single-use — the runner supplies its own one-time code — so the same + * command stays valid for any number of runners until the CA renews. + * The approval link uses this request's own (authenticated, unproxied) + * Host header: it is for the operator's browser, which is already here. + */ + async connectCommand(hostHint?: string, rawHost?: string) { + if (!this.enrollment) + throw new RunnerRequestError(409, "Runner enrollment is disabled."); + const host = await this.prepareEndpoint(hostHint); + return { + command: connectCliCommand({ + host, + port: this.port!, + caFingerprint: this.authority!.caFingerprint, + }), + // This browser's own Host header — reliable here, unlike for a + // runner that may reach us only through the listener's proxy. + approveUrl: rawHost + ? `https://${rawHost}/settings/connections` + : undefined, + }; + } + + /** + * `POST /api/runners/connect`: an unauthenticated runner requests pairing. + * Reached either directly or, for a runner that only has the listener's + * own pinned CA (see `connectCommand`), proxied through it like `/ping`. + */ + async createConnectRequest(publicKey: unknown) { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); if (typeof publicKey !== "string" || publicKey.length === 0) @@ -946,14 +991,7 @@ export class RemoteRunnerService { try { const { id, code, expiresAt } = await this.enrollment.registry.createConnectRequest(publicKey); - return { - id, - code, - approveUrl: serviceOrigin - ? `https://${serviceOrigin}/settings/connections` - : undefined, - expiresAt: expiresAt.toISOString(), - }; + return { id, code, expiresAt: expiresAt.toISOString() }; } catch (error) { if (error instanceof PairingRejected) throw new RunnerRequestError(400, error.message); diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts index 034853f47..7483c53d7 100644 --- a/apps/server/src/routes/runners.ts +++ b/apps/server/src/routes/runners.ts @@ -118,18 +118,31 @@ export async function registerRunnerRoutes( try { return reply .code(201) - .send( - await deps.runners.createConnectRequest( - body.publicKey, - request.headers.host - ) - ); + .send(await deps.runners.createConnectRequest(body.publicKey)); } catch (error) { return fail(reply, error); } } ); + // The authenticated operator's copy of the invocation to run on a + // runner — always reachable even when the ordinary API is loopback or + // plain HTTP, since it targets the runner listener's own pinned CA. + app.get(`${base}/connect-command`, async (request, reply) => { + if (!deps.runners) + return reply + .code(409) + .send({ error: "Runner enrollment is disabled." }); + try { + return await deps.runners.connectCommand( + hostHint(request.headers.host), + request.headers.host + ); + } catch (error) { + return fail(reply, error); + } + }); + app.get( `${base}/connect/:id`, { diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index 2c82cacd0..ac5efc91f 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -1,13 +1,19 @@ import { X509Certificate } from "node:crypto"; +import { mkdtemp, readFile } from "node:fs/promises"; import http from "node:http"; import type { AddressInfo } from "node:net"; -import { connect, type TLSSocket } from "node:tls"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { connect, createServer, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { runRunnerConnect } from "../src/agents/remote/enrollment.js"; import { RunnerRegistry } from "../src/agents/remote/registry.js"; import { RemoteRunnerService } from "../src/agents/remote/service.js"; import { generateRunnerKey, + issueAuthority, + issueServer, runnerPublicKey, } from "../src/agents/remote/x509.js"; import { wireFrames, type Frame } from "../src/agents/remote/protocol.js"; @@ -62,6 +68,7 @@ async function waitFor(check: () => boolean | Promise) { describe("runner-initiated connect enrollment", () => { let pool: Pool; let api: http.Server; + let activeService: RemoteRunnerService | undefined; const services: RemoteRunnerService[] = []; const runners: FakeRunner[] = []; @@ -76,13 +83,55 @@ describe("runner-initiated connect enrollment", () => { } ); services.push(service); + activeService = service; return service; }; beforeAll(async () => { pool = await setupTestDb(); await runTestMigrations(); - api = http.createServer((_request, response) => response.end("api")); + // Stands in for the real Fastify app the listener proxies to: just + // enough of /api/runners/connect(...) to prove the proxy path works, + // delegating to whichever service this test created. + api = http.createServer((request, response) => { + const url = request.url ?? ""; + const send = (status: number, body: unknown) => { + const text = JSON.stringify(body); + response.writeHead(status, { "content-type": "application/json" }); + response.end(text); + }; + if (url === "/api/runners/connect" && request.method === "POST") { + let raw = ""; + request.on("data", (chunk) => (raw += chunk)); + request.on("end", async () => { + try { + const body = JSON.parse(raw || "{}") as { publicKey?: unknown }; + send( + 201, + await activeService!.createConnectRequest(body.publicKey) + ); + } catch (error) { + send((error as { status?: number }).status ?? 500, { + error: (error as Error).message, + }); + } + }); + return; + } + const pollId = /^\/api\/runners\/connect\/([^/]+)$/.exec(url)?.[1]; + if (pollId && request.method === "GET") { + activeService! + .pollConnectRequest(pollId) + .then((result) => send(200, result)) + .catch((error) => + send((error as { status?: number }).status ?? 500, { + error: (error as Error).message, + }) + ); + return; + } + response.end("api"); + }); await new Promise((resolve) => api.listen(0, HOST, resolve)); }, 60_000); @@ -102,15 +151,9 @@ describe("runner-initiated connect enrollment", () => { it("creates a pending request the runner can poll before approval", async () => { const service = makeService(); const { publicKey } = generateRunnerKey(); - const created = await service.createConnectRequest( - publicKey, - `${HOST}:9999` - ); + const created = await service.createConnectRequest(publicKey); expect(created.id).toMatch(/^conn_/); expect(created.code).toMatch(/^[0-9A-Z]{4}-[0-9A-Z]{4}$/); - expect(created.approveUrl).toBe( - `https://${HOST}:9999/settings/connections` - ); expect(new Date(created.expiresAt).getTime()).toBeGreaterThan(Date.now()); expect(await service.pollConnectRequest(created.id)).toEqual({ @@ -129,10 +172,24 @@ describe("runner-initiated connect enrollment", () => { it("rejects a malformed public key", async () => { const service = makeService(); await expect( - service.createConnectRequest("not a key", undefined) + service.createConnectRequest("not a key") ).rejects.toMatchObject({ status: 400 }); }); + it("builds a reusable connect command and a usable approval link", async () => { + const service = makeService(); + const built = await service.connectCommand(HOST, "web.example:8443"); + expect(built.command).toMatch( + /^dispatch-runner connect --service https:\/\/127\.0\.0\.1:\d+ --ca-sha256 [a-f0-9]{64}$/ + ); + expect(built.approveUrl).toBe( + "https://web.example:8443/settings/connections" + ); + // Not single-use: asking again returns the same reachable address. + const again = await service.connectCommand(HOST, "web.example:8443"); + expect(again.command).toBe(built.command); + }); + it("approves with the correct code, binds the key, and lets the runner connect", async () => { const service = makeService(); const { key, publicKey } = generateRunnerKey(); @@ -250,4 +307,124 @@ describe("runner-initiated connect enrollment", () => { service.denyConnectRequest("conn_missing") ).rejects.toMatchObject({ status: 404 }); }); + + it("runs the real CLI end-to-end over the runner listener's own pinned HTTPS (no main API HTTPS needed)", async () => { + const service = makeService(); + const { command } = await service.connectCommand(HOST); + const [, endpoint, pin] = + /--service (\S+) --ca-sha256 (\S+)/.exec(command) ?? []; + const dir = await mkdtemp(path.join(tmpdir(), "connect-cli-")); + + const printed: string[] = []; + const originalWrite = process.stdout.write.bind(process.stdout); + (process.stdout.write as unknown) = (chunk: unknown) => { + printed.push(String(chunk)); + return true; + }; + + const connectPromise = runRunnerConnect([ + "--service", + endpoint!, + "--ca-sha256", + pin!, + "--dir", + dir, + ]).finally(() => { + process.stdout.write = originalWrite; + }); + + let id: string | undefined; + let code: string | undefined; + await waitFor(async () => { + const pending = await service.listConnectRequests(); + id = pending[0]?.id; + code = /Code: (\S+)/.exec(printed.join(""))?.[1]; + return Boolean(id && code); + }); + // The UI's own last-8-characters reference matches what the CLI prints. + expect(printed.join("")).toContain(`Request: ${id!.slice(-8)}`); + + await service.approveConnectRequest(id!, code!, "zeta", HOST); + await connectPromise; + + const cert = await readFile(path.join(dir, "cert.pem"), "utf8"); + const key = await readFile(path.join(dir, "key.pem"), "utf8"); + const ca = await readFile(path.join(dir, "ca.pem"), "utf8"); + const leaf = new X509Certificate(cert); + expect(leaf.subject).toMatch(/^CN=rnr_[a-f0-9]+$/); + const registrationId = leaf.subject.replace("CN=", ""); + + runners.push( + await dialRunner({ + endpoint: endpoint!, + ca, + cert, + key, + workspaces: ["proof"], + }) + ); + await waitFor(() => + service.available({ runner: registrationId, workspace: "proof" }) + ); + }, 20_000); }); + +describe("pinned connect bootstrap", () => { + it("rejects a leaf from another CA even though the peer echoes the real pinned CA", async () => { + const real = issueAuthority("real"); + const rogue = issueAuthority("rogue"); + const leaf = issueServer(rogue, [HOST]); + const received: unknown[] = []; + const server = connectServer(leaf, rogue, (frame, send, socket) => { + received.push(frame); + if ((frame as { type?: string }).type === "ca_request") { + send({ type: "ca", ca: real.cert } as never); + socket.end(); + } else socket.destroy(); + }); + await new Promise((resolve) => server.listen(0, HOST, resolve)); + const port = (server.address() as AddressInfo).port; + const pin = new X509Certificate(real.cert).fingerprint256 + .replace(/:/g, "") + .toLowerCase(); + try { + const dir = await mkdtemp(path.join(tmpdir(), "connect-rogue-")); + // The bootstrap step alone succeeds — the real CA is exactly what was + // pinned — so a failure here must come from the second, real request + // refusing the rogue leaf, not from the CA check itself. + await expect( + runRunnerConnect([ + "--service", + `https://${HOST}:${port}`, + "--ca-sha256", + pin, + "--dir", + dir, + ]) + ).rejects.toThrow(); + expect(received).toEqual([{ type: "ca_request", version: 1 }]); + } finally { + server.close(); + } + }); +}); + +function connectServer( + leaf: { cert: string; key: string }, + ca: { cert: string }, + onFrame: ( + frame: unknown, + send: (frame: unknown) => void, + socket: TLSSocket + ) => void +) { + return createServer( + { cert: leaf.cert + ca.cert, key: leaf.key }, + (socket: TLSSocket) => { + socket.on("error", () => {}); + const send = wireFrames(socket, (frame) => + onFrame(frame, send as never, socket) + ); + } + ); +} From 2ba156855454442c908416ff8189a56d6a899aa1 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:17:41 -0700 Subject: [PATCH 054/642] Start enrollment requests over the verified TLS connection on Bun --- apps/server/src/agents/remote/enrollment.ts | 23 +++------------------ 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 2c2a172a8..5f27d6248 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -559,26 +559,9 @@ async function requestJson( } ); request.on("error", (error) => finish(error as Error)); - if (!pinned) { - if (payload) request.write(payload); - request.end(); - return; - } - // Defense in depth, as exchangeCode also does: re-check the leaf itself - // against the now-confirmed CA before the request body goes out. - request.on("socket", (socket: TLSSocket) => { - socket.once("secureConnect", () => { - try { - verifyServiceLeaf(socket, hostname, pinned.ca); - } catch (error) { - finish(error as Error); - request.destroy(); - return; - } - if (payload) request.write(payload); - request.end(); - }); - }); + // Bun starts the HTTPS request on end(). TLS verifies the endpoint + // hostname and certificate chain against the selected CA before sending. + request.end(payload); }); } From 64f8836b425a193546fa9c0474ef14c5a74cf962 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:18:39 -0700 Subject: [PATCH 055/642] Route runner ownership checks and constrain bootstrap polling to issued IDs --- .agents/owners.json | 14 ++++++++++++++ .agents/personas/agent-runtime-owner.md | 1 + .agents/personas/auth-trust-owner.md | 2 ++ apps/server/src/agents/remote/service.ts | 2 +- 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.agents/owners.json b/.agents/owners.json index 8709f4827..787f36764 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -22,6 +22,16 @@ { "paths": [ "apps/server/src/agents/**", + "apps/server/src/main.ts", + "apps/server/src/routes/runners.ts", + "apps/server/src/routes/runner-*.ts", + "apps/server/test/remote-*.test.ts", + "apps/server/test/runner-*.test.ts", + "apps/server/test/helpers/remote-acp-fixture.ts", + "packages/runner-protocol/**", + "docs/design/remote-runner-handoff.md", + "scripts/e2e-remote-runners.sh", + "scripts/remote-runner/codex-offline-preflight.sh", "apps/server/src/shared/process/**", "apps/server/src/server/agent-*.ts", "apps/server/src/shared/git/**", @@ -329,6 +339,10 @@ "apps/server/src/browser-origin.ts", "apps/server/src/server-origin.ts", "apps/server/src/local-tls.ts", + "apps/server/src/agents/remote/enrollment.ts", + "apps/server/src/agents/remote/registry.ts", + "apps/server/src/agents/remote/service.ts", + "apps/server/src/routes/runners.ts", "apps/server/src/multi-listener.ts", "apps/server/src/server/auth-runtime.ts", "apps/server/src/routes/auth.ts", diff --git a/.agents/personas/agent-runtime-owner.md b/.agents/personas/agent-runtime-owner.md index e833ed962..994827087 100644 --- a/.agents/personas/agent-runtime-owner.md +++ b/.agents/personas/agent-runtime-owner.md @@ -14,6 +14,7 @@ Read `apps/server/src/agents/manager.ts`, `agents/acp/`, `shared/git/`, and the - Effort choices come from the selected model’s reported capabilities. Trace validation, adapter propagation, live effort persistence, and resume fallback when a saved level is removed; never substitute a fixed per-runtime list. - Launch and restart must preserve the agent's cwd, worktree, model, ACP session and MCP identity, and permissions. Verify quoting through each shell/ACP adapter boundary, including paths with spaces. +- Bind remote prompts, permission replies, replay cursors, and cleanup to the opaque runner and session IDs. Check independent reconnect and revoke, same-named folders, and durable cleanup when a managed runner is offline. - Cancellation, archive, and cleanup must target the owned engine host/session/worktree, preserve unrelated agents, and avoid orphan processes. Check failed or partially completed launches. - ACP initialization, prompt cancellation, permission replies, engine disconnect, and session restore must preserve the owning agent and stream. Never mix host IPC ids with engine request ids. - Lifecycle transitions and reconciliation must agree with persisted agent state; concurrent starts, restarts, and exits must not revive an archived agent or duplicate a session. diff --git a/.agents/personas/auth-trust-owner.md b/.agents/personas/auth-trust-owner.md index c262024d3..925431dda 100644 --- a/.agents/personas/auth-trust-owner.md +++ b/.agents/personas/auth-trust-owner.md @@ -21,6 +21,8 @@ Trace changed authentication and trust boundaries across server hooks, routes, b - Portfolio reader credentials must remain read-only and distinct from account/MCP credentials, including first-run mode and cookie-bearing requests. Recheck revocation and project allowlists on every page; cached snapshots must never outlive their authorization. +- Runner enrollment must bind the issued certificate to the locally generated key and the operator-approved request. Check the pinned CA, endpoint hostname, one-time code, and which requests the runner listener forwards. + ## Findings Report only concrete defects introduced or worsened by the reviewed changes. Each finding must identify a realistic failure scenario, its impact, a changed location or contract responsible, and the smallest useful fix. Surrounding code is context, not an invitation to audit pre-existing debt. Submit a clean approval when there are no actionable findings. diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index cd0f1d7f2..365ad6084 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -742,7 +742,7 @@ export class RemoteRunnerService { /^\/api\/(?:v1\/)?runners\/connect$/.test(url) && request.method === "POST"; const connectPoll = - /^\/api\/(?:v1\/)?runners\/connect\/[^/]+$/.test(url) && + /^\/api\/(?:v1\/)?runners\/connect\/conn_[A-Za-z0-9_-]{24}$/.test(url) && request.method === "GET"; const agentId = /^\/api\/mcp\/(agt_[a-z0-9]+)$/.exec(url)?.[1]; const token = /^Bearer (\S+)$/.exec( From 6c2d1deb1fc4ced3def5d5b6908e1b916a02b9d5 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:21:06 -0700 Subject: [PATCH 056/642] Identify remote sessions by runner name on agent cards --- apps/web/src/components/app/agent-card-details.tsx | 12 ++++++++---- apps/web/src/components/app/agent-card-header.tsx | 6 +++++- apps/web/src/components/app/agent-card-status.tsx | 8 +++++++- apps/web/src/components/app/agent-card.tsx | 14 ++++++++++++++ apps/web/src/hooks/use-runners.ts | 5 ++++- 5 files changed, 38 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/app/agent-card-details.tsx b/apps/web/src/components/app/agent-card-details.tsx index 19cbcf2b5..e28ca2560 100644 --- a/apps/web/src/components/app/agent-card-details.tsx +++ b/apps/web/src/components/app/agent-card-details.tsx @@ -74,6 +74,7 @@ function CompactMetaRow({ } export type AgentCardDetailsProps = { + remoteLocation?: string; agent: Agent; personaParentName?: string; diffStats: DiffStats | null | undefined; @@ -94,6 +95,7 @@ export type AgentCardDetailsProps = { * indicator. */ export function AgentCardDetails({ + remoteLocation, agent, personaParentName, diffStats, @@ -118,7 +120,9 @@ export function AgentCardDetails({

- {agent.gitContext?.isWorktree ? ( + {remoteLocation ? ( + + ) : agent.gitContext?.isWorktree ? (
@@ -203,11 +207,11 @@ export function AgentCardDetails({
- {workspaceDir ? ( + {!remoteLocation && workspaceDir ? ( ) : null} - - {agent.gitContext?.isWorktree && workspaceDir ? ( + {!remoteLocation && } + {!remoteLocation && agent.gitContext?.isWorktree && workspaceDir ? (
- {!projectId && repoName && !agent.reconnect ? ( + {remoteLocation ? ( + + {remoteLocation} + + ) : !projectId && repoName && !agent.reconnect ? ( ) : null}
diff --git a/apps/web/src/components/app/agent-card.tsx b/apps/web/src/components/app/agent-card.tsx index b4a12a689..d5ba79948 100644 --- a/apps/web/src/components/app/agent-card.tsx +++ b/apps/web/src/components/app/agent-card.tsx @@ -1,3 +1,5 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; +import { useRunners } from "@/hooks/use-runners"; import React from "react"; import { Pin, PinOff } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -107,6 +109,15 @@ function AgentCardImpl({ const isStopped = state === "stopped"; const isExpanded = expandedAgentId === agent.id; const fullAccessEnabled = isFullAccessEnabled(agent); + const placement = remotePlacement(agent.cwd); + const { data: runners } = useRunners({ enabled: Boolean(placement) }); + const runnerName = placement + ? (runners?.find((r) => r.id === placement.runner)?.name ?? "Remote runner") + : undefined; + const remoteLocation = + placement && runnerName && !agent.runnerManaged + ? `${runnerName} · ${placement.workspace}` + : runnerName; const [settingsOpen, setSettingsOpen] = React.useState(false); // Sub agent rows reuse the same rename dialog; tracking which row opened it // keeps one dialog instance instead of one per row. @@ -181,6 +192,7 @@ function AgentCardImpl({ )} >
(await api<{ runners: Runner[] }>("/api/runners")).runners, refetchInterval: options.poll ? 5000 : false, From d5f189174f954712e30f63999a754d6414a9d005 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:22:14 -0700 Subject: [PATCH 057/642] Make the connect approval link service-agnostic and configurable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The create-request response can now carry an approveUrl too, but only ever from the explicitly configured DISPATCH_RUNNER_APPROVAL_ORIGIN (http:// or https://, so a Vite dev server on its own port works as well as a production HTTPS origin) — that call comes from the runner, which has no browser origin to offer, so there is no per-request host to guess from. connect-command still prefers its own (reliable) request host when the env var is unset. The CLI drops its hardcoded "Dispatch" wording, printing whatever approveUrl the service sends, or a generic fallback when none is configured. Co-Authored-By: Claude Sonnet 5 --- apps/server/src/agents/remote/enrollment.ts | 12 +++- apps/server/src/agents/remote/service.ts | 55 +++++++++++++++++-- .../server/test/remote-runner-connect.test.ts | 44 ++++++++++++++- docs/design/remote-runner-prototype.md | 46 +++++++++++----- 4 files changed, 133 insertions(+), 24 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 5f27d6248..91742ddd7 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -565,7 +565,13 @@ async function requestJson( }); } -type ConnectCreated = { id: string; code: string; expiresAt: string }; +type ConnectCreated = { + id: string; + code: string; + expiresAt: string; + /** Set only when the service has an approval origin configured. */ + approveUrl?: string; +}; type ConnectPoll = | { status: "pending" } | { @@ -632,7 +638,9 @@ export async function runRunnerConnect(argv: string[]) { // Same reference the pending-requests list shows in Settings, so an // operator juggling more than one pending runner can tell them apart. `Request: ${created.id.slice(-8)}`, - "Ask an operator to approve this runner in Dispatch (Settings → Connections → Remote runners) using this code and request reference.", + created.approveUrl + ? `Approve at: ${created.approveUrl}` + : "Ask an operator to approve this runner using the code and request reference above.", `This code expires at ${created.expiresAt}.`, "Waiting for approval…", "", diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 365ad6084..14a66e491 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -60,6 +60,16 @@ export type EnrollmentOptions = { endpointHost?: string; /** External HTTPS MCP origin; defaults to the runner listener's proxy. */ mcpOrigin?: string; + /** + * Where an operator approves a runner-initiated connect request in a + * browser — the Dispatch web app's own reachable origin, http or https + * (a Vite dev server is plain HTTP on its own port; production is + * typically HTTPS). Unset means no link is offered: a single inbound + * request's own Host header is reliable for `connectCommand` (the + * operator's own browser call) but not for `createConnectRequest` (the + * runner's), which has no way to know the operator's browser origin. + */ + approvalOrigin?: string; /** * Service-side approval for the runner's fixed repo operation: true for * every placement, or a list of `` / `/`. @@ -136,6 +146,21 @@ function httpsOrigin(value: string | undefined, label: string) { return value.replace(/\/$/, ""); } +/** + * Unlike the MCP origin, the approval link may legitimately be plain HTTP + * (a Vite dev server) as well as HTTPS (production), so only its shape — + * a bare http(s) origin, no path — is checked here. + */ +function anyOrigin(value: string | undefined, label: string) { + if (!value) return undefined; + const url = new URL(value); + if (url.protocol !== "http:" && url.protocol !== "https:") + throw new Error(`${label} must be an http(s) origin`); + if (url.pathname !== "/" || url.search || url.hash) + throw new Error(`${label} must be a bare origin, without a path`); + return value.replace(/\/$/, ""); +} + function isLoopbackHost(host: string) { const bare = host.replace(/^\[|\]$/g, "").toLowerCase(); return ( @@ -210,6 +235,7 @@ export function configuredRunner(input?: { : undefined, endpointHost: process.env.DISPATCH_RUNNER_ENDPOINT_HOST, mcpOrigin: process.env.DISPATCH_RUNNER_MCP_ORIGIN, + approvalOrigin: process.env.DISPATCH_RUNNER_APPROVAL_ORIGIN, repoTool: parseRepoTool(process.env.DISPATCH_RUNNER_REPO_TOOL), log: console, } @@ -269,6 +295,7 @@ export class RemoteRunnerService { } if (enrollment) { httpsOrigin(enrollment.mcpOrigin, "DISPATCH_RUNNER_MCP_ORIGIN"); + anyOrigin(enrollment.approvalOrigin, "DISPATCH_RUNNER_APPROVAL_ORIGIN"); if (enrollment.endpointHost && !validHost(enrollment.endpointHost)) throw new Error("DISPATCH_RUNNER_ENDPOINT_HOST is not a valid host"); } @@ -960,6 +987,18 @@ export class RemoteRunnerService { * The approval link uses this request's own (authenticated, unproxied) * Host header: it is for the operator's browser, which is already here. */ + /** Where an operator approves a connect request, if known. */ + private approveUrl(fallbackHost?: string) { + if (this.enrollment?.approvalOrigin) + return `${this.enrollment.approvalOrigin}/settings/connections`; + // Best-effort only: reliable when `fallbackHost` is this request's own + // (unproxied) Host header, not when it's a guess at the runner's view + // of the service. + return fallbackHost + ? `https://${fallbackHost}/settings/connections` + : undefined; + } + async connectCommand(hostHint?: string, rawHost?: string) { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); @@ -970,11 +1009,7 @@ export class RemoteRunnerService { port: this.port!, caFingerprint: this.authority!.caFingerprint, }), - // This browser's own Host header — reliable here, unlike for a - // runner that may reach us only through the listener's proxy. - approveUrl: rawHost - ? `https://${rawHost}/settings/connections` - : undefined, + approveUrl: this.approveUrl(rawHost), }; } @@ -991,7 +1026,15 @@ export class RemoteRunnerService { try { const { id, code, expiresAt } = await this.enrollment.registry.createConnectRequest(publicKey); - return { id, code, expiresAt: expiresAt.toISOString() }; + return { + id, + code, + expiresAt: expiresAt.toISOString(), + // Only ever set from configuration (see approveUrl): this request + // came from the runner, which has no way to tell us the operator's + // browser origin, so there is no per-request fallback to guess. + approveUrl: this.approveUrl(), + }; } catch (error) { if (error instanceof PairingRejected) throw new RunnerRequestError(400, error.message); diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index ac5efc91f..71424e54c 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -72,10 +72,15 @@ describe("runner-initiated connect enrollment", () => { const services: RemoteRunnerService[] = []; const runners: FakeRunner[] = []; - const makeService = () => { + const makeService = (approvalOrigin?: string) => { const service = new RemoteRunnerService( undefined, - { registry: new RunnerRegistry(pool), host: HOST, endpointHost: HOST }, + { + registry: new RunnerRegistry(pool), + host: HOST, + endpointHost: HOST, + approvalOrigin, + }, { host: HOST, port: (api.address() as AddressInfo).port, @@ -155,6 +160,9 @@ describe("runner-initiated connect enrollment", () => { expect(created.id).toMatch(/^conn_/); expect(created.code).toMatch(/^[0-9A-Z]{4}-[0-9A-Z]{4}$/); expect(new Date(created.expiresAt).getTime()).toBeGreaterThan(Date.now()); + // No DISPATCH_RUNNER_APPROVAL_ORIGIN configured: omitted, not guessed — + // this call came from the runner, which has no browser origin to offer. + expect(created.approveUrl).toBeUndefined(); expect(await service.pollConnectRequest(created.id)).toEqual({ status: "pending", @@ -169,6 +177,38 @@ describe("runner-initiated connect enrollment", () => { ]); }); + it("offers an approval link, including over plain HTTP for a dev frontend, only when configured", async () => { + const service = makeService("http://localhost:5173"); + const { publicKey } = generateRunnerKey(); + const created = await service.createConnectRequest(publicKey); + expect(created.approveUrl).toBe( + "http://localhost:5173/settings/connections" + ); + // connect-command prefers the same configured origin over the + // (unreliable for a dev frontend on a different port) request host. + const built = await service.connectCommand(HOST, "127.0.0.1:9999"); + expect(built.approveUrl).toBe("http://localhost:5173/settings/connections"); + }); + + it("rejects a malformed DISPATCH_RUNNER_APPROVAL_ORIGIN", () => { + expect( + () => + new RemoteRunnerService(undefined, { + registry: new RunnerRegistry(pool), + host: HOST, + approvalOrigin: "https://example.com/settings", + }) + ).toThrow(/bare origin/); + expect( + () => + new RemoteRunnerService(undefined, { + registry: new RunnerRegistry(pool), + host: HOST, + approvalOrigin: "ftp://example.com", + }) + ).toThrow(/http\(s\)/); + }); + it("rejects a malformed public key", async () => { const service = makeService(); await expect( diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 8c9e79954..3950d0de9 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -110,14 +110,32 @@ optional when `endpointHost` is given. `dispatch-runner connect --service https://HOST:PORT [--ca-sha256 HEX] [--dir /etc/dispatch-runner] [--config FILE]` enrolls without a pairing command typed on the runner: the runner dials the Dispatch service itself. -It generates its keypair locally (the private key never leaves the host, as -with the operator-initiated flow above) and `POST /api/runners/connect` -with only its public key. The service returns a short operator-facing code, -an opaque high-entropy request id for the CLI's own polling, and, when the -request carried a usable `Host` header, an `approveUrl` pointing at -**Settings → Connections → Remote runners** on that same origin. The CLI -prints the code and URL and polls `GET /api/runners/connect/:id` (addressed -only by that same opaque id) until an operator approves it. +`GET /api/runners/connect-command` (authenticated) gives an operator the +exact invocation to run — it always targets the runner listener's own +pinned CA and port, so it works even when the ordinary API is loopback-only +or plain HTTP, and it is reusable: the runner supplies its own one-time +code, so the same command can be copied onto any number of clean runners. + +The runner generates its keypair locally (the private key never leaves the +host, as with the operator-initiated flow above) and +`POST /api/runners/connect` with only its public key, reached either +directly or, for a runner that only has the listener's own pinned CA, +proxied through that listener the same way `/ping` already is. The service +returns a short operator-facing code and an opaque high-entropy request id +for the CLI's own polling. The CLI prints the code and polls +`GET /api/runners/connect/:id` (addressed only by that same opaque id) +until an operator approves it. + +Both `connect-command` and the create response may also carry an +`approveUrl` pointing at **Settings → Connections → Remote runners**. For +`connect-command` it is built from that authenticated call's own (reliable) +Host header; the create call has no such thing to go on — it comes from the +runner, not a browser — so it is only ever populated from the explicitly +configured `DISPATCH_RUNNER_APPROVAL_ORIGIN` (a bare `http://` or `https://` +origin; `http://` so a Vite dev server's own port can be used, not just a +production HTTPS origin). Unset, the create response simply omits it and +the CLI falls back to code-only instructions — honest rather than a guess +that can point at the wrong origin. The operator reads the code off the runner's own terminal or logs — it is never sent back by the runner — and calls the authenticated @@ -134,12 +152,12 @@ Approval issues the same kind of mTLS client certificate as pairing above, automatically and without a second step, and the poll response that follows carries the certificate, the CA, and the `endpoint` to dial — the same `runner.json` fields `remote-runner-pair` writes. `--ca-sha256` pins the -service's certificate chain for a self-signed deployment; unlike pairing, -pinning happens inside the single connection that carries the actual -request — nothing is written to the socket until the presented chain -matches, and there is no separate unauthenticated round trip first. Without -`--ca-sha256`, the service is expected to hold an ordinarily trusted -certificate. +service's certificate chain for a self-signed deployment the same way +pairing's bootstrap does: the CLI confirms the CA over the same +`ca_request`/`ca` wire-protocol exchange first, then makes the real request +over an ordinary, fully chain-and-hostname-verified TLS connection trusting +only that CA. Without `--ca-sha256`, the service is expected to hold an +ordinarily trusted certificate. ## Legacy manual enrollment From 13edd849c6439e01dd0bccbc3e0326d97d845d7e Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:25:00 -0700 Subject: [PATCH 058/642] Wire engine management into the runner transport, HTTP routes and health push Adds the "engine" wire command (runner.ts/service.ts) with a scoped, privilege-dropped executor on the runner side; an authenticated HTTP surface (engine-management routes) backed by a shared EngineManager instance so the existing engine-login/engine-update routes and the new scope-aware routes never diverge on in-flight state; runner-pushed engine inventory alongside the existing health push, validated before trusting it; and an explicit engineManagement capability flag on RunnerSummary so older runners are never assumed to support it. Also fixes an installation-detection bug found during integration: a runner's configured launch path is not evidence of installation on a fresh host, so the executor now actually probes the binary under the workload identity, sanitizes --version output to a safe token (never raw CLI text), and surfaces install-unavailable when a configured install/update command's own executable can't run. Co-Authored-By: Claude Sonnet 5 --- .../src/agents/remote/engine-manager.ts | 47 ++- .../agents/remote/engine-runner-executor.ts | 73 ++++- .../src/agents/remote/engine-transport.ts | 96 ++++++ apps/server/src/agents/remote/protocol.ts | 1 + apps/server/src/agents/remote/runner.ts | 70 ++++- apps/server/src/agents/remote/service.ts | 28 ++ apps/server/src/routes/engine-management.ts | 84 +++++ apps/server/src/routes/system.ts | 11 +- apps/server/src/server.ts | 54 +++- .../test/engine-management-routes.test.ts | 114 +++++++ apps/server/test/engine-manager.test.ts | 11 +- .../test/engine-runner-executor.test.ts | 89 ++++++ apps/server/test/engine-wire.test.ts | 288 ++++++++++++++++++ .../test/remote-runner-enrollment.test.ts | 9 +- apps/server/test/runner-routes.test.ts | 8 +- .../src/components/app/runner-settings.tsx | 1 - .../runner-engines/runner-engines.test.tsx | 7 +- .../runner-engines/runner-engines.tsx | 7 + apps/web/src/hooks/use-runner-engines.ts | 14 +- .../runner-protocol/src/engine-management.ts | 81 ++++- packages/runner-protocol/src/index.ts | 17 ++ 21 files changed, 1037 insertions(+), 73 deletions(-) create mode 100644 apps/server/src/agents/remote/engine-transport.ts create mode 100644 apps/server/src/routes/engine-management.ts create mode 100644 apps/server/test/engine-management-routes.test.ts create mode 100644 apps/server/test/engine-wire.test.ts diff --git a/apps/server/src/agents/remote/engine-manager.ts b/apps/server/src/agents/remote/engine-manager.ts index 7e50d740a..3e684890c 100644 --- a/apps/server/src/agents/remote/engine-manager.ts +++ b/apps/server/src/agents/remote/engine-manager.ts @@ -36,17 +36,23 @@ export type { EngineScope }; /** What a runner's connection exposes for engine management; supplied by the caller. */ export interface RunnerEngineTransport { /** - * Send one operation to the named runner workspace. `onEvent` receives - * any progress frames the runner streams before its ack. Reject (or - * resolve `{ ok: false, unsupported: true }`) for an offline runner or - * one that predates engine management. + * Send one operation to the named runner. `onEvent` receives any + * progress frames the runner streams before its ack. Reject (or resolve + * `{ ok: false, unsupported: true }`) for an offline runner or one that + * predates engine management. */ send( runnerId: string, - workspace: string, operation: EngineOperation, onEvent?: (event: EngineOperationEvent) => void ): Promise; + /** + * The runner's last pushed inventory snapshot, if any — a cheap read + * that skips a wire round trip. `inventory()` falls back to `send` with + * a `"status"` operation when this is absent (not yet pushed, or the + * transport doesn't track a cache). + */ + cachedInventory?(runnerId: string): EngineInventoryEntry[] | undefined; } export type LocalEngineDeps = { @@ -109,16 +115,21 @@ export class EngineManager { const ack = scope.kind === "local" ? await this.localRpc(operation) - : await this.deps.remote.send( - scope.runnerId, - scope.workspace, - operation, - onEvent - ); + : await this.deps.remote.send(scope.runnerId, operation, onEvent); // Refresh before returning, so a caller that awaits `rpc` sees the - // change notification fire no later than its own result. - if (operation.type !== "status") - await this.inventory(scope).catch(() => {}); + // change notification fire no later than its own result. A runner's + // own pushed-cache update can lag its ack by a round trip, so force a + // live read here rather than risk handing back what the cache held + // before the operation ran. + if (operation.type !== "status") { + const entries = + scope.kind === "local" + ? await this.localInventory().catch(() => null) + : await this.remoteInventory(scope, { force: true }).catch( + () => null + ); + if (entries) this.emitChanged(scope, entries); + } return ack; } @@ -156,12 +167,16 @@ export class EngineManager { } private async remoteInventory( - scope: Extract + scope: Extract, + opts: { force?: boolean } = {} ): Promise { + const cached = opts.force + ? undefined + : this.deps.remote.cachedInventory?.(scope.runnerId); + if (cached) return cached; let result: EngineInventoryEntry[] = []; const ack = await this.deps.remote.send( scope.runnerId, - scope.workspace, { type: "status" }, (event) => { if (event.type === "inventory") result = event.entries; diff --git a/apps/server/src/agents/remote/engine-runner-executor.ts b/apps/server/src/agents/remote/engine-runner-executor.ts index 826aef534..0ab7b241c 100644 --- a/apps/server/src/agents/remote/engine-runner-executor.ts +++ b/apps/server/src/agents/remote/engine-runner-executor.ts @@ -85,7 +85,19 @@ function setprivWrap( }); } -type RunResult = { code: number | null }; +type RunResult = { code: number | null; spawnError?: string }; + +/** + * `--version` output reduced to a safe version token, or null. Never falls + * back to the raw line: arbitrary CLI stderr/stdout must not reach a + * persisted inventory or the browser as if it were a version number. + */ +const SAFE_VERSION = /^\d+\.\d+(?:\.\d+)?[\w.+-]{0,40}$/; +function sanitizeVersion(output: string): string | null { + const line = output.trim().split("\n")[0]?.trim() ?? ""; + const match = /\d+\.\d+(?:\.\d+)?[\w.+-]*/.exec(line)?.[0]; + return match && SAFE_VERSION.test(match) ? match : null; +} export class EngineRunnerExecutor { private readonly logins: EngineLogins; @@ -132,16 +144,28 @@ export class EngineRunnerExecutor { clearTimeout(timer); resolve({ code }); }); - child.on("error", () => { + child.on("error", (error) => { clearTimeout(timer); - resolve({ code: null }); + resolve({ + code: null, + spawnError: (error as NodeJS.ErrnoException).code, + }); }); }); } - private async readVersion(bin: string): Promise { + /** + * Whether `bin` actually runs under the workload identity, and the safe + * version token it reports. A configured path is a launch-time target, + * not evidence of installation — a fresh host's `runner.json` names every + * engine's enforced path before any of them exist, so this always probes + * the real process rather than trusting path presence. + */ + private async probe( + bin: string + ): Promise<{ installed: boolean; version: string | null }> { let output = ""; - const { code } = await this.run( + const { code, spawnError } = await this.run( bin, ["--version"], this.config.env, @@ -150,10 +174,19 @@ export class EngineRunnerExecutor { output = (output + chunk).slice(-2_000); } ); - if (code !== 0) return null; - const line = output.trim().split("\n")[0]?.trim() ?? ""; - if (!line) return null; - return /\d+\.\d+(?:\.\d+)?[\w.+-]*/.exec(line)?.[0] ?? line; + if (spawnError || code !== 0) return { installed: false, version: null }; + return { installed: true, version: sanitizeVersion(output) }; + } + + /** Whether a configured install/update command's own executable can run at all. */ + private async commandUsable(command: ManagedCommand): Promise { + const { spawnError } = await this.run( + command.executable, + ["--version"], + { ...this.config.env, ...command.env }, + 5_000 + ); + return spawnError === undefined; } /** The scope-aware engine list and supported actions, for a snapshot view. */ @@ -162,8 +195,10 @@ export class EngineRunnerExecutor { RUNNER_ENGINES.map(async (engine) => { const cfg = this.config.engines[engine]; const bin = cfg?.bin ?? null; - const installed = Boolean(bin); - const version = installed ? await this.readVersion(bin!) : null; + const probed = bin + ? await this.probe(bin) + : { installed: false, version: null }; + const { installed, version } = probed; let signedIn: boolean | null = null; let detail: string | undefined; if (installed && isLoginEngine(engine)) { @@ -172,7 +207,11 @@ export class EngineRunnerExecutor { detail = status.detail; } const actions: EngineSupportedAction[] = []; - if (!installed && cfg?.install) actions.push("install"); + let issue: string | undefined; + if (!installed && cfg?.install) { + if (await this.commandUsable(cfg.install)) actions.push("install"); + else issue = "install-unavailable"; + } if (installed && cfg?.update) actions.push("update"); if (installed && isLoginEngine(engine)) actions.push("login", "login_cancel"); @@ -183,6 +222,7 @@ export class EngineRunnerExecutor { signedIn, version, ...(detail ? { detail } : {}), + ...(issue ? { issue } : {}), actions, }; }) @@ -195,8 +235,11 @@ export class EngineRunnerExecutor { onEvent?: (event: EngineOperationEvent) => void ): Promise { switch (operation.type) { - case "status": + case "status": { + const entries = await this.inventory(); + onEvent?.({ type: "inventory", entries }); return { ok: true }; + } case "install": return this.runManaged(operation.engine, "install", onEvent); case "update": @@ -251,7 +294,7 @@ export class EngineRunnerExecutor { phase: kind, message: kind === "install" ? "Installing…" : "Updating…", }); - const before = cfg?.bin ? await this.readVersion(cfg.bin) : null; + const before = cfg?.bin ? (await this.probe(cfg.bin)).version : null; await this.run( step.executable, step.args, @@ -268,7 +311,7 @@ export class EngineRunnerExecutor { }); } ); - const after = cfg?.bin ? await this.readVersion(cfg.bin) : null; + const after = cfg?.bin ? (await this.probe(cfg.bin)).version : null; const success = kind === "install" ? Boolean(after) diff --git a/apps/server/src/agents/remote/engine-transport.ts b/apps/server/src/agents/remote/engine-transport.ts new file mode 100644 index 000000000..0f761ecb4 --- /dev/null +++ b/apps/server/src/agents/remote/engine-transport.ts @@ -0,0 +1,96 @@ +import { + MANAGED_WORKSPACE, + type EngineOperationAck, + type EngineOperationEvent, +} from "./protocol.js"; +import { RunnerUnavailable, type RemoteRunnerService } from "./service.js"; +import type { RunnerEngineTransport } from "./engine-manager.js"; + +/** + * `RunnerEngineTransport` backed by the live runner wire connection: sends + * an `"engine"` command through `RemoteRunnerService.request`, which opens + * a channel for progress (`data` frames, NDJSON `EngineOperationEvent` + * lines) alongside the terminal `result` frame carrying the JSON-encoded + * ack. A runner that predates engine management never answers the + * command, surfacing as `unsupported`. + */ +export function remoteEngineTransport( + service: RemoteRunnerService +): RunnerEngineTransport { + return { + cachedInventory(runnerId) { + return service.engineInventorySnapshot(runnerId); + }, + async send(runnerId, operation, onEvent) { + // Engine management is runner-wide, not per-workspace; the wire + // Command still needs *a* workspace for routing, and every runner + // built for this always advertises MANAGED_WORKSPACE. + const placement = { runner: runnerId, workspace: MANAGED_WORKSPACE }; + if (!service.available(placement)) { + return { + ok: false, + error: "The runner is disconnected or unavailable.", + unsupported: true, + }; + } + try { + const { value, channel } = await service.request( + placement, + // Engine commands aren't bound to any agent; the id is a fixed, + // opaque placeholder the runner's "engine" branch never checks. + { + agentId: "@engine", + workspace: MANAGED_WORKSPACE, + kind: "engine", + operation, + }, + true + ); + try { + let buffer = ""; + let chunk: Buffer | null; + // The channel is handed back only once the whole round trip + // settled, so every progress frame the runner sent is already + // sitting in its paused-mode buffer — drain it synchronously + // rather than racing a "data" listener against stream teardown. + while ( + channel && + (chunk = channel.read() as Buffer | null) !== null + ) { + buffer += chunk.toString("utf8"); + let newline: number; + while ((newline = buffer.indexOf("\n")) >= 0) { + const line = buffer.slice(0, newline); + buffer = buffer.slice(newline + 1); + if (!line) continue; + try { + onEvent?.(JSON.parse(line) as EngineOperationEvent); + } catch { + /* a malformed progress line is not fatal to the operation */ + } + } + } + } finally { + channel?.destroy(); + } + if (typeof value !== "string") { + return { ok: false, error: "No response from the runner." }; + } + try { + return JSON.parse(value) as EngineOperationAck; + } catch { + return { ok: false, error: "Malformed response from the runner." }; + } + } catch (error) { + if (error instanceof RunnerUnavailable) { + return { ok: false, error: error.message, unsupported: true }; + } + return { + ok: false, + error: + error instanceof Error ? error.message : "Runner request failed.", + }; + } + }, + }; +} diff --git a/apps/server/src/agents/remote/protocol.ts b/apps/server/src/agents/remote/protocol.ts index 9f91aca01..298090467 100644 --- a/apps/server/src/agents/remote/protocol.ts +++ b/apps/server/src/agents/remote/protocol.ts @@ -1,2 +1,3 @@ export * from "@dispatch/runner-protocol"; export { hostChannel, wireFrames } from "@dispatch/runner-protocol/node"; +export * from "@dispatch/runner-protocol/engine-management"; diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 4b9305532..eb10fbb12 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -40,8 +40,13 @@ import { wireFrames, type Command, type Frame, + type RunnerEngine, type RunnerRepository, } from "./protocol.js"; +import { + EngineRunnerExecutor, + type ManagedCommand, +} from "./engine-runner-executor.js"; type RunnerConfig = { endpoint: string; @@ -57,6 +62,16 @@ type RunnerConfig = { bins: HostLaunch["bins"]; adapter?: string[]; workspaces?: Record; + /** + * Operator-approved install/update commands per engine, run under the + * same workload identity as everything else here. The launch path for + * each engine comes from `bins` above, not from here — this only names + * how to get (or refresh) what lives at that path. Omitted entirely for + * runners that don't offer managed install/update. + */ + engines?: Partial< + Record + >; }; export const runnerGitArgs = [ @@ -196,6 +211,19 @@ export async function runRemoteRunner(filename: string) { await chmod(hostRoot, 0o711); const sampleHealth = runnerHealthSampler(); + const engineExecutor = new EngineRunnerExecutor({ + uid: config.uid, + gid: config.gid, + env, + engines: { + claude: { bin: config.bins.claudeBin || null, ...config.engines?.claude }, + codex: { bin: config.bins.codexBin || null, ...config.engines?.codex }, + opencode: { + bin: config.bins.opencodeBin || null, + ...config.engines?.opencode, + }, + }, + }); const storage = await realpath(config.state); const sessions = path.join(storage, "sessions"); const cache = path.join(storage, "repositories"); @@ -451,6 +479,22 @@ export async function runRemoteRunner(filename: string) { sampling = false; } }; + let samplingEngines = false; + const reportEngineInventory = async () => { + if (samplingEngines || socket.destroyed) return; + samplingEngines = true; + try { + const entries = await engineExecutor.inventory(); + safeSend({ type: "engine_inventory", entries }); + } catch (error) { + console.warn( + "Runner engine inventory unavailable:", + (error as Error).message + ); + } finally { + samplingEngines = false; + } + }; const channels = new Map>(); const timeout = setTimeout(() => socket.destroy(), 5000); socket.on("error", (error: Error) => @@ -475,6 +519,25 @@ export async function runRemoteRunner(filename: string) { async function request(id: string, command: Command) { if (!isOpaqueId(id)) throw new Error("Invalid runner request ID"); if (socket.destroyed) return; + if (command.kind === "engine") { + const ack = await engineExecutor.handle( + command.operation, + (event) => { + if (!socket.destroyed) + safeSend({ + type: "data", + id, + data: Buffer.from( + JSON.stringify(event) + "\n", + "utf8" + ).toString("base64"), + }); + } + ); + safeSend({ type: "result", id, value: JSON.stringify(ack) }); + if (command.operation.type !== "status") void reportEngineInventory(); + return; + } const { agentId, workspace } = command; const target = isOpaqueId(workspace) && Object.hasOwn(workspaces, workspace) @@ -616,7 +679,11 @@ export async function runRemoteRunner(filename: string) { const send = wireFrames(socket, (frame) => { if (frame.type === "accept_health" && !healthInterval) { void reportHealth(); - healthInterval = setInterval(() => void reportHealth(), 30_000); + void reportEngineInventory(); + healthInterval = setInterval(() => { + void reportHealth(); + void reportEngineInventory(); + }, 30_000); } else if (frame.type === "request") { void request(frame.id, frame.command).catch((error) => safeSend({ @@ -646,6 +713,7 @@ export async function runRemoteRunner(filename: string) { ? [MANAGED_WORKSPACE] : configuredHandles, ...(managedWorkspace ? { managedWorkspace: true } : {}), + engineManagement: true, }); }); }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 14a66e491..a53956609 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -13,7 +13,9 @@ import { hostChannel, MANAGED_WORKSPACE, wireFrames, + parseEngineInventory, type Command, + type EngineInventoryEntry, type Frame, type Placement, } from "./protocol.js"; @@ -85,6 +87,10 @@ export type RunnerSummary = { status: RunnerStatus; health?: RunnerHealth; healthReceivedAt?: string; + /** Whether this (online) peer advertised support for engine management. */ + engineManagement: boolean; + /** Last pushed snapshot while online; absent offline or before the first push. */ + engines?: EngineInventoryEntry[]; workspaces: string[]; managedWorkspace?: true; }; @@ -126,6 +132,10 @@ type Peer = { gate: Gate; health?: { sample: RunnerHealth; receivedAt: Date }; reportsHealth?: boolean; + /** Advertised in `ready`; whether this peer answers the `"engine"` command. */ + engineManagement: boolean; + /** Last pushed, validated engine inventory; absent until the runner first reports one. */ + engines?: EngineInventoryEntry[]; pending: Map; channels: Map; }; @@ -639,6 +649,7 @@ export class RemoteRunnerService { peer = { socket, reportsHealth: frame.health === true, + engineManagement: frame.engineManagement === true, send, workspaces: new Set(frame.workspaces), managedWorkspace: frame.managedWorkspace === true, @@ -675,6 +686,10 @@ export class RemoteRunnerService { error ) ); + } else if (frame.type === "engine_inventory") { + const entries = parseEngineInventory(frame.entries); + if (entries === null) return socket.destroy(); + peer.engines = entries; } else if (frame.type === "result") peer.pending.get(frame.id)?.(frame); else if (frame.type === "data") peer.channels.get(frame.id)?.push(Buffer.from(frame.data, "base64")); @@ -842,6 +857,9 @@ export class RemoteRunnerService { // Legacy locators keep addressing the configured id. id: this.legacy.id, name: this.legacy.id, + engineManagement: + peer?.gate.approved() === true && peer.engineManagement, + ...(peer?.engines ? { engines: peer.engines } : {}), ...(peer?.health ? { health: peer.health.sample, @@ -876,6 +894,8 @@ export class RemoteRunnerService { : online ? "online" : "offline", + engineManagement: online && peer.engineManagement, + ...(online && peer.engines ? { engines: peer.engines } : {}), ...(online && peer.health ? { health: peer.health.sample, @@ -1142,6 +1162,14 @@ export class RemoteRunnerService { ); } + /** The runner's last pushed, validated engine inventory, if any. */ + engineInventorySnapshot( + runnerId: string + ): EngineInventoryEntry[] | undefined { + const peer = this.peers.get(runnerId); + return peer?.gate.approved() ? peer.engines : undefined; + } + available(placement: Placement) { const peer = this.peers.get(placement.runner); return Boolean( diff --git a/apps/server/src/routes/engine-management.ts b/apps/server/src/routes/engine-management.ts new file mode 100644 index 000000000..6775a6d4e --- /dev/null +++ b/apps/server/src/routes/engine-management.ts @@ -0,0 +1,84 @@ +import type { FastifyInstance } from "fastify"; +import * as z from "zod/v4"; + +import { + EngineManager, + type EngineScope, +} from "../agents/remote/engine-manager.js"; + +const scopeSchema = z.union([ + z.object({ kind: z.literal("local") }), + z.object({ + kind: z.literal("runner"), + runnerId: z.string().min(1).max(128), + }), +]); + +function parseScopeQuery(query: unknown): EngineScope | null { + const q = (query ?? {}) as Record; + const parsed = scopeSchema.safeParse({ + kind: q.scope, + ...(q.scope === "runner" ? { runnerId: q.runnerId } : {}), + }); + return parsed.success ? parsed.data : null; +} + +const engineOperationSchema = z.union([ + z.object({ type: z.literal("status") }), + z.object({ + type: z.literal("install"), + engine: z.enum(["claude", "codex", "opencode"]), + }), + z.object({ + type: z.literal("update"), + engine: z.enum(["claude", "codex", "opencode"]), + }), + z.object({ + type: z.literal("login_start"), + engine: z.enum(["claude", "codex", "opencode"]), + restart: z.boolean().optional(), + }), + z.object({ + type: z.literal("login_submit"), + loginId: z.string().min(1).max(128), + code: z.string().min(1).max(2000), + }), + z.object({ + type: z.literal("login_cancel"), + loginId: z.string().min(1).max(128), + }), +]); + +const operationBodySchema = z.object({ + scope: scopeSchema, + operation: engineOperationSchema, +}); + +/** + * Engine install/update/sign-in, scoped to this machine or a named runner. + * Ordinary `/api` routes — the global auth hook protects them like every + * other control route. Backed by `EngineManager`, which wraps the existing + * local `EngineLogins`/`EngineUpdateOperations` untouched and forwards + * runner-scoped operations over the wire. + */ +export async function registerEngineManagementRoutes( + app: FastifyInstance, + manager: EngineManager +): Promise { + app.get("/api/v1/engine-management/inventory", async (request, reply) => { + const scope = parseScopeQuery(request.query); + if (!scope) { + return reply.code(400).send({ error: "Invalid or missing scope." }); + } + return { entries: await manager.inventory(scope) }; + }); + + app.post("/api/v1/engine-management/operations", async (request, reply) => { + const body = operationBodySchema.safeParse(request.body); + if (!body.success) { + return reply.code(400).send({ error: "Invalid scope or operation." }); + } + const ack = await manager.rpc(body.data.scope, body.data.operation); + return { ack }; + }); +} diff --git a/apps/server/src/routes/system.ts b/apps/server/src/routes/system.ts index e5c68ca36..f05723b93 100644 --- a/apps/server/src/routes/system.ts +++ b/apps/server/src/routes/system.ts @@ -75,6 +75,8 @@ type SystemRouteDeps = { maintenanceMode?: () => string; engineBins: { claude: string; codex: string; opencode?: string }; localCertificateTrust?: boolean; + /** Shared with engine-management routes so both see the same operation state. */ + engineUpdates?: EngineUpdateOperations; /** Update recovery helper protocol; omitted in tests that don't need it. */ }; @@ -138,13 +140,12 @@ export async function registerSystemRoutes( }; }); - const engineUpdates = new EngineUpdateOperations( - engineOperationStore(deps.pool), - { + const engineUpdates = + deps.engineUpdates ?? + new EngineUpdateOperations(engineOperationStore(deps.pool), { onError: (error) => deps.appLog.error({ err: error }, "Engine update persistence failed"), - } - ); + }); app.get("/api/v1/system/engines", async (request) => { const operations = await engineUpdates.read(); return { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 58638f17b..0e7fbc877 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -137,8 +137,15 @@ import { createAutoCheckRuntime } from "./release-auto-check.js"; import { registerStaticRoutes } from "./routes/static.js"; import { registerSystemRoutes } from "./routes/system.js"; import { registerEngineLoginRoutes } from "./routes/engine-login.js"; +import { registerEngineManagementRoutes } from "./routes/engine-management.js"; import { EngineLogins } from "./agents/engine-login.js"; import { engineStatuses } from "./agents/engine-availability.js"; +import { + EngineUpdateOperations, + engineOperationStore, +} from "./agents/engine-updates.js"; +import { EngineManager } from "./agents/remote/engine-manager.js"; +import { remoteEngineTransport } from "./agents/remote/engine-transport.js"; import { registerPluginRoutes } from "./routes/plugin.js"; import { registerResourceRoutes } from "./routes/resources.js"; import { @@ -1098,7 +1105,24 @@ async function registerRoutes() { }); await registerScheduledMessageRoutes(app, scheduledMessages); + // Shared with registerEngineManagementRoutes below: one login/update + // tracker per process, so a scope-aware view (local or runner) and the + // existing engine routes never diverge on the same in-flight state. + const engineLogins = new EngineLogins({ + resolveBin: async (engine) => + ( + await engineStatuses({ + claude: config.claudeBin, + codex: config.codexBin, + }) + ).find((status) => status.id === engine)?.path ?? null, + }); + const engineUpdates = new EngineUpdateOperations(engineOperationStore(pool), { + onError: (error) => + app.log.error({ err: error }, "Engine update persistence failed"), + }); await registerSystemRoutes(app, { + engineUpdates, runnerWorkspaceAvailable: (placement) => remoteRunner?.available(placement) ?? false, slackAnswers, @@ -1132,16 +1156,28 @@ async function registerRoutes() { opencode: config.opencodeBin, }, }); - await registerEngineLoginRoutes( + await registerEngineLoginRoutes(app, engineLogins); + await registerEngineManagementRoutes( app, - new EngineLogins({ - resolveBin: async (engine) => - ( - await engineStatuses({ - claude: config.claudeBin, - codex: config.codexBin, - }) - ).find((status) => status.id === engine)?.path ?? null, + new EngineManager({ + local: { + logins: engineLogins, + updates: engineUpdates, + overrides: { + claude: config.claudeBin, + codex: config.codexBin, + opencode: config.opencodeBin, + }, + }, + remote: remoteRunner + ? remoteEngineTransport(remoteRunner) + : { + send: async () => ({ + ok: false, + error: "Runner enrollment is disabled.", + unsupported: true, + }), + }, }) ); await registerUpdateRecoveryRoutes(app, updateRecoveryRuntime.routeDeps); diff --git a/apps/server/test/engine-management-routes.test.ts b/apps/server/test/engine-management-routes.test.ts new file mode 100644 index 000000000..2550e14a8 --- /dev/null +++ b/apps/server/test/engine-management-routes.test.ts @@ -0,0 +1,114 @@ +import Fastify from "fastify"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { registerEngineManagementRoutes } from "../src/routes/engine-management.js"; +import { + EngineManager, + type RunnerEngineTransport, +} from "../src/agents/remote/engine-manager.js"; +import type { EngineLogins } from "../src/agents/engine-login.js"; +import type { EngineUpdateOperations } from "../src/agents/engine-updates.js"; + +function fakeLogins(): EngineLogins { + return { + status: vi.fn(async () => ({ + engine: "claude", + installed: true, + signedIn: true, + })), + start: vi.fn(), + submitCode: vi.fn(), + cancel: vi.fn(), + get: vi.fn(), + current: vi.fn(), + close: vi.fn(), + } as unknown as EngineLogins; +} + +function fakeUpdates(): EngineUpdateOperations { + return { + start: vi.fn(), + read: vi.fn(async () => ({})), + } as unknown as EngineUpdateOperations; +} + +describe("engine-management routes", () => { + afterEach(() => vi.clearAllMocks()); + + it("reads local inventory and rejects a missing scope", async () => { + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: { send: vi.fn() }, + }); + const test = Fastify(); + await registerEngineManagementRoutes(test, manager); + + const ok = await test.inject({ + method: "GET", + url: "/api/v1/engine-management/inventory?scope=local", + }); + expect(ok.statusCode).toBe(200); + expect(JSON.parse(ok.body).entries).toEqual( + expect.arrayContaining([expect.objectContaining({ id: "claude" })]) + ); + + const bad = await test.inject({ + method: "GET", + url: "/api/v1/engine-management/inventory", + }); + expect(bad.statusCode).toBe(400); + + await test.close(); + }); + + it("forwards a runner-scoped operation to the transport", async () => { + const send = vi.fn(async () => ({ + ok: true, + })); + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: { send }, + }); + const test = Fastify(); + await registerEngineManagementRoutes(test, manager); + + const res = await test.inject({ + method: "POST", + url: "/api/v1/engine-management/operations", + payload: { + scope: { kind: "runner", runnerId: "r1" }, + operation: { type: "login_start", engine: "claude" }, + }, + }); + expect(res.statusCode).toBe(200); + expect(JSON.parse(res.body).ack).toEqual({ ok: true }); + expect(send).toHaveBeenCalledWith( + "r1", + { type: "login_start", engine: "claude" }, + undefined + ); + + await test.close(); + }); + + it("rejects a malformed operation body", async () => { + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: { send: vi.fn() }, + }); + const test = Fastify(); + await registerEngineManagementRoutes(test, manager); + + const res = await test.inject({ + method: "POST", + url: "/api/v1/engine-management/operations", + payload: { + scope: { kind: "local" }, + operation: { type: "launch_rocket" }, + }, + }); + expect(res.statusCode).toBe(400); + + await test.close(); + }); +}); diff --git a/apps/server/test/engine-manager.test.ts b/apps/server/test/engine-manager.test.ts index 060b2e2a9..bb3510b26 100644 --- a/apps/server/test/engine-manager.test.ts +++ b/apps/server/test/engine-manager.test.ts @@ -188,12 +188,11 @@ describe("EngineManager runner scope", () => { remote: transport, }); await manager.rpc( - { kind: "runner", runnerId: "r1", workspace: "w1" }, + { kind: "runner", runnerId: "r1" }, { type: "login_start", engine: "claude" } ); expect(transport.send).toHaveBeenCalledWith( "r1", - "w1", { type: "login_start", engine: "claude" }, undefined ); @@ -201,7 +200,7 @@ describe("EngineManager runner scope", () => { it("reads inventory from the runner's streamed inventory event", async () => { const transport = fakeTransport({ - send: vi.fn(async (_r, _w, _op, onEvent) => { + send: vi.fn(async (_r, _op, onEvent) => { onEvent?.({ type: "inventory", entries: [ @@ -225,7 +224,6 @@ describe("EngineManager runner scope", () => { const inventory = await manager.inventory({ kind: "runner", runnerId: "r1", - workspace: "w1", }); expect(inventory).toEqual([ { @@ -254,7 +252,6 @@ describe("EngineManager runner scope", () => { const inventory = await manager.inventory({ kind: "runner", runnerId: "r1", - workspace: "w1", }); expect(inventory.every((e) => !e.installed && e.signedIn === null)).toBe( true @@ -264,7 +261,7 @@ describe("EngineManager runner scope", () => { it("notifies onChanged listeners after a state-changing operation", async () => { const transport = fakeTransport({ - send: vi.fn(async (_r, _w, op) => { + send: vi.fn(async (_r, op) => { if (op.type === "status") { return { ok: true }; } @@ -275,7 +272,7 @@ describe("EngineManager runner scope", () => { local: { logins: fakeLogins(), updates: fakeUpdates() }, remote: transport, }); - const scope = { kind: "runner" as const, runnerId: "r1", workspace: "w1" }; + const scope = { kind: "runner" as const, runnerId: "r1" }; const listener = vi.fn(); const unsubscribe = manager.onChanged(scope, listener); await manager.rpc(scope, { type: "login_start", engine: "claude" }); diff --git a/apps/server/test/engine-runner-executor.test.ts b/apps/server/test/engine-runner-executor.test.ts index b24c3abdd..39d5854a2 100644 --- a/apps/server/test/engine-runner-executor.test.ts +++ b/apps/server/test/engine-runner-executor.test.ts @@ -66,6 +66,95 @@ if (args === "--version") { expect(codex.actions).toEqual([]); }); + it("reports not installed when a configured launch path doesn't actually exist yet", async () => { + // A fresh runner's runner.json names every engine's enforced launch + // path before any of them have been installed — the configured path + // string is not evidence of installation. + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { + claude: { + bin: path.join(dir, "does-not-exist"), + install: { executable: fake, args: ["install"] }, + }, + }, + }); + const inventory = await executor.inventory(); + const claude = inventory.find((entry) => entry.id === "claude")!; + expect(claude.installed).toBe(false); + expect(claude.version).toBeNull(); + expect(claude.signedIn).toBeNull(); + expect(claude.actions).toEqual(["install"]); + }); + + it("never reports raw CLI output as a version", async () => { + const chatty = path.join(dir, "fake-chatty.mjs"); + writeFileSync( + chatty, + `#!/usr/bin/env node\nconsole.log("not a version string, just chatter");\nprocess.exit(0);\n` + ); + chmodSync(chatty, 0o755); + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { claude: { bin: chatty } }, + }); + const inventory = await executor.inventory(); + const claude = inventory.find((entry) => entry.id === "claude")!; + expect(claude.installed).toBe(true); + expect(claude.version).toBeNull(); + }); + + it("flags install-unavailable and withholds the action when the installer's own executable is missing", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { + codex: { + bin: null, + install: { + executable: path.join(dir, "no-such-npm"), + args: ["install", "-g"], + }, + }, + }, + }); + const inventory = await executor.inventory(); + const codex = inventory.find((entry) => entry.id === "codex")!; + expect(codex.installed).toBe(false); + expect(codex.actions).toEqual([]); + expect(codex.issue).toBe("install-unavailable"); + }); + + it("pushes a fresh inventory snapshot for a status operation", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { claude: { bin: fake } }, + }); + const events: unknown[] = []; + const ack = await executor.handle({ type: "status" }, (event) => + events.push(event) + ); + expect(ack).toEqual({ ok: true }); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + type: "inventory", + entries: expect.arrayContaining([ + expect.objectContaining({ id: "claude", installed: true }), + ]), + }); + }); + it("offers install only when a managed install command is configured", async () => { executor = new EngineRunnerExecutor({ uid: 1000, diff --git a/apps/server/test/engine-wire.test.ts b/apps/server/test/engine-wire.test.ts new file mode 100644 index 000000000..f2f670f67 --- /dev/null +++ b/apps/server/test/engine-wire.test.ts @@ -0,0 +1,288 @@ +import type { AddressInfo } from "node:net"; +import { connect, type TLSSocket } from "node:tls"; +import type { Pool } from "pg"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; + +import { exchangeCode } from "../src/agents/remote/enrollment.js"; +import { remoteEngineTransport } from "../src/agents/remote/engine-transport.js"; +import { + MANAGED_WORKSPACE, + wireFrames, + type EngineOperationEvent, + type Frame, +} from "../src/agents/remote/protocol.js"; +import { RunnerRegistry } from "../src/agents/remote/registry.js"; +import { RemoteRunnerService } from "../src/agents/remote/service.js"; +import { generateRunnerKey } from "../src/agents/remote/x509.js"; +import { runTestMigrations, setupTestDb, teardownTestDb } from "./db/setup.js"; + +const HOST = "127.0.0.1"; + +function parseCommand(command: string) { + const value = (flag: string) => + new RegExp(`--${flag} (\\S+)`).exec(command)?.[1] ?? ""; + return { + endpoint: value("endpoint"), + pin: value("ca-sha256"), + code: value("code"), + }; +} + +async function waitFor(check: () => boolean | Promise) { + for (let i = 0; i < 100; i++) { + if (await check()) return; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + throw new Error("condition not reached"); +} + +/** A fake runner that answers `"engine"` requests the way runner.ts does. */ +function dialEngineRunner(input: { + endpoint: string; + ca: string; + cert: string; + key: string; + workspaces: string[]; + engineManagement?: boolean; + onEngine?: ( + id: string, + reply: (frame: Frame) => void, + operation: unknown + ) => void; + inventoryEntries?: unknown[]; +}) { + const url = new URL(input.endpoint); + return new Promise<{ + socket: TLSSocket; + pushInventory: (entries: unknown) => void; + }>((resolve, reject) => { + const socket = connect({ + host: url.hostname, + port: Number(url.port), + ca: input.ca, + cert: input.cert, + key: input.key, + rejectUnauthorized: true, + }); + socket.on("error", reject); + const send = wireFrames(socket, (frame) => { + if (frame.type === "request" && frame.command.kind === "engine") { + input.onEngine?.(frame.id, send, frame.command.operation); + } + }); + socket.once("secureConnect", () => { + send({ + type: "ready", + version: 1, + ...(input.engineManagement !== false ? { engineManagement: true } : {}), + workspaces: input.workspaces, + }); + resolve({ + socket, + pushInventory: (entries) => + send({ type: "engine_inventory", entries } as Frame), + }); + }); + }); +} + +describe("engine wire integration", () => { + let pool: Pool; + const services: RemoteRunnerService[] = []; + const sockets: TLSSocket[] = []; + + const makeService = () => { + const service = new RemoteRunnerService(undefined, { + registry: new RunnerRegistry(pool), + host: HOST, + endpointHost: HOST, + }); + services.push(service); + return service; + }; + + async function enroll(service: RemoteRunnerService, name: string) { + const created = await service.createRegistration(name); + const { endpoint, pin, code } = parseCommand(created.command); + const runnerKey = generateRunnerKey(); + const enrolled = await exchangeCode({ + endpoint, + pin, + code, + publicKey: runnerKey.publicKey, + }); + return { created, endpoint, key: runnerKey.key, ...enrolled }; + } + + beforeAll(async () => { + pool = await setupTestDb(); + await runTestMigrations(); + }, 60_000); + + afterEach(async () => { + for (const socket of sockets.splice(0)) socket.destroy(); + for (const service of services.splice(0)) service.close(); + await pool.query("DELETE FROM runner_registrations"); + await pool.query("DELETE FROM runner_authority"); + }); + + afterAll(async () => { + await teardownTestDb(); + }); + + it("round-trips an engine operation with streamed progress and a final ack", async () => { + const service = makeService(); + const alpha = await enroll(service, "alpha"); + const { socket } = await dialEngineRunner({ + endpoint: alpha.endpoint, + ca: alpha.ca, + cert: alpha.cert, + key: alpha.key, + workspaces: [MANAGED_WORKSPACE], + onEngine: (id, reply, operation) => { + expect(operation).toEqual({ type: "update", engine: "claude" }); + const event: EngineOperationEvent = { + type: "operation_progress", + operationId: "op-1", + engine: "claude", + phase: "update", + message: "Updating…", + }; + reply({ + type: "data", + id, + data: Buffer.from(JSON.stringify(event) + "\n", "utf8").toString( + "base64" + ), + }); + reply({ + type: "result", + id, + value: JSON.stringify({ ok: true, operationId: "op-1" }), + }); + }, + }); + sockets.push(socket); + await waitFor(() => + service.available({ + runner: alpha.created.id, + workspace: MANAGED_WORKSPACE, + }) + ); + + const transport = remoteEngineTransport(service); + const events: EngineOperationEvent[] = []; + const ack = await transport.send( + alpha.created.id, + { type: "update", engine: "claude" }, + (event) => events.push(event) + ); + expect(ack).toEqual({ ok: true, operationId: "op-1" }); + expect(events).toEqual([ + { + type: "operation_progress", + operationId: "op-1", + engine: "claude", + phase: "update", + message: "Updating…", + }, + ]); + }); + + it("reports unsupported for an offline or non-engine-aware runner", async () => { + const service = makeService(); + const alpha = await enroll(service, "alpha"); + const transport = remoteEngineTransport(service); + const ack = await transport.send(alpha.created.id, { type: "status" }); + expect(ack).toMatchObject({ ok: false, unsupported: true }); + }); + + it("stores and validates a pushed engine inventory, exposed via list()", async () => { + const service = makeService(); + const alpha = await enroll(service, "alpha"); + const { socket, pushInventory } = await dialEngineRunner({ + endpoint: alpha.endpoint, + ca: alpha.ca, + cert: alpha.cert, + key: alpha.key, + workspaces: [MANAGED_WORKSPACE], + }); + sockets.push(socket); + await waitFor(() => + service.available({ + runner: alpha.created.id, + workspace: MANAGED_WORKSPACE, + }) + ); + + const entries = [ + { + id: "claude", + label: "Claude Code", + installed: true, + signedIn: true, + version: "1.2.3", + actions: ["update", "login", "login_cancel"], + }, + ]; + pushInventory(entries); + await waitFor( + () => service.engineInventorySnapshot(alpha.created.id) !== undefined + ); + expect(service.engineInventorySnapshot(alpha.created.id)).toEqual(entries); + const summary = (await service.list())[0]; + expect(summary?.engines).toEqual(entries); + expect(summary?.engineManagement).toBe(true); + }); + + it("reports engineManagement false for a runner that never advertised it", async () => { + const service = makeService(); + const alpha = await enroll(service, "alpha"); + const { socket } = await dialEngineRunner({ + endpoint: alpha.endpoint, + ca: alpha.ca, + cert: alpha.cert, + key: alpha.key, + workspaces: [MANAGED_WORKSPACE], + engineManagement: false, + }); + sockets.push(socket); + await waitFor(() => + service.available({ + runner: alpha.created.id, + workspace: MANAGED_WORKSPACE, + }) + ); + expect((await service.list())[0]?.engineManagement).toBe(false); + }); + + it("drops the connection on a malformed pushed inventory", async () => { + const service = makeService(); + const alpha = await enroll(service, "alpha"); + const { socket, pushInventory } = await dialEngineRunner({ + endpoint: alpha.endpoint, + ca: alpha.ca, + cert: alpha.cert, + key: alpha.key, + workspaces: [MANAGED_WORKSPACE], + }); + sockets.push(socket); + await waitFor(() => + service.available({ + runner: alpha.created.id, + workspace: MANAGED_WORKSPACE, + }) + ); + pushInventory([ + { + id: "not-a-real-engine", + label: "x", + installed: true, + signedIn: null, + version: null, + actions: [], + }, + ]); + await waitFor(() => socket.destroyed); + }); +}); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index b44d5ebc4..28bf40c71 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -198,7 +198,13 @@ describe("runner enrollment service", () => { /^dispatch-runner remote-runner-pair --endpoint https:\/\/127\.0\.0\.1:\d+ --ca-sha256 [a-f0-9]{64} --code \S+$/ ); expect(await service.list()).toEqual([ - { id: created.id, name: "alpha", status: "pending", workspaces: [] }, + { + id: created.id, + name: "alpha", + status: "pending", + engineManagement: false, + workspaces: [], + }, ]); const { endpoint, pin, code } = parseCommand(created.command); @@ -252,6 +258,7 @@ describe("runner enrollment service", () => { id: created.id, name: "alpha", status: "online", + engineManagement: false, workspaces: ["proof"], }, ]); diff --git a/apps/server/test/runner-routes.test.ts b/apps/server/test/runner-routes.test.ts index 20c720e87..e7b31d847 100644 --- a/apps/server/test/runner-routes.test.ts +++ b/apps/server/test/runner-routes.test.ts @@ -71,7 +71,13 @@ describe("runner control API", () => { }); expect(listed.json()).toEqual({ runners: [ - { id: body.id, name: "lima", status: "pending", workspaces: [] }, + { + id: body.id, + name: "lima", + status: "pending", + engineManagement: false, + workspaces: [], + }, ], }); diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index 406f47832..0a6d82c59 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -132,7 +132,6 @@ export function RunnerSettings(): JSX.Element { scope={{ kind: "runner", runnerId: runner.id, - workspace: runner.workspaces[0] ?? "", }} /> )} diff --git a/apps/web/src/components/runner-engines/runner-engines.test.tsx b/apps/web/src/components/runner-engines/runner-engines.test.tsx index bbf353c8c..3a5f19ade 100644 --- a/apps/web/src/components/runner-engines/runner-engines.test.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.test.tsx @@ -74,25 +74,24 @@ it("renders each engine's installed/signed-in state and available actions", asyn expect(screen.getByTestId("runner-engine-codex-install")).toBeTruthy(); }); -it("posts an install operation scoped to a runner workspace and refreshes", async () => { +it("posts an install operation scoped to a runner and refreshes", async () => { const ack: EngineOperationAck = { ok: true, operationId: "op-1" }; vi.mocked(api).mockImplementation( async (path: string, init?: RequestInit) => { if (init?.method === "POST") { expect(JSON.parse(init.body as string)).toMatchObject({ - scope: { kind: "runner", runnerId: "r1", workspace: "w1" }, + scope: { kind: "runner", runnerId: "r1" }, operation: { type: "install", engine: "codex" }, }); return { ack }; } expect(path).toContain("scope=runner"); expect(path).toContain("runnerId=r1"); - expect(path).toContain("workspace=w1"); return { entries: baseEntries }; } ); - renderWithClient({ kind: "runner", runnerId: "r1", workspace: "w1" }); + renderWithClient({ kind: "runner", runnerId: "r1" }); await waitFor(() => screen.getByTestId("runner-engine-codex-install")); fireEvent.click(screen.getByTestId("runner-engine-codex-install")); diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index 4ee1f9087..1192c3f3b 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -166,6 +166,13 @@ function EngineRow({

{entry.detail}

)} + {entry.issue === "install-unavailable" && ( +

+ Install isn't available on this runner — its install command couldn't + run (likely missing npm/node for this engine). +

+ )} + {operation.isError && (

{operation.error.message} diff --git a/apps/web/src/hooks/use-runner-engines.ts b/apps/web/src/hooks/use-runner-engines.ts index 804b55740..af1b0f45a 100644 --- a/apps/web/src/hooks/use-runner-engines.ts +++ b/apps/web/src/hooks/use-runner-engines.ts @@ -12,23 +12,21 @@ import { api } from "@/lib/api"; /** * Scope-aware engine inventory and install/update/sign-in, for an engine - * running locally or on a named runner workspace. Expects the HTTP routes: + * running locally or on a named runner (runner-wide, not per-workspace). + * Expects the HTTP routes: * * - `GET /api/v1/engine-management/inventory?{scope query}` → `{ entries }` * - `POST /api/v1/engine-management/operations` with `{ scope, operation }` * body → `{ ack }` * - * where the scope query is `scope=local` or - * `scope=runner&runnerId=&workspace=`. Both routes back onto - * `EngineManager` (`apps/server/src/agents/remote/engine-manager.ts`). + * where the scope query is `scope=local` or `scope=runner&runnerId=`. + * Both routes back onto `EngineManager` + * (`apps/server/src/agents/remote/engine-manager.ts`). */ function scopeQuery(scope: EngineScope): string { const params = new URLSearchParams({ scope: scope.kind }); - if (scope.kind === "runner") { - params.set("runnerId", scope.runnerId); - params.set("workspace", scope.workspace); - } + if (scope.kind === "runner") params.set("runnerId", scope.runnerId); return params.toString(); } diff --git a/packages/runner-protocol/src/engine-management.ts b/packages/runner-protocol/src/engine-management.ts index a8ee1fc69..5b06d7b4f 100644 --- a/packages/runner-protocol/src/engine-management.ts +++ b/packages/runner-protocol/src/engine-management.ts @@ -23,6 +23,13 @@ export type EngineInventoryEntry = { version: string | null; /** Who it's signed in as, or how; never a token, URL or code. */ detail?: string; + /** + * A short, pre-defined reason an action isn't offered even though it + * otherwise would be — e.g. `"install-unavailable"` when a configured + * install/update command's own executable can't run (missing npm/node). + * Never raw CLI output. + */ + issue?: string; actions: EngineSupportedAction[]; }; @@ -91,16 +98,18 @@ export const RUNNER_ENGINES: readonly RunnerEngine[] = [ "opencode", ]; -/** Where an engine's CLI runs: this machine, or a named runner workspace. */ +/** + * Where an engine's CLI runs: this machine, or a named runner. Runner-wide, + * not per-workspace — a runner's `bins` (and its install/update commands) + * are one configuration for the whole runner, not one per workspace. + */ export type EngineScope = | { kind: "local" } - | { kind: "runner"; runnerId: string; workspace: string }; + | { kind: "runner"; runnerId: string }; /** A stable string key for a scope, for query params, cache keys and event names. */ export function engineScopeKey(scope: EngineScope): string { - return scope.kind === "local" - ? "local" - : `runner:${scope.runnerId}/${scope.workspace}`; + return scope.kind === "local" ? "local" : `runner:${scope.runnerId}`; } export function isEngineOperation(value: unknown): value is EngineOperation { @@ -115,3 +124,65 @@ export function isEngineOperation(value: unknown): value is EngineOperation { type === "login_cancel" ); } + +const SUPPORTED_ACTIONS = new Set([ + "install", + "update", + "login", + "login_cancel", +]); + +/** + * Validate a runner-pushed inventory snapshot before trusting it: bounded + * length, known engine ids and action names, safe-shaped version/detail + * strings. A malformed or over-long snapshot is dropped entirely (returns + * null) rather than partially accepted. + */ +export function parseEngineInventory( + input: unknown +): EngineInventoryEntry[] | null { + if (!Array.isArray(input) || input.length > RUNNER_ENGINES.length) + return null; + const entries: EngineInventoryEntry[] = []; + const seen = new Set(); + for (const item of input) { + if (!item || typeof item !== "object") return null; + const { id, label, installed, signedIn, version, detail, issue, actions } = + item as Record; + if ( + typeof id !== "string" || + !(RUNNER_ENGINES as readonly string[]).includes(id) || + seen.has(id as RunnerEngine) || + typeof label !== "string" || + label.length > 80 || + typeof installed !== "boolean" || + (signedIn !== null && typeof signedIn !== "boolean") || + (version !== null && + (typeof version !== "string" || !/^[\w.+-]{1,40}$/.test(version))) || + (detail !== undefined && + (typeof detail !== "string" || detail.length > 200)) || + (issue !== undefined && + (typeof issue !== "string" || issue.length > 80)) || + !Array.isArray(actions) || + actions.length > SUPPORTED_ACTIONS.size || + !actions.every( + (action): action is EngineSupportedAction => + typeof action === "string" && + SUPPORTED_ACTIONS.has(action as EngineSupportedAction) + ) + ) + return null; + seen.add(id as RunnerEngine); + entries.push({ + id: id as RunnerEngine, + label, + installed, + signedIn: signedIn as boolean | null, + version: version as string | null, + ...(detail !== undefined ? { detail } : {}), + ...(issue !== undefined ? { issue } : {}), + actions, + }); + } + return entries; +} diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index b40e274cd..862a11b0b 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -1,5 +1,9 @@ import type { RunnerHealth } from "./health.js"; export { type RunnerHealth, parseRunnerHealth } from "./health.js"; +import type { + EngineInventoryEntry, + EngineOperation, +} from "./engine-management.js"; export const MANAGED_WORKSPACE = "@session"; export type Placement = { runner: string; workspace: string }; @@ -81,6 +85,15 @@ export type Command = { agentId: string; workspace: string } & ( | { kind: "launch"; launch: RemoteLaunch } | { kind: "attach" | "alive" | "discard" | "log" | "repo" } | { kind: "stop"; force: boolean } + /** + * Runner-wide engine install/update/sign-in — not bound to any agent or + * workspace binding; the runner answers it before any agent-binding + * checks. `workspace` only needs to name one of the runner's online + * workspaces, for routing. A runner that predates this never answers it, + * so the reply handler (service.ts, RunnerEngineTransport) treats a lost + * acknowledgement or error as `unsupported`. + */ + | { kind: "engine"; operation: EngineOperation } ); export type Frame = | { @@ -89,9 +102,13 @@ export type Frame = workspaces: string[]; health?: true; managedWorkspace?: true; + /** Advertises support for the `"engine"` command and inventory push. */ + engineManagement?: true; } | { type: "accept_health" } | { type: "health"; sample: RunnerHealth } + /** Runner-pushed, same cadence as health; see parseEngineInventory. */ + | { type: "engine_inventory"; entries: EngineInventoryEntry[] } | { type: "request"; id: string; command: Command } | { type: "result"; From ae9124bfd58f779d3dc109f9f43d1652ae5f295d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:27:46 -0700 Subject: [PATCH 059/642] Install and update runner engines in the workload account's prefix --- bin/install-dispatch-runner.sh | 19 ++++++++++++++++--- docs/remote-runner-linux.md | 12 ++++++------ scripts/remote-runner/test-installer.sh | 16 ++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/bin/install-dispatch-runner.sh b/bin/install-dispatch-runner.sh index cfda7c4b2..b3b5b663b 100755 --- a/bin/install-dispatch-runner.sh +++ b/bin/install-dispatch-runner.sh @@ -54,6 +54,14 @@ start_enabled_runner() { stable_start } +# npm's global prefix has a bin/ directory that the workload owns and uses for launch. +engine_commands() { + local package="$1" command + printf -v command '{"executable":"npm","args":["install","--global","--prefix","%s","%s@latest"]}' \ + "$state/home/.local" "$package" + printf '{"install":%s,"update":%s}' "$command" "$command" +} + write_config() { local uid gid uid=$(id -u "$account") @@ -67,9 +75,14 @@ write_config() { "home": "$state/home", "path": "$state/home/.local/bin:/usr/local/bin:/usr/bin:/bin", "bins": { - "claudeBin": "/usr/local/bin/claude", - "codexBin": "/usr/local/bin/codex", - "opencodeBin": "/usr/local/bin/opencode" + "claudeBin": "$state/home/.local/bin/claude", + "codexBin": "$state/home/.local/bin/codex", + "opencodeBin": "$state/home/.local/bin/opencode" + }, + "engines": { + "claude": $(engine_commands @anthropic-ai/claude-code), + "codex": $(engine_commands @openai/codex), + "opencode": $(engine_commands opencode-ai) }, "workspaces": {} } diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index 56549b440..634cff4c4 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -24,12 +24,12 @@ The runner must be able to reach the HTTPS address in the pairing command. and starts the service once enrollment succeeds. Wait for **Online** in Settings. -3. Install the engines you plan to use according to their Linux instructions. - The default runner configuration looks for `claude`, `codex`, and - `opencode` under `/usr/local/bin`. Install any companion binaries the - engine requires. If the selected engine needs credentials, - sign in as the workload account using its managed home. For example, run - `sudo -u dispatch-runner -H /usr/local/bin/codex login` if you use Codex. +3. Open **Manage engines** on the runner in Dispatch. Choose **Install** for + the engine you want, then **Sign in** for Codex or Claude. The runner uses + Node.js and npm from its workload PATH to install engine binaries under + `/var/lib/dispatch-runner/home/.local/bin`. Install Node.js and npm on + the Linux host to enable managed engine installs and updates. Credentials + belong to that runner's workload account. 4. Choose the runner when launching a session in Dispatch. The runner allocates the managed session directory. The reserved `@session` placement is supplied by the runner. Installation requires no checkout or workspace path. diff --git a/scripts/remote-runner/test-installer.sh b/scripts/remote-runner/test-installer.sh index fdbe4991b..ba0d997c9 100755 --- a/scripts/remote-runner/test-installer.sh +++ b/scripts/remote-runner/test-installer.sh @@ -169,6 +169,22 @@ run install v1.0.0 ! grep -Eq '^(start|enable) ' "$root/systemctl" [[ "$(find "$root/settings/runner.json" -perm 0600 -print)" == "$root/settings/runner.json" ]] grep -q '"workspaces": {}' "$root/settings/runner.json" +node - "$root/settings/runner.json" <<'JS' +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const config = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); +const packages = { codex: "@openai/codex", claude: "@anthropic-ai/claude-code", opencode: "opencode-ai" }; +for (const [engine, pkg] of Object.entries(packages)) { + const prefix = config.home + "/.local"; + assert.equal(config.bins[engine + "Bin"], prefix + "/bin/" + engine); + for (const action of ["install", "update"]) { + assert.deepEqual(config.engines[engine][action], { + executable: "npm", + args: ["install", "--global", "--prefix", prefix, pkg + "@latest"] + }); + } +} +JS cp "$root/runtime/dispatch" "$root/original" run update v1.0.1 From e35436cabf9adb1b49e4e99247fbc320800508bb Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:27:44 -0700 Subject: [PATCH 060/642] Embed the approval link in the copied command; sudo it by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit connect-command now bakes --approval-url into the printed command itself (shell-safely: validated as a real URL, single-quoted, and the request Host it's built from is checked against a bare host[:port] shape first), so a preview or default install with no DISPATCH_RUNNER_APPROVAL_ORIGIN configured still gets a working link — the browser that asked for the command is the only reliable source for it, and that's exactly who's asking here. dispatch-runner connect accepts --approval-url and prints it ahead of the service's own (env-only) approveUrl. The printed command is now sudo-prefixed by default, matching what writing to the root-owned /etc/dispatch-runner actually requires. Co-Authored-By: Claude Sonnet 5 --- apps/server/src/agents/remote/enrollment.ts | 48 +++++++++++++-- apps/server/src/agents/remote/service.ts | 32 +++++++++- .../server/test/remote-runner-connect.test.ts | 60 ++++++++++++++++++- docs/design/remote-runner-prototype.md | 20 ++++--- 4 files changed, 141 insertions(+), 19 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 91742ddd7..6eda6f104 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -79,19 +79,41 @@ export function pairingCommand(input: { * Dispatch API is loopback-only or plain HTTP, since nothing about it * depends on the main API's own binding or certificate. */ +/** + * A bare shell word, single-quoted. Only ever used for a URL that already + * passed `new URL(...)`, so the single-quote rejection is a defense-in-depth + * backstop, not the primary validation. + */ +function shellSingleQuoted(value: string) { + if (value.includes("'") || /[\x00-\x1f]/.test(value)) + throw new Error("Value is not safe to embed in a shell command."); + return `'${value}'`; +} + export function connectCliCommand(input: { host: string; port: number; caFingerprint: string; + /** Embedded as `--approval-url` so the CLI can print it without needing + * the service to know the operator's browser origin on its own. */ + approvalUrl?: string; }) { const pin = normalizeFingerprint(input.caFingerprint) .replace(/:/g, "") .toLowerCase(); - return [ - "dispatch-runner connect", + const parts = [ + // Writing to the default /etc/dispatch-runner needs root, same as + // remote-runner-pair; unlike that command, this one is copied and run + // directly by an operator, so spell it out rather than assume it. + "sudo dispatch-runner connect", `--service https://${formatHost(input.host)}:${input.port}`, `--ca-sha256 ${pin}`, - ].join(" "); + ]; + if (input.approvalUrl !== undefined) + parts.push( + `--approval-url ${shellSingleQuoted(new URL(input.approvalUrl).toString())}` + ); + return parts.join(" "); } /** @@ -418,6 +440,8 @@ type ConnectOptions = { dir: string; config?: string; timeoutMs?: number; + /** Printed back to the operator as-is; this CLI never dials it. */ + approvalUrl?: string; }; function parseConnectArgs(argv: string[]): ConnectOptions { @@ -432,13 +456,20 @@ function parseConnectArgs(argv: string[]): ConnectOptions { const service = values.get("service"); if (!service) throw new Error( - "Usage: dispatch-runner connect --service https://HOST:PORT [--ca-sha256 HEX] [--dir /etc/dispatch-runner] [--config FILE]" + "Usage: dispatch-runner connect --service https://HOST:PORT [--ca-sha256 HEX] [--approval-url URL] [--dir /etc/dispatch-runner] [--config FILE]" ); + const approvalUrl = values.get("approval-url"); + if (approvalUrl !== undefined) { + const protocol = new URL(approvalUrl).protocol; + if (protocol !== "http:" && protocol !== "https:") + throw new Error("--approval-url must be an http(s) URL."); + } return { service, pin: values.get("ca-sha256"), dir: path.resolve(values.get("dir") ?? "/etc/dispatch-runner"), config: values.get("config"), + approvalUrl, }; } @@ -632,14 +663,19 @@ export async function runRunnerConnect(argv: string[]) { { pin: options.pin, timeoutMs: options.timeoutMs } )) as ConnectCreated; + // `--approval-url` (the operator's own browser, baked into the copied + // command by connect-command) takes priority: the service's own + // approveUrl only exists when DISPATCH_RUNNER_APPROVAL_ORIGIN is set, + // which a preview or default install typically has no reason to. + const approveUrl = options.approvalUrl ?? created.approveUrl; process.stdout.write( [ `Code: ${created.code}`, // Same reference the pending-requests list shows in Settings, so an // operator juggling more than one pending runner can tell them apart. `Request: ${created.id.slice(-8)}`, - created.approveUrl - ? `Approve at: ${created.approveUrl}` + approveUrl + ? `Approve at: ${approveUrl}` : "Ask an operator to approve this runner using the code and request reference above.", `This code expires at ${created.expiresAt}.`, "Waiting for approval…", diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index a53956609..6bf975944 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -149,6 +149,20 @@ function validHost(host: string) { ); } +/** + * A bare `host[:port]`, as a Host header should contain. Used before a + * request-derived value is embedded in a URL that itself gets embedded in + * a copy-pasted shell command (`connectCommand`'s `--approval-url`) — + * reject anything else rather than let a crafted Host header ride along. + */ +function validHostPort(value: string) { + const match = /^(\[[0-9a-fA-F:]+\]|[^:[\]\s]+)(?::(\d+))?$/.exec(value); + if (!match) return false; + const host = match[1]!.replace(/^\[|\]$/g, ""); + const port = match[2]; + return validHost(host) && (!port || Number(port) <= 65535); +} + function httpsOrigin(value: string | undefined, label: string) { if (!value) return undefined; if (new URL(value).protocol !== "https:") @@ -1013,23 +1027,35 @@ export class RemoteRunnerService { return `${this.enrollment.approvalOrigin}/settings/connections`; // Best-effort only: reliable when `fallbackHost` is this request's own // (unproxied) Host header, not when it's a guess at the runner's view - // of the service. - return fallbackHost + // of the service. Validated before it goes anywhere near a URL that + // itself gets embedded in a copy-pasted shell command. + return fallbackHost && validHostPort(fallbackHost) ? `https://${fallbackHost}/settings/connections` : undefined; } + /** + * `GET /api/runners/connect-command`. The approval link is embedded in + * the printed command itself (`--approval-url`) as well as returned + * alongside it: with no `DISPATCH_RUNNER_APPROVAL_ORIGIN` configured — + * the common case for a preview or default install — this request's own + * Host header (the operator's browser, calling this authenticated route + * directly) is still the best answer, and the CLI has no other way to + * learn it. + */ async connectCommand(hostHint?: string, rawHost?: string) { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); const host = await this.prepareEndpoint(hostHint); + const approveUrl = this.approveUrl(rawHost); return { command: connectCliCommand({ host, port: this.port!, caFingerprint: this.authority!.caFingerprint, + approvalUrl: approveUrl, }), - approveUrl: this.approveUrl(rawHost), + approveUrl, }; } diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index 71424e54c..f0e79c6e2 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -7,7 +7,10 @@ import path from "node:path"; import { connect, createServer, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; -import { runRunnerConnect } from "../src/agents/remote/enrollment.js"; +import { + connectCliCommand, + runRunnerConnect, +} from "../src/agents/remote/enrollment.js"; import { RunnerRegistry } from "../src/agents/remote/registry.js"; import { RemoteRunnerService } from "../src/agents/remote/service.js"; import { @@ -188,6 +191,9 @@ describe("runner-initiated connect enrollment", () => { // (unreliable for a dev frontend on a different port) request host. const built = await service.connectCommand(HOST, "127.0.0.1:9999"); expect(built.approveUrl).toBe("http://localhost:5173/settings/connections"); + expect(built.command).toContain( + "--approval-url 'http://localhost:5173/settings/connections'" + ); }); it("rejects a malformed DISPATCH_RUNNER_APPROVAL_ORIGIN", () => { @@ -216,11 +222,11 @@ describe("runner-initiated connect enrollment", () => { ).rejects.toMatchObject({ status: 400 }); }); - it("builds a reusable connect command and a usable approval link", async () => { + it("builds a reusable, sudo-prefixed connect command embedding the approval link", async () => { const service = makeService(); const built = await service.connectCommand(HOST, "web.example:8443"); expect(built.command).toMatch( - /^dispatch-runner connect --service https:\/\/127\.0\.0\.1:\d+ --ca-sha256 [a-f0-9]{64}$/ + /^sudo dispatch-runner connect --service https:\/\/127\.0\.0\.1:\d+ --ca-sha256 [a-f0-9]{64} --approval-url 'https:\/\/web\.example:8443\/settings\/connections'$/ ); expect(built.approveUrl).toBe( "https://web.example:8443/settings/connections" @@ -230,6 +236,17 @@ describe("runner-initiated connect enrollment", () => { expect(again.command).toBe(built.command); }); + it("drops a Host header that isn't a safe bare host[:port] rather than embed it anywhere", async () => { + const service = makeService(); + const built = await service.connectCommand( + HOST, + "web.example:8443'; rm -rf / #" + ); + expect(built.approveUrl).toBeUndefined(); + expect(built.command).not.toContain("--approval-url"); + expect(built.command).not.toContain("rm -rf"); + }); + it("approves with the correct code, binds the key, and lets the runner connect", async () => { const service = makeService(); const { key, publicKey } = generateRunnerKey(); @@ -468,3 +485,40 @@ function connectServer( } ); } + +describe("connect command shell safety", () => { + it("sudo-prefixes and omits --approval-url when none is given", () => { + const command = connectCliCommand({ + host: "runner.example", + port: 12345, + caFingerprint: "AB".repeat(32), + }); + expect(command).toBe( + `sudo dispatch-runner connect --service https://runner.example:12345 --ca-sha256 ${"ab".repeat(32)}` + ); + }); + + it("rejects an approval URL that isn't a well-formed URL at all", () => { + expect(() => + connectCliCommand({ + host: "runner.example", + port: 1, + caFingerprint: "AB".repeat(32), + approvalUrl: "not a url", + }) + ).toThrow(); + }); + + it("CLI rejects a non-http(s) --approval-url before contacting the service", async () => { + await expect( + runRunnerConnect([ + "--service", + "https://127.0.0.1:1", + "--ca-sha256", + "ab".repeat(32), + "--approval-url", + "javascript:alert(1)", + ]) + ).rejects.toThrow(/--approval-url must be an http\(s\) URL/); + }); +}); diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 3950d0de9..5fd9bd3ba 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -129,13 +129,19 @@ until an operator approves it. Both `connect-command` and the create response may also carry an `approveUrl` pointing at **Settings → Connections → Remote runners**. For `connect-command` it is built from that authenticated call's own (reliable) -Host header; the create call has no such thing to go on — it comes from the -runner, not a browser — so it is only ever populated from the explicitly -configured `DISPATCH_RUNNER_APPROVAL_ORIGIN` (a bare `http://` or `https://` -origin; `http://` so a Vite dev server's own port can be used, not just a -production HTTPS origin). Unset, the create response simply omits it and -the CLI falls back to code-only instructions — honest rather than a guess -that can point at the wrong origin. +Host header, or from `DISPATCH_RUNNER_APPROVAL_ORIGIN` when that is set (a +bare `http://` or `https://` origin; `http://` so a Vite dev server's own +port can be used, not just a production HTTPS origin) — checked against a +bare-host-and-port shape before it goes anywhere near a URL. That URL is +also embedded directly in the printed command as `--approval-url`, single- +quoted and re-validated as a well-formed URL first, so the common preview +or default-install case (no approval-origin configured at all) still gets +a working link without the service needing to know anything about the +operator's browser in advance. The create call has no such host to go on — +it comes from the runner, not a browser — so its own `approveUrl` is only +ever populated from `DISPATCH_RUNNER_APPROVAL_ORIGIN`; unset, it is omitted +and the CLI falls back to whatever `--approval-url` it was given, or +code-only instructions if that's absent too. The operator reads the code off the runner's own terminal or logs — it is never sent back by the runner — and calls the authenticated From 35fe52461c3f948890fad716e2b99bbc16af446a Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:31:59 -0700 Subject: [PATCH 061/642] Negotiate runner engine inventory separately from health samples --- apps/server/src/agents/remote/runner.ts | 4 +++- apps/server/src/agents/remote/service.ts | 13 +++++++++++-- apps/server/test/engine-wire.test.ts | 1 + packages/runner-protocol/README.md | 5 +++++ packages/runner-protocol/src/index.ts | 2 +- 5 files changed, 21 insertions(+), 4 deletions(-) diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index eb10fbb12..3291f686f 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -479,9 +479,10 @@ export async function runRemoteRunner(filename: string) { sampling = false; } }; + let acceptsInventory = false; let samplingEngines = false; const reportEngineInventory = async () => { - if (samplingEngines || socket.destroyed) return; + if (!acceptsInventory || samplingEngines || socket.destroyed) return; samplingEngines = true; try { const entries = await engineExecutor.inventory(); @@ -678,6 +679,7 @@ export async function runRemoteRunner(filename: string) { const send = wireFrames(socket, (frame) => { if (frame.type === "accept_health" && !healthInterval) { + acceptsInventory = frame.engineInventory === true; void reportHealth(); void reportEngineInventory(); healthInterval = setInterval(() => { diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 6bf975944..93f32e1f6 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -676,7 +676,12 @@ export class RemoteRunnerService { this.peers.set(gate.key, peer); previous?.socket.destroy(); gate.ready?.(frame.workspaces, peer.managedWorkspace); - if (peer.reportsHealth) send({ type: "accept_health" }); + if (peer.reportsHealth) { + send({ + type: "accept_health", + ...(peer.engineManagement ? { engineInventory: true } : {}), + }); + } return; } if (this.peers.get(gate.key) !== peer) return socket.destroy(); @@ -700,7 +705,11 @@ export class RemoteRunnerService { error ) ); - } else if (frame.type === "engine_inventory") { + } else if ( + frame.type === "engine_inventory" && + peer.engineManagement && + peer.reportsHealth + ) { const entries = parseEngineInventory(frame.entries); if (entries === null) return socket.destroy(); peer.engines = entries; diff --git a/apps/server/test/engine-wire.test.ts b/apps/server/test/engine-wire.test.ts index f2f670f67..193f5e04a 100644 --- a/apps/server/test/engine-wire.test.ts +++ b/apps/server/test/engine-wire.test.ts @@ -74,6 +74,7 @@ function dialEngineRunner(input: { send({ type: "ready", version: 1, + health: true, ...(input.engineManagement !== false ? { engineManagement: true } : {}), workspaces: input.workspaces, }); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index fbe90a90a..0e745a79e 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -99,6 +99,11 @@ submission because an engine-initiated turn was already open. ## Runner health +Engine inventory is opt-in for each connection. Runners advertise +`engineManagement: true` in `ready`. A service can set `engineInventory: true` +on its `accept_health` response to receive periodic `engine_inventory` frames. +A plain `accept_health` subscribes to health samples alone. + A runner can advertise `health: true` in its v1 ready frame. A service that wants reports replies once with `{"type":"accept_health"}`. The runner pushes a `health` frame containing its latest sample immediately and every 30 seconds diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index 862a11b0b..8f14784df 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -105,7 +105,7 @@ export type Frame = /** Advertises support for the `"engine"` command and inventory push. */ engineManagement?: true; } - | { type: "accept_health" } + | { type: "accept_health"; engineInventory?: true } | { type: "health"; sample: RunnerHealth } /** Runner-pushed, same cadence as health; see parseEngineInventory. */ | { type: "engine_inventory"; entries: EngineInventoryEntry[] } From 856cc310fabf61f31f298eebd88927fd72293c1d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:33:26 -0700 Subject: [PATCH 062/642] Allow runner engine installs to finish before timing out the control request --- apps/server/src/agents/remote/service.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 93f32e1f6..8c51f8d3f 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1259,7 +1259,9 @@ export class RemoteRunnerService { }; const timer = setTimeout( () => finish(), - command.kind === "launch" && command.launch.repository + // Repository fetches and engine package installs may take minutes. + command.kind === "engine" || + (command.kind === "launch" && command.launch.repository) ? 300_000 : 20_000 ); From e19d141a7f628dba0c062ab5f4c88c800a8dd6f6 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:31:45 -0700 Subject: [PATCH 063/642] Match the approval link's scheme to the browser's, not the bootstrap's connect-command's fallback approveUrl always assumed https, breaking the normal LAN preview: Vite's dev frontend is plain HTTP on its own port (confirmed via vite.config.ts's deliberate changeOrigin:false, which preserves the browser's real Host end to end for exactly this kind of check), while the runner's own --service bootstrap stays HTTPS-only and unrelated. connectCommand now takes the request's own protocol and uses it for the fallback approval link; DISPATCH_RUNNER_APPROVAL_ORIGIN's explicit scheme is unaffected since it was never guessed in the first place. Co-Authored-By: Claude Sonnet 5 --- apps/server/src/agents/remote/service.ts | 38 ++++++++++++------- apps/server/src/routes/runners.ts | 3 +- .../server/test/remote-runner-connect.test.ts | 19 ++++++++++ docs/design/remote-runner-prototype.md | 25 ++++++------ 4 files changed, 60 insertions(+), 25 deletions(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 8c51f8d3f..e71b0a92d 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1031,16 +1031,24 @@ export class RemoteRunnerService { * Host header: it is for the operator's browser, which is already here. */ /** Where an operator approves a connect request, if known. */ - private approveUrl(fallbackHost?: string) { + /** + * `fallbackProtocol` is the *browser's* own scheme for this request + * (Fastify's `request.protocol`) — a LAN preview's Vite frontend is + * plain HTTP even though the runner's own bootstrap stays HTTPS-only, + * so this can never be assumed to be `https`. + */ + private approveUrl(fallbackHost?: string, fallbackProtocol?: string) { if (this.enrollment?.approvalOrigin) return `${this.enrollment.approvalOrigin}/settings/connections`; - // Best-effort only: reliable when `fallbackHost` is this request's own - // (unproxied) Host header, not when it's a guess at the runner's view - // of the service. Validated before it goes anywhere near a URL that - // itself gets embedded in a copy-pasted shell command. - return fallbackHost && validHostPort(fallbackHost) - ? `https://${fallbackHost}/settings/connections` - : undefined; + // Best-effort only: reliable when `fallbackHost`/`fallbackProtocol` are + // this request's own (unproxied) Host header and scheme, not when + // they're a guess at the runner's view of the service. + if (!fallbackHost || !validHostPort(fallbackHost)) return undefined; + const protocol = + fallbackProtocol === "http" || fallbackProtocol === "https" + ? fallbackProtocol + : "https"; + return `${protocol}://${fallbackHost}/settings/connections`; } /** @@ -1048,15 +1056,19 @@ export class RemoteRunnerService { * the printed command itself (`--approval-url`) as well as returned * alongside it: with no `DISPATCH_RUNNER_APPROVAL_ORIGIN` configured — * the common case for a preview or default install — this request's own - * Host header (the operator's browser, calling this authenticated route - * directly) is still the best answer, and the CLI has no other way to - * learn it. + * Host header and scheme (the operator's browser, calling this + * authenticated route directly) are still the best answer, and the CLI + * has no other way to learn them. */ - async connectCommand(hostHint?: string, rawHost?: string) { + async connectCommand( + hostHint?: string, + rawHost?: string, + rawProtocol?: string + ) { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); const host = await this.prepareEndpoint(hostHint); - const approveUrl = this.approveUrl(rawHost); + const approveUrl = this.approveUrl(rawHost, rawProtocol); return { command: connectCliCommand({ host, diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts index 7483c53d7..3d784e557 100644 --- a/apps/server/src/routes/runners.ts +++ b/apps/server/src/routes/runners.ts @@ -136,7 +136,8 @@ export async function registerRunnerRoutes( try { return await deps.runners.connectCommand( hostHint(request.headers.host), - request.headers.host + request.headers.host, + request.protocol ); } catch (error) { return fail(reply, error); diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index f0e79c6e2..85f34186d 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -247,6 +247,25 @@ describe("runner-initiated connect enrollment", () => { expect(built.command).not.toContain("rm -rf"); }); + it("matches a plain-HTTP LAN preview frontend's own scheme, not the bootstrap's HTTPS", async () => { + const service = makeService(); + // A Vite dev frontend reachable on the LAN is plain HTTP on its own + // port, independent of the runner's own (always-HTTPS) bootstrap. + const built = await service.connectCommand( + HOST, + "192.168.1.246:59244", + "http" + ); + expect(built.approveUrl).toBe( + "http://192.168.1.246:59244/settings/connections" + ); + expect(built.command).toContain( + "--approval-url 'http://192.168.1.246:59244/settings/connections'" + ); + // The --service target is still always https, regardless. + expect(built.command).toMatch(/--service https:\/\//); + }); + it("approves with the correct code, binds the key, and lets the runner connect", async () => { const service = makeService(); const { key, publicKey } = generateRunnerKey(); diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 5fd9bd3ba..abd7481e1 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -129,17 +129,20 @@ until an operator approves it. Both `connect-command` and the create response may also carry an `approveUrl` pointing at **Settings → Connections → Remote runners**. For `connect-command` it is built from that authenticated call's own (reliable) -Host header, or from `DISPATCH_RUNNER_APPROVAL_ORIGIN` when that is set (a -bare `http://` or `https://` origin; `http://` so a Vite dev server's own -port can be used, not just a production HTTPS origin) — checked against a -bare-host-and-port shape before it goes anywhere near a URL. That URL is -also embedded directly in the printed command as `--approval-url`, single- -quoted and re-validated as a well-formed URL first, so the common preview -or default-install case (no approval-origin configured at all) still gets -a working link without the service needing to know anything about the -operator's browser in advance. The create call has no such host to go on — -it comes from the runner, not a browser — so its own `approveUrl` is only -ever populated from `DISPATCH_RUNNER_APPROVAL_ORIGIN`; unset, it is omitted +Host header and scheme — a LAN preview's Vite frontend is plain HTTP on its +own port, so the scheme is never assumed to be HTTPS even though the +runner's own bootstrap always is — or from `DISPATCH_RUNNER_APPROVAL_ORIGIN` +when that is set (a bare `http://` or `https://` origin; `http://` so a +Vite dev server's own port can be used, not just a production HTTPS +origin). The Host is checked against a bare-host-and-port shape before it +goes anywhere near a URL. That URL is also embedded directly in the printed +command as `--approval-url`, single-quoted and re-validated as a +well-formed URL first, so the common preview or default-install case (no +approval-origin configured at all) still gets a working link without the +service needing to know anything about the operator's browser in advance. +The create call has no such host to go on — it comes from the runner, not +a browser — so its own `approveUrl` is only ever populated from +`DISPATCH_RUNNER_APPROVAL_ORIGIN`; unset, it is omitted and the CLI falls back to whatever `--approval-url` it was given, or code-only instructions if that's absent too. From 51202d4458dbd718d75c56adbb42432c68d061e2 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:18:37 -0700 Subject: [PATCH 064/642] Match approval forms by the runner's printed request reference --- e2e/remote-runner/harness.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 2e155822d..c76122155 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -133,19 +133,26 @@ export async function requestConnection( output += chunk; }); }); - const pairingCode = () => /^Code: ([A-Z0-9_-]+)\r?$/im.exec(output)?.[1]; + const approval = () => { + const code = /^Code: ([A-Z0-9_-]+)\r?$/im.exec(output)?.[1]; + const reference = /^Request: ([A-Z0-9_-]+)\r?$/im.exec(output)?.[1]; + return code && reference ? { code, reference } : undefined; + }; await expect .poll( () => { if (failure) throw failure; - return pairingCode(); + return approval(); }, { timeout: 20_000 } ) .toBeTruthy(); - const form = page.getByTestId("runner-approval"); + const { code, reference } = approval()!; + const form = page.getByTestId("runner-approval").filter({ + has: page.getByText(`Connection request · ${reference}`, { exact: true }), + }); await expect(form).toHaveCount(1, { timeout: 15_000 }); - return { form, code: pairingCode()!, finished }; + return { form, code, finished }; } export function startRunner(name: GuestName) { From 628c9959a64595cdf7b8e57e0724629405cf50ea Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:25:52 -0700 Subject: [PATCH 065/642] Capture runner liveness and journal cursors on acceptance failure --- e2e/remote-runner/acceptance.spec.ts | 14 ++++------ e2e/remote-runner/harness.ts | 41 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index dfef95d24..ce882b6df 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -6,6 +6,7 @@ import { enrollViaUi, revokeViaUi, guest, + guestDiagnostics, guestOk, invocations, lane, @@ -50,15 +51,10 @@ test.afterAll(async ({ request }) => { test.afterEach(async ({}, testInfo) => { if (testInfo.status === testInfo.expectedStatus) return; for (const name of ["alpha", "beta", "scratch"] as const) { - const logs = guest( - name, - 'for file in /var/log/runner.log /var/lib/runner/bindings/logs/*; do [ ! -f "$file" ] || { printf "\\n%s\\n" "$file"; tail -60 "$file"; }; done' - ); - if (logs.trim()) - await testInfo.attach(`${name} runner logs`, { - body: logs, - contentType: "text/plain", - }); + await testInfo.attach(`${name} runner diagnostics`, { + body: guestDiagnostics(name), + contentType: "text/plain", + }); } }); diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index c76122155..1a8a63450 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -48,6 +48,47 @@ export const invocations = (name: RunnerName) => ).trim() ); +export function guestDiagnostics(name: GuestName) { + const container = state.runners[name].container; + const status = docker( + "inspect", + "--format", + "status={{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}", + container + ); + try { + const processes = guest( + name, + "ps -A -o pid,ppid,stat,comm; cat /sys/fs/cgroup/memory.events 2>/dev/null || true" + ); + const journals = guest( + name, + "if [ -d /var/lib/runner/hosts ]; then find /var/lib/runner/hosts -name journal.jsonl -exec tail -n 8 {} +; fi" + ) + .split("\n") + .filter((line) => line.startsWith("{")) + .map((line) => { + const { seq, journalId, event } = JSON.parse(line); + return `agent=${event?.agentId} journal=${journalId} seq=${seq} event=${event?.type} ${event?.state ?? ""}`.trimEnd(); + }) + .join("\n"); + const calls = + name === "scratch" + ? guest( + name, + "if [ -d /var/lib/runner/sessions ]; then find /var/lib/runner/sessions -name provider-invocations -exec wc -l {} +; fi" + ).trim() + : String(invocations(name)); + const logs = guest( + name, + 'for file in /var/log/runner.log /var/lib/runner/bindings/logs/*; do [ ! -f "$file" ] || { printf "\\n%s\\n" "$file"; tail -60 "$file"; }; done' + ); + return `${status}${processes}\nInvocation counts: ${calls}\n${journals}\n${logs}`; + } catch { + return `${status}Guest diagnostics unavailable.\n`; + } +} + /** Fault injection on the runner's TCP path (TLS stays end to end). */ export async function lane( name: RunnerName, From b8e83dce011559d29140b8f6fb8ddcc446f6cf41 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:30:02 -0700 Subject: [PATCH 066/642] Exercise the approval URL in the Settings connect command --- e2e/remote-runner/harness.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 1a8a63450..74e76fcf1 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -140,6 +140,7 @@ export async function requestConnection( const command = await connectCommand(page); const service = new URL(commandOption(command, "--service")!); const pin = commandOption(command, "--ca-sha256"); + const approvalUrl = commandOption(command, "--approval-url"); if (Number(service.port) === state.runnerPort) service.port = String(state.runners[name].proxyPort); const args = [ @@ -152,6 +153,7 @@ export async function requestConnection( "--dir", dir, ...(pin ? ["--ca-sha256", pin] : []), + ...(approvalUrl ? ["--approval-url", approvalUrl] : []), ...(dir === "/etc/dispatch-runner" ? ["--config", "/run/cfg/runner.json"] : []), @@ -189,6 +191,7 @@ export async function requestConnection( ) .toBeTruthy(); const { code, reference } = approval()!; + if (approvalUrl) expect(output).toContain(`Approve at: ${approvalUrl}`); const form = page.getByTestId("runner-approval").filter({ has: page.getByText(`Connection request · ${reference}`, { exact: true }), }); From 8b7a047cf36c902d874fae0f126c01f4fc1a9d60 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:48:49 -0700 Subject: [PATCH 067/642] Explain private GitHub access for runner worktrees --- docs/remote-runner-linux.md | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index 634cff4c4..ea4ec527a 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -30,9 +30,10 @@ The runner must be able to reach the HTTPS address in the pairing command. `/var/lib/dispatch-runner/home/.local/bin`. Install Node.js and npm on the Linux host to enable managed engine installs and updates. Credentials belong to that runner's workload account. -4. Choose the runner when launching a session in Dispatch. The runner allocates - the managed session directory. The reserved `@session` placement is supplied - by the runner. Installation requires no checkout or workspace path. +4. In **Create Agent**, choose the runner. A Dispatch project can supply the + repository. Select a base branch for a new worktree, use an existing branch, + or clear the repository for a scratch session. The runner creates the + session directory and removes it when the agent is archived. The command downloads the bootstrap from the selected GitHub release and verifies its signed build provenance against @@ -79,6 +80,21 @@ Inspect startup logs with `sudo journalctl -u dispatch-runner.service`. For custom engine install paths, edit the `bins` object in `/etc/dispatch-runner/runner.json` as root and restart the service while idle. +## Private GitHub repositories + +For private checkouts, install GitHub CLI at `/usr/bin/gh` on the runner and +sign in once as its workload account. Configure the Git credential helper so +agents can also push over HTTPS from inside their worktrees. + +```sh +sudo -u dispatch-runner -H /usr/bin/gh auth login --hostname github.com --git-protocol https --web +sudo -u dispatch-runner -H /usr/bin/gh auth setup-git --hostname github.com +``` + +Sessions on this runner share that account’s repository access. Choose a +repository in Create Agent as needed. Public HTTPS checkouts and scratch +sessions work without a GitHub login. + ## Update or recover Run the installed updater with the exact target release tag. The tag must From b07e55d102d9888b55f3124832afb54851a09e8b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:48:25 -0700 Subject: [PATCH 068/642] Fix engine-management routing, exit-code handling, staging and progress gaps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - engine-transport: route by any workspace the peer actually advertises (anyWorkspace), not a hardcoded @session — a runner with only configured folders and no managed-session support never advertises it. - commandUsable: check the child's exit code, not just spawn errors — setpriv itself always starts fine, so a missing npm/node on the workload's PATH surfaces as exit 127, not a Node-level spawn error. - runManaged: stop ignoring the install/update command's exit code and always returning ok:true. Now distinguishes a real failure (ok:false with the exit code) from a legitimate no-op update ("already up to date", ok:true with a message) — neither was previously possible to tell apart from the ack. - engine-login: add a createStageDir seam so a staged (Codex) login's scratch CODEX_HOME can be chowned to the workload identity before the CLI runs under dropped privileges — the default root-owned 0700 mkdtemp can't be written to once setpriv drops to a different uid. - Add the login_status operation end to end (protocol, executor, manager, routes, web hook/component): the only way to observe a sign-in settling after login_start/login_submit already returned, since Codex's device flow finishes on its own and Claude's code verification happens asynchronously after submission. The component now polls it while a sign-in is active, fixing a UI case where the row showed "signed in" (from the inventory refresh) while the sign-in panel stayed stuck on "Checking the code…". - Component/hooks also now surface a failed install/update as an error (previously silently reported as success) and an up-to-date update as a distinct success message. Co-Authored-By: Claude Sonnet 5 --- apps/server/src/agents/engine-login.ts | 18 +- .../src/agents/remote/engine-manager.ts | 7 +- .../agents/remote/engine-runner-executor.ts | 57 ++++++- .../src/agents/remote/engine-transport.ts | 18 +- apps/server/src/agents/remote/service.ts | 16 ++ apps/server/src/routes/engine-management.ts | 4 + .../test/engine-runner-executor.test.ts | 158 +++++++++++++++++- apps/server/test/engine-wire.test.ts | 26 +++ .../runner-engines/runner-engines.test.tsx | 106 ++++++++++++ .../runner-engines/runner-engines.tsx | 55 +++++- apps/web/src/hooks/use-runner-engines.ts | 38 +++++ .../runner-protocol/src/engine-management.ts | 20 ++- 12 files changed, 493 insertions(+), 30 deletions(-) diff --git a/apps/server/src/agents/engine-login.ts b/apps/server/src/agents/engine-login.ts index 4e91ea9f7..abda6a07f 100644 --- a/apps/server/src/agents/engine-login.ts +++ b/apps/server/src/agents/engine-login.ts @@ -122,6 +122,14 @@ export type EngineLoginDeps = { now?: () => number; /** Test seam: how long the CLI gets to print its link. */ linkTimeoutMs?: number; + /** + * How a staged login's scratch `CODEX_HOME` is created. Defaults to a + * root-owned `mkdtemp` under the system temp dir — correct when the CLI + * runs as this same process's own identity. A caller whose `command` + * drops to a different (e.g. workload) uid before running the CLI must + * override this so that identity can actually write into the directory. + */ + createStageDir?: () => Promise; }; export type LoginScriptOptions = { @@ -211,9 +219,15 @@ export class EngineLogins { private readonly env: NodeJS.ProcessEnv; private readonly now: () => number; private readonly linkTimeoutMs: number; + private readonly createStageDir: NonNullable< + EngineLoginDeps["createStageDir"] + >; constructor(private readonly deps: EngineLoginDeps) { this.command = deps.command ?? shellCommand; + this.createStageDir = + deps.createStageDir ?? + (() => mkdtemp(path.join(os.tmpdir(), "dispatch-engine-login-"))); this.env = { ...hostProcessEnv(deps.env ?? process.env), // Claude also tries to open the link itself; on a server that is the @@ -301,9 +315,7 @@ export class EngineLogins { } const { staged } = COMMANDS[engine]; if (staged) { - entry.stageDir = await mkdtemp( - path.join(os.tmpdir(), "dispatch-engine-login-") - ); + entry.stageDir = await this.createStageDir(); } const command = this.command(bin, args, { ttlSeconds: LOGIN_TTL_MS / 1000 + 60, diff --git a/apps/server/src/agents/remote/engine-manager.ts b/apps/server/src/agents/remote/engine-manager.ts index 3e684890c..7e9b267d9 100644 --- a/apps/server/src/agents/remote/engine-manager.ts +++ b/apps/server/src/agents/remote/engine-manager.ts @@ -121,7 +121,7 @@ export class EngineManager { // own pushed-cache update can lag its ack by a round trip, so force a // live read here rather than risk handing back what the cache held // before the operation ran. - if (operation.type !== "status") { + if (operation.type !== "status" && operation.type !== "login_status") { const entries = scope.kind === "local" ? await this.localInventory().catch(() => null) @@ -246,6 +246,11 @@ export class EngineManager { if (!login) return { ok: false, error: "Sign-in not found." }; return { ok: true, login }; } + case "login_status": { + const login = logins.get(operation.loginId); + if (!login) return { ok: false, error: "Sign-in not found." }; + return { ok: true, login }; + } } } } diff --git a/apps/server/src/agents/remote/engine-runner-executor.ts b/apps/server/src/agents/remote/engine-runner-executor.ts index 0ab7b241c..854c6c251 100644 --- a/apps/server/src/agents/remote/engine-runner-executor.ts +++ b/apps/server/src/agents/remote/engine-runner-executor.ts @@ -1,5 +1,8 @@ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; +import { chown, mkdtemp } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; import type { RunnerEngine } from "@dispatch/runner-protocol"; import { @@ -114,6 +117,17 @@ export class EngineRunnerExecutor { return this.wrap(shBin!, shArgs); }, env: config.env, + // A staged login (Codex) writes its scratch CODEX_HOME under the + // dropped-privilege workload identity, not this (root) process — + // the default root-owned 0700 mkdtemp would refuse that write, so + // this chowns it to the workload before the CLI ever touches it. + createStageDir: async () => { + const dir = await mkdtemp( + path.join(os.tmpdir(), "dispatch-engine-login-") + ); + await chown(dir, config.uid, config.gid); + return dir; + }, }); } @@ -178,15 +192,21 @@ export class EngineRunnerExecutor { return { installed: true, version: sanitizeVersion(output) }; } - /** Whether a configured install/update command's own executable can run at all. */ + /** + * Whether a configured install/update command's own executable can run + * at all. `setpriv` itself is a fixed system path, so a missing target + * (e.g. no npm on the workload's PATH) is never a Node-level spawn + * error — setpriv starts fine and the shell it execs into exits 127. + * Both failure shapes must be checked. + */ private async commandUsable(command: ManagedCommand): Promise { - const { spawnError } = await this.run( + const { spawnError, code } = await this.run( command.executable, ["--version"], { ...this.config.env, ...command.env }, 5_000 ); - return spawnError === undefined; + return spawnError === undefined && code === 0; } /** The scope-aware engine list and supported actions, for a snapshot view. */ @@ -270,6 +290,11 @@ export class EngineRunnerExecutor { if (!login) return { ok: false, error: "Sign-in not found." }; return { ok: true, login: toLoginView(login) }; } + case "login_status": { + const login = this.logins.get(operation.loginId); + if (!login) return { ok: false, error: "Sign-in not found." }; + return { ok: true, login: toLoginView(login) }; + } } } @@ -295,7 +320,7 @@ export class EngineRunnerExecutor { message: kind === "install" ? "Installing…" : "Updating…", }); const before = cfg?.bin ? (await this.probe(cfg.bin)).version : null; - await this.run( + const result = await this.run( step.executable, step.args, { ...this.config.env, ...step.env }, @@ -311,21 +336,35 @@ export class EngineRunnerExecutor { }); } ); + const commandFailed = result.spawnError !== undefined || result.code !== 0; const after = cfg?.bin ? (await this.probe(cfg.bin)).version : null; - const success = + const label = kind === "install" ? "Install" : "Update"; + const advanced = kind === "install" ? Boolean(after) : Boolean(before && after && compareVersions(after, before) > 0); + // An update command can legitimately exit 0 and do nothing — the + // engine was already current. That's success, not a failed update. + const upToDate = + !commandFailed && kind === "update" && !advanced && Boolean(before); + const success = !commandFailed && (advanced || upToDate); + const message = commandFailed + ? `${label} command failed${result.code !== null ? ` (exit code ${result.code})` : ""}.` + : upToDate + ? `Already up to date (version ${after}).` + : advanced + ? `${label} completed. Verified installed version ${after}.` + : `${label} command completed, but a ${kind === "install" ? "new" : "newer"} installed version could not be verified.`; onEvent?.({ type: "operation_complete", operationId, engine, success, - message: success - ? `${kind === "install" ? "Install" : "Update"} completed. Verified installed version ${after}.` - : `${kind === "install" ? "Install" : "Update"} command completed, but a ${kind === "install" ? "new" : "newer"} installed version could not be verified.`, + message, }); - return { ok: true, operationId }; + return success + ? { ok: true, operationId, message } + : { ok: false, error: message }; } /** Stop every sign-in under way; for shutdown. */ diff --git a/apps/server/src/agents/remote/engine-transport.ts b/apps/server/src/agents/remote/engine-transport.ts index 0f761ecb4..72ad82dfe 100644 --- a/apps/server/src/agents/remote/engine-transport.ts +++ b/apps/server/src/agents/remote/engine-transport.ts @@ -1,8 +1,4 @@ -import { - MANAGED_WORKSPACE, - type EngineOperationAck, - type EngineOperationEvent, -} from "./protocol.js"; +import type { EngineOperationAck, EngineOperationEvent } from "./protocol.js"; import { RunnerUnavailable, type RemoteRunnerService } from "./service.js"; import type { RunnerEngineTransport } from "./engine-manager.js"; @@ -23,16 +19,18 @@ export function remoteEngineTransport( }, async send(runnerId, operation, onEvent) { // Engine management is runner-wide, not per-workspace; the wire - // Command still needs *a* workspace for routing, and every runner - // built for this always advertises MANAGED_WORKSPACE. - const placement = { runner: runnerId, workspace: MANAGED_WORKSPACE }; - if (!service.available(placement)) { + // Command still needs *a* workspace for routing. A runner with only + // configured folders (no managed-session support) never advertises + // MANAGED_WORKSPACE, so pick whatever it actually advertises. + const workspace = service.anyWorkspace(runnerId); + if (!workspace) { return { ok: false, error: "The runner is disconnected or unavailable.", unsupported: true, }; } + const placement = { runner: runnerId, workspace }; try { const { value, channel } = await service.request( placement, @@ -40,7 +38,7 @@ export function remoteEngineTransport( // opaque placeholder the runner's "engine" branch never checks. { agentId: "@engine", - workspace: MANAGED_WORKSPACE, + workspace, kind: "engine", operation, }, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index e71b0a92d..13451709c 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1217,6 +1217,22 @@ export class RemoteRunnerService { return peer?.gate.approved() ? peer.engines : undefined; } + /** + * Any workspace this (approved, connected) peer currently advertises — + * for a runner-wide command like `"engine"` that needs *a* workspace + * for routing but has no workspace of its own. A runner with only + * configured folders and no managed-session support never advertises + * `MANAGED_WORKSPACE`, so that must never be assumed. + */ + anyWorkspace(runnerId: string): string | undefined { + const peer = this.peers.get(runnerId); + if (!peer?.gate.approved()) return undefined; + for (const workspace of peer.workspaces) { + if (peer.gate.allows(workspace)) return workspace; + } + return undefined; + } + available(placement: Placement) { const peer = this.peers.get(placement.runner); return Boolean( diff --git a/apps/server/src/routes/engine-management.ts b/apps/server/src/routes/engine-management.ts index 6775a6d4e..aeceea96b 100644 --- a/apps/server/src/routes/engine-management.ts +++ b/apps/server/src/routes/engine-management.ts @@ -47,6 +47,10 @@ const engineOperationSchema = z.union([ type: z.literal("login_cancel"), loginId: z.string().min(1).max(128), }), + z.object({ + type: z.literal("login_status"), + loginId: z.string().min(1).max(128), + }), ]); const operationBodySchema = z.object({ diff --git a/apps/server/test/engine-runner-executor.test.ts b/apps/server/test/engine-runner-executor.test.ts index 39d5854a2..21d2566f1 100644 --- a/apps/server/test/engine-runner-executor.test.ts +++ b/apps/server/test/engine-runner-executor.test.ts @@ -1,4 +1,10 @@ -import { mkdtempSync, rmSync, writeFileSync, chmodSync } from "node:fs"; +import { + existsSync, + mkdtempSync, + rmSync, + writeFileSync, + chmodSync, +} from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -32,7 +38,7 @@ if (args === "--version") { } else if (args === "install") { process.exit(mode === "fail-install" ? 1 : 0); } else if (args === "update") { - process.exit(0); + process.exit(mode === "fail-update" ? 1 : 0); } else { process.exit(2); } @@ -41,6 +47,13 @@ if (args === "--version") { chmodSync(fake, 0o755); }); + const makeExitCode = (dir: string, code: number) => { + const file = path.join(dir, `fake-exit-${code}.mjs`); + writeFileSync(file, `#!/usr/bin/env node\nprocess.exit(${code});\n`); + chmodSync(file, 0o755); + return file; + }; + afterAll(() => rmSync(dir, { recursive: true, force: true })); afterEach(() => executor?.close()); @@ -191,6 +204,147 @@ if (args === "--version") { expect(events[events.length - 1]).toBe("operation_complete"); }); + it("reports a failed update as ok:false with the exit code, not a false success", async () => { + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: { ...process.env, FAKE_ENGINE_MODE: "fail-update" }, + wrap: passthroughWrap, + engines: { + claude: { bin: fake, update: { executable: fake, args: ["update"] } }, + }, + }); + const events: unknown[] = []; + const ack = await executor.handle( + { type: "update", engine: "claude" }, + (event) => events.push(event) + ); + expect(ack).toMatchObject({ + ok: false, + error: expect.stringContaining("exit code 1"), + }); + expect(events.at(-1)).toMatchObject({ + type: "operation_complete", + success: false, + }); + }); + + it("reports an already-current update as success, not a failure", async () => { + // The fake CLI's update command exits 0 and leaves the version + // unchanged (no FAKE_ENGINE_MODE override) — a legitimate no-op. + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { + claude: { bin: fake, update: { executable: fake, args: ["update"] } }, + }, + }); + const ack = await executor.handle({ type: "update", engine: "claude" }); + expect(ack).toMatchObject({ + ok: true, + message: expect.stringContaining("up to date"), + }); + }); + + it("treats a setpriv-started but command-not-found installer as unusable (exit 127)", async () => { + const exit127 = makeExitCode(dir, 127); + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: process.env, + wrap: passthroughWrap, + engines: { + codex: { bin: null, install: { executable: exit127, args: [] } }, + }, + }); + const inventory = await executor.inventory(); + const codex = inventory.find((entry) => entry.id === "codex")!; + expect(codex.actions).toEqual([]); + expect(codex.issue).toBe("install-unavailable"); + }); + + it("stages a Codex device sign-in under the workload's own home, never the supervisor's", async () => { + const workloadHome = mkdtempSync( + path.join(os.tmpdir(), "dispatch-workload-home-") + ); + const codexFake = path.join(dir, "fake-codex.mjs"); + writeFileSync( + codexFake, + `#!/usr/bin/env node +import { writeFileSync } from "node:fs"; +const args = process.argv.slice(2).join(" "); +if (args === "login --device-auth") { + process.stdout.write("Open: https://auth.openai.com/codex/device\\nEnter code: ABCD-1234\\n"); + setTimeout(() => { + writeFileSync(process.env.CODEX_HOME + "/auth.json", "{}"); + process.exit(0); + }, 30); +} else if (args === "login status") { + console.log("Logged in using ChatGPT"); +} else { + process.exit(2); +} +` + ); + chmodSync(codexFake, 0o755); + // Chowning the stage dir to the process's own uid/gid is always + // permitted (no root needed), so this exercises the real + // createStageDir/chown code path rather than a mocked seam. + const uid = process.getuid?.() ?? 0; + const gid = process.getgid?.() ?? 0; + // vitest.config.ts pins CODEX_HOME for the whole suite so no test + // ever touches the real ~/.codex; a real runner's env never sets it, + // so this test must clear it to exercise the actual $HOME/.codex + // fallback the staged login script falls back to. + const { CODEX_HOME: _pinned, ...envWithoutCodexHome } = process.env; + executor = new EngineRunnerExecutor({ + uid, + gid, + env: { ...envWithoutCodexHome, HOME: workloadHome }, + wrap: passthroughWrap, + engines: { codex: { bin: codexFake } }, + }); + const started = await executor.handle({ + type: "login_start", + engine: "codex", + }); + expect(started.ok).toBe(true); + expect(started.login?.status).toBe("waiting"); + expect(started.login?.userCode).toBe("ABCD-1234"); + + const untilTerminal = async (loginId: string, timeoutMs = 5_000) => { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + const status = await executor!.handle({ + type: "login_status", + loginId, + }); + if ( + status.login?.status === "succeeded" || + status.login?.status === "failed" + ) + return status; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + throw new Error("timed out waiting for the sign-in to settle"); + }; + const status = await untilTerminal(started.login!.id); + expect(status.ok).toBe(true); + expect(status.login?.status).toBe("succeeded"); + // The final credential landed under the workload home we configured + // — proof the staged script's $HOME-derived path actually resolved + // to it, not to this (real) process's own home. This machine's real + // ~/.codex may already contain unrelated files from ordinary local + // use, so the isolation proof is "it wrote here", not "it didn't + // write there" against that uncontrolled real directory. + expect(existsSync(path.join(workloadHome, ".codex", "auth.json"))).toBe( + true + ); + rmSync(workloadHome, { recursive: true, force: true }); + }); + it("rejects an operation with no configured managed command", async () => { executor = new EngineRunnerExecutor({ uid: 1000, diff --git a/apps/server/test/engine-wire.test.ts b/apps/server/test/engine-wire.test.ts index 193f5e04a..bbe4a6b26 100644 --- a/apps/server/test/engine-wire.test.ts +++ b/apps/server/test/engine-wire.test.ts @@ -190,6 +190,32 @@ describe("engine wire integration", () => { ]); }); + it("routes engine commands over a configured-folder workspace when @session isn't advertised", async () => { + const service = makeService(); + const alpha = await enroll(service, "alpha"); + const { socket } = await dialEngineRunner({ + endpoint: alpha.endpoint, + ca: alpha.ca, + cert: alpha.cert, + key: alpha.key, + // No MANAGED_WORKSPACE at all — a runner with only named folders + // and no managed-session support, per the real runner.ts shape. + workspaces: ["proof"], + onEngine: (id, reply, operation) => { + expect(operation).toEqual({ type: "status" }); + reply({ type: "result", id, value: JSON.stringify({ ok: true }) }); + }, + }); + sockets.push(socket); + await waitFor(() => + service.available({ runner: alpha.created.id, workspace: "proof" }) + ); + + const transport = remoteEngineTransport(service); + const ack = await transport.send(alpha.created.id, { type: "status" }); + expect(ack).toEqual({ ok: true }); + }); + it("reports unsupported for an offline or non-engine-aware runner", async () => { const service = makeService(); const alpha = await enroll(service, "alpha"); diff --git a/apps/web/src/components/runner-engines/runner-engines.test.tsx b/apps/web/src/components/runner-engines/runner-engines.test.tsx index 3a5f19ade..aed624a48 100644 --- a/apps/web/src/components/runner-engines/runner-engines.test.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.test.tsx @@ -131,3 +131,109 @@ it("walks a Codex-style device sign-in to the waiting state", async () => { await waitFor(() => expect(screen.getByText("ABCD-1234")).toBeTruthy()); expect(screen.getByText("https://auth.example.com/device")).toBeTruthy(); }); + +it("surfaces a failed update instead of silently reporting success", async () => { + const ack: EngineOperationAck = { + ok: false, + error: "Update command failed (exit code 1).", + }; + vi.mocked(api).mockImplementation( + async (path: string, init?: RequestInit) => { + if (init?.method === "POST") return { ack }; + return { entries: baseEntries }; + } + ); + + renderWithClient({ kind: "local" }); + await waitFor(() => screen.getByTestId("runner-engine-claude-update")); + fireEvent.click(screen.getByTestId("runner-engine-claude-update")); + + await waitFor(() => + expect( + screen.getByTestId("runner-engine-claude-action-error").textContent + ).toContain("exit code 1") + ); +}); + +it("shows an up-to-date update as a success message, not a failure", async () => { + const ack: EngineOperationAck = { + ok: true, + message: "Already up to date (version 1.2.3).", + }; + vi.mocked(api).mockImplementation( + async (path: string, init?: RequestInit) => { + if (init?.method === "POST") return { ack }; + return { entries: baseEntries }; + } + ); + + renderWithClient({ kind: "local" }); + await waitFor(() => screen.getByTestId("runner-engine-claude-update")); + fireEvent.click(screen.getByTestId("runner-engine-claude-update")); + + await waitFor(() => + expect( + screen.getByTestId("runner-engine-claude-action-success").textContent + ).toContain("Already up to date") + ); + expect(screen.queryByTestId("runner-engine-claude-action-error")).toBeNull(); +}); + +it("polls login status and reflects a device sign-in settling on its own", async () => { + let loginPolls = 0; + vi.mocked(api).mockImplementation( + async (path: string, init?: RequestInit) => { + if (init?.method === "POST") { + const body = JSON.parse(init.body as string); + if (body.operation.type === "login_start") { + return { + ack: { + ok: true, + login: { + id: "login-1", + engine: "claude", + status: "waiting", + needsCode: false, + url: "https://auth.example.com/device", + userCode: "ABCD-1234", + expiresAt: new Date().toISOString(), + }, + }, + }; + } + // login_status: settle to "succeeded" on the second poll, the + // way a self-driven device flow finishes without the user + // submitting anything. + loginPolls += 1; + const settled = loginPolls >= 2; + return { + ack: { + ok: true, + login: { + id: "login-1", + engine: "claude", + status: settled ? "succeeded" : "waiting", + needsCode: false, + ...(settled ? { detail: "me@example.com" } : {}), + expiresAt: new Date().toISOString(), + }, + }, + }; + } + return { entries: [{ ...baseEntries[0]!, signedIn: false }] }; + } + ); + + renderWithClient({ kind: "local" }); + await waitFor(() => screen.getByTestId("runner-engine-claude-sign-in")); + fireEvent.click(screen.getByTestId("runner-engine-claude-sign-in")); + + await waitFor(() => expect(screen.getByText("ABCD-1234")).toBeTruthy()); + await waitFor( + () => + expect(screen.getByText(/Signed in/).textContent).toContain( + "me@example.com" + ), + { timeout: 5_000 } + ); +}); diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index 1192c3f3b..454bc7d9a 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useEffect, useState } from "react"; import { CheckCircle2, Loader2 } from "lucide-react"; import type { @@ -12,6 +12,7 @@ import { CopyButton } from "@/components/ui/copy-button"; import { Input } from "@/components/ui/input"; import { useRunnerEngineInventory, + useRunnerEngineLoginStatus, useRunnerEngineOperation, } from "@/hooks/use-runner-engines"; import type { EngineScope } from "@dispatch/runner-protocol/engine-management"; @@ -82,15 +83,43 @@ function EngineRow({ }): JSX.Element { const operation = useRunnerEngineOperation(scope); const [code, setCode] = useState(""); + const [actionResult, setActionResult] = useState<{ + kind: "success" | "error"; + message: string; + } | null>(null); + + // The CLI's own output (a code being verified, a device flow finishing + // on its own) settles asynchronously, after login_start/login_submit + // already returned — poll the sign-in's current view while it's active + // so that settling is actually visible instead of stuck on "waiting". + const loginActive = isLoginActive(activeLogin); + const loginStatus = useRunnerEngineLoginStatus( + scope, + loginActive ? activeLogin!.id : null + ); + useEffect(() => { + const polled = loginStatus.data?.ack; + if (polled?.ok && polled.login) onLoginChange(polled.login); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [loginStatus.data]); const run = ( op: Parameters["mutate"]>[0] - ) => + ) => { + setActionResult(null); operation.mutate(op, { onSuccess: ({ ack }) => { if (ack.ok && ack.login) onLoginChange(ack.login); + if (op.type === "install" || op.type === "update") { + setActionResult( + ack.ok + ? { kind: "success", message: ack.message ?? "Done." } + : { kind: "error", message: ack.error } + ); + } }, }); + }; const canInstall = entry.actions.includes("install"); const canUpdate = entry.actions.includes("update"); @@ -179,6 +208,28 @@ function EngineRow({

)} + {actionResult?.kind === "error" && ( +

+ {actionResult.message} +

+ )} + {actionResult?.kind === "success" && ( +

+

+ )} + {isLoginActive(activeLogin) && activeLogin && ( ({ + queryKey: [...runnerEnginesKey(scope), "login", loginId], + enabled: loginId !== null, + queryFn: () => + api(`/api/v1/engine-management/operations`, { + method: "POST", + body: JSON.stringify({ + scope, + operation: { type: "login_status", loginId }, + }), + }), + refetchInterval: (query) => { + const ack = query.state.data?.ack; + return ack?.ok && isLoginActive(ack.login) ? 1_500 : false; + }, + }); +} diff --git a/packages/runner-protocol/src/engine-management.ts b/packages/runner-protocol/src/engine-management.ts index 5b06d7b4f..a0a168cdf 100644 --- a/packages/runner-protocol/src/engine-management.ts +++ b/packages/runner-protocol/src/engine-management.ts @@ -61,7 +61,14 @@ export type EngineOperation = | { type: "update"; engine: RunnerEngine } | { type: "login_start"; engine: RunnerEngine; restart?: boolean } | { type: "login_submit"; loginId: string; code: string } - | { type: "login_cancel"; loginId: string }; + | { type: "login_cancel"; loginId: string } + /** + * Read a sign-in's current view without acting on it — the only way to + * observe progress that happens after the CLI's output arrived + * asynchronously (a code being verified, a device flow finishing on its + * own), since the op that started or answered it already returned. + */ + | { type: "login_status"; loginId: string }; /** * Progress for a long-running operation. Sent as they happen; a scope may @@ -89,7 +96,13 @@ export type EngineOperationEvent = | { type: "login_update"; login: EngineLoginView }; export type EngineOperationAck = - | { ok: true; operationId?: string; login?: EngineLoginView } + | { + ok: true; + operationId?: string; + login?: EngineLoginView; + /** e.g. "Already up to date (version 1.2.3)." — never raw CLI output. */ + message?: string; + } | { ok: false; error: string; unsupported?: boolean }; export const RUNNER_ENGINES: readonly RunnerEngine[] = [ @@ -121,7 +134,8 @@ export function isEngineOperation(value: unknown): value is EngineOperation { type === "update" || type === "login_start" || type === "login_submit" || - type === "login_cancel" + type === "login_cancel" || + type === "login_status" ); } From 97350836554f05ecb91fa73267adc55c81c43d0e Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:51:07 -0700 Subject: [PATCH 069/642] Capture the pending permission on the other runner in UI acceptance --- e2e/remote-runner/acceptance.spec.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index ce882b6df..23ae28056 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -133,7 +133,7 @@ test("UI launches local, alpha and beta; each answer comes from its own side", a }); }); -test("permissions are answered per runner and never cross", async () => { +test("permissions are answered per runner and never cross", async ({}, testInfo) => { for (const r of ["alpha", "beta"] as const) await chat(pages[r]!, "prove-permission"); const ask = (r: RunnerName) => pages[r]!.getByTestId("permission-requests"); @@ -159,6 +159,10 @@ test("permissions are answered per runner and never cross", async () => { ) ).toBe(false); await expect(ask("beta")).toBeVisible(); + await testInfo.attach("beta waiting after alpha approval", { + body: await pages.beta!.screenshot(), + contentType: "image/png", + }); await ask("beta").getByRole("button", { name: "Deny", exact: true }).click(); await expect( answers(pages.beta!, "Guest permission answered.").last() From c278b82a4c647c9a36e3bf0a6bbfbae94a24714e Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 09:52:23 -0700 Subject: [PATCH 070/642] Report Linux service startup from the installer wrapper after it succeeds --- apps/server/src/agents/remote/enrollment.ts | 12 +++--------- bin/dispatch-runner | 1 + 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 6eda6f104..db4058c24 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -138,7 +138,7 @@ export function pinnedAuthority(pem: unknown, pin: string): X509Certificate { now > new Date(ca.validTo).getTime() ) { throw new Error( - "The service certificate does not match the pinned Dispatch runner CA." + "The service certificate does not match the pinned runner CA." ); } return ca; @@ -165,7 +165,7 @@ export function verifyServiceLeaf( !names ) { throw new Error( - "The service certificate does not match the pinned Dispatch runner CA." + "The service certificate does not match the pinned runner CA." ); } } @@ -646,9 +646,7 @@ function verifyIssuedConnectCredentials( pin !== undefined && issuedCa.fingerprint256 !== normalizeFingerprint(pin) ) - throw new Error( - "The issued CA does not match the pinned Dispatch runner CA." - ); + throw new Error("The issued CA does not match the pinned runner CA."); } /** `dispatch-runner connect …`: ask an operator to approve this runner. */ @@ -721,10 +719,6 @@ export async function runRunnerConnect(argv: string[]) { cert: path.join(options.dir, "cert.pem"), key: path.join(options.dir, "key.pem"), })}`, - // This CLI never touches systemd itself (see persistRunnerCredentials); - // the installer only installs and daemon-reloads, so enrollment is - // the last step that needs telling the operator what to do next. - "Start it: sudo systemctl enable --now dispatch-runner.service", "", ].join("\n") ); diff --git a/bin/dispatch-runner b/bin/dispatch-runner index f8dbaf9a4..5b96dab2a 100755 --- a/bin/dispatch-runner +++ b/bin/dispatch-runner @@ -17,3 +17,4 @@ exec 9>"$runtime/install.lock" flock -n 9 || { printf 'Another runner install, update, or connection is running.\n' >&2; exit 1; } "$runtime/dispatch" "$@" systemctl enable --now dispatch-runner.service +printf 'Runner service started.\n' From 7c2424833f819a707511d16df403730d13127c57 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 11:55:03 -0700 Subject: [PATCH 071/642] Pair runners with a single service URL and return the approval link --- apps/server/src/agents/remote/enrollment.ts | 72 +++++------- apps/server/src/agents/remote/service.ts | 82 ++----------- apps/server/src/routes/runners.ts | 4 +- .../server/test/remote-runner-connect.test.ts | 111 ++++++------------ apps/web/src/components/app/runner-health.tsx | 7 +- bin/dispatch-dev | 12 +- docs/design/remote-runner-prototype.md | 31 ++--- docs/remote-runner-linux.md | 10 +- e2e/remote-runner/harness.ts | 20 ++-- e2e/remote-runner/playwright.config.ts | 1 + 10 files changed, 121 insertions(+), 229 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index db4058c24..1cc9eeb16 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -79,41 +79,16 @@ export function pairingCommand(input: { * Dispatch API is loopback-only or plain HTTP, since nothing about it * depends on the main API's own binding or certificate. */ -/** - * A bare shell word, single-quoted. Only ever used for a URL that already - * passed `new URL(...)`, so the single-quote rejection is a defense-in-depth - * backstop, not the primary validation. - */ -function shellSingleQuoted(value: string) { - if (value.includes("'") || /[\x00-\x1f]/.test(value)) - throw new Error("Value is not safe to embed in a shell command."); - return `'${value}'`; -} - export function connectCliCommand(input: { host: string; port: number; caFingerprint: string; - /** Embedded as `--approval-url` so the CLI can print it without needing - * the service to know the operator's browser origin on its own. */ - approvalUrl?: string; }) { - const pin = normalizeFingerprint(input.caFingerprint) - .replace(/:/g, "") - .toLowerCase(); - const parts = [ - // Writing to the default /etc/dispatch-runner needs root, same as - // remote-runner-pair; unlike that command, this one is copied and run - // directly by an operator, so spell it out rather than assume it. - "sudo dispatch-runner connect", - `--service https://${formatHost(input.host)}:${input.port}`, - `--ca-sha256 ${pin}`, - ]; - if (input.approvalUrl !== undefined) - parts.push( - `--approval-url ${shellSingleQuoted(new URL(input.approvalUrl).toString())}` - ); - return parts.join(" "); + const pin = normalizeFingerprint(input.caFingerprint).replace(/:/g, ""); + const service = new URL(`https://${formatHost(input.host)}:${input.port}`); + // The fragment conveys trust from Settings and is never sent over HTTP. + service.hash = `sha256=${Buffer.from(pin, "hex").toString("base64url")}`; + return `sudo dispatch-runner connect '${service.href}'`; } /** @@ -445,19 +420,40 @@ type ConnectOptions = { }; function parseConnectArgs(argv: string[]): ConnectOptions { + const positional = argv[0] && !argv[0].startsWith("--") ? argv[0] : undefined; const values = new Map(); - for (let index = 0; index < argv.length; index += 2) { + for (let index = positional ? 1 : 0; index < argv.length; index += 2) { const flag = argv[index]; const value = argv[index + 1]; if (!flag?.startsWith("--") || value === undefined) throw new Error(`Unexpected argument: ${flag ?? ""}`); values.set(flag.slice(2), value); } - const service = values.get("service"); - if (!service) + if (positional && values.has("service")) + throw new Error("Supply only one service URL."); + const address = positional ?? values.get("service"); + if (!address) throw new Error( - "Usage: dispatch-runner connect --service https://HOST:PORT [--ca-sha256 HEX] [--approval-url URL] [--dir /etc/dispatch-runner] [--config FILE]" + "Usage: dispatch-runner connect [--dir DIR] [--config FILE]" ); + const service = new URL(address); + let pin = values.get("ca-sha256"); + if (service.hash) { + const encoded = /^#sha256=([A-Za-z0-9_-]{43})$/.exec(service.hash)?.[1]; + if ( + !encoded || + Buffer.from(encoded, "base64url").toString("base64url") !== encoded + ) + throw new Error("Invalid service URL fingerprint."); + const embedded = Buffer.from(encoded, "base64url").toString("hex"); + if ( + pin !== undefined && + normalizeFingerprint(pin) !== normalizeFingerprint(embedded) + ) + throw new Error("Conflicting service fingerprints."); + pin = embedded; + service.hash = ""; + } const approvalUrl = values.get("approval-url"); if (approvalUrl !== undefined) { const protocol = new URL(approvalUrl).protocol; @@ -465,8 +461,8 @@ function parseConnectArgs(argv: string[]): ConnectOptions { throw new Error("--approval-url must be an http(s) URL."); } return { - service, - pin: values.get("ca-sha256"), + service: service.href, + pin, dir: path.resolve(values.get("dir") ?? "/etc/dispatch-runner"), config: values.get("config"), approvalUrl, @@ -661,10 +657,6 @@ export async function runRunnerConnect(argv: string[]) { { pin: options.pin, timeoutMs: options.timeoutMs } )) as ConnectCreated; - // `--approval-url` (the operator's own browser, baked into the copied - // command by connect-command) takes priority: the service's own - // approveUrl only exists when DISPATCH_RUNNER_APPROVAL_ORIGIN is set, - // which a preview or default install typically has no reason to. const approveUrl = options.approvalUrl ?? created.approveUrl; process.stdout.write( [ diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 13451709c..24f743809 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -62,15 +62,7 @@ export type EnrollmentOptions = { endpointHost?: string; /** External HTTPS MCP origin; defaults to the runner listener's proxy. */ mcpOrigin?: string; - /** - * Where an operator approves a runner-initiated connect request in a - * browser — the Dispatch web app's own reachable origin, http or https - * (a Vite dev server is plain HTTP on its own port; production is - * typically HTTPS). Unset means no link is offered: a single inbound - * request's own Host header is reliable for `connectCommand` (the - * operator's own browser call) but not for `createConnectRequest` (the - * runner's), which has no way to know the operator's browser origin. - */ + /** Public web origin when the operator UI has a separate listener or proxy. */ approvalOrigin?: string; /** * Service-side approval for the runner's fixed repo operation: true for @@ -149,20 +141,6 @@ function validHost(host: string) { ); } -/** - * A bare `host[:port]`, as a Host header should contain. Used before a - * request-derived value is embedded in a URL that itself gets embedded in - * a copy-pasted shell command (`connectCommand`'s `--approval-url`) — - * reject anything else rather than let a crafted Host header ride along. - */ -function validHostPort(value: string) { - const match = /^(\[[0-9a-fA-F:]+\]|[^:[\]\s]+)(?::(\d+))?$/.exec(value); - if (!match) return false; - const host = match[1]!.replace(/^\[|\]$/g, ""); - const port = match[2]; - return validHost(host) && (!port || Number(port) <= 65535); -} - function httpsOrigin(value: string | undefined, label: string) { if (!value) return undefined; if (new URL(value).protocol !== "https:") @@ -1022,61 +1000,28 @@ export class RemoteRunnerService { // Runner-initiated ("connect") enrollment // --------------------------------------------------------------------------- - /** - * `GET /api/runners/connect-command`: the authenticated operator's copy - * of the invocation to run on the runner. Unlike pairing, this is not - * single-use — the runner supplies its own one-time code — so the same - * command stays valid for any number of runners until the CA renews. - * The approval link uses this request's own (authenticated, unproxied) - * Host header: it is for the operator's browser, which is already here. - */ - /** Where an operator approves a connect request, if known. */ - /** - * `fallbackProtocol` is the *browser's* own scheme for this request - * (Fastify's `request.protocol`) — a LAN preview's Vite frontend is - * plain HTTP even though the runner's own bootstrap stays HTTPS-only, - * so this can never be assumed to be `https`. - */ - private approveUrl(fallbackHost?: string, fallbackProtocol?: string) { - if (this.enrollment?.approvalOrigin) - return `${this.enrollment.approvalOrigin}/settings/connections`; - // Best-effort only: reliable when `fallbackHost`/`fallbackProtocol` are - // this request's own (unproxied) Host header and scheme, not when - // they're a guess at the runner's view of the service. - if (!fallbackHost || !validHostPort(fallbackHost)) return undefined; - const protocol = - fallbackProtocol === "http" || fallbackProtocol === "https" - ? fallbackProtocol - : "https"; - return `${protocol}://${fallbackHost}/settings/connections`; + private approveUrl() { + let origin = this.enrollment?.approvalOrigin; + if (!origin && this.api) { + const { host, port, tls } = this.api; + const webHost = + host === "0.0.0.0" || host === "::" ? advertisedHost(undefined) : host; + origin = `${tls ? "https" : "http"}://${formatHost(webHost)}:${port}`; + } + return origin ? new URL("/settings/connections", origin).href : undefined; } - /** - * `GET /api/runners/connect-command`. The approval link is embedded in - * the printed command itself (`--approval-url`) as well as returned - * alongside it: with no `DISPATCH_RUNNER_APPROVAL_ORIGIN` configured — - * the common case for a preview or default install — this request's own - * Host header and scheme (the operator's browser, calling this - * authenticated route directly) are still the best answer, and the CLI - * has no other way to learn them. - */ - async connectCommand( - hostHint?: string, - rawHost?: string, - rawProtocol?: string - ) { + async connectCommand(hostHint?: string) { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); const host = await this.prepareEndpoint(hostHint); - const approveUrl = this.approveUrl(rawHost, rawProtocol); return { command: connectCliCommand({ host, port: this.port!, caFingerprint: this.authority!.caFingerprint, - approvalUrl: approveUrl, }), - approveUrl, + approveUrl: this.approveUrl(), }; } @@ -1097,9 +1042,6 @@ export class RemoteRunnerService { id, code, expiresAt: expiresAt.toISOString(), - // Only ever set from configuration (see approveUrl): this request - // came from the runner, which has no way to tell us the operator's - // browser origin, so there is no per-request fallback to guess. approveUrl: this.approveUrl(), }; } catch (error) { diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts index 3d784e557..a75565305 100644 --- a/apps/server/src/routes/runners.ts +++ b/apps/server/src/routes/runners.ts @@ -135,9 +135,7 @@ export async function registerRunnerRoutes( .send({ error: "Runner enrollment is disabled." }); try { return await deps.runners.connectCommand( - hostHint(request.headers.host), - request.headers.host, - request.protocol + hostHint(request.headers.host) ); } catch (error) { return fail(reply, error); diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index 85f34186d..67880bb31 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -163,9 +163,9 @@ describe("runner-initiated connect enrollment", () => { expect(created.id).toMatch(/^conn_/); expect(created.code).toMatch(/^[0-9A-Z]{4}-[0-9A-Z]{4}$/); expect(new Date(created.expiresAt).getTime()).toBeGreaterThan(Date.now()); - // No DISPATCH_RUNNER_APPROVAL_ORIGIN configured: omitted, not guessed — - // this call came from the runner, which has no browser origin to offer. - expect(created.approveUrl).toBeUndefined(); + expect(created.approveUrl).toBe( + `http://${HOST}:${(api.address() as AddressInfo).port}/settings/connections` + ); expect(await service.pollConnectRequest(created.id)).toEqual({ status: "pending", @@ -180,20 +180,16 @@ describe("runner-initiated connect enrollment", () => { ]); }); - it("offers an approval link, including over plain HTTP for a dev frontend, only when configured", async () => { + it("offers an approval link, including over plain HTTP for a dev frontend, when the web UI uses a separate origin", async () => { const service = makeService("http://localhost:5173"); const { publicKey } = generateRunnerKey(); const created = await service.createConnectRequest(publicKey); expect(created.approveUrl).toBe( "http://localhost:5173/settings/connections" ); - // connect-command prefers the same configured origin over the - // (unreliable for a dev frontend on a different port) request host. - const built = await service.connectCommand(HOST, "127.0.0.1:9999"); - expect(built.approveUrl).toBe("http://localhost:5173/settings/connections"); - expect(built.command).toContain( - "--approval-url 'http://localhost:5173/settings/connections'" - ); + const built = await service.connectCommand(HOST); + expect(built.approveUrl).toBe(created.approveUrl); + expect(built.command).not.toContain("localhost:5173"); }); it("rejects a malformed DISPATCH_RUNNER_APPROVAL_ORIGIN", () => { @@ -222,48 +218,10 @@ describe("runner-initiated connect enrollment", () => { ).rejects.toMatchObject({ status: 400 }); }); - it("builds a reusable, sudo-prefixed connect command embedding the approval link", async () => { + it("keeps the copied service address reusable across runner registrations", async () => { const service = makeService(); - const built = await service.connectCommand(HOST, "web.example:8443"); - expect(built.command).toMatch( - /^sudo dispatch-runner connect --service https:\/\/127\.0\.0\.1:\d+ --ca-sha256 [a-f0-9]{64} --approval-url 'https:\/\/web\.example:8443\/settings\/connections'$/ - ); - expect(built.approveUrl).toBe( - "https://web.example:8443/settings/connections" - ); - // Not single-use: asking again returns the same reachable address. - const again = await service.connectCommand(HOST, "web.example:8443"); - expect(again.command).toBe(built.command); - }); - - it("drops a Host header that isn't a safe bare host[:port] rather than embed it anywhere", async () => { - const service = makeService(); - const built = await service.connectCommand( - HOST, - "web.example:8443'; rm -rf / #" - ); - expect(built.approveUrl).toBeUndefined(); - expect(built.command).not.toContain("--approval-url"); - expect(built.command).not.toContain("rm -rf"); - }); - - it("matches a plain-HTTP LAN preview frontend's own scheme, not the bootstrap's HTTPS", async () => { - const service = makeService(); - // A Vite dev frontend reachable on the LAN is plain HTTP on its own - // port, independent of the runner's own (always-HTTPS) bootstrap. - const built = await service.connectCommand( - HOST, - "192.168.1.246:59244", - "http" - ); - expect(built.approveUrl).toBe( - "http://192.168.1.246:59244/settings/connections" - ); - expect(built.command).toContain( - "--approval-url 'http://192.168.1.246:59244/settings/connections'" - ); - // The --service target is still always https, regardless. - expect(built.command).toMatch(/--service https:\/\//); + const first = await service.connectCommand(HOST); + expect((await service.connectCommand(HOST)).command).toBe(first.command); }); it("approves with the correct code, binds the key, and lets the runner connect", async () => { @@ -387,8 +345,8 @@ describe("runner-initiated connect enrollment", () => { it("runs the real CLI end-to-end over the runner listener's own pinned HTTPS (no main API HTTPS needed)", async () => { const service = makeService(); const { command } = await service.connectCommand(HOST); - const [, endpoint, pin] = - /--service (\S+) --ca-sha256 (\S+)/.exec(command) ?? []; + const [, endpoint] = + /^sudo dispatch-runner connect '(https:\/\/[^']+)'$/.exec(command) ?? []; const dir = await mkdtemp(path.join(tmpdir(), "connect-cli-")); const printed: string[] = []; @@ -398,16 +356,11 @@ describe("runner-initiated connect enrollment", () => { return true; }; - const connectPromise = runRunnerConnect([ - "--service", - endpoint!, - "--ca-sha256", - pin!, - "--dir", - dir, - ]).finally(() => { - process.stdout.write = originalWrite; - }); + const connectPromise = runRunnerConnect([endpoint!, "--dir", dir]).finally( + () => { + process.stdout.write = originalWrite; + } + ); let id: string | undefined; let code: string | undefined; @@ -420,6 +373,9 @@ describe("runner-initiated connect enrollment", () => { // The UI's own last-8-characters reference matches what the CLI prints. expect(printed.join("")).toContain(`Request: ${id!.slice(-8)}`); + expect(printed.join("")).toContain( + `Approve at: http://${HOST}:${(api.address() as AddressInfo).port}/settings/connections` + ); await service.approveConnectRequest(id!, code!, "zeta", HOST); await connectPromise; @@ -432,7 +388,7 @@ describe("runner-initiated connect enrollment", () => { runners.push( await dialRunner({ - endpoint: endpoint!, + endpoint: new URL(endpoint!).origin, ca, cert, key, @@ -506,26 +462,29 @@ function connectServer( } describe("connect command shell safety", () => { - it("sudo-prefixes and omits --approval-url when none is given", () => { + it("copies a single service URL with the private CA fingerprint", () => { const command = connectCliCommand({ host: "runner.example", port: 12345, caFingerprint: "AB".repeat(32), }); expect(command).toBe( - `sudo dispatch-runner connect --service https://runner.example:12345 --ca-sha256 ${"ab".repeat(32)}` + `sudo dispatch-runner connect 'https://runner.example:12345/#sha256=${Buffer.alloc(32, 0xab).toString("base64url")}'` ); }); - it("rejects an approval URL that isn't a well-formed URL at all", () => { - expect(() => - connectCliCommand({ - host: "runner.example", - port: 1, - caFingerprint: "AB".repeat(32), - approvalUrl: "not a url", - }) - ).toThrow(); + it("rejects malformed or conflicting URL fingerprints before enrollment", async () => { + await expect( + runRunnerConnect(["https://example.org/#sha256=oops"]) + ).rejects.toThrow(/Invalid service URL fingerprint/); + const encoded = Buffer.alloc(32, 1).toString("base64url"); + await expect( + runRunnerConnect([ + `https://example.org/#sha256=${encoded}`, + "--ca-sha256", + "00".repeat(32), + ]) + ).rejects.toThrow(/Conflicting service fingerprints/); }); it("CLI rejects a non-http(s) --approval-url before contacting the service", async () => { diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index 90e173234..8b4bd432c 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -14,7 +14,12 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) { const [open, setOpen] = useState(false); const installer = useRunnerInstaller(open); const tag = installer.data?.tag; - if (!health || !healthReceivedAt) return null; + if (!health || !healthReceivedAt) + return runner.status === "online" ? ( +

+ No health report received. +

+ ) : null; const update = tag && /^v?\d+\.\d+\.\d+$/.test(health.version) && diff --git a/bin/dispatch-dev b/bin/dispatch-dev index 0d71f2555..afc79f924 100755 --- a/bin/dispatch-dev +++ b/bin/dispatch-dev @@ -494,6 +494,16 @@ cmd_up() { DEV_LAN_HOST="" [ "$DEV_BIND_HOST" = "0.0.0.0" ] && DEV_LAN_HOST="$(lan_address)" + DEV_VITE_PORT="${RESTART_VITE_PORT:-$(find_free_port)}" + while [ "$DEV_VITE_PORT" = "$DEV_API_PORT" ]; do + DEV_VITE_PORT="$(find_free_port)" + done + local web_host="${DEV_LAN_HOST:-$DEV_DISPLAY_HOST}" + case "$web_host" in + ::) web_host="[::1]" ;; + *:*) web_host="[${web_host}]" ;; + esac + # Build environment ( @@ -520,6 +530,7 @@ cmd_up() { # Override port, session prefix, and agent runtime — always explicit so .env doesn't leak export DISPATCH_PORT="$DEV_API_PORT" + export DISPATCH_RUNNER_APPROVAL_ORIGIN="${DISPATCH_RUNNER_APPROVAL_ORIGIN:-http://$web_host:$DEV_VITE_PORT}" export DISPATCH_DEV_STACK=1 # Bind to all interfaces so the dev stack is reachable from other devices # (phone, another laptop) on the LAN or tailnet, not just this machine. @@ -607,7 +618,6 @@ cmd_up() { fi # --- Vite Frontend --- - DEV_VITE_PORT="${RESTART_VITE_PORT:-$(find_free_port)}" local vite_cache_dir vite_cache_dir="$(log_dir)/vite-cache" diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index abd7481e1..df8afdbb1 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -107,7 +107,7 @@ optional when `endpointHost` is given. ## Runner-initiated enrollment -`dispatch-runner connect --service https://HOST:PORT [--ca-sha256 HEX] +`dispatch-runner connect [--dir /etc/dispatch-runner] [--config FILE]` enrolls without a pairing command typed on the runner: the runner dials the Dispatch service itself. `GET /api/runners/connect-command` (authenticated) gives an operator the @@ -126,25 +126,16 @@ for the CLI's own polling. The CLI prints the code and polls `GET /api/runners/connect/:id` (addressed only by that same opaque id) until an operator approves it. -Both `connect-command` and the create response may also carry an -`approveUrl` pointing at **Settings → Connections → Remote runners**. For -`connect-command` it is built from that authenticated call's own (reliable) -Host header and scheme — a LAN preview's Vite frontend is plain HTTP on its -own port, so the scheme is never assumed to be HTTPS even though the -runner's own bootstrap always is — or from `DISPATCH_RUNNER_APPROVAL_ORIGIN` -when that is set (a bare `http://` or `https://` origin; `http://` so a -Vite dev server's own port can be used, not just a production HTTPS -origin). The Host is checked against a bare-host-and-port shape before it -goes anywhere near a URL. That URL is also embedded directly in the printed -command as `--approval-url`, single-quoted and re-validated as a -well-formed URL first, so the common preview or default-install case (no -approval-origin configured at all) still gets a working link without the -service needing to know anything about the operator's browser in advance. -The create call has no such host to go on — it comes from the runner, not -a browser — so its own `approveUrl` is only ever populated from -`DISPATCH_RUNNER_APPROVAL_ORIGIN`; unset, it is omitted -and the CLI falls back to whatever `--approval-url` it was given, or -code-only instructions if that's absent too. +Settings supplies a single HTTPS service URL. For Dispatch's private listener +the URL fragment carries the SHA-256 fingerprint of the service CA, encoded +in base64url. The runner verifies it locally before requesting a code. A bare +HTTPS service URL uses the runner host's normal certificate trust store. + +The create response supplies the browser approval link alongside the code. +Dispatch uses its web listener address, or the public web origin configured +by the service when it serves the UI separately (including Vite previews). +The runner prints the link supplied by the service. Older commands with +`--service`, `--ca-sha256` and `--approval-url` are still accepted. The operator reads the code off the runner's own terminal or logs — it is never sent back by the runner — and calls the authenticated diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index ea4ec527a..7e3725103 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -11,16 +11,14 @@ The runner must be able to reach the HTTPS address in the pairing command. the installation command for the available release. The installer prepares the workload account and configuration, and adds `dispatch-runner` to `/usr/local/bin`. -2. Run the separate connect command on Linux. Use the service URL and any - CA pin supplied by Dispatch Settings: +2. Run the separate connect command on Linux. Copy the service URL from Dispatch Settings: ```sh - sudo dispatch-runner connect --service 'https://dispatch.example' + sudo dispatch-runner connect 'https://dispatch.example' ``` - Add `--ca-sha256 HEX` if Settings includes a CA fingerprint for a - privately trusted service. Enter the code shown in the terminal into - Dispatch and approve the connection there. The installed command enables + Keep the full URL when copying. For a private certificate it includes a + fingerprint. Open the approval link printed by the runner and enter its code. The installed command enables and starts the service once enrollment succeeds. Wait for **Online** in Settings. diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 74e76fcf1..9a9c541a2 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -127,20 +127,17 @@ async function connectCommand(page: Page) { return (await command.innerText()).trim(); } -function commandOption(command: string, flag: string) { - const match = new RegExp(flag + " +(?:'([^']+)'|([^\\s]+))").exec(command); - return match?.[1] ?? match?.[2]; -} - export async function requestConnection( page: Page, name: GuestName, dir = "/etc/dispatch-runner" ) { const command = await connectCommand(page); - const service = new URL(commandOption(command, "--service")!); - const pin = commandOption(command, "--ca-sha256"); - const approvalUrl = commandOption(command, "--approval-url"); + const match = /^sudo dispatch-runner connect '(https:\/\/[^']+)'$/.exec( + command + ); + expect(match, "Settings supplies exactly one service URL").toBeTruthy(); + const service = new URL(match![1]!); if (Number(service.port) === state.runnerPort) service.port = String(state.runners[name].proxyPort); const args = [ @@ -148,12 +145,9 @@ export async function requestConnection( state.runners[name].container, "/opt/bin/dispatch-runner", "connect", - "--service", service.href, "--dir", dir, - ...(pin ? ["--ca-sha256", pin] : []), - ...(approvalUrl ? ["--approval-url", approvalUrl] : []), ...(dir === "/etc/dispatch-runner" ? ["--config", "/run/cfg/runner.json"] : []), @@ -191,7 +185,9 @@ export async function requestConnection( ) .toBeTruthy(); const { code, reference } = approval()!; - if (approvalUrl) expect(output).toContain(`Approve at: ${approvalUrl}`); + expect(output).toContain( + `Approve at: ${new URL("/settings/connections", page.url()).href}` + ); const form = page.getByTestId("runner-approval").filter({ has: page.getByText(`Connection request · ${reference}`, { exact: true }), }); diff --git a/e2e/remote-runner/playwright.config.ts b/e2e/remote-runner/playwright.config.ts index bd00053a5..d7e34fe58 100644 --- a/e2e/remote-runner/playwright.config.ts +++ b/e2e/remote-runner/playwright.config.ts @@ -19,6 +19,7 @@ export default defineConfig({ ...(base.webServer as object), env: { ...((base.webServer as { env?: Record }).env ?? {}), + DISPATCH_HOST: "127.0.0.1", DISPATCH_RUNNER_HOST: process.env.DISPATCH_RUNNER_HOST ?? "", DISPATCH_RUNNER_REPO_TOOL: process.env.DISPATCH_RUNNER_REPO_TOOL ?? "", DISPATCH_RUNNER_PORT: process.env.DISPATCH_RUNNER_PORT ?? "", From 5ba0486091aba227a9baa2715e9422f5449c2ae1 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 19:24:13 -0700 Subject: [PATCH 072/642] Exercise runner disconnects while a permission decision is pending --- e2e/remote-runner/acceptance.spec.ts | 33 +++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index 23ae28056..1f896e938 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -1,4 +1,5 @@ import { expect, test, type Page } from "@playwright/test"; +import type { AgentPermissionsResponse } from "@dispatch/shared"; import { authHeaders, cleanupE2EAgents } from "../helpers"; import { agentInfo, @@ -133,12 +134,36 @@ test("UI launches local, alpha and beta; each answer comes from its own side", a }); }); -test("permissions are answered per runner and never cross", async ({}, testInfo) => { +test("permission decisions stay on their runner across a disconnect", async ({ + request, +}, testInfo) => { + const betaBefore = invocations("beta"); + const url = `/api/v1/agents/${agents.beta}/permissions`; + const betaPermissions = async (): Promise => { + const response = await request.get(url, { headers: authHeaders() }); + expect(response.ok()).toBe(true); + return response.json(); + }; for (const r of ["alpha", "beta"] as const) await chat(pages[r]!, "prove-permission"); const ask = (r: RunnerName) => pages[r]!.getByTestId("permission-requests"); await expect(ask("alpha")).toBeVisible({ timeout: 30_000 }); await expect(ask("beta")).toBeVisible({ timeout: 30_000 }); + const pending = (await betaPermissions()).requests; + expect(pending).toHaveLength(1); + const permissionId = pending[0]!.id; + await lane("beta", "block"); + await expect + .poll(async () => (await betaPermissions()).connected) + .toBe(false); + const offlineAnswer = await request.post( + `${url}/${encodeURIComponent(permissionId)}`, + { + headers: authHeaders(), + data: { optionId: "allow" }, + } + ); + expect(offlineAnswer.status()).toBe(409); await ask("alpha") .getByRole("button", { name: "Allow once", exact: true }) .click(); @@ -158,6 +183,11 @@ test("permissions are answered per runner and never cross", async ({}, testInfo) `test -f ${state.runners.beta.workspaceDir}/protected-action` ) ).toBe(false); + await lane("beta", "allow"); + await expect.poll(betaPermissions, { timeout: 60_000 }).toMatchObject({ + connected: true, + requests: [{ id: permissionId }], + }); await expect(ask("beta")).toBeVisible(); await testInfo.attach("beta waiting after alpha approval", { body: await pages.beta!.screenshot(), @@ -167,6 +197,7 @@ test("permissions are answered per runner and never cross", async ({}, testInfo) await expect( answers(pages.beta!, "Guest permission answered.").last() ).toBeVisible({ timeout: 30_000 }); + expect(invocations("beta")).toBe(betaBefore + 1); expect( guestOk( "beta", From c9eae4d5450d39b73cf875ba38d4f4ea1ee24be2 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 19:33:01 -0700 Subject: [PATCH 073/642] Separate the runner wire contract from connection and service state --- apps/server/src/agents/remote/enrollment.ts | 115 +++------ apps/server/src/agents/remote/runner.ts | 7 +- apps/server/src/agents/remote/service.ts | 235 +++++++----------- .../server/test/remote-runner-connect.test.ts | 20 +- .../test/remote-runner-enrollment.test.ts | 20 +- .../test/runner-protocol-consumer.test.ts | 93 ++++++- package.json | 1 + packages/runner-protocol/README.md | 67 +++++ packages/runner-protocol/package.json | 1 + packages/runner-protocol/src/connection.ts | 95 +++++++ packages/runner-protocol/src/enrollment.ts | 30 +++ packages/runner-protocol/src/execution.ts | 114 +++++++++ packages/runner-protocol/src/index.ts | 172 +------------ packages/runner-protocol/src/node.ts | 18 +- packages/runner-protocol/src/placement.ts | 44 ++++ packages/runner-protocol/src/session.ts | 47 ++++ 16 files changed, 664 insertions(+), 415 deletions(-) create mode 100644 packages/runner-protocol/src/connection.ts create mode 100644 packages/runner-protocol/src/enrollment.ts create mode 100644 packages/runner-protocol/src/execution.ts create mode 100644 packages/runner-protocol/src/placement.ts create mode 100644 packages/runner-protocol/src/session.ts diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 1cc9eeb16..02abe20a1 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -5,7 +5,13 @@ import https from "node:https"; import { isIP } from "node:net"; import path from "node:path"; import { connect, type TLSSocket } from "node:tls"; -import { wireFrames } from "./protocol.js"; +import { + wireFrames, + type ConnectCreated, + type ConnectPoll, + type EnrollmentRequest, + type EnrollmentReply, +} from "./protocol.js"; import { generateRunnerKey, normalizeFingerprint } from "./x509.js"; /* @@ -15,13 +21,6 @@ import { generateRunnerKey, normalizeFingerprint } from "./x509.js"; * the code, generates its private key locally and only sends the public key. */ -export type EnrollFrame = - | { type: "enroll"; version: 1; code: string; publicKey: string } - | { type: "enrolled"; id: string; name: string; cert: string; ca: string } - | { type: "enroll_error"; error: string } - | { type: "ca_request"; version: 1 } - | { type: "ca"; ca: string }; - /** Display names only; placements address runners by registration id. */ export function validRunnerName(name: unknown): name is string { return ( @@ -33,23 +32,6 @@ export function validRunnerName(name: unknown): name is string { ); } -/** Mirrors the runner protocol's opaque workspace identity rule. */ -export function validWorkspaceId(value: unknown): value is string { - if ( - typeof value !== "string" || - value.length === 0 || - value.length > 128 || - /[\x00-\x1f\x7f-\x9f]/u.test(value) - ) - return false; - try { - encodeURIComponent(value); - return true; - } catch { - return false; - } -} - export function formatHost(host: string) { return isIP(host) === 6 ? `[${host}]` : host; } @@ -195,13 +177,13 @@ async function writeAtomic(file: string, data: string, mode: number) { type Endpoint = { host: string; port: number }; /** One frame out, one frame back, over a fresh TLS connection. */ -function roundTrip( +function roundTrip( endpoint: Endpoint, tls: { ca?: string }, timeoutMs: number, - request: (socket: TLSSocket) => EnrollFrame, - accept: (reply: EnrollFrame) => unknown -): Promise { + request: (socket: TLSSocket) => EnrollmentRequest, + accept: (reply: EnrollmentReply) => T +): Promise { return new Promise((resolve, reject) => { let settled = false; const socket = connect({ @@ -214,13 +196,13 @@ function roundTrip( // the returned CA must match the pinned digest. { rejectUnauthorized: false }), }); - const finish = (error?: Error, value?: unknown) => { + const finish = (...result: [Error] | [null, T]) => { if (settled) return; settled = true; clearTimeout(timer); socket.destroy(); - if (error) reject(error); - else resolve(value); + if (result[0]) reject(result[0]); + else resolve(result[1]); }; const timer = setTimeout( () => finish(new Error("Pairing timed out.")), @@ -231,23 +213,25 @@ function roundTrip( finish(new Error("The service closed the pairing connection.")) ); socket.once("secureConnect", () => { - let frame: EnrollFrame; + let frame: EnrollmentRequest; try { frame = request(socket); } catch (error) { return finish(error as Error); } - const send = wireFrames(socket, (incoming) => { - const reply = incoming as unknown as EnrollFrame; - if (reply.type === "enroll_error") - return finish(new Error(reply.error)); - try { - finish(undefined, accept(reply)); - } catch (error) { - finish(error as Error); + const send = wireFrames( + socket, + (reply) => { + if (reply.type === "enroll_error") + return finish(new Error(reply.error)); + try { + finish(null, accept(reply)); + } catch (error) { + finish(error as Error); + } } - }); - send(frame as never); + ); + send(frame); }); }); } @@ -277,19 +261,8 @@ export async function exchangeCode(input: { }; const timeoutMs = input.timeoutMs ?? 15_000; normalizeFingerprint(input.pin); - const caPem = (await roundTrip( - endpoint, - {}, - timeoutMs, - () => ({ type: "ca_request", version: 1 }), - (reply) => { - if (reply.type !== "ca") throw new Error("Unexpected pairing reply."); - pinnedAuthority(reply.ca, input.pin); - return reply.ca; - } - )) as string; - const ca = pinnedAuthority(caPem, input.pin); - return (await roundTrip( + const { caPem, ca } = await fetchPinnedCa(endpoint, input.pin, timeoutMs); + return roundTrip( endpoint, { ca: caPem }, timeoutMs, @@ -317,7 +290,7 @@ export async function exchangeCode(input: { throw new Error("The issued certificate does not match."); return reply; } - )) as Extract; + ); } /** @@ -484,18 +457,16 @@ async function fetchPinnedCa( pin: string, timeoutMs: number ): Promise<{ caPem: string; ca: X509Certificate }> { - const caPem = (await roundTrip( + return roundTrip( endpoint, {}, timeoutMs, () => ({ type: "ca_request", version: 1 }), (reply) => { if (reply.type !== "ca") throw new Error("Unexpected pairing reply."); - pinnedAuthority(reply.ca, pin); - return reply.ca; + return { caPem: reply.ca, ca: pinnedAuthority(reply.ca, pin) }; } - )) as string; - return { caPem, ca: pinnedAuthority(caPem, pin) }; + ); } /** @@ -592,26 +563,6 @@ async function requestJson( }); } -type ConnectCreated = { - id: string; - code: string; - expiresAt: string; - /** Set only when the service has an approval origin configured. */ - approveUrl?: string; -}; -type ConnectPoll = - | { status: "pending" } - | { - status: "approved"; - id: string; - name: string; - endpoint: string; - cert: string; - ca: string; - } - | { status: "denied" } - | { status: "expired" }; - /** * Independent, local checks on an approved reply before anything from it * is trusted enough to write to disk — on top of, not instead of, the TLS diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 3291f686f..4e9aa2c56 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -39,7 +39,8 @@ import { RUNNER_WIRE_VERSION, wireFrames, type Command, - type Frame, + type RunnerFrame, + type ServiceFrame, type RunnerEngine, type RunnerRepository, } from "./protocol.js"; @@ -507,7 +508,7 @@ export async function runRemoteRunner(filename: string) { for (const channel of channels.values()) channel.destroy(); finished(); }); - const safeSend = (frame: Frame) => { + const safeSend = (frame: RunnerFrame) => { if (!socket.destroyed) { try { send(frame); @@ -677,7 +678,7 @@ export async function runRemoteRunner(filename: string) { } } - const send = wireFrames(socket, (frame) => { + const send = wireFrames(socket, (frame) => { if (frame.type === "accept_health" && !healthInterval) { acceptsInventory = frame.engineInventory === true; void reportHealth(); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 24f743809..2d326b61e 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -5,18 +5,30 @@ import https from "node:https"; import { connect as connectTcp, isIP } from "node:net"; import os from "node:os"; import { createServer, type Server, type TLSSocket } from "node:tls"; -import type { Duplex } from "node:stream"; +import { + RunnerConnection, + RunnerUnavailable, +} from "@dispatch/runner-protocol/connection"; +export { + RunnerUnavailable, + RunnerHostGone, +} from "@dispatch/runner-protocol/connection"; import type { Pool } from "pg"; import { parseRunnerHealth, type RunnerHealth, - hostChannel, + parseReadyFrame, + type ConnectCreated, + type ConnectPoll, + type ServiceFrame, + type RunnerFrame, + type EnrollmentRequest, + type EnrollmentReply, MANAGED_WORKSPACE, wireFrames, parseEngineInventory, type Command, type EngineInventoryEntry, - type Frame, type Placement, } from "./protocol.js"; import { @@ -24,8 +36,6 @@ import { formatHost, pairingCommand, validRunnerName, - validWorkspaceId, - type EnrollFrame, } from "./enrollment.js"; import { ConnectRequestInvalid, @@ -87,7 +97,6 @@ export type RunnerSummary = { managedWorkspace?: true; }; -export class RunnerUnavailable extends Error {} export class RunnerRevoked extends RunnerUnavailable { static readonly reason = "The runner registration was revoked. Dispatch no longer has access to this session."; @@ -95,7 +104,6 @@ export class RunnerRevoked extends RunnerUnavailable { super(RunnerRevoked.reason); } } -export class RunnerHostGone extends Error {} export class RunnerRequestError extends Error { constructor( readonly status: number, @@ -114,11 +122,9 @@ type Gate = { ready?(workspaces: string[], managedWorkspace: boolean): void; }; -type Settle = (frame?: Extract) => void; - type Peer = { socket: TLSSocket; - send: (frame: Frame) => void; + connection: RunnerConnection; workspaces: Set; managedWorkspace: boolean; gate: Gate; @@ -128,8 +134,6 @@ type Peer = { engineManagement: boolean; /** Last pushed, validated engine inventory; absent until the runner first reports one. */ engines?: EngineInventoryEntry[]; - pending: Map; - channels: Map; }; const MAX_UNAUTHENTICATED = 64; @@ -615,45 +619,32 @@ export class RemoteRunnerService { clearTimeout(deadline); if (!peer) return; if (this.peers.get(gate.key) === peer) this.peers.delete(gate.key); - for (const settle of peer.pending.values()) settle(); - for (const channel of peer.channels.values()) channel.push(null); + peer.connection.close(); if (gate.registrationId) void this.enrollment?.registry .seen(gate.registrationId) .catch(() => {}); }); - const send = wireFrames(socket, (frame) => { + const send = wireFrames(socket, (frame) => { if (!gate.approved()) return socket.destroy(); if (!peer) { - if ( - frame.type !== "ready" || - frame.version !== 1 || - !Array.isArray(frame.workspaces) || - frame.workspaces.length > 256 || - (frame.managedWorkspace !== undefined && - (frame.managedWorkspace !== true || - frame.workspaces.length !== 1 || - frame.workspaces[0] !== MANAGED_WORKSPACE)) || - !frame.workspaces.every((workspace) => validWorkspaceId(workspace)) - ) - return socket.destroy(); + const ready = parseReadyFrame(frame); + if (!ready) return socket.destroy(); clearTimeout(deadline); peer = { socket, - reportsHealth: frame.health === true, - engineManagement: frame.engineManagement === true, - send, - workspaces: new Set(frame.workspaces), - managedWorkspace: frame.managedWorkspace === true, + reportsHealth: ready.health === true, + engineManagement: ready.engineManagement === true, + connection: new RunnerConnection(send), + workspaces: new Set(ready.workspaces), + managedWorkspace: ready.managedWorkspace === true, gate, - pending: new Map(), - channels: new Map(), }; // A reconnect replaces a half-open predecessor for the same runner. const previous = this.peers.get(gate.key); this.peers.set(gate.key, peer); previous?.socket.destroy(); - gate.ready?.(frame.workspaces, peer.managedWorkspace); + gate.ready?.(ready.workspaces, peer.managedWorkspace); if (peer.reportsHealth) { send({ type: "accept_health", @@ -691,79 +682,83 @@ export class RemoteRunnerService { const entries = parseEngineInventory(frame.entries); if (entries === null) return socket.destroy(); peer.engines = entries; - } else if (frame.type === "result") peer.pending.get(frame.id)?.(frame); - else if (frame.type === "data") - peer.channels.get(frame.id)?.push(Buffer.from(frame.data, "base64")); - else if (frame.type === "close") peer.channels.get(frame.id)?.push(null); + } else if ( + frame.type === "result" || + frame.type === "data" || + frame.type === "close" + ) + peer.connection.receive(frame); else socket.destroy(); }); } private pair(socket: TLSSocket) { let used = false; - const reply = (frame: EnrollFrame) => { + const reply = (frame: EnrollmentReply) => { try { - send(frame as unknown as Frame); + send(frame); } catch { /* closed */ } socket.end(); }; - const send = wireFrames(socket, (frame) => { - if (used) return socket.destroy(); - used = true; - const request = frame as unknown as EnrollFrame; - // Public bootstrap: the CA certificate, which runners check against - // the fingerprint pinned in their pairing command. - if (request.type === "ca_request" && request.version === 1) - return reply({ - type: "ca", - ca: this.authority?.caPem ?? "", - }); - if ( - request.type !== "enroll" || - request.version !== 1 || - typeof request.code !== "string" || - request.code.length > 128 || - typeof request.publicKey !== "string" || - request.publicKey.length > 8192 - ) - return reply({ - type: "enroll_error", - error: "Invalid pairing request.", - }); - this.enrollment!.registry.redeem(request.code, request.publicKey).then( - ({ registration, cert, ca, previousFingerprint }) => { - // A re-key retires the old certificate and its live connection. - if (previousFingerprint) { - this.enrolled.delete(previousFingerprint); - this.peers.get(registration.id)?.socket.destroy(); - } - this.enrolled.set(registration.fingerprint!, registration); - reply({ - type: "enrolled", - id: registration.id, - name: registration.name, - cert, - ca, + const send = wireFrames( + socket, + (request) => { + if (used) return socket.destroy(); + used = true; + // Public bootstrap: the CA certificate, which runners check against + // the fingerprint pinned in their pairing command. + if (request.type === "ca_request" && request.version === 1) + return reply({ + type: "ca", + ca: this.authority?.caPem ?? "", }); - }, - (error) => { - // Slow down code guessing; codes carry 160 bits regardless. - setTimeout( - () => - reply({ - type: "enroll_error", - error: - error instanceof PairingRejected - ? error.message - : "Pairing failed.", - }), - 500 - ); - } - ); - }); + if ( + request.type !== "enroll" || + request.version !== 1 || + typeof request.code !== "string" || + request.code.length > 128 || + typeof request.publicKey !== "string" || + request.publicKey.length > 8192 + ) + return reply({ + type: "enroll_error", + error: "Invalid pairing request.", + }); + this.enrollment!.registry.redeem(request.code, request.publicKey).then( + ({ registration, cert, ca, previousFingerprint }) => { + // A re-key retires the old certificate and its live connection. + if (previousFingerprint) { + this.enrolled.delete(previousFingerprint); + this.peers.get(registration.id)?.socket.destroy(); + } + this.enrolled.set(registration.fingerprint!, registration); + reply({ + type: "enrolled", + id: registration.id, + name: registration.name, + cert, + ca, + }); + }, + (error) => { + // Slow down code guessing; codes carry 160 bits regardless. + setTimeout( + () => + reply({ + type: "enroll_error", + error: + error instanceof PairingRejected + ? error.message + : "Pairing failed.", + }), + 500 + ); + } + ); + } + ); } /** @@ -1030,7 +1025,7 @@ export class RemoteRunnerService { * Reached either directly or, for a runner that only has the listener's * own pinned CA (see `connectCommand`), proxied through it like `/ping`. */ - async createConnectRequest(publicKey: unknown) { + async createConnectRequest(publicKey: unknown): Promise { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); if (typeof publicKey !== "string" || publicKey.length === 0) @@ -1052,7 +1047,7 @@ export class RemoteRunnerService { } /** `GET /api/runners/connect/:id`: the runner's own unauthenticated poll. */ - async pollConnectRequest(id: string) { + async pollConnectRequest(id: string): Promise { if (!this.enrollment) throw new RunnerRequestError(409, "Runner enrollment is disabled."); const request = await this.enrollment.registry.pollConnectRequest(id); @@ -1203,51 +1198,7 @@ export class RemoteRunnerService { "The enrolled runner is disconnected or the workspace is unavailable." ); } - const id = crypto.randomUUID(); - const channel = open - ? hostChannel(id, peer.send, () => peer.channels.delete(id)) - : undefined; - // The HostClient takes over error handling after the attach acknowledgement. - channel?.on("error", () => {}); - if (channel) peer.channels.set(id, channel); - try { - const value = await new Promise( - (resolve, reject) => { - const finish: Settle = (frame) => { - clearTimeout(timer); - peer.pending.delete(id); - if (!frame) - reject( - new RunnerUnavailable( - "Runner acknowledgement was lost; execution is unknown." - ) - ); - else if (frame.code === "host-gone") - reject(new RunnerHostGone(frame.error)); - else if (frame.error) reject(new Error(frame.error)); - else resolve(frame.value); - }; - const timer = setTimeout( - () => finish(), - // Repository fetches and engine package installs may take minutes. - command.kind === "engine" || - (command.kind === "launch" && command.launch.repository) - ? 300_000 - : 20_000 - ); - peer.pending.set(id, finish); - try { - peer.send({ type: "request", id, command }); - } catch { - finish(); - } - } - ); - return { value, channel }; - } catch (error) { - channel?.destroy(); - throw error; - } + return peer.connection.request(command, { openChannel: open }); } close() { diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index 67880bb31..0dd1493da 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -19,7 +19,12 @@ import { issueServer, runnerPublicKey, } from "../src/agents/remote/x509.js"; -import { wireFrames, type Frame } from "../src/agents/remote/protocol.js"; +import { + wireFrames, + type Frame, + type EnrollmentRequest, + type EnrollmentReply, +} from "../src/agents/remote/protocol.js"; import { runTestMigrations, setupTestDb, teardownTestDb } from "./db/setup.js"; const HOST = "127.0.0.1"; @@ -409,8 +414,8 @@ describe("pinned connect bootstrap", () => { const received: unknown[] = []; const server = connectServer(leaf, rogue, (frame, send, socket) => { received.push(frame); - if ((frame as { type?: string }).type === "ca_request") { - send({ type: "ca", ca: real.cert } as never); + if (frame.type === "ca_request") { + send({ type: "ca", ca: real.cert }); socket.end(); } else socket.destroy(); }); @@ -445,8 +450,8 @@ function connectServer( leaf: { cert: string; key: string }, ca: { cert: string }, onFrame: ( - frame: unknown, - send: (frame: unknown) => void, + frame: EnrollmentRequest, + send: (frame: EnrollmentReply) => void, socket: TLSSocket ) => void ) { @@ -454,8 +459,9 @@ function connectServer( { cert: leaf.cert + ca.cert, key: leaf.key }, (socket: TLSSocket) => { socket.on("error", () => {}); - const send = wireFrames(socket, (frame) => - onFrame(frame, send as never, socket) + const send = wireFrames( + socket, + (frame) => onFrame(frame, send, socket) ); } ); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 28bf40c71..fd61d30e3 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -6,7 +6,12 @@ import { connect, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { exchangeCode } from "../src/agents/remote/enrollment.js"; -import { wireFrames, type Frame } from "../src/agents/remote/protocol.js"; +import { + wireFrames, + type Frame, + type EnrollmentRequest, + type EnrollmentReply, +} from "../src/agents/remote/protocol.js"; import { RunnerRegistry } from "../src/agents/remote/registry.js"; import { advertisedHost, @@ -778,11 +783,14 @@ describe("pinned pairing bootstrap", () => { { cert: leaf.cert + rogue.cert, key: leaf.key }, (socket) => { socket.on("error", () => {}); - const send = wireFrames(socket, (frame) => { - received.push(frame); - send({ type: "ca", ca: real.cert } as never); - socket.end(); - }); + const send = wireFrames( + socket, + (frame) => { + received.push(frame); + send({ type: "ca", ca: real.cert }); + socket.end(); + } + ); } ); await new Promise((resolve) => server.listen(0, HOST, resolve)); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index b1ba321ca..d37d2de81 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -1,12 +1,20 @@ import { Duplex } from "node:stream"; import { type Frame, + type ServiceFrame, + type Command, + parseReadyFrame, isOpaqueId, remotePlacement, workspaceLocator, } from "@dispatch/runner-protocol"; import { hostChannel, wireFrames } from "@dispatch/runner-protocol/node"; -import { expect, it } from "vitest"; +import { + RunnerConnection, + RunnerHostGone, + RunnerUnavailable, +} from "@dispatch/runner-protocol/connection"; +import { expect, it, vi } from "vitest"; it("round-trips opaque locator components without URL normalization", () => { const placement = { runner: "Runner/β", workspace: "../repo?x=%2F#main" }; @@ -75,3 +83,86 @@ it("consumes the v1 launch and channel framing without Dispatch server imports", ]); transport.destroy(); }); + +it("negotiates advertised v1 capabilities independently on each ready frame", () => { + const ready = { type: "ready", version: 1, workspaces: ["proof"] }; + expect(parseReadyFrame({ ...ready, futureExtension: true })).toEqual(ready); + expect(parseReadyFrame({ ...ready, health: "yes" })).toEqual(ready); + expect(parseReadyFrame({ ...ready, version: 2 })).toBeNull(); + expect(parseReadyFrame({ ...ready, workspaces: [""] })).toBeNull(); + expect(parseReadyFrame({ ...ready, managedWorkspace: true })).toBeNull(); + const managed = { + ...ready, + managedWorkspace: true, + workspaces: ["@session"], + health: true, + engineManagement: true, + }; + expect(parseReadyFrame(managed)).toEqual(managed); +}); + +function peer() { + const sent: ServiceFrame[] = []; + const connection = new RunnerConnection((frame) => sent.push(frame)); + return { connection, sent }; +} +const attach: Command = { + kind: "attach", + agentId: "session-A", + workspace: "shared", +}; +function requestId(frame: ServiceFrame | undefined) { + if (frame?.type !== "request") throw new Error("Expected a service request"); + return frame.id; +} + +it("correlates out-of-order replies and buffers channel bytes before the attach receipt", async () => { + const { connection, sent } = peer(); + const attached = connection.request(attach, { openChannel: true }); + const alive = connection.request({ ...attach, kind: "alive" }); + const id = requestId(sent[0]); + connection.receive({ type: "result", id: requestId(sent[1]), value: false }); + expect((await alive).value).toBe(false); + connection.receive({ type: "data", id, data: "AP8=" }); + connection.receive({ type: "result", id, value: true }); + const { channel } = await attached; + expect(channel!.read()).toEqual(Buffer.from([0, 255])); + connection.receive({ type: "close", id }); + for await (const _chunk of channel!) + throw new Error("Unexpected extra channel data"); + expect(channel!.destroyed).toBe(true); +}); + +it("disconnect settles only its own requests and a missing host has a distinct result", async () => { + const alpha = peer(); + const beta = peer(); + const lost = alpha.connection.request(attach); + const pending = beta.connection.request(attach); + alpha.connection.close(); + await expect(lost).rejects.toThrow(/acknowledgement was lost/); + await expect(alpha.connection.request(attach)).rejects.toBeInstanceOf( + RunnerUnavailable + ); + beta.connection.receive({ + type: "result", + id: requestId(beta.sent[0]), + code: "host-gone", + }); + await expect(pending).rejects.toBeInstanceOf(RunnerHostGone); +}); + +it("a timed-out request has an unknown outcome even if its receipt arrives late", async () => { + vi.useFakeTimers(); + try { + const { connection, sent } = peer(); + const lost = expect(connection.request(attach)).rejects.toThrow( + /execution is unknown/ + ); + await vi.advanceTimersByTimeAsync(20_000); + await lost; + connection.receive({ type: "result", id: requestId(sent[0]), value: true }); + expect(sent).toHaveLength(1); + } finally { + vi.useRealTimers(); + } +}); diff --git a/package.json b/package.json index 38e92b3d3..baf6c918a 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "ci": "node --test scripts/playwright-policy.test.mjs && pnpm run format && pnpm run check && pnpm run lint:web && pnpm run build && pnpm run test && pnpm run test:e2e", "coverage": "pnpm --filter @dispatch/server test:coverage && pnpm --filter @dispatch/web test:coverage", "test": "pnpm --filter @dispatch/server test && pnpm --filter @dispatch/web test && pnpm --filter @dispatch/browser-extension test", + "test:runner-protocol": "pnpm --filter @dispatch/server exec vitest run test/runner-protocol-consumer.test.ts", "test:watch": "pnpm --filter @dispatch/server test:watch", "test:e2e": "bash scripts/e2e-isolated.sh", "test:e2e:remote-runners": "bash scripts/e2e-remote-runners.sh", diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 0e745a79e..ed5cda3a2 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -6,6 +6,47 @@ the package. The separate `@dispatch/runner-protocol/node` entry point provides NDJSON framing and a `Duplex` channel for Node-compatible runtimes. The package ships TypeScript source for Bun or a TypeScript-aware bundler. +## Implementing a service or runner + +| Boundary | Initiator | Responsibility | Contract | +| ---------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- | +| Enrollment | Runner | Ask the service for a code, poll for approval, and verify the issued certificate before persisting credentials. | `enrollment.ts` defines HTTP responses and private-CA bootstrap frames. | +| Execution | Runner advertises, service requests | Bind each authenticated connection to a registration. Validate the first `ready` with `parseReadyFrame`. Send commands for advertised workspaces and capabilities. | `execution.ts` defines `ServiceFrame`, `RunnerFrame`, and `Command`. | +| Session | Service attaches to a host | Exchange hello/welcome, replay journal entries, and deliver prompts inside the attached byte stream. | `session.ts` defines journal positions and receipts. See **Receipts and replay** below. | + +For a Node-compatible service, create one `RunnerConnection` from +`@dispatch/runner-protocol/connection` per authenticated, ready peer. Its +constructor takes a frame sender. Route incoming `result`, `data`, and +`close` to `receive`. Call `close()` when the transport disconnects and +create a fresh connection when the runner returns. Call +`request(command, { openChannel: true })` to buffer channel data from the +moment an attach or engine operation is sent. Dispatch owns the registration +lookup, authorization, dashboard state, and durable journal storage. + +To extend v1, define the message in its sending direction and document its +receipt or failure semantics. For an optional operation, advertise support in +`ready` and exercise both a capable peer and a peer that omits the flag. +`wireFrames` handles NDJSON and buffering. Its directional TypeScript types +describe the expected messages; the recipient validates incoming values. + +Run the in-memory consumer tests from the repository root with +`pnpm run test:runner-protocol`. +They use the package's public exports and require no database, TLS certificates, +agent process, or running Dispatch instance. + +For changes beyond the portable contract, the implementation tests in +`apps/server/test/` exercise different boundaries: + +| Change | Test fixture | +| -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| Pair, approve, rotate or revoke | `remote-runner-connect` and `remote-runner-enrollment` use a test registry and local TLS peers. | +| Start a workload, allocate a session or check out a repository | `remote-runner-startup`, `remote-session-storage` and `runner-repositories` cover host configuration and filesystem behavior. | +| Record and recover received events | `remote-event-inbox` exercises the durable cursor and payload together. | +| Report health or manage an engine | `runner-health`, `engine-manager` and `engine-runner-executor` exercise sampling, routing and workload execution. | + +For a change that crosses these boundaries, `pnpm run test:e2e:remote-runners` +runs the browser workflow with isolated Linux runners and deterministic engines. + ## Identity and transport Runner registration is a service-side identity bound to its authenticated @@ -57,6 +98,32 @@ ACP session with an empty service MCP list. v1 launches with the original binaries require that shape, so keep sending it when interoperating with those binaries. +## Commands and results + +| Command | Successful `result.value` | Channel | +| --------- | ----------------------------------------------------- | ---------------------------------------------------------------------- | +| `launch` | `true` after spawning the host | None | +| `attach` | `true` after connecting to the host | Bidirectional host protocol until close | +| `alive` | Boolean indicating host presence | None | +| `stop` | `true` after stopping the host | None | +| `discard` | `true` after retiring session state | None | +| `log` | A short guest host diagnostic string | None | +| `repo` | Standard output of the workspace's configured command | None | +| `engine` | JSON-encoded `EngineOperationAck` | Newline-delimited `EngineOperationEvent` records in base64 data frames | + +An agent command addresses its bound workspace. Engine management is +runner-wide. Its v1 envelope still carries an advertised workspace and an +agent ID placeholder. Gate it on the runner's `engineManagement` capability. + +An execution error uses `result.error`. An attach to a known missing host +also sets `result.code` to `host-gone`. Losing the connection before the +result leaves the outcome unknown. The service can reattach using the +durable cursor described below. + +The portable session types cover journal replay and prompt receipts. The +complete vocabulary spoken by Dispatch's ACP host, including permission +decisions, is in `apps/server/src/agents/acp/host-protocol.ts`. + ## Receipts and replay | Signal | Meaning | diff --git a/packages/runner-protocol/package.json b/packages/runner-protocol/package.json index 4276e85eb..9eb59a0fa 100644 --- a/packages/runner-protocol/package.json +++ b/packages/runner-protocol/package.json @@ -5,6 +5,7 @@ "type": "module", "exports": { ".": "./src/index.ts", + "./connection": "./src/connection.ts", "./node": "./src/node.ts", "./engine-management": "./src/engine-management.ts" }, diff --git a/packages/runner-protocol/src/connection.ts b/packages/runner-protocol/src/connection.ts new file mode 100644 index 000000000..35ddfad4c --- /dev/null +++ b/packages/runner-protocol/src/connection.ts @@ -0,0 +1,95 @@ +import type { Duplex } from "node:stream"; +import type { + ChannelFrame, + Command, + ResultFrame, + ServiceFrame, +} from "./index.js"; +import { hostChannel } from "./node.js"; + +export class RunnerUnavailable extends Error {} +export class RunnerHostGone extends Error {} + +/** Service side of one authenticated runner connection. Request IDs and channels are local to it. */ +export class RunnerConnection { + private readonly pending = new Map void>(); + private readonly channels = new Map(); + private closed = false; + + constructor(private readonly send: (frame: ServiceFrame) => void) {} + + receive(frame: ChannelFrame | ResultFrame) { + switch (frame.type) { + case "result": + this.pending.get(frame.id)?.(frame); + break; + case "data": + this.channels.get(frame.id)?.push(Buffer.from(frame.data, "base64")); + break; + case "close": + this.channels.get(frame.id)?.push(null); + break; + } + } + + close() { + this.closed = true; + for (const settle of this.pending.values()) settle(); + for (const channel of this.channels.values()) channel.push(null); + this.channels.clear(); + } + + async request(command: Command, { openChannel = false } = {}) { + if (this.closed) + throw new RunnerUnavailable("The runner connection is closed."); + const id = crypto.randomUUID(); + const channel = openChannel + ? hostChannel(id, this.send, () => this.channels.delete(id)) + : undefined; + // The consumer can attach its error listener after the request resolves. + channel?.on("error", () => {}); + if (channel) this.channels.set(id, channel); + try { + const value = await this.sendRequest(id, command); + return { value, channel }; + } catch (error) { + channel?.destroy(); + throw error; + } + } + + private sendRequest( + id: string, + command: Command + ): Promise { + // Repository fetches and engine package installs can run for minutes. + const timeoutMs = + command.kind === "engine" || + (command.kind === "launch" && command.launch.repository) + ? 300_000 + : 20_000; + return new Promise((resolve, reject) => { + const finish = (frame?: ResultFrame) => { + clearTimeout(timer); + this.pending.delete(id); + if (!frame) + reject( + new RunnerUnavailable( + "Runner acknowledgement was lost; execution is unknown." + ) + ); + else if (frame.code === "host-gone") + reject(new RunnerHostGone(frame.error)); + else if (frame.error) reject(new Error(frame.error)); + else resolve(frame.value); + }; + const timer = setTimeout(finish, timeoutMs); + this.pending.set(id, finish); + try { + this.send({ type: "request", id, command }); + } catch { + finish(); + } + }); + } +} diff --git a/packages/runner-protocol/src/enrollment.ts b/packages/runner-protocol/src/enrollment.ts new file mode 100644 index 000000000..f544b2f91 --- /dev/null +++ b/packages/runner-protocol/src/enrollment.ts @@ -0,0 +1,30 @@ +/** Public bootstrap messages on the runner TLS listener, before agent traffic. */ +export type EnrollmentRequest = + | { type: "ca_request"; version: 1 } + | { type: "enroll"; version: 1; code: string; publicKey: string }; + +export type EnrollmentReply = + | { type: "ca"; ca: string } + | { type: "enrolled"; id: string; name: string; cert: string; ca: string } + | { type: "enroll_error"; error: string }; + +/** Responses from the service's HTTPS connection-request and polling routes. */ +export type ConnectCreated = { + id: string; + code: string; + expiresAt: string; + /** Optional link for the operator who approves the request. */ + approveUrl?: string; +}; +export type ConnectPoll = + | { status: "pending" } + | { + status: "approved"; + id: string; + name: string; + endpoint: string; + cert: string; + ca: string; + } + | { status: "denied" } + | { status: "expired" }; diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts new file mode 100644 index 000000000..7cc3b76a2 --- /dev/null +++ b/packages/runner-protocol/src/execution.ts @@ -0,0 +1,114 @@ +import { MANAGED_WORKSPACE, isOpaqueId } from "./placement.js"; +import type { + EngineInventoryEntry, + EngineOperation, +} from "./engine-management.js"; +import type { RunnerHealth } from "./health.js"; + +export const RUNNER_WIRE_VERSION = 1; + +export type RunnerEngine = "claude" | "codex" | "opencode"; + +export type ServiceMcp = { + url: string; + token: string; + /** Legacy launchers omit the name and use "dispatch". */ + name?: string; +}; + +export type RepositoryCheckout = + | { kind: "new"; branch: string; base?: string } + | { kind: "branch"; branch: string } + | { kind: "pr"; branch: string; number: number }; + +export type RunnerRepository = { url: string; checkout: RepositoryCheckout }; + +/** The guest supplies all machine-local execution settings. */ +export type RemoteLaunch = { + agentId: string; + engine: RunnerEngine; + fullAccess?: boolean; + model: string | null; + effort?: string | null; + systemPrompt: string | null; + personaContext?: string | null; + mcp?: ServiceMcp; + resumeSessionId: string | null; + repository?: RunnerRepository; +}; + +export type Command = { agentId: string; workspace: string } & ( + | { kind: "launch"; launch: RemoteLaunch } + | { kind: "attach" | "alive" | "discard" | "log" | "repo" } + | { kind: "stop"; force: boolean } + /** + * Runner-wide engine install/update/sign-in — not bound to any agent or + * workspace binding; the runner answers it before any agent-binding + * checks. `workspace` only needs to name one of the runner's online + * workspaces, for routing. A runner that predates this never answers it, + * so the reply handler (service.ts, RunnerEngineTransport) treats a lost + * acknowledgement or error as `unsupported`. + */ + | { kind: "engine"; operation: EngineOperation } +); +export type ReadyFrame = { + type: "ready"; + version: typeof RUNNER_WIRE_VERSION; + workspaces: string[]; + health?: true; + managedWorkspace?: true; + /** Advertises support for the `"engine"` command and inventory push. */ + engineManagement?: true; +}; + +/** Accept v1 extension fields and enable optional features only when explicitly true. */ +export function parseReadyFrame(value: unknown): ReadyFrame | null { + if (!value || typeof value !== "object") return null; + const frame = value as Record; + if ( + frame.type !== "ready" || + frame.version !== RUNNER_WIRE_VERSION || + !Array.isArray(frame.workspaces) || + frame.workspaces.length > 256 || + !frame.workspaces.every(isOpaqueId) || + (frame.managedWorkspace !== undefined && + (frame.managedWorkspace !== true || + frame.workspaces.length !== 1 || + frame.workspaces[0] !== MANAGED_WORKSPACE)) + ) + return null; + return { + type: "ready", + version: RUNNER_WIRE_VERSION, + workspaces: frame.workspaces, + ...(frame.health === true && { health: true }), + ...(frame.engineManagement === true && { engineManagement: true }), + ...(frame.managedWorkspace === true && { managedWorkspace: true }), + }; +} + +export type ChannelFrame = + | { type: "data"; id: string; data: string } + | { type: "close"; id: string }; + +export type ServiceFrame = + | { type: "accept_health"; engineInventory?: true } + | { type: "request"; id: string; command: Command } + | ChannelFrame; + +export type ResultFrame = { + type: "result"; + id: string; + value?: boolean | string; + error?: string; + code?: "host-gone"; +}; + +export type RunnerFrame = + | ReadyFrame + | { type: "health"; sample: RunnerHealth } + | { type: "engine_inventory"; entries: EngineInventoryEntry[] } + | ResultFrame + | ChannelFrame; + +export type Frame = ServiceFrame | RunnerFrame; diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index 8f14784df..3b1757685 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -1,167 +1,5 @@ -import type { RunnerHealth } from "./health.js"; -export { type RunnerHealth, parseRunnerHealth } from "./health.js"; -import type { - EngineInventoryEntry, - EngineOperation, -} from "./engine-management.js"; -export const MANAGED_WORKSPACE = "@session"; - -export type Placement = { runner: string; workspace: string }; - -/** Wire identities are case-sensitive and are not paths. */ -export function isOpaqueId(value: unknown): value is string { - if ( - typeof value !== "string" || - value.length === 0 || - value.length > 128 || - /[\x00-\x1f\x7f-\x9f]/u.test(value) - ) { - return false; - } - try { - // Reject lone UTF-16 surrogates, which have no UTF-8 representation. - encodeURIComponent(value); - return true; - } catch { - return false; - } -} - -/** Split first and decode each component exactly once. URL parsers can normalize IDs. */ -export function remotePlacement(cwd: string): Placement | null { - const match = /^runner:\/\/([\w.!~*'()%+-]+)\/([\w.!~*'()%+@-]+)$/.exec(cwd); - if (!match || match[0] !== cwd) return null; - try { - const runner = decodeURIComponent(match[1]!); - const workspace = decodeURIComponent(match[2]!); - return isOpaqueId(runner) && isOpaqueId(workspace) - ? { runner, workspace } - : null; - } catch { - return null; - } -} - -export function workspaceLocator({ runner, workspace }: Placement): string { - if (!isOpaqueId(runner) || !isOpaqueId(workspace)) { - throw new Error("Invalid runner or workspace ID"); - } - return `runner://${encodeURIComponent(runner)}/${workspace === MANAGED_WORKSPACE ? workspace : encodeURIComponent(workspace)}`; -} - -export const RUNNER_WIRE_VERSION = 1; - -export type RunnerEngine = "claude" | "codex" | "opencode"; - -export type ServiceMcp = { - url: string; - token: string; - /** Legacy launchers omit the name and use "dispatch". */ - name?: string; -}; - -export type RepositoryCheckout = - | { kind: "new"; branch: string; base?: string } - | { kind: "branch"; branch: string } - | { kind: "pr"; branch: string; number: number }; - -export type RunnerRepository = { url: string; checkout: RepositoryCheckout }; - -/** The guest supplies all machine-local execution settings. */ -export type RemoteLaunch = { - agentId: string; - engine: RunnerEngine; - fullAccess?: boolean; - model: string | null; - effort?: string | null; - systemPrompt: string | null; - personaContext?: string | null; - mcp?: ServiceMcp; - resumeSessionId: string | null; - repository?: RunnerRepository; -}; - -export type Command = { agentId: string; workspace: string } & ( - | { kind: "launch"; launch: RemoteLaunch } - | { kind: "attach" | "alive" | "discard" | "log" | "repo" } - | { kind: "stop"; force: boolean } - /** - * Runner-wide engine install/update/sign-in — not bound to any agent or - * workspace binding; the runner answers it before any agent-binding - * checks. `workspace` only needs to name one of the runner's online - * workspaces, for routing. A runner that predates this never answers it, - * so the reply handler (service.ts, RunnerEngineTransport) treats a lost - * acknowledgement or error as `unsupported`. - */ - | { kind: "engine"; operation: EngineOperation } -); -export type Frame = - | { - type: "ready"; - version: typeof RUNNER_WIRE_VERSION; - workspaces: string[]; - health?: true; - managedWorkspace?: true; - /** Advertises support for the `"engine"` command and inventory push. */ - engineManagement?: true; - } - | { type: "accept_health"; engineInventory?: true } - | { type: "health"; sample: RunnerHealth } - /** Runner-pushed, same cadence as health; see parseEngineInventory. */ - | { type: "engine_inventory"; entries: EngineInventoryEntry[] } - | { type: "request"; id: string; command: Command } - | { - type: "result"; - id: string; - value?: boolean | string; - error?: string; - code?: "host-gone"; - } - | { type: "data"; id: string; data: string } - | { type: "close"; id: string }; - -/** The last contiguous position durably received in the named host journal. */ -export type ReplayHello = { - type: "hello"; - fromSeq: number; - journalId?: string | null; - replayComplete?: boolean; -}; - -export type HostWelcome = { - type: "welcome"; - agentId: string; - engine: RunnerEngine; - sessionId: string; - resumed: boolean; - running: boolean; - journalSeq: number; - journalId?: string; -}; - -export type JournalEntry = { - seq: number; - at: string; - event: Event; - /** Absent on entries written by older hosts. */ - journalId?: string; -}; - -export type HostEvent = { - type: "event"; -} & JournalEntry; -export type ReplayComplete = { type: "replay_complete" }; - -export type HostPrompt = { - type: "prompt"; - id: string; - text: string; - journalId?: string; - source?: Source; - images?: Image[]; -}; - -export type PromptReceipt = - | { type: "prompt_accepted"; id: string } - /** An engine-initiated turn is open and the host did not submit this prompt. */ - | { type: "prompt_deferred"; id: string }; +export * from "./placement.js"; +export * from "./enrollment.js"; +export * from "./execution.js"; +export * from "./session.js"; +export * from "./health.js"; diff --git a/packages/runner-protocol/src/node.ts b/packages/runner-protocol/src/node.ts index f2ec198c2..d7da3c831 100644 --- a/packages/runner-protocol/src/node.ts +++ b/packages/runner-protocol/src/node.ts @@ -1,13 +1,13 @@ import { Duplex } from "node:stream"; import { StringDecoder } from "node:string_decoder"; -import type { Frame } from "./index.js"; +import type { Frame, ChannelFrame } from "./index.js"; -type Send = (frame: Frame) => void; +type Send = (frame: T) => void; -export function wireFrames( +export function wireFrames( socket: Duplex, - receive: (frame: Frame) => void -): Send { + receive: (frame: Incoming) => void +): Send { const decoder = new StringDecoder("utf8"); let pending = ""; socket.on("data", (chunk: Buffer) => { @@ -18,7 +18,7 @@ export function wireFrames( const line = pending.slice(0, newline); pending = pending.slice(newline + 1); try { - receive(JSON.parse(line) as Frame); + receive(JSON.parse(line) as Incoming); } catch { return socket.destroy(); } @@ -34,7 +34,11 @@ export function wireFrames( }; } -export function hostChannel(id: string, send: Send, dispose: () => void) { +export function hostChannel( + id: string, + send: Send, + dispose: () => void +) { return new Duplex({ allowHalfOpen: false, read() {}, diff --git a/packages/runner-protocol/src/placement.ts b/packages/runner-protocol/src/placement.ts new file mode 100644 index 000000000..6dbb5d296 --- /dev/null +++ b/packages/runner-protocol/src/placement.ts @@ -0,0 +1,44 @@ +export const MANAGED_WORKSPACE = "@session"; + +export type Placement = { runner: string; workspace: string }; + +/** Wire identities are case-sensitive and are not paths. */ +export function isOpaqueId(value: unknown): value is string { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > 128 || + /[\x00-\x1f\x7f-\x9f]/u.test(value) + ) { + return false; + } + try { + // Reject lone UTF-16 surrogates, which have no UTF-8 representation. + encodeURIComponent(value); + return true; + } catch { + return false; + } +} + +/** Split first and decode each component exactly once. URL parsers can normalize IDs. */ +export function remotePlacement(cwd: string): Placement | null { + const match = /^runner:\/\/([\w.!~*'()%+-]+)\/([\w.!~*'()%+@-]+)$/.exec(cwd); + if (!match || match[0] !== cwd) return null; + try { + const runner = decodeURIComponent(match[1]!); + const workspace = decodeURIComponent(match[2]!); + return isOpaqueId(runner) && isOpaqueId(workspace) + ? { runner, workspace } + : null; + } catch { + return null; + } +} + +export function workspaceLocator({ runner, workspace }: Placement): string { + if (!isOpaqueId(runner) || !isOpaqueId(workspace)) { + throw new Error("Invalid runner or workspace ID"); + } + return `runner://${encodeURIComponent(runner)}/${workspace === MANAGED_WORKSPACE ? workspace : encodeURIComponent(workspace)}`; +} diff --git a/packages/runner-protocol/src/session.ts b/packages/runner-protocol/src/session.ts new file mode 100644 index 000000000..9fc946718 --- /dev/null +++ b/packages/runner-protocol/src/session.ts @@ -0,0 +1,47 @@ +import type { RunnerEngine } from "./execution.js"; + +/** The last contiguous position durably received in the named host journal. */ +export type ReplayHello = { + type: "hello"; + fromSeq: number; + journalId?: string | null; + replayComplete?: boolean; +}; + +export type HostWelcome = { + type: "welcome"; + agentId: string; + engine: RunnerEngine; + sessionId: string; + resumed: boolean; + running: boolean; + journalSeq: number; + journalId?: string; +}; + +export type JournalEntry = { + seq: number; + at: string; + event: Event; + /** Absent on entries written by older hosts. */ + journalId?: string; +}; + +export type HostEvent = { + type: "event"; +} & JournalEntry; +export type ReplayComplete = { type: "replay_complete" }; + +export type HostPrompt = { + type: "prompt"; + id: string; + text: string; + journalId?: string; + source?: Source; + images?: Image[]; +}; + +export type PromptReceipt = + | { type: "prompt_accepted"; id: string } + /** An engine-initiated turn is open and the host did not submit this prompt. */ + | { type: "prompt_deferred"; id: string }; From 5f565e6a731ecf38fdc39d0aee8c759ead297b71 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:05:11 -0700 Subject: [PATCH 074/642] Address session and runner operations at their actual scope --- apps/server/src/agents/acp/runtime.ts | 28 ++++-------- apps/server/src/agents/manager.ts | 3 +- .../src/agents/remote/engine-transport.ts | 44 ++++--------------- apps/server/src/agents/remote/service.ts | 39 +++++++++++----- apps/server/test/engine-wire.test.ts | 28 +++++++++++- packages/runner-protocol/src/execution.ts | 19 ++++---- 6 files changed, 82 insertions(+), 79 deletions(-) diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 66729c5fd..4babc8949 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -825,15 +825,10 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { openSocket: async () => { await entry.events; return ( - await remoteService().request( - placement, - { - kind: "attach", - agentId, - workspace: placement.workspace, - }, - true - ) + await remoteService().requestSession(placement, { + kind: "attach", + agentId, + }) ).channel!; }, reconnectError: (error: unknown) => { @@ -936,10 +931,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const placement = await placementOf(agentId); if (placement) { const response = await remoteService() - .request(placement, { + .requestSession(placement, { kind: "log", agentId, - workspace: placement.workspace, }) .catch(() => null); return String(response?.value ?? ""); @@ -1017,10 +1011,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { placement: _placement, ...launch } = input; - await remoteService().request(placement, { + await remoteService().requestSession(placement, { kind: "launch", agentId: input.agentId, - workspace: placement.workspace, launch, }); const entry = await connect(input.agentId, LAUNCH_TIMEOUT_MS); @@ -1158,10 +1151,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const placement = await placementOf(agentId); if (placement) { try { - const { value } = await remoteService().request(placement, { + const { value } = await remoteService().requestSession(placement, { kind: "alive", agentId, - workspace: placement.workspace, }); return value === true; } catch (error) { @@ -1497,10 +1489,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { async stop(agentId, force) { const placement = await placementOf(agentId); if (placement) { - await remoteService().request(placement, { + await remoteService().requestSession(placement, { kind: "stop", agentId, - workspace: placement.workspace, force, }); const entry = live.get(agentId); @@ -1582,10 +1573,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { async discard(agentId) { const placement = await placementOf(agentId); if (placement) { - await remoteService().request(placement, { + await remoteService().requestSession(placement, { kind: "discard", agentId, - workspace: placement.workspace, }); } const entry = live.get(agentId); diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index e9ea0c7b9..004681afc 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -2529,10 +2529,9 @@ export class AgentManager { return async () => String( ( - await this.remote!.request(placement, { + await this.remote!.requestSession(placement, { kind: "repo", agentId: agent.id, - workspace: placement.workspace, }) ).value ?? "" ); diff --git a/apps/server/src/agents/remote/engine-transport.ts b/apps/server/src/agents/remote/engine-transport.ts index 72ad82dfe..45353ac92 100644 --- a/apps/server/src/agents/remote/engine-transport.ts +++ b/apps/server/src/agents/remote/engine-transport.ts @@ -1,15 +1,10 @@ import type { EngineOperationAck, EngineOperationEvent } from "./protocol.js"; -import { RunnerUnavailable, type RemoteRunnerService } from "./service.js"; +import { + RunnerCapabilityUnavailable, + type RemoteRunnerService, +} from "./service.js"; import type { RunnerEngineTransport } from "./engine-manager.js"; -/** - * `RunnerEngineTransport` backed by the live runner wire connection: sends - * an `"engine"` command through `RemoteRunnerService.request`, which opens - * a channel for progress (`data` frames, NDJSON `EngineOperationEvent` - * lines) alongside the terminal `result` frame carrying the JSON-encoded - * ack. A runner that predates engine management never answers the - * command, surfacing as `unsupported`. - */ export function remoteEngineTransport( service: RemoteRunnerService ): RunnerEngineTransport { @@ -18,32 +13,11 @@ export function remoteEngineTransport( return service.engineInventorySnapshot(runnerId); }, async send(runnerId, operation, onEvent) { - // Engine management is runner-wide, not per-workspace; the wire - // Command still needs *a* workspace for routing. A runner with only - // configured folders (no managed-session support) never advertises - // MANAGED_WORKSPACE, so pick whatever it actually advertises. - const workspace = service.anyWorkspace(runnerId); - if (!workspace) { - return { - ok: false, - error: "The runner is disconnected or unavailable.", - unsupported: true, - }; - } - const placement = { runner: runnerId, workspace }; try { - const { value, channel } = await service.request( - placement, - // Engine commands aren't bound to any agent; the id is a fixed, - // opaque placeholder the runner's "engine" branch never checks. - { - agentId: "@engine", - workspace, - kind: "engine", - operation, - }, - true - ); + const { value, channel } = await service.requestRunner(runnerId, { + kind: "engine", + operation, + }); try { let buffer = ""; let chunk: Buffer | null; @@ -80,7 +54,7 @@ export function remoteEngineTransport( return { ok: false, error: "Malformed response from the runner." }; } } catch (error) { - if (error instanceof RunnerUnavailable) { + if (error instanceof RunnerCapabilityUnavailable) { return { ok: false, error: error.message, unsupported: true }; } return { diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 2d326b61e..d9769c1d8 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -28,6 +28,8 @@ import { wireFrames, parseEngineInventory, type Command, + type RunnerOperation, + type SessionOperation, type EngineInventoryEntry, type Placement, } from "./protocol.js"; @@ -97,6 +99,8 @@ export type RunnerSummary = { managedWorkspace?: true; }; +export class RunnerCapabilityUnavailable extends Error {} + export class RunnerRevoked extends RunnerUnavailable { static readonly reason = "The runner registration was revoked. Dispatch no longer has access to this session."; @@ -1154,20 +1158,33 @@ export class RemoteRunnerService { return peer?.gate.approved() ? peer.engines : undefined; } - /** - * Any workspace this (approved, connected) peer currently advertises — - * for a runner-wide command like `"engine"` that needs *a* workspace - * for routing but has no workspace of its own. A runner with only - * configured folders and no managed-session support never advertises - * `MANAGED_WORKSPACE`, so that must never be assumed. - */ - anyWorkspace(runnerId: string): string | undefined { + requestSession(placement: Placement, operation: SessionOperation) { + return this.request( + placement, + { ...operation, workspace: placement.workspace }, + operation.kind === "attach" + ); + } + + async requestRunner(runnerId: string, operation: RunnerOperation) { const peer = this.peers.get(runnerId); - if (!peer?.gate.approved()) return undefined; + if (!peer?.gate.approved()) + throw new RunnerUnavailable("The runner is disconnected or unavailable."); + if (!peer.engineManagement) + throw new RunnerCapabilityUnavailable( + "This runner does not support engine management." + ); + + // V1 requires a routable workspace and an id even for a runner-wide operation. for (const workspace of peer.workspaces) { - if (peer.gate.allows(workspace)) return workspace; + if (peer.gate.allows(workspace)) + return this.request( + { runner: runnerId, workspace }, + { ...operation, agentId: "@engine", workspace }, + true + ); } - return undefined; + throw new RunnerUnavailable("The runner has no available workspace."); } available(placement: Placement) { diff --git a/apps/server/test/engine-wire.test.ts b/apps/server/test/engine-wire.test.ts index bbe4a6b26..e19d444d6 100644 --- a/apps/server/test/engine-wire.test.ts +++ b/apps/server/test/engine-wire.test.ts @@ -216,12 +216,36 @@ describe("engine wire integration", () => { expect(ack).toEqual({ ok: true }); }); - it("reports unsupported for an offline or non-engine-aware runner", async () => { + it("distinguishes a disconnected peer from a connected peer lacking engine management", async () => { const service = makeService(); const alpha = await enroll(service, "alpha"); const transport = remoteEngineTransport(service); const ack = await transport.send(alpha.created.id, { type: "status" }); - expect(ack).toMatchObject({ ok: false, unsupported: true }); + expect(ack).toMatchObject({ + ok: false, + error: expect.stringContaining("disconnected"), + }); + expect(ack).not.toHaveProperty("unsupported"); + let received = 0; + const { socket } = await dialEngineRunner({ + ...alpha, + workspaces: ["proof"], + engineManagement: false, + onEngine: () => { + received++; + }, + }); + sockets.push(socket); + await waitFor(() => + service.available({ runner: alpha.created.id, workspace: "proof" }) + ); + expect( + await transport.send(alpha.created.id, { type: "status" }) + ).toMatchObject({ + ok: false, + unsupported: true, + }); + expect(received).toBe(0); }); it("stores and validates a pushed engine inventory, exposed via list()", async () => { diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 7cc3b76a2..a2a3dc13b 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -37,19 +37,18 @@ export type RemoteLaunch = { repository?: RunnerRepository; }; -export type Command = { agentId: string; workspace: string } & ( +export type SessionOperation = { agentId: string } & ( | { kind: "launch"; launch: RemoteLaunch } | { kind: "attach" | "alive" | "discard" | "log" | "repo" } | { kind: "stop"; force: boolean } - /** - * Runner-wide engine install/update/sign-in — not bound to any agent or - * workspace binding; the runner answers it before any agent-binding - * checks. `workspace` only needs to name one of the runner's online - * workspaces, for routing. A runner that predates this never answers it, - * so the reply handler (service.ts, RunnerEngineTransport) treats a lost - * acknowledgement or error as `unsupported`. - */ - | { kind: "engine"; operation: EngineOperation } +); + +export type RunnerOperation = { kind: "engine"; operation: EngineOperation }; + +/** V1 uses one envelope for both scopes. Runner operations ignore the agent id. */ +export type Command = { workspace: string } & ( + | SessionOperation + | (RunnerOperation & { agentId: string }) ); export type ReadyFrame = { type: "ready"; From 8cf8c3f135d54af1bca7c56fbf28e994c37ce3e5 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:02:08 -0700 Subject: [PATCH 075/642] Validate runner commands and enrollment replies at wire boundaries --- apps/server/src/agents/acp/host-protocol.ts | 31 +-- apps/server/src/agents/acp/host/main.ts | 15 +- apps/server/src/agents/acp/prompt-source.ts | 59 +--- apps/server/src/agents/remote/enrollment.ts | 50 ++-- apps/server/src/agents/remote/repository.ts | 47 +--- apps/server/src/agents/remote/runner.ts | 14 +- apps/server/test/acp-host.test.ts | 17 ++ .../server/test/remote-runner-connect.test.ts | 43 ++- .../server/test/remote-runner-startup.test.ts | 23 +- .../test/runner-protocol-consumer.test.ts | 260 +++++++++++++++++- packages/runner-protocol/README.md | 18 +- .../runner-protocol/src/engine-management.ts | 40 ++- packages/runner-protocol/src/enrollment.ts | 47 ++++ packages/runner-protocol/src/execution.ts | 170 +++++++++++- packages/runner-protocol/src/session.ts | 196 +++++++++++++ packages/runner-protocol/src/validation.ts | 22 ++ 16 files changed, 885 insertions(+), 167 deletions(-) create mode 100644 packages/runner-protocol/src/validation.ts diff --git a/apps/server/src/agents/acp/host-protocol.ts b/apps/server/src/agents/acp/host-protocol.ts index a87ab9875..ffabb32c2 100644 --- a/apps/server/src/agents/acp/host-protocol.ts +++ b/apps/server/src/agents/acp/host-protocol.ts @@ -1,17 +1,16 @@ import type { HostEvent, - HostPrompt, HostWelcome, JournalEntry as RunnerJournalEntry, PromptReceipt, RemoteLaunch, ReplayComplete, - ReplayHello, + SessionCommand, } from "@dispatch/runner-protocol"; import type { BackgroundSnapshot } from "@dispatch/shared"; import type { AgentMcpInventoryResponse } from "@dispatch/shared"; import type { AgentPermissionRequest } from "@dispatch/shared"; -import type { PromptImage, PromptSource } from "./prompt-source.js"; +import type { PromptSource } from "./prompt-source.js"; import path from "node:path"; import { StringDecoder } from "node:string_decoder"; @@ -60,24 +59,7 @@ export function hostFile( /** One journal line: an event with its position in the host's stream. */ export type JournalEntry = RunnerJournalEntry; -export type ClientMessage = - | ReplayHello - | HostPrompt - | { type: "steer"; id: string; text: string; source?: PromptSource } - | { type: "cancel" } - | { type: "interrupt"; id: string; turnSeq: number } - | { - type: "answer_permission"; - id: string; - requestId: string; - optionId: string | null; - } - /** Set one of the session's config options (model, effort, mode). */ - | { type: "set_config"; id: string; configId: string; value: string } - | { type: "shutdown"; force?: boolean } - | { type: "mcp_inventory"; id: string; sessionId: string } - | { type: "background_work"; id: string; sessionId: string } - | { type: "ping" }; +export type ClientMessage = SessionCommand; export type HostMessage = | (HostWelcome & { @@ -119,7 +101,9 @@ export type HostMessage = * function that takes each chunk and yields the complete messages in it; * a partial trailing line waits for the next chunk. */ -export function ndjsonDecoder(): (chunk: Buffer | string) => T[] { +export function ndjsonDecoder( + onMalformed?: () => void +): (chunk: Buffer | string) => T[] { let buffer = ""; const decoder = new StringDecoder("utf8"); return (chunk) => { @@ -133,7 +117,8 @@ export function ndjsonDecoder(): (chunk: Buffer | string) => T[] { try { out.push(JSON.parse(line) as T); } catch { - // A corrupt line is dropped rather than poisoning the stream. + // Keep parsing subsequent lines after a malformed message. + onMalformed?.(); } } return out; diff --git a/apps/server/src/agents/acp/host/main.ts b/apps/server/src/agents/acp/host/main.ts index 6dd607b82..05a92d924 100644 --- a/apps/server/src/agents/acp/host/main.ts +++ b/apps/server/src/agents/acp/host/main.ts @@ -1,3 +1,7 @@ +import { + parseSessionCommand, + sessionCommandId, +} from "@dispatch/runner-protocol"; import { applyLaunchEffort } from "../launch-effort.js"; import { firstPromptContext } from "../persona-context.js"; import type { PromptSource } from "../prompt-source.js"; @@ -293,9 +297,16 @@ async function main(): Promise { const server = net.createServer((socket) => { if (client && client !== socket) client.destroy(); client = socket; - const decode = ndjsonDecoder(); + const rejectCommand = (id?: string) => + send(socket, { type: "error", id, message: "Invalid host command." }); + const decode = ndjsonDecoder(() => rejectCommand()); socket.on("data", (chunk) => { - for (const message of decode(chunk)) { + for (const value of decode(chunk)) { + const message = parseSessionCommand(value); + if (!message) { + rejectCommand(sessionCommandId(value)); + continue; + } void handle(socket, message).catch((err) => { logger.warn({ err: String(err) }, "host: message handler failed"); }); diff --git a/apps/server/src/agents/acp/prompt-source.ts b/apps/server/src/agents/acp/prompt-source.ts index d53d47eff..09cf41355 100644 --- a/apps/server/src/agents/acp/prompt-source.ts +++ b/apps/server/src/agents/acp/prompt-source.ts @@ -1,58 +1,5 @@ -import type { PromptConversation } from "@dispatch/shared"; - -/** - * What a prompt sent to the harness was, for the prompt a turn entry - * renders. The wire text is an envelope Dispatch built; the feed wants the - * human-facing source behind it, not the envelope. - */ -export type PromptSource = { - /** Source discussion for batching and steering, retained through the host journal. - * User-thread turns use their validated source discussion for output at turn start. */ - conversation?: PromptConversation; - /** - * A person's post. With a conversation, a prompt steers only that - * conversation; another agent's post without one steers any open turn. - */ - userMessage?: boolean; - /** Structured answers and commands retain their dedicated delivery policy. */ - steeringExcluded?: boolean; - /** Agent-authored scheduled content, explicitly eligible for steering. */ - scheduleId?: string; - scheduleDeliveryId?: string; - /** - * The recipient is waiting on this: a review it launched, a finding - * thread it is a side of, a finding settled or reopened. It joins the - * active turn whatever conversation that turn is in, rather than - * waiting behind the very work that is waiting on it. - */ - awaited?: boolean; -} & ( - | { - source: "chat"; - /** The post that opened the turn: the first, when there were several. */ - chatMessageId: string; - /** - * Every post the turn was given, in order, when posts that queued up - * behind a turn were delivered to it together. - */ - chatMessageIds?: string[]; - /** - * The block whose thread this prompt's answer belongs in, when the - * prompt says so rather than leaving it to what the post is: a - * notice that a finding changed is answered under the finding. - * Retained when prompts from this conversation are delivered together. - */ - answerIn?: string; - } - | { source: "agent"; senderId: string; senderName: string; text: string } - | { source: "system"; text: string } - /** - * A turn the engine started on its own between prompts (a background - * task finished, a goal continued). `after` is the block that answered - * the turn before it: this is source context; new ordinary work uses the agent home. - */ - | { source: "engine"; text: string; after?: string } -); +import type { PromptImage, PromptSource } from "@dispatch/runner-protocol"; +export type { PromptImage, PromptSource } from "@dispatch/runner-protocol"; const SYSTEM_MAX = 500; @@ -69,8 +16,6 @@ export type QueuedPrompt = { createdAt: string; }; -/** Server-resolved files, kept out of turn journals and encoded only for ACP. */ -export type PromptImage = { path: string; mimeType: string }; export type PromptOptions = { alone?: boolean; /** Checked immediately before submission, including queued release. */ diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index 02abe20a1..eea1b1e73 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -7,7 +7,8 @@ import path from "node:path"; import { connect, type TLSSocket } from "node:tls"; import { wireFrames, - type ConnectCreated, + parseConnectCreated, + parseConnectPoll, type ConnectPoll, type EnrollmentRequest, type EnrollmentReply, @@ -544,11 +545,14 @@ async function requestJson( new Error("The service sent an unreadable response.") ); } - if ((response.statusCode ?? 0) >= 400) { + const status = response.statusCode ?? 0; + if (status < 200 || status >= 300) { + const error = (parsed as { error?: unknown } | null)?.error; return finish( new Error( - (parsed as { error?: string } | undefined)?.error ?? - `The service returned ${response.statusCode}.` + typeof error === "string" + ? error + : `The service returned ${status}.` ) ); } @@ -573,8 +577,6 @@ function verifyIssuedConnectCredentials( publicKey: string, pin: string | undefined ) { - if (new URL(polled.endpoint).protocol !== "https:") - throw new Error("The service returned a non-HTTPS runner endpoint."); const issuedCa = new X509Certificate(polled.ca); const cert = new X509Certificate(polled.cert); if ( @@ -600,13 +602,17 @@ function verifyIssuedConnectCredentials( export async function runRunnerConnect(argv: string[]) { const options = parseConnectArgs(argv); const { key, publicKey } = generateRunnerKey(); - const created = (await requestJson( - options.service, - "POST", - "/api/runners/connect", - { publicKey }, - { pin: options.pin, timeoutMs: options.timeoutMs } - )) as ConnectCreated; + const created = parseConnectCreated( + await requestJson( + options.service, + "POST", + "/api/runners/connect", + { publicKey }, + { pin: options.pin, timeoutMs: options.timeoutMs } + ) + ); + if (!created) + throw new Error("Invalid connect creation response from the service."); const approveUrl = options.approvalUrl ?? created.approveUrl; process.stdout.write( @@ -629,13 +635,17 @@ export async function runRunnerConnect(argv: string[]) { for (;;) { if (Date.now() > deadline) throw new Error("The connect request expired before it was approved."); - const polled = (await requestJson( - options.service, - "GET", - `/api/runners/connect/${created.id}`, - undefined, - { pin: options.pin, timeoutMs: options.timeoutMs } - )) as ConnectPoll; + const polled = parseConnectPoll( + await requestJson( + options.service, + "GET", + `/api/runners/connect/${encodeURIComponent(created.id)}`, + undefined, + { pin: options.pin, timeoutMs: options.timeoutMs } + ) + ); + if (!polled) + throw new Error("Invalid connect polling response from the service."); if (polled.status === "denied") throw new Error("The connect request was denied."); if (polled.status === "expired") diff --git a/apps/server/src/agents/remote/repository.ts b/apps/server/src/agents/remote/repository.ts index 5c8020af2..8d85bcccd 100644 --- a/apps/server/src/agents/remote/repository.ts +++ b/apps/server/src/agents/remote/repository.ts @@ -1,6 +1,11 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import type { RepositoryCheckout } from "./protocol.js"; +import { + parseRunnerRepositoryUrl, + validBranch, + type RepositoryCheckout, +} from "./protocol.js"; +export { validBranch }; export type RepositoryInput = { url?: string; checkout: RepositoryCheckout }; @@ -12,49 +17,13 @@ export function repositoryUrl(input: string, fromOrigin = false): string { } const invalid = () => new Error("Runner repositories require a credential-free HTTPS Git URL."); - if ( - !source.startsWith("https://") || - source.length > 2048 || - /[\s\\?#\x00-\x1f\x7f]/.test(source) - ) - throw invalid(); - let url: URL; - try { - url = new URL(source); - } catch { - throw invalid(); - } - if ( - !url.hostname || - url.pathname === "/" || - url.hash || - url.search || - (!fromOrigin && (url.username || url.password)) - ) - throw invalid(); + const url = parseRunnerRepositoryUrl(source, fromOrigin); + if (!url) throw invalid(); url.username = ""; url.password = ""; return url.href; } -/** A full branch name, never a revision expression, option, or raw ref. */ -export function validBranch(value: unknown): value is string { - return ( - typeof value === "string" && - value.length > 0 && - value.length <= 200 && - !value.startsWith("-") && - !value.startsWith("refs/") && - !value.endsWith(".") && - value !== "HEAD" && - value !== "@" && - !/[\x00-\x20\x7f~^:?*\[\\]|\.\.|@\{/.test(value) && - value - .split("/") - .every((part) => part && !part.startsWith(".") && !part.endsWith(".lock")) - ); -} - export function parseRepository(input: unknown): RepositoryInput { if (!input || typeof input !== "object" || !("checkout" in input)) throw new Error("A runner repository requires a checkout."); diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 4e9aa2c56..7a28ef29a 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -38,9 +38,10 @@ import { MANAGED_WORKSPACE, RUNNER_WIRE_VERSION, wireFrames, + parseServiceFrame, + runnerRequestId, type Command, type RunnerFrame, - type ServiceFrame, type RunnerEngine, type RunnerRepository, } from "./protocol.js"; @@ -678,7 +679,16 @@ export async function runRemoteRunner(filename: string) { } } - const send = wireFrames(socket, (frame) => { + const send = wireFrames(socket, (value) => { + if (socket.destroyed) return; + const frame = parseServiceFrame(value); + if (!frame) { + const id = runnerRequestId(value); + if (id !== undefined) + safeSend({ type: "result", id, error: "Invalid runner command." }); + else socket.destroy(); + return; + } if (frame.type === "accept_health" && !healthInterval) { acceptsInventory = frame.engineInventory === true; void reportHealth(); diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index 1636240ba..6eabcac2f 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -627,6 +627,23 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); const welcome = first.messages.find( (message) => message.type === "welcome" )!; + first.socket.write( + encodeMessage({ + type: "prompt", + id: "malformed-operation", + text: "proof-count", + journalId: welcome.journalId, + images: [{ path: true, mimeType: "image/png" }], + }) + ); + await until(() => + first.messages.some( + (message) => + message.type === "error" && + message.id === "malformed-operation" && + message.message === "Invalid host command." + ) + ); const command = { type: "prompt", id: "first-operation", diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index 0dd1493da..7f78519b9 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -1,12 +1,20 @@ import { X509Certificate } from "node:crypto"; -import { mkdtemp, readFile } from "node:fs/promises"; +import { mkdtemp, readdir, readFile, rm } from "node:fs/promises"; import http from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import path from "node:path"; import { connect, createServer, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; -import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from "vitest"; import { connectCliCommand, runRunnerConnect, @@ -347,6 +355,37 @@ describe("runner-initiated connect enrollment", () => { ).rejects.toMatchObject({ status: 404 }); }); + it("rejects malformed creation and unknown polling replies before writing credentials", async () => { + const service = makeService(); + const { command } = await service.connectCommand(HOST); + const [, endpoint] = + /^sudo dispatch-runner connect '(https:\/\/[^']+)'$/.exec(command) ?? []; + const dir = await mkdtemp(path.join(tmpdir(), "malformed-connect-cli-")); + const create = service.createConnectRequest.bind(service); + const createReply = vi.spyOn(service, "createConnectRequest"); + const pollReply = vi.spyOn(service, "pollConnectRequest"); + try { + createReply.mockImplementationOnce(async (key) => { + const reply = await create(key); + return { ...reply, expiresAt: "invalid" }; + }); + await expect(runRunnerConnect([endpoint!, "--dir", dir])).rejects.toThrow( + "Invalid connect creation response" + ); + expect(pollReply).not.toHaveBeenCalled(); + pollReply.mockResolvedValueOnce(JSON.parse('{"status":"future-status"}')); + await expect(runRunnerConnect([endpoint!, "--dir", dir])).rejects.toThrow( + "Invalid connect polling response" + ); + expect(pollReply).toHaveBeenCalledTimes(1); + expect(await readdir(dir)).toEqual([]); + } finally { + createReply.mockRestore(); + pollReply.mockRestore(); + await rm(dir, { force: true, recursive: true }); + } + }); + it("runs the real CLI end-to-end over the runner listener's own pinned HTTPS (no main API HTTPS needed)", async () => { const service = makeService(); const { command } = await service.connectCommand(HOST); diff --git a/apps/server/test/remote-runner-startup.test.ts b/apps/server/test/remote-runner-startup.test.ts index ce45ec570..a3196b5e5 100644 --- a/apps/server/test/remote-runner-startup.test.ts +++ b/apps/server/test/remote-runner-startup.test.ts @@ -190,6 +190,25 @@ describe("remote runner startup", () => { workspaces: handles, health: true, }); + socket.emit( + "data", + Buffer.from( + JSON.stringify({ + type: "request", + id: "invalid-discard", + command: { + kind: "discard", + agentId: ["fixture"], + workspace: "@session", + }, + }) + "\n" + ) + ); + expect(JSON.parse(socket.write.mock.calls[1]![0])).toEqual({ + type: "result", + id: "invalid-discard", + error: "Invalid runner command.", + }); socket.emit( "data", Buffer.from( @@ -204,8 +223,8 @@ describe("remote runner startup", () => { }) + "\n" ) ); - await vi.waitFor(() => expect(socket.write).toHaveBeenCalledTimes(2)); - expect(JSON.parse(socket.write.mock.calls[1]![0])).toMatchObject({ + await vi.waitFor(() => expect(socket.write).toHaveBeenCalledTimes(3)); + expect(JSON.parse(socket.write.mock.calls[2]![0])).toMatchObject({ type: "result", id: "discard-test", ...(managed ? { value: true } : { error: expect.any(String) }), diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index d37d2de81..dc1cedba8 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -4,6 +4,12 @@ import { type ServiceFrame, type Command, parseReadyFrame, + parseServiceFrame, + parseSessionCommand, + parseConnectCreated, + parseConnectPoll, + runnerRequestId, + sessionCommandId, isOpaqueId, remotePlacement, workspaceLocator, @@ -50,7 +56,11 @@ it("consumes the v1 launch and channel framing without Dispatch server imports", done(); }, }); - const send = wireFrames(transport, (frame) => received.push(frame)); + const send = wireFrames(transport, (value) => { + const frame = parseServiceFrame(value); + if (!frame) throw new Error("Malformed service frame"); + received.push(frame); + }); const launch: Frame = { type: "request", id: "provider:launch/42", @@ -166,3 +176,251 @@ it("a timed-out request has an unknown outcome even if its receipt arrives late" vi.useRealTimers(); } }); + +const requestFrame = (command: object) => ({ + type: "request", + id: "caller/request:1", + command: { agentId: "caller/agent:1", workspace: "@session", ...command }, +}); + +it("accepts each v1 execution command and preserves additive launch fields", () => { + for (const kind of ["attach", "alive", "discard", "log", "repo"]) { + const request = requestFrame({ kind }); + expect(parseServiceFrame(request)).toBe(request); + } + const stop = requestFrame({ kind: "stop", force: false }); + expect(parseServiceFrame(stop)).toBe(stop); + + const launch = { + agentId: "legacy-launch-id", + engine: "claude", + model: null, + systemPrompt: "", + resumeSessionId: null, + fullAccess: false, + effort: "high", + personaContext: null, + mcp: { + url: "https://service.example/mcp", + token: "fixture", + name: "tool-service", + futureMcpField: true, + }, + }; + for (const checkout of [ + { kind: "new", branch: "topic/new", base: "main" }, + { kind: "branch", branch: "topic/existing" }, + { kind: "pr", branch: "topic/pr", number: 42 }, + ]) { + const request = { + ...requestFrame({ + kind: "launch", + launch: { + ...launch, + repository: { url: "https://git.example/project.git", checkout }, + }, + }), + futureFrameField: {}, + }; + expect(parseServiceFrame(request)).toBe(request); + } + for (const fields of [ + { fullAccess: "false" }, + { engine: "future-engine" }, + { model: false }, + { systemPrompt: 1 }, + { effort: 1 }, + { personaContext: [] }, + { resumeSessionId: [] }, + { mcp: { url: "http://service.example/mcp", token: "fixture" } }, + { mcp: { url: "https://service.example/mcp", token: 1 } }, + { + repository: { + url: "https://git.example/project", + checkout: { kind: "pr", branch: "topic/pr", number: -1 }, + }, + }, + { + repository: { + url: "https://git.example/project", + checkout: { kind: "new", branch: "--option" }, + }, + }, + { + repository: { + url: "https://user:pass@git.example/project", + checkout: { kind: "branch", branch: "topic" }, + }, + }, + ]) { + const request = requestFrame({ + kind: "launch", + launch: { ...launch, ...fields }, + }); + expect(parseServiceFrame(request)).toBeNull(); + expect(runnerRequestId(request)).toBe(request.id); + } + expect(parseServiceFrame(requestFrame({ kind: "stop" }))).toBeNull(); + expect( + parseServiceFrame(requestFrame({ kind: "future-command" })) + ).toBeNull(); + expect(parseServiceFrame({ ...stop, command: null })).toBeNull(); + expect(parseServiceFrame({ ...stop, id: "" })).toBeNull(); + expect(runnerRequestId({ ...stop, id: [] })).toBeUndefined(); + expect( + parseServiceFrame({ type: "data", id: "channel", data: "AP8=\n" }) + ).toBeNull(); +}); + +it("validates operation-specific engine arguments", () => { + for (const operation of [ + { type: "status", futureStatusParameter: true }, + { type: "install", engine: "codex" }, + { type: "update", engine: "claude" }, + { type: "login_start", engine: "opencode" }, + { type: "login_start", engine: "opencode", restart: false }, + { type: "login_submit", loginId: "login:1", code: "fixture" }, + { type: "login_cancel", loginId: "login:1" }, + { type: "login_status", loginId: "login:1" }, + ]) { + const request = requestFrame({ + kind: "engine", + agentId: "@engine", + operation, + }); + expect(parseServiceFrame(request)).toBe(request); + } + for (const operation of [ + null, + { type: "install" }, + { type: "update", engine: "future-engine" }, + { type: "login_start", engine: "codex", restart: "no" }, + { type: "login_submit", loginId: "login:1", code: 42 }, + { type: "login_cancel", loginId: null }, + { type: "login_status" }, + { type: "future-operation" }, + ]) { + expect( + parseServiceFrame(requestFrame({ kind: "engine", operation })) + ).toBeNull(); + } +}); + +it("decodes the host session vocabulary including legacy and extended prompts", () => { + const source = { + source: "chat", + chatMessageId: "message:1", + chatMessageIds: ["message:1", "message:2"], + conversation: { streamId: "stream:1", threadId: null }, + answerIn: "message:2", + userMessage: true, + steeringExcluded: false, + awaited: false, + scheduleId: "schedule:1", + scheduleDeliveryId: "delivery:1", + attribution: { displayName: "Fixture" }, + }; + const prompt = { + type: "prompt", + id: "prompt:1", + text: "", + journalId: "journal:1", + source, + images: [{ path: "/fixture/image", mimeType: "image/png", alt: "Fixture" }], + }; + for (const command of [ + { type: "hello", fromSeq: 0 }, + { type: "hello", fromSeq: 1, journalId: null, replayComplete: true }, + { type: "prompt", id: "legacy", text: "Hello" }, + prompt, + { type: "steer", id: "steer:1", text: "Follow-up", source }, + { type: "cancel" }, + { type: "interrupt", id: "interrupt:1", turnSeq: 2 }, + { + type: "answer_permission", + id: "permission:1", + requestId: "request:2", + optionId: null, + }, + { type: "set_config", id: "set:1", configId: "mode", value: "default" }, + { type: "shutdown", force: false }, + { type: "shutdown" }, + { type: "mcp_inventory", id: "inventory:1", sessionId: "session:1" }, + { type: "background_work", id: "background:1", sessionId: "session:1" }, + { type: "ping", futureFlag: true }, + ]) { + expect(parseSessionCommand(command)).toBe(command); + } + for (const command of [ + null, + { type: "hello", fromSeq: -1 }, + { type: "hello", fromSeq: 1.5 }, + { type: "hello", fromSeq: 0, replayComplete: "true" }, + { ...prompt, journalId: 7 }, + { ...prompt, source: { ...source, conversation: { streamId: "stream" } } }, + { ...prompt, source: { ...source, chatMessageIds: [null] } }, + { ...prompt, images: [{ path: "/fixture/image" }] }, + { type: "steer", id: "steer:1", text: 1 }, + { type: "interrupt", id: "interrupt:1", turnSeq: 2 ** 53 }, + { type: "answer_permission", id: "permission:1", requestId: "request:2" }, + { type: "set_config", id: "set:1", configId: "mode", value: true }, + { type: "shutdown", force: "false" }, + { type: "mcp_inventory", id: "inventory:1" }, + { type: "background_work", id: "background:1", sessionId: [] }, + { type: "future-command", id: "future:1" }, + ]) { + expect(parseSessionCommand(command)).toBeNull(); + } + expect(sessionCommandId({ ...prompt, text: false })).toBe(prompt.id); +}); + +it("recognizes only supported enrollment replies and retains their extensions", () => { + const created = { + id: "connect/request:1", + code: "TEST-CODE", + expiresAt: "2030-01-01T00:00:00.000Z", + }; + const withLink = { + ...created, + approveUrl: "http://service.example/approve", + futureField: true, + }; + expect(parseConnectCreated(created)).toBe(created); + expect(parseConnectCreated(withLink)).toBe(withLink); + for (const result of [ + null, + { ...created, id: ".." }, + { ...created, code: "CODE\nFORGED" }, + { ...created, expiresAt: "tomorrow" }, + { ...created, approveUrl: "file:///tmp/approve" }, + ]) { + expect(parseConnectCreated(result)).toBeNull(); + } + const approved = { + status: "approved", + id: "collector/runner:1", + name: "Collector", + endpoint: "https://runner.example:4000", + cert: "fixture PEM", + ca: "fixture CA", + newerField: true, + }; + for (const reply of [ + { status: "pending" }, + { status: "denied" }, + { status: "expired" }, + approved, + ]) { + expect(parseConnectPoll(reply)).toBe(reply); + } + for (const reply of [ + null, + { status: "queued" }, + { ...approved, endpoint: "http://runner.example:4000" }, + { ...approved, name: [] }, + { ...approved, cert: "" }, + { ...approved, ca: false }, + ]) { + expect(parseConnectPoll(reply)).toBeNull(); + } +}); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index ed5cda3a2..bc6fe62be 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -27,7 +27,17 @@ To extend v1, define the message in its sending direction and document its receipt or failure semantics. For an optional operation, advertise support in `ready` and exercise both a capable peer and a peer that omits the flag. `wireFrames` handles NDJSON and buffering. Its directional TypeScript types -describe the expected messages; the recipient validates incoming values. +describe the expected messages. Pass parsed JSON to `parseServiceFrame` +before dispatching a runner command, and to `parseSessionCommand` at the host +end of an attached channel. These decoders accept additive fields in familiar +v1 messages and reject unknown command kinds. The runner replies with +`result.error` if a malformed request has a usable ID and closes the transport +if it cannot correlate the frame. The host replies with an `error` message. + +For HTTPS enrollment, decode successful response bodies with +`parseConnectCreated` and `parseConnectPoll` before displaying a code, polling, +or saving credentials. An unknown poll status is a protocol error. Verify the +issued certificate and CA before saving credentials. Run the in-memory consumer tests from the repository root with `pnpm run test:runner-protocol`. @@ -120,9 +130,9 @@ also sets `result.code` to `host-gone`. Losing the connection before the result leaves the outcome unknown. The service can reattach using the durable cursor described below. -The portable session types cover journal replay and prompt receipts. The -complete vocabulary spoken by Dispatch's ACP host, including permission -decisions, is in `apps/server/src/agents/acp/host-protocol.ts`. +The portable session types cover commands received by the host, journal replay, +and prompt receipts. Dispatch-specific host replies and event payloads are +defined in `apps/server/src/agents/acp/host-protocol.ts`. ## Receipts and replay diff --git a/packages/runner-protocol/src/engine-management.ts b/packages/runner-protocol/src/engine-management.ts index a0a168cdf..96ab0dda9 100644 --- a/packages/runner-protocol/src/engine-management.ts +++ b/packages/runner-protocol/src/engine-management.ts @@ -1,4 +1,5 @@ -import type { RunnerEngine } from "./index.js"; +import type { RunnerEngine } from "./execution.js"; +import { isRecord } from "./validation.js"; /** * Engine install/update/sign-in, scoped to wherever an engine's CLI runs: @@ -125,18 +126,33 @@ export function engineScopeKey(scope: EngineScope): string { return scope.kind === "local" ? "local" : `runner:${scope.runnerId}`; } +export function isRunnerEngine(value: unknown): value is RunnerEngine { + return RUNNER_ENGINES.some((engine) => engine === value); +} + export function isEngineOperation(value: unknown): value is EngineOperation { - if (!value || typeof value !== "object") return false; - const type = (value as { type?: unknown }).type; - return ( - type === "status" || - type === "install" || - type === "update" || - type === "login_start" || - type === "login_submit" || - type === "login_cancel" || - type === "login_status" - ); + if (!isRecord(value)) return false; + switch (value.type) { + case "status": + return true; + case "install": + case "update": + return isRunnerEngine(value.engine); + case "login_start": + return ( + isRunnerEngine(value.engine) && + (value.restart === undefined || typeof value.restart === "boolean") + ); + case "login_submit": + return ( + typeof value.loginId === "string" && typeof value.code === "string" + ); + case "login_cancel": + case "login_status": + return typeof value.loginId === "string"; + default: + return false; + } } const SUPPORTED_ACTIONS = new Set([ diff --git a/packages/runner-protocol/src/enrollment.ts b/packages/runner-protocol/src/enrollment.ts index f544b2f91..9c26b1915 100644 --- a/packages/runner-protocol/src/enrollment.ts +++ b/packages/runner-protocol/src/enrollment.ts @@ -1,3 +1,6 @@ +import { isOpaqueId } from "./placement.js"; +import { isHttpUrl, isRecord } from "./validation.js"; + /** Public bootstrap messages on the runner TLS listener, before agent traffic. */ export type EnrollmentRequest = | { type: "ca_request"; version: 1 } @@ -28,3 +31,47 @@ export type ConnectPoll = } | { status: "denied" } | { status: "expired" }; + +function isConnectCreated(value: unknown): value is ConnectCreated { + return ( + isRecord(value) && + isOpaqueId(value.id) && + value.id !== "." && + value.id !== ".." && + isOpaqueId(value.code) && + typeof value.expiresAt === "string" && + Number.isFinite(Date.parse(value.expiresAt)) && + !/[\x00-\x1f\x7f-\x9f]/u.test(value.expiresAt) && + (value.approveUrl === undefined || isHttpUrl(value.approveUrl, true)) + ); +} + +function isConnectPoll(value: unknown): value is ConnectPoll { + if (!isRecord(value)) return false; + switch (value.status) { + case "pending": + case "denied": + case "expired": + return true; + case "approved": + return ( + isOpaqueId(value.id) && + isOpaqueId(value.name) && + isHttpUrl(value.endpoint) && + typeof value.cert === "string" && + value.cert.trim().length > 0 && + typeof value.ca === "string" && + value.ca.trim().length > 0 + ); + default: + return false; + } +} + +export function parseConnectCreated(value: unknown): ConnectCreated | null { + return isConnectCreated(value) ? value : null; +} + +export function parseConnectPoll(value: unknown): ConnectPoll | null { + return isConnectPoll(value) ? value : null; +} diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index a2a3dc13b..701f7a546 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,9 +1,12 @@ import { MANAGED_WORKSPACE, isOpaqueId } from "./placement.js"; -import type { - EngineInventoryEntry, - EngineOperation, +import { + type EngineInventoryEntry, + type EngineOperation, + isEngineOperation, + isRunnerEngine, } from "./engine-management.js"; import type { RunnerHealth } from "./health.js"; +import { isHttpUrl, isNullableString, isRecord } from "./validation.js"; export const RUNNER_WIRE_VERSION = 1; @@ -111,3 +114,164 @@ export type RunnerFrame = | ChannelFrame; export type Frame = ServiceFrame | RunnerFrame; + +/** A full branch name, never a revision expression, option, or raw ref. */ +export function validBranch(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= 200 && + !value.startsWith("-") && + !value.startsWith("refs/") && + !value.endsWith(".") && + value !== "HEAD" && + value !== "@" && + !/[\x00-\x20\x7f~^:?*\[\\]|\.\.|@\{/.test(value) && + value + .split("/") + .every((part) => part && !part.startsWith(".") && !part.endsWith(".lock")) + ); +} + +/** Check the URL before a runner makes any workspace changes. */ +export function parseRunnerRepositoryUrl( + source: unknown, + fromOrigin = false +): URL | null { + if ( + typeof source !== "string" || + !source.startsWith("https://") || + source.length > 2048 || + /[\s\\?#\x00-\x1f\x7f]/.test(source) + ) + return null; + try { + const url = new URL(source); + return url.hostname && + url.pathname !== "/" && + !url.hash && + !url.search && + (fromOrigin || (!url.username && !url.password)) + ? url + : null; + } catch { + return null; + } +} + +function isRepository(value: unknown): value is RunnerRepository { + if ( + !isRecord(value) || + !parseRunnerRepositoryUrl(value.url) || + !isRecord(value.checkout) + ) + return false; + const checkout = value.checkout; + if (!validBranch(checkout.branch)) return false; + switch (checkout.kind) { + case "new": + return checkout.base === undefined || validBranch(checkout.base); + case "branch": + return true; + case "pr": + return ( + typeof checkout.number === "number" && + Number.isSafeInteger(checkout.number) && + checkout.number > 0 + ); + default: + return false; + } +} + +function isServiceMcp(value: unknown): value is ServiceMcp { + return ( + isRecord(value) && + isHttpUrl(value.url) && + typeof value.token === "string" && + value.token.length > 0 && + (value.name === undefined || typeof value.name === "string") + ); +} + +function isRemoteLaunch(value: unknown): value is RemoteLaunch { + return ( + isRecord(value) && + isOpaqueId(value.agentId) && + isRunnerEngine(value.engine) && + isNullableString(value.model) && + isNullableString(value.systemPrompt) && + isNullableString(value.resumeSessionId) && + (value.fullAccess === undefined || typeof value.fullAccess === "boolean") && + (value.effort === undefined || isNullableString(value.effort)) && + (value.personaContext === undefined || + isNullableString(value.personaContext)) && + (value.mcp === undefined || isServiceMcp(value.mcp)) && + (value.repository === undefined || isRepository(value.repository)) + ); +} + +function isCommand(value: unknown): value is Command { + if ( + !isRecord(value) || + !isOpaqueId(value.agentId) || + !isOpaqueId(value.workspace) + ) + return false; + switch (value.kind) { + case "launch": + return isRemoteLaunch(value.launch); + case "attach": + case "alive": + case "discard": + case "log": + case "repo": + return true; + case "stop": + return typeof value.force === "boolean"; + case "engine": + return isEngineOperation(value.operation); + default: + return false; + } +} + +/** Correlation ID usable even if the rest of the request is malformed. */ +export function runnerRequestId(value: unknown): string | undefined { + return isRecord(value) && value.type === "request" && isOpaqueId(value.id) + ? value.id + : undefined; +} + +function isBase64(value: unknown): value is string { + if (typeof value !== "string" || /[^A-Za-z0-9+/=]/u.test(value)) return false; + const paddingStart = value.indexOf("="); + if (paddingStart === -1) return value.length % 4 !== 1; + return ( + value.length % 4 === 0 && + (value.slice(paddingStart) === "=" || value.slice(paddingStart) === "==") + ); +} + +function isServiceFrame(value: unknown): value is ServiceFrame { + if (!isRecord(value)) return false; + switch (value.type) { + case "accept_health": + return ( + value.engineInventory === undefined || value.engineInventory === true + ); + case "request": + return isOpaqueId(value.id) && isCommand(value.command); + case "close": + return isOpaqueId(value.id); + case "data": + return isOpaqueId(value.id) && isBase64(value.data); + default: + return false; + } +} + +/** Validate known v1 fields while preserving any additive fields from peers. */ +export function parseServiceFrame(value: unknown): ServiceFrame | null { + return isServiceFrame(value) ? value : null; +} diff --git a/packages/runner-protocol/src/session.ts b/packages/runner-protocol/src/session.ts index 9fc946718..90716f0b3 100644 --- a/packages/runner-protocol/src/session.ts +++ b/packages/runner-protocol/src/session.ts @@ -1,4 +1,5 @@ import type { RunnerEngine } from "./execution.js"; +import { isNullableString, isRecord, isSequence } from "./validation.js"; /** The last contiguous position durably received in the named host journal. */ export type ReplayHello = { @@ -45,3 +46,198 @@ export type PromptReceipt = | { type: "prompt_accepted"; id: string } /** An engine-initiated turn is open and the host did not submit this prompt. */ | { type: "prompt_deferred"; id: string }; + +/** + * What a prompt sent to the harness was, for the prompt a turn entry + * renders. The wire text is an envelope Dispatch built; the feed wants the + * human-facing source behind it, not the envelope. + */ +export type PromptSource = { + /** Source discussion for batching and steering, retained through the host journal. + * User-thread turns use their validated source discussion for output at turn start. */ + conversation?: { streamId: string; threadId: string | null }; + /** + * A person's post. With a conversation, a prompt steers only that + * conversation; another agent's post without one steers any open turn. + */ + userMessage?: boolean; + /** Structured answers and commands retain their dedicated delivery policy. */ + steeringExcluded?: boolean; + /** Agent-authored scheduled content, explicitly eligible for steering. */ + scheduleId?: string; + scheduleDeliveryId?: string; + /** + * The recipient is waiting on this: a review it launched, a finding + * thread it is a side of, a finding settled or reopened. It joins the + * active turn whatever conversation that turn is in, rather than + * waiting behind the very work that is waiting on it. + */ + awaited?: boolean; +} & ( + | { + source: "chat"; + /** The post that opened the turn: the first, when there were several. */ + chatMessageId: string; + /** + * Every post the turn was given, in order, when posts that queued up + * behind a turn were delivered to it together. + */ + chatMessageIds?: string[]; + /** + * The block whose thread this prompt's answer belongs in, when the + * prompt says so rather than leaving it to what the post is: a + * notice that a finding changed is answered under the finding. + * Retained when prompts from this conversation are delivered together. + */ + answerIn?: string; + } + | { source: "agent"; senderId: string; senderName: string; text: string } + | { source: "system"; text: string } + /** + * A turn the engine started on its own between prompts (a background + * task finished, a goal continued). `after` is the block that answered + * the turn before it: this is source context; new ordinary work uses the agent home. + */ + | { source: "engine"; text: string; after?: string } +); + +/** Server-resolved files, kept out of turn journals and encoded only for ACP. */ +export type PromptImage = { path: string; mimeType: string }; + +export type SessionCommand = + | ReplayHello + | HostPrompt + | { type: "steer"; id: string; text: string; source?: PromptSource } + | { type: "cancel" } + | { type: "interrupt"; id: string; turnSeq: number } + | { + type: "answer_permission"; + id: string; + requestId: string; + optionId: string | null; + } + /** Set one of the session's config options (model, effort, mode). */ + | { type: "set_config"; id: string; configId: string; value: string } + | { type: "shutdown"; force?: boolean } + | { type: "mcp_inventory"; id: string; sessionId: string } + | { type: "background_work"; id: string; sessionId: string } + | { type: "ping" }; + +function isPromptSource(value: unknown): value is PromptSource { + if (!isRecord(value)) return false; + const { conversation } = value; + if ( + conversation !== undefined && + (!isRecord(conversation) || + typeof conversation.streamId !== "string" || + !isNullableString(conversation.threadId)) + ) + return false; + if ( + ![value.userMessage, value.steeringExcluded, value.awaited].every( + (flag) => flag === undefined || typeof flag === "boolean" + ) || + ![value.scheduleId, value.scheduleDeliveryId].every( + (id) => id === undefined || typeof id === "string" + ) + ) + return false; + switch (value.source) { + case "chat": + return ( + typeof value.chatMessageId === "string" && + (value.chatMessageIds === undefined || + (Array.isArray(value.chatMessageIds) && + value.chatMessageIds.every((id) => typeof id === "string"))) && + (value.answerIn === undefined || typeof value.answerIn === "string") + ); + case "agent": + return ( + typeof value.senderId === "string" && + typeof value.senderName === "string" && + typeof value.text === "string" + ); + case "system": + return typeof value.text === "string"; + case "engine": + return ( + typeof value.text === "string" && + (value.after === undefined || typeof value.after === "string") + ); + default: + return false; + } +} + +function isPromptImage(value: unknown): value is PromptImage { + return ( + isRecord(value) && + typeof value.path === "string" && + typeof value.mimeType === "string" + ); +} + +function isPromptInput(value: Record): boolean { + return ( + typeof value.id === "string" && + typeof value.text === "string" && + (value.source === undefined || isPromptSource(value.source)) + ); +} + +export function sessionCommandId(value: unknown): string | undefined { + return isRecord(value) && typeof value.id === "string" ? value.id : undefined; +} + +function isSessionCommand(value: unknown): value is SessionCommand { + if (!isRecord(value)) return false; + switch (value.type) { + case "hello": + return ( + isSequence(value.fromSeq) && + (value.journalId === undefined || isNullableString(value.journalId)) && + (value.replayComplete === undefined || + typeof value.replayComplete === "boolean") + ); + case "prompt": + return ( + isPromptInput(value) && + (value.journalId === undefined || + typeof value.journalId === "string") && + (value.images === undefined || + (Array.isArray(value.images) && value.images.every(isPromptImage))) + ); + case "steer": + return isPromptInput(value); + case "interrupt": + return typeof value.id === "string" && isSequence(value.turnSeq); + case "answer_permission": + return ( + typeof value.id === "string" && + typeof value.requestId === "string" && + isNullableString(value.optionId) + ); + case "set_config": + return ( + typeof value.id === "string" && + typeof value.configId === "string" && + typeof value.value === "string" + ); + case "shutdown": + return value.force === undefined || typeof value.force === "boolean"; + case "mcp_inventory": + case "background_work": + return ( + typeof value.id === "string" && typeof value.sessionId === "string" + ); + case "cancel": + case "ping": + return true; + default: + return false; + } +} + +export function parseSessionCommand(value: unknown): SessionCommand | null { + return isSessionCommand(value) ? value : null; +} diff --git a/packages/runner-protocol/src/validation.ts b/packages/runner-protocol/src/validation.ts new file mode 100644 index 000000000..684c420b3 --- /dev/null +++ b/packages/runner-protocol/src/validation.ts @@ -0,0 +1,22 @@ +export function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +export function isNullableString(value: unknown): value is string | null { + return value === null || typeof value === "string"; +} + +export function isSequence(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} + +export function isHttpUrl(value: unknown, allowHttp = false): value is string { + if (typeof value !== "string" || /[\x00-\x20\x7f-\x9f]/u.test(value)) + return false; + try { + const url = new URL(value); + return url.protocol === "https:" || (allowHttp && url.protocol === "http:"); + } catch { + return false; + } +} From c050dfe411e2f3d16973af8139db79e00eae182e Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:05:14 -0700 Subject: [PATCH 076/642] Recover remote runner sessions across supervisor restarts --- apps/server/src/agents/remote/runner.ts | 351 ++---------- .../src/agents/remote/session-processes.ts | 325 +++++++++++ .../src/agents/remote/session-supervisor.ts | 518 ++++++++++++++++++ .../server/test/remote-runner-startup.test.ts | 9 +- .../test/remote-runner-supervisor.test.ts | 236 ++++++++ 5 files changed, 1118 insertions(+), 321 deletions(-) create mode 100644 apps/server/src/agents/remote/session-processes.ts create mode 100644 apps/server/src/agents/remote/session-supervisor.ts create mode 100644 apps/server/test/remote-runner-supervisor.test.ts diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 7a28ef29a..66ccc9cfa 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -1,37 +1,15 @@ import { runnerHealthSampler } from "./health.js"; -import { spawn, execFile, type ChildProcess } from "node:child_process"; -import { createHash, randomUUID } from "node:crypto"; -import { closeSync, openSync, readFileSync } from "node:fs"; -import { - mkdir, - writeFile, - readFile, - rm, - chown, - chmod, - stat, - lstat, - rename, - realpath, - rmdir, -} from "node:fs/promises"; +import { execFile } from "node:child_process"; +import { readFileSync } from "node:fs"; import { createConnection, isIP } from "node:net"; import path from "node:path"; import process from "node:process"; import { connect } from "node:tls"; import { promisify } from "node:util"; -import { hostFile, type HostLaunch } from "../acp/host-protocol.js"; -import { - ownedEnvironment, - killOwnedProcesses, -} from "../../shared/process/owned-processes.js"; -import { - missingPath, - prepareScratchSession, - RunnerRepositories, - type WorkloadCommand, -} from "./session-storage.js"; -import { parseRepository } from "./repository.js"; +import type { HostLaunch } from "../acp/host-protocol.js"; +import type { WorkloadCommand } from "./session-storage.js"; +import { createSessionSupervisor } from "./session-supervisor.js"; +export { runnerStorageKey } from "./session-supervisor.js"; import { hostCommand } from "../acp/runtime.js"; import { isOpaqueId, @@ -43,7 +21,6 @@ import { type Command, type RunnerFrame, type RunnerEngine, - type RunnerRepository, } from "./protocol.js"; import { EngineRunnerExecutor, @@ -94,14 +71,6 @@ export const runnerGitArgs = [ const execute = promisify(execFile); const setpriv = "/usr/bin/setpriv"; -// Use the old storage name for existing prototype bindings. Other wire IDs -// never enter a filesystem path, even when they look like a relative path. -export function runnerStorageKey(agentId: string): string { - return /^agt_[a-z0-9]+$/.test(agentId) - ? agentId - : `opaque-${createHash("sha256").update(agentId).digest("base64url")}`; -} - function validExecutionId(value: number) { return Number.isInteger(value) && value > 0 && value < 0xffffffff; } @@ -185,7 +154,6 @@ export async function runRemoteRunner(filename: string) { if (!configuredHandles.every(isOpaqueId)) throw new Error("Runner workspace IDs must be valid opaque identifiers."); const managedWorkspace = configuredHandles.length === 0; - const managedBinding = "\0managed"; const env = { HOME: config.home, PATH: config.path, @@ -203,15 +171,6 @@ export async function runRemoteRunner(filename: string) { cert: readFileSync(config.cert), key: readFileSync(config.key), }; - const bindings = path.join(config.state, "bindings"); - const hostRoot = path.join(config.state, "hosts"); - const logs = path.join(bindings, "logs"); - - await mkdir(logs, { recursive: true, mode: 0o700 }); - await chmod(config.state, 0o711); - await mkdir(hostRoot, { recursive: true, mode: 0o711 }); - await chmod(hostRoot, 0o711); - const sampleHealth = runnerHealthSampler(); const engineExecutor = new EngineRunnerExecutor({ uid: config.uid, @@ -226,13 +185,6 @@ export async function runRemoteRunner(filename: string) { }, }, }); - const storage = await realpath(config.state); - const sessions = path.join(storage, "sessions"); - const cache = path.join(storage, "repositories"); - for (const root of [sessions, cache]) { - await mkdir(root, { mode: 0o711, recursive: true }); - await chmod(root, 0o711); - } const asWorkload: WorkloadCommand = async (bin, args, opts) => { const { stdout } = await execute( setpriv, @@ -252,205 +204,13 @@ export async function runRemoteRunner(filename: string) { ); return stdout; }; - const repositories = new RunnerRepositories( - cache, - config.uid, - config.gid, - asWorkload - ); - const hosts = new Map(); - const active = new Set(); - const readOptional = (file: string) => - readFile(file, "utf8").catch(missingPath); - const writePrivateState = async (file: string, contents: string) => { - const temp = path.join(bindings, `.pending-${randomUUID()}`); - try { - await writeFile(temp, contents, { flag: "wx", mode: 0o600 }); - await rename(temp, file); - } finally { - await rm(temp, { force: true }); - } - }; - const readBinding = (key: string) => readOptional(path.join(bindings, key)); - const retireFile = (key: string) => path.join(bindings, `${key}.retired`); - const repositoryFile = (key: string) => - path.join(bindings, `${key}.repository`); - const markerFile = (key: string) => path.join(bindings, `${key}.owner`); - - async function stopFormerHost(key: string) { - const marker = await readOptional(markerFile(key)); - if (marker) killOwnedProcesses(marker); - } - - async function removeGuestDirectory(dir: string) { - const entry = await lstat(dir).catch(missingPath); - if (!entry) return; - if (entry.uid === 0) { - // Startup can fail before handing the fresh, private directory over. - // The workload has never had access to this directory. - await rm(dir, { force: true, recursive: true }); - return; - } - // Resolve and remove workload-owned content as the workload. The - // supervisor only removes the now-empty, directly managed directory. - await asWorkload("/usr/bin/find", [dir, "-mindepth", "1", "-delete"]); - await rmdir(dir); - } - - async function discardManaged(key: string, dir: string) { - await writeFile(retireFile(key), "", { mode: 0o600 }); - await stopFormerHost(key); - const session = path.join(sessions, key); - const stored = await readOptional(repositoryFile(key)); - const repository = - stored === null ? null : (JSON.parse(stored) as RunnerRepository | null); - if (repository) await repositories.remove(session, repository); - await removeGuestDirectory(session); - await removeGuestDirectory(dir); - await rm(repositoryFile(key), { force: true }); - await rm(markerFile(key), { force: true }); - await rm(path.join(logs, key), { force: true }); - } - - async function launch( - command: Extract, - cwd: string | undefined, - key: string - ) { - const { agentId, workspace } = command; - if (hosts.has(agentId) || active.has(agentId)) - throw new Error("Runner already has a host for this agent"); - active.add(agentId); - try { - const { mcp } = command.launch; - const mcpUrl = mcp === undefined ? undefined : new URL(mcp.url); - if (mcpUrl && (mcpUrl.protocol !== "https:" || !mcp?.token)) { - throw new Error( - "Remote service MCP requires HTTPS and a scoped token." - ); - } - const managed = managedWorkspace && workspace === MANAGED_WORKSPACE; - if (!managed && command.launch.repository !== undefined) - throw new Error( - "Repository checkout requires a managed runner session." - ); - if (managed && (await readOptional(retireFile(key))) !== null) - throw new Error("This runner session has been archived."); - - const binding = path.join(bindings, key); - const bindingValue = managed ? managedBinding : workspace; - await writeFile(binding, bindingValue, { flag: "wx", mode: 0o600 }).catch( - async (error) => { - if ( - error.code !== "EEXIST" || - (await readBinding(key)) !== bindingValue - ) - throw error; - } - ); - if (managed) { - await stopFormerHost(key); - const parsed = - command.launch.repository === undefined - ? null - : parseRepository(command.launch.repository); - if (parsed && !parsed.url) - throw new Error("Missing runner repository URL."); - const repository = parsed?.url - ? { url: parsed.url, checkout: parsed.checkout } - : null; - const encoded = JSON.stringify(repository); - const stored = await readOptional(repositoryFile(key)); - if (stored !== null && stored !== encoded) - throw new Error( - "This runner session is bound to a different checkout." - ); - if (stored === null) - await writePrivateState(repositoryFile(key), encoded); - cwd = await prepareScratchSession( - sessions, - key, - config.uid, - config.gid - ); - if (repository) cwd = await repositories.prepare(cwd, repository); - } - if (!cwd || (!managed && !(await stat(cwd)).isDirectory())) - throw new Error("Guest workspace is unavailable"); - const dir = path.join(hostRoot, key); - const files = path.join(dir, "files"); - const { repository: _repository, ...launchOptions } = command.launch; - const launch: HostLaunch = { - ...launchOptions, - agentId, - cwd, - bins: config.bins, - env: { - DISPATCH_AGENT_ID: agentId, - DISPATCH_FILES_DIR: files, - ...(mcpUrl ? { DISPATCH_API_URL: mcpUrl.origin } : {}), - NODE_EXTRA_CA_CERTS: config.ca, - }, - pathPrefix: [], - reportTurnActivity: true, - }; - // Write only into a fresh directory: a previous CLI account could have - // replaced anything under its old host directory with symlinks. - if (managed) await removeGuestDirectory(dir); - else await rm(dir, { force: true, recursive: true }); - await mkdir(dir, { mode: 0o700 }); - await mkdir(files, { mode: 0o700 }); - await chown(files, config.uid, config.gid); - await writeFile(hostFile(dir, "launch"), JSON.stringify(launch), { - mode: 0o600, - }); - await chown(hostFile(dir, "launch"), config.uid, config.gid); - await chown(dir, config.uid, config.gid); - const log = openSync(path.join(logs, key), "a", 0o600); - try { - const [bin, ...args] = hostCommand(); - if (!bin) throw new Error("Runner host executable is missing"); - const owned = ownedEnvironment(env); - if (managed) await writePrivateState(markerFile(key), owned.marker); - const child = spawn( - setpriv, - [...childArgs, bin, ...args, "--state", dir], - { - cwd, - env: owned.env, - detached: true, - stdio: ["ignore", log, log], - } - ); - hosts.set(agentId, child); - const forget = () => { - if (hosts.get(agentId) === child) hosts.delete(agentId); - }; - child.on("exit", () => { - try { - killOwnedProcesses(owned.marker); - } catch (error) { - console.error( - "Guest host descendant cleanup:", - (error as Error).message - ); - } finally { - forget(); - } - }); - child.on("error", forget); - await new Promise((resolve, reject) => { - child.once("spawn", resolve); - child.once("error", reject); - }); - child.unref(); - } finally { - closeSync(log); - } - } finally { - active.delete(agentId); - } - } + const supervisor = await createSessionSupervisor({ + ...config, + env, + workspaces: new Set(configuredHandles), + asWorkload, + hostCommand: () => [setpriv, ...childArgs, ...hostCommand()], + }); while (true) { await new Promise((finished) => { @@ -467,10 +227,7 @@ export async function runRemoteRunner(filename: string) { if (sampling || socket.destroyed) return; sampling = true; try { - const dirs = [...hosts.keys()].map((id) => - path.join(hostRoot, runnerStorageKey(id)) - ); - const sample = await sampleHealth(dirs); + const sample = await sampleHealth(await supervisor.liveDirectories()); safeSend({ type: "health", sample }); } catch (error) { console.warn( @@ -549,37 +306,18 @@ export async function runRemoteRunner(filename: string) { const managed = managedWorkspace && workspace === MANAGED_WORKSPACE; if (!isOpaqueId(agentId) || (!target && !managed)) throw new Error("Unknown runner workspace or agent"); - const key = runnerStorageKey(agentId); const result = (value?: string | boolean) => safeSend({ type: "result", id, value }); if (command.kind === "launch") { - await launch(command, target?.cwd, key); + await supervisor.launch(command, target?.cwd); result(true); return; } - const binding = await readBinding(key); - if (binding !== (managed ? managedBinding : workspace)) { - if (command.kind === "alive") return result(false); - if (managed && binding === null && !active.has(agentId)) { - if (command.kind === "stop") return result(true); - if (command.kind === "discard") { - active.add(agentId); - try { - await writeFile(retireFile(key), "", { mode: 0o600 }); - } finally { - active.delete(agentId); - } - return result(true); - } - } - throw new Error("Agent is not bound to this workspace"); - } if (socket.destroyed) return; - const host = hosts.get(agentId); - const dir = path.join(hostRoot, key); switch (command.kind) { case "attach": { - if (!host) { + const channel = await supervisor.attach(agentId, workspace); + if (!channel) { safeSend({ type: "result", id, @@ -588,7 +326,10 @@ export async function runRemoteRunner(filename: string) { }); break; } - const channel = createConnection(hostFile(dir, "socket")); + if (socket.destroyed) { + channel.destroy(); + break; + } channels.set(id, channel); channel.once("connect", () => result(true)); channel.on("data", (chunk: Buffer) => @@ -609,55 +350,22 @@ export async function runRemoteRunner(filename: string) { break; } case "alive": - result(Boolean(host)); + result(await supervisor.alive(agentId, workspace)); break; case "stop": - if (host?.pid) { - const exited = new Promise((resolve) => - host.once("exit", () => resolve()) - ); - const signal = (value: NodeJS.Signals) => { - try { - process.kill(-host.pid!, value); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ESRCH") - throw error; - } - }; - const timer = setTimeout(() => signal("SIGKILL"), 8_000); - signal(command.force ? "SIGKILL" : "SIGTERM"); - try { - await exited; - } finally { - clearTimeout(timer); - } - } - if (managed && !active.has(agentId)) await stopFormerHost(key); + await supervisor.stop(agentId, workspace, command.force); result(true); break; case "discard": - if (host || active.has(agentId)) - throw new Error("Stop the guest host before discarding it"); - active.add(agentId); - try { - if (managed) await discardManaged(key, dir); - else await rm(dir, { force: true, recursive: true }); - await rm(path.join(bindings, key), { force: true }); - } finally { - active.delete(agentId); - } + await supervisor.discard(agentId, workspace); result(true); break; - case "log": { - const log = await readFile(path.join(logs, key), "utf8").catch( - () => "" - ); - result( - `Guest agent host ${host ? "log" : "exited"}.${log ? "\n" + log.slice(-2048) : ""}` - ); + case "log": + result(await supervisor.log(agentId, workspace)); break; - } case "repo": { + if (!(await supervisor.isBound(agentId, workspace))) + throw new Error("Agent is not bound to this workspace"); const [bin, ...args] = target?.repoTool ?? []; if (!bin) throw new Error( @@ -729,6 +437,9 @@ export async function runRemoteRunner(filename: string) { engineManagement: true, }); }); + }).catch((error) => { + supervisor.close(); + throw error; }); await new Promise((resolve) => setTimeout(resolve, 1000)); } diff --git a/apps/server/src/agents/remote/session-processes.ts b/apps/server/src/agents/remote/session-processes.ts new file mode 100644 index 000000000..0324a44ab --- /dev/null +++ b/apps/server/src/agents/remote/session-processes.ts @@ -0,0 +1,325 @@ +import { spawn } from "node:child_process"; +import { + closeSync, + constants, + fstatSync, + openSync, + readdirSync, + readFileSync, + readlinkSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import { setTimeout as delay } from "node:timers/promises"; +import { ownedEnvironment } from "../../shared/process/owned-processes.js"; +import type { WorkloadCommand } from "./session-storage.js"; + +type Kernel = ReturnType; + +function linuxKernel() { + // These two supported Linux architectures share the pidfd_send_signal ABI. + if (process.arch !== "arm64" && process.arch !== "x64") + throw new Error("Runner session supervision requires arm64 or x64 Linux."); + const { dlopen, read } = createRequire(import.meta.url)( + "bun:ffi" + ) as typeof import("bun:ffi"); + const { symbols } = dlopen("libc.so.6", { + flock: { args: ["i32", "i32"], returns: "i32" }, + syscall: { args: ["i32", "i32", "i32", "ptr", "i32"], returns: "i32" }, + __errno_location: { args: [], returns: "ptr" }, + }); + const errno = () => read.i32(symbols.__errno_location()!); + return { + lock(fd: number) { + if (symbols.flock(fd, 2 | 4) !== 0) + throw new Error(`Cannot lock runner session state (errno ${errno()}).`); + }, + signal(fd: number, signal: number) { + if (symbols.syscall(424, fd, signal, null, 0) === 0) return; + const code = errno(); + if (code !== 3) + // ESRCH + throw new Error( + `Cannot signal runner session process (errno ${code}).` + ); + }, + }; +} + +function tryProc(operation: () => T): T | null { + try { + return operation(); + } catch (error) { + if ( + ["ENOENT", "ESRCH"].includes((error as NodeJS.ErrnoException).code ?? "") + ) + return null; + throw error; + } +} + +export function parseProcessStat(text: string) { + // The comm field can contain whitespace, parentheses and newlines. + const fields = text + .slice(text.lastIndexOf(")") + 2) + .trim() + .split(/\s+/); + const session = Number(fields[3]); + const start = fields[19]; + if (!Number.isSafeInteger(session) || !start || !/^\d+$/.test(start)) + throw new Error("Invalid Linux process stat."); + return { session, start, dead: fields[0] === "Z" || fields[0] === "X" }; +} + +function withProcess( + pid: number, + operation: (fd: number, proc: string) => T +) { + // Linux accepts an open /proc/PID directory as a pidfd for signaling. + // Reading stat through the same descriptor also pins the lookup to that + // instance of the task, even when a later process gets the numeric PID. + const fd = tryProc(() => + openSync(`/proc/${pid}`, constants.O_RDONLY | constants.O_DIRECTORY) + ); + if (fd === null) return null; + try { + return operation(fd, `/proc/self/fd/${fd}`); + } finally { + closeSync(fd); + } +} + +function statProcess(proc: string) { + return tryProc(() => parseProcessStat(readFileSync(`${proc}/stat`, "utf8"))); +} + +export type SessionIdentity = { + scope: string; + pid: number; + start: string; + marker: string; +}; + +export function validMarker(marker: unknown): marker is string { + return ( + typeof marker === "string" && /^DISPATCH_OWNED_[a-f0-9]{32}=1$/.test(marker) + ); +} + +export function parseSessionIdentity(raw: string): SessionIdentity { + const identity = JSON.parse(raw) as SessionIdentity | null; + if ( + !identity || + typeof identity.scope !== "string" || + !Number.isSafeInteger(identity.pid) || + identity.pid <= 1 || + typeof identity.start !== "string" || + !/^\d+$/.test(identity.start) || + !validMarker(identity.marker) + ) + throw new Error("Invalid runner host identity."); + return identity; +} + +export type SessionProcesses = ReturnType; + +export function createSessionProcesses( + uid: number, + asWorkload: WorkloadCommand +) { + const kernel = linuxKernel(); + const scope = [ + readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), + readlinkSync("/proc/self/ns/pid"), + ].join(":"); + + const withHost = ( + identity: SessionIdentity, + use: (fd: number, proc: string) => T + ) => { + if (identity.scope !== scope || identity.pid === process.pid) return null; + return withProcess(identity.pid, (fd, proc) => { + const found = statProcess(proc); + if ( + !found || + found.dead || + found.start !== identity.start || + found.session !== identity.pid + ) + return null; + return use(fd, proc); + }); + }; + const alive = (identity: SessionIdentity) => + withHost(identity, () => true) === true; + + // The launched host and engine inherit this exact marker. Match only the + // configured workload UID, and hold descriptors across enumeration and + // verification so recycled PIDs cannot be signaled. Read the environment + // as the workload: container root can lack CAP_SYS_PTRACE. + async function cleanup(marker: string) { + if (!validMarker(marker)) throw new Error("Invalid runner process marker."); + for (let pass = 0; pass < 4; pass++) { + const pids = readdirSync("/proc").filter( + (pid) => /^[1-9]\d*$/.test(pid) && Number(pid) !== process.pid + ); + let found = false; + for (let offset = 0; offset < pids.length; offset += 128) { + const candidates: { fd: number; file: string }[] = []; + try { + for (const pid of pids.slice(offset, offset + 128)) { + const fd = tryProc(() => + openSync( + `/proc/${pid}`, + constants.O_RDONLY | constants.O_DIRECTORY + ) + ); + if (fd === null) continue; + if (fstatSync(fd).uid === uid) + candidates.push({ fd, file: `/proc/${pid}/environ` }); + else closeSync(fd); + } + if (!candidates.length) continue; + // grep may see a child disappear between enumeration and open. Keep + // its successful matches and handle exit codes other than 0/1/2. + const output = await asWorkload("/usr/bin/grep", [ + "-azlFx", + "--", + marker, + ...candidates.map(({ file }) => file), + ]).catch((error) => { + if ([1, 2].includes(error.code)) return String(error.stdout ?? ""); + throw error; + }); + const matches = new Set(output.split("\n")); + for (const { fd, file } of candidates) { + if (!matches.has(file)) continue; + const current = statProcess(`/proc/self/fd/${fd}`); + if (!current || current.dead || fstatSync(fd).uid !== uid) continue; + found = true; + kernel.signal(fd, 9); + } + } finally { + for (const { fd } of candidates) closeSync(fd); + } + } + if (!found) return; + await delay(25); + } + throw new Error("Runner session processes did not exit after cleanup."); + } + + return { + acquire(stateLock: string) { + const fd = openSync( + stateLock, + constants.O_CREAT | constants.O_NOFOLLOW | constants.O_RDWR, + 0o600 + ); + try { + kernel.lock(fd); + // Confirm pidfd signaling is supported before accepting requests. + withProcess(process.pid, (self) => kernel.signal(self, 0)); + return () => closeSync(fd); + } catch (error) { + closeSync(fd); + throw error; + } + }, + alive, + async spawn( + command: string[], + cwd: string, + env: NodeJS.ProcessEnv, + log: number, + record: (identity: SessionIdentity) => Promise, + onExit: (identity: SessionIdentity) => void + ) { + const owned = ownedEnvironment(env); + // With undelivered stdin on supervisor death, the shell exits before + // dropping privilege or running the host. After release, exec preserves + // the PID and start time recorded while the root launcher was blocked. + const child = spawn( + "/bin/sh", + [ + "-c", + 'IFS= read -r gate && [ "$gate" = start ] && exec "$@" {}); + child.on("exit", () => { + if (identity) onExit(identity); + }); + try { + await new Promise((resolve, reject) => { + child.once("spawn", resolve); + child.on("error", reject); + }); + const pid = child.pid!; + const proc = withProcess(pid, (_fd, dir) => statProcess(dir)); + if (!proc || proc.dead || proc.session !== pid) + throw new Error( + "Runner could not identify the detached host launcher." + ); + identity = { scope, pid, start: proc.start, marker: owned.marker }; + await record(identity); + child.stdin!.end("start\n"); + child.unref(); + } catch (error) { + child.stdin!.destroy(); + throw error; + } + }, + async stop(identity: SessionIdentity, force: boolean) { + const wait = async (ms: number) => { + const deadline = performance.now() + ms; + while (alive(identity) && performance.now() < deadline) await delay(50); + }; + if (!force) { + withHost(identity, (fd) => kernel.signal(fd, 15)); + await wait(8_000); + } + if (alive(identity)) { + withHost(identity, (leader, leaderProc) => { + // Force-stop members of the detached session even if they removed + // their environment marker. Recheck the original leader through its + // descriptor after reading each candidate's session membership. + for (const entry of readdirSync("/proc")) { + if (!/^[1-9]\d*$/.test(entry)) continue; + const pid = Number(entry); + if (pid === identity.pid || pid === process.pid) continue; + withProcess(pid, (fd, proc) => { + const member = statProcess(proc); + const host = statProcess(leaderProc); + if ( + member && + !member.dead && + member.session === identity.pid && + host && + !host.dead + ) + kernel.signal(fd, 9); + }); + } + kernel.signal(leader, 9); + }); + await wait(2_000); + } + if (alive(identity)) throw new Error("Guest agent host did not stop."); + }, + cleanup(identity: SessionIdentity) { + return identity.scope === scope + ? cleanup(identity.marker) + : Promise.resolve(); + }, + cleanupLegacy: cleanup, + socketInUse(socket: string) { + return readFileSync("/proc/net/unix", "utf8") + .split("\n") + .some((line) => /^\S+\s+(?:\S+\s+){6}(.*)$/.exec(line)?.[1] === socket); + }, + }; +} diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts new file mode 100644 index 000000000..345c210d6 --- /dev/null +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -0,0 +1,518 @@ +import { createHash, randomUUID } from "node:crypto"; +import { closeSync, constants, fstatSync, openSync } from "node:fs"; +import { + chmod, + chown, + lstat, + mkdir, + open, + readdir, + readFile, + realpath, + rename, + rm, + rmdir, + stat, + writeFile, +} from "node:fs/promises"; +import { createConnection } from "node:net"; +import path from "node:path"; +import { hostFile, type HostLaunch } from "../acp/host-protocol.js"; +import { + MANAGED_WORKSPACE, + type Command, + type RunnerRepository, +} from "./protocol.js"; +import { parseRepository } from "./repository.js"; +import { + createSessionProcesses, + parseSessionIdentity, + type SessionIdentity, + type SessionProcesses, +} from "./session-processes.js"; +import { + missingPath, + prepareScratchSession, + RunnerRepositories, + type WorkloadCommand, +} from "./session-storage.js"; + +// Use the old storage name for existing prototype bindings. Other wire IDs +// never enter a filesystem path, even when they look like a relative path. +export function runnerStorageKey(agentId: string): string { + return /^agt_[a-z0-9]+$/.test(agentId) + ? agentId + : `opaque-${createHash("sha256").update(agentId).digest("base64url")}`; +} + +type LaunchCommand = Extract; + +type SupervisorOptions = { + state: string; + uid: number; + gid: number; + ca: string; + bins: HostLaunch["bins"]; + env: NodeJS.ProcessEnv; + workspaces: ReadonlySet; + hostCommand: () => string[]; + asWorkload: WorkloadCommand; +}; + +const managedBinding = "\0managed"; +const readOptional = (file: string) => + readFile(file, "utf8").catch(missingPath); + +async function ownedDirectory(dir: string, mode: number) { + const entry = await lstat(dir); + if ( + !entry.isDirectory() || + entry.uid !== process.getuid?.() || + entry.mode & 0o022 + ) + throw new Error( + "Runner state directories must be owned by the supervisor." + ); + await chmod(dir, mode); +} + +export async function createSessionSupervisor( + config: SupervisorOptions, + processes: SessionProcesses = createSessionProcesses( + config.uid, + config.asWorkload + ) +) { + const { asWorkload, env } = config; + const managedWorkspace = config.workspaces.size === 0; + await mkdir(config.state, { recursive: true, mode: 0o700 }); + await ownedDirectory(config.state, 0o711); + const storage = await realpath(config.state); + const bindings = path.join(storage, "bindings"); + await mkdir(bindings, { mode: 0o700, recursive: true }); + await ownedDirectory(bindings, 0o700); + const release = processes.acquire(path.join(bindings, ".lock")); + const hostRoot = path.join(storage, "hosts"); + const logs = path.join(bindings, "logs"); + const sessions = path.join(storage, "sessions"); + const cache = path.join(storage, "repositories"); + try { + for (const [root, mode] of [ + [logs, 0o700], + [hostRoot, 0o711], + [sessions, 0o711], + [cache, 0o711], + ] as const) { + await mkdir(root, { mode, recursive: true }); + await ownedDirectory(root, mode); + } + } catch (error) { + release(); + throw error; + } + const repositories = new RunnerRepositories( + cache, + config.uid, + config.gid, + asWorkload + ); + const operations = new Map>(); + + function serialize(key: string, operation: () => Promise): Promise { + const pending = (operations.get(key) ?? Promise.resolve()) + .catch(() => {}) + .then(operation); + operations.set(key, pending); + return pending.finally(() => { + if (operations.get(key) === pending) operations.delete(key); + }); + } + + async function writePrivateState(file: string, contents: string) { + const temp = path.join(bindings, `.pending-${randomUUID()}`); + try { + const handle = await open(temp, "wx", 0o600); + try { + await handle.writeFile(contents); + await handle.sync(); + } finally { + await handle.close(); + } + await rename(temp, file); + const directory = await open( + bindings, + constants.O_RDONLY | constants.O_DIRECTORY + ); + try { + await directory.sync(); + } finally { + await directory.close(); + } + } finally { + await rm(temp, { force: true }); + } + } + + const readBinding = (key: string) => readOptional(path.join(bindings, key)); + const retireFile = (key: string) => path.join(bindings, `${key}.retired`); + const repositoryFile = (key: string) => + path.join(bindings, `${key}.repository`); + const markerFile = (key: string) => path.join(bindings, `${key}.owner`); + const identityFile = (key: string) => path.join(bindings, `${key}.host`); + function managedTarget(workspace: string) { + if (managedWorkspace && workspace === MANAGED_WORKSPACE) return true; + if (!config.workspaces.has(workspace)) + throw new Error("Unknown runner workspace"); + return false; + } + + async function readIdentity(key: string) { + const record = await readOptional(identityFile(key)); + return record === null ? null : parseSessionIdentity(record); + } + + async function cleanHost(key: string, identity: SessionIdentity | null) { + if (identity) { + await processes.cleanup(identity); + // Unlink only after all known descendants have gone. + await rm(identityFile(key), { force: true }); + } + } + + async function cleanLegacyHost(key: string) { + const legacy = await readOptional(markerFile(key)); + if (legacy) { + await processes.cleanupLegacy(legacy); + await rm(markerFile(key), { force: true }); + } + } + + function checkUntrackedSocket(dir: string) { + const originalPath = path.join(config.state, "hosts", path.basename(dir)); + if ( + processes.socketInUse(hostFile(dir, "socket")) || + (originalPath !== dir && + processes.socketInUse(hostFile(originalPath, "socket"))) + ) + throw new Error( + "Runner cannot verify ownership of the existing guest host." + ); + } + + async function removeGuestDirectory(dir: string) { + const entry = await lstat(dir).catch(missingPath); + if (!entry) return; + if (!entry.isDirectory()) + throw new Error("Invalid runner session directory."); + if (entry.uid === process.getuid?.()) { + // Startup can fail before handing the private directory over. + await rm(dir, { force: true, recursive: true }); + return; + } + await asWorkload("/usr/bin/find", [dir, "-mindepth", "1", "-delete"]); + await rmdir(dir); + } + + async function discardManaged(key: string) { + await writePrivateState(retireFile(key), ""); + const session = path.join(sessions, key); + const stored = await readOptional(repositoryFile(key)); + const repository = + stored === null ? null : (JSON.parse(stored) as RunnerRepository | null); + if (repository) await repositories.remove(session, repository); + await removeGuestDirectory(session); + await rm(repositoryFile(key), { force: true }); + await rm(path.join(logs, key), { force: true }); + } + + async function launch( + command: LaunchCommand, + cwd: string | undefined, + key: string + ) { + const { agentId, workspace } = command; + const { mcp } = command.launch; + const mcpUrl = mcp === undefined ? undefined : new URL(mcp.url); + if (mcpUrl && (mcpUrl.protocol !== "https:" || !mcp?.token)) { + throw new Error("Remote service MCP requires HTTPS and a scoped token."); + } + const managed = managedTarget(workspace); + if (!managed && command.launch.repository !== undefined) + throw new Error("Repository checkout requires a managed runner session."); + if (managed && (await readOptional(retireFile(key))) !== null) + throw new Error("This runner session has been archived."); + + const binding = await readBinding(key); + const bindingValue = managed ? managedBinding : workspace; + if (binding === null) + await writePrivateState(path.join(bindings, key), bindingValue); + else if (binding !== bindingValue) + throw new Error("Agent is not bound to this workspace"); + const identity = await readIdentity(key); + if (identity && processes.alive(identity)) + throw new Error("Runner already has a host for this agent"); + await cleanHost(key, identity); + checkUntrackedSocket(path.join(hostRoot, key)); + await cleanLegacyHost(key); + if (managed) { + const parsed = + command.launch.repository === undefined + ? null + : parseRepository(command.launch.repository); + if (parsed && !parsed.url) + throw new Error("Missing runner repository URL."); + const repository = parsed?.url + ? { url: parsed.url, checkout: parsed.checkout } + : null; + const encoded = JSON.stringify(repository); + const stored = await readOptional(repositoryFile(key)); + if (stored !== null && stored !== encoded) + throw new Error( + "This runner session is bound to a different checkout." + ); + if (stored === null) + await writePrivateState(repositoryFile(key), encoded); + cwd = await prepareScratchSession(sessions, key, config.uid, config.gid); + if (repository) cwd = await repositories.prepare(cwd, repository); + } + if (!cwd || (!managed && !(await stat(cwd)).isDirectory())) + throw new Error("Guest workspace is unavailable"); + const dir = path.join(hostRoot, key); + const files = path.join(dir, "files"); + const { repository: _repository, ...launchOptions } = command.launch; + const launch: HostLaunch = { + ...launchOptions, + agentId, + cwd, + bins: config.bins, + env: { + DISPATCH_AGENT_ID: agentId, + DISPATCH_FILES_DIR: files, + ...(mcpUrl ? { DISPATCH_API_URL: mcpUrl.origin } : {}), + NODE_EXTRA_CA_CERTS: config.ca, + }, + pathPrefix: [], + reportTurnActivity: true, + }; + // Write only into a fresh directory: a previous CLI account could have + // replaced anything under its old host directory with symlinks. + await removeGuestDirectory(dir); + await mkdir(dir, { mode: 0o700 }); + await mkdir(files, { mode: 0o700 }); + await chown(files, config.uid, config.gid); + await writeFile(hostFile(dir, "launch"), JSON.stringify(launch), { + mode: 0o600, + }); + await chown(hostFile(dir, "launch"), config.uid, config.gid); + await chown(dir, config.uid, config.gid); + + const log = openSync(path.join(logs, key), "a", 0o600); + try { + const host = config.hostCommand(); + if (!host[0]) throw new Error("Runner host executable is missing"); + await processes.spawn( + [...host, "--state", dir], + cwd, + env, + log, + (identity) => + writePrivateState(identityFile(key), JSON.stringify(identity)), + (identity) => { + void serialize(key, async () => { + const current = await readIdentity(key); + if ( + current?.marker === identity.marker && + !processes.alive(current) + ) + await cleanHost(key, current); + }).catch((error) => + console.error("Guest host descendant cleanup:", error.message) + ); + } + ); + } finally { + closeSync(log); + } + } + + async function bound(key: string, workspace: string) { + const binding = await readBinding(key); + return binding === (managedTarget(workspace) ? managedBinding : workspace); + } + + async function cleanExited(key: string) { + const current = await readIdentity(key); + if (current && !processes.alive(current)) await cleanHost(key, current); + } + + async function trackedKeys() { + return (await readdir(bindings)) + .filter((file) => + /^(agt_[a-z0-9]+|opaque-[A-Za-z0-9_-]{43})\.host$/.test(file) + ) + .map((file) => file.slice(0, -5)); + } + + // Recovered hosts have no ChildProcess exit event. Keep descendant cleanup + // independent of the service connection and isolate failures by session. + let sweeping = false; + const sweep = setInterval(() => { + if (sweeping) return; + sweeping = true; + void trackedKeys() + .then((keys) => + Promise.allSettled( + keys.map((key) => serialize(key, () => cleanExited(key))) + ) + ) + .then((results) => { + for (const result of results) { + if (result.status === "rejected") + console.error( + "Guest host descendant cleanup:", + result.reason.message + ); + } + }) + .catch((error) => console.error("Guest host inventory:", error.message)) + .finally(() => { + sweeping = false; + }); + }, 5_000); + sweep.unref(); + + return { + launch(command: LaunchCommand, cwd: string | undefined) { + const key = runnerStorageKey(command.agentId); + return serialize(key, () => launch(command, cwd, key)); + }, + async alive(agentId: string, workspace: string) { + const key = runnerStorageKey(agentId); + return serialize(key, async () => { + if (!(await bound(key, workspace))) return false; + const identity = await readIdentity(key); + return identity !== null && processes.alive(identity); + }); + }, + attach(agentId: string, workspace: string) { + const key = runnerStorageKey(agentId); + return serialize(key, async () => { + if (!(await bound(key, workspace))) + throw new Error("Agent is not bound to this workspace"); + const identity = await readIdentity(key); + if (!identity || !processes.alive(identity)) return null; + + // Open the socket inode without following a workload-created symlink. + // Linux connect through /proc/self/fd pins the checked inode, even if + // the workload replaces the pathname before connect completes. + const linuxOpenPath = 0x200000; // O_PATH is not exposed by Node. + let fd: number; + try { + fd = openSync( + hostFile(path.join(hostRoot, key), "socket"), + linuxOpenPath | constants.O_NOFOLLOW + ); + } catch (error) { + throw new Error("Guest host socket is unavailable", { cause: error }); + } + try { + const socket = fstatSync(fd); + if (!socket.isSocket() || socket.uid !== config.uid) + throw new Error("Guest host socket is unavailable"); + if (!processes.alive(identity)) { + closeSync(fd); + return null; + } + const channel = createConnection(`/proc/self/fd/${fd}`); + const releaseSocket = () => { + channel.off("connect", releaseSocket); + channel.off("close", releaseSocket); + closeSync(fd); + }; + channel.once("connect", releaseSocket); + channel.once("close", releaseSocket); + return channel; + } catch (error) { + closeSync(fd); + throw error; + } + }); + }, + stop(agentId: string, workspace: string, force: boolean) { + const key = runnerStorageKey(agentId); + return serialize(key, async () => { + if (!(await bound(key, workspace))) { + if (managedTarget(workspace) && (await readBinding(key)) === null) + return; + throw new Error("Agent is not bound to this workspace"); + } + const dir = path.join(hostRoot, key); + const identity = await readIdentity(key); + if (identity) await processes.stop(identity, force); + await cleanHost(key, identity); + checkUntrackedSocket(dir); + await cleanLegacyHost(key); + }); + }, + discard(agentId: string, workspace: string) { + const key = runnerStorageKey(agentId); + return serialize(key, async () => { + const managed = managedTarget(workspace); + if (!(await bound(key, workspace))) { + if (managed && (await readBinding(key)) === null) { + await writePrivateState(retireFile(key), ""); + return; + } + throw new Error("Agent is not bound to this workspace"); + } + const identity = await readIdentity(key); + if (identity && processes.alive(identity)) + throw new Error("Stop the guest host before discarding it"); + const dir = path.join(hostRoot, key); + await cleanHost(key, identity); + checkUntrackedSocket(dir); + await cleanLegacyHost(key); + if (managed) await discardManaged(key); + await removeGuestDirectory(dir); + await rm(path.join(bindings, key), { force: true }); + }); + }, + async log(agentId: string, workspace: string) { + const key = runnerStorageKey(agentId); + if (!(await bound(key, workspace))) + throw new Error("Agent is not bound to this workspace"); + const identity = await readIdentity(key); + const live = identity && processes.alive(identity); + const log = await readFile(path.join(logs, key), "utf8").catch( + missingPath + ); + return `Guest agent host ${live ? "log" : "exited"}.${log ? "\n" + log.slice(-2048) : ""}`; + }, + async isBound(agentId: string, workspace: string) { + return bound(runnerStorageKey(agentId), workspace); + }, + async liveDirectories() { + const dirs = await Promise.all( + (await trackedKeys()).map(async (key) => { + const binding = await readBinding(key); + if ( + binding === null || + !(managedWorkspace + ? binding === managedBinding + : config.workspaces.has(binding)) + ) + return null; + const identity = await readIdentity(key); + return identity && processes.alive(identity) + ? path.join(hostRoot, key) + : null; + }) + ); + return dirs.filter((dir) => dir !== null); + }, + close() { + clearInterval(sweep); + release(); + }, + }; +} diff --git a/apps/server/test/remote-runner-startup.test.ts b/apps/server/test/remote-runner-startup.test.ts index a3196b5e5..0df6f5c05 100644 --- a/apps/server/test/remote-runner-startup.test.ts +++ b/apps/server/test/remote-runner-startup.test.ts @@ -34,7 +34,7 @@ const { reportIdentity, dial } = vi.hoisted(() => { }); // Exercise the real runner startup on every test platform. The kernel probe -// and TLS dial are the only external operations replaced by the test. +// and TLS dial are mocked along with the Linux session primitives. vi.mock("node:process", async (original) => { const { default: process } = await original(); return { @@ -53,6 +53,13 @@ vi.mock("node:tls", async (original) => ({ connect: dial, })); +vi.mock("../src/agents/remote/session-processes.js", async (original) => ({ + ...(await original< + typeof import("../src/agents/remote/session-processes.js") + >()), + createSessionProcesses: () => ({ acquire: () => () => {} }), +})); + import { runnerStorageKey, runRemoteRunner, diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts new file mode 100644 index 000000000..02826dbff --- /dev/null +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -0,0 +1,236 @@ +import { + mkdir, + mkdtemp, + readFile, + realpath, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + parseProcessStat, + type SessionIdentity, + type SessionProcesses, +} from "../src/agents/remote/session-processes.js"; +import { createSessionSupervisor } from "../src/agents/remote/session-supervisor.js"; + +type Supervisor = Awaited>; + +const marker = "DISPATCH_OWNED_00000000000000000000000000000000=1"; +const identity = { pid: 100, start: "500", scope: "boot:namespace", marker }; +const agentId = "agt_fixture"; +const launch = (workspace: string) => + ({ + kind: "launch", + agentId, + workspace, + launch: { engine: "codex" }, + }) as const; + +describe("runner session supervision", () => { + let root: string; + let state: string; + let record: string; + let supervisor: Supervisor | undefined; + let kernelHost: SessionIdentity | undefined; + let locked: boolean; + + const processes = { + acquire: vi.fn(() => { + if (locked) throw new Error("Already locked"); + locked = true; + return () => { + locked = false; + }; + }), + alive: vi.fn( + (record: SessionIdentity) => + record.scope === kernelHost?.scope && + record.pid === kernelHost.pid && + record.start === kernelHost.start + ), + stop: vi.fn(async (record: SessionIdentity) => { + if (processes.alive(record)) kernelHost = undefined; + }), + cleanup: vi.fn(async (_identity: SessionIdentity) => {}), + cleanupLegacy: vi.fn(async () => {}), + socketInUse: vi.fn(() => false), + spawn: vi.fn(), + } satisfies SessionProcesses; + + async function start(workspaces: string[]) { + supervisor = await createSessionSupervisor( + { + state, + uid: process.getuid!(), + gid: process.getgid!(), + ca: "ca", + bins: { claudeBin: "", codexBin: "" }, + env: {}, + workspaces: new Set(workspaces), + hostCommand: () => ["/test-host"], + asWorkload: vi.fn(), + }, + processes + ); + return supervisor; + } + + beforeEach(async () => { + vi.clearAllMocks(); + processes.socketInUse.mockReturnValue(false); + processes.spawn.mockImplementation( + async (_command, _cwd, _env, _log, save) => { + await save(identity); + expect(JSON.parse(await readFile(record, "utf8"))).toEqual(identity); + kernelHost = identity; + } + ); + kernelHost = undefined; + locked = false; + root = await mkdtemp(path.join(os.tmpdir(), "runner-supervisor-")); + state = path.join(await realpath(root), "state"); + record = path.join(state, "bindings", agentId + ".host"); + }); + + afterEach(async () => { + supervisor?.close(); + supervisor = undefined; + await rm(root, { recursive: true, force: true }); + }); + + it.each([ + { config: ["configured", "other"], workspace: "configured" }, + { config: [], workspace: "@session" }, + ])( + "rediscovers a $workspace host and stops it under the original binding", + async ({ config, workspace }) => { + const first = await start(config); + await first.launch(launch(workspace), root); + expect((await stat(record)).mode & 0o777).toBe(0o600); + + first.close(); + const recovered = await start(config); + expect(await recovered.alive(agentId, workspace)).toBe(true); + expect(await recovered.liveDirectories()).toEqual([ + path.join(state, "hosts", agentId), + ]); + await expect(recovered.launch(launch(workspace), root)).rejects.toThrow( + "already has a host" + ); + await expect(recovered.discard(agentId, workspace)).rejects.toThrow( + "Stop the guest host" + ); + if (config.length) { + expect(await recovered.alive(agentId, "other")).toBe(false); + await expect(recovered.stop(agentId, "other", true)).rejects.toThrow( + "not bound" + ); + await expect(recovered.attach(agentId, "other")).rejects.toThrow( + "not bound" + ); + } + expect(processes.spawn).toHaveBeenCalledTimes(1); + + await writeFile(path.join(state, "hosts", agentId, "host.pid"), "666\n"); + await recovered.stop(agentId, workspace, true); + expect(processes.stop).toHaveBeenCalledExactlyOnceWith(identity, true); + expect(processes.cleanup).toHaveBeenCalledExactlyOnceWith(identity); + expect(await recovered.liveDirectories()).toEqual([]); + await recovered.discard(agentId, workspace); + await expect( + stat(path.join(state, "hosts", agentId)) + ).rejects.toMatchObject({ code: "ENOENT" }); + if (!config.length) + await expect(recovered.launch(launch(workspace), root)).rejects.toThrow( + "archived" + ); + } + ); + + it("rejects a retry after launch was recorded but the receipt was lost", async () => { + const first = await start(["configured"]); + processes.spawn.mockImplementationOnce( + async (_command, _cwd, _env, _log, save) => { + await save(identity); + kernelHost = identity; + throw new Error("receipt lost"); + } + ); + await expect(first.launch(launch("configured"), root)).rejects.toThrow( + "receipt lost" + ); + first.close(); + + const recovered = await start(["configured"]); + await expect(recovered.launch(launch("configured"), root)).rejects.toThrow( + "already has a host" + ); + expect(await recovered.alive(agentId, "configured")).toBe(true); + expect(processes.spawn).toHaveBeenCalledTimes(1); + }); + + it("serializes overlapping launches and stops", async () => { + const running = await start(["configured"]); + const first = running.launch(launch("configured"), root); + const second = running.launch(launch("configured"), root); + const stopped = running.stop(agentId, "configured", false); + await expect(second).rejects.toThrow("already has a host"); + await first; + await stopped; + expect(processes.spawn).toHaveBeenCalledTimes(1); + expect(processes.stop).toHaveBeenCalledExactlyOnceWith(identity, false); + }); + + it("treats a recycled PID as stale and leaves an unrelated host running", async () => { + const running = await start(["configured"]); + await running.launch(launch("configured"), root); + const unrelated = { ...identity, start: "501" }; + kernelHost = unrelated; + expect(await running.alive(agentId, "configured")).toBe(false); + expect(await running.attach(agentId, "configured")).toBeNull(); + await running.stop(agentId, "configured", true); + expect(kernelHost).toBe(unrelated); + }); + + it("fences a legacy live socket and rejects a second supervisor", async () => { + const running = await start(["configured"]); + await expect(start(["configured"])).rejects.toThrow("Already locked"); + const hostDir = path.join(state, "hosts", agentId); + await mkdir(hostDir); + await writeFile(path.join(hostDir, "host.pid"), "100\n"); + processes.socketInUse.mockReturnValue(true); + await expect(running.launch(launch("configured"), root)).rejects.toThrow( + "cannot verify ownership" + ); + await expect(running.stop(agentId, "configured", true)).rejects.toThrow( + "cannot verify ownership" + ); + expect(processes.spawn).not.toHaveBeenCalled(); + expect(processes.stop).not.toHaveBeenCalled(); + }); + + it("leaves the durable record in place when cleanup fails", async () => { + const running = await start(["configured"]); + await running.launch(launch("configured"), root); + processes.cleanup.mockRejectedValueOnce(new Error("cleanup failed")); + await expect(running.stop(agentId, "configured", true)).rejects.toThrow( + "cleanup failed" + ); + await expect(stat(record)).resolves.toBeDefined(); + await running.stop(agentId, "configured", true); + await expect(stat(record)).rejects.toMatchObject({ code: "ENOENT" }); + }); +}); + +it("reads session and start time after a process name containing parentheses", () => { + const stat = "100 (process ) name) S 1 100 100 " + "0 ".repeat(15) + "500 0"; + expect(parseProcessStat(stat)).toEqual({ + session: 100, + start: "500", + dead: false, + }); +}); From 1f58f1ad428203aeeeaf81969e3eff4cda5f2b4f Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:09:44 -0700 Subject: [PATCH 077/642] Preserve workloads on daemon restarts and back off repeated reconnects --- apps/server/src/agents/remote/runner.ts | 24 +++++- apps/server/src/agents/remote/service.ts | 1 + .../server/test/remote-runner-startup.test.ts | 14 ++++ bin/dispatch-runner.service | 2 +- bin/install-dispatch-runner.sh | 31 ++++++-- docs/remote-runner-linux.md | 7 ++ e2e/remote-runner/acceptance.spec.ts | 73 +++++++++++++++++++ e2e/remote-runner/harness.ts | 15 +++- scripts/remote-runner/test-installer.sh | 7 ++ 9 files changed, 164 insertions(+), 10 deletions(-) diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 66ccc9cfa..b2d7d1698 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -27,6 +27,17 @@ import { type ManagedCommand, } from "./engine-runner-executor.js"; +/** Keep the first redial fast. Spread retries when many offline runners start together. */ +export function runnerReconnectDelay(random = Math.random) { + let windowMs = 1000; + return (connectedMs: number) => { + if (connectedMs >= 30_000) windowMs = 1000; + const delay = Math.round(windowMs * (0.5 + random() / 2)); + windowMs = Math.min(windowMs * 2, 30_000); + return delay; + }; +} + type RunnerConfig = { endpoint: string; ca: string; @@ -212,11 +223,15 @@ export async function runRemoteRunner(filename: string) { hostCommand: () => [setpriv, ...childArgs, ...hostCommand()], }); + const nextDelay = runnerReconnectDelay(); while (true) { - await new Promise((finished) => { + const connectedMs = await new Promise((finished) => { + let connectedAt: number | undefined; const socket = connect({ ...credentials, host, + keepAlive: true, + keepAliveInitialDelay: 30_000, port: Number(endpoint.port || 443), ...(isIP(host) ? {} : { servername: host }), rejectUnauthorized: true, @@ -264,7 +279,9 @@ export async function runRemoteRunner(filename: string) { clearTimeout(timeout); clearInterval(healthInterval); for (const channel of channels.values()) channel.destroy(); - finished(); + finished( + connectedAt === undefined ? 0 : performance.now() - connectedAt + ); }); const safeSend = (frame: RunnerFrame) => { if (!socket.destroyed) { @@ -425,6 +442,7 @@ export async function runRemoteRunner(filename: string) { else socket.destroy(); }); socket.once("secureConnect", () => { + connectedAt = performance.now(); clearTimeout(timeout); safeSend({ type: "ready", @@ -441,6 +459,6 @@ export async function runRemoteRunner(filename: string) { supervisor.close(); throw error; }); - await new Promise((resolve) => setTimeout(resolve, 1000)); + await new Promise((resolve) => setTimeout(resolve, nextDelay(connectedMs))); } } diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index d9769c1d8..e6ea0f714 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -617,6 +617,7 @@ export class RemoteRunnerService { } private attachPeer(socket: TLSSocket, gate: Gate) { + socket.setKeepAlive(true, 30_000); const deadline = setTimeout(() => socket.destroy(), 5000); let peer: Peer | undefined; socket.on("close", () => { diff --git a/apps/server/test/remote-runner-startup.test.ts b/apps/server/test/remote-runner-startup.test.ts index 0df6f5c05..eebf90ff4 100644 --- a/apps/server/test/remote-runner-startup.test.ts +++ b/apps/server/test/remote-runner-startup.test.ts @@ -63,6 +63,7 @@ vi.mock("../src/agents/remote/session-processes.js", async (original) => ({ import { runnerStorageKey, runRemoteRunner, + runnerReconnectDelay, } from "../src/agents/remote/runner.js"; it("preserves prototype storage while keeping opaque wire IDs out of paths", () => { @@ -284,3 +285,16 @@ describe("remote runner startup", () => { expect((await stat(key)).mode & 0o777).toBe(0o600); }); }); + +it("spreads failed dials, caps the delay and recovers quickly after a stable connection", () => { + for (const random of [0, 0.5, 1]) { + const next = runnerReconnectDelay(() => random); + const factor = (1 + random) / 2; + expect(Array.from({ length: 8 }, () => next(10))).toEqual( + [1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000].map( + (window) => window * factor + ) + ); + expect(next(30_000)).toBe(1000 * factor); + } +}); diff --git a/bin/dispatch-runner.service b/bin/dispatch-runner.service index 816c61517..f404a8bd2 100644 --- a/bin/dispatch-runner.service +++ b/bin/dispatch-runner.service @@ -9,7 +9,7 @@ ExecStart=/opt/dispatch-runner/dispatch remote-runner /etc/dispatch-runner/runne UMask=0077 Restart=on-failure RestartSec=5s -KillMode=control-group +KillMode=process Delegate=no [Install] diff --git a/bin/install-dispatch-runner.sh b/bin/install-dispatch-runner.sh index b3b5b663b..b618ec16d 100755 --- a/bin/install-dispatch-runner.sh +++ b/bin/install-dispatch-runner.sh @@ -90,6 +90,27 @@ CONFIG install -m 0600 "$stage/runner.json" "$config" } +# Replace only the exact prototype unit. Administrator customizations and +# drop-ins keep their usual systemd precedence. +install_service_unit() { + local replacement + tar -xOzf "$stage/dispatch-server.tar.gz" bin/dispatch-runner.service > "$stage/$unit" + [[ -s "$stage/$unit" ]] || error "Missing systemd service template from $tag" + if [[ -e "$unit_path" ]]; then + cmp -s "$stage/$unit" "$unit_path" && return 0 + sed 's/^KillMode=process$/KillMode=control-group/' "$stage/$unit" > "$stage/legacy-unit" + if ! cmp -s "$stage/legacy-unit" "$unit_path"; then + printf 'Keeping customized %s. Check its KillMode before testing daemon recovery.\n' "$unit_path" >&2 + return 0 + fi + fi + replacement=$(mktemp "${unit_path}.XXXXXX") + if ! install -m 0644 "$stage/$unit" "$replacement" || ! mv -fT "$replacement" "$unit_path"; then + rm -f -- "$replacement" + error "Could not install runner unit" + fi +} + install_runner() { local account_entry account_home account_shell if [[ -e "$command_path" || -L "$command_path" ]]; then @@ -129,11 +150,7 @@ install_runner() { install -m 0755 "$stage/dispatch" "$stage/initial" mv -fT "$stage/initial" "$runtime/dispatch" fi - tar -xOzf "$stage/dispatch-server.tar.gz" bin/dispatch-runner.service > "$stage/$unit" - [[ -s "$stage/$unit" ]] || error "Missing systemd service template from $tag" - if [[ ! -f "$unit_path" ]]; then - install -m 0644 "$stage/$unit" "$unit_path" - fi + install_service_unit tar -xOzf "$stage/dispatch-server.tar.gz" bin/install-dispatch-runner.sh > "$stage/updater" [[ -s "$stage/updater" ]] || error "Missing updater from $tag" chmod 0755 "$stage/updater" @@ -227,6 +244,8 @@ update_runner() { fi stage_release if cmp -s "$stage/dispatch" "$runtime/dispatch"; then + install_service_unit + systemctl daemon-reload printf 'Runner already has the requested release.\n' return fi @@ -245,6 +264,8 @@ update_runner() { fi rm -f -- "$runtime/previous" sync -f "$runtime" + install_service_unit + systemctl daemon-reload printf 'Runner updated to %s.\n' "$tag" } diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index 7e3725103..20ac71702 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -74,6 +74,13 @@ dedicated non-login `dispatch-runner` account. The workload account owns under `/etc/dispatch-runner` are root-only. The CA certificate is readable by the workload for its scoped Dispatch requests. The service is enabled at boot and the supervisor reconnects to Dispatch. +The managed service supervises connections. Its systemd unit signals only +the runner daemon on stop or restart. Active agent hosts can keep working +during that interval, and the next daemon reattaches to them. To shut down +all work on a machine, stop the agents in Dispatch while the runner is online, +then stop the unit. A machine reboot ends those processes. The updater still +checks the whole service cgroup and defers while workload processes remain. + Inspect startup logs with `sudo journalctl -u dispatch-runner.service`. For custom engine install paths, edit the `bins` object in `/etc/dispatch-runner/runner.json` as root and restart the service while idle. diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index 1f896e938..e6de7bb69 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -4,6 +4,8 @@ import { authHeaders, cleanupE2EAgents } from "../helpers"; import { agentInfo, chat, + crashRunner, + startRunner, enrollViaUi, revokeViaUi, guest, @@ -206,6 +208,48 @@ test("permission decisions stay on their runner across a disconnect", async ({ ).toBe(false); }); +test("runner supervisor restarts mid-turn and reattaches to the original host", async ({ + request, +}, testInfo) => { + const page = pages.beta!; + const pidFile = `/var/lib/runner/hosts/${agents.beta}/host.pid`; + const pid = guest("beta", `cat ${pidFile}`).trim(); + expect(pid).toMatch(/^[1-9][0-9]*$/); + const before = invocations("beta"); + const turns = await settledTurns(page).count(); + await chat(page, "proof-delay:12000 proof-count supervisor-restart"); + await expect(answers(page, "Guest turn waiting for reconnect.")).toBeVisible({ + timeout: 30_000, + }); + crashRunner("beta"); + await expect + .poll(async () => (await runnerRow(request, "beta"))?.status) + .toBe("offline"); + expect(guestOk("beta", `kill -0 ${pid}`)).toBe(true); + startRunner("beta"); + await expect + .poll(async () => (await runnerRow(request, "beta"))?.status, { + timeout: 30_000, + }) + .toBe("online"); + await expect(settledTurns(page)).toHaveCount(turns + 1, { timeout: 60_000 }); + await expect( + answers(page, "Guest turn completed after reconnect.") + ).toHaveCount(1); + expect(invocations("beta")).toBe(before + 1); + expect(guest("beta", `cat ${pidFile}`).trim()).toBe(pid); + await newSettledTurn( + page, + "proof-count after-supervisor-restart", + "Local or guest fixture turn completed." + ); + expect(invocations("beta")).toBe(before + 2); + await testInfo.attach("runner supervisor recovered", { + body: await page.screenshot(), + contentType: "image/png", + }); +}); + test("disconnect alpha mid-turn: others continue; reconnect gives one invocation and one completion", async ({ request, }, testInfo) => { @@ -352,10 +396,12 @@ test.describe("failure suite", () => { request, }) => { const before = invocations("beta"); + const previous = await settledTurns(pages.beta!).count(); await chat(pages.beta!, "proof-delay:12000 proof-count flap"); await expect( answers(pages.beta!, "Guest turn waiting for reconnect.").last() ).toBeVisible({ timeout: 30_000 }); + await expect.poll(() => invocations("beta")).toBe(before + 1); for (let i = 0; i < 3; i++) { await lane("beta", "sever"); await new Promise((r) => setTimeout(r, 1500)); @@ -368,6 +414,9 @@ test.describe("failure suite", () => { await expect( answers(pages.beta!, "Guest turn completed after reconnect.").last() ).toBeVisible({ timeout: 60_000 }); + await expect(settledTurns(pages.beta!)).toHaveCount(previous + 1, { + timeout: 60_000, + }); expect(invocations("beta")).toBe(before + 1); }); @@ -430,6 +479,30 @@ test("managed scratch launch reports health and archive removes the guest sessio "called" ); + const scratchPid = guest( + "scratch", + `cat /var/lib/runner/hosts/${id}/host.pid` + ).trim(); + expect(scratchPid).toMatch(/^[1-9][0-9]*$/); + crashRunner("scratch"); + await expect + .poll(async () => (await runnerRow(request, "scratch"))?.status) + .toBe("offline"); + startRunner("scratch"); + await expect + .poll(async () => (await runnerRow(request, "scratch"))?.status, { + timeout: 30_000, + }) + .toBe("online"); + await newSettledTurn( + page, + "proof-count after-scratch-recovery", + "Local or guest fixture turn completed." + ); + expect( + guest("scratch", `cat /var/lib/runner/hosts/${id}/host.pid`).trim() + ).toBe(scratchPid); + await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); const health = page .getByTestId(`runner-${runnerId}`) diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 9a9c541a2..7524fdc10 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -209,7 +209,20 @@ export function startRunner(name: GuestName) { state.runners[name].container, "sh", "-c", - "/opt/bin/dispatch-runner remote-runner /run/cfg/runner.json >/var/log/runner.log 2>&1" + "echo $$ > /run/runner-fixture.pid; exec /opt/bin/dispatch-runner remote-runner /run/cfg/runner.json >>/var/log/runner.log 2>&1" + ); +} + +/** Crash only the fixture supervisor. Its independent ACP process stays alive. */ +export function crashRunner(name: GuestName) { + guest( + name, + `set -eu + pid=$(cat /run/runner-fixture.pid) + test "$pid" -gt 1 + test "$(readlink /proc/$pid/exe)" = /opt/bin/dispatch-runner + test "$(tr '\\000' ' ' "$root/legacy-unit" +cp "$root/legacy-unit" "$root/dispatch-runner.service" run update v1.0.1 +grep -qx 'KillMode=process' "$root/dispatch-runner.service" +printf '# administrator setting\n' >> "$root/dispatch-runner.service" +run update v1.0.1 +grep -qx '# administrator setting' "$root/dispatch-runner.service" grep -q 'release-new x64' "$root/runtime/dispatch" [[ ! -e "$root/running" && ! -e "$root/settings/key.pem" ]] From d759a3017b64a23fdbaa65f0c3097c4a490a30a0 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:08:16 -0700 Subject: [PATCH 078/642] Bound runner log reads and document supervisor compatibility --- .../src/agents/remote/session-processes.ts | 4 ++ .../src/agents/remote/session-supervisor.ts | 26 ++++++++-- .../test/remote-runner-supervisor.test.ts | 50 ++++++++++++++++++- docs/remote-runner-linux.md | 10 +++- 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/apps/server/src/agents/remote/session-processes.ts b/apps/server/src/agents/remote/session-processes.ts index 0324a44ab..c67ae8b71 100644 --- a/apps/server/src/agents/remote/session-processes.ts +++ b/apps/server/src/agents/remote/session-processes.ts @@ -16,6 +16,10 @@ import type { WorkloadCommand } from "./session-storage.js"; type Kernel = ReturnType; function linuxKernel() { + if (!process.versions.bun) + throw new Error( + "Runner session supervision requires the Bun runtime. Use the compiled Dispatch Linux binary." + ); // These two supported Linux architectures share the pidfd_send_signal ABI. if (process.arch !== "arm64" && process.arch !== "x64") throw new Error("Runner session supervision requires arm64 or x64 Linux."); diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 345c210d6..9380f4aa5 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -63,6 +63,26 @@ const managedBinding = "\0managed"; const readOptional = (file: string) => readFile(file, "utf8").catch(missingPath); +const logTailBytes = 2 * 1024; + +async function readLogTail(file: string) { + const handle = await open(file, "r").catch(missingPath); + if (!handle) return ""; + try { + const { size } = await handle.stat(); + const start = Math.max(0, size - logTailBytes); + const tail = Buffer.alloc(size - start); + const { bytesRead } = await handle.read(tail, 0, tail.length, start); + let first = 0; + // The window may start inside a UTF-8 code point. + while (start > 0 && first < bytesRead && (tail[first]! & 0xc0) === 0x80) + first++; + return tail.toString("utf8", first, bytesRead); + } finally { + await handle.close(); + } +} + async function ownedDirectory(dir: string, mode: number) { const entry = await lstat(dir); if ( @@ -483,10 +503,8 @@ export async function createSessionSupervisor( throw new Error("Agent is not bound to this workspace"); const identity = await readIdentity(key); const live = identity && processes.alive(identity); - const log = await readFile(path.join(logs, key), "utf8").catch( - missingPath - ); - return `Guest agent host ${live ? "log" : "exited"}.${log ? "\n" + log.slice(-2048) : ""}`; + const log = await readLogTail(path.join(logs, key)); + return `Guest agent host ${live ? "log" : "exited"}.${log ? "\n" + log : ""}`; }, async isBound(agentId: string, workspace: string) { return bound(runnerStorageKey(agentId), workspace); diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index 02826dbff..b6a65e03d 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -1,6 +1,7 @@ import { mkdir, mkdtemp, + open, readFile, realpath, rm, @@ -56,7 +57,7 @@ describe("runner session supervision", () => { if (processes.alive(record)) kernelHost = undefined; }), cleanup: vi.fn(async (_identity: SessionIdentity) => {}), - cleanupLegacy: vi.fn(async () => {}), + cleanupLegacy: vi.fn(async (_marker: string) => {}), socketInUse: vi.fn(() => false), spawn: vi.fn(), } satisfies SessionProcesses; @@ -213,6 +214,53 @@ describe("runner session supervision", () => { expect(processes.stop).not.toHaveBeenCalled(); }); + it.each([ + { + config: ["configured", "other"], + workspace: "configured", + binding: "configured", + }, + { config: [], workspace: "@session", binding: "\0managed" }, + ])( + "reuses an idle legacy $workspace binding", + async ({ config, workspace, binding }) => { + const running = await start(config); + const bindings = path.join(state, "bindings"); + await writeFile(path.join(bindings, agentId), binding, { mode: 0o600 }); + if (config.length === 0) { + await writeFile(path.join(bindings, agentId + ".owner"), marker, { + mode: 0o600, + }); + await writeFile(path.join(bindings, agentId + ".repository"), "null", { + mode: 0o600, + }); + } + expect(await running.alive(agentId, workspace)).toBe(false); + await running.launch(launch(workspace), root); + expect(await running.alive(agentId, workspace)).toBe(true); + expect(processes.cleanupLegacy.mock.calls).toEqual( + config.length ? [] : [[marker]] + ); + } + ); + + it("reads a bounded UTF-8 tail from a large guest log", async () => { + const running = await start(["configured"]); + await running.launch(launch("configured"), root); + const log = await open(path.join(state, "bindings", "logs", agentId), "r+"); + const expected = "x".repeat(2044) + "✓"; + try { + // A sparse offset beyond Node's whole-file read limit leaves the actual + // disk usage small. The 2 KiB tail starts within the preceding emoji. + await log.write("🚀" + expected, 2 ** 31, "utf8"); + } finally { + await log.close(); + } + expect(await running.log(agentId, "configured")).toBe( + "Guest agent host log.\n" + expected + ); + }); + it("leaves the durable record in place when cleanup fails", async () => { const running = await start(["configured"]); await running.launch(launch("configured"), root); diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index 20ac71702..78459e393 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -2,10 +2,13 @@ Use a supported Dispatch release and a Linux x86-64 or ARM64 host with systemd, the unified cgroup v2 hierarchy, and systemd's `freeze` and `thaw` commands. -Install Git, procps (ps), findutils, Bash, curl, tar, util-linux (including `/usr/bin/setpriv` and `flock`), +Install Git, GNU grep, procps (ps), findutils, Bash, curl, tar, util-linux (including `/usr/bin/setpriv` and `flock`), `useradd`, GNU coreutils, and a GitHub CLI with `gh attestation verify --bundle`. GitHub CLI verifies the published bundles without a GitHub login. The runner must be able to reach the HTTPS address in the pairing command. +The published binary bundles Bun and runs on glibc-based Linux. Session +supervision requires a kernel with pidfd signaling (introduced in Linux 5.1). +For manual source runs, use Bun. 1. In Dispatch, open **Settings → Connections → Remote runners** and run the installation command for the available release. The installer @@ -116,7 +119,10 @@ ended. On an idle runner it retains the previous executable, atomically replaces the live executable, and checks that the replacement service survives startup. The runner's **Online** status in Settings confirms reconnection. If startup fails, the updater restores the previous executable and starts it. -Updates preserve the enrollment, settings, and workload state. Updating before +Updates preserve the enrollment, settings, configured workspace bindings and +managed checkouts. Host recovery starts with sessions launched by a +restart-aware supervisor. For a manual upgrade from an older runner, stop +its sessions with the old supervisor before replacing it. Updating before connect keeps the service stopped. If an update was interrupted, run: From 9f0022a2af08a9f39a2f26a6d640150441cbfdb4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:13:21 -0700 Subject: [PATCH 079/642] Document runner lifetime boundaries and restart conformance coverage --- docs/design/remote-runner-prototype.md | 8 ++++---- packages/runner-protocol/README.md | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index df8afdbb1..bac65d213 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -267,9 +267,9 @@ The Lima slice supports bounded operations for launching, attaching, prompting, permissions, stopping, and invoking an approved repo tool. It supports trying the same Linux artifact on a second host. General scheduling, checkout provisioning, arbitrary repo tool manifests, file transfer and git views are still machine-local -features outside this slice. The implementation supports one manually enrolled -runner and pre-provisioned standalone workspaces. Full restart recovery of the -runner daemon itself requires work beyond the service and network reconnect -tested here. The guest connection uses Lima's host-loopback reachability and +features outside this slice. This original Lima run used one manually enrolled runner and a pre-provisioned +workspace. The current Linux runner also recovers live hosts across daemon +restarts. The multi-runner acceptance suite kills the daemon during a turn +and checks the host PID, provider invocation count and visible completion. The guest connection uses Lima's host-loopback reachability and establishes process and filesystem separation. Subsequent Cloudy and scoped Hangar runs are recorded in the [implementation handoff](remote-runner-handoff.md). diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index bc6fe62be..6539a3413 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -51,6 +51,7 @@ For changes beyond the portable contract, the implementation tests in | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | Pair, approve, rotate or revoke | `remote-runner-connect` and `remote-runner-enrollment` use a test registry and local TLS peers. | | Start a workload, allocate a session or check out a repository | `remote-runner-startup`, `remote-session-storage` and `runner-repositories` cover host configuration and filesystem behavior. | +| Reattach or stop a host after the runner daemon restarts | `remote-runner-supervisor` tests binding, process identity, and cleanup independently of TLS. | | Record and recover received events | `remote-event-inbox` exercises the durable cursor and payload together. | | Report health or manage an engine | `runner-health`, `engine-manager` and `engine-runner-executor` exercise sampling, routing and workload execution. | @@ -122,7 +123,9 @@ those binaries. | `engine` | JSON-encoded `EngineOperationAck` | Newline-delimited `EngineOperationEvent` records in base64 data frames | An agent command addresses its bound workspace. Engine management is -runner-wide. Its v1 envelope still carries an advertised workspace and an +runner-wide. Dispatch callers use `requestSession(placement, operation)` or +`requestRunner(runnerId, operation)`. Only the v1 adapter fills in the routing +fields for runner-wide operations. The engine command’s v1 envelope still carries an advertised workspace and an agent ID placeholder. Gate it on the runner's `engineManagement` capability. An execution error uses `result.error`. An attach to a known missing host @@ -134,6 +137,16 @@ The portable session types cover commands received by the host, journal replay, and prompt receipts. Dispatch-specific host replies and event payloads are defined in `apps/server/src/agents/acp/host-protocol.ts`. +### Surviving a daemon restart + +On Linux, the runner's session supervisor records each new host's identity +before allowing it to start the engine. That record belongs to the runner, +survives its TLS connection, and identifies the process within its boot and +PID namespace. A replacement daemon can attach to the same host and journal. +A host that exited, or a machine that rebooted, follows the host-loss path. +When a prompt's outcome is unknown, the service needs a receipt or journal +evidence before deciding whether another delivery is safe. + ## Receipts and replay | Signal | Meaning | From e5a8244f12ec407f9e7d5c72a2bcf45aef59943b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:14:25 -0700 Subject: [PATCH 080/642] Bound enrollment HTTP response bodies --- apps/server/src/agents/remote/enrollment.ts | 37 +++++-- .../server/test/remote-runner-connect.test.ts | 100 ++++++++++++++++++ 2 files changed, 129 insertions(+), 8 deletions(-) diff --git a/apps/server/src/agents/remote/enrollment.ts b/apps/server/src/agents/remote/enrollment.ts index eea1b1e73..207ed5e3b 100644 --- a/apps/server/src/agents/remote/enrollment.ts +++ b/apps/server/src/agents/remote/enrollment.ts @@ -470,6 +470,8 @@ async function fetchPinnedCa( ); } +const MAX_ENROLLMENT_RESPONSE_BYTES = 64 * 1024; + /** * One HTTPS request to the service. With `pin`, first confirms the pinned * CA over the runner listener's own wire-protocol bootstrap (see @@ -506,10 +508,6 @@ async function requestJson( if (error) reject(error); else resolve(value); }; - const timer = setTimeout(() => { - request.destroy(); - finish(new Error("The request to the service timed out.")); - }, timeoutMs); const request = https.request( { hostname, @@ -534,11 +532,30 @@ async function requestJson( : { rejectUnauthorized: true }), }, (response) => { - let data = ""; - response.on("data", (chunk) => (data += chunk)); - response.on("end", () => { + const chunks: Buffer[] = []; + let size = 0; + const interrupted = () => + finish(new Error("The service interrupted its response.")); + response.once("aborted", interrupted); + response.on("error", interrupted); + response.once("close", interrupted); + response.on("data", (chunk: Buffer) => { + if (settled) return; + size += chunk.length; + if (size > MAX_ENROLLMENT_RESPONSE_BYTES) { + finish(new Error("The service response is too large.")); + request.destroy(); + return; + } + chunks.push(chunk); + }); + response.once("end", () => { + if (settled) return; let parsed: unknown; try { + const data = new TextDecoder("utf-8", { fatal: true }).decode( + Buffer.concat(chunks, size) + ); parsed = data ? JSON.parse(data) : undefined; } catch { return finish( @@ -560,7 +577,11 @@ async function requestJson( }); } ); - request.on("error", (error) => finish(error as Error)); + const timer = setTimeout(() => { + finish(new Error("The request to the service timed out.")); + request.destroy(); + }, timeoutMs); + request.on("error", (error) => finish(error)); // Bun starts the HTTPS request on end(). TLS verifies the endpoint // hostname and certificate chain against the selected CA before sending. request.end(payload); diff --git a/apps/server/test/remote-runner-connect.test.ts b/apps/server/test/remote-runner-connect.test.ts index 7f78519b9..857d1592d 100644 --- a/apps/server/test/remote-runner-connect.test.ts +++ b/apps/server/test/remote-runner-connect.test.ts @@ -545,3 +545,103 @@ describe("connect command shell safety", () => { ).rejects.toThrow(/--approval-url must be an http\(s\) URL/); }); }); + +describe("connect HTTP response body", () => { + async function expectFailure( + respond: (socket: TLSSocket) => void, + message: string + ) { + const authority = issueAuthority("response fixture"); + const leaf = issueServer(authority, [HOST]); + const sockets = new Set(); + const server = createServer( + { cert: leaf.cert + authority.cert, key: leaf.key }, + (socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + socket.on("error", () => {}); + let request = ""; + const receive = (chunk: Buffer) => { + request += chunk.toString("utf8"); + if (request.startsWith("{")) { + if (!request.includes("\n")) return; + socket.off("data", receive); + socket.end( + JSON.stringify({ type: "ca", ca: authority.cert }) + "\n" + ); + } else if (request.includes("\r\n\r\n")) { + socket.off("data", receive); + respond(socket); + } + }; + socket.on("data", receive); + } + ); + const dir = await mkdtemp(path.join(tmpdir(), "connect-response-")); + try { + await new Promise((resolve) => server.listen(0, HOST, resolve)); + const { port } = server.address() as AddressInfo; + const pin = new X509Certificate(authority.cert).fingerprint256.replaceAll( + ":", + "" + ); + await expect( + runRunnerConnect([ + `https://${HOST}:${port}`, + "--ca-sha256", + pin, + "--dir", + dir, + ]) + ).rejects.toThrow(message); + expect(await readdir(dir)).toEqual([]); + } finally { + for (const socket of sockets) socket.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + await rm(dir, { force: true, recursive: true }); + } + } + + const chunked = (status: string) => + `HTTP/1.1 ${status}\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n`; + + function writeChunk(socket: TLSSocket, chunk: Buffer) { + socket.write(chunk.length.toString(16) + "\r\n"); + socket.write(chunk); + socket.write("\r\n"); + } + + it("rejects a response interrupted before the declared body is complete", async () => { + await expectFailure((socket) => { + const partial = JSON.stringify({ + id: "fixture-id", + code: "TEST-CODE", + expiresAt: "2099-01-01T00:00:00Z", + }); + socket.end( + `HTTP/1.1 201 Created\r\nContent-Length: ${Buffer.byteLength(partial) + 1}\r\nConnection: close\r\n\r\n${partial}` + ); + }, "The service interrupted its response."); + }, 5_000); + + it("rejects a chunked response once its total byte count exceeds 64 KiB", async () => { + await expectFailure((socket) => { + socket.write(chunked("201 Created")); + const chunk = Buffer.from("é".repeat(20 * 1024)); + writeChunk(socket, chunk); + writeChunk(socket, chunk); + // Leave the response open so waiting for end would hang. + }, "The service response is too large."); + }, 5_000); + + it("preserves a multibyte character split across response chunks", async () => { + await expectFailure((socket) => { + const body = Buffer.from(JSON.stringify({ error: "Service says 🧪" })); + const split = body.indexOf(Buffer.from("🧪")) + 2; + socket.write(chunked("400 Bad Request")); + writeChunk(socket, body.subarray(0, split)); + writeChunk(socket, body.subarray(split)); + socket.end("0\r\n\r\n"); + }, "Service says 🧪"); + }); +}); From 598070c197cc58fd52dca694bbf26ad4f72324ed Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 20:27:39 -0700 Subject: [PATCH 081/642] Reattach a live remote host before submitting the first prompt after recovery --- apps/server/src/agents/acp/runtime.ts | 354 +++++++++++---------- apps/server/test/acp-runtime-queue.test.ts | 37 +++ 2 files changed, 229 insertions(+), 162 deletions(-) diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 4babc8949..96605274a 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -25,7 +25,11 @@ import type { import type { AppConfig } from "../../config.js"; import type { DriverEvent } from "./driver.js"; -import type { PromptImage, PromptSource } from "./prompt-source.js"; +import type { + PromptImage, + PromptSource, + PromptOptions, +} from "./prompt-source.js"; import type { AgentRuntime, RuntimeEventListener, @@ -369,7 +373,7 @@ function sourceBlockIds(source?: PromptSource): string[] { } export type AcpRuntimeDeps = { - remote?: RemoteRunnerService; + remote?: Pick; remoteInbox?: Pick; recoverRemoteEvent?: (agentId: string) => Promise; placement?: (agentId: string) => Promise; @@ -949,6 +953,170 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { } } + function enqueuePrompt( + entry: Live, + agentId: string, + text: string, + source?: PromptSource, + opts?: PromptOptions + ) { + let resolveAccepted!: () => void; + let rejectAccepted!: (err: Error) => void; + const accepted = new Promise((resolve, reject) => { + resolveAccepted = resolve; + rejectAccepted = reject; + }); + let resolveSettled!: () => void; + const settled = new Promise((resolve) => { + resolveSettled = resolve; + }).finally(() => { + entry.pending -= 1; + }); + const own: Waiting = { + text, + ...(opts?.beforeSubmit ? { beforeSubmit: opts.beforeSubmit } : {}), + ...(opts?.onDeferred ? { onDeferred: opts.onDeferred } : {}), + ...(opts?.signal ? { signal: opts.signal } : {}), + ...(opts?.images?.length ? { images: opts.images } : {}), + ...(source ? { source } : {}), + alone: + opts?.delivery === "interrupt" || + opts?.alone === true || + source?.source !== "chat", + // Steering accepts text only. Keep images for the next ordinary turn. + delivery: + opts?.delivery === "interrupt" + ? "interrupt" + : opts?.images?.length + ? "queue" + : (opts?.delivery ?? "queue"), + taken: false, + resolveAccepted, + rejectAccepted, + resolveSettled, + cancelled: false, + interruptTargetSeq: entry.turnSeq, + interruptHandled: + !entry.turnOpen || + (entry.turnSeq !== undefined && + entry.interruptedTurnSeq === entry.turnSeq), + }; + if (own.delivery === "interrupt") { + const firstOrdinary = entry.waiting.findIndex( + (w) => w.delivery !== "interrupt" + ); + entry.waiting.splice( + firstOrdinary < 0 ? entry.waiting.length : firstOrdinary, + 0, + own + ); + } else if (isUserPost(own)) { + // A person's post goes ahead of queued agent and system traffic, + // behind interrupts and the person's own earlier posts. A deferred + // batch put back at the front may sit ahead of those posts. + let after = entry.waiting.length; + while (after > 0 && !isUserPost(entry.waiting[after - 1]!)) after--; + const firstOther = entry.waiting.findIndex( + (w, i) => i >= after && w.delivery !== "interrupt" && !isUserPost(w) + ); + entry.waiting.splice( + firstOther < 0 ? entry.waiting.length : firstOther, + 0, + own + ); + } else { + entry.waiting.push(own); + } + entry.pending += 1; + if ( + deps.classifySteering && + own.delivery === "auto" && + isUserPost(own) && + !own.source?.steeringExcluded && + !own.source?.awaited && + !own.source?.scheduleId && + !own.images?.length && + entry.turnOpen && + entry.turnSeq !== undefined && + entry.conversation && + entry.client.welcome?.steeringSupported && + source?.source === "chat" + ) { + const state: NonNullable = { + seq: entry.turnSeq, + controller: new AbortController(), + pending: true, + decision: undefined as SteeringDecision | undefined, + }; + own.steering = state; + const timer = setTimeout(() => { + if (own.steering !== state) return; + finishDecision(own, "expired"); + void pump(agentId, entry); + }, 3000); + void deps + .classifySteering({ + agentId, + messageId: source.chatMessageId, + turnSeq: state.seq, + activeMessageIds: [...entry.turnBlockIds], + conversation: entry.conversation, + defaultSteers: steers(own, entry), + signal: state.controller.signal, + }) + .then((decision) => { + if ( + own.steering !== state || + live.get(agentId) !== entry || + !entry.turnOpen || + entry.turnSeq !== state.seq || + own.taken + ) { + decision?.finish(state.outcome ?? "expired"); + return; + } + state.pending = false; + state.decision = decision; + if (decision?.valid() && decision.choice === "queue_next") + decision.finish("queued"); + if (decision?.choice === "keep_existing_default") + decision.finish("default"); + }) + .catch(() => { + if (own.steering === state) state.pending = false; + }) + .finally(() => { + clearTimeout(timer); + void pump(agentId, entry); + }); + } + if (opts?.signal) { + const discard = () => { + if (own.taken) return; + const index = entry.waiting.indexOf(own); + if (index < 0) return; + entry.waiting.splice(index, 1); + finishDecision(own, "overridden"); + own.cancelled = true; + own.rejectAccepted( + Object.assign( + new Error("Scheduled delivery cancelled before submission."), + { name: "ScheduledDeliveryCancelledError" } + ) + ); + own.resolveSettled(); + }; + opts.signal.addEventListener("abort", discard, { once: true }); + void settled.finally(() => + opts.signal?.removeEventListener("abort", discard) + ); + if (opts.signal.aborted) discard(); + } + accepted.catch(() => {}); + void pump(agentId, entry); + return { accepted, settled }; + } + runtime = { tracksProcesses: () => true, async getBackgroundWork(agentId) { @@ -1168,167 +1336,29 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { prompt(agentId, text, source, opts) { const entry = live.get(agentId); - if (!entry) { - const err = new Error( - "The agent is not running; the prompt cannot be delivered." - ); - return { accepted: Promise.reject(err), settled: Promise.reject(err) }; - } - let resolveAccepted!: () => void; - let rejectAccepted!: (err: Error) => void; - const accepted = new Promise((resolve, reject) => { - resolveAccepted = resolve; - rejectAccepted = reject; - }); - let resolveSettled!: () => void; - const settled = new Promise((resolve) => { - resolveSettled = resolve; - }).finally(() => { - entry.pending -= 1; - }); - const own: Waiting = { - text, - ...(opts?.beforeSubmit ? { beforeSubmit: opts.beforeSubmit } : {}), - ...(opts?.onDeferred ? { onDeferred: opts.onDeferred } : {}), - ...(opts?.signal ? { signal: opts.signal } : {}), - ...(opts?.images?.length ? { images: opts.images } : {}), - ...(source ? { source } : {}), - alone: - opts?.delivery === "interrupt" || - opts?.alone === true || - source?.source !== "chat", - // Steering accepts text only. Keep images for the next ordinary turn. - delivery: - opts?.delivery === "interrupt" - ? "interrupt" - : opts?.images?.length - ? "queue" - : (opts?.delivery ?? "queue"), - taken: false, - resolveAccepted, - rejectAccepted, - resolveSettled, - cancelled: false, - interruptTargetSeq: entry.turnSeq, - interruptHandled: - !entry.turnOpen || - (entry.turnSeq !== undefined && - entry.interruptedTurnSeq === entry.turnSeq), - }; - if (own.delivery === "interrupt") { - const firstOrdinary = entry.waiting.findIndex( - (w) => w.delivery !== "interrupt" - ); - entry.waiting.splice( - firstOrdinary < 0 ? entry.waiting.length : firstOrdinary, - 0, - own - ); - } else if (isUserPost(own)) { - // A person's post goes ahead of queued agent and system traffic, - // behind interrupts and the person's own earlier posts. A deferred - // batch put back at the front may sit ahead of those posts. - let after = entry.waiting.length; - while (after > 0 && !isUserPost(entry.waiting[after - 1]!)) after--; - const firstOther = entry.waiting.findIndex( - (w, i) => i >= after && w.delivery !== "interrupt" && !isUserPost(w) - ); - entry.waiting.splice( - firstOther < 0 ? entry.waiting.length : firstOther, - 0, - own - ); - } else { - entry.waiting.push(own); - } - entry.pending += 1; - if ( - deps.classifySteering && - own.delivery === "auto" && - isUserPost(own) && - !own.source?.steeringExcluded && - !own.source?.awaited && - !own.source?.scheduleId && - !own.images?.length && - entry.turnOpen && - entry.turnSeq !== undefined && - entry.conversation && - entry.client.welcome?.steeringSupported && - source?.source === "chat" - ) { - const state: NonNullable = { - seq: entry.turnSeq, - controller: new AbortController(), - pending: true, - decision: undefined as SteeringDecision | undefined, - }; - own.steering = state; - const timer = setTimeout(() => { - if (own.steering !== state) return; - finishDecision(own, "expired"); - void pump(agentId, entry); - }, 3000); - void deps - .classifySteering({ - agentId, - messageId: source.chatMessageId, - turnSeq: state.seq, - activeMessageIds: [...entry.turnBlockIds], - conversation: entry.conversation, - defaultSteers: steers(own, entry), - signal: state.controller.signal, - }) - .then((decision) => { - if ( - own.steering !== state || - live.get(agentId) !== entry || - !entry.turnOpen || - entry.turnSeq !== state.seq || - own.taken - ) { - decision?.finish(state.outcome ?? "expired"); - return; - } - state.pending = false; - state.decision = decision; - if (decision?.valid() && decision.choice === "queue_next") - decision.finish("queued"); - if (decision?.choice === "keep_existing_default") - decision.finish("default"); - }) - .catch(() => { - if (own.steering === state) state.pending = false; - }) - .finally(() => { - clearTimeout(timer); - void pump(agentId, entry); - }); - } - if (opts?.signal) { - const discard = () => { - if (own.taken) return; - const index = entry.waiting.indexOf(own); - if (index < 0) return; - entry.waiting.splice(index, 1); - finishDecision(own, "overridden"); - own.cancelled = true; - own.rejectAccepted( - Object.assign( - new Error("Scheduled delivery cancelled before submission."), - { name: "ScheduledDeliveryCancelledError" } - ) + const pending = connecting.get(agentId); + if (entry && (!entry.remote || !pending)) + return enqueuePrompt(entry, agentId, text, source, opts); + + // Dispatch may finish starting while an already running remote host is + // still reconnecting. Attach before the first send, sharing any replay + // already under way. This path never retries a submitted prompt. + const delivery = (async () => { + if (!deps.remote || !(await placementOf(agentId))) + throw new Error( + "The agent is not running; the prompt cannot be delivered." ); - own.resolveSettled(); - }; - opts.signal.addEventListener("abort", discard, { once: true }); - void settled.finally(() => - opts.signal?.removeEventListener("abort", discard) - ); - if (opts.signal.aborted) discard(); - } - accepted.catch(() => {}); - void pump(agentId, entry); - return { accepted, settled }; + const host = await (pending ?? connect(agentId, ATTACH_TIMEOUT_MS)); + if (live.get(agentId) !== host) + throw new Error( + "The agent host disconnected before prompt submission." + ); + return enqueuePrompt(host, agentId, text, source, opts); + })(); + return { + accepted: delivery.then((result) => result.accepted), + settled: delivery.then((result) => result.settled), + }; }, controlQueuedPrompt(agentIds, blockId, action) { diff --git a/apps/server/test/acp-runtime-queue.test.ts b/apps/server/test/acp-runtime-queue.test.ts index b2d3d9f32..8f2c0c5be 100644 --- a/apps/server/test/acp-runtime-queue.test.ts +++ b/apps/server/test/acp-runtime-queue.test.ts @@ -80,8 +80,11 @@ async function fastFailingHost(): Promise<{ running: true, turn: null, journalSeq: seq, + ...(message.replayComplete && { journalId: "fixture-journal" }), } satisfies HostMessage) ); + if (message.replayComplete) + socket.write(encodeMessage({ type: "replay_complete" })); } else if (message.type === "prompt") { prompts.push(message.text); socket.write( @@ -120,6 +123,40 @@ async function fastFailingHost(): Promise<{ } describe("AcpRuntime prompt queue", () => { + it("attaches a surviving remote host on the first prompt after service startup", async () => { + const { stateRoot, prompts } = await fastFailingHost(); + const placement = { runner: "test-runner", workspace: "proof" }; + // The host already exists, while the new service has no runtime entry. + const requestSession = vi.fn(async (target, operation) => { + if (operation.kind === "discard") + return { value: true, channel: undefined }; + expect(target).toEqual(placement); + expect(operation).toEqual({ kind: "attach", agentId }); + return { + value: true, + channel: net.createConnection( + hostFile(path.join(stateRoot, agentId), "socket") + ), + }; + }); + const runtime = createAcpRuntime({ + config: { + agentStateRoot: stateRoot, + agentRuntime: "acp", + dispatchApiUrl: "https://test.invalid", + } as Parameters[0]["config"], + logger, + hostSeq: async () => ({ seq: 0, journalId: null }), + placement: async () => placement, + remote: { requestSession, available: () => true }, + }); + const delivery = runtime.prompt(agentId, "during service recovery"); + await Promise.all([delivery.accepted, delivery.settled]); + expect(requestSession).toHaveBeenCalledTimes(1); + expect(prompts).toEqual(["during service recovery"]); + await runtime.discard(agentId); + }); + it("takes the next prompt after a turn whose ack and settle arrive together", async () => { const { stateRoot, prompts } = await fastFailingHost(); const runtime = createAcpRuntime({ From 8058bef236275b3712a72cfc543cca1a2ec66c50 Mon Sep 17 00:00:00 2001 From: Dispatch Field Test Date: Thu, 19 Nov 2026 04:01:31 +0000 Subject: [PATCH 082/642] Explain runner state lock contention --- apps/server/src/agents/remote/session-processes.ts | 10 +++++++++- apps/server/test/remote-runner-supervisor.test.ts | 10 ++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/server/src/agents/remote/session-processes.ts b/apps/server/src/agents/remote/session-processes.ts index c67ae8b71..1d844c4e5 100644 --- a/apps/server/src/agents/remote/session-processes.ts +++ b/apps/server/src/agents/remote/session-processes.ts @@ -15,6 +15,14 @@ import type { WorkloadCommand } from "./session-storage.js"; type Kernel = ReturnType; +export function runnerStateLockError(code: number): Error { + if (code === 11) + return new Error( + "Another runner daemon is already using this state directory. Stop the other runner or configure a different state directory." + ); + return new Error(`Cannot lock runner session state (errno ${code}).`); +} + function linuxKernel() { if (!process.versions.bun) throw new Error( @@ -35,7 +43,7 @@ function linuxKernel() { return { lock(fd: number) { if (symbols.flock(fd, 2 | 4) !== 0) - throw new Error(`Cannot lock runner session state (errno ${errno()}).`); + throw runnerStateLockError(errno()); }, signal(fd: number, signal: number) { if (symbols.syscall(424, fd, signal, null, 0) === 0) return; diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index b6a65e03d..64c3a5275 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -13,6 +13,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { parseProcessStat, + runnerStateLockError, type SessionIdentity, type SessionProcesses, } from "../src/agents/remote/session-processes.js"; @@ -31,6 +32,15 @@ const launch = (workspace: string) => launch: { engine: "codex" }, }) as const; +it("explains lock contention while retaining diagnostics for other flock failures", () => { + expect(runnerStateLockError(11).message).toMatch( + /Another runner daemon is already using this state directory.*Stop the other runner or configure a different state directory/ + ); + expect(runnerStateLockError(9).message).toBe( + "Cannot lock runner session state (errno 9)." + ); +}); + describe("runner session supervision", () => { let root: string; let state: string; From 24eeb2e4488ba37fc93fa49fd0d4c83811c429a8 Mon Sep 17 00:00:00 2001 From: Dispatch Field Test Date: Thu, 19 Nov 2026 04:06:41 +0000 Subject: [PATCH 083/642] Show exact runner health report time --- .../src/components/app/runner-health.test.tsx | 80 +++++++++++++++++++ apps/web/src/components/app/runner-health.tsx | 38 ++++++++- 2 files changed, 115 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/components/app/runner-health.test.tsx diff --git a/apps/web/src/components/app/runner-health.test.tsx b/apps/web/src/components/app/runner-health.test.tsx new file mode 100644 index 000000000..142379da1 --- /dev/null +++ b/apps/web/src/components/app/runner-health.test.tsx @@ -0,0 +1,80 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; + +import type { Runner } from "@/hooks/use-runners"; +import { RunnerHealthDetails } from "./runner-health"; + +vi.mock("./runner-onboarding", () => ({ + RunnerCommand: () => null, + useRunnerInstaller: () => ({ data: undefined }), +})); + +const runner: Runner = { + id: "runner-1", + name: "Build runner", + status: "online", + workspaces: [], +}; +const receivedAt = "2026-01-15T08:42:17.123Z"; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +it.each(["online", "offline"] as const)( + "shows a relative report time and reveals the exact local timestamp on focus for an %s runner", + async (status) => { + vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-01-15T08:43:25Z")); + render( + + ); + fireEvent.click(screen.getByText(/1 session/)); + + const report = screen.getByText("1m ago"); + expect(report.getAttribute("datetime")).toBe(receivedAt); + expect(report.tabIndex).toBe(0); + expect(screen.queryByRole("tooltip")).toBeNull(); + + fireEvent.focus(report); + + const tooltip = await screen.findByRole("tooltip"); + expect(report.getAttribute("aria-describedby")).toBe(tooltip.id); + expect(tooltip.textContent).toBe( + new Intl.DateTimeFormat(undefined, { + year: "numeric", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + second: "2-digit", + timeZoneName: "shortOffset", + }).format(new Date(receivedAt)) + ); + } +); + +it("preserves the no-sample state", () => { + const { rerender } = render(); + expect(screen.getByText("No health report received.")).toBeTruthy(); + expect(screen.queryByText("Last report")).toBeNull(); + + rerender(); + expect(screen.queryByText("No health report received.")).toBeNull(); + expect(screen.queryByText("Last report")).toBeNull(); +}); diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index 8b4bd432c..bd687fca7 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -1,9 +1,25 @@ import { useState } from "react"; import { RunnerCommand, useRunnerInstaller } from "./runner-onboarding"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; import type { Runner } from "@/hooks/use-runners"; import { isVersionNewer } from "@/lib/tips/version-compare"; import { formatRelativeTime } from "@/lib/format"; +const reportDateTimeOptions: Intl.DateTimeFormatOptions = { + year: "numeric", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + second: "2-digit", + timeZoneName: "shortOffset", +}; + const memory = (bytes: number) => bytes < 1024 ** 3 ? `${Math.round(bytes / 1024 ** 2)} MiB` @@ -51,9 +67,25 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) {
{health.version}
Last report
- + + + + + + + {new Date(healthReceivedAt).toLocaleString( + undefined, + reportDateTimeOptions + )} + + +
{update && ( From a28039efeb751013e01b9db6009f6e6606ff27b8 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:34:46 -0700 Subject: [PATCH 084/642] Inventory Dispatch execution needs before introducing a local runner --- docs/design/runner-capability-inventory.md | 110 +++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 docs/design/runner-capability-inventory.md diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md new file mode 100644 index 000000000..b261873a9 --- /dev/null +++ b/docs/design/runner-capability-inventory.md @@ -0,0 +1,110 @@ +# What Dispatch needs from a runner + +**Starting point.** Implement owner review through a built-in local runner and a connected Linux runner. Both should accept the same operations on an opaque agent ID. Keep the native Mac execution path underneath the local implementation. The first release can support a different set of capabilities on each machine. Dispatch must be able to tell the user which operations their selected runner supports. + +**Evidence baseline.** This inventory traces the feature branch at `598070c197cc`. GitHub’s main branch was at `8eebbe319863` during the audit. Ten main-branch commits were absent from the feature branch. The compatibility cases below include newer OpenCode launch, resume and verified update behavior, ACP adapter updates, and interruption across conversations. This is a source audit plus evidence from the two real runner sessions. Most rows have not been exercised on both placements. [Lifecycle model](../04-agent-lifecycle.md) · [ACP design](acp-runtime.md) · [Runner contract and compatibility](remote-runner-prototype.md) + +## What exists on the wire + +The outer protocol already covers launch, attach, liveness, stop, discard, log tail, a configured repository command, and runner-wide engine operations. Its ready frame advertises capabilities. The attached session channel carries prompts, steering, cancellation, permission answers, config changes, inventories, receipts and replay. Both transports should use these contracts. The existing repository command executes one configured operation. It cannot answer arbitrary questions about a managed checkout. The current prompt source also contains Dispatch-specific conversation and scheduling fields. A second service should be able to omit that metadata or have it echoed opaquely. [Execution](../../packages/runner-protocol/src/execution.ts) · [Session](../../packages/runner-protocol/src/session.ts) · [Runner implementation](../../apps/server/src/agents/remote/runner.ts) + +## Capability inventory + +“Present” means a protocol operation exists. “Partial” means only part of the local workflow has a runner path. “Gap” means the current wire contract lacks the required operation. “Decision” means ownership or support must be explicit before migrating that caller. Each entry includes an acceptance case and its source. + +### Placement and session creation + +**Choose a machine and location.** **Partial.** Dispatch owns projects, names, defaults and admission policy. The execution side resolves folders, Git context, branch choices and permissions. This Mac supports arbitrary existing folders, non-repos and existing main checkouts. Remote runners support configured folders or managed scratch and repository sessions. + +- A default local launch still works in a non-repo. Two runners using an identical folder name each reach their own files. A revoked placement cannot silently fall back to local. [Project matching](../../apps/server/src/projects/matching.ts) · [Path and branch queries](../../apps/server/src/routes/system.ts) · [Placement](../../packages/runner-protocol/src/placement.ts) + +**Provision and prepare an agent.** **Partial.** Preserve local worktree location, branch and base selection, allowed local config copying, initial files, dependency setup and phase/error reporting. Managed runners create a scratch directory or checkout from a cache, with new, existing or PR branch choices. Setup files and credentials belong to the selected environment. + +- Check a new branch, a direct existing branch, a busy branch, a missing package manager and a retry after partial setup. In the field test a valid checkout still lacked dependencies and the guest install exited 137. [Workspace preparation](../../apps/server/src/agents/workspace-prep.ts) · [File seeding](../../apps/server/src/agents/file-seed.ts) · [Runner Git](../../apps/server/src/agents/remote/repository.ts) + +**Track the effective checkout.** **Gap for shared managed worktrees.** Local sessions can report a moved workspace. A local child may share its parent’s current worktree or request a new one. Managed remote launch derives its directory from the new agent’s ID. Keep author identity, launching agent, display parent and checkout ownership distinct. + +- Launch a child in the author’s current checkout and another in a separate checkout. Reviewers keep separate sessions and see the author’s uncommitted files. A cross-runner reference is rejected. [Workspace selection](../../apps/server/src/agents/workspace-target.ts) · [Child launch options](../../apps/server/src/shared/mcp/agent-launch-tools.ts) · [Runner supervisor](../../apps/server/src/agents/remote/session-supervisor.ts) + +### Running an agent + +**Launch, supervise and recover.** **Present for core operations.** The execution side selects binaries and workload identity, builds the environment, starts or resumes the provider host, reports readiness, reattaches, tails bounded logs, stops descendants and discards state. Dispatch persists desired lifecycle and reconciles it with the runner. + +- Distinguish spawn, provider-ready and prompt-accepted. Recover a live host without a second invocation. Exercise stale PID, duplicate launch, forced stop and a service restart. [Agent manager](../../apps/server/src/agents/manager.ts) · [Supervisor](../../apps/server/src/agents/remote/session-supervisor.ts) · [Host environment](../../apps/server/src/agents/acp/host-env.ts) + +**Deliver turns, permissions and results.** **Present for core operations.** Preserve queued prompts, images, mid-turn steering, targeted interruption, cancel, permission request/answer, runtime config, background work and MCP inventory. Dispatch decides which conversation or human owns a response. The runner delivers it to the correct session. + +- Disconnect after prompt acceptance and before completion. Resume from the last contiguous durable event in the same journal. Test journal replacement, an unanswered permission, and cross-conversation interruption. [Session messages](../../packages/runner-protocol/src/session.ts) · [Durable inbox](../../apps/server/src/agents/remote/event-inbox.ts) · [Steering](../../apps/server/src/agents/steering.ts) + +**Authorize and connect service tools.** **Partial.** The runner accepts optional service-owned MCP. When present, endpoint reachability, workload trust, the agent’s scoped credential, and revocation must work for the actual engine. Dispatch owns tool authorization and the access ceiling for children. + +- A real Codex session lists and calls its tool over authenticated TLS on first launch. In the field test, provider login succeeded while the tool connection failed until the guest trusted the service CA. Also run a session with MCP omitted. [MCP routes](../../apps/server/src/routes/mcp.ts) · [Access ceiling](../../apps/server/src/shared/access-ceiling.ts) · [Host environment](../../apps/server/src/agents/acp/host-env.ts) + +### Working with a checkout + +**Select and launch owner reviewers.** **Confirmed gap.** Dispatch currently runs Git in the parent cwd and loads checkout-local ownership rules and persona definitions. Dispatch should retain policy, reviewer selection, threads and findings. The runner supplies checkout facts and scoped file contents, then launches the reviewer in the author’s checkout. + +- Both real agents called owner review and got Git exit 128 on a runner URL. Repeat on both placements with committed, staged, unstaged, renamed and untracked files. Verify matching owners, correct base and visible files. [Owner handler](../../apps/server/src/server/mcp-persona-handlers.ts) · [Changed-file collection](../../apps/server/src/personas/codeowners.ts) · [Review workflow](../code-owner-reviews.md) + +**Display Changes and worktree state.** **Gap.** Base/ref resolution, file lists, diff stats, individual hunks, image diffs, repo identity and dirty/unmerged state read the checkout. Dispatch owns diff comments, rendering and refresh timing. Background refreshers must use the same placement as foreground requests. + +- Compare an untracked file, rename, image and dirty worktree against the same base. Handle a missing base without probing another machine. [Agent diff](../../apps/server/src/shared/git/agent-diff.ts) · [Agent routes](../../apps/server/src/routes/agents/lifecycle-routes.ts) · [Stats refresher](../../apps/server/src/agents/diff-stats-refresher.ts) + +**Discover repositories and interact with GitHub.** **Partial.** Runner Git can provision a checkout. Repository search, branch/PR lookup, PR status/checks and risk analysis have separate callers. Decide explicitly whether each uses a Dispatch GitHub identity or the workload’s GitHub identity. A project association alone grants no GitHub access. + +- From a fresh runner account, sign in to GitHub, clone a private test repo, fetch a fork PR, and verify the identity used for push and PR creation. Sign out and verify isolation from other runners. Local-only review must also work with no published branch. [Search](../../apps/server/src/routes/runner-repositories.ts) · [PR reader](../../apps/server/src/agents/pull-request-reader.ts) · [Refresh](../../apps/server/src/agents/pull-request-refresher.ts) · [Risk inputs](../../apps/server/src/agents/merge-risk/sources.ts) + +**Browse workspace files.** **Gap.** Directory listing, filtering/ignore rules, indexing and bounded text/image reads require the effective workspace. Preserve traversal, symlink, size and binary-file handling on the execution side. + +- Expand a directory and open a file in the runner checkout. A path escaping the workspace is refused there. [Workspace routes](../../apps/server/src/routes/agents/workspace-routes.ts) · [File explorer](../file-explorer.md) + +**Move attachments across the boundary.** **Partial.** Dispatch stores and serves user-visible attachments. Initial files, images supplied to a prompt, and files a runner agent posts by path require explicit delivery or collection. A runner-local file path in a chat post is insufficient. + +- Upload an image, deliver it to one runner agent, then have it post a generated file that opens after its session is archived. [File routes](../../apps/server/src/routes/files.ts) · [Prompt images](../../apps/server/src/agents/acp/prompt-images.ts) · [Attachment behavior](../file-attachments.md) + +### Repository automation and cleanup + +**Discover repo tools, hooks and instructions.** **Partial.** Local sessions load checkout-specific persona files, tool manifests and lifecycle hooks. Local stop hooks skip remote placements today. The proof command on configured workspaces covers only a narrow case. Service policy controls what may run. The execution side resolves the manifest and runs the approved operation in the correct checkout. + +- A repo dev tool uses the runner’s working directory. Stop hooks run with their documented semantics for the launch and moved checkout. Missing tools are reported explicitly. [Repo tools](../../apps/server/src/shared/mcp/repo-tools.ts) · [Hooks](../../apps/server/src/agents/lifecycle-hooks.ts) · [Persona discovery](../../apps/server/src/personas/catalog.ts) + +**Stop, archive and retain shared work.** **Partial.** Local archive checks dirty/unmerged changes, cleanup policy and live references. Managed runners queue offline cleanup. A shared review checkout adds a borrower whose archive must release its reference. Dispatch owns archive confirmation, history and retention. + +- Archive the reviewer first and continue author work. Archive the owner while a borrower exists, disconnect during cleanup, restart, and retry without deleting another session’s work. Include a pre-migration live agent. [Archive and reference checks](../../apps/server/src/agents/archive.ts) · [Retention](../../apps/server/src/agents/retention.ts) · [Runner supervisor](../../apps/server/src/agents/remote/session-supervisor.ts) + +### Machine capabilities and integrations + +**Manage engines and credentials.** **Partial.** Inventory, versions, supported actions, install/update, and Codex/Claude login are runner-scoped. Model and effort catalogs, plugin install/status, provider usage, account reset and quota probes also need explicit machine/account scope. Dispatch can aggregate sanitized results. + +- Compare two runners signed into different accounts. Verify first login, cancel, async completion, update, unavailable actions, selected model/effort and version-compatible OpenCode resume. [Engine operations](../../packages/runner-protocol/src/engine-management.ts) · [Model discovery](../../apps/server/src/agents/engine-models.ts) · [Provider plans](../../apps/server/src/agents/provider-plans.ts) · [Plugin routes](../../apps/server/src/routes/plugin.ts) + +**Human terminals and desktop integrations.** **Decision per capability.** A human PTY opened in the agent checkout needs machine-local process, resize, input, detach/resume and close. Desktop IDE, clipboard, browser and computer-use actions need an explicit target and OS permissions. Some belong to the operator’s desktop, even when the agent runs elsewhere. + +- Keep native Mac behavior. A remote terminal, if offered, opens in the correct guest with the correct identity. Never interpret a remote path as a request to open a Mac file. [Human terminal manager](../../apps/server/src/terminal/manager.ts) · [Clipboard behavior](../../apps/server/src/routes/files.ts) · [Mac integration](../macos-app.md) + +**Serve previews.** **Deferred.** An agent can publish a preview link. Reaching a server bound inside a remote execution environment is a separate capability. Dispatch owns the browser-facing URL and access policy. + +- When implemented, two runners can independently serve the same guest port. Access and live reload end for the revoked runner. [Preview acceptance in handoff](remote-runner-handoff.md) + +**Report health and manage the runner.** **Present in part.** Remote registration, pairing, certificates, revocation, periodic health and engine inventory already exist. Keep wire-version negotiation, last-seen time, stale reports, session counts, CPU, memory, diagnostics, safe update and recovery visible. Built-in local execution needs a stable identity and capability set. The app installer can own its lifecycle. + +- An older runner lacks an optional feature and still executes supported commands. A revoked runner stays revoked. A busy update defers. Distinguish stale data from a measured zero. [Health](../../packages/runner-protocol/src/health.ts) · [Enrollment](../../packages/runner-protocol/src/enrollment.ts) · [Installer](../../bin/install-dispatch-runner.sh) + +### Other launch entry points + +**Launch from tasks, jobs, templates and agent tools.** **Cross-cutting.** The UI is one caller. Scheduled jobs, templates, child launches and reviewers can inherit a project, directory, access policy and defaults. Dispatch owns schedules, task state, messages, brain objects and project membership. Some callers currently infer scope from a local repo root. + +- Launch the same project via Create Agent, a task, a template and a child. Verify placement and project association across restart. A project may contain a scratch session without a repository. [Jobs](../../apps/server/src/jobs/service.ts) · [Templates](../../apps/server/src/templates/service.ts) · [Repo-keyed brain storage](../../apps/server/src/brain/store.ts) · [Child options](../../apps/server/src/shared/mcp/agent-launch-tools.ts) + +## First implementation and release gate + +1. **Characterize local owner review before moving it.** Use an unpublished feature branch, checkout-local owner rules and a persona, staged and unstaged changes, and an untracked file. Capture the selected base, paths, owners and effective reviewer cwd. Cover the case where the launcher differs from the display parent. [Existing owner tests](../../apps/server/test/mcp-persona-codeowners.test.ts) +2. **Define the minimum portable operations for that fixture.** An authenticated service asks the runner for checkout changes relative to a base and bounded reads of the relevant config. The normal launch command gains an optional way to use the existing worktree of a named agent on the same runner. Define missing checkout/base, wrong placement, unsupported capability, author archive, and retry responses. The runner validates the binding. Dispatch parses ownership rules, selects people/personas and tracks findings. A shared mutable checkout requires a way to identify the reviewed state, including dirty files. A commit hash alone cannot do that. Define what “read-only reviewer” can actually enforce on each platform before promising it. +3. **Implement the built-in runner first, then the Linux implementation.** Use the same typed requests, responses, validation and contract fixtures. The local transport can call in process. Keep path resolution, Git invocation and file access inside the implementation. The candidate feature should pass existing local tests before remote support is enabled. +4. **Gate the migrated workflow on both implementations.** The same test launches the reviewer on the author’s machine, verifies it can see the unpublished and uncommitted changes, and verifies archiving it leaves the author working. Add remote disconnect/reconnect, revocation, and a second runner with the same folder name. Forbid direct filesystem, Git/process helpers and local-cwd fallbacks in the migrated review orchestration, including indirect helper calls. Run the independent protocol-consumer test. Finally repeat both real-agent tasks from their runner sessions. [Consumer test](../../apps/server/test/runner-protocol-consumer.test.ts) · [Multi-runner acceptance](../../e2e/remote-runner/acceptance.spec.ts) + +## Keeping the list honest + +Treat this as a register of workflows. Before migrating a row, enumerate its UI, HTTP, MCP, background worker and archive/recovery entry points. Trace their use of filesystem APIs, Git/gh, process spawning, home directories, provider state and machine-local URLs. Record the implementation owner, negotiated capability, local baseline test, remote test and supported exception. Mark a row complete only when its callers use the boundary and the shared acceptance case passes. A source link or matching method signature alone is insufficient evidence. + +Repeat the audit against main at each integration. Capability-specific contract tests should run for local and Linux execution, with platform-only and deferred cases visibly identified. Existing live sessions, old runners and outstanding durable events need compatibility fixtures throughout the transition. The unverified areas with the highest consequence are shared-worktree lifecycle, first-launch MCP trust, private GitHub authentication, artifact transfer, native desktop permissions, and update/recovery across versions. From f85d0f901e1c13633061c2842197af5a4cbe422d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:40:48 -0700 Subject: [PATCH 085/642] Define optional checkout inspection and shared-worktree launch on the runner protocol --- packages/runner-protocol/src/checkout.ts | 50 +++++++++++++++++++++++ packages/runner-protocol/src/execution.ts | 13 ++++++ packages/runner-protocol/src/index.ts | 1 + 3 files changed, 64 insertions(+) create mode 100644 packages/runner-protocol/src/checkout.ts diff --git a/packages/runner-protocol/src/checkout.ts b/packages/runner-protocol/src/checkout.ts new file mode 100644 index 000000000..4788d28dc --- /dev/null +++ b/packages/runner-protocol/src/checkout.ts @@ -0,0 +1,50 @@ +import { isRecord } from "./validation.js"; + +/** Operations are relative to the bound session checkout. Paths never name host files. */ +export type CheckoutQuery = + | { kind: "changes"; baseBranch: string | null } + | { kind: "readFile"; path: string }; + +export type CheckoutReply = + | { kind: "changes"; baseRef: string; head: string; files: string[] } + | { kind: "readFile"; content: string | null }; + +function relativePath(value: unknown): value is string { + return ( + typeof value === "string" && + value.length <= 4096 && + !value.includes("\0") && + !value.split("/").some((part) => !part || part === "." || part === "..") + ); +} + +export function isCheckoutQuery(value: unknown): value is CheckoutQuery { + if (!isRecord(value)) return false; + if (value.kind === "readFile") return relativePath(value.path); + return ( + value.kind === "changes" && + (value.baseBranch === null || + (typeof value.baseBranch === "string" && + value.baseBranch.length > 0 && + value.baseBranch.length <= 255 && + !/^[.-]|[\x00-\x20\x7f~^:?*\[\\]|\.\.|@\{/.test(value.baseBranch))) + ); +} + +export function isCheckoutReply( + value: unknown, + query: CheckoutQuery +): value is CheckoutReply { + if (!isRecord(value) || value.kind !== query.kind) return false; + if (value.kind === "readFile") + return value.content === null || typeof value.content === "string"; + return ( + typeof value.baseRef === "string" && + value.baseRef.length > 0 && + value.baseRef.length <= 512 && + typeof value.head === "string" && + /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.head) && + Array.isArray(value.files) && + value.files.every(relativePath) + ); +} diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 701f7a546..f896b79f6 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,3 +1,4 @@ +import { isCheckoutQuery, type CheckoutQuery } from "./checkout.js"; import { MANAGED_WORKSPACE, isOpaqueId } from "./placement.js"; import { type EngineInventoryEntry, @@ -38,10 +39,12 @@ export type RemoteLaunch = { mcp?: ServiceMcp; resumeSessionId: string | null; repository?: RunnerRepository; + useWorktreeOf?: string; }; export type SessionOperation = { agentId: string } & ( | { kind: "launch"; launch: RemoteLaunch } + | { kind: "inspectCheckout"; query: CheckoutQuery } | { kind: "attach" | "alive" | "discard" | "log" | "repo" } | { kind: "stop"; force: boolean } ); @@ -61,6 +64,8 @@ export type ReadyFrame = { managedWorkspace?: true; /** Advertises support for the `"engine"` command and inventory push. */ engineManagement?: true; + checkoutInspection?: true; + sharedWorktree?: true; }; /** Accept v1 extension fields and enable optional features only when explicitly true. */ @@ -83,6 +88,8 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { type: "ready", version: RUNNER_WIRE_VERSION, workspaces: frame.workspaces, + ...(frame.checkoutInspection === true && { checkoutInspection: true }), + ...(frame.sharedWorktree === true && { sharedWorktree: true }), ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), ...(frame.managedWorkspace === true && { managedWorkspace: true }), @@ -207,6 +214,10 @@ function isRemoteLaunch(value: unknown): value is RemoteLaunch { (value.personaContext === undefined || isNullableString(value.personaContext)) && (value.mcp === undefined || isServiceMcp(value.mcp)) && + (value.useWorktreeOf === undefined || + (isOpaqueId(value.useWorktreeOf) && + value.repository === undefined && + value.useWorktreeOf !== value.agentId)) && (value.repository === undefined || isRepository(value.repository)) ); } @@ -221,6 +232,8 @@ function isCommand(value: unknown): value is Command { switch (value.kind) { case "launch": return isRemoteLaunch(value.launch); + case "inspectCheckout": + return isCheckoutQuery(value.query); case "attach": case "alive": case "discard": diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index 3b1757685..d85c1fa8a 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -3,3 +3,4 @@ export * from "./enrollment.js"; export * from "./execution.js"; export * from "./session.js"; export * from "./health.js"; +export * from "./checkout.js"; From 823ec58fa61d4d75a605718364d9421ebb38d097 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:43:25 -0700 Subject: [PATCH 086/642] Preserve shared managed runner checkouts across reviewer lifecycles --- .../src/agents/remote/session-supervisor.ts | 222 ++++++++++++-- .../test/remote-runner-supervisor.test.ts | 286 +++++++++++++++++- 2 files changed, 471 insertions(+), 37 deletions(-) diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 9380f4aa5..cada3fded 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { closeSync, constants, fstatSync, openSync } from "node:fs"; +import { closeSync, constants, fstatSync, openSync, type Stats } from "node:fs"; import { chmod, chown, @@ -20,6 +20,7 @@ import path from "node:path"; import { hostFile, type HostLaunch } from "../acp/host-protocol.js"; import { MANAGED_WORKSPACE, + isOpaqueId, type Command, type RunnerRepository, } from "./protocol.js"; @@ -45,7 +46,9 @@ export function runnerStorageKey(agentId: string): string { : `opaque-${createHash("sha256").update(agentId).digest("base64url")}`; } -type LaunchCommand = Extract; +type LaunchCommand = Extract & { + launch: { useWorktreeOf?: unknown }; +}; type SupervisorOptions = { state: string; @@ -60,9 +63,19 @@ type SupervisorOptions = { }; const managedBinding = "\0managed"; +const sharedBindingPrefix = managedBinding + ":"; +const storageKeyPattern = /^(agt_[a-z0-9]+|opaque-[A-Za-z0-9_-]{43})$/; const readOptional = (file: string) => readFile(file, "utf8").catch(missingPath); +function checkoutOwner(binding: string | null) { + if (!binding?.startsWith(sharedBindingPrefix)) return null; + const key = binding.slice(sharedBindingPrefix.length); + if (!storageKeyPattern.test(key)) + throw new Error("Invalid runner checkout binding."); + return key; +} + const logTailBytes = 2 * 1024; async function readLogTail(file: string) { @@ -148,6 +161,29 @@ export async function createSessionSupervisor( }); } + function withLaunchLocks( + key: string, + owner: string | null, + operation: () => Promise + ) { + if (owner === null) return serialize(key, operation); + // Acquire both keys in a stable order, including for invalid cross-loans. + const [first, second] = key < owner ? [key, owner] : [owner, key]; + return serialize(first, () => serialize(second, operation)); + } + + async function syncBindings() { + const directory = await open( + bindings, + constants.O_RDONLY | constants.O_DIRECTORY + ); + try { + await directory.sync(); + } finally { + await directory.close(); + } + } + async function writePrivateState(file: string, contents: string) { const temp = path.join(bindings, `.pending-${randomUUID()}`); try { @@ -159,15 +195,7 @@ export async function createSessionSupervisor( await handle.close(); } await rename(temp, file); - const directory = await open( - bindings, - constants.O_RDONLY | constants.O_DIRECTORY - ); - try { - await directory.sync(); - } finally { - await directory.close(); - } + await syncBindings(); } finally { await rm(temp, { force: true }); } @@ -177,6 +205,7 @@ export async function createSessionSupervisor( const retireFile = (key: string) => path.join(bindings, `${key}.retired`); const repositoryFile = (key: string) => path.join(bindings, `${key}.repository`); + const cwdFile = (key: string) => path.join(bindings, `${key}.cwd`); const markerFile = (key: string) => path.join(bindings, `${key}.owner`); const identityFile = (key: string) => path.join(bindings, `${key}.host`); function managedTarget(workspace: string) { @@ -233,22 +262,75 @@ export async function createSessionSupervisor( await rmdir(dir); } - async function discardManaged(key: string) { - await writePrivateState(retireFile(key), ""); + async function checkedDirectory(dir: string) { + const entry = await lstat(dir).catch(missingPath); + if (!entry?.isDirectory() || (await realpath(dir)) !== dir) + throw new Error("The runner session checkout is unavailable."); + return entry; + } + + function checkoutParentIsProtected(entry: Stats | null) { + return ( + entry !== null && + entry.uid === process.getuid?.() && + (entry.mode & 0o777) === 0o711 + ); + } + + async function managedDirectory(key: string) { + const stored = await readOptional(repositoryFile(key)); + if (stored === null) + throw new Error("The runner session checkout is unavailable."); + const session = path.join(sessions, key); + const entry = await checkedDirectory(session); + if (JSON.parse(stored) === null) return session; + const checkout = path.join(session, "checkout"); + await checkedDirectory(checkout); + if (checkoutParentIsProtected(entry)) return checkout; + // The parent of a Git checkout must be supervisor-owned so a workload + // cannot swap the verified checkout for a symlink after it is resolved. + // Legacy sessions get this protection when first inspected or borrowed. + await chown(session, process.getuid!(), process.getgid!()); + await chmod(session, 0o711); + await checkedDirectory(checkout); + return checkout; + } + + async function hasBorrowers(key: string) { + for (const entry of await readdir(bindings)) { + if ( + storageKeyPattern.test(entry) && + checkoutOwner(await readBinding(entry)) === key + ) + return true; + } + return false; + } + + async function discardManagedCheckout(key: string) { + if (await hasBorrowers(key)) + throw new Error("Runner checkout is still in use by a borrower."); const session = path.join(sessions, key); const stored = await readOptional(repositoryFile(key)); const repository = stored === null ? null : (JSON.parse(stored) as RunnerRepository | null); - if (repository) await repositories.remove(session, repository); + // Remove the directory before unregistering it so the workload never + // regains write access to a protected checkout parent. + if ( + repository && + checkoutParentIsProtected(await lstat(session).catch(missingPath)) + ) + await removeGuestDirectory(path.join(session, "checkout")); await removeGuestDirectory(session); + if (repository) await repositories.remove(session, repository); await rm(repositoryFile(key), { force: true }); - await rm(path.join(logs, key), { force: true }); } async function launch( command: LaunchCommand, cwd: string | undefined, - key: string + key: string, + owner: string | null ) { const { agentId, workspace } = command; const { mcp } = command.launch; @@ -263,18 +345,29 @@ export async function createSessionSupervisor( throw new Error("This runner session has been archived."); const binding = await readBinding(key); - const bindingValue = managed ? managedBinding : workspace; + const bindingValue = owner + ? sharedBindingPrefix + owner + : managed + ? managedBinding + : workspace; + if (binding !== null && binding !== bindingValue) + throw new Error("Agent is not bound to this workspace or checkout"); + if (owner) { + if ((await readBinding(owner)) !== managedBinding) + throw new Error("The author does not own a checkout on this runner."); + if (binding === null && (await readOptional(retireFile(owner))) !== null) + throw new Error("The author checkout has been archived."); + cwd = await managedDirectory(owner); + } if (binding === null) await writePrivateState(path.join(bindings, key), bindingValue); - else if (binding !== bindingValue) - throw new Error("Agent is not bound to this workspace"); const identity = await readIdentity(key); if (identity && processes.alive(identity)) throw new Error("Runner already has a host for this agent"); await cleanHost(key, identity); checkUntrackedSocket(path.join(hostRoot, key)); await cleanLegacyHost(key); - if (managed) { + if (managed && !owner) { const parsed = command.launch.repository === undefined ? null @@ -292,14 +385,31 @@ export async function createSessionSupervisor( ); if (stored === null) await writePrivateState(repositoryFile(key), encoded); - cwd = await prepareScratchSession(sessions, key, config.uid, config.gid); - if (repository) cwd = await repositories.prepare(cwd, repository); + const session = path.join(sessions, key); + const entry = await lstat(session).catch(missingPath); + if (entry) await checkedDirectory(session); + const protectedParent = repository && checkoutParentIsProtected(entry); + cwd = protectedParent + ? session + : await prepareScratchSession(sessions, key, config.uid, config.gid); + if (repository) { + const checkout = path.join(cwd, "checkout"); + if (await lstat(checkout).catch(missingPath)) + await checkedDirectory(checkout); + await repositories.prepare(cwd, repository); + cwd = await managedDirectory(key); + } } if (!cwd || (!managed && !(await stat(cwd)).isDirectory())) throw new Error("Guest workspace is unavailable"); + if (!managed) await writePrivateState(cwdFile(key), await realpath(cwd)); const dir = path.join(hostRoot, key); const files = path.join(dir, "files"); - const { repository: _repository, ...launchOptions } = command.launch; + const { + repository: _repository, + useWorktreeOf: _owner, + ...launchOptions + } = command.launch; const launch: HostLaunch = { ...launchOptions, agentId, @@ -356,8 +466,13 @@ export async function createSessionSupervisor( } async function bound(key: string, workspace: string) { - const binding = await readBinding(key); - return binding === (managedTarget(workspace) ? managedBinding : workspace); + return matchesWorkspace(await readBinding(key), workspace); + } + + function matchesWorkspace(binding: string | null, workspace: string) { + return managedTarget(workspace) + ? binding === managedBinding || checkoutOwner(binding) !== null + : binding === workspace; } async function cleanExited(key: string) { @@ -402,9 +517,50 @@ export async function createSessionSupervisor( sweep.unref(); return { - launch(command: LaunchCommand, cwd: string | undefined) { + async launch(command: LaunchCommand, cwd: string | undefined) { const key = runnerStorageKey(command.agentId); - return serialize(key, () => launch(command, cwd, key)); + const { useWorktreeOf } = command.launch; + if (useWorktreeOf === undefined) + return withLaunchLocks(key, null, () => + launch(command, cwd, key, null) + ); + if (!isOpaqueId(useWorktreeOf) || useWorktreeOf === command.agentId) + throw new Error("Invalid author for a shared runner checkout."); + if ( + !managedTarget(command.workspace) || + command.launch.repository !== undefined + ) + throw new Error( + "Sharing requires a managed runner session without a repository selection." + ); + const owner = runnerStorageKey(useWorktreeOf); + return withLaunchLocks(key, owner, () => + launch(command, cwd, key, owner) + ); + }, + checkoutDirectory(agentId: string, workspace: string): Promise { + const key = runnerStorageKey(agentId); + return serialize(key, async () => { + const managed = managedTarget(workspace); + const binding = await readBinding(key); + if (!matchesWorkspace(binding, workspace)) + throw new Error("Agent is not bound to this workspace"); + if (managed) { + if ((await readOptional(retireFile(key))) !== null) + throw new Error("This runner session has been archived."); + const owner = checkoutOwner(binding); + if (owner && (await readBinding(owner)) !== managedBinding) + throw new Error( + "The author does not own a checkout on this runner." + ); + return managedDirectory(owner ?? key); + } + const cwd = await readOptional(cwdFile(key)); + if (cwd === null) + throw new Error("The runner session checkout is unavailable."); + await checkedDirectory(cwd); + return cwd; + }); }, async alive(agentId: string, workspace: string) { const key = runnerStorageKey(agentId); @@ -488,13 +644,21 @@ export async function createSessionSupervisor( const identity = await readIdentity(key); if (identity && processes.alive(identity)) throw new Error("Stop the guest host before discarding it"); + if (managed) await writePrivateState(retireFile(key), ""); const dir = path.join(hostRoot, key); await cleanHost(key, identity); checkUntrackedSocket(dir); await cleanLegacyHost(key); - if (managed) await discardManaged(key); + if (managed) { + if (!checkoutOwner(await readBinding(key))) + await discardManagedCheckout(key); + await rm(path.join(logs, key), { force: true }); + } else { + await rm(cwdFile(key), { force: true }); + } await removeGuestDirectory(dir); await rm(path.join(bindings, key), { force: true }); + if (managed) await syncBindings(); }); }, async log(agentId: string, workspace: string) { @@ -516,7 +680,7 @@ export async function createSessionSupervisor( if ( binding === null || !(managedWorkspace - ? binding === managedBinding + ? binding === managedBinding || checkoutOwner(binding) !== null : config.workspaces.has(binding)) ) return null; diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index b6a65e03d..f0d90a480 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -1,3 +1,5 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { mkdir, mkdtemp, @@ -6,11 +8,13 @@ import { realpath, rm, stat, + symlink, writeFile, } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { MANAGED_WORKSPACE } from "../src/agents/remote/protocol.js"; import { parseProcessStat, type SessionIdentity, @@ -23,6 +27,7 @@ type Supervisor = Awaited>; const marker = "DISPATCH_OWNED_00000000000000000000000000000000=1"; const identity = { pid: 100, start: "500", scope: "boot:namespace", marker }; const agentId = "agt_fixture"; +const reviewerId = "agt_reviewer"; const launch = (workspace: string) => ({ kind: "launch", @@ -30,6 +35,14 @@ const launch = (workspace: string) => workspace, launch: { engine: "codex" }, }) as const; +const sharedLaunch = ( + useWorktreeOf: string = agentId, + workspace = MANAGED_WORKSPACE +) => ({ + ...launch(workspace), + agentId: reviewerId, + launch: { ...launch(workspace).launch, useWorktreeOf }, +}); describe("runner session supervision", () => { let root: string; @@ -37,6 +50,7 @@ describe("runner session supervision", () => { let record: string; let supervisor: Supervisor | undefined; let kernelHost: SessionIdentity | undefined; + let kernelReviewer: SessionIdentity | undefined; let locked: boolean; const processes = { @@ -47,14 +61,19 @@ describe("runner session supervision", () => { locked = false; }; }), - alive: vi.fn( - (record: SessionIdentity) => - record.scope === kernelHost?.scope && - record.pid === kernelHost.pid && - record.start === kernelHost.start + alive: vi.fn((record: SessionIdentity) => + [kernelHost, kernelReviewer].some( + (host) => + host !== undefined && + record.scope === host.scope && + record.pid === host.pid && + record.start === host.start + ) ), stop: vi.fn(async (record: SessionIdentity) => { - if (processes.alive(record)) kernelHost = undefined; + if (!processes.alive(record)) return; + if (record.pid === kernelReviewer?.pid) kernelReviewer = undefined; + if (record.pid === kernelHost?.pid) kernelHost = undefined; }), cleanup: vi.fn(async (_identity: SessionIdentity) => {}), cleanupLegacy: vi.fn(async (_marker: string) => {}), @@ -62,7 +81,12 @@ describe("runner session supervision", () => { spawn: vi.fn(), } satisfies SessionProcesses; - async function start(workspaces: string[]) { + async function start( + workspaces: string[], + asWorkload: Parameters< + typeof createSessionSupervisor + >[0]["asWorkload"] = vi.fn() + ) { supervisor = await createSessionSupervisor( { state, @@ -73,7 +97,7 @@ describe("runner session supervision", () => { env: {}, workspaces: new Set(workspaces), hostCommand: () => ["/test-host"], - asWorkload: vi.fn(), + asWorkload, }, processes ); @@ -91,6 +115,7 @@ describe("runner session supervision", () => { } ); kernelHost = undefined; + kernelReviewer = undefined; locked = false; root = await mkdtemp(path.join(os.tmpdir(), "runner-supervisor-")); state = path.join(await realpath(root), "state"); @@ -272,6 +297,251 @@ describe("runner session supervision", () => { await running.stop(agentId, "configured", true); await expect(stat(record)).rejects.toMatchObject({ code: "ENOENT" }); }); + + it("starts the reviewer in the author's checkout with independent state", async () => { + const running = await start([]); + const author = path.join(state, "sessions", agentId); + const reviewerHost = path.join(state, "hosts", reviewerId); + await running.launch(launch(MANAGED_WORKSPACE), undefined); + await writeFile(path.join(author, "uncommitted.txt"), "author's work"); + const reviewerIdentity = { ...identity, pid: 101 }; + processes.spawn.mockImplementationOnce( + async (command, cwd, _env, _log, save) => { + expect(command.at(-1)).toBe(reviewerHost); + expect(cwd).toBe(author); + expect(await readFile(path.join(cwd, "uncommitted.txt"), "utf8")).toBe( + "author's work" + ); + await save(reviewerIdentity); + kernelReviewer = reviewerIdentity; + } + ); + await running.launch(sharedLaunch(), undefined); + expect(await running.alive(reviewerId, MANAGED_WORKSPACE)).toBe(true); + expect(await running.checkoutDirectory(reviewerId, MANAGED_WORKSPACE)).toBe( + author + ); + const payload = JSON.parse( + await readFile(path.join(reviewerHost, "launch.json"), "utf8") + ); + expect(payload).toMatchObject({ + agentId: reviewerId, + cwd: author, + env: { DISPATCH_FILES_DIR: path.join(reviewerHost, "files") }, + }); + expect(payload).not.toHaveProperty("useWorktreeOf"); + await expect( + stat(path.join(state, "sessions", reviewerId)) + ).rejects.toMatchObject({ code: "ENOENT" }); + await expect( + running.discard(reviewerId, MANAGED_WORKSPACE) + ).rejects.toThrow("Stop the guest host"); + await running.stop(reviewerId, MANAGED_WORKSPACE, true); + await running.discard(reviewerId, MANAGED_WORKSPACE); + expect(await running.alive(agentId, MANAGED_WORKSPACE)).toBe(true); + expect(await readFile(path.join(author, "uncommitted.txt"), "utf8")).toBe( + "author's work" + ); + }); + + it("retains the author checkout until all borrower state is discarded across restarts", async () => { + const workspace = MANAGED_WORKSPACE; + const running = await start([]); + await running.launch(launch(workspace), undefined); + await running.stop(agentId, workspace, true); + // Even a failed spawn has reserved the binding. Only a successful + // discard confirms that any partially started host is gone. + processes.spawn.mockRejectedValueOnce(new Error("spawn failed")); + await expect(running.launch(sharedLaunch(), undefined)).rejects.toThrow( + "spawn failed" + ); + await expect(running.discard(agentId, workspace)).rejects.toThrow( + "still in use" + ); + running.close(); + + const recovered = await start([]); + const author = path.join(state, "sessions", agentId); + expect(await recovered.checkoutDirectory(reviewerId, workspace)).toBe( + author + ); + await expect( + recovered.checkoutDirectory(agentId, workspace) + ).rejects.toThrow("archived"); + await expect( + recovered.launch({ ...sharedLaunch(), agentId: "agt_new" }, undefined) + ).rejects.toThrow("archived"); + await expect( + recovered.launch({ ...launch(workspace), agentId: reviewerId }, undefined) + ).rejects.toThrow("not bound"); + await expect(recovered.discard(agentId, workspace)).rejects.toThrow( + "still in use" + ); + await recovered.discard(reviewerId, workspace); + await expect(stat(author)).resolves.toBeDefined(); + await recovered.discard(agentId, workspace); + await recovered.discard(agentId, workspace); + await expect(stat(author)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("holds the owner checkout through a concurrent borrower launch", async () => { + const workspace = MANAGED_WORKSPACE; + const running = await start([]); + await running.launch(launch(workspace), undefined); + await running.stop(agentId, workspace, true); + const entered = Promise.withResolvers(); + const finish = Promise.withResolvers(); + processes.spawn.mockImplementationOnce(async () => { + entered.resolve(); + await finish.promise; + }); + const started = running.launch(sharedLaunch(), undefined); + await entered.promise; + const discarding = running.discard(agentId, workspace); + finish.resolve(); + await started; + await expect(discarding).rejects.toThrow("still in use"); + }); + + it("rejects invalid, unbound and chained author references", async () => { + const running = await start([]); + await expect( + running.launch(sharedLaunch(reviewerId), undefined) + ).rejects.toThrow("Invalid author"); + await expect( + running.launch(sharedLaunch("bad\0id"), undefined) + ).rejects.toThrow("Invalid author"); + await expect(running.launch(sharedLaunch(), undefined)).rejects.toThrow( + "does not own" + ); + await running.launch(launch(MANAGED_WORKSPACE), undefined); + processes.spawn.mockResolvedValueOnce(); + await running.launch(sharedLaunch(), undefined); + await expect( + running.launch( + { ...sharedLaunch(reviewerId), agentId: "agt_chain" }, + undefined + ) + ).rejects.toThrow("does not own"); + expect(processes.spawn).toHaveBeenCalledTimes(2); + }); + + it("keeps named launches and rejects borrowing through a named workspace", async () => { + const running = await start(["configured", "other"]); + await running.launch(launch("configured"), root); + expect(await running.checkoutDirectory(agentId, "configured")).toBe( + await realpath(root) + ); + await expect(running.checkoutDirectory(agentId, "other")).rejects.toThrow( + "not bound" + ); + await expect( + running.launch(sharedLaunch(agentId, "other"), root) + ).rejects.toThrow("Sharing requires a managed"); + }); + + it("rejects symlink redirection of a legacy repository checkout", async () => { + const running = await start([]); + const workspace = MANAGED_WORKSPACE; + const author = path.join(state, "sessions", agentId); + await mkdir(author); + await symlink(root, path.join(author, "checkout")); + await writeFile(path.join(state, "bindings", agentId), "\0managed"); + await writeFile( + path.join(state, "bindings", agentId + ".repository"), + "{}" + ); + await expect(running.launch(sharedLaunch(), undefined)).rejects.toThrow( + "checkout is unavailable" + ); + await expect(running.checkoutDirectory(agentId, workspace)).rejects.toThrow( + "checkout is unavailable" + ); + expect(await running.isBound(reviewerId, workspace)).toBe(false); + expect(processes.spawn).not.toHaveBeenCalled(); + }); + + it("borrows a pre-migration Git worktree and retries owner cleanup", async () => { + const git = (...args: string[]) => + execFileSync("git", args, { encoding: "utf8" }); + const workspace = MANAGED_WORKSPACE; + const url = "https://github.com/fixture/project.git"; + const repository = { + url, + checkout: { kind: "new" as const, branch: "feature" }, + }; + const cache = path.join( + state, + "repositories", + createHash("sha256").update(url).digest("hex") + ); + const author = path.join(state, "sessions", agentId); + const checkout = path.join(author, "checkout"); + const workload = vi.fn(async (bin, args) => + execFileSync(bin, args, { encoding: "utf8" }) + ); + const running = await start([], workload); + git("init", "--quiet", "--bare", cache); + const seed = path.join(await realpath(root), "seed"); + git("init", "--quiet", seed); + git( + "-C", + seed, + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "--allow-empty", + "-m", + "seed" + ); + git("-C", seed, "push", "--quiet", cache, "HEAD:refs/heads/feature"); + await mkdir(author); + git( + `--git-dir=${cache}`, + "worktree", + "add", + "--quiet", + checkout, + "feature" + ); + await writeFile(path.join(state, "bindings", agentId), "\0managed"); + await writeFile( + path.join(state, "bindings", agentId + ".repository"), + JSON.stringify(repository) + ); + await writeFile(path.join(checkout, "uncommitted.txt"), "pending change"); + + processes.spawn.mockResolvedValueOnce(); + await running.launch(sharedLaunch(), undefined); + expect(processes.spawn.mock.calls[0]?.[1]).toBe(checkout); + expect(await running.checkoutDirectory(reviewerId, workspace)).toBe( + checkout + ); + expect((await stat(author)).mode & 0o777).toBe(0o711); + expect(workload).not.toHaveBeenCalled(); + await expect(running.discard(agentId, workspace)).rejects.toThrow( + "still in use" + ); + await running.discard(reviewerId, workspace); + expect(await readFile(path.join(checkout, "uncommitted.txt"), "utf8")).toBe( + "pending change" + ); + + workload.mockRejectedValueOnce(new Error("Git cleanup interrupted")); + await expect(running.discard(agentId, workspace)).rejects.toThrow( + "Git cleanup interrupted" + ); + running.close(); + const recovered = await start([], workload); + await recovered.discard(agentId, workspace); + expect( + git(`--git-dir=${cache}`, "worktree", "list", "--porcelain") + ).not.toContain(checkout); + await expect(stat(author)).rejects.toMatchObject({ code: "ENOENT" }); + }); }); it("reads session and start time after a process name containing parentheses", () => { From 4355dfaca551d02b0505b3089eb6a9f38d477cb4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:49:16 -0700 Subject: [PATCH 087/642] Record the selected review base for new runner branches --- .../src/agents/remote/session-storage.ts | 7 +++ .../test/remote-runner-supervisor.test.ts | 62 +++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/apps/server/src/agents/remote/session-storage.ts b/apps/server/src/agents/remote/session-storage.ts index 6cd6281a3..d057552fd 100644 --- a/apps/server/src/agents/remote/session-storage.ts +++ b/apps/server/src/agents/remote/session-storage.ts @@ -203,6 +203,13 @@ export class RunnerRepositories { try { if (needsFastForward) await this.git("-C", cwd, "merge", "--ff-only", "--", commit); + if (checkout.kind === "new") + await git( + "config", + "--replace-all", + `branch.${branch}.dispatchReviewBase`, + checkout.base ?? defaultBranch + ); if (checkout.kind !== "new" && remote) await git( "branch", diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index f0d90a480..c4cceba22 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -542,6 +542,68 @@ describe("runner session supervision", () => { ).not.toContain(checkout); await expect(stat(author)).rejects.toMatchObject({ code: "ENOENT" }); }); + + it("records the review base of new branches without assigning an upstream", async () => { + const git = (...args: string[]) => + execFileSync("git", args, { encoding: "utf8" }); + const workspace = MANAGED_WORKSPACE; + const url = "https://github.com/fixture/project.git"; + const seed = path.join(await realpath(root), "seed"); + git("init", "--quiet", "--initial-branch=trunk", seed); + git( + "-C", + seed, + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "--allow-empty", + "-m", + "seed" + ); + git("-C", seed, "branch", "release"); + const running = await start([], async (bin, args) => + execFileSync( + bin, + args.some((arg) => arg === "ls-remote" || arg === "fetch") + ? args.map((arg) => (arg === url ? seed : arg)) + : args, + { encoding: "utf8" } + ) + ); + + for (const [branch, base] of [ + ["explicit-base", "release"], + ["default-base", undefined], + ] as const) { + const id = `review-${branch}`; + processes.spawn.mockResolvedValueOnce(); + await running.launch( + { + ...launch(workspace), + agentId: id, + launch: { + ...launch(workspace).launch, + repository: { url, checkout: { kind: "new", branch, base } }, + }, + }, + undefined + ); + const cwd = await running.checkoutDirectory(id, workspace); + const config = git( + "-C", + cwd, + "config", + "--get-regexp", + `^branch\\.${branch}\\.` + ); + expect(config.trim()).toBe( + `branch.${branch}.dispatchreviewbase ${base ?? "trunk"}` + ); + } + }); }); it("reads session and start time after a process name containing parentheses", () => { From a81210e46a0c614d7fece14f0fc754d85243f216 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:42:55 -0700 Subject: [PATCH 088/642] Inspect bound Git checkouts through local and runner entry points --- apps/server/src/agents/checkout-inspection.ts | 259 ++++++++++++++++ apps/server/src/personas/codeowners.ts | 38 +-- apps/server/src/shared/git/base-ref.ts | 3 +- .../src/shared/git/owner-review-files.ts | 44 +++ apps/server/test/checkout-inspection.test.ts | 286 ++++++++++++++++++ 5 files changed, 593 insertions(+), 37 deletions(-) create mode 100644 apps/server/src/agents/checkout-inspection.ts create mode 100644 apps/server/src/shared/git/owner-review-files.ts create mode 100644 apps/server/test/checkout-inspection.test.ts diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts new file mode 100644 index 000000000..d6f5b60d8 --- /dev/null +++ b/apps/server/src/agents/checkout-inspection.ts @@ -0,0 +1,259 @@ +import { execFile } from "node:child_process"; +import { constants } from "node:fs"; +import { lstat, open, type FileHandle } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { + isCheckoutQuery, + type CheckoutQuery, + type CheckoutReply, +} from "@dispatch/runner-protocol"; + +import { + refreshRemoteBaseRef, + resolveBaseRef, +} from "../shared/git/base-ref.js"; +import { collectOwnerReviewFiles } from "../shared/git/owner-review-files.js"; +import { getPrStatus } from "../shared/github/pr.js"; +import type { CommandRunner } from "../shared/lib/run-command.js"; + +const MAX_QUERY_BYTES = 16 * 1024; +const MAX_REPLY_BYTES = 4 * 1024 * 1024; +const MAX_FILE_BYTES = 256 * 1024; +const MAX_ERROR_BYTES = 4 * 1024; +const execFileAsync = promisify(execFile); + +// Git and gh inherit the caller's identity, environment and credentials. +const run: CommandRunner = async (command, args, options = {}) => { + const { stdout, stderr, exitCode } = await execFileAsync(command, args, { + cwd: options.cwd, + env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1" }, + maxBuffer: MAX_REPLY_BYTES, + timeout: options.timeoutMs ?? 5_000, + killSignal: "SIGKILL", + }) + .then((result) => ({ ...result, exitCode: 0 })) + .catch((error) => { + if ( + typeof error.code === "number" && + options.allowedExitCodes?.includes(error.code) + ) { + return { + stdout: error.stdout as string, + stderr: error.stderr as string, + exitCode: error.code as number, + }; + } + const detail = + error.stderr?.trim().slice(0, MAX_ERROR_BYTES) || + error.code || + error.signal; + throw new Error( + `Checkout inspection ${command} failed: ${detail ?? "unknown error"}` + ); + }); + + return { + stdout: options.trimOutput === false ? stdout : stdout.trim(), + stderr: stderr.trim(), + exitCode, + }; +}; + +function parseQuery(input: unknown): CheckoutQuery { + if (isCheckoutQuery(input) && Object.keys(input).length === 2) return input; + throw new Error("Invalid checkout inspection query"); +} + +function validateFilePath(file: string): string[] { + const segments = file.split("/"); + if ( + file.includes("\0") || + file.includes("\\") || + /^[a-z]:/i.test(file) || + segments.some( + (segment) => + !segment || + segment === "." || + segment === ".." || + segment.toLowerCase() === ".git" + ) + ) { + throw new Error("Expected a repository-relative worktree file path"); + } + return segments; +} + +// These flags are provided by the operating systems but aren't exposed by Node. +const DARWIN_NOFOLLOW_ANY = 0x20000000; +const LINUX_OPEN_PATH = 0x200000; + +async function openRegularFile( + root: string, + segments: string[] +): Promise { + const target = path.join(root, ...segments); + if (process.platform === "darwin") { + if (!(await lstat(target)).isFile()) + throw new Error("Expected a regular worktree file"); + return open( + target, + constants.O_RDONLY | constants.O_NONBLOCK | DARWIN_NOFOLLOW_ANY + ); + } + if (process.platform !== "linux") { + throw new Error("Checkout file inspection requires macOS or Linux"); + } + + // Open each component relative to a pinned directory. A concurrent symlink + // replacement can't redirect either the directory traversal or the file open. + let directory = await open("/", LINUX_OPEN_PATH | constants.O_DIRECTORY); + try { + for (const segment of path + .join(root, ...segments.slice(0, -1)) + .split("/") + .filter(Boolean)) { + const next = await open( + `/proc/self/fd/${directory.fd}/${segment}`, + LINUX_OPEN_PATH | constants.O_DIRECTORY | constants.O_NOFOLLOW + ); + await directory.close(); + directory = next; + } + const entry = await open( + `/proc/self/fd/${directory.fd}/${segments.at(-1)}`, + LINUX_OPEN_PATH | constants.O_NOFOLLOW + ); + try { + if (!(await entry.stat()).isFile()) + throw new Error("Expected a regular worktree file"); + return await open(`/proc/self/fd/${entry.fd}`, constants.O_RDONLY); + } finally { + await entry.close(); + } + } finally { + await directory.close(); + } +} + +async function readWorktreeFile( + root: string, + segments: string[] +): Promise { + try { + const file = await openRegularFile(root, segments); + try { + const stat = await file.stat(); + if (!stat.isFile()) throw new Error("Expected a regular worktree file"); + if (stat.size > MAX_FILE_BYTES) + throw new Error("Checkout file is too large"); + // Enforce the limit even if the file grows after stat. + const bytes = Buffer.alloc(MAX_FILE_BYTES + 1); + let size = 0; + while (size < bytes.length) { + const { bytesRead } = await file.read( + bytes, + size, + bytes.length - size, + size + ); + if (bytesRead === 0) return bytes.toString("utf8", 0, size); + size += bytesRead; + } + throw new Error("Checkout file is too large"); + } finally { + await file.close(); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +async function inspectChanges( + root: string, + baseBranch: string | null +): Promise { + if (baseBranch === null) { + try { + baseBranch = (await getPrStatus({ cwd: root }, run)).baseRefName; + } catch { + // No usable PR; the base helpers fall back to the upstream or main. + } + } + const options = { + runCommand: run, + allowUpstreamFallback: baseBranch === null, + }; + await refreshRemoteBaseRef(root, baseBranch, options); + const baseRef = + (await resolveBaseRef(root, baseBranch, options)) ?? "origin/main"; + const { stdout: head } = await run("git", ["rev-parse", "--verify", "HEAD"], { + cwd: root, + }); + const files = await collectOwnerReviewFiles(root, baseRef, run, head); + return { kind: "changes", baseRef, head, files }; +} + +function encodeReply(reply: CheckoutReply): string { + const encoded = JSON.stringify(reply) + "\n"; + if (Buffer.byteLength(encoded) > MAX_REPLY_BYTES) { + throw new Error("Checkout inspection reply is too large"); + } + return encoded; +} + +export async function inspectCheckout( + cwd: string, + query: CheckoutQuery +): Promise { + const validated = parseQuery(query); + // Preserve whitespace in the root, removing only Git's terminating newline. + const { stdout } = await run("git", ["rev-parse", "--show-toplevel"], { + cwd, + trimOutput: false, + }); + const root = stdout.replace(/\n$/, ""); + if (!path.isAbsolute(root)) + throw new Error("Could not resolve checkout root"); + const reply: CheckoutReply = + validated.kind === "changes" + ? await inspectChanges(root, validated.baseBranch) + : { + kind: "readFile", + content: await readWorktreeFile( + root, + validateFilePath(validated.path) + ), + }; + encodeReply(reply); + return reply; +} + +export async function runCheckoutInspectionCli(cwd: string): Promise { + try { + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of process.stdin) { + const bytes = Buffer.from(chunk); + size += bytes.length; + if (size > MAX_QUERY_BYTES) + throw new Error("Checkout inspection query is too large"); + chunks.push(bytes); + } + const query = parseQuery( + JSON.parse(Buffer.concat(chunks).toString("utf8")) + ); + const reply = await inspectCheckout(cwd, query); + await new Promise((resolve, reject) => { + process.stdout.write(encodeReply(reply), (error) => + error ? reject(error) : resolve() + ); + }); + } catch (error) { + const message = + error instanceof Error ? error.message : "Checkout inspection failed"; + process.stderr.write(message.slice(0, MAX_ERROR_BYTES) + "\n"); + process.exitCode = 1; + } +} diff --git a/apps/server/src/personas/codeowners.ts b/apps/server/src/personas/codeowners.ts index 83355561f..060744336 100644 --- a/apps/server/src/personas/codeowners.ts +++ b/apps/server/src/personas/codeowners.ts @@ -2,10 +2,11 @@ import { access, readFile } from "node:fs/promises"; import path from "node:path"; import * as z from "zod/v4"; -import type { CommandRunner } from "../shared/lib/run-command.js"; import { validatePersonaSlug } from "./authoring.js"; import { LEGACY_OWNERS_PATH, OWNERS_PATH } from "./paths.js"; +export { collectOwnerReviewFiles } from "../shared/git/owner-review-files.js"; + // Deliberately small glob language: repo-relative paths, *, **, and ?. // All matching rules contribute owners; there is no last-rule-wins behavior. const patternSchema = z @@ -165,41 +166,6 @@ export function resolveCodeowners( }; } -export async function collectOwnerReviewFiles( - cwd: string, - baseRef: string, - run: CommandRunner -): Promise { - // --no-renames represents a rename as deletion + addition, so both owners - // are selected. NUL delimiters preserve whitespace and unusual filenames. - const results = await Promise.all([ - run( - "git", - ["diff", "--name-only", "--no-renames", "-z", `${baseRef}...HEAD`, "--"], - { cwd, trimOutput: false } - ), - // Index and working-tree edits can cancel in diff HEAD. Collect both. - run( - "git", - ["diff", "--cached", "--name-only", "--no-renames", "-z", "HEAD", "--"], - { cwd, trimOutput: false } - ), - run("git", ["diff", "--name-only", "--no-renames", "-z", "--"], { - cwd, - trimOutput: false, - }), - run("git", ["ls-files", "--others", "--exclude-standard", "-z"], { - cwd, - trimOutput: false, - }), - ]); - return [ - ...new Set( - results.flatMap((result) => result.stdout.split("\0").filter(Boolean)) - ), - ].sort(); -} - export async function launchOwnerReviewPlan( plan: OwnerReviewPlan, context: string, diff --git a/apps/server/src/shared/git/base-ref.ts b/apps/server/src/shared/git/base-ref.ts index abbff63e9..903f15b81 100644 --- a/apps/server/src/shared/git/base-ref.ts +++ b/apps/server/src/shared/git/base-ref.ts @@ -12,9 +12,10 @@ export type ResolveBaseRefOptions = { function normalizeBranchName(ref: string | null | undefined): string | null { const candidate = ref?.trim(); if (!candidate || !isSafeRef(candidate)) return null; - return candidate.startsWith("origin/") + const branch = candidate.startsWith("origin/") ? candidate.slice("origin/".length) : candidate; + return isSafeRef(branch) ? branch : null; } async function resolveTargetBranch( diff --git a/apps/server/src/shared/git/owner-review-files.ts b/apps/server/src/shared/git/owner-review-files.ts new file mode 100644 index 000000000..02575ce66 --- /dev/null +++ b/apps/server/src/shared/git/owner-review-files.ts @@ -0,0 +1,44 @@ +import type { CommandRunner } from "../lib/run-command.js"; + +export async function collectOwnerReviewFiles( + cwd: string, + baseRef: string, + run: CommandRunner, + head: string = "HEAD" +): Promise { + // --no-renames represents a rename as deletion + addition, so both owners + // are selected. NUL delimiters preserve whitespace and unusual filenames. + const results = await Promise.all([ + run( + "git", + [ + "diff", + "--name-only", + "--no-renames", + "-z", + `${baseRef}...${head}`, + "--", + ], + { cwd, trimOutput: false } + ), + // Index and working-tree edits can cancel in diff HEAD. Collect both. + run( + "git", + ["diff", "--cached", "--name-only", "--no-renames", "-z", head, "--"], + { cwd, trimOutput: false } + ), + run("git", ["diff", "--name-only", "--no-renames", "-z", "--"], { + cwd, + trimOutput: false, + }), + run("git", ["ls-files", "--others", "--exclude-standard", "-z"], { + cwd, + trimOutput: false, + }), + ]); + return [ + ...new Set( + results.flatMap((result) => result.stdout.split("\0").filter(Boolean)) + ), + ].sort(); +} diff --git a/apps/server/test/checkout-inspection.test.ts b/apps/server/test/checkout-inspection.test.ts new file mode 100644 index 000000000..b6bc05fa3 --- /dev/null +++ b/apps/server/test/checkout-inspection.test.ts @@ -0,0 +1,286 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { CheckoutQuery, CheckoutReply } from "@dispatch/runner-protocol"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; + +import { inspectCheckout } from "../src/agents/checkout-inspection.js"; + +let scratch: string; +let cli: string; +let fixture: string; +let repo: string; +let checkout: string; +let bin: string; + +function git(cwd: string, ...args: string[]): string { + return execFileSync("git", args, { + cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }).trim(); +} + +function put(root: string, file: string, content: string): void { + const target = path.join(root, file); + mkdirSync(path.dirname(target), { recursive: true }); + writeFileSync(target, content); +} + +function runCli(cwd: string, input: string) { + const result = spawnSync(process.execPath, [cli], { + cwd, + input, + encoding: "utf8", + timeout: 10_000, + maxBuffer: 5 * 1024 * 1024, + }); + if (result.error) throw result.error; + return result; +} + +function subprocess(cwd: string, query: CheckoutQuery): Promise { + return Promise.resolve().then(() => { + const result = runCli(cwd, JSON.stringify(query)); + if (result.status !== 0) { + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + throw new Error(result.stderr.trim()); + } + expect(result.stderr).toBe(""); + return JSON.parse(result.stdout); + }); +} + +beforeAll(() => { + scratch = mkdtempSync( + path.join(os.tmpdir(), "dispatch-checkout-inspection-") + ); + cli = path.join(scratch, "inspect.mjs"); + const entry = path.join(scratch, "entry.ts"); + const implementation = fileURLToPath( + new URL("../src/agents/checkout-inspection.ts", import.meta.url) + ); + writeFileSync( + entry, + `import { runCheckoutInspectionCli } from ${JSON.stringify(implementation)};\nawait runCheckoutInspectionCli(process.cwd());\n` + ); + execFileSync("bun", ["build", "--target=node", "--outfile", cli, entry], { + stdio: "pipe", + }); +}); + +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +beforeEach(() => { + fixture = mkdtempSync(path.join(scratch, "repo-")); + repo = path.join(fixture, "origin"); + checkout = path.join(fixture, "linked worktree"); + bin = path.join(fixture, "bin"); + mkdirSync(bin); + mkdirSync(repo); + vi.stubEnv("PATH", bin + path.delimiter + process.env.PATH); + vi.stubEnv("GIT_CONFIG_GLOBAL", "/dev/null"); + vi.stubEnv("GIT_CONFIG_NOSYSTEM", "1"); + vi.stubEnv("GIT_ALLOW_PROTOCOL", "file"); + writeFileSync(path.join(bin, "gh"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + + git(repo, "init", "-b", "main"); + git(repo, "config", "user.email", "test@example.invalid"); + git(repo, "config", "user.name", "Checkout test"); + git(repo, "config", "commit.gpgsign", "false"); + put(repo, "rename source.txt", "rename"); + put(repo, "cancel.txt", "original"); + put(repo, "deleted.txt", "delete"); + put(repo, "unstaged.txt", "before"); + put(repo, ".gitignore", "ignore.me\n"); + git(repo, "add", "."); + git(repo, "commit", "-m", "base"); + git(repo, "worktree", "add", "-b", "feature", checkout); + git(repo, "remote", "add", "origin", repo); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(fixture, { recursive: true, force: true }); +}); + +describe.each([ + ["in process", inspectCheckout], + ["CLI", subprocess], +] as const)("checkout inspection %s", (_name, inspect) => { + it("refreshes a base and reports committed, staged, unstaged, deleted, renamed and untracked paths", async () => { + put(checkout, "committed.txt", "committed"); + git(checkout, "add", "committed.txt"); + git(checkout, "commit", "-m", "feature"); + git(checkout, "mv", "rename source.txt", "rename destination.txt"); + rmSync(path.join(checkout, "deleted.txt")); + put(checkout, "cancel.txt", "index"); + git(checkout, "add", "cancel.txt"); + put(checkout, "cancel.txt", "original"); + put(checkout, "unstaged.txt", "after"); + put(checkout, "sub/ unicode-齿\n.txt ", "untracked"); + put(checkout, "ignore.me", "ignored"); + expect( + await inspect(path.join(checkout, "sub"), { + kind: "changes", + baseBranch: "main", + }) + ).toEqual({ + kind: "changes", + baseRef: "origin/main", + head: git(checkout, "rev-parse", "HEAD"), + files: [ + "cancel.txt", + "committed.txt", + "deleted.txt", + "rename destination.txt", + "rename source.txt", + "sub/ unicode-齿\n.txt ", + "unstaged.txt", + ], + }); + expect(git(checkout, "rev-parse", "origin/main")).toBe( + git(repo, "rev-parse", "main") + ); + }); + + it("tries the PR base, then falls back to the configured upstream if no PR exists", async () => { + git(repo, "branch", "release"); + git(repo, "branch", "integration"); + git(checkout, "fetch", "origin", "integration"); + git(checkout, "branch", "--set-upstream-to", "origin/integration"); + writeFileSync( + path.join(bin, "gh"), + `#!/bin/sh +cat <<'JSON' +{"number":1,"url":"https://example.invalid/pr/1","title":"Test PR","state":"OPEN","isDraft":false,"headRefName":"feature","baseRefName":"release"} +JSON +` + ); + const expectBase = async (baseBranch: string | null, baseRef: string) => { + expect( + await inspect(checkout, { kind: "changes", baseBranch }) + ).toMatchObject({ baseRef, files: [] }); + }; + await expectBase(null, "origin/release"); + await expectBase("main", "origin/main"); + writeFileSync(path.join(bin, "gh"), "#!/bin/sh\nexit 1\n"); + await expectBase(null, "origin/integration"); + }); + + it("reads live, repo-relative regular files and reports missing files", async () => { + put(checkout, ".agents/owners.json", " owners 齿\n"); + expect( + await inspect(path.join(checkout, ".agents"), { + kind: "readFile", + path: ".agents/owners.json", + }) + ).toEqual({ + kind: "readFile", + content: " owners 齿\n", + }); + expect( + await inspect(checkout, { + kind: "readFile", + path: ".agents/missing.json", + }) + ).toEqual({ + kind: "readFile", + content: null, + }); + }); + + it("refuses escaping paths, Git metadata, symlinks, FIFOs and oversized files", async () => { + put(fixture, "outside/info", "outside"); + put(checkout, "oversized", "x".repeat(256 * 1024 + 1)); + symlinkSync( + path.join(fixture, "outside"), + path.join(checkout, "directory-link") + ); + symlinkSync( + path.join(fixture, "outside/info"), + path.join(checkout, "file-link") + ); + execFileSync("mkfifo", [path.join(checkout, "pipe")]); + for (const file of [ + "../outside/info", + path.join(fixture, "outside/info"), + ".git", + "directory-link/info", + "file-link", + "pipe", + "oversized", + ]) { + await expect( + inspect(checkout, { kind: "readFile", path: file }) + ).rejects.toThrow(); + } + }); + + it("rejects oversized Git output", async () => { + const realGit = execFileSync("which", ["git"], { encoding: "utf8" }).trim(); + vi.stubEnv("CHECKOUT_TEST_GIT", realGit); + vi.stubEnv("CHECKOUT_TEST_NODE", process.execPath); + writeFileSync( + path.join(bin, "git"), + `#!/bin/sh +if [ "$1" = ls-files ]; then + exec "$CHECKOUT_TEST_NODE" -e 'process.stdout.write("x".repeat(5 * 1024 * 1024))' +fi +exec "$CHECKOUT_TEST_GIT" "$@" +`, + { mode: 0o755 } + ); + await expect( + inspect(checkout, { kind: "changes", baseBranch: "main" }) + ).rejects.toThrow(/MAXBUFFER/); + }); + + it("fails with a Git diagnostic when no base resolves", async () => { + git(repo, "branch", "-m", "main", "trunk"); + await expect( + inspect(checkout, { kind: "changes", baseBranch: "unknown" }) + ).rejects.toThrow(/origin\/main/); + }); + + it("fails with a Git diagnostic outside a worktree", async () => { + await expect( + inspect(fixture, { kind: "changes", baseBranch: "main" }) + ).rejects.toThrow(/not a git repository/); + }); +}); + +it("rejects malformed and oversized stdin with stderr and no reply", () => { + for (const [input, diagnostic] of [ + ["{", /JSON/], + ['{"kind":"changes"}', /Invalid checkout inspection query/], + [ + '{"kind":"readFile","path":"file","cwd":"/"}', + /Invalid checkout inspection query/, + ], + [" ".repeat(16 * 1024 + 1), /query is too large/], + ] as const) { + const result = runCli(checkout, input); + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toMatch(diagnostic); + } +}); From cbb7af24ae8ec313d8c46bdc145b573539928de6 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:51:06 -0700 Subject: [PATCH 089/642] Fingerprint dirty checkout state and honor recorded review bases --- apps/server/src/agents/checkout-inspection.ts | 236 ++++++++++++++++-- .../src/shared/git/owner-review-files.ts | 32 ++- apps/server/test/checkout-inspection.test.ts | 70 +++++- 3 files changed, 303 insertions(+), 35 deletions(-) diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index d6f5b60d8..659310766 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -1,6 +1,7 @@ import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; import { constants } from "node:fs"; -import { lstat, open, type FileHandle } from "node:fs/promises"; +import { lstat, open, readlink, type FileHandle } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { @@ -13,13 +14,18 @@ import { refreshRemoteBaseRef, resolveBaseRef, } from "../shared/git/base-ref.js"; -import { collectOwnerReviewFiles } from "../shared/git/owner-review-files.js"; +import { + collectOwnerReviewChanges, + ownerReviewPaths, +} from "../shared/git/owner-review-files.js"; import { getPrStatus } from "../shared/github/pr.js"; import type { CommandRunner } from "../shared/lib/run-command.js"; const MAX_QUERY_BYTES = 16 * 1024; const MAX_REPLY_BYTES = 4 * 1024 * 1024; const MAX_FILE_BYTES = 256 * 1024; +const MAX_FINGERPRINT_BYTES = 16 * 1024 * 1024; +const MAX_FINGERPRINT_FILES = 10_000; const MAX_ERROR_BYTES = 4 * 1024; const execFileAsync = promisify(execFile); @@ -105,21 +111,8 @@ async function openRegularFile( throw new Error("Checkout file inspection requires macOS or Linux"); } - // Open each component relative to a pinned directory. A concurrent symlink - // replacement can't redirect either the directory traversal or the file open. - let directory = await open("/", LINUX_OPEN_PATH | constants.O_DIRECTORY); + const directory = await openLinuxDirectory(path.dirname(target)); try { - for (const segment of path - .join(root, ...segments.slice(0, -1)) - .split("/") - .filter(Boolean)) { - const next = await open( - `/proc/self/fd/${directory.fd}/${segment}`, - LINUX_OPEN_PATH | constants.O_DIRECTORY | constants.O_NOFOLLOW - ); - await directory.close(); - directory = next; - } const entry = await open( `/proc/self/fd/${directory.fd}/${segments.at(-1)}`, LINUX_OPEN_PATH | constants.O_NOFOLLOW @@ -136,6 +129,27 @@ async function openRegularFile( } } +// Pin every directory component so a symlink replacement cannot redirect +// traversal. The procfs path acts as openat for Node's pathname APIs. +async function openLinuxDirectory(target: string): Promise { + let directory = await open("/", LINUX_OPEN_PATH | constants.O_DIRECTORY); + try { + for (const segment of target.split("/").filter(Boolean)) { + const next = await open( + `/proc/self/fd/${directory.fd}/${segment}`, + LINUX_OPEN_PATH | constants.O_DIRECTORY | constants.O_NOFOLLOW + ); + const previous = directory; + directory = next; + await previous.close(); + } + return directory; + } catch (error) { + await directory.close(); + throw error; + } +} + async function readWorktreeFile( root: string, segments: string[] @@ -170,10 +184,139 @@ async function readWorktreeFile( } } -async function inspectChanges( +async function recordedReviewBase(root: string): Promise { + const { stdout: ref, exitCode } = await run( + "git", + ["symbolic-ref", "--quiet", "HEAD"], + { cwd: root, allowedExitCodes: [0, 1] } + ); + if (exitCode !== 0 || !ref.startsWith("refs/heads/")) return null; + const branch = ref.slice("refs/heads/".length); + + const { stdout: baseBranch } = await run( + "git", + ["config", "--local", "--get", `branch.${branch}.dispatchReviewBase`], + { cwd: root, allowedExitCodes: [0, 1], trimOutput: false } + ); + const query = { kind: "changes", baseBranch: baseBranch.replace(/\n$/, "") }; + if (!isCheckoutQuery(query)) return null; + + const { exitCode: invalid } = await run( + "git", + ["check-ref-format", `refs/heads/${query.baseBranch}`], + { cwd: root, allowedExitCodes: [0, 1] } + ); + return invalid === 0 ? query.baseBranch : null; +} + +async function describeWorktreePath(root: string, relative: string) { + const target = path.join(root, relative); + const parent = + process.platform === "linux" + ? await openLinuxDirectory(path.dirname(target)) + : await open( + path.dirname(target), + constants.O_DIRECTORY | DARWIN_NOFOLLOW_ANY + ); + try { + const entry = + process.platform === "linux" + ? `/proc/self/fd/${parent.fd}/${path.basename(target)}` + : target; + const stat = await lstat(entry); + if (stat.isSymbolicLink()) { + const link = await readlink(entry, { encoding: "buffer" }); + return { mode: stat.mode, link: link.toString("base64"), regular: false }; + } + if (stat.isDirectory()) { + throw new Error( + "Checkout fingerprint cannot inspect a dirty directory or submodule" + ); + } + return { mode: stat.mode, regular: stat.isFile() }; + } finally { + await parent.close(); + } +} + +async function fingerprintCheckout( root: string, - baseBranch: string | null -): Promise { + base: string, + head: string, + staged: string, + unmerged: string, + unstaged: string[], + untracked: string[] +): Promise { + if (unstaged.length + untracked.length > MAX_FINGERPRINT_FILES) + throw new Error("Too many dirty files to fingerprint the checkout"); + + const hash = createHash("sha256"); + hash.update(JSON.stringify([base, head, staged, unmerged])); + const buffer = Buffer.alloc(64 * 1024); + let remaining = MAX_FINGERPRINT_BYTES; + for (const [kind, files] of [ + ["unstaged", unstaged], + ["untracked", untracked], + ] as const) { + for (const relative of [...new Set(files)].sort()) { + const descriptor = await describeWorktreePath(root, relative).catch( + (error) => { + if ( + kind === "unstaged" && + (error as NodeJS.ErrnoException).code === "ENOENT" + ) + return null; + throw error; + } + ); + hash.update(JSON.stringify([kind, relative, descriptor])); + if (!descriptor?.regular) continue; + const file = await openRegularFile(root, relative.split("/")); + try { + const before = await file.stat(); + if (!before.isFile()) + throw new Error("Checkout changed while fingerprinting dirty files"); + if (before.size > remaining) + throw new Error( + "Dirty file contents exceed the checkout fingerprint limit" + ); + const content = createHash("sha256"); + let offset = 0; + for (;;) { + const { bytesRead } = await file.read( + buffer, + 0, + Math.min(buffer.length, remaining + 1), + offset + ); + if (bytesRead === 0) break; + offset += bytesRead; + remaining -= bytesRead; + if (remaining < 0) + throw new Error( + "Dirty file contents exceed the checkout fingerprint limit" + ); + content.update(buffer.subarray(0, bytesRead)); + } + const after = await file.stat(); + if ( + before.mode !== descriptor.mode || + before.ctimeMs !== after.ctimeMs || + before.size !== offset + ) + throw new Error("Checkout changed while fingerprinting dirty files"); + hash.update(content.digest()); + } finally { + await file.close(); + } + } + } + return hash.digest("hex"); +} + +async function inspectChanges(root: string, baseBranch: string | null) { + baseBranch ??= await recordedReviewBase(root); if (baseBranch === null) { try { baseBranch = (await getPrStatus({ cwd: root }, run)).baseRefName; @@ -186,13 +329,54 @@ async function inspectChanges( allowUpstreamFallback: baseBranch === null, }; await refreshRemoteBaseRef(root, baseBranch, options); - const baseRef = - (await resolveBaseRef(root, baseBranch, options)) ?? "origin/main"; - const { stdout: head } = await run("git", ["rev-parse", "--verify", "HEAD"], { - cwd: root, - }); - const files = await collectOwnerReviewFiles(root, baseRef, run, head); - return { kind: "changes", baseRef, head, files }; + const baseRef = await resolveBaseRef(root, baseBranch, options); + if (baseRef === null) + throw new Error("Could not resolve checkout base (origin/main fallback)"); + const [{ stdout: head }, { stdout: base }] = await Promise.all([ + run("git", ["rev-parse", "--verify", "HEAD"], { cwd: root }), + run( + "git", + ["rev-parse", "--verify", "--end-of-options", `${baseRef}^{commit}`], + { cwd: root } + ), + ]); + const [changes, staged, unmerged] = await Promise.all([ + collectOwnerReviewChanges(root, base, run, head), + run( + "git", + [ + "diff", + "--cached", + "--raw", + "--no-abbrev", + "--no-renames", + "-z", + head, + "--", + ], + { cwd: root, trimOutput: false } + ), + run("git", ["ls-files", "--unmerged", "-z"], { + cwd: root, + trimOutput: false, + }), + ]); + const stateId = await fingerprintCheckout( + root, + base, + head, + staged.stdout, + unmerged.stdout, + changes.unstaged, + changes.untracked + ); + return { + kind: "changes" as const, + baseRef, + head, + files: ownerReviewPaths(changes), + stateId, + }; } function encodeReply(reply: CheckoutReply): string { diff --git a/apps/server/src/shared/git/owner-review-files.ts b/apps/server/src/shared/git/owner-review-files.ts index 02575ce66..a7bc1e2c7 100644 --- a/apps/server/src/shared/git/owner-review-files.ts +++ b/apps/server/src/shared/git/owner-review-files.ts @@ -1,14 +1,14 @@ import type { CommandRunner } from "../lib/run-command.js"; -export async function collectOwnerReviewFiles( +export async function collectOwnerReviewChanges( cwd: string, baseRef: string, run: CommandRunner, head: string = "HEAD" -): Promise { +) { // --no-renames represents a rename as deletion + addition, so both owners // are selected. NUL delimiters preserve whitespace and unusual filenames. - const results = await Promise.all([ + const [committed, staged, unstaged, untracked] = await Promise.all([ run( "git", [ @@ -36,9 +36,25 @@ export async function collectOwnerReviewFiles( trimOutput: false, }), ]); - return [ - ...new Set( - results.flatMap((result) => result.stdout.split("\0").filter(Boolean)) - ), - ].sort(); + const paths = (stdout: string) => stdout.split("\0").filter(Boolean); + return { + committed: paths(committed.stdout), + staged: paths(staged.stdout), + unstaged: paths(unstaged.stdout), + untracked: paths(untracked.stdout), + }; +} + +export function ownerReviewPaths( + changes: Awaited> +): string[] { + return [...new Set(Object.values(changes).flat())].sort(); +} + +export async function collectOwnerReviewFiles( + cwd: string, + baseRef: string, + run: CommandRunner +): Promise { + return ownerReviewPaths(await collectOwnerReviewChanges(cwd, baseRef, run)); } diff --git a/apps/server/test/checkout-inspection.test.ts b/apps/server/test/checkout-inspection.test.ts index b6bc05fa3..675f00782 100644 --- a/apps/server/test/checkout-inspection.test.ts +++ b/apps/server/test/checkout-inspection.test.ts @@ -147,6 +147,7 @@ describe.each([ kind: "changes", baseRef: "origin/main", head: git(checkout, "rev-parse", "HEAD"), + stateId: expect.stringMatching(/^[0-9a-f]{64}$/), files: [ "cancel.txt", "committed.txt", @@ -186,6 +187,73 @@ JSON await expectBase(null, "origin/integration"); }); + it("uses the active branch's valid recorded base before inference", async () => { + git(repo, "branch", "-m", "main", "trunk"); + git(checkout, "config", "branch.feature.dispatchReviewBase", "trunk"); + git(checkout, "tag", "feature"); + const result = await inspect(checkout, { + kind: "changes", + baseBranch: null, + }); + expect(result).toMatchObject({ baseRef: "origin/trunk", files: [] }); + git(checkout, "config", "branch.feature.dispatchReviewBase", "trunk."); + await expect( + inspect(checkout, { kind: "changes", baseBranch: null }) + ).rejects.toThrow(/origin\/main/); + }); + + it("changes stateId for staged and unstaged edits to the same paths", async () => { + const query = { kind: "changes", baseBranch: "main" } as const; + put(checkout, "unstaged.txt", "after"); + const unstaged = await inspect(checkout, query); + expect(await inspect(checkout, query)).toEqual(unstaged); + put(checkout, "unstaged.txt", "other"); + const edited = await inspect(checkout, query); + git(checkout, "add", "unstaged.txt"); + const staged = await inspect(checkout, query); + put(checkout, "unstaged.txt", "index"); + git(checkout, "add", "unstaged.txt"); + const restaged = await inspect(checkout, query); + + const ids = [unstaged, edited, staged, restaged].map((result) => { + expect(result).toMatchObject({ + files: ["unstaged.txt"], + stateId: expect.stringMatching(/^[0-9a-f]{64}$/), + }); + return result.kind === "changes" && "stateId" in result + ? result.stateId + : null; + }); + expect(new Set(ids).size).toBe(ids.length); + }); + + it("fingerprints untracked bytes and symlink targets without reading symlink destinations or FIFOs", async () => { + const query = { kind: "changes", baseBranch: "main" } as const; + const target = path.join(fixture, "outside"); + put(fixture, "outside", "before"); + put(checkout, "untracked", "one"); + symlinkSync(target, path.join(checkout, "link")); + execFileSync("mkfifo", [path.join(checkout, "pipe")]); + const initial = await inspect(checkout, query); + put(fixture, "outside", "after"); + expect(await inspect(checkout, query)).toEqual(initial); + put(checkout, "untracked", "two"); + const edited = await inspect(checkout, query); + expect(edited).not.toEqual(initial); + rmSync(path.join(checkout, "link")); + symlinkSync(target + "-elsewhere", path.join(checkout, "link")); + const changedLink = await inspect(checkout, query); + expect(changedLink).toMatchObject({ files: ["link", "untracked"] }); + expect(changedLink).not.toEqual(edited); + }); + + it("rejects a dirty checkout above the fingerprint byte budget", async () => { + put(checkout, "untracked", "x".repeat(16 * 1024 * 1024 + 1)); + await expect( + inspect(checkout, { kind: "changes", baseBranch: "main" }) + ).rejects.toThrow(/fingerprint limit/); + }); + it("reads live, repo-relative regular files and reports missing files", async () => { put(checkout, ".agents/owners.json", " owners 齿\n"); expect( @@ -254,7 +322,7 @@ exec "$CHECKOUT_TEST_GIT" "$@" ).rejects.toThrow(/MAXBUFFER/); }); - it("fails with a Git diagnostic when no base resolves", async () => { + it("fails clearly when no base resolves", async () => { git(repo, "branch", "-m", "main", "trunk"); await expect( inspect(checkout, { kind: "changes", baseBranch: "unknown" }) From e2f9fad9127ff647fee1751fc84fdb91e7ae31ad Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:43:48 -0700 Subject: [PATCH 090/642] Route owner reviews through runner checkout inspection --- apps/server/src/personas/loader.ts | 30 +- apps/server/src/routes/mcp.ts | 20 +- .../server/src/server/mcp-persona-handlers.ts | 166 ++++-- .../test/mcp-persona-codeowners.test.ts | 554 +++++++++++------- apps/server/test/mcp-routes.test.ts | 41 ++ 5 files changed, 529 insertions(+), 282 deletions(-) diff --git a/apps/server/src/personas/loader.ts b/apps/server/src/personas/loader.ts index 1e7321e08..144a2e422 100644 --- a/apps/server/src/personas/loader.ts +++ b/apps/server/src/personas/loader.ts @@ -165,22 +165,34 @@ export async function loadPersonasFromRoots(input: { export async function loadPersonaBySlug( repoRoot: string, slug: string +): Promise { + return loadPersonaFromCheckout(slug, async (filePath) => { + try { + return await readFile(path.join(repoRoot, filePath), "utf-8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + }); +} + +/** Read and parse the first definition present in checkout precedence order. */ +export async function loadPersonaFromCheckout( + slug: string, + readCheckoutFile: (path: string) => Promise ): Promise { if (slug.includes("/") || slug.includes("\\") || slug.includes("..")) { throw new Error("Invalid persona slug."); } for (const personasDir of PERSONA_DIRS) { - const filePath = path.join(repoRoot, personasDir, `${slug}.md`); + const filePath = `${personasDir}/${slug}.md`; try { - return toPersonaDefinition(slug, await readFile(filePath, "utf-8")); + const content = await readCheckoutFile(filePath); + if (content !== null) return toPersonaDefinition(slug, content); } catch (error) { - // Only a missing file falls through; anything else must not silently - // select a stale legacy copy. - if ((error as NodeJS.ErrnoException).code !== "ENOENT") { - throw new Error( - `Could not read persona ${path.join(personasDir, `${slug}.md`)}: ${errorMessage(error)}` - ); - } + throw new Error( + `Could not read persona ${filePath}: ${errorMessage(error)}` + ); } } return null; diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index 5bebdc7fd..c6c4b20cf 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -5,6 +5,7 @@ import type { ScheduledMessageService } from "../scheduled-messages/service.js"; import path from "node:path"; import type { FastifyInstance } from "fastify"; +import { isJSONRPCRequest } from "@modelcontextprotocol/sdk/types.js"; import type { Pool } from "pg"; import type { SharedUiEvent } from "@dispatch/shared"; @@ -46,6 +47,19 @@ function onceResponseFinished(res: { }); } +function isOwnerReviewRequest(body: unknown): boolean { + const messages: unknown[] = Array.isArray(body) ? body : [body]; + return ( + messages.length > 0 && + messages.every( + (message) => + isJSONRPCRequest(message) && + message.method === "tools/call" && + message.params?.name === "launch_owner_reviews" + ) + ); +} + type McpRouteDeps = { pullRequests?: Pick; riskEnabled?: () => Promise; @@ -208,7 +222,9 @@ export async function registerMcpRoutes( // Repo tools, brain and job defaults follow a moved workspace. const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; try { - if (!remotePlacement(agent.cwd)) { + // Owner review gets checkout facts through the runner. Keep the usual + // scope for other requests, including batches with repo-dependent tools. + if (!remotePlacement(agent.cwd) && !isOwnerReviewRequest(request.body)) { repoRoot = await resolveRepoRoot(workspaceDir); worktreeRoot = await resolveWorktreeRoot(workspaceDir); } @@ -342,7 +358,7 @@ export async function registerMcpRoutes( // Repo tools, brain and job defaults follow a moved workspace. const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; try { - if (!remotePlacement(agent.cwd)) { + if (!remotePlacement(agent.cwd) && !isOwnerReviewRequest(request.body)) { repoRoot = await resolveRepoRoot(workspaceDir); worktreeRoot = await resolveWorktreeRoot(workspaceDir); } diff --git a/apps/server/src/server/mcp-persona-handlers.ts b/apps/server/src/server/mcp-persona-handlers.ts index f45f91c12..495f30019 100644 --- a/apps/server/src/server/mcp-persona-handlers.ts +++ b/apps/server/src/server/mcp-persona-handlers.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import type { Effort } from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; import { discoverPersonas, resolveLaunchPersona } from "../personas/resolve.js"; @@ -16,24 +17,17 @@ import { assemblePersonaPrompt, buildStandardFeedbackGuidance, MAX_PERSONA_PROMPT_BYTES, - loadPersonaBySlug, + loadPersonaFromCheckout, type PersonaDefinition, } from "../personas/loader.js"; import { - collectOwnerReviewFiles, launchOwnerReviewPlan, - loadCodeowners, + parseCodeowners, resolveCodeowners, type OwnerReviewResult, } from "../personas/codeowners.js"; -import { - refreshRemoteBaseRef, - resolveBaseRef, -} from "../shared/git/base-ref.js"; -import { resolveWorktreeRoot } from "../shared/git/git-context.js"; +import { LEGACY_OWNERS_PATH, OWNERS_PATH } from "../personas/paths.js"; import { validateAgentModel } from "../shared/agent-models.js"; -import { getPrStatus } from "../shared/github/pr.js"; -import { runCommand } from "../shared/lib/run-command.js"; import type { PublishUiEvent } from "./mcp-handler-types.js"; import { PERSONA_CONTEXT_ARG } from "../agents/acp/persona-context.js"; @@ -55,7 +49,7 @@ export type PersonaLaunchOptions = { agentType?: (typeof CLI_AGENT_TYPES)[number]; model?: string; effort?: Effort | null; - /** Internal: launch the exact checkout-local persona validated by the batch. */ + /** Internal: use a definition already selected by the caller. */ resolvedPersona?: PersonaDefinition; /** Display name; defaults to `-`. */ name?: string; @@ -70,6 +64,7 @@ export type PreparedPersonaLaunch = { effort: Effort | null; cwd: string; agentArgs: string[]; + fullAccess: boolean; }; /** @@ -82,38 +77,28 @@ export type PreparedPersonaLaunch = { export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { const { pool, agentManager, publishUiEvent, withStreamFlag } = deps; - async function resolveReviewBase( + async function preparePersonaLaunch( parent: AgentRecord, - cwd: string - ): Promise { - let baseBranch: string | null = parent.workspacePath - ? parent.workspaceBaseBranch - : (parent.baseBranch ?? - (parent.worktreePath && parent.worktreeBranch ? "main" : null)); - if (baseBranch == null) { - try { - baseBranch = - (await getPrStatus({ cwd }, runCommand)).baseRefName ?? null; - } catch { - /* No PR: use the normal upstream fallback. */ - } - } - const allowUpstreamFallback = baseBranch == null; - await refreshRemoteBaseRef(cwd, baseBranch, { - runCommand, - allowUpstreamFallback, - }); - return ( - (await resolveBaseRef(cwd, baseBranch, { - runCommand, - allowUpstreamFallback, - })) ?? "origin/main" + opts: PersonaLaunchOptions + ): Promise { + const cwd = agentWorkspaceDir(parent) ?? parent.cwd; + return prepareReviewLaunch( + parent, + opts, + cwd, + parent.fullAccess, + () => + opts.resolvedPersona ?? + resolveLaunchPersona(cwd, opts.persona, "review") ); } - async function preparePersonaLaunch( + async function prepareReviewLaunch( parent: AgentRecord, - opts: PersonaLaunchOptions + opts: PersonaLaunchOptions, + cwd: string, + fullAccess: boolean, + resolvePersona: () => PersonaDefinition | Promise ): Promise { const fallbackReviewType = isCliAgentType(parent.reviewAgentType) ? parent.reviewAgentType @@ -133,10 +118,7 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { const model = validateAgentModel(agentType, opts.model); const effort = validateAgentEffort(agentType, opts.effort, model); - const parentCwd = agentWorkspaceDir(parent) ?? parent.cwd; - const persona = - opts.resolvedPersona ?? - (await resolveLaunchPersona(parentCwd, opts.persona, "review")); + const persona = await resolvePersona(); if (!supportsPersonaType(persona, "review")) throw new Error( `Persona "${opts.persona}" is not available for review launches.` @@ -149,7 +131,7 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { PERSONA_CONTEXT_ARG, prompt, ]; - if (parent.fullAccess) { + if (fullAccess) { const fullAccessArg = agentType === "claude" ? CLAUDE_FULL_ACCESS_ARG @@ -164,8 +146,9 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { agentType, model, effort, - cwd: parentCwd, + cwd, agentArgs, + fullAccess, }; } @@ -177,16 +160,28 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { async function launchPersonaAgent( parentId: string, opts: PersonaLaunchOptions + ) { + const parent = await agentManager.getAgent(parentId); + if (!parent) throw new Error("Parent agent not found."); + return launchReviewer(parent, opts, () => + preparePersonaLaunch(parent, opts) + ); + } + + async function launchReviewer( + parent: AgentRecord, + opts: PersonaLaunchOptions, + prepare: () => Promise, + useWorktreeOf?: string ): Promise<{ agentId: string; name: string; persona: string; warnings?: string[]; }> { - const parent = await agentManager.getAgent(parentId); - if (!parent) throw new Error("Parent agent not found."); - // Lineage stays flat for display; the requester owns workspace, runtime - // permissions, provenance and feedback. Never prepare from the display parent. + const parentId = parent.id; + // Lineage stays flat for display. The requester owns the checkout, + // provenance and feedback even when it has a display parent. const displayParentId = parent.parentAgentId ?? parentId; if (parent.parentAgentId) { const displayParent = await agentManager.getAgent(displayParentId); @@ -195,7 +190,7 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { "Review display parent must belong to the requester's project." ); } - const prepared = await preparePersonaLaunch(parent, opts); + const prepared = await prepare(); const agent = await agentManager.createAgent( { name: opts.name ?? `${opts.persona}-${parentId.slice(-6)}`, @@ -204,17 +199,18 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { model: prepared.model, effort: prepared.effort, agentArgs: prepared.agentArgs, - fullAccess: parent.fullAccess, + fullAccess: prepared.fullAccess, useWorktree: false, persona: opts.persona, role: "review", parentAgentId: displayParentId, launchedByAgentId: parentId, + ...(useWorktreeOf ? { projectId: parent.projectId } : {}), personaContext: opts.context, initialPrompt: buildPersonaKickoffPrompt(parentId), launchContext: { prompt: opts.context }, }, - { detachLaunch: true } + { detachLaunch: true, ...(useWorktreeOf ? { useWorktreeOf } : {}) } ); const fresh = await agentManager.getAgent(agent.id); publishUiEvent({ @@ -248,12 +244,43 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { ): Promise { const parent = await agentManager.getAgent(parentId); if (!parent) throw new Error("Parent agent not found."); - const cwd = agentWorkspaceDir(parent) ?? parent.cwd; - const root = await resolveWorktreeRoot(cwd); - const config = await loadCodeowners(root); - const baseRef = await resolveReviewBase(parent, cwd); - const files = await collectOwnerReviewFiles(root, baseRef, runCommand); - const resolvedPlan = resolveCodeowners(config, files, baseRef); + const baseBranch = remotePlacement(parent.cwd) + ? null + : parent.workspacePath + ? (parent.workspaceBaseBranch ?? null) + : (parent.baseBranch ?? + (parent.worktreePath && parent.worktreeBranch ? "main" : null)); + const changes = await agentManager.inspectCheckout(parent, { + kind: "changes", + baseBranch, + }); + if (changes.kind !== "changes") + throw new Error("Runner did not return checkout changes."); + const readCheckoutFile = async (path: string) => { + const reply = await agentManager.inspectCheckout(parent, { + kind: "readFile", + path, + }); + if (reply.kind !== "readFile") + throw new Error("Runner did not return the checkout file."); + return reply.content; + }; + let ownersPath = OWNERS_PATH; + let content = await readCheckoutFile(ownersPath); + if (content === null) { + ownersPath = LEGACY_OWNERS_PATH; + content = await readCheckoutFile(ownersPath); + } + if (content === null) + throw new Error( + `No ${OWNERS_PATH} found in this workspace. Add ownership rules before launching owner reviews.` + ); + const config = parseCodeowners(content, ownersPath); + const resolvedPlan = resolveCodeowners( + config, + changes.files, + changes.baseRef + ); let plan = resolvedPlan; let omittedOwners: OwnerReviewResult["omittedOwners"]; if (opts.personas !== undefined) { @@ -284,7 +311,7 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { const selectedPersonas = new Map(); for (const owner of plan.owners) { const persona = - (await loadPersonaBySlug(root, owner.persona)) ?? + (await loadPersonaFromCheckout(owner.persona, readCheckoutFile)) ?? getBuiltInPersona(owner.persona); if (!persona) throw new Error( @@ -305,15 +332,28 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { const result = await launchOwnerReviewPlan( plan, opts.context, - (persona, context) => - launchPersonaAgent(parentId, { + (persona, context) => { + const launchOpts = { persona, - context, + context: `Inspect the shared checkout without modifying it. Report findings to the launcher.\n\n${context}`, agentType: opts.agentType, model: opts.model, effort: opts.effort, - resolvedPersona: selectedPersonas.get(persona), - }) + }; + return launchReviewer( + parent, + launchOpts, + () => + prepareReviewLaunch( + parent, + launchOpts, + parent.cwd, + false, + () => selectedPersonas.get(persona)! + ), + parent.id + ); + } ); return { ...result, ...selection }; } diff --git a/apps/server/test/mcp-persona-codeowners.test.ts b/apps/server/test/mcp-persona-codeowners.test.ts index 0a64c49d0..6ec625eef 100644 --- a/apps/server/test/mcp-persona-codeowners.test.ts +++ b/apps/server/test/mcp-persona-codeowners.test.ts @@ -1,46 +1,38 @@ -import { personaCatalog } from "../src/personas/catalog.js"; +import { access, readFile, readdir } from "node:fs/promises"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { personaCatalog } from "../src/personas/catalog.js"; import { createPersonaHandlers } from "../src/server/mcp-persona-handlers.js"; -import { loadCodeowners } from "../src/personas/codeowners.js"; -import { - loadPersonaBySlug, - assemblePersonaPrompt, -} from "../src/personas/loader.js"; import { - refreshRemoteBaseRef, - resolveBaseRef, -} from "../src/shared/git/base-ref.js"; -import { resolveRepoRoot } from "../src/shared/git/git-context.js"; + resolveRepoRoot, + resolveWorktreeRoot, +} from "../src/shared/git/git-context.js"; import { getBuiltInPersona } from "../src/personas/built-in.js"; import { runCommand } from "../src/shared/lib/run-command.js"; -vi.mock("../src/shared/git/git-context.js", () => ({ - resolveRepoRoot: vi.fn(async (cwd: string) => cwd), - resolveWorktreeRoot: vi.fn(async (cwd: string) => cwd), +vi.mock("node:fs/promises", async (importOriginal) => ({ + ...(await importOriginal()), + access: vi.fn(() => { + throw new Error("Unexpected checkout filesystem access"); + }), + readFile: vi.fn(() => { + throw new Error("Unexpected checkout filesystem read"); + }), + readdir: vi.fn(() => { + throw new Error("Unexpected checkout filesystem listing"); + }), })); -vi.mock("../src/shared/git/base-ref.js", () => ({ - refreshRemoteBaseRef: vi.fn(async () => {}), - resolveBaseRef: vi.fn(async () => "origin/acp-runtime"), -})); -vi.mock("../src/shared/github/pr.js", () => ({ - getPrStatus: vi.fn(async () => ({ baseRefName: "acp-runtime" })), +vi.mock("../src/shared/git/git-context.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../src/shared/git/git-context.js") + >()), + resolveRepoRoot: vi.fn(async () => "/main-checkout"), + resolveWorktreeRoot: vi.fn(async () => "/worktree"), })); vi.mock("../src/shared/lib/run-command.js", () => ({ - runCommand: vi.fn(async () => ({ - exitCode: 0, - stdout: "src/a.ts\0", - stderr: "", - })), -})); -vi.mock("../src/personas/loader.js", async (importOriginal) => ({ - ...(await importOriginal()), - loadPersonas: vi.fn(async () => []), - loadPersonaBySlug: vi.fn(), - assemblePersonaPrompt: vi.fn(() => "assembled-prompt"), - buildStandardFeedbackGuidance: vi.fn(() => "protected-review-guidance"), - MAX_PERSONA_PROMPT_BYTES: 64 * 1024, + runCommand: vi.fn(() => { + throw new Error("Unexpected local process"); + }), })); - vi.mock("../src/agent-type-settings.js", () => ({ CLI_AGENT_TYPES: ["codex", "claude", "opencode", "cursor"], getEnabledAgentTypes: vi.fn(async () => [ @@ -52,10 +44,15 @@ vi.mock("../src/agent-type-settings.js", () => ({ isCliAgentType: (type: string) => ["codex", "claude", "opencode", "cursor"].includes(type), })); -vi.mock("../src/personas/codeowners.js", async (importOriginal) => ({ - ...(await importOriginal()), - loadCodeowners: vi.fn(), -})); + +const modernOwnersPath = ".agents/owners.json"; +const legacyOwnersPath = ".dispatch/codeowners.json"; +const personaFile = (slug: string) => `.agents/personas/${slug}.md`; +const ownersMap = (...personas: string[]) => + JSON.stringify({ version: 1, rules: [{ paths: ["src/**"], personas }] }); +type Query = Parameters< + import("../src/agents/manager.js").AgentManager["inspectCheckout"] +>[1]; function setup(parentChanges: Record = {}) { const parent = { @@ -68,11 +65,34 @@ function setup(parentChanges: Record = {}) { baseBranch: "acp-runtime", type: "codex", parentAgentId: null, + projectId: "project", fullAccess: false, ...parentChanges, }; + const checkout = { + files: ["src/a.ts"], + baseRef: "origin/acp-runtime", + content: new Map([ + [modernOwnersPath, ownersMap("owner-one", "owner-two")], + [personaFile("owner-one"), "Verify subsystem contracts"], + [personaFile("owner-two"), "Verify other contracts"], + ]), + }; const agentManager = { getAgent: vi.fn(async (_id?: string) => parent), + inspectCheckout: vi.fn(async (_agent: typeof parent, query: Query) => + query.kind === "changes" + ? { + kind: "changes" as const, + baseRef: checkout.baseRef, + head: "head", + files: checkout.files, + } + : { + kind: "readFile" as const, + content: checkout.content.get(query.path) ?? null, + } + ), createAgent: vi.fn(async (input: { name: string }) => ({ id: `agent-${input.name}`, name: input.name, @@ -84,80 +104,117 @@ function setup(parentChanges: Record = {}) { publishUiEvent: vi.fn(), withStreamFlag: (agent: any) => ({ ...agent, hasStream: false }), }); - return { parent, agentManager, handlers }; + return { parent, agentManager, handlers, checkout }; } -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(resolveRepoRoot).mockImplementation(async (cwd) => cwd); - vi.mocked(loadCodeowners).mockResolvedValue({ - version: 1, - rules: [{ paths: ["src/**"], personas: ["owner-one", "owner-two"] }], - }); - vi.mocked(loadPersonaBySlug).mockImplementation(async (_root, slug) => ({ - slug, - name: slug, - description: "Owner", - type: "review", - body: "Verify subsystem contracts", - })); - vi.mocked(runCommand).mockResolvedValue({ - exitCode: 0, - stdout: "src/a.ts\0", - stderr: "", - }); -}); +beforeEach(() => vi.clearAllMocks()); + +describe("code owner launches through the checkout boundary", () => { + it.each([ + { cwd: "/checkout", baseBranch: "acp-runtime" }, + { cwd: "runner://linux/@session", baseBranch: null }, + ])( + "plans and launches using only runner checkout facts for $cwd", + async ({ cwd, baseBranch }) => { + const { handlers, agentManager, parent, checkout } = setup({ + cwd, + parentAgentId: "launcher", + fullAccess: true, + reviewAgentType: "claude", + }); + checkout.baseRef = "origin/review-target"; + checkout.files = [ + "src/unstaged.ts", + "src/staged.ts", + "src/committed.ts", + "src/untracked.ts", + "src/renamed-from.ts", + "renamed-to.ts", + ]; + checkout.content.set(legacyOwnersPath, ownersMap("legacy-owner")); + checkout.content.set( + ".dispatch/personas/owner-one.md", + "Stale legacy instructions" + ); + const context = "Changed routing"; + const preview = await handlers.launchOwnerReviews(parent.id, { + context, + dryRun: true, + }); + expect(preview).toEqual({ + baseRef: checkout.baseRef, + changedFiles: [...checkout.files].sort(), + owners: ["owner-one", "owner-two"].map((persona) => ({ + persona, + files: checkout.files + .filter((path) => path.startsWith("src/")) + .sort(), + })), + uncoveredFiles: ["renamed-to.ts"], + launched: [], + failures: [], + }); + expect(agentManager.createAgent).not.toHaveBeenCalled(); + + const result = await handlers.launchOwnerReviews(parent.id, { + context, + agentType: "opencode", + }); + expect(result).toEqual({ + ...preview, + launched: preview.owners.map((owner) => ({ + ...owner, + agentId: `agent-${owner.persona}-parent`, + })), + }); + expect(agentManager.inspectCheckout.mock.calls).toEqual([ + [parent, { kind: "changes", baseBranch }], + [parent, { kind: "readFile", path: modernOwnersPath }], + [parent, { kind: "changes", baseBranch }], + [parent, { kind: "readFile", path: modernOwnersPath }], + [parent, { kind: "readFile", path: personaFile("owner-one") }], + [parent, { kind: "readFile", path: personaFile("owner-two") }], + ]); + expect(agentManager.createAgent).toHaveBeenCalledWith( + expect.objectContaining({ + cwd, + type: "opencode", + persona: "owner-one", + projectId: "project", + parentAgentId: "launcher", + launchedByAgentId: "parent", + useWorktree: false, + fullAccess: false, + initialPrompt: expect.stringContaining('to: "parent"'), + agentArgs: expect.arrayContaining([ + expect.stringContaining("Verify subsystem contracts"), + expect.stringContaining('post with to: "parent"'), + ]), + personaContext: expect.stringContaining( + "Inspect the shared checkout without modifying it." + ), + }), + { detachLaunch: true, useWorktreeOf: "parent" } + ); + // These spies also catch checkout access hidden inside a helper. The source + // locator may be opaque, and neither placement may consult the server host. + for (const forbidden of [ + access, + readFile, + readdir, + runCommand, + resolveRepoRoot, + resolveWorktreeRoot, + ]) + expect(forbidden).not.toHaveBeenCalled(); + } + ); -describe("ACP code owner launches", () => { - it("previews selected owners without launching", async () => { - const { handlers, agentManager } = setup(); - const result = await handlers.launchOwnerReviews("parent", { - context: "Changed routing", - dryRun: true, - }); - expect(result.owners).toEqual([ - { persona: "owner-one", files: ["src/a.ts"] }, - { persona: "owner-two", files: ["src/a.ts"] }, - ]); - expect(result.launched).toEqual([]); - expect(agentManager.createAgent).not.toHaveBeenCalled(); - }); - it("launches ordinary ACP persona agents with the briefing and one resolved base", async () => { - const { handlers, agentManager } = setup(); - const result = await handlers.launchOwnerReviews("parent", { - context: "Changed routing", - agentType: "codex", - }); - expect(result.launched.map((owner) => owner.persona)).toEqual([ - "owner-one", - "owner-two", - ]); - expect(agentManager.createAgent).toHaveBeenCalledTimes(2); - expect(resolveBaseRef).toHaveBeenCalledTimes(1); - expect(assemblePersonaPrompt).toHaveBeenCalledWith( - expect.objectContaining({ slug: "owner-one" }), - expect.stringContaining("Changed routing") - ); - expect(agentManager.createAgent).toHaveBeenCalledWith( - expect.objectContaining({ - persona: "owner-one", - parentAgentId: "parent", - launchedByAgentId: "parent", - useWorktree: false, - cwd: "/checkout", - }), - { detachLaunch: true } - ); - }); it.each([false, true])( "selects and deduplicates a subset (dryRun=%s)", async (dryRun) => { - const { handlers, agentManager } = setup(); - vi.mocked(runCommand).mockResolvedValue({ - exitCode: 0, - stdout: "src/a.ts\0unowned.txt\0", - stderr: "", - }); + const { handlers, agentManager, checkout } = setup(); + checkout.files.push("unowned.txt"); const result = await handlers.launchOwnerReviews("parent", { context: "Subset review", personas: ["owner-two", "owner-two"], @@ -175,19 +232,24 @@ describe("ACP code owner launches", () => { ); expect(agentManager.createAgent).toHaveBeenCalledTimes(dryRun ? 0 : 1); if (!dryRun) - expect(assemblePersonaPrompt).toHaveBeenCalledWith( - expect.objectContaining({ slug: "owner-two" }), - expect.stringContaining('Matched changed paths:\n"src/a.ts"') + expect(agentManager.createAgent).toHaveBeenCalledWith( + expect.objectContaining({ + personaContext: expect.stringContaining( + 'Matched changed paths:\n"src/a.ts"' + ), + }), + { detachLaunch: true, useWorktreeOf: "parent" } ); } ); + it.each( [[], ["owner-one", "typo"], ["unrelated-persona"]].map((personas) => ({ personas, })) )("rejects invalid selection %j before launching", async ({ personas }) => { const { handlers, agentManager } = setup(); - for (const dryRun of [false, true]) { + for (const dryRun of [false, true]) await expect( handlers.launchOwnerReviews("parent", { context: "Review", @@ -195,106 +257,160 @@ describe("ACP code owner launches", () => { dryRun, }) ).rejects.toThrow(/at least one|not in the resolved owner plan/); - } expect(agentManager.createAgent).not.toHaveBeenCalled(); }); + it("validates all selected definitions before launching, including dry runs", async () => { - const { handlers, agentManager } = setup(); - vi.mocked(loadPersonaBySlug).mockResolvedValue(null); - for (const dryRun of [false, true]) { + const { handlers, agentManager, checkout } = setup(); + checkout.content.delete(personaFile("owner-two")); + for (const dryRun of [false, true]) await expect( handlers.launchOwnerReviews("parent", { context: "Review", personas: ["owner-one", "owner-two"], dryRun, }) - ).rejects.toThrow("not found"); - } + ).rejects.toThrow('Owner persona "owner-two" not found'); expect(agentManager.createAgent).not.toHaveBeenCalled(); }); - it("routes against a moved workspace and its base, not the original checkout", async () => { - const { handlers, agentManager } = setup({ - workspacePath: "/moved", - workspaceBaseBranch: "feature-base", - }); - await handlers.launchOwnerReviews("parent", { - context: "Changed moved workspace", - }); - expect(loadCodeowners).toHaveBeenCalledWith("/moved"); - expect(refreshRemoteBaseRef).toHaveBeenCalledWith( - "/moved", + + it.each([ + [ + { workspacePath: "/moved", workspaceBaseBranch: "feature-base" }, "feature-base", - expect.objectContaining({ allowUpstreamFallback: false }) - ); - expect(runCommand).toHaveBeenCalledWith( - "git", - expect.anything(), - expect.objectContaining({ cwd: "/moved" }) + ], + [{ workspacePath: "/moved", workspaceBaseBranch: null }, null], + [ + { baseBranch: null, worktreePath: "/managed", worktreeBranch: "feature" }, + "main", + ], + [{ baseBranch: null }, null], + ] as const)( + "preserves the local base choice for %j", + async (overrides, baseBranch) => { + const { handlers, agentManager, parent } = setup(overrides); + await handlers.launchOwnerReviews("parent", { + context: "Review", + dryRun: true, + }); + expect(agentManager.inspectCheckout).toHaveBeenCalledWith(parent, { + kind: "changes", + baseBranch, + }); + } + ); + + it("loads legacy rules and personas when modern paths are missing", async () => { + const { handlers, agentManager, checkout } = setup(); + checkout.content.delete(modernOwnersPath); + checkout.content.set(legacyOwnersPath, ownersMap("legacy-owner")); + checkout.content.set( + ".dispatch/personas/legacy-owner.md", + "Legacy review instructions" ); + const result = await handlers.launchOwnerReviews("parent", { + context: "Review", + }); + expect(result.launched.map(({ persona }) => persona)).toEqual([ + "legacy-owner", + ]); expect(agentManager.createAgent).toHaveBeenCalledWith( - expect.objectContaining({ cwd: "/moved" }), - expect.anything() + expect.objectContaining({ + agentArgs: expect.arrayContaining([ + expect.stringContaining("Legacy review instructions"), + ]), + }), + { detachLaunch: true, useWorktreeOf: "parent" } ); }); - it("launches the validated built-in instead of another checkout override", async () => { - const { handlers, parent } = setup(); - vi.mocked(resolveRepoRoot).mockResolvedValue("/main-checkout"); - vi.mocked(loadCodeowners).mockResolvedValue({ - version: 1, - rules: [{ paths: ["src/**"], personas: ["code-review"] }], + + it("reports a missing map", async () => { + const { handlers, checkout } = setup(); + checkout.content.delete(modernOwnersPath); + await expect( + handlers.launchOwnerReviews("parent", { context: "Review" }) + ).rejects.toThrow("No .agents/owners.json found"); + }); + + it("rejects an invalid modern map even when a legacy map is present", async () => { + const { handlers, agentManager, checkout } = setup(); + checkout.content.set(modernOwnersPath, ""); + checkout.content.set(legacyOwnersPath, ownersMap("owner-one")); + await expect( + handlers.launchOwnerReviews("parent", { context: "Review" }) + ).rejects.toThrow("Invalid .agents/owners.json"); + expect(agentManager.createAgent).not.toHaveBeenCalled(); + }); + + it("rejects an invalid modern persona even when a legacy persona is present", async () => { + const { handlers, agentManager, checkout } = setup(); + checkout.content.set( + personaFile("owner-one"), + "---\ntype: other\n---\nInvalid" + ); + checkout.content.set( + ".dispatch/personas/owner-one.md", + "Legacy instructions" + ); + await expect( + handlers.launchOwnerReviews("parent", { context: "Review" }) + ).rejects.toThrow("Invalid persona type"); + expect(agentManager.createAgent).not.toHaveBeenCalled(); + }); + + it("uses the built-in for owner review and allows catalog overrides for manual review", async () => { + const { handlers, agentManager, parent, checkout } = setup({ + fullAccess: true, }); + checkout.content.set(modernOwnersPath, ownersMap("code-review")); + const builtin = getBuiltInPersona("code-review")!; const override = { - ...getBuiltInPersona("code-review")!, + ...builtin, body: "Conflicting main checkout instructions", }; - vi.mocked(loadPersonaBySlug).mockImplementation(async (root) => - root === "/main-checkout" ? override : null - ); - await handlers.launchOwnerReviews("parent", { context: "Review" }); - expect(assemblePersonaPrompt).toHaveBeenLastCalledWith( - getBuiltInPersona("code-review"), - expect.any(String) - ); - expect(loadPersonaBySlug).not.toHaveBeenCalledWith( - "/main-checkout", - "code-review" - ); - // Ordinary manual launches may use the shared remote catalog, but owner - // reviews must stay pinned to their own workspace. - vi.spyOn(personaCatalog, "get").mockResolvedValueOnce({ + const catalog = vi.spyOn(personaCatalog, "get").mockResolvedValueOnce({ personas: [override], warnings: [], refreshing: false, updatedAt: null, }); - await handlers.preparePersonaLaunch(parent as any, { - persona: "code-review", - context: "Manual review", - }); - expect(assemblePersonaPrompt).toHaveBeenLastCalledWith( - override, - "Manual review" - ); + try { + await handlers.launchOwnerReviews("parent", { context: "Review" }); + expect(catalog).not.toHaveBeenCalled(); + expect(agentManager.createAgent).toHaveBeenCalledWith( + expect.objectContaining({ + fullAccess: false, + agentArgs: expect.arrayContaining([ + expect.stringContaining(builtin.body.trimEnd()), + ]), + }), + { detachLaunch: true, useWorktreeOf: "parent" } + ); + const absent = Object.assign(new Error("Persona file absent"), { + code: "ENOENT", + }); + vi.mocked(readFile) + .mockRejectedValueOnce(absent) + .mockRejectedValueOnce(absent); + await handlers.launchPersonaAgent(parent.id, { + persona: "code-review", + context: "Manual review", + }); + expect(agentManager.createAgent).toHaveBeenLastCalledWith( + expect.objectContaining({ + fullAccess: true, + agentArgs: expect.arrayContaining([ + "--dangerously-bypass-approvals-and-sandbox", + expect.stringContaining(override.body), + ]), + }), + { detachLaunch: true } + ); + } finally { + catalog.mockRestore(); + } }); - it("rejects unknown owners before creating any agents", async () => { - const { handlers, agentManager } = setup(); - vi.mocked(loadPersonaBySlug).mockImplementation(async (_root, slug) => - slug === "owner-two" - ? null - : { - slug, - name: slug, - description: "Owner", - type: "review", - body: "Instructions", - } - ); - await expect( - handlers.launchOwnerReviews("parent", { context: "Review" }) - ).rejects.toThrow('Owner persona "owner-two" not found'); - expect(agentManager.createAgent).not.toHaveBeenCalled(); - }); it("reports a partial launch without hiding successful agents", async () => { const { handlers, agentManager } = setup(); agentManager.createAgent.mockRejectedValueOnce( @@ -314,41 +430,53 @@ describe("ACP code owner launches", () => { }, ]); }); - it("launches child owner reviews in the caller checkout with flat lineage and caller delivery", async () => { + + it("surfaces unavailable shared-checkout launch on a runner that can inspect", async () => { const { handlers, agentManager } = setup({ - parentAgentId: "launcher", - worktreePath: "/child-checkout", - fullAccess: false, + cwd: "runner://older/@session", + reviewAgentType: "claude", }); + agentManager.createAgent.mockRejectedValueOnce( + new Error("Runner does not support sharing checkouts") + ); const result = await handlers.launchOwnerReviews("parent", { - context: "Review child changes", - personas: ["owner-two"], + context: "Review", + personas: ["owner-one"], }); - expect(loadCodeowners).toHaveBeenCalledWith("/child-checkout"); - expect(loadPersonaBySlug).toHaveBeenCalledWith( - "/child-checkout", - "owner-two" - ); - expect(result.launched).toHaveLength(1); - expect(agentManager.createAgent).toHaveBeenCalledWith( + expect(result.launched).toEqual([]); + expect(result.failures).toEqual([ + { + persona: "owner-one", + files: ["src/a.ts"], + error: "Runner does not support sharing checkouts", + }, + ]); + expect(agentManager.createAgent).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ - cwd: "/child-checkout", - parentAgentId: "launcher", - launchedByAgentId: "parent", + cwd: "runner://older/@session", + type: "claude", fullAccess: false, - initialPrompt: expect.stringContaining('to: "parent"'), }), - { detachLaunch: true } + { detachLaunch: true, useWorktreeOf: "parent" } ); }); - it("rejects a cross-project display parent before creating a reviewer", async () => { + + it("rejects cross-project display parents for both owner and manual launch", async () => { const { handlers, agentManager, parent } = setup({ parentAgentId: "launcher", - projectId: "child-project", }); agentManager.getAgent.mockImplementation(async (id?: string) => id === "launcher" ? { ...parent, projectId: "other-project" } : parent ); + const result = await handlers.launchOwnerReviews("parent", { + context: "Review", + }); + expect(result.launched).toEqual([]); + expect(result.failures.map(({ error }) => error)).toEqual( + Array(2).fill( + "Review display parent must belong to the requester's project." + ) + ); await expect( handlers.launchPersonaAgent("parent", { persona: "owner-one", @@ -357,12 +485,22 @@ describe("ACP code owner launches", () => { ).rejects.toThrow("requester's project"); expect(agentManager.createAgent).not.toHaveBeenCalled(); }); - it("propagates git failures instead of treating them as empty changes", async () => { - const { handlers, agentManager } = setup(); - vi.mocked(runCommand).mockRejectedValue(new Error("Cannot read diff")); - await expect( - handlers.launchOwnerReviews("parent", { context: "Review" }) - ).rejects.toThrow("Cannot read diff"); + + it.each([ + { cwd: "/checkout", reason: "Cannot read diff" }, + { + cwd: "runner://old/@session", + reason: "Runner does not support checkout inspection", + }, + ])("surfaces checkout failure for $cwd", async ({ cwd, reason }) => { + const { handlers, agentManager } = setup({ cwd }); + agentManager.inspectCheckout.mockRejectedValue(new Error(reason)); + for (const dryRun of [false, true]) + await expect( + handlers.launchOwnerReviews("parent", { context: "Review", dryRun }) + ).rejects.toThrow(reason); expect(agentManager.createAgent).not.toHaveBeenCalled(); + expect(runCommand).not.toHaveBeenCalled(); + expect(readFile).not.toHaveBeenCalled(); }); }); diff --git a/apps/server/test/mcp-routes.test.ts b/apps/server/test/mcp-routes.test.ts index fe71f2752..222895914 100644 --- a/apps/server/test/mcp-routes.test.ts +++ b/apps/server/test/mcp-routes.test.ts @@ -11,6 +11,10 @@ import Fastify, { type FastifyInstance } from "fastify"; import { registerMcpRoutes } from "../src/routes/mcp.js"; import { handleMcpRequest } from "../src/shared/mcp/server.js"; +import { + resolveRepoRoot, + resolveWorktreeRoot, +} from "../src/shared/git/git-context.js"; // The routes hijack the reply and hand the raw socket to the MCP transport, // so the stub has to end the response itself or `inject` never settles. @@ -317,6 +321,43 @@ describe("usage callback wiring", () => { ); }); +describe("owner review checkout boundary", () => { + it.each(["/api/mcp/agt_test1", "/api/mcp/jobs/run_1/agt_test1"])( + "skips host checkout discovery for owner calls on %s", + async (url) => { + const call = { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { + name: "launch_owner_reviews", + arguments: { context: "Review" }, + }, + }; + for (const payload of [call, [call, { ...call, id: 2 }]]) { + const res = await app.inject({ method: "POST", url, payload }); + expect(res.statusCode).toBe(200); + expect(handleMcpRequest).toHaveBeenLastCalledWith( + expect.anything(), + expect.anything(), + payload, + expect.objectContaining({ repoRoot: null, worktreeRoot: null }) + ); + expect(resolveRepoRoot).not.toHaveBeenCalled(); + expect(resolveWorktreeRoot).not.toHaveBeenCalled(); + } + const res = await app.inject({ + method: "POST", + url, + payload: [call, { ...call, id: 2, params: { name: "list_personas" } }], + }); + expect(res.statusCode).toBe(200); + expect(resolveRepoRoot).toHaveBeenCalledWith("/tmp/test"); + expect(resolveWorktreeRoot).toHaveBeenCalledWith("/tmp/test"); + } + ); +}); + describe("job access ceiling wiring", () => { it.each([ ["/api/mcp/agt_test1", false], From 9c296aff7f16f07a62693eaa27566de02f298404 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:48:26 -0700 Subject: [PATCH 091/642] Recheck checkout state before launching owner reviews --- apps/server/src/personas/codeowners.ts | 13 +++- .../server/src/server/mcp-persona-handlers.ts | 67 +++++++++++++------ .../test/mcp-persona-codeowners.test.ts | 35 +++++++++- .../test/persona-interaction-tools.test.ts | 1 + 4 files changed, 90 insertions(+), 26 deletions(-) diff --git a/apps/server/src/personas/codeowners.ts b/apps/server/src/personas/codeowners.ts index 060744336..7568f491b 100644 --- a/apps/server/src/personas/codeowners.ts +++ b/apps/server/src/personas/codeowners.ts @@ -54,7 +54,7 @@ export type OwnerReviewPlan = { owners: Array<{ persona: string; files: string[] }>; uncoveredFiles: string[]; }; -export type OwnerReviewResult = OwnerReviewPlan & { +type OwnerReviewLaunchResult = OwnerReviewPlan & { /** Present for explicit selection; omitted owners have not been launched. */ omittedOwners?: OwnerReviewPlan["owners"]; launched: Array<{ @@ -65,6 +65,9 @@ export type OwnerReviewResult = OwnerReviewPlan & { }>; failures: Array<{ persona: string; error: string; files: string[] }>; }; +export type OwnerReviewResult = OwnerReviewLaunchResult & { + reviewedState: { head: string; stateId: string }; +}; /** The owners map in use: `.agents/owners.json`, else the legacy location. */ async function findOwnersPath(root: string): Promise { @@ -173,8 +176,12 @@ export async function launchOwnerReviewPlan( persona: string, context: string ) => Promise<{ agentId: string; warnings?: string[] }> -): Promise { - const result: OwnerReviewResult = { ...plan, launched: [], failures: [] }; +): Promise { + const result: OwnerReviewLaunchResult = { + ...plan, + launched: [], + failures: [], + }; // Launch sequentially to preserve normal lifecycle ordering. Review agents // run concurrently once started. A failure must not hide successful launches. for (const owner of plan.owners) { diff --git a/apps/server/src/server/mcp-persona-handlers.ts b/apps/server/src/server/mcp-persona-handlers.ts index 495f30019..54aecc1be 100644 --- a/apps/server/src/server/mcp-persona-handlers.ts +++ b/apps/server/src/server/mcp-persona-handlers.ts @@ -244,18 +244,8 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { ): Promise { const parent = await agentManager.getAgent(parentId); if (!parent) throw new Error("Parent agent not found."); - const baseBranch = remotePlacement(parent.cwd) - ? null - : parent.workspacePath - ? (parent.workspaceBaseBranch ?? null) - : (parent.baseBranch ?? - (parent.worktreePath && parent.worktreeBranch ? "main" : null)); - const changes = await agentManager.inspectCheckout(parent, { - kind: "changes", - baseBranch, - }); - if (changes.kind !== "changes") - throw new Error("Runner did not return checkout changes."); + const changes = await inspectReviewChanges(parent); + const reviewedState = { head: changes.head, stateId: changes.stateId }; const readCheckoutFile = async (path: string) => { const reply = await agentManager.inspectCheckout(parent, { kind: "readFile", @@ -304,12 +294,12 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { }; } const selection = omittedOwners === undefined ? {} : { omittedOwners }; - if (opts.dryRun && opts.personas === undefined) - return { ...plan, launched: [], failures: [] }; // Resolve the whole selection before launching any agent. Ownership is // local to this checkout, even though manual persona launches can fall back. const selectedPersonas = new Map(); - for (const owner of plan.owners) { + const validateOwners = + opts.dryRun && opts.personas === undefined ? [] : plan.owners; + for (const owner of validateOwners) { const persona = (await loadPersonaFromCheckout(owner.persona, readCheckoutFile)) ?? getBuiltInPersona(owner.persona); @@ -327,35 +317,68 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { ); selectedPersonas.set(owner.persona, persona); } + const author = await agentManager.getAgent(parentId); + if (!author) throw new Error("Parent agent not found."); + const latest = await inspectReviewChanges(author); + if ( + latest.baseRef !== changes.baseRef || + latest.head !== reviewedState.head || + latest.stateId !== reviewedState.stateId + ) + throw new Error( + "The checkout changed while planning owner reviews. Finish the checkout changes, then retry launch_owner_reviews." + ); if (opts.dryRun) - return { ...plan, ...selection, launched: [], failures: [] }; + return { + ...plan, + ...selection, + reviewedState, + launched: [], + failures: [], + }; const result = await launchOwnerReviewPlan( plan, opts.context, (persona, context) => { const launchOpts = { persona, - context: `Inspect the shared checkout without modifying it. Report findings to the launcher.\n\n${context}`, + context: `Inspect the shared checkout without modifying it. Report findings to the launcher.\nCheckout recorded during review planning: HEAD ${reviewedState.head}, state ID ${reviewedState.stateId}.\n\n${context}`, agentType: opts.agentType, model: opts.model, effort: opts.effort, }; return launchReviewer( - parent, + author, launchOpts, () => prepareReviewLaunch( - parent, + author, launchOpts, - parent.cwd, + author.cwd, false, () => selectedPersonas.get(persona)! ), - parent.id + author.id ); } ); - return { ...result, ...selection }; + return { ...result, ...selection, reviewedState }; + } + + async function inspectReviewChanges(agent: AgentRecord) { + const baseBranch = remotePlacement(agent.cwd) + ? null + : agent.workspacePath + ? (agent.workspaceBaseBranch ?? null) + : (agent.baseBranch ?? + (agent.worktreePath && agent.worktreeBranch ? "main" : null)); + const reply = await agentManager.inspectCheckout(agent, { + kind: "changes", + baseBranch, + }); + if (reply.kind !== "changes") + throw new Error("Runner did not return checkout changes."); + return reply; } async function listPersonas(agentCwd: string) { diff --git a/apps/server/test/mcp-persona-codeowners.test.ts b/apps/server/test/mcp-persona-codeowners.test.ts index 6ec625eef..67831ae27 100644 --- a/apps/server/test/mcp-persona-codeowners.test.ts +++ b/apps/server/test/mcp-persona-codeowners.test.ts @@ -72,6 +72,8 @@ function setup(parentChanges: Record = {}) { const checkout = { files: ["src/a.ts"], baseRef: "origin/acp-runtime", + head: "a".repeat(40), + stateId: "1".repeat(64), content: new Map([ [modernOwnersPath, ownersMap("owner-one", "owner-two")], [personaFile("owner-one"), "Verify subsystem contracts"], @@ -85,7 +87,8 @@ function setup(parentChanges: Record = {}) { ? { kind: "changes" as const, baseRef: checkout.baseRef, - head: "head", + head: checkout.head, + stateId: checkout.stateId, files: checkout.files, } : { @@ -143,6 +146,7 @@ describe("code owner launches through the checkout boundary", () => { }); expect(preview).toEqual({ baseRef: checkout.baseRef, + reviewedState: { head: checkout.head, stateId: checkout.stateId }, changedFiles: [...checkout.files].sort(), owners: ["owner-one", "owner-two"].map((persona) => ({ persona, @@ -171,9 +175,11 @@ describe("code owner launches through the checkout boundary", () => { [parent, { kind: "changes", baseBranch }], [parent, { kind: "readFile", path: modernOwnersPath }], [parent, { kind: "changes", baseBranch }], + [parent, { kind: "changes", baseBranch }], [parent, { kind: "readFile", path: modernOwnersPath }], [parent, { kind: "readFile", path: personaFile("owner-one") }], [parent, { kind: "readFile", path: personaFile("owner-two") }], + [parent, { kind: "changes", baseBranch }], ]); expect(agentManager.createAgent).toHaveBeenCalledWith( expect.objectContaining({ @@ -189,6 +195,9 @@ describe("code owner launches through the checkout boundary", () => { agentArgs: expect.arrayContaining([ expect.stringContaining("Verify subsystem contracts"), expect.stringContaining('post with to: "parent"'), + expect.stringContaining( + `HEAD ${checkout.head}, state ID ${checkout.stateId}` + ), ]), personaContext: expect.stringContaining( "Inspect the shared checkout without modifying it." @@ -210,6 +219,30 @@ describe("code owner launches through the checkout boundary", () => { } ); + it.each([ + { cwd: "/checkout", path: modernOwnersPath, dryRun: true }, + { + cwd: "runner://linux/@session", + path: personaFile("owner-two"), + dryRun: false, + }, + ])( + "rejects a changed dirty state during $path inspection", + async ({ cwd, path, dryRun }) => { + const { handlers, agentManager, checkout } = setup({ cwd }); + const inspect = agentManager.inspectCheckout.getMockImplementation()!; + agentManager.inspectCheckout.mockImplementation((agent, query) => { + if (query.kind === "readFile" && query.path === path) + checkout.stateId = "2".repeat(64); + return inspect(agent, query); + }); + await expect( + handlers.launchOwnerReviews("parent", { context: "Review", dryRun }) + ).rejects.toThrow(/checkout changed.*retry launch_owner_reviews/i); + expect(agentManager.createAgent).not.toHaveBeenCalled(); + } + ); + it.each([false, true])( "selects and deduplicates a subset (dryRun=%s)", async (dryRun) => { diff --git a/apps/server/test/persona-interaction-tools.test.ts b/apps/server/test/persona-interaction-tools.test.ts index 44f2b69a4..af70ec32b 100644 --- a/apps/server/test/persona-interaction-tools.test.ts +++ b/apps/server/test/persona-interaction-tools.test.ts @@ -244,6 +244,7 @@ describe("launch_owner_reviews MCP tool", () => { changedFiles: ["src/a.ts"], owners: [], uncoveredFiles: [], + reviewedState: { head: "a".repeat(40), stateId: "1".repeat(64) }, launched: [ { persona: "owner", From bbaff672dafa9e2313168e04eded4d5ef813e663 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:55:09 -0700 Subject: [PATCH 092/642] Allow configured and nested runner review checkouts --- .../src/agents/remote/session-supervisor.ts | 103 ++++++++++++------ .../test/remote-runner-supervisor.test.ts | 92 ++++++++++++++-- 2 files changed, 150 insertions(+), 45 deletions(-) diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index cada3fded..68de29783 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -12,7 +12,6 @@ import { rename, rm, rmdir, - stat, writeFile, } from "node:fs/promises"; import { createConnection } from "node:net"; @@ -161,15 +160,16 @@ export async function createSessionSupervisor( }); } - function withLaunchLocks( - key: string, - owner: string | null, - operation: () => Promise - ) { - if (owner === null) return serialize(key, operation); - // Acquire both keys in a stable order, including for invalid cross-loans. - const [first, second] = key < owner ? [key, owner] : [owner, key]; - return serialize(first, () => serialize(second, operation)); + function withLaunchLocks(keys: string[], operation: () => Promise) { + // Acquire the launch, author, and checkout keys in a stable order. + const ordered = [...new Set(keys)].sort(); + const acquire = (index: number): Promise => { + const key = ordered[index]; + return key === undefined + ? operation() + : serialize(key, () => acquire(index + 1)); + }; + return acquire(0); } async function syncBindings() { @@ -269,6 +269,20 @@ export async function createSessionSupervisor( return entry; } + async function configuredDirectory(key: string, configuredCwd?: string) { + const stored = await readOptional(cwdFile(key)); + const current = + configuredCwd === undefined ? undefined : await realpath(configuredCwd); + if (stored !== null && current !== undefined && current !== stored) + throw new Error("Agent is bound to a different configured directory."); + const cwd = stored ?? current; + if (cwd === undefined) + throw new Error("The runner session checkout is unavailable."); + await checkedDirectory(cwd); + if (stored === null) await writePrivateState(cwdFile(key), cwd); + return cwd; + } + function checkoutParentIsProtected(entry: Stats | null) { return ( entry !== null && @@ -400,9 +414,12 @@ export async function createSessionSupervisor( cwd = await managedDirectory(key); } } - if (!cwd || (!managed && !(await stat(cwd)).isDirectory())) - throw new Error("Guest workspace is unavailable"); - if (!managed) await writePrivateState(cwdFile(key), await realpath(cwd)); + if (!cwd) throw new Error("Guest workspace is unavailable"); + if (!managed) { + if (command.launch.useWorktreeOf === undefined) cwd = await realpath(cwd); + await checkedDirectory(cwd); + await writePrivateState(cwdFile(key), cwd); + } const dir = path.join(hostRoot, key); const files = path.join(dir, "files"); const { @@ -521,24 +538,48 @@ export async function createSessionSupervisor( const key = runnerStorageKey(command.agentId); const { useWorktreeOf } = command.launch; if (useWorktreeOf === undefined) - return withLaunchLocks(key, null, () => - launch(command, cwd, key, null) - ); + return serialize(key, () => launch(command, cwd, key, null)); if (!isOpaqueId(useWorktreeOf) || useWorktreeOf === command.agentId) throw new Error("Invalid author for a shared runner checkout."); - if ( - !managedTarget(command.workspace) || - command.launch.repository !== undefined - ) - throw new Error( - "Sharing requires a managed runner session without a repository selection." - ); - const owner = runnerStorageKey(useWorktreeOf); - return withLaunchLocks(key, owner, () => - launch(command, cwd, key, owner) - ); + if (command.launch.repository !== undefined) + throw new Error("A shared runner checkout cannot select a repository."); + const { workspace } = command; + const author = runnerStorageKey(useWorktreeOf); + if (!managedTarget(workspace)) { + return withLaunchLocks([key, author], async () => { + if ((await readBinding(author)) !== workspace) + throw new Error( + "The author is not bound to this runner workspace." + ); + if (cwd === undefined) + throw new Error("Guest workspace is unavailable"); + return launch( + command, + await configuredDirectory(author, cwd), + key, + null + ); + }); + } + const owner = checkoutOwner(await readBinding(author)) ?? author; + if (owner === key) + throw new Error("Invalid author for a shared runner checkout."); + return withLaunchLocks([key, author, owner], async () => { + if ( + author !== owner && + (checkoutOwner(await readBinding(author)) !== owner || + (await readOptional(retireFile(author))) !== null) + ) + throw new Error("The author does not own a checkout on this runner."); + return launch(command, cwd, key, owner); + }); }, - checkoutDirectory(agentId: string, workspace: string): Promise { + checkoutDirectory( + agentId: string, + workspace: string, + // Only the runner's configured path may supply a missing legacy cwd. + configuredCwd?: string + ): Promise { const key = runnerStorageKey(agentId); return serialize(key, async () => { const managed = managedTarget(workspace); @@ -555,11 +596,7 @@ export async function createSessionSupervisor( ); return managedDirectory(owner ?? key); } - const cwd = await readOptional(cwdFile(key)); - if (cwd === null) - throw new Error("The runner session checkout is unavailable."); - await checkedDirectory(cwd); - return cwd; + return configuredDirectory(key, configuredCwd); }); }, async alive(agentId: string, workspace: string) { diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index c4cceba22..e4900295b 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -403,7 +403,7 @@ describe("runner session supervision", () => { await expect(discarding).rejects.toThrow("still in use"); }); - it("rejects invalid, unbound and chained author references", async () => { + it("rejects invalid, unbound and indirect self references", async () => { const running = await start([]); await expect( running.launch(sharedLaunch(reviewerId), undefined) @@ -418,26 +418,94 @@ describe("runner session supervision", () => { processes.spawn.mockResolvedValueOnce(); await running.launch(sharedLaunch(), undefined); await expect( - running.launch( - { ...sharedLaunch(reviewerId), agentId: "agt_chain" }, - undefined - ) - ).rejects.toThrow("does not own"); + running.launch({ ...sharedLaunch(reviewerId), agentId }, undefined) + ).rejects.toThrow("Invalid author"); expect(processes.spawn).toHaveBeenCalledTimes(2); }); - it("keeps named launches and rejects borrowing through a named workspace", async () => { + it("binds a nested managed reviewer directly to the durable checkout owner", async () => { + const workspace = MANAGED_WORKSPACE; + const nested = "agt_nested"; + const running = await start([]); + await running.launch(launch(workspace), undefined); + await running.stop(agentId, workspace, true); + processes.spawn.mockResolvedValueOnce(); + await running.launch(sharedLaunch(), undefined); + running.close(); + + const recovered = await start([]); + processes.spawn.mockResolvedValueOnce(); + await recovered.launch( + { ...sharedLaunch(reviewerId), agentId: nested }, + undefined + ); + await recovered.discard(reviewerId, workspace); + const author = path.join(state, "sessions", agentId); + expect(await recovered.checkoutDirectory(nested, workspace)).toBe(author); + await expect(recovered.discard(agentId, workspace)).rejects.toThrow( + "still in use" + ); + await recovered.discard(nested, workspace); + await recovered.discard(agentId, workspace); + await expect(stat(author)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("shares a configured workspace with separate host state and no folder cleanup", async () => { const running = await start(["configured", "other"]); await running.launch(launch("configured"), root); - expect(await running.checkoutDirectory(agentId, "configured")).toBe( - await realpath(root) + const configured = await realpath(root); + const file = path.join(configured, "work.txt"); + await writeFile(file, "configured work"); + processes.spawn.mockResolvedValueOnce(); + await running.launch(sharedLaunch(agentId, "configured"), root); + expect(processes.spawn.mock.calls.at(-1)?.[0].at(-1)).toBe( + path.join(state, "hosts", reviewerId) ); - await expect(running.checkoutDirectory(agentId, "other")).rejects.toThrow( - "not bound" + expect(processes.spawn.mock.calls.at(-1)?.[1]).toBe(configured); + expect(await running.checkoutDirectory(reviewerId, "configured")).toBe( + configured ); await expect( running.launch(sharedLaunch(agentId, "other"), root) - ).rejects.toThrow("Sharing requires a managed"); + ).rejects.toThrow("not bound"); + const alternate = path.join(configured, "alternate"); + await mkdir(alternate); + const redirected = path.join(configured, "redirected"); + await symlink(alternate, redirected); + await expect( + running.launch(sharedLaunch(agentId, "configured"), redirected) + ).rejects.toThrow("different configured directory"); + await running.stop(agentId, "configured", true); + await running.discard(agentId, "configured"); + expect(await running.checkoutDirectory(reviewerId, "configured")).toBe( + configured + ); + await running.discard(reviewerId, "configured"); + expect(await readFile(file, "utf8")).toBe("configured work"); + }); + + it("recovers a pre-upgrade configured author's cwd from trusted configuration", async () => { + const workspace = "configured"; + const running = await start([workspace]); + await writeFile(path.join(state, "bindings", agentId), workspace); + await expect(running.checkoutDirectory(agentId, workspace)).rejects.toThrow( + "unavailable" + ); + const configured = await realpath(root); + processes.spawn.mockResolvedValueOnce(); + await running.launch(sharedLaunch(agentId, workspace), root); + expect(await running.checkoutDirectory(agentId, workspace)).toBe( + configured + ); + expect(await running.checkoutDirectory(reviewerId, workspace)).toBe( + configured + ); + + const legacyInspectId = "agt_legacyinspect"; + await writeFile(path.join(state, "bindings", legacyInspectId), workspace); + expect( + await running.checkoutDirectory(legacyInspectId, workspace, root) + ).toBe(configured); }); it("rejects symlink redirection of a legacy repository checkout", async () => { From c53390a827f3e7133260b0dcad9bb4f71c566320 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:58:48 -0700 Subject: [PATCH 093/642] Use the runner checkout contract for local and remote owner reviews --- apps/server/src/agents/checkout-runner.ts | 61 ++++++++ apps/server/src/agents/manager.ts | 107 +++++++++++-- apps/server/src/agents/remote/runner.ts | 39 ++++- apps/server/src/agents/remote/service.ts | 23 +++ .../migrations/0057_runner_worktree_owner.sql | 2 + apps/server/src/main.ts | 4 + apps/server/test/db/agent-manager.test.ts | 78 ++++++++++ .../server/test/helpers/remote-acp-fixture.ts | 6 + apps/server/test/migrations.test.ts | 6 + .../test/remote-runner-enrollment.test.ts | 63 ++++++++ .../test/runner-protocol-consumer.test.ts | 49 ++++++ docs/design/remote-runner-prototype.md | 15 ++ e2e/fixtures/fake-acp-agent.mjs | 14 +- e2e/remote-runner/owner-review.spec.ts | 140 ++++++++++++++++++ packages/runner-protocol/src/checkout.ts | 34 ++++- packages/runner-protocol/src/connection.ts | 1 + packages/runner-protocol/src/execution.ts | 30 ++-- 17 files changed, 628 insertions(+), 44 deletions(-) create mode 100644 apps/server/src/agents/checkout-runner.ts create mode 100644 apps/server/src/db/migrations/0057_runner_worktree_owner.sql create mode 100644 e2e/remote-runner/owner-review.spec.ts diff --git a/apps/server/src/agents/checkout-runner.ts b/apps/server/src/agents/checkout-runner.ts new file mode 100644 index 000000000..36e4bff46 --- /dev/null +++ b/apps/server/src/agents/checkout-runner.ts @@ -0,0 +1,61 @@ +import { + isCheckoutQuery, + isCheckoutReply, + remotePlacement, + type CheckoutQuery, + type CheckoutReply, + type SessionOperation, +} from "@dispatch/runner-protocol"; +import { inspectCheckout } from "./checkout-inspection.js"; +import { AgentError } from "./errors.js"; +import type { RemoteRunnerService } from "./remote/service.js"; +import type { AgentRecord } from "./types.js"; +import { agentWorkspaceDir } from "./workspace-target.js"; + +type Inspect = Extract; + +/** The built-in runner resolves the same agent-scoped operation in process. */ +async function inspectLocalCheckout(agent: AgentRecord, operation: Inspect) { + const cwd = agentWorkspaceDir(agent); + if (!cwd || operation.agentId !== agent.id) + throw new AgentError("The session checkout is unavailable.", 409); + return inspectCheckout(cwd, operation.query); +} + +export async function inspectAgentCheckout( + agent: AgentRecord, + query: CheckoutQuery, + remote?: RemoteRunnerService +): Promise { + if (!isCheckoutQuery(query)) + throw new AgentError("Invalid checkout query.", 400); + const operation: Inspect = { + kind: "inspectCheckout", + agentId: agent.id, + query, + }; + const placement = remotePlacement(agent.cwd); + let reply: unknown; + if (placement) { + if (!remote) + throw new AgentError("The agent’s runner is unavailable.", 409); + const { value } = await remote.requestSession(placement, operation); + if (typeof value !== "string") + throw new AgentError("Missing runner checkout response.", 502); + try { + reply = JSON.parse(value); + } catch { + throw new AgentError("Malformed runner checkout response.", 502); + } + } else { + reply = await inspectLocalCheckout(agent, operation); + } + if (!isCheckoutReply(reply, query)) + throw new AgentError("Invalid runner checkout response.", 502); + return reply; +} + +/** Resolve the launch placement from the requester, never the display parent. */ +export function reviewerWorkspace(owner: AgentRecord) { + return agentWorkspaceDir(owner) ?? owner.cwd; +} diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 004681afc..b79c8526c 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -72,11 +72,14 @@ import type { PromptImage, } from "./acp/prompt-source.js"; import { type EngineBins, isAcpEngine } from "./acp/engine-spec.js"; +import { inspectAgentCheckout, reviewerWorkspace } from "./checkout-runner.js"; import { RemoteEventInbox } from "./remote/event-inbox.js"; import { MANAGED_WORKSPACE, remotePlacement, type RunnerRepository, + type CheckoutQuery, + type CheckoutReply, } from "./remote/protocol.js"; import { inferRepositoryUrl, parseRepository } from "./remote/repository.js"; import { RunnerRevoked, type RemoteRunnerService } from "./remote/service.js"; @@ -1353,6 +1356,29 @@ export class AgentManager { return updated; } + async inspectCheckout( + agent: AgentRecord, + query: CheckoutQuery + ): Promise { + if ( + agent.runnerManaged && + query.kind === "changes" && + query.baseBranch === null + ) { + // The launch checkout can have an unpublished base. A borrowed checkout inherits it. + const { rows } = await this.pool.query<{ + runner_repository: RunnerRepository | null; + }>( + "SELECT owner.runner_repository FROM agents a JOIN agents owner ON owner.id = COALESCE(a.runner_worktree_owner, a.id) WHERE a.id = $1", + [agent.id] + ); + const checkout = rows[0]?.runner_repository?.checkout; + if (checkout?.kind === "new" && checkout.base) + query = { ...query, baseBranch: checkout.base }; + } + return inspectAgentCheckout(agent, query, this.remote); + } + /** * Create an agent. By default the call returns once the agent is running * (jobs, templates and MCP launches want the outcome). With @@ -1365,11 +1391,41 @@ export class AgentManager { input: CreateAgentInput, options: { detachLaunch?: boolean; + /** Trusted owner review launch, never accepted from an HTTP launch payload. */ + useWorktreeOf?: string; /** Commit owner state before the engine can discover tools or run a turn. */ beforeLaunch?: (agentId: string) => Promise; } = {} ): Promise { input = { ...input }; + const { useWorktreeOf } = options; + if (useWorktreeOf !== undefined) { + const owner = await this.getAgent(useWorktreeOf); + if ( + !owner || + input.role !== "review" || + input.launchedByAgentId !== owner.id || + !input.parentAgentId || + !input.persona || + input.repository || + input.useWorktree || + (input.cwd !== owner.cwd && input.cwd !== reviewerWorkspace(owner)) || + (input.projectId !== undefined && input.projectId !== owner.projectId) + ) + throw new AgentError("Invalid reviewer checkout binding.", 400); + const reviewerParent = + input.parentAgentId === owner.id + ? owner + : await this.getAgent(input.parentAgentId); + if (!reviewerParent || reviewerParent.projectId !== owner.projectId) + throw new AgentError( + "Review parent must belong to the requester's project.", + 400 + ); + input.cwd = reviewerWorkspace(owner); + input.useWorktree = false; + input.projectId = owner.projectId; + } const placement = remotePlacement(input.cwd); const managed = placement ? (this.remote?.isManagedWorkspace(placement) ?? false) @@ -1398,10 +1454,10 @@ export class AgentManager { ); } if ( - (input.projectId && !managed) || - input.parentAgentId || + (!useWorktreeOf && + (input.parentAgentId || (input.projectId && !managed))) || input.templateId || - input.persona || + (input.persona && !useWorktreeOf) || input.jobRunId || input.initialFiles?.length || input.useWorktree @@ -1411,6 +1467,11 @@ export class AgentManager { 400 ); } + if (useWorktreeOf && !this.remote.supportsSharedWorktree(placement)) + throw new AgentError( + "Update the runner to launch a reviewer in an existing checkout.", + 409 + ); input.useWorktree = false; } if (input.templateId) { @@ -1508,7 +1569,13 @@ export class AgentManager { 400 ); const p = await this.prepareCreateInputs(input); - await this.insertAgentRecord(p, input, runnerRepository, managed); + await this.insertAgentRecord( + p, + input, + runnerRepository, + managed, + placement ? useWorktreeOf : undefined + ); const createdAgent = await this.getAgent(p.id); if (createdAgent) { @@ -1864,12 +1931,13 @@ export class AgentManager { p: PreparedCreateInputs, input: CreateAgentInput, repository: RunnerRepository | null, - runnerManaged: boolean + runnerManaged: boolean, + useWorktreeOf?: string ): Promise { await this.pool.query( ` - INSERT INTO agents (id, name, type, role, status, cwd, launch_cwd, files_dir, agent_args, model, full_access, setup_phase, persona, parent_agent_id, launched_by_agent_id, persona_context, review_agent_type, cli_session_id, base_branch, template_id, project_id, effort, runner_repository, runner_managed, updated_at) - VALUES ($1, $2, $3, $4, 'creating', $5, $6, $7, $8::jsonb, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22::jsonb, $23, NOW()) + INSERT INTO agents (id, name, type, role, status, cwd, launch_cwd, files_dir, agent_args, model, full_access, setup_phase, persona, parent_agent_id, launched_by_agent_id, persona_context, review_agent_type, cli_session_id, base_branch, template_id, project_id, effort, runner_repository, runner_managed, runner_worktree_owner, updated_at) + VALUES ($1, $2, $3, $4, 'creating', $5, $6, $7, $8::jsonb, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22::jsonb, $23, $24, NOW()) `, [ p.id, @@ -1895,6 +1963,7 @@ export class AgentManager { p.effort, repository ? JSON.stringify(repository) : null, runnerManaged, + useWorktreeOf ?? null, ] ); } @@ -2188,16 +2257,24 @@ export class AgentManager { "The runner workspace mode changed since this agent was created.", 409 ); - const repository = agent.runnerManaged - ? (( - await this.pool.query<{ - runner_repository: RunnerRepository | null; - }>("SELECT runner_repository FROM agents WHERE id = $1", [agent.id]) - ).rows[0]?.runner_repository ?? undefined) - : undefined; + const binding = + placement && (agent.runnerManaged || agent.role === "review") + ? ( + await this.pool.query<{ + runner_repository: RunnerRepository | null; + runner_worktree_owner: string | null; + }>( + "SELECT runner_repository, runner_worktree_owner FROM agents WHERE id = $1", + [agent.id] + ) + ).rows[0] + : undefined; return this.runtime.launch({ agentId: agent.id, - repository, + repository: binding?.runner_repository ?? undefined, + ...(binding?.runner_worktree_owner && { + useWorktreeOf: binding.runner_worktree_owner, + }), cwd: agent.cwd, placement, engine: agent.type, diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index b2d7d1698..09dfd8f9f 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -10,7 +10,7 @@ import type { HostLaunch } from "../acp/host-protocol.js"; import type { WorkloadCommand } from "./session-storage.js"; import { createSessionSupervisor } from "./session-supervisor.js"; export { runnerStorageKey } from "./session-supervisor.js"; -import { hostCommand } from "../acp/runtime.js"; +import { hostCommand, selfCommand } from "../acp/runtime.js"; import { isOpaqueId, MANAGED_WORKSPACE, @@ -332,6 +332,41 @@ export async function runRemoteRunner(filename: string) { } if (socket.destroyed) return; switch (command.kind) { + case "inspectCheckout": { + const cwd = await supervisor.checkoutDirectory( + agentId, + workspace, + target?.cwd + ); + const child = execute( + setpriv, + [...childArgs, ...selfCommand("runner-inspect-checkout"), cwd], + { + env: { + ...env, + GIT_TERMINAL_PROMPT: "0", + GH_PROMPT_DISABLED: "1", + }, + timeout: 90_000, + maxBuffer: 4 * 1024 * 1024, + } + ); + child.child.stdin?.on("error", () => {}); // execFile reports early child failure. + child.child.stdin?.end(JSON.stringify(command.query)); + try { + const { stdout } = await child; + result(stdout.trimEnd()); + } catch (error) { + // execFile's default message includes the command and machine-local paths. + const detail = (error as { stderr?: string }).stderr + ?.trim() + .slice(0, 1024); + throw new Error( + detail || "The runner could not inspect the checkout." + ); + } + break; + } case "attach": { const channel = await supervisor.attach(agentId, workspace); if (!channel) { @@ -453,6 +488,8 @@ export async function runRemoteRunner(filename: string) { : configuredHandles, ...(managedWorkspace ? { managedWorkspace: true } : {}), engineManagement: true, + checkoutInspection: true, + sharedWorktree: true, }); }); }).catch((error) => { diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index e6ea0f714..a43d88e19 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -136,6 +136,8 @@ type Peer = { reportsHealth?: boolean; /** Advertised in `ready`; whether this peer answers the `"engine"` command. */ engineManagement: boolean; + checkoutInspection: boolean; + sharedWorktree: boolean; /** Last pushed, validated engine inventory; absent until the runner first reports one. */ engines?: EngineInventoryEntry[]; }; @@ -640,6 +642,8 @@ export class RemoteRunnerService { socket, reportsHealth: ready.health === true, engineManagement: ready.engineManagement === true, + checkoutInspection: ready.checkoutInspection === true, + sharedWorktree: ready.sharedWorktree === true, connection: new RunnerConnection(send), workspaces: new Set(ready.workspaces), managedWorkspace: ready.managedWorkspace === true, @@ -1188,6 +1192,13 @@ export class RemoteRunnerService { throw new RunnerUnavailable("The runner has no available workspace."); } + supportsSharedWorktree(placement: Placement) { + return ( + this.available(placement) && + this.peers.get(placement.runner)?.sharedWorktree === true + ); + } + available(placement: Placement) { const peer = this.peers.get(placement.runner); return Boolean( @@ -1216,6 +1227,18 @@ export class RemoteRunnerService { "The enrolled runner is disconnected or the workspace is unavailable." ); } + if (command.kind === "inspectCheckout" && !peer.checkoutInspection) + throw new RunnerCapabilityUnavailable( + "Update the runner to inspect a session checkout." + ); + if ( + command.kind === "launch" && + command.launch.useWorktreeOf && + !peer.sharedWorktree + ) + throw new RunnerCapabilityUnavailable( + "Update the runner to launch a reviewer in an existing checkout." + ); return peer.connection.request(command, { openChannel: open }); } diff --git a/apps/server/src/db/migrations/0057_runner_worktree_owner.sql b/apps/server/src/db/migrations/0057_runner_worktree_owner.sql new file mode 100644 index 000000000..ebf8cb7ad --- /dev/null +++ b/apps/server/src/db/migrations/0057_runner_worktree_owner.sql @@ -0,0 +1,2 @@ +-- Persist the trusted launcher's binding for a resumed remote reviewer. +ALTER TABLE agents ADD COLUMN runner_worktree_owner text; diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index c611bc329..767091c47 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -43,6 +43,10 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "connect") { const { runRunnerConnect } = await import("./agents/remote/enrollment.js"); await runRunnerConnect(process.argv.slice(3)); +} else if (process.argv[2] === "runner-inspect-checkout") { + const { runCheckoutInspectionCli } = + await import("./agents/checkout-inspection.js"); + await runCheckoutInspectionCli(process.argv[3]!); } else if (process.argv[2] === "remote-runner") { const { runRemoteRunner } = await import("./agents/remote/runner.js"); await runRemoteRunner(process.argv[3]!); diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index 443d85bd3..0f49214fb 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -310,6 +310,84 @@ describe("AgentManager", () => { expect(discard).toHaveBeenCalledExactlyOnceWith(agent.id); }); + it("persists the actual reviewer checkout owner on the same runner and reuses it on restart", async () => { + const supportsSharedWorktree = vi.fn(() => true); + const requestSession = vi.fn(async () => ({ + value: JSON.stringify({ + kind: "changes", + head: "a".repeat(40), + baseRef: "origin/develop", + stateId: "b".repeat(64), + files: ["src/test.ts"], + }), + })); + const remote = { + available: () => true, + isManagedWorkspace: () => true, + supportsSharedWorktree, + requestSession, + originFor: () => "https://example.test", + } as unknown as RemoteRunnerService; + const first = new AgentManager(pool, noopLogger, testConfig, { + runtime, + remote, + }); + const cwd = "runner://runner-test/@session"; + const parent = await first.createAgent({ + cwd, + repository: { + url: "https://example.test/r.git", + checkout: { kind: "new", branch: "topic", base: "develop" }, + }, + }); + const launch = { + cwd, + role: "review" as const, + parentAgentId: parent.id, + launchedByAgentId: parent.id, + useWorktree: false, + persona: "code-review", + }; + await expect( + first.createAgent( + { ...launch, cwd: "runner://unrelated/@session" }, + { useWorktreeOf: parent.id } + ) + ).rejects.toThrow("Invalid reviewer"); + supportsSharedWorktree.mockReturnValueOnce(false); + await expect( + first.createAgent(launch, { useWorktreeOf: parent.id }) + ).rejects.toThrow("Update the runner"); + const child = await first.createAgent(launch, { + useWorktreeOf: parent.id, + }); + const expected = expect.objectContaining({ + agentId: child.id, + useWorktreeOf: parent.id, + placement: { runner: "runner-test", workspace: "@session" }, + }); + expect(runtime.launch).toHaveBeenLastCalledWith(expected); + await first.stopAgent(child.id); + const resumed = new AgentManager(pool, noopLogger, testConfig, { + runtime, + remote, + }); + await resumed.startAgent(child.id); + expect(runtime.launch).toHaveBeenLastCalledWith(expected); + await resumed.inspectCheckout(child, { + kind: "changes", + baseBranch: null, + }); + expect(requestSession).toHaveBeenCalledWith( + { runner: "runner-test", workspace: "@session" }, + { + kind: "inspectCheckout", + agentId: child.id, + query: { kind: "changes", baseBranch: "develop" }, + } + ); + }); + it.each([null, "project-b"])( "inherits parent membership with template project %s", async (templateProject) => { diff --git a/apps/server/test/helpers/remote-acp-fixture.ts b/apps/server/test/helpers/remote-acp-fixture.ts index 41fe5d5cd..9c52d76fb 100644 --- a/apps/server/test/helpers/remote-acp-fixture.ts +++ b/apps/server/test/helpers/remote-acp-fixture.ts @@ -23,6 +23,12 @@ const fake = createFakeAcpAgent({ "called\n" ); } + if (prompt.includes("proof-reviewed-checkout")) { + const marker = ( + await readFile(path.join(session.cwd, "review-marker.txt"), "utf8") + ).trim(); + await report("Checkout marker " + marker); + } const sleep = /proof-delay:(\d+)/.exec(prompt); if (sleep) { await report("Guest turn waiting for reconnect."); diff --git a/apps/server/test/migrations.test.ts b/apps/server/test/migrations.test.ts index 4b06fe5cf..afb1133d0 100644 --- a/apps/server/test/migrations.test.ts +++ b/apps/server/test/migrations.test.ts @@ -75,6 +75,12 @@ describe("block_reactions uniqueness migration", () => { /** Rewinds task migrations, which depend on projects and agents, so older eras can replay. */ async function dropTasks(): Promise { + await pool.query( + "ALTER TABLE agents DROP COLUMN IF EXISTS runner_worktree_owner" + ); + await pool.query( + "DELETE FROM pgmigrations WHERE name = '0057_runner_worktree_owner'" + ); await pool.query( "ALTER TABLE agents DROP COLUMN IF EXISTS runner_managed, DROP COLUMN IF EXISTS runner_repository, DROP COLUMN IF EXISTS runner_cleanup_pending" ); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index fd61d30e3..e66682885 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -58,6 +58,8 @@ function dialRunner(input: { answer?: boolean; health?: Extract["sample"]; managedWorkspace?: true; + sharedWorktree?: true; + checkoutInspection?: true; }): Promise { const url = new URL(input.endpoint); return new Promise((resolve, reject) => { @@ -86,6 +88,8 @@ function dialRunner(input: { workspaces: input.workspaces, ...(input.health ? { health: true as const } : {}), managedWorkspace: input.managedWorkspace, + sharedWorktree: input.sharedWorktree, + checkoutInspection: input.checkoutInspection, }); resolve({ socket, closed, requests }); }); @@ -537,6 +541,65 @@ describe("runner enrollment service", () => { ); }); + it("gates worktree reuse and inspection before sending requests to older peers", async () => { + const service = makeService(); + const a = await enroll(service, "alpha"); + const placement = { runner: a.id, workspace: "@session" }; + const legacy = await dialRunner({ + ...a, + label: "old", + workspaces: ["@session"], + }); + await waitFor(() => service.available(placement)); + const query = { + kind: "inspectCheckout", + agentId: "author", + query: { kind: "changes", baseBranch: null }, + } as const; + const launch = { + kind: "launch", + agentId: "reviewer", + launch: { + agentId: "reviewer", + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + useWorktreeOf: "author", + }, + } as const; + try { + await expect(service.requestSession(placement, query)).rejects.toThrow( + "Update the runner" + ); + await expect(service.requestSession(placement, launch)).rejects.toThrow( + "Update the runner" + ); + expect(legacy.requests.filter((f) => f.type === "request")).toEqual([]); + } finally { + legacy.socket.destroy(); + } + await waitFor(() => !service.available(placement)); + const current = await dialRunner({ + ...a, + label: "current", + workspaces: ["@session"], + checkoutInspection: true, + sharedWorktree: true, + }); + try { + await waitFor(() => service.supportsSharedWorktree(placement)); + expect((await service.requestSession(placement, query)).value).toBe( + "current" + ); + expect((await service.requestSession(placement, launch)).value).toBe( + "current" + ); + } finally { + current.socket.destroy(); + } + }); + it("distinguishes a configured @session handle from managed mode and retains the mode offline", async () => { const service = makeService(); const a = await enroll(service, "alpha"); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index dc1cedba8..5c2928747 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -11,6 +11,7 @@ import { runnerRequestId, sessionCommandId, isOpaqueId, + isCheckoutReply, remotePlacement, workspaceLocator, } from "@dispatch/runner-protocol"; @@ -107,10 +108,58 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () workspaces: ["@session"], health: true, engineManagement: true, + checkoutInspection: true, + sharedWorktree: true, }; expect(parseReadyFrame(managed)).toEqual(managed); }); +it("validates checkout queries, results and borrowed launches", () => { + const parse = (command: unknown) => + parseServiceFrame({ type: "request", id: "request-1", command }); + const request = { + kind: "inspectCheckout", + agentId: "author", + workspace: "@session", + }; + const read = { kind: "readFile", path: ".agents/owners.json" } as const; + expect(parse({ ...request, query: read })).not.toBeNull(); + for (const path of ["/etc/config", "../other", "a//b", "./config"]) + expect(parse({ ...request, query: { ...read, path } })).toBeNull(); + expect(isCheckoutReply({ kind: "changes", files: [] }, read)).toBe(false); + expect(isCheckoutReply({ kind: "readFile", content: null }, read)).toBe(true); + const command = { + kind: "launch", + workspace: "@session", + agentId: "reviewer", + }; + const launch = { + agentId: "reviewer", + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + useWorktreeOf: "author", + }; + expect(parse({ ...command, launch })).not.toBeNull(); + expect(parse({ ...command, agentId: "other", launch })).toBeNull(); + expect( + parse({ ...command, launch: { ...launch, useWorktreeOf: "reviewer" } }) + ).toBeNull(); + expect( + parse({ + ...command, + launch: { + ...launch, + repository: { + url: "https://repo.test/x", + checkout: { kind: "branch", branch: "x" }, + }, + }, + }) + ).toBeNull(); +}); + function peer() { const sent: ServiceFrame[] = []; const connection = new RunnerConnection((frame) => sent.push(frame)); diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index bac65d213..5fc04d872 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -222,6 +222,21 @@ established guest hosts continue. The client checks the service hostname. command as the guest CLI account and returns its bounded stdout. Product `post` runs through the usual Dispatch MCP route and permissions. +### Inspecting and sharing a live checkout + +A service can inspect the checkout bound to an existing agent ID when the connected peer advertises `checkoutInspection: true`. The built-in local runner handles the same typed query in process. The Linux runner resolves the session binding and executes the inspection as the workload account. + +| Request | Reply | +| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `inspectCheckout` with `{kind:"changes",baseBranch}` | Effective base ref, HEAD commit, a state identifier for the inspected changes, and repo-relative changed paths. The paths include committed, staged, unstaged and untracked files. | +| `inspectCheckout` with `{kind:"readFile",path}` | Bounded text from a regular file relative to the checkout root, or null if absent. | + +A service interprets checkout contents according to its own policy. Dispatch reads the ownership map and persona definitions and selects the reviewers. An independent consumer can use the same operations without implementing those concepts. + +With `sharedWorktree: true`, a launch can specify `useWorktreeOf`, an existing agent ID bound to the same runner and workspace. A launch supplies either that reference or a repository to provision. The new agent has its own host, identity, journal and credentials. Referencing a live worktree gives it access to the author's current files, including edits made after the review started. The state identifier lets the service compare what it inspected across requests. File write permissions depend on the workload and engine access policy. The checkout reference itself grants no read-only guarantee. + +The service checks advertised capabilities on each connection before sending a dependent command. A peer without the extension can continue its existing sessions. Callers receive an actionable unsupported error if they request checkout inspection or sharing. A failed remote inspection must never resolve the runner locator as a local path. + ## Observed traces The initial fake-agent turn ran as `agt_4643ddec746a`. The UI showed diff --git a/e2e/fixtures/fake-acp-agent.mjs b/e2e/fixtures/fake-acp-agent.mjs index 50e8d4da4..cfe54839f 100755 --- a/e2e/fixtures/fake-acp-agent.mjs +++ b/e2e/fixtures/fake-acp-agent.mjs @@ -5,8 +5,8 @@ // Codex, usage with cost for Claude and OpenCode, a model option for the // three that publish one, nested tool calls for Claude, a permission ask // for OpenCode, and honors set_mode for Gemini. It never calls a model and -// never touches the workspace. -import { existsSync } from "node:fs"; +// only reads a workspace marker when the runner review fixture requests it. +import { existsSync, readFileSync } from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; import { Readable, Writable } from "node:stream"; @@ -239,6 +239,16 @@ const agent = { const cwd = cwdBySession.get(params.sessionId) ?? process.cwd(); const emit = (update) => conn.sessionUpdate({ sessionId: params.sessionId, update }); + if (text.includes("proof-reviewed-checkout")) { + const marker = readFileSync( + path.join(cwd, "review-marker.txt"), + "utf8" + ).trim(); + await emit({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Checkout marker " + marker }, + }); + } const receiptId = params._meta?.["dispatch/steering"]?.id; if (receiptId) { await new Promise((resolve) => setTimeout(resolve, 250)); diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts new file mode 100644 index 000000000..29bdd8bc3 --- /dev/null +++ b/e2e/remote-runner/owner-review.spec.ts @@ -0,0 +1,140 @@ +import { expect, test } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { authHeaders, callMcpToolViaAPI, deleteAgentViaAPI } from "../helpers"; +import { + enrollViaUi, + newSettledTurn, + runnerRow, + settledTurns, + state, +} from "./harness"; + +/** One identical unpublished repo fixture for native and guest review. */ +function seed(directory: string, marker: string) { + const git = (...args: string[]) => + execFileSync("git", ["-C", directory, ...args], { stdio: "pipe" }); + git("init", "-b", "main"); + git("config", "user.name", "Runner review fixture"); + git("config", "user.email", "fixture@localhost"); + mkdirSync(path.join(directory, ".agents")); + writeFileSync( + path.join(directory, ".agents/owners.json"), + JSON.stringify({ + version: 1, + rules: [{ paths: ["*.txt"], personas: ["code-review"] }], + }) + ); + writeFileSync(path.join(directory, ".gitignore"), "provider-invocations\n"); + git("add", "."); + git("commit", "-m", "base"); + git("switch", "-c", "unpublished"); + writeFileSync(path.join(directory, "committed.txt"), "committed\n"); + git("add", "."); + git("commit", "-m", "change"); + writeFileSync(path.join(directory, "review-marker.txt"), marker); +} + +for (const placement of ["This Mac", "Linux runner"] as const) { + test(`owner reviews share committed and uncommitted work on ${placement}`, async ({ + page, + request, + }, testInfo) => { + const tmp = mkdtempSync(path.join(os.tmpdir(), "dispatch-review-")); + const marker = randomUUID(); + const agents: string[] = []; + try { + seed(tmp, marker); + const remote = placement === "Linux runner"; + let cwd = tmp; + if (remote) { + const row = await runnerRow(request, "scratch"); + const runnerId = + row?.id ?? (await enrollViaUi(page, request, "scratch")); + cwd = `runner://${runnerId}/@session`; + } + const created = await request.post("/api/v1/agents", { + headers: authHeaders(), + data: { + name: "Field review author", + type: "claude", + cwd, + useWorktree: false, + initialPrompt: "ready", + }, + }); + expect(created.ok(), await created.text()).toBe(true); + const author = (await created.json()).agent.id as string; + agents.push(author); + await page.goto("/agents/" + author, { waitUntil: "domcontentloaded" }); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + if (remote) { + const container = state.runners.scratch.container; + const directory = "/var/lib/runner/sessions/" + author; + execFileSync("docker", ["cp", tmp + "/.", container + ":" + directory]); + execFileSync("docker", [ + "exec", + container, + "chown", + "-R", + "1500:1500", + directory, + ]); + } + const review = await callMcpToolViaAPI( + request, + author, + "launch_owner_reviews", + { + context: "Check the author's unpublished and dirty changes.", + agentType: "claude", + } + ); + const plan = ( + review.result as { + structuredContent: { + owners: { persona: string; files: string[] }[]; + failures: unknown[]; + launched: { agentId: string }[]; + }; + } + ).structuredContent; + expect(plan.failures).toEqual([]); + expect(plan.owners).toEqual([ + { + persona: "code-review", + files: ["committed.txt", "review-marker.txt"], + }, + ]); + expect(plan.launched).toHaveLength(1); + const reviewer = plan.launched[0]!.agentId; + agents.push(reviewer); + await page.goto("/agents/" + reviewer, { waitUntil: "domcontentloaded" }); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + await newSettledTurn( + page, + "proof-reviewed-checkout", + "Checkout marker " + marker + ); + await testInfo.attach("reviewer in author checkout", { + body: await page.screenshot(), + contentType: "image/png", + }); + await deleteAgentViaAPI(request, reviewer); + agents.pop(); + await page.goto("/agents/" + author, { waitUntil: "domcontentloaded" }); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + await newSettledTurn( + page, + "proof-reviewed-checkout", + "Checkout marker " + marker + ); + } finally { + for (const id of agents.reverse()) await deleteAgentViaAPI(request, id); + rmSync(tmp, { recursive: true, force: true }); + } + }); +} diff --git a/packages/runner-protocol/src/checkout.ts b/packages/runner-protocol/src/checkout.ts index 4788d28dc..63c39113a 100644 --- a/packages/runner-protocol/src/checkout.ts +++ b/packages/runner-protocol/src/checkout.ts @@ -6,9 +6,33 @@ export type CheckoutQuery = | { kind: "readFile"; path: string }; export type CheckoutReply = - | { kind: "changes"; baseRef: string; head: string; files: string[] } + | { + kind: "changes"; + baseRef: string; + head: string; + stateId: string; + files: string[]; + } | { kind: "readFile"; content: string | null }; +/** A full branch name, never a revision expression, option, or raw ref. */ +export function validBranch(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= 200 && + !value.startsWith("-") && + !value.startsWith("refs/") && + !value.endsWith(".") && + value !== "HEAD" && + value !== "@" && + !/[\x00-\x20\x7f~^:?*\[\\]|\.\.|@\{/.test(value) && + value + .split("/") + .every((part) => part && !part.startsWith(".") && !part.endsWith(".lock")) + ); +} + function relativePath(value: unknown): value is string { return ( typeof value === "string" && @@ -23,11 +47,7 @@ export function isCheckoutQuery(value: unknown): value is CheckoutQuery { if (value.kind === "readFile") return relativePath(value.path); return ( value.kind === "changes" && - (value.baseBranch === null || - (typeof value.baseBranch === "string" && - value.baseBranch.length > 0 && - value.baseBranch.length <= 255 && - !/^[.-]|[\x00-\x20\x7f~^:?*\[\\]|\.\.|@\{/.test(value.baseBranch))) + (value.baseBranch === null || validBranch(value.baseBranch)) ); } @@ -42,6 +62,8 @@ export function isCheckoutReply( typeof value.baseRef === "string" && value.baseRef.length > 0 && value.baseRef.length <= 512 && + typeof value.stateId === "string" && + /^[a-f0-9]{64}$/.test(value.stateId) && typeof value.head === "string" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.head) && Array.isArray(value.files) && diff --git a/packages/runner-protocol/src/connection.ts b/packages/runner-protocol/src/connection.ts index 35ddfad4c..ddf69fe92 100644 --- a/packages/runner-protocol/src/connection.ts +++ b/packages/runner-protocol/src/connection.ts @@ -64,6 +64,7 @@ export class RunnerConnection { ): Promise { // Repository fetches and engine package installs can run for minutes. const timeoutMs = + command.kind === "inspectCheckout" || command.kind === "engine" || (command.kind === "launch" && command.launch.repository) ? 300_000 diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index f896b79f6..2e787ead0 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,4 +1,8 @@ -import { isCheckoutQuery, type CheckoutQuery } from "./checkout.js"; +import { + isCheckoutQuery, + validBranch, + type CheckoutQuery, +} from "./checkout.js"; import { MANAGED_WORKSPACE, isOpaqueId } from "./placement.js"; import { type EngineInventoryEntry, @@ -122,24 +126,6 @@ export type RunnerFrame = export type Frame = ServiceFrame | RunnerFrame; -/** A full branch name, never a revision expression, option, or raw ref. */ -export function validBranch(value: unknown): value is string { - return ( - typeof value === "string" && - value.length > 0 && - value.length <= 200 && - !value.startsWith("-") && - !value.startsWith("refs/") && - !value.endsWith(".") && - value !== "HEAD" && - value !== "@" && - !/[\x00-\x20\x7f~^:?*\[\\]|\.\.|@\{/.test(value) && - value - .split("/") - .every((part) => part && !part.startsWith(".") && !part.endsWith(".lock")) - ); -} - /** Check the URL before a runner makes any workspace changes. */ export function parseRunnerRepositoryUrl( source: unknown, @@ -231,7 +217,11 @@ function isCommand(value: unknown): value is Command { return false; switch (value.kind) { case "launch": - return isRemoteLaunch(value.launch); + return ( + isRemoteLaunch(value.launch) && + (value.launch.useWorktreeOf === undefined || + value.agentId === value.launch.agentId) + ); case "inspectCheckout": return isCheckoutQuery(value.query); case "attach": From 94e7aea5c0bf9aac3df91264b756bedd011e5c23 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 21:59:38 -0700 Subject: [PATCH 094/642] Assign checkout inspection regressions to the runner owner --- .agents/owners.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.agents/owners.json b/.agents/owners.json index 787f36764..b0adfe1b9 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -26,6 +26,7 @@ "apps/server/src/routes/runners.ts", "apps/server/src/routes/runner-*.ts", "apps/server/test/remote-*.test.ts", + "apps/server/test/checkout-inspection.test.ts", "apps/server/test/runner-*.test.ts", "apps/server/test/helpers/remote-acp-fixture.ts", "packages/runner-protocol/**", From 23c06bfe14ad150d05207bf641ad86e9c0fe2890 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 22:03:40 -0700 Subject: [PATCH 095/642] Record owner-review parity in the runner capability inventory --- docs/design/runner-capability-inventory.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index b261873a9..6e50191f6 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -22,7 +22,7 @@ The outer protocol already covers launch, attach, liveness, stop, discard, log t - Check a new branch, a direct existing branch, a busy branch, a missing package manager and a retry after partial setup. In the field test a valid checkout still lacked dependencies and the guest install exited 137. [Workspace preparation](../../apps/server/src/agents/workspace-prep.ts) · [File seeding](../../apps/server/src/agents/file-seed.ts) · [Runner Git](../../apps/server/src/agents/remote/repository.ts) -**Track the effective checkout.** **Gap for shared managed worktrees.** Local sessions can report a moved workspace. A local child may share its parent’s current worktree or request a new one. Managed remote launch derives its directory from the new agent’s ID. Keep author identity, launching agent, display parent and checkout ownership distinct. +**Track the effective checkout.** **Present for owner reviews.** A reviewer can borrow the author’s effective checkout by opaque agent ID on This Mac or on a capable Linux runner. Each reviewer has its own session. A managed runner retains the checkout until its owner and borrowers have released it. General child launches and workspace moves still need parity coverage. - Launch a child in the author’s current checkout and another in a separate checkout. Reviewers keep separate sessions and see the author’s uncommitted files. A cross-runner reference is rejected. [Workspace selection](../../apps/server/src/agents/workspace-target.ts) · [Child launch options](../../apps/server/src/shared/mcp/agent-launch-tools.ts) · [Runner supervisor](../../apps/server/src/agents/remote/session-supervisor.ts) @@ -42,9 +42,9 @@ The outer protocol already covers launch, attach, liveness, stop, discard, log t ### Working with a checkout -**Select and launch owner reviewers.** **Confirmed gap.** Dispatch currently runs Git in the parent cwd and loads checkout-local ownership rules and persona definitions. Dispatch should retain policy, reviewer selection, threads and findings. The runner supplies checkout facts and scoped file contents, then launches the reviewer in the author’s checkout. +**Select and launch owner reviewers.** **Present.** Dispatch requests changed paths, HEAD, a checkout state identifier and bounded file reads from the author’s runner. Dispatch loads ownership rules, selects review personas, checks that the review state still matches, and launches a reviewer in the same checkout. Dispatch owns review threads and findings. -- Both real agents called owner review and got Git exit 128 on a runner URL. Repeat on both placements with committed, staged, unstaged, renamed and untracked files. Verify matching owners, correct base and visible files. [Owner handler](../../apps/server/src/server/mcp-persona-handlers.ts) · [Changed-file collection](../../apps/server/src/personas/codeowners.ts) · [Review workflow](../code-owner-reviews.md) +- The original field test failed when Dispatch passed a runner URL to local Git. The [placement parity test](../../e2e/remote-runner/owner-review.spec.ts) checks an unpublished commit and an untracked marker, reads it through each reviewer, archives the reviewer, and confirms the author retains access. Staged, unstaged and renamed path handling have [checkout-level tests](../../apps/server/test/checkout-inspection.test.ts). [Owner handler](../../apps/server/src/server/mcp-persona-handlers.ts) · [Changed-file collection](../../apps/server/src/personas/codeowners.ts) · [Review workflow](../code-owner-reviews.md) **Display Changes and worktree state.** **Gap.** Base/ref resolution, file lists, diff stats, individual hunks, image diffs, repo identity and dirty/unmerged state read the checkout. Dispatch owns diff comments, rendering and refresh timing. Background refreshers must use the same placement as foreground requests. From 395283956cd2a635723ffb9f3a053bf870aacf1c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 22:04:12 -0700 Subject: [PATCH 096/642] Route capability inventory changes to the runtime owner --- .agents/owners.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.agents/owners.json b/.agents/owners.json index b0adfe1b9..9456e4e6d 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -31,6 +31,7 @@ "apps/server/test/helpers/remote-acp-fixture.ts", "packages/runner-protocol/**", "docs/design/remote-runner-handoff.md", + "docs/design/runner-capability-inventory.md", "scripts/e2e-remote-runners.sh", "scripts/remote-runner/codex-offline-preflight.sh", "apps/server/src/shared/process/**", From 5fff363968d4150f2ef3e2b13833056593231ea2 Mon Sep 17 00:00:00 2001 From: Dispatch Field Test Date: Thu, 19 Nov 2026 05:08:37 +0000 Subject: [PATCH 097/642] Open runner health timestamp on tap --- .../src/components/app/runner-health.test.tsx | 35 ++++++++------ apps/web/src/components/app/runner-health.tsx | 47 +++++++++++-------- 2 files changed, 49 insertions(+), 33 deletions(-) diff --git a/apps/web/src/components/app/runner-health.test.tsx b/apps/web/src/components/app/runner-health.test.tsx index 142379da1..0539f9231 100644 --- a/apps/web/src/components/app/runner-health.test.tsx +++ b/apps/web/src/components/app/runner-health.test.tsx @@ -24,7 +24,7 @@ afterEach(() => { }); it.each(["online", "offline"] as const)( - "shows a relative report time and reveals the exact local timestamp on focus for an %s runner", + "reveals the exact local timestamp on focus or activation for an %s runner", async (status) => { vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-01-15T08:43:25Z")); render( @@ -46,8 +46,10 @@ it.each(["online", "offline"] as const)( ); fireEvent.click(screen.getByText(/1 session/)); - const report = screen.getByText("1m ago"); - expect(report.getAttribute("datetime")).toBe(receivedAt); + const report = screen.getByRole("button", { name: "Last report: 1m ago" }); + expect(report.querySelector("time")?.getAttribute("datetime")).toBe( + receivedAt + ); expect(report.tabIndex).toBe(0); expect(screen.queryByRole("tooltip")).toBeNull(); @@ -55,17 +57,22 @@ it.each(["online", "offline"] as const)( const tooltip = await screen.findByRole("tooltip"); expect(report.getAttribute("aria-describedby")).toBe(tooltip.id); - expect(tooltip.textContent).toBe( - new Intl.DateTimeFormat(undefined, { - year: "numeric", - month: "short", - day: "numeric", - hour: "numeric", - minute: "2-digit", - second: "2-digit", - timeZoneName: "shortOffset", - }).format(new Date(receivedAt)) - ); + const exactTime = new Intl.DateTimeFormat(undefined, { + year: "numeric", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + second: "2-digit", + timeZoneName: "shortOffset", + }).format(new Date(receivedAt)); + expect(tooltip.textContent).toBe(exactTime); + + fireEvent.blur(report); + expect(screen.queryByRole("tooltip")).toBeNull(); + + fireEvent.click(report); + expect((await screen.findByRole("tooltip")).textContent).toBe(exactTime); } ); diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index bd687fca7..5801cf249 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -20,6 +20,33 @@ const reportDateTimeOptions: Intl.DateTimeFormatOptions = { timeZoneName: "shortOffset", }; +function RunnerReportTime({ receivedAt }: { receivedAt: string }) { + const [open, setOpen] = useState(false); + const relativeTime = formatRelativeTime(receivedAt); + + return ( + + + { + // Radix closes the tooltip on click by default. Let activation open it. + event.preventDefault(); + setOpen(true); + }} + > + + + + {new Date(receivedAt).toLocaleString(undefined, reportDateTimeOptions)} + + + + ); +} + const memory = (bytes: number) => bytes < 1024 ** 3 ? `${Math.round(bytes / 1024 ** 2)} MiB` @@ -67,25 +94,7 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) {
{health.version}
Last report
- - - - - - - {new Date(healthReceivedAt).toLocaleString( - undefined, - reportDateTimeOptions - )} - - - +
{update && ( From bd24bc88d73220766508571fd62ba0f42c72ff57 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 22:10:24 -0700 Subject: [PATCH 098/642] Keep parity screenshots with each placement test result --- e2e/remote-runner/owner-review.spec.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts index 29bdd8bc3..5ff157303 100644 --- a/e2e/remote-runner/owner-review.spec.ts +++ b/e2e/remote-runner/owner-review.spec.ts @@ -119,8 +119,10 @@ for (const placement of ["This Mac", "Linux runner"] as const) { "proof-reviewed-checkout", "Checkout marker " + marker ); + const screenshot = testInfo.outputPath("reviewer-checkout.png"); + await page.screenshot({ path: screenshot }); await testInfo.attach("reviewer in author checkout", { - body: await page.screenshot(), + path: screenshot, contentType: "image/png", }); await deleteAgentViaAPI(request, reviewer); From 62b81b422df7141aff1fd15191bc8be67156b846 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 22:11:11 -0700 Subject: [PATCH 099/642] Format the two reviewed runner changes --- apps/server/src/agents/remote/session-processes.ts | 3 +-- apps/web/src/components/app/runner-health.tsx | 5 ++++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/server/src/agents/remote/session-processes.ts b/apps/server/src/agents/remote/session-processes.ts index 1d844c4e5..7850ed6e6 100644 --- a/apps/server/src/agents/remote/session-processes.ts +++ b/apps/server/src/agents/remote/session-processes.ts @@ -42,8 +42,7 @@ function linuxKernel() { const errno = () => read.i32(symbols.__errno_location()!); return { lock(fd: number) { - if (symbols.flock(fd, 2 | 4) !== 0) - throw runnerStateLockError(errno()); + if (symbols.flock(fd, 2 | 4) !== 0) throw runnerStateLockError(errno()); }, signal(fd: number, signal: number) { if (symbols.syscall(424, fd, signal, null, 0) === 0) return; diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index 5801cf249..620832e5a 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -40,7 +40,10 @@ function RunnerReportTime({ receivedAt }: { receivedAt: string }) { - {new Date(receivedAt).toLocaleString(undefined, reportDateTimeOptions)} + {new Date(receivedAt).toLocaleString( + undefined, + reportDateTimeOptions + )} From a7a5077ed2c0628f171ccf834a526938b78e5f8b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 22:15:03 -0700 Subject: [PATCH 100/642] Document review-state coverage for ignored policy files --- docs/design/remote-runner-prototype.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index 5fc04d872..cd216eaa8 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -233,6 +233,8 @@ A service can inspect the checkout bound to an existing agent ID when the connec A service interprets checkout contents according to its own policy. Dispatch reads the ownership map and persona definitions and selects the reviewers. An independent consumer can use the same operations without implementing those concepts. +The changes query honors Git’s standard ignore rules for untracked files. Dispatch can still read an ignored, untracked ownership map or persona definition by path. If that file changes during review planning, the two inspections can return the same state ID and the review can use the earlier contents. Tracking those files in Git puts their edits within the state check. + With `sharedWorktree: true`, a launch can specify `useWorktreeOf`, an existing agent ID bound to the same runner and workspace. A launch supplies either that reference or a repository to provision. The new agent has its own host, identity, journal and credentials. Referencing a live worktree gives it access to the author's current files, including edits made after the review started. The state identifier lets the service compare what it inspected across requests. File write permissions depend on the workload and engine access policy. The checkout reference itself grants no read-only guarantee. The service checks advertised capabilities on each connection before sending a dependent command. A peer without the extension can continue its existing sessions. Callers receive an actionable unsupported error if they request checkout inspection or sharing. A failed remote inspection must never resolve the runner locator as a local path. From 2d5f37f860b3b34ff352b6773eadee47b29afbfb Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:24:32 -0700 Subject: [PATCH 101/642] Manage GitHub login and repository selection within the selected runner --- .../components/app/create-agent-dialog.tsx | 5 +- .../components/app/runner-github-account.tsx | 200 ++++++++++++++++++ .../app/runner-repository-fields.tsx | 26 ++- .../components/app/use-create-agent-form.ts | 14 +- apps/web/src/hooks/use-runners.ts | 1 + 5 files changed, 236 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/components/app/runner-github-account.tsx diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index 0ea854648..bb7b1120f 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -195,8 +195,11 @@ function CreateAgentDialogContent({
)} - {form.managedSession && ( + {form.managedSession && form.runnerId && ( + +

+ {runner.status === "online" + ? "Update the runner to manage its GitHub account here." + : "GitHub account details are available when the runner is online."} +

+
+ ); + } + return ; +} + +function AccountHeading() { + return ( +

+

+ ); +} + +function ConnectedAccount({ runner }: { runner: Runner }) { + const client = useQueryClient(); + const [confirmLogout, setConfirmLogout] = useState(false); + const path = "/api/v1/runners/" + encodeURIComponent(runner.id) + "/github"; + const key = ["runner-github-account", runner.id] as const; + const account = useQuery({ + queryKey: key, + queryFn: ({ signal }) => + api(path, { signal, cache: "no-store" }), + refetchInterval: (q) => (q.state.data?.status === "pending" ? 2000 : false), + retry: false, + gcTime: 0, + }); + const action = useMutation({ + mutationFn: (op: "login" | "logout" | "cancel") => + api(op === "logout" ? path : path + "/login", { + method: op === "login" ? "POST" : "DELETE", + }), + onMutate: () => client.cancelQueries({ queryKey: key }), + onSuccess: async (value) => { + client.setQueryData(key, value); + client.removeQueries({ + queryKey: ["runner-repository-search", runner.id], + }); + await client.invalidateQueries({ queryKey: key }); + }, + onError: () => client.invalidateQueries({ queryKey: key }), + }); + const state = account.data; + const pending = state?.status === "pending"; + const signedIn = state?.status === "signed-in"; + const unavailable = state?.status === "unavailable"; + const statusText = account.isError + ? "Couldn’t read the account." + : account.isPending + ? "Checking account…" + : signedIn + ? `Signed in as @${state.login}` + : unavailable + ? state.message || "GitHub CLI is unavailable on this runner." + : state?.status === "failed" + ? state.message || "Sign-in did not complete." + : pending + ? state.code + ? "Waiting for GitHub approval" + : "Requesting a device code…" + : "Signed out"; + return ( +
+
+
+ +

+ {statusText} +

+
+ {account.isError || unavailable ? ( + + ) : signedIn ? ( + + ) : pending ? ( + + ) : ( + !account.isPending && ( + + ) + )} +
+ {pending && state.code && !account.isError && ( +
+

+ Enter this code on GitHub to authorize {runner.name}. +

+
+
+ + {state.code} + + +
+ +
+
+ )} + {action.isError && ( +

+ {action.error.message} +

+ )} + + + + Sign out of GitHub on {runner.name}? + + + Agents on this runner will lose access through @{state?.login}. This + removes the saved login from this machine. You can revoke the token + separately on GitHub. + +
+ Cancel + action.mutate("logout")}> + Sign out + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/app/runner-repository-fields.tsx b/apps/web/src/components/app/runner-repository-fields.tsx index 243b8776f..ba764ced5 100644 --- a/apps/web/src/components/app/runner-repository-fields.tsx +++ b/apps/web/src/components/app/runner-repository-fields.tsx @@ -30,6 +30,8 @@ export function isRepositoryUrl(value: string) { } export function RunnerRepositoryFields({ + runnerId, + canSearch, repository, onRepository, mode, @@ -39,6 +41,8 @@ export function RunnerRepositoryFields({ loading, failed, }: { + runnerId: string; + canSearch: boolean; repository: string; onRepository: (value: string) => void; mode: RunnerBranchMode; @@ -57,14 +61,15 @@ export function RunnerRepositoryFields({ return () => clearTimeout(timeout); }, [text, searchable]); const matches = useQuery({ - queryKey: ["runner-repository-search", search], - queryFn: () => + queryKey: ["runner-repository-search", runnerId, search], + queryFn: ({ signal }) => api<{ repositories: { name: string; url: string }[] }>( - `/api/v1/runners/repository-search?q=${encodeURIComponent(search)}` + `/api/v1/runners/${encodeURIComponent(runnerId)}/repository-search?q=${encodeURIComponent(search)}`, + { signal, cache: "no-store" } ), - enabled: Boolean(search && search === text && searchable), + enabled: canSearch && Boolean(search && search === text && searchable), retry: false, - staleTime: 60_000, + gcTime: 0, }); return (
@@ -76,7 +81,11 @@ export function RunnerRepositoryFields({ id={id} value={repository} onChange={(e) => onRepository(e.target.value)} - placeholder="Search GitHub or paste an HTTPS URL" + placeholder={ + canSearch + ? "Search GitHub or paste an HTTPS URL" + : "Paste an HTTPS repository URL" + } autoComplete="off" data-testid="runner-repository" disabled={loading} @@ -92,14 +101,15 @@ export function RunnerRepositoryFields({ folder.

) : null} - {search && + {canSearch && + search && text === search && searchable && (matches.isLoading ? (

Searching GitHub…

) : matches.isError ? (

- GitHub search is unavailable. Paste a repository URL. + Check this runner’s GitHub sign-in or paste a repository URL.

) : matches.data?.repositories.length ? (
    { + if (id === runnerId) return; + setChosenRepo(null); + setRunnerBranch(""); + setBranchMode("new"); setRunnerId(id); setRunnerWorkspace(null); }; @@ -377,6 +381,10 @@ export function useCreateAgentForm({ }, }; } else if (branch.startsWith("https://")) { + if (!runnerId || !runner?.githubManagement) + throw new Error( + "Update this runner to open a pull request by URL, or enter a branch name." + ); const pr = new URL(branch); const repo = new URL(repository.trim()); if ( @@ -388,7 +396,7 @@ export function useCreateAgentForm({ "Choose a pull request from the selected repository." ); const head = await api<{ url: string; branch: string }>( - `/api/v1/runners/pull-request-head?url=${encodeURIComponent(branch)}` + `/api/v1/runners/${encodeURIComponent(runnerId)}/pull-request-head?url=${encodeURIComponent(branch)}` ); checkout = { url: head.url, @@ -477,6 +485,8 @@ export function useCreateAgentForm({ [ createBaseBranch, managedSession, + runnerId, + runner?.githubManagement, repository, branchMode, runnerBranch, @@ -509,6 +519,8 @@ export function useCreateAgentForm({ runners, runnerId, runnerUnavailable, + runnerGitHubAvailable: + runner?.status === "online" && runner?.githubManagement === true, managedSession, repository, chooseRepo, diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index c796758c4..b148916f0 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -12,6 +12,7 @@ export type Runner = { workspaces: string[]; managedWorkspace?: true; engineManagement?: true; + githubManagement?: boolean; health?: RunnerHealth; healthReceivedAt?: string; }; From 1a3c85aa1f4bc2594f5fb54de8997ffb418b05a3 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:26:35 -0700 Subject: [PATCH 102/642] Manage GitHub authentication on remote runners --- .../agents/remote/github-runner-executor.ts | 290 ++++++++++++++++++ apps/server/src/agents/remote/runner.ts | 24 ++ apps/server/src/agents/remote/service.ts | 101 +++++- apps/server/src/routes/runner-github.ts | 33 ++ apps/server/src/routes/runner-repositories.ts | 105 ++----- apps/server/src/server.ts | 13 +- apps/server/test/engine-wire.test.ts | 80 +++++ .../test/github-runner-executor.test.ts | 185 +++++++++++ .../test/remote-runner-enrollment.test.ts | 2 + .../test/runner-protocol-consumer.test.ts | 24 ++ apps/server/test/runner-repositories.test.ts | 35 ++- apps/server/test/runner-routes.test.ts | 24 ++ packages/runner-protocol/README.md | 22 ++ packages/runner-protocol/src/execution.ts | 9 +- packages/runner-protocol/src/github.ts | 127 ++++++++ packages/runner-protocol/src/index.ts | 1 + 16 files changed, 984 insertions(+), 91 deletions(-) create mode 100644 apps/server/src/agents/remote/github-runner-executor.ts create mode 100644 apps/server/src/routes/runner-github.ts create mode 100644 apps/server/test/github-runner-executor.test.ts create mode 100644 packages/runner-protocol/src/github.ts diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts new file mode 100644 index 000000000..6a19ccb8c --- /dev/null +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -0,0 +1,290 @@ +import { execFile, spawn, type ChildProcess } from "node:child_process"; +import { promisify } from "node:util"; +import { + githubDeviceUrl, + githubPullRequestHead, + githubRepositoryResults, + validGitHubLogin, + type GitHubOperation, + type GitHubStatus, +} from "./protocol.js"; + +const host = "github.com"; +const gh = "/usr/bin/gh"; +const hostArgs = ["--hostname", host]; +const execute = promisify(execFile); +const codePattern = /one-time code: ([A-Z0-9]{4}-[A-Z0-9]{4})\r?\n/i; + +type Login = { + connection: AbortSignal; + child: ChildProcess; + finished: Promise; + code?: string; +}; + +type CommandWrapper = ( + bin: string, + args: string[] +) => { + bin: string; + args: string[]; +}; + +/** Commands run with the same dedicated workload HOME as checkout and agents. */ +export class GitHubRunnerExecutor { + private readonly env: NodeJS.ProcessEnv; + private login?: Login; + private failed = false; + private queue = Promise.resolve(); + + constructor( + env: NodeJS.ProcessEnv, + private readonly wrap: CommandWrapper + ) { + this.env = { + ...env, + GH_HOST: host, + GH_PROMPT_DISABLED: "1", + GH_NO_UPDATE_NOTIFIER: "1", + GH_NO_EXTENSION_UPDATE_NOTIFIER: "1", + NO_COLOR: "1", + LC_ALL: "C", + }; + } + + private async run(args: string[], signal: AbortSignal) { + const command = this.wrap(gh, args); + const { stdout } = await execute(command.bin, command.args, { + env: this.env, + signal, + killSignal: "SIGKILL", + timeout: 7_000, + maxBuffer: 128 * 1024, + }); + return stdout.trim(); + } + + private async configuredUser(signal: AbortSignal) { + try { + const login = await this.run( + ["config", "get", "user", "--host", host], + signal + ); + if (!validGitHubLogin(login)) + throw new Error("Invalid configured GitHub user."); + return login; + } catch (error) { + const { stderr } = error as { stderr?: string }; + if (stderr?.trim() === 'could not find key "user"') return undefined; + throw error; + } + } + + private async account(signal: AbortSignal): Promise { + if (!(await this.configuredUser(signal))) return { status: "signed-out" }; + try { + const login = await this.run( + ["api", ...hostArgs, "user", "--jq", ".login"], + signal + ); + if (validGitHubLogin(login)) return { status: "signed-in", login }; + } catch (error) { + const { code, stderr } = error as { code?: number; stderr?: string }; + if (code === 4 || /HTTP 401\b/.test(stderr ?? "")) + return { status: "signed-out" }; + } + return { status: "unavailable" }; + } + + private currentLogin(): GitHubStatus { + const code = this.login?.code; + return code + ? { status: "pending", code, verificationUrl: githubDeviceUrl } + : { status: "pending" }; + } + + private start(connection: AbortSignal) { + const command = this.wrap(gh, [ + "auth", + "login", + ...hostArgs, + "--git-protocol", + "https", + "--web", + // Runner services have no desktop keyring. gh owns the file in the + // workload account's private config; no caller sees the credential. + "--insecure-storage", + ]); + connection.throwIfAborted(); + const child = spawn(command.bin, command.args, { + env: this.env, + stdio: ["ignore", "ignore", "pipe"], + }); + const session: Login = { connection, child, finished: Promise.resolve() }; + this.login = session; + let tail = ""; + let cancelled = false; + let setupFailed = false; + const cancel = () => { + cancelled = true; + session.code = undefined; + child.kill("SIGKILL"); + }; + connection.addEventListener("abort", cancel, { once: true }); + const codeDeadline = setTimeout(() => child.kill("SIGKILL"), 30_000); + const timeout = setTimeout(() => child.kill("SIGKILL"), 15 * 60_000); + child.stderr?.setEncoding("utf8"); + child.stderr?.on("data", (chunk: string) => { + if (cancelled || session.code) return; + tail = (tail + chunk).slice(-2048); + const match = codePattern.exec(tail); + if (match?.[1] && tail.includes(githubDeviceUrl)) { + session.code = match[1].toUpperCase(); + clearTimeout(codeDeadline); + tail = ""; + } + }); + // Even a spawn error is followed by a close event. + child.on("error", () => {}); + session.finished = new Promise((resolve) => { + child.once("close", resolve); + }).then(async (code) => { + clearTimeout(timeout); + clearTimeout(codeDeadline); + session.code = undefined; + if (code === 0) { + try { + // gh's non-interactive login does not prompt to install this helper. + await this.run( + ["auth", "setup-git", ...hostArgs], + AbortSignal.timeout(7000) + ); + } catch { + setupFailed = true; + } + } + connection.removeEventListener("abort", cancel); + this.failed = + setupFailed || (!cancelled && !connection.aborted && code !== 0); + this.login = undefined; + }); + } + + private async stopLogin() { + const session = this.login; + if (!session) return; + session.code = undefined; + session.child.kill("SIGKILL"); + await session.finished; + this.failed = false; + } + + private async statusOperation( + operation: GitHubOperation, + signal: AbortSignal + ): Promise { + signal.throwIfAborted(); + switch (operation.type) { + case "status": + if (this.login) return this.currentLogin(); + if (this.failed) return { status: "failed" }; + return this.account(signal); + case "login": { + if (this.login?.connection === signal) return this.currentLogin(); + await this.login?.finished; + signal.throwIfAborted(); + this.failed = false; + const account = await this.account(signal); + if (account.status === "signed-out") { + this.start(signal); + return this.currentLogin(); + } + if (account.status === "signed-in") { + await this.run(["auth", "setup-git", ...hostArgs], signal); + } + return account; + } + case "cancel": + await this.stopLogin(); + return this.account(signal); + case "logout": { + await this.stopLogin(); + this.failed = false; + const login = await this.configuredUser(signal); + if (login) + await this.run( + ["auth", "logout", ...hostArgs, "--user", login], + signal + ); + return this.account(signal); + } + default: + throw new Error("Invalid GitHub account operation."); + } + } + + async handle(operation: GitHubOperation, signal: AbortSignal) { + signal.throwIfAborted(); + switch (operation.type) { + case "repositorySearch": { + const rows = await this.run( + [ + "search", + "repos", + "--match", + "name", + "--limit", + "12", + "--json", + "fullName,url", + "--", + operation.query, + ], + signal + ); + const value: unknown = JSON.parse(rows); + if (!Array.isArray(value)) + throw new Error("Invalid GitHub repository list."); + return githubRepositoryResults( + value.map((row) => ({ + name: row?.fullName, + url: row?.url, + })) + ); + } + case "pullRequestHead": { + const { owner, repo, number } = operation; + const head = await this.run( + [ + "api", + ...hostArgs, + `repos/${owner}/${repo}/pulls/${number}`, + "--jq", + "{url:.head.repo.clone_url,branch:.head.ref}", + ], + signal + ); + return githubPullRequestHead(JSON.parse(head)); + } + default: { + const result = this.queue.then(() => + this.statusOperation(operation, signal) + ); + this.queue = result.then( + () => {}, + () => {} + ); + try { + return await result; + } catch (error) { + const { stderr } = error as { stderr?: string }; + if (stderr?.includes("No such file or directory")) + return { status: "unavailable" }; + return { + status: operation.type === "status" ? "unavailable" : "failed", + }; + } + } + } + } +} diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 09dfd8f9f..5ec9af2c3 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -22,6 +22,7 @@ import { type RunnerFrame, type RunnerEngine, } from "./protocol.js"; +import { GitHubRunnerExecutor } from "./github-runner-executor.js"; import { EngineRunnerExecutor, type ManagedCommand, @@ -183,6 +184,10 @@ export async function runRemoteRunner(filename: string) { key: readFileSync(config.key), }; const sampleHealth = runnerHealthSampler(); + const github = new GitHubRunnerExecutor(env, (bin, args) => ({ + bin: setpriv, + args: [...childArgs, bin, ...args], + })); const engineExecutor = new EngineRunnerExecutor({ uid: config.uid, gid: config.gid, @@ -227,6 +232,7 @@ export async function runRemoteRunner(filename: string) { while (true) { const connectedMs = await new Promise((finished) => { let connectedAt: number | undefined; + const connection = new AbortController(); const socket = connect({ ...credentials, host, @@ -276,6 +282,7 @@ export async function runRemoteRunner(filename: string) { console.error("Runner transport:", error.message) ); socket.on("close", () => { + connection.abort(); clearTimeout(timeout); clearInterval(healthInterval); for (const channel of channels.values()) channel.destroy(); @@ -315,6 +322,22 @@ export async function runRemoteRunner(filename: string) { if (command.operation.type !== "status") void reportEngineInventory(); return; } + if (command.kind === "github") { + try { + const value = await github.handle( + command.operation, + connection.signal + ); + safeSend({ type: "result", id, value: JSON.stringify(value) }); + } catch { + safeSend({ + type: "result", + id, + error: "Runner GitHub operation failed.", + }); + } + return; + } const { agentId, workspace } = command; const target = isOpaqueId(workspace) && Object.hasOwn(workspaces, workspace) @@ -488,6 +511,7 @@ export async function runRemoteRunner(filename: string) { : configuredHandles, ...(managedWorkspace ? { managedWorkspace: true } : {}), engineManagement: true, + githubManagement: true, checkoutInspection: true, sharedWorktree: true, }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index a43d88e19..149660105 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -29,6 +29,11 @@ import { parseEngineInventory, type Command, type RunnerOperation, + type GitHubOperation, + type GitHubStatus, + parseGitHubStatus, + githubPullRequestHead, + githubRepositoryResults, type SessionOperation, type EngineInventoryEntry, type Placement, @@ -93,6 +98,7 @@ export type RunnerSummary = { healthReceivedAt?: string; /** Whether this (online) peer advertised support for engine management. */ engineManagement: boolean; + githubManagement: boolean; /** Last pushed snapshot while online; absent offline or before the first push. */ engines?: EngineInventoryEntry[]; workspaces: string[]; @@ -136,6 +142,7 @@ type Peer = { reportsHealth?: boolean; /** Advertised in `ready`; whether this peer answers the `"engine"` command. */ engineManagement: boolean; + githubManagement: boolean; checkoutInspection: boolean; sharedWorktree: boolean; /** Last pushed, validated engine inventory; absent until the runner first reports one. */ @@ -642,6 +649,7 @@ export class RemoteRunnerService { socket, reportsHealth: ready.health === true, engineManagement: ready.engineManagement === true, + githubManagement: ready.githubManagement === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, connection: new RunnerConnection(send), @@ -864,6 +872,8 @@ export class RemoteRunnerService { name: this.legacy.id, engineManagement: peer?.gate.approved() === true && peer.engineManagement, + githubManagement: + peer?.gate.approved() === true && peer.githubManagement, ...(peer?.engines ? { engines: peer.engines } : {}), ...(peer?.health ? { @@ -900,6 +910,7 @@ export class RemoteRunnerService { ? "online" : "offline", engineManagement: online && peer.engineManagement, + githubManagement: online && peer.githubManagement, ...(online && peer.engines ? { engines: peer.engines } : {}), ...(online && peer.health ? { @@ -1175,9 +1186,15 @@ export class RemoteRunnerService { const peer = this.peers.get(runnerId); if (!peer?.gate.approved()) throw new RunnerUnavailable("The runner is disconnected or unavailable."); - if (!peer.engineManagement) + if ( + operation.kind === "engine" + ? !peer.engineManagement + : !peer.githubManagement + ) throw new RunnerCapabilityUnavailable( - "This runner does not support engine management." + operation.kind === "engine" + ? "This runner does not support engine management." + : "Update the runner to manage its GitHub account." ); // V1 requires a routable workspace and an id even for a runner-wide operation. @@ -1185,13 +1202,89 @@ export class RemoteRunnerService { if (peer.gate.allows(workspace)) return this.request( { runner: runnerId, workspace }, - { ...operation, agentId: "@engine", workspace }, - true + { ...operation, agentId: `@${operation.kind}`, workspace }, + operation.kind === "engine" ); } throw new RunnerUnavailable("The runner has no available workspace."); } + private async requestGitHub( + runnerId: string, + operation: GitHubOperation + ): Promise { + const { value } = await this.requestRunner(runnerId, { + kind: "github", + operation, + }); + if (typeof value !== "string") throw new Error("Invalid GitHub reply."); + return JSON.parse(value); + } + + async githubAccount( + runnerId: string, + type: "status" | "login" | "cancel" | "logout" + ): Promise { + try { + const status = parseGitHubStatus( + await this.requestGitHub(runnerId, { type }) + ); + if (status.status === "failed") + return { + ...status, + message: + "GitHub sign-in or configuration failed. Try again on this runner.", + }; + if (status.status === "unavailable") + return { + ...status, + message: + "GitHub is unavailable. Check that GitHub CLI is installed on the runner and it can reach github.com.", + }; + return status; + } catch (error) { + if ( + error instanceof RunnerCapabilityUnavailable || + error instanceof RunnerUnavailable + ) + return { status: "unavailable", message: error.message }; + return { + status: "unavailable", + message: "The runner could not report its GitHub account.", + }; + } + } + + async searchGitHubRepositories(runnerId: string, query: string) { + const response = await this.requestGitHub(runnerId, { + type: "repositorySearch", + query, + }); + if ( + !response || + typeof response !== "object" || + !("repositories" in response) + ) + throw new Error("Invalid GitHub repository reply."); + return githubRepositoryResults(response.repositories); + } + + async lookupGitHubPullRequestHead( + runnerId: string, + owner: string, + repo: string, + number: number + ) { + return githubPullRequestHead( + await this.requestGitHub(runnerId, { + type: "pullRequestHead", + owner, + repo, + number, + }) + ); + } + supportsSharedWorktree(placement: Placement) { return ( this.available(placement) && diff --git a/apps/server/src/routes/runner-github.ts b/apps/server/src/routes/runner-github.ts new file mode 100644 index 000000000..8defc8236 --- /dev/null +++ b/apps/server/src/routes/runner-github.ts @@ -0,0 +1,33 @@ +import type { FastifyInstance } from "fastify"; +import type { RemoteRunnerService } from "../agents/remote/service.js"; + +declare module "fastify" { + interface FastifyContextConfig { + /** Require ordinary host credentials even during passwordless setup. */ + hostAuthenticationRequired?: boolean; + } +} + +export function registerRunnerGitHub( + app: FastifyInstance, + runners: Pick +) { + const base = "/api/v1/runners/:id/github"; + const operations = [ + ["GET", base, "status"], + ["POST", `${base}/login`, "login"], + ["DELETE", `${base}/login`, "cancel"], + ["DELETE", base, "logout"], + ] as const; + for (const [method, url, operation] of operations) { + app.route<{ Params: { id: string } }>({ + method, + url, + config: { hostAuthenticationRequired: true }, + async handler(req, reply) { + reply.header("Cache-Control", "no-store"); + return runners.githubAccount(req.params.id, operation); + }, + }); + } +} diff --git a/apps/server/src/routes/runner-repositories.ts b/apps/server/src/routes/runner-repositories.ts index 22d562860..ec3e18192 100644 --- a/apps/server/src/routes/runner-repositories.ts +++ b/apps/server/src/routes/runner-repositories.ts @@ -1,104 +1,67 @@ import type { FastifyInstance } from "fastify"; -import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; +import { + validGitHubRepoPart, + validRepositorySearch, +} from "../agents/remote/protocol.js"; +import type { RemoteRunnerService } from "../agents/remote/service.js"; -/** Search with the service user's gh account. Only the repository address leaves the service. */ export function registerRunnerRepositorySearch( app: FastifyInstance, - run: CommandRunner = runCommand + runners: Pick< + RemoteRunnerService, + "searchGitHubRepositories" | "lookupGitHubPullRequestHead" + > ) { - app.get<{ Querystring: { q?: string } }>( - "/api/v1/runners/repository-search", + const options = { config: { hostAuthenticationRequired: true } } as const; + app.get<{ Params: { id: string }; Querystring: { q?: string } }>( + "/api/v1/runners/:id/repository-search", + options, async (req, reply) => { + reply.header("Cache-Control", "no-store"); const q = req.query.q; - if ( - typeof q !== "string" || - !/^[a-zA-Z0-9_.-][a-zA-Z0-9_./ -]{1,99}$/.test(q) - ) + if (!validRepositorySearch(q)) return reply .code(400) .send({ error: "Enter a repository name or owner/name." }); try { - const { stdout } = await run( - "gh", - [ - "search", - "repos", - "--match", - "name", - "--limit", - "12", - "--json", - "fullName,url", - "--", - q, - ], - { - timeoutMs: 8000, - env: { GH_PROMPT_DISABLED: "1" }, - } - ); - const rows: unknown = JSON.parse(stdout); - if (!Array.isArray(rows)) throw new Error("Invalid repository list"); - const repositories = rows.flatMap((row) => - typeof row?.fullName === "string" && - typeof row.url === "string" && - /^https:\/\//.test(row.url) - ? [{ name: row.fullName, url: row.url }] - : [] - ); - return { repositories }; + return await runners.searchGitHubRepositories(req.params.id, q); } catch { return reply.code(503).send({ - error: "GitHub search is unavailable. Paste an HTTPS repository URL.", + error: + "GitHub search is unavailable on this runner. Paste an HTTPS repository URL.", }); } } ); - app.get<{ Querystring: { url?: string } }>( - "/api/v1/runners/pull-request-head", + app.get<{ Params: { id: string }; Querystring: { url?: string } }>( + "/api/v1/runners/:id/pull-request-head", + options, async (req, reply) => { + reply.header("Cache-Control", "no-store"); const match = typeof req.query.url === "string" && - /^https:\/\/github\.com\/([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.-]+)\/pull\/([1-9][0-9]{0,9})\/?$/.exec( + /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]{0,9})\/?$/.exec( req.query.url ); - if (!match || [match[1], match[2]].some((v) => v === "." || v === "..")) + if ( + !match || + !validGitHubRepoPart(match[1]) || + !validGitHubRepoPart(match[2]) + ) return reply .code(400) .send({ error: "Enter a GitHub pull request URL." }); try { - // The pull ref in the base repo is read-only. Resolve the actual contributor branch. - const { stdout } = await run( - "gh", - [ - "api", - "--hostname", - "github.com", - `repos/${match[1]}/${match[2]}/pulls/${match[3]}`, - "--jq", - "{url:.head.repo.clone_url,branch:.head.ref}", - ], - { timeoutMs: 8000, env: { GH_PROMPT_DISABLED: "1" } } + return await runners.lookupGitHubPullRequestHead( + req.params.id, + match[1], + match[2], + Number(match[3]) ); - const head: unknown = JSON.parse(stdout); - if ( - !head || - typeof head !== "object" || - !("url" in head) || - !("branch" in head) || - typeof head.branch !== "string" || - !head.branch || - typeof head.url !== "string" || - !/^https:\/\/github\.com\/[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+(?:\.git)?$/.test( - head.url - ) - ) - throw new Error("Unavailable head"); - return { url: head.url, branch: head.branch }; } catch { return reply.code(422).send({ error: - "Could not resolve the PR’s source branch. Check GitHub access or enter the source repository and branch.", + "Could not resolve the PR’s source branch. Check GitHub access on this runner or enter the source repository and branch.", }); } } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 0e7fbc877..47d8e65b6 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -126,6 +126,7 @@ import { registerMcpRoutes } from "./routes/mcp.js"; import { registerPersonaRoutes } from "./routes/personas.js"; import { registerPersonalityRoutes } from "./routes/personalities.js"; import { registerQuickPhraseRoutes } from "./routes/quick-phrases.js"; +import { registerRunnerGitHub } from "./routes/runner-github.js"; import { registerRunnerInstaller } from "./routes/runner-installer.js"; import { registerRunnerRepositorySearch } from "./routes/runner-repositories.js"; import { registerRunnerRoutes } from "./routes/runners.js"; @@ -947,8 +948,13 @@ async function registerRoutes() { if (request.routeOptions.config.runnerConnectBootstrap) return; // The recovery helper authenticates with its enrollment key, loopback-only. if (request.routeOptions.config.updateRecovery) return; - // If no password is set, all routes are open (first-run mode). - if (!(await authRuntime.isPasswordSetCached())) return; + // First-run mode permits general API use. Runner GitHub credentials + // and private repository lookups still require host authentication. + if ( + !request.routeOptions.config.hostAuthenticationRequired && + !(await authRuntime.isPasswordSetCached()) + ) + return; // Bearer token is accepted on all API routes (for MCP agents, scripts, etc.) const authHeader = request.headers.authorization; @@ -1366,7 +1372,8 @@ async function registerRoutes() { await registerQuickPhraseRoutes(app, { pool }); if (remoteRunner) { - registerRunnerRepositorySearch(app); + registerRunnerGitHub(app, remoteRunner); + registerRunnerRepositorySearch(app, remoteRunner); registerRunnerInstaller(app, pool); } await registerRunnerRoutes(app, { runners: remoteRunner }); diff --git a/apps/server/test/engine-wire.test.ts b/apps/server/test/engine-wire.test.ts index e19d444d6..9bfd58590 100644 --- a/apps/server/test/engine-wire.test.ts +++ b/apps/server/test/engine-wire.test.ts @@ -10,6 +10,7 @@ import { wireFrames, type EngineOperationEvent, type Frame, + type GitHubOperation, } from "../src/agents/remote/protocol.js"; import { RunnerRegistry } from "../src/agents/remote/registry.js"; import { RemoteRunnerService } from "../src/agents/remote/service.js"; @@ -44,6 +45,7 @@ function dialEngineRunner(input: { key: string; workspaces: string[]; engineManagement?: boolean; + onGitHub?: (operation: GitHubOperation) => unknown; onEngine?: ( id: string, reply: (frame: Frame) => void, @@ -68,6 +70,12 @@ function dialEngineRunner(input: { const send = wireFrames(socket, (frame) => { if (frame.type === "request" && frame.command.kind === "engine") { input.onEngine?.(frame.id, send, frame.command.operation); + } else if (frame.type === "request" && frame.command.kind === "github") { + send({ + type: "result", + id: frame.id, + value: JSON.stringify(input.onGitHub?.(frame.command.operation)), + }); } }); socket.once("secureConnect", () => { @@ -76,6 +84,7 @@ function dialEngineRunner(input: { version: 1, health: true, ...(input.engineManagement !== false ? { engineManagement: true } : {}), + ...(input.onGitHub && { githubManagement: true }), workspaces: input.workspaces, }); resolve({ @@ -248,6 +257,77 @@ describe("engine wire integration", () => { expect(received).toBe(0); }); + it("routes GitHub operations to the chosen capable runner and drops access on revoke", async () => { + const service = makeService(); + const alpha = await enroll(service, "alpha"); + const beta = await enroll(service, "beta"); + const operations: GitHubOperation[] = []; + const a = await dialEngineRunner({ + ...alpha, + workspaces: ["proof"], + onGitHub(operation) { + operations.push(operation); + if (operation.type === "repositorySearch") + return { + repositories: [ + { name: "org/project", url: "https://github.com/org/project" }, + { + name: "org/reject", + url: "https://secret@github.com/org/reject", + }, + ], + }; + return { + status: "pending", + code: "ABCD-1234", + verificationUrl: "https://github.com/login/device", + token: "synthetic-token", + }; + }, + }); + const b = await dialEngineRunner({ ...beta, workspaces: ["proof"] }); + sockets.push(a.socket, b.socket); + await waitFor(() => + [alpha, beta].every((peer) => + service.available({ runner: peer.created.id, workspace: "proof" }) + ) + ); + const list = await service.list(); + expect( + list.find((entry) => entry.id === alpha.created.id)?.githubManagement + ).toBe(true); + expect( + list.find((entry) => entry.id === beta.created.id)?.githubManagement + ).toBe(false); + expect(JSON.stringify(list)).not.toContain("ABCD-1234"); + expect(await service.githubAccount(alpha.created.id, "login")).toEqual({ + status: "pending", + code: "ABCD-1234", + verificationUrl: "https://github.com/login/device", + }); + expect( + await service.searchGitHubRepositories(alpha.created.id, "org/project") + ).toEqual({ + repositories: [ + { name: "org/project", url: "https://github.com/org/project" }, + ], + }); + expect(await service.githubAccount(beta.created.id, "login")).toMatchObject( + { + status: "unavailable", + message: expect.stringContaining("Update"), + } + ); + await service.revoke(alpha.created.id); + expect( + await service.githubAccount(alpha.created.id, "status") + ).toMatchObject({ status: "unavailable" }); + expect(operations).toEqual([ + { type: "login" }, + { type: "repositorySearch", query: "org/project" }, + ]); + }); + it("stores and validates a pushed engine inventory, exposed via list()", async () => { const service = makeService(); const alpha = await enroll(service, "alpha"); diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts new file mode 100644 index 000000000..ebc499ab0 --- /dev/null +++ b/apps/server/test/github-runner-executor.test.ts @@ -0,0 +1,185 @@ +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { expect, it, vi } from "vitest"; +import { GitHubRunnerExecutor } from "../src/agents/remote/github-runner-executor.js"; +import { runnerGitArgs } from "../src/agents/remote/runner.js"; + +async function fixture( + run: (input: { + executor: GitHubRunnerExecutor; + root: string; + gh: string; + env: NodeJS.ProcessEnv; + }) => Promise +) { + const root = await mkdtemp(path.join(os.tmpdir(), "dispatch-gh-fixture-")); + const gh = path.join(root, "gh"); + const env = { HOME: root, PATH: process.env.PATH }; + try { + await writeFile( + gh, + String.raw`#!/bin/sh +set -eu +cd "$HOME" +case "$1 $2" in + 'config get') + test "$*" = 'config get user --host github.com' + if [ -f login ]; then cat login; else + printf 'could not find key "user"\n' >&2 + exit 1 + fi + ;; + 'auth login') + test "$GH_PROMPT_DISABLED" = '1' + test "$*" = 'auth login --hostname github.com --git-protocol https --web --insecure-storage' + printf '! First copy your one-time code: ABCD-' >&2 + printf '1234\nOpen this URL to continue in your web browser: https://github.com/login/device\n' >&2 + until [ -f authorize ] || [ -f reject ]; do sleep .02; done + if [ -f reject ]; then printf 'synthetic-secret\n' >&2; exit 1; fi + printf 'fixture-user\n' > login + ;; + 'auth setup-git') + test "$*" = 'auth setup-git --hostname github.com' + git config --global credential.https://github.com.helper "!$0 auth git-credential" + ;; + 'auth logout') + test "$*" = 'auth logout --hostname github.com --user fixture-user' + rm -f login + ;; + 'auth git-credential') + cat >/dev/null + test "$3" = 'get' + test -f login + printf 'username=fixture-user\npassword=synthetic-token\n' + ;; + 'api --hostname') + test "$3" = 'github.com' + case "$4" in + user) if [ -f revoked ]; then printf '(HTTP 401)\n' >&2; exit 1; fi; cat login ;; + repos/org/project/pulls/42) printf '%s' '{"url":"https://github.com/fork/project.git","branch":"fix"}' ;; + *) exit 1 ;; + esac + ;; + 'search repos') + test "$GH_HOST" = 'github.com' + test -f login + printf '%s' '[{"fullName":"org/project","url":"https://github.com/org/project"},{"fullName":"ignored/secret","url":"https://synthetic-token@github.com/org/project"}]' + ;; + *) exit 1 ;; +esac +`, + { mode: 0o700 } + ); + const executor = new GitHubRunnerExecutor(env, (bin, args) => { + expect(bin).toBe("/usr/bin/gh"); + return { bin: gh, args }; + }); + await run({ executor, root, gh, env }); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +it("completes a device login and configures the same credential helper for an agent and managed checkout", async () => { + await fixture(async ({ executor, root, env, gh }) => { + const connection = new AbortController(); + const handle = (type: "status" | "login" | "logout") => + executor.handle({ type }, connection.signal); + try { + expect(await handle("status")).toEqual({ status: "signed-out" }); + expect(await handle("login")).toMatchObject({ status: "pending" }); + await vi.waitFor(async () => + expect(await handle("status")).toEqual({ + status: "pending", + code: "ABCD-1234", + verificationUrl: "https://github.com/login/device", + }) + ); + expect(await handle("login")).toMatchObject({ + status: "pending", + code: "ABCD-1234", + }); + await writeFile(path.join(root, "authorize"), ""); + await vi.waitFor(async () => + expect(await handle("status")).toEqual({ + status: "signed-in", + login: "fixture-user", + }) + ); + for (const args of [ + [], + runnerGitArgs.map((arg) => arg.replace("/usr/bin/gh", gh)), + ]) { + const result = execFileSync("git", [...args, "credential", "fill"], { + cwd: root, + env: { ...env, GIT_TERMINAL_PROMPT: "0" }, + input: "protocol=https\nhost=github.com\n\n", + encoding: "utf8", + }); + expect(result).toContain("username=fixture-user"); + } + expect( + await executor.handle( + { type: "repositorySearch", query: "org/project" }, + connection.signal + ) + ).toEqual({ + repositories: [ + { name: "org/project", url: "https://github.com/org/project" }, + ], + }); + expect( + await executor.handle( + { + type: "pullRequestHead", + owner: "org", + repo: "project", + number: 42, + }, + connection.signal + ) + ).toEqual({ url: "https://github.com/fork/project.git", branch: "fix" }); + await writeFile(path.join(root, "revoked"), ""); + expect(await handle("status")).toEqual({ status: "signed-out" }); + expect(await handle("logout")).toEqual({ status: "signed-out" }); + } finally { + connection.abort(); + } + }); +}); + +it("clears pending device codes on cancel, disconnect and failed authorization", async () => { + await fixture(async ({ executor, root }) => { + let controller = new AbortController(); + const handle = (type: "status" | "login" | "cancel") => + executor.handle({ type }, controller.signal); + const pending = async () => { + await handle("login"); + await vi.waitFor(async () => + expect(await handle("status")).toMatchObject({ + status: "pending", + code: "ABCD-1234", + }) + ); + }; + try { + await pending(); + expect(await handle("cancel")).toEqual({ status: "signed-out" }); + await pending(); + controller.abort(); + controller = new AbortController(); + await vi.waitFor(async () => + expect(await handle("status")).toEqual({ status: "signed-out" }) + ); + await pending(); + await writeFile(path.join(root, "reject"), ""); + await vi.waitFor(async () => + expect(await handle("status")).toEqual({ status: "failed" }) + ); + } finally { + controller.abort(); + } + }); +}); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index e66682885..2d8a7afe8 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -212,6 +212,7 @@ describe("runner enrollment service", () => { name: "alpha", status: "pending", engineManagement: false, + githubManagement: false, workspaces: [], }, ]); @@ -268,6 +269,7 @@ describe("runner enrollment service", () => { name: "alpha", status: "online", engineManagement: false, + githubManagement: false, workspaces: ["proof"], }, ]); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 5c2928747..d2f65191e 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -108,12 +108,36 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () workspaces: ["@session"], health: true, engineManagement: true, + githubManagement: true, checkoutInspection: true, sharedWorktree: true, }; expect(parseReadyFrame(managed)).toEqual(managed); }); +it("validates runner-scoped GitHub command payloads", () => { + const parse = (operation: unknown) => + parseServiceFrame({ + type: "request", + id: "request-1", + command: { + kind: "github", + workspace: "@session", + agentId: "@github", + operation, + }, + }); + expect(parse({ type: "login" })).not.toBeNull(); + expect(parse({ type: "repositorySearch", query: "org/repo" })).not.toBeNull(); + expect(parse({ type: "repositorySearch", query: "--help\n" })).toBeNull(); + expect( + parse({ type: "pullRequestHead", owner: "..", repo: "repo", number: 1 }) + ).toBeNull(); + expect( + parse({ type: "pullRequestHead", owner: "org", repo: "repo", number: 1 }) + ).not.toBeNull(); +}); + it("validates checkout queries, results and borrowed launches", () => { const parse = (command: unknown) => parseServiceFrame({ type: "request", id: "request-1", command }); diff --git a/apps/server/test/runner-repositories.test.ts b/apps/server/test/runner-repositories.test.ts index ac4f65d10..c6b244640 100644 --- a/apps/server/test/runner-repositories.test.ts +++ b/apps/server/test/runner-repositories.test.ts @@ -6,18 +6,18 @@ import { installRunnerCommand } from "../src/routes/runner-installer.js"; describe("runner repository selection", () => { it("returns the contributor's repo and branch for a fork PR", async () => { const app = Fastify(); - const run = vi.fn().mockResolvedValue({ - stdout: JSON.stringify({ - url: "https://github.com/contributor/fork.git", - branch: "fix", - }), - stderr: "", - exitCode: 0, + const lookup = vi.fn().mockResolvedValue({ + url: "https://github.com/contributor/fork.git", + branch: "fix", + }); + const search = vi.fn().mockRejectedValue(new Error("secret from upstream")); + registerRunnerRepositorySearch(app, { + lookupGitHubPullRequestHead: lookup, + searchGitHubRepositories: search, }); - registerRunnerRepositorySearch(app, run); try { const r = await app.inject({ - url: "/api/v1/runners/pull-request-head", + url: "/api/v1/runners/rnr_fixture/pull-request-head", query: { url: "https://github.com/org/base/pull/12" }, }); expect(r.statusCode).toBe(200); @@ -25,13 +25,24 @@ describe("runner repository selection", () => { url: "https://github.com/contributor/fork.git", branch: "fix", }); - expect(run.mock.calls[0]?.[1]).toContain("repos/org/base/pulls/12"); + expect(lookup).toHaveBeenCalledWith("rnr_fixture", "org", "base", 12); const bad = await app.inject({ - url: "/api/v1/runners/pull-request-head", + url: "/api/v1/runners/rnr_fixture/pull-request-head", query: { url: "https://example.com/org/base/pull/12" }, }); expect(bad.statusCode).toBe(400); - expect(run).toHaveBeenCalledTimes(1); + expect(lookup).toHaveBeenCalledTimes(1); + const unavailable = await app.inject({ + url: "/api/v1/runners/rnr_other/repository-search", + query: { q: "org/base" }, + }); + expect(search).toHaveBeenCalledWith("rnr_other", "org/base"); + expect(unavailable.statusCode).toBe(503); + expect(unavailable.body).not.toContain("secret from upstream"); + expect( + (await app.inject("/api/v1/runners/repository-search?q=org/base")) + .statusCode + ).toBe(404); } finally { await app.close(); } diff --git a/apps/server/test/runner-routes.test.ts b/apps/server/test/runner-routes.test.ts index e7b31d847..c2d339146 100644 --- a/apps/server/test/runner-routes.test.ts +++ b/apps/server/test/runner-routes.test.ts @@ -22,6 +22,12 @@ describe("runner control API", () => { ["POST", "/api/runners"], ["DELETE", "/api/runners/rnr_x"], ["GET", "/api/v1/runners"], + ["GET", "/api/v1/runners/rnr_x/github"], + ["POST", "/api/v1/runners/rnr_x/github/login"], + ["DELETE", "/api/v1/runners/rnr_x/github/login"], + ["DELETE", "/api/v1/runners/rnr_x/github"], + ["GET", "/api/v1/runners/rnr_x/repository-search?q=org/repo"], + ["GET", "/api/v1/runners/rnr_x/pull-request-head"], ] as const) { const response = await ctx.app.inject({ method, @@ -32,6 +38,23 @@ describe("runner control API", () => { } }); + it("rejects scoped MCP tokens and sets no-store on GitHub account replies", async () => { + const url = "/api/v1/runners/rnr_missing/github"; + const hostToken = await ctx.auth.getOrCreateAuthToken(ctx.pool); + const scoped = ctx.auth.createAgentMcpToken(hostToken, "agt_fixture"); + const denied = await ctx.app.inject({ + url, + headers: { authorization: `Bearer ${scoped}` }, + }); + expect(denied.statusCode).toBe(401); + const permitted = await ctx.app.inject({ + url, + headers: { authorization: `Bearer ${hostToken}` }, + }); + expect(permitted.headers["cache-control"]).toBe("no-store"); + expect(permitted.json().status).toBe("unavailable"); + }); + it("creates, lists and revokes a registration", async () => { const cookie = await ctx.sessionCookie(); const created = await ctx.app.inject({ @@ -76,6 +99,7 @@ describe("runner control API", () => { name: "lima", status: "pending", engineManagement: false, + githubManagement: false, workspaces: [], }, ], diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 6539a3413..55d9ec31f 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -206,3 +206,25 @@ turn. CPU is a percentage over two samples (null until available), and memory is reported in bytes. Version identifies the runner build. Dispatch binds each report to its authenticated registration and stores the last snapshot with a service-side receipt time so stale measurements can be labeled after disconnect. + +### Optional GitHub account management + +Runners that advertise `githubManagement: true` in `ready` accept the +runner-wide `github` command. As with other runner-wide commands, use a +routable workspace and an opaque placeholder agent ID. The operation +supports account status, device-login start, cancel, and logout, plus +repository search and pull request source-branch lookup on github.com. +Replies are JSON strings carried in `result.value`. Account replies have a +`status` of `signed-out`, `signed-in`, `pending`, `unavailable`, or +`failed`. Poll with `status` for the device code while pending and the +account login after authorization. The consumer should expose a pending +code only to the authenticated operator and should keep it out of logs, +inventory, and durable state. + +The Linux implementation uses the runner's dedicated workload account. +Headless GitHub CLI login stores its credential in the workload user's gh +configuration file. Managed checkouts and agent HTTPS Git operations use +the same account through the gh credential helper. A transport disconnect +ends a pending login, and a completed credential remains with that +workload account. Logout removes the active account locally. GitHub +authorization can be revoked separately in GitHub settings. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 2e787ead0..2210cdf7b 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -10,6 +10,7 @@ import { isEngineOperation, isRunnerEngine, } from "./engine-management.js"; +import { isGitHubOperation, type GitHubOperation } from "./github.js"; import type { RunnerHealth } from "./health.js"; import { isHttpUrl, isNullableString, isRecord } from "./validation.js"; @@ -53,7 +54,9 @@ export type SessionOperation = { agentId: string } & ( | { kind: "stop"; force: boolean } ); -export type RunnerOperation = { kind: "engine"; operation: EngineOperation }; +export type RunnerOperation = + | { kind: "engine"; operation: EngineOperation } + | { kind: "github"; operation: GitHubOperation }; /** V1 uses one envelope for both scopes. Runner operations ignore the agent id. */ export type Command = { workspace: string } & ( @@ -68,6 +71,7 @@ export type ReadyFrame = { managedWorkspace?: true; /** Advertises support for the `"engine"` command and inventory push. */ engineManagement?: true; + githubManagement?: true; checkoutInspection?: true; sharedWorktree?: true; }; @@ -96,6 +100,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.sharedWorktree === true && { sharedWorktree: true }), ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), + ...(frame.githubManagement === true && { githubManagement: true }), ...(frame.managedWorkspace === true && { managedWorkspace: true }), }; } @@ -234,6 +239,8 @@ function isCommand(value: unknown): value is Command { return typeof value.force === "boolean"; case "engine": return isEngineOperation(value.operation); + case "github": + return isGitHubOperation(value.operation); default: return false; } diff --git a/packages/runner-protocol/src/github.ts b/packages/runner-protocol/src/github.ts new file mode 100644 index 000000000..4dc01c653 --- /dev/null +++ b/packages/runner-protocol/src/github.ts @@ -0,0 +1,127 @@ +import { validBranch } from "./checkout.js"; +import { isRecord } from "./validation.js"; + +export const githubDeviceUrl = "https://github.com/login/device"; + +export type GitHubOperation = + | { type: "status" | "login" | "cancel" | "logout" } + | { type: "repositorySearch"; query: string } + | { type: "pullRequestHead"; owner: string; repo: string; number: number }; + +export type GitHubStatus = + | { status: "signed-in"; login: string } + | { status: "pending"; code?: string; verificationUrl?: string } + | { status: "signed-out" } + | { status: "unavailable" | "failed"; message?: string }; + +export function validGitHubLogin(value: unknown): value is string { + return ( + typeof value === "string" && /^[a-z\d](?:[a-z\d_-]{0,38})$/i.test(value) + ); +} + +export function validGitHubDeviceCode(value: unknown): value is string { + return typeof value === "string" && /^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(value); +} + +export function validRepositorySearch(value: unknown): value is string { + return ( + typeof value === "string" && /^[a-z\d_.-][a-z\d_./ -]{1,99}$/i.test(value) + ); +} + +export function validGitHubRepoPart(value: unknown): value is string { + return ( + typeof value === "string" && + value !== "." && + value !== ".." && + /^[a-z\d_.-]{1,100}$/i.test(value) + ); +} + +export function isGitHubOperation(value: unknown): value is GitHubOperation { + if (!isRecord(value)) return false; + switch (value.type) { + case "status": + case "login": + case "cancel": + case "logout": + return true; + case "repositorySearch": + return validRepositorySearch(value.query); + case "pullRequestHead": + return ( + validGitHubRepoPart(value.owner) && + validGitHubRepoPart(value.repo) && + typeof value.number === "number" && + Number.isSafeInteger(value.number) && + value.number > 0 && + value.number <= 9_999_999_999 + ); + default: + return false; + } +} + +export function parseGitHubRepositoryUrl(value: unknown): value is string { + if (typeof value !== "string") return false; + const match = /^https:\/\/github\.com\/([^/]+)\/([^/]+)$/.exec(value); + return ( + !!match && validGitHubRepoPart(match[1]) && validGitHubRepoPart(match[2]) + ); +} + +export function githubRepositoryResults(value: unknown) { + if (!Array.isArray(value)) throw new Error("Invalid GitHub repository list."); + const repositories = value.slice(0, 12).flatMap((row) => { + if ( + !isRecord(row) || + typeof row.name !== "string" || + !parseGitHubRepositoryUrl(row.url) + ) + return []; + const parts = row.name.split("/"); + return parts.length === 2 && parts.every(validGitHubRepoPart) + ? [{ name: row.name, url: row.url }] + : []; + }); + return { repositories }; +} + +export function githubPullRequestHead(value: unknown) { + if ( + isRecord(value) && + parseGitHubRepositoryUrl(value.url) && + validBranch(value.branch) + ) { + return { url: value.url, branch: value.branch }; + } + throw new Error("GitHub pull request source branch is unavailable."); +} + +export function parseGitHubStatus(value: unknown): GitHubStatus { + if (isRecord(value)) { + switch (value.status) { + case "signed-in": + if (validGitHubLogin(value.login)) + return { status: "signed-in", login: value.login }; + break; + case "pending": + return value.verificationUrl === githubDeviceUrl && + validGitHubDeviceCode(value.code) + ? { + status: "pending", + code: value.code, + verificationUrl: githubDeviceUrl, + } + : { status: "pending" }; + case "signed-out": + return { status: "signed-out" }; + case "unavailable": + return { status: "unavailable" }; + case "failed": + return { status: "failed" }; + } + } + throw new Error("Invalid GitHub status."); +} diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index d85c1fa8a..8328a7ab6 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -4,3 +4,4 @@ export * from "./execution.js"; export * from "./session.js"; export * from "./health.js"; export * from "./checkout.js"; +export * from "./github.js"; From 02c50f5d58aab3bc5c3a80288efa0a58fe1be32c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:25:41 -0700 Subject: [PATCH 103/642] Redesign remote runner settings around a focused roster --- .../src/components/app/runner-health.test.tsx | 2 +- apps/web/src/components/app/runner-health.tsx | 22 +- .../src/components/app/runner-onboarding.tsx | 160 ++++-- .../components/app/runner-settings.test.tsx | 161 ++++++ .../src/components/app/runner-settings.tsx | 506 ++++++++++++------ .../runner-engines/runner-engines.tsx | 16 +- apps/web/src/components/ui/alert-dialog.tsx | 2 + 7 files changed, 642 insertions(+), 227 deletions(-) create mode 100644 apps/web/src/components/app/runner-settings.test.tsx diff --git a/apps/web/src/components/app/runner-health.test.tsx b/apps/web/src/components/app/runner-health.test.tsx index 0539f9231..bf1da16dd 100644 --- a/apps/web/src/components/app/runner-health.test.tsx +++ b/apps/web/src/components/app/runner-health.test.tsx @@ -82,6 +82,6 @@ it("preserves the no-sample state", () => { expect(screen.queryByText("Last report")).toBeNull(); rerender(); - expect(screen.queryByText("No health report received.")).toBeNull(); + expect(screen.getByText("No health report received.")).toBeTruthy(); expect(screen.queryByText("Last report")).toBeNull(); }); diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index 620832e5a..d40471a38 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -61,11 +61,11 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) { const installer = useRunnerInstaller(open); const tag = installer.data?.tag; if (!health || !healthReceivedAt) - return runner.status === "online" ? ( -

    + return ( +

    No health report received.

    - ) : null; + ); const update = tag && /^v?\d+\.\d+\.\d+$/.test(health.version) && @@ -75,16 +75,16 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) { Date.now() - Date.parse(healthReceivedAt) > 90_000; return (
    setOpen(event.currentTarget.open)} data-testid="runner-health" > - + {stale && "Last report · "} {health.sessions} {health.sessions === 1 ? "session" : "sessions"} ·{" "} {health.working} working -
    +
    CPU
    {health.cpuPercent === null ? "Sampling…" : `${health.cpuPercent}%`} @@ -101,10 +101,12 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) {
    {update && ( -
    -

    - Update available · {tag}. Run this on {runner.name} when its - sessions are finished. +

    +

    + Update available · {tag} +

    +

    + Run this on {runner.name} after its sessions finish.

    { e.preventDefault(); if ( @@ -117,23 +126,28 @@ function ApproveRunner({ request }: { request: PairRequest }) { />
    - - +
    + + +
    {(approve.error || dismiss.error) && (

    {(approve.error ?? dismiss.error)?.message} @@ -156,14 +170,49 @@ export function useRunnerInstaller(enabled: boolean) { }); } -export function RunnerOnboarding() { - const [opened, setOpened] = useState(false); +export function RunnerPairingRequests() { const pending = useQuery({ queryKey: ["runner-pairing-requests"], queryFn: () => api<{ requests: PairRequest[] }>("/api/v1/runners/connect"), refetchInterval: 5000, retry: false, }); + if (pending.isError && !pending.data) { + return ( +

    +

    + Could not load pairing requests. +

    + +
    + ); + } + + const requests = pending.data?.requests ?? []; + if (requests.length === 0) return null; + return ( +
    +

    + Pending approvals +

    +
    + {requests.map((request) => ( + + ))} +
    +
    + ); +} + +export function RunnerOnboarding() { + const [opened, setOpened] = useState(false); const instructions = useQuery({ queryKey: ["runner-connect-instructions"], queryFn: () => api<{ command: string }>("/api/v1/runners/connect-command"), @@ -172,19 +221,23 @@ export function RunnerOnboarding() { }); const installer = useRunnerInstaller(opened); return ( -
    - - {opened && ( -
    -
    -

    Install on Linux

    + + + + + + + Add runner + + Pair a Linux machine with this Dispatch instance. + + +
    +
    +

    1. Install on Linux

    Use a Linux x86-64 or ARM64 machine with systemd, GitHub CLI, Git, and sudo access. @@ -198,7 +251,9 @@ export function RunnerOnboarding() { Retry release check ) : installer.isPending ? ( -

    Checking release…

    +

    + Checking release… +

    ) : installer.data?.command ? ( ) : ( @@ -208,11 +263,11 @@ export function RunnerOnboarding() {

    )}
    -
    -

    Connect to Dispatch

    +
    +

    2. Connect to Dispatch

    - Run this on the machine. It will print a pairing code to enter - here. + Run this on the machine, then close this dialog and approve the + request using the pairing code printed in your terminal.

    {instructions.data ? ( ) : ( -

    Preparing command…

    +

    + Preparing command… +

    )}
    - )} - {pending.data?.requests.map((request) => ( - - ))} - {pending.isError && ( - - )} -
    +
    + + + +
    + + ); } diff --git a/apps/web/src/components/app/runner-settings.test.tsx b/apps/web/src/components/app/runner-settings.test.tsx new file mode 100644 index 000000000..aa8db65ad --- /dev/null +++ b/apps/web/src/components/app/runner-settings.test.tsx @@ -0,0 +1,161 @@ +// @vitest-environment jsdom +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; + +import type { Runner } from "@/hooks/use-runners"; +import { api } from "@/lib/api"; +import { RunnerSettings } from "./runner-settings"; + +vi.mock("@/lib/api", () => ({ api: vi.fn() })); +vi.mock("./runner-github-account", () => ({ + RunnerGitHubAccount: ({ runner }: { runner: Runner }) => ( +

    GitHub for {runner.name}

    + ), +})); + +const online: Runner = { + id: "build", + name: "Build machine", + status: "online", + workspaces: [], + engineManagement: true, +}; +const offline: Runner = { + ...online, + id: "spare", + name: "Spare machine", + status: "offline", +}; + +afterEach(() => { + cleanup(); + vi.resetAllMocks(); +}); + +function renderSettings() { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + return render( + + + + ); +} + +it("scopes details and confirmation to the selected runner and records a revocation", async () => { + let revoked = false; + vi.mocked(api).mockImplementation(async (path) => { + if (path === "/api/runners") { + return { + runners: [revoked ? { ...online, status: "revoked" } : online, offline], + }; + } + if (path === "/api/v1/runners/connect") return { requests: [] }; + if (path === "/api/runners/build") { + revoked = true; + return {}; + } + throw new Error(`Unexpected endpoint ${path}`); + }); + + renderSettings(); + const selectBuild = await screen.findByTestId("runner-select-build"); + expect(screen.queryByTestId("runner-detail")).toBeNull(); + + fireEvent.click(screen.getByTestId("runner-select-spare")); + expect(screen.getByText("GitHub for Spare machine")).toBeTruthy(); + expect(screen.queryByText("GitHub for Build machine")).toBeNull(); + expect(screen.queryByRole("button", { name: "Manage engines" })).toBeNull(); + + fireEvent.click(selectBuild); + expect(document.activeElement).toBe( + screen.getByRole("heading", { name: "Build machine" }) + ); + expect(screen.getByRole("button", { name: "Manage engines" })).toBeTruthy(); + const revoke = screen.getByTestId("runner-revoke-build"); + fireEvent.click(revoke); + const confirmation = screen.getByRole("alertdialog", { + name: "Revoke access for Build machine?", + }); + fireEvent.click(within(confirmation).getByRole("button", { name: "Cancel" })); + expect(api).not.toHaveBeenCalledWith("/api/runners/build", expect.anything()); + + fireEvent.click(revoke); + fireEvent.click(screen.getByTestId("runner-revoke-confirm-build")); + await screen.findByText("Access revoked for Build machine."); + expect(screen.queryByTestId("runner-detail")).toBeNull(); + expect(screen.queryByTestId("runner-select-build")).toBeNull(); + expect(api).toHaveBeenCalledWith("/api/runners/build", { method: "DELETE" }); + const history = screen.getByText("Revoked runners (1)").closest("details"); + expect(history?.open).toBe(false); + expect(within(history!).getByTestId("runner-build").textContent).toContain( + "Revoked" + ); +}); + +it("leaves pairing approvals actionable after closing the Add runner dialog", async () => { + let approved = false; + vi.mocked(api).mockImplementation(async (path) => { + if (path === "/api/runners") return { runners: approved ? [online] : [] }; + if (path === "/api/v1/runners/connect") { + return { requests: approved ? [] : [{ id: "request-deadbeef" }] }; + } + if (path === "/api/v1/runners/installer") + return { command: null, tag: null }; + if (path === "/api/v1/runners/connect-command") { + return { + command: "sudo dispatch-runner connect https://dispatch.example", + }; + } + if (path === "/api/v1/runners/connect/request-deadbeef/approve") { + approved = true; + return {}; + } + throw new Error(`Unexpected endpoint ${path}`); + }); + + renderSettings(); + const approval = await screen.findByTestId("runner-approval"); + const submit = within(approval).getByRole("button", { + name: "Approve runner", + }) as HTMLButtonElement; + expect(submit.disabled).toBe(true); + expect(screen.queryByRole("dialog")).toBeNull(); + + fireEvent.click(screen.getByRole("button", { name: "Add runner" })); + const dialog = screen.getByRole("dialog", { name: "Add runner" }); + await within(dialog).findByTestId("runner-connect-command"); + expect( + within(dialog).getByText(/signed runner installer is not available/) + ).toBeTruthy(); + fireEvent.click(within(dialog).getByRole("button", { name: "Done" })); + expect(screen.queryByRole("dialog")).toBeNull(); + + fireEvent.change(within(approval).getByLabelText("Runner name"), { + target: { value: " Build machine " }, + }); + fireEvent.change(within(approval).getByLabelText("Pairing code"), { + target: { value: " CODE " }, + }); + fireEvent.click(submit); + await screen.findByTestId("runner-select-build"); + await waitFor(() => + expect(screen.queryByTestId("runner-approval")).toBeNull() + ); + expect(api).toHaveBeenCalledWith( + "/api/v1/runners/connect/request-deadbeef/approve", + { + method: "POST", + body: JSON.stringify({ name: "Build machine", code: "CODE" }), + } + ); +}); diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index 0a6d82c59..580927bb1 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -1,24 +1,26 @@ -import { RunnerEngines } from "@/components/runner-engines/runner-engines"; -import { RunnerHealthDetails } from "./runner-health"; -import { useState } from "react"; -import { Server, Unplug } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { ArrowLeft, ChevronRight, Server } from "lucide-react"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; import { - Card, - CardContent, - CardDescription, - CardHeader, - CardTitle, -} from "@/components/ui/card"; -import { RunnerOnboarding } from "./runner-onboarding"; + AlertDialog, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import { RunnerEngines } from "@/components/runner-engines/runner-engines"; import { useRunnerMutations, useRunners, + type Runner, type RunnerStatus, } from "@/hooks/use-runners"; import { cn } from "@/lib/utils"; +import { RunnerGitHubAccount } from "./runner-github-account"; +import { RunnerHealthDetails } from "./runner-health"; +import { RunnerOnboarding, RunnerPairingRequests } from "./runner-onboarding"; const STATUS_LABEL: Record = { pending: "Waiting to pair", @@ -28,172 +30,360 @@ const STATUS_LABEL: Record = { }; const STATUS_DOT: Record = { - pending: "bg-amber-400", - online: "bg-emerald-500", + pending: "bg-status-waiting", + online: "bg-status-working", offline: "bg-muted-foreground/60", revoked: "bg-destructive", }; +function RunnerStatusLabel({ + runner, + inRoster, +}: { + runner: Runner; + inRoster?: boolean; +}) { + return ( + + + ); +} + export function RunnerSettings(): JSX.Element { const runners = useRunners({ poll: true }); - const { revoke } = useRunnerMutations(); - const [expandedEngines, setExpandedEngines] = useState(null); - const [confirmId, setConfirmId] = useState(null); + const [selectedId, setSelectedId] = useState(null); + const [notice, setNotice] = useState(""); + const rosterHeading = useRef(null); + const returnFocus = useRef(null); + const roster = (runners.data ?? []).filter( + (runner) => runner.status !== "revoked" + ); + const history = (runners.data ?? []).filter( + (runner) => runner.status === "revoked" + ); + const selected = roster.find((runner) => runner.id === selectedId); - const list = runners.data ?? []; + useEffect(() => { + const row = returnFocus.current; + if (selectedId || !row) return; + (row.isConnected ? row : rosterHeading.current)?.focus(); + returnFocus.current = null; + }, [selectedId]); return ( - - - Remote runners - - Run agents on another machine. Pair a runner, then pick it in Create - Agent. Local agents keep working if a runner disconnects. - - - +
    +
    +
    +

    + Remote runners +

    +

    + Connect a machine to run agents there from Dispatch. +

    +
    +
    - {runners.isPending ? ( -

    - Loading runners... + +

    + {notice} +

    + + {runners.isPending ? ( +

    + Loading runners… +

    + ) : runners.isError && !runners.data ? ( +
    +

    + Could not load runners.

    - ) : runners.isError ? ( -
    -

    - Could not load runners. -

    - +
    + ) : ( +
    0 && + "[@container(min-width:36rem)]:grid [@container(min-width:36rem)]:grid-cols-[minmax(0,2fr)_minmax(0,3fr)] [@container(min-width:36rem)]:items-start [@container(min-width:36rem)]:gap-5" + )} + > +
    +

    - Try again - -

    - ) : list.length === 0 ? ( -

    - No runners yet. Agents run on this Mac. -

    - ) : ( -
      - {list.map((runner) => ( -
    • -
    +
    + )} +
+ {selected ? ( + setSelectedId(null)} + onRevoked={() => { + setNotice(`Access revoked for ${selected.name}.`); + setSelectedId(null); + }} + /> + ) : roster.length > 0 ? ( +

+ Select a runner to view its details. +

+ ) : null} + + )} + + ); +} + +function RunnerDetail({ + runner, + onBack, + onRevoked, +}: { + runner: Runner; + onBack: () => void; + onRevoked: () => void; +}) { + const heading = useRef(null); + const [enginesOpen, setEnginesOpen] = useState(false); + const [confirmOpen, setConfirmOpen] = useState(false); + const { revoke } = useRunnerMutations(); + + useEffect(() => { + heading.current?.focus(); + }, []); + + return ( +
+
+ +
+

+ {runner.name} +

+ +
+ {runner.workspaces.length > 0 && !runner.managedWorkspace && ( +

+ Folders: {runner.workspaces.join(", ")} +

)} - {revoke.isError && ( -

- Could not revoke that runner. Try again. +

+ +
+

Health

+ +
+ +
+ +
+ +
+
+

Agent engines

+ {runner.status === "online" && runner.engineManagement && ( + + )} +
+ {runner.status !== "online" ? ( +

+ Engine management is available when the runner is online. +

+ ) : !runner.engineManagement ? ( +

+ This runner doesn’t support engine management.

+ ) : ( + )} - - +
+ +
+ { + if (revoke.isPending) return; + if (open) revoke.reset(); + setConfirmOpen(open); + }} + > + + + Revoke access for {runner.name}? + + + This disconnects the runner from this Dispatch instance and blocks + new sessions on it. To reconnect it, pair it again. + + {revoke.isError && ( +

+ {revoke.error.message} +

+ )} +
+ + Cancel + + +
+
+ + + +
+
+
); } diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index 454bc7d9a..b01f799ce 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -46,7 +46,15 @@ export function RunnerEngines({ scope }: { scope: EngineScope }): JSX.Element { } return ( -
+
+ {entries.length === 0 && ( +

+ No engines reported. +

+ )} {entries.map((entry) => (
-
+
{entry.label} @@ -316,7 +324,7 @@ function LoginFlow({ {login.userCode ? (
- + {login.userCode} Date: Wed, 18 Nov 2026 23:30:43 -0700 Subject: [PATCH 104/642] Honor passwordless operator access for runner GitHub routes --- apps/server/src/routes/runner-github.ts | 6 +-- apps/server/src/routes/runner-repositories.ts | 2 +- apps/server/src/server.ts | 12 ++--- .../test/remote-runner-enrollment.test.ts | 18 +++++++ apps/server/test/runner-github-auth.test.ts | 47 +++++++++++++++++++ 5 files changed, 75 insertions(+), 10 deletions(-) create mode 100644 apps/server/test/runner-github-auth.test.ts diff --git a/apps/server/src/routes/runner-github.ts b/apps/server/src/routes/runner-github.ts index 8defc8236..f95a42b00 100644 --- a/apps/server/src/routes/runner-github.ts +++ b/apps/server/src/routes/runner-github.ts @@ -3,8 +3,8 @@ import type { RemoteRunnerService } from "../agents/remote/service.js"; declare module "fastify" { interface FastifyContextConfig { - /** Require ordinary host credentials even during passwordless setup. */ - hostAuthenticationRequired?: boolean; + /** Validate supplied bearer credentials even during passwordless setup. */ + rejectInvalidBearer?: boolean; } } @@ -23,7 +23,7 @@ export function registerRunnerGitHub( app.route<{ Params: { id: string } }>({ method, url, - config: { hostAuthenticationRequired: true }, + config: { rejectInvalidBearer: true }, async handler(req, reply) { reply.header("Cache-Control", "no-store"); return runners.githubAccount(req.params.id, operation); diff --git a/apps/server/src/routes/runner-repositories.ts b/apps/server/src/routes/runner-repositories.ts index ec3e18192..8dc5d913a 100644 --- a/apps/server/src/routes/runner-repositories.ts +++ b/apps/server/src/routes/runner-repositories.ts @@ -12,7 +12,7 @@ export function registerRunnerRepositorySearch( "searchGitHubRepositories" | "lookupGitHubPullRequestHead" > ) { - const options = { config: { hostAuthenticationRequired: true } } as const; + const options = { config: { rejectInvalidBearer: true } } as const; app.get<{ Params: { id: string }; Querystring: { q?: string } }>( "/api/v1/runners/:id/repository-search", options, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47d8e65b6..ee168a113 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -948,17 +948,17 @@ async function registerRoutes() { if (request.routeOptions.config.runnerConnectBootstrap) return; // The recovery helper authenticates with its enrollment key, loopback-only. if (request.routeOptions.config.updateRecovery) return; - // First-run mode permits general API use. Runner GitHub credentials - // and private repository lookups still require host authentication. + const authHeader = request.headers.authorization; + const hasBearer = authHeader?.startsWith("Bearer ") === true; + // Passwordless operator access follows the normal first-run policy. + // Routes with this flag still validate an explicitly supplied bearer. if ( - !request.routeOptions.config.hostAuthenticationRequired && + !(request.routeOptions.config.rejectInvalidBearer && hasBearer) && !(await authRuntime.isPasswordSetCached()) ) return; - // Bearer token is accepted on all API routes (for MCP agents, scripts, etc.) - const authHeader = request.headers.authorization; - if (authHeader?.startsWith("Bearer ")) { + if (hasBearer) { const token = authHeader.slice(7); if (shouldAcceptApiBearerToken(token, config.authToken)) { return; diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 2d8a7afe8..b59ee2928 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -758,6 +758,24 @@ describe("runner enrollment service", () => { "origin", ]) expect(forwarded[name], name).toBeUndefined(); + apiRequests.length = 0; + for (const [method, path] of [ + ["GET", `/api/v1/runners/${a.created.id}/github`], + ["POST", `/api/v1/runners/${a.created.id}/github/login`], + ["GET", `/api/v1/runners/${a.created.id}/repository-search?q=org/repo`], + ["GET", `/api/v1/runners/${a.created.id}/pull-request-head`], + ]) { + expect( + ( + await get( + path, + { authorization: "Bearer agent-token:agt_abc" }, + method + ) + ).status + ).toBe(404); + } + expect(apiRequests).toHaveLength(0); // /ping carries no credentials upstream. apiRequests.length = 0; await get("/ping", { authorization: "Bearer agent-token:agt_abc" }); diff --git a/apps/server/test/runner-github-auth.test.ts b/apps/server/test/runner-github-auth.test.ts new file mode 100644 index 000000000..f46b1ef5d --- /dev/null +++ b/apps/server/test/runner-github-auth.test.ts @@ -0,0 +1,47 @@ +import { expect, it } from "vitest"; +import { useInjectApp } from "./helpers/inject-app.js"; + +const ctx = useInjectApp({ + setupAuth: false, + env: { + DISPATCH_RUNNER_HOST: "127.0.0.1", + DISPATCH_RUNNER_PORT: "0", + DISPATCH_RUNNER_ENDPOINT_HOST: "127.0.0.1", + }, +}); + +it("lets passwordless operators use runner GitHub routes while rejecting scoped bearers", async () => { + const hostToken = await ctx.auth.getOrCreateAuthToken(ctx.pool); + const scoped = ctx.auth.createAgentMcpToken(hostToken, "agt_fixture"); + const base = "/api/v1/runners/rnr_missing"; + for (const [method, url, status] of [ + ["GET", `${base}/github`, 200], + ["POST", `${base}/github/login`, 200], + ["DELETE", `${base}/github/login`, 200], + ["DELETE", `${base}/github`, 200], + ["GET", `${base}/repository-search?q=org/repo`, 503], + [ + "GET", + `${base}/pull-request-head?url=https://github.com/org/repo/pull/1`, + 422, + ], + ] as const) { + const operator = await ctx.app.inject({ method, url }); + expect(operator.statusCode, url).toBe(status); + expect(operator.headers["cache-control"]).toBe("no-store"); + + const agent = await ctx.app.inject({ + method, + url, + headers: { authorization: `Bearer ${scoped}` }, + }); + expect(agent.statusCode, url).toBe(401); + + const bearer = await ctx.app.inject({ + method, + url, + headers: { authorization: `Bearer ${hostToken}` }, + }); + expect(bearer.statusCode, url).toBe(status); + } +}); From 00f27f736711064fd83f8b1af5aab2a8669e0de5 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:32:48 -0700 Subject: [PATCH 105/642] Validate explicit credentials on runner GitHub endpoints --- apps/server/src/routes/runner-github.ts | 6 +++--- apps/server/src/routes/runner-repositories.ts | 2 +- apps/server/src/server.ts | 10 ++++++---- apps/server/test/runner-github-auth.test.ts | 6 ++++++ 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/apps/server/src/routes/runner-github.ts b/apps/server/src/routes/runner-github.ts index f95a42b00..ede5915ab 100644 --- a/apps/server/src/routes/runner-github.ts +++ b/apps/server/src/routes/runner-github.ts @@ -3,8 +3,8 @@ import type { RemoteRunnerService } from "../agents/remote/service.js"; declare module "fastify" { interface FastifyContextConfig { - /** Validate supplied bearer credentials even during passwordless setup. */ - rejectInvalidBearer?: boolean; + /** Validate supplied authorization credentials even during passwordless setup. */ + validateSuppliedAuthorization?: boolean; } } @@ -23,7 +23,7 @@ export function registerRunnerGitHub( app.route<{ Params: { id: string } }>({ method, url, - config: { rejectInvalidBearer: true }, + config: { validateSuppliedAuthorization: true }, async handler(req, reply) { reply.header("Cache-Control", "no-store"); return runners.githubAccount(req.params.id, operation); diff --git a/apps/server/src/routes/runner-repositories.ts b/apps/server/src/routes/runner-repositories.ts index 8dc5d913a..8f33b6d7d 100644 --- a/apps/server/src/routes/runner-repositories.ts +++ b/apps/server/src/routes/runner-repositories.ts @@ -12,7 +12,7 @@ export function registerRunnerRepositorySearch( "searchGitHubRepositories" | "lookupGitHubPullRequestHead" > ) { - const options = { config: { rejectInvalidBearer: true } } as const; + const options = { config: { validateSuppliedAuthorization: true } } as const; app.get<{ Params: { id: string }; Querystring: { q?: string } }>( "/api/v1/runners/:id/repository-search", options, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ee168a113..1f5d38a30 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -949,16 +949,18 @@ async function registerRoutes() { // The recovery helper authenticates with its enrollment key, loopback-only. if (request.routeOptions.config.updateRecovery) return; const authHeader = request.headers.authorization; - const hasBearer = authHeader?.startsWith("Bearer ") === true; // Passwordless operator access follows the normal first-run policy. - // Routes with this flag still validate an explicitly supplied bearer. + // Routes with this flag still validate explicitly supplied credentials. if ( - !(request.routeOptions.config.rejectInvalidBearer && hasBearer) && + !( + request.routeOptions.config.validateSuppliedAuthorization && + authHeader !== undefined + ) && !(await authRuntime.isPasswordSetCached()) ) return; - if (hasBearer) { + if (authHeader?.startsWith("Bearer ")) { const token = authHeader.slice(7); if (shouldAcceptApiBearerToken(token, config.authToken)) { return; diff --git a/apps/server/test/runner-github-auth.test.ts b/apps/server/test/runner-github-auth.test.ts index f46b1ef5d..d81b55064 100644 --- a/apps/server/test/runner-github-auth.test.ts +++ b/apps/server/test/runner-github-auth.test.ts @@ -36,6 +36,12 @@ it("lets passwordless operators use runner GitHub routes while rejecting scoped headers: { authorization: `Bearer ${scoped}` }, }); expect(agent.statusCode, url).toBe(401); + const unsupportedScheme = await ctx.app.inject({ + method, + url, + headers: { authorization: `bearer ${scoped}` }, + }); + expect(unsupportedScheme.statusCode, url).toBe(401); const bearer = await ctx.app.inject({ method, From 5263252a324d135b26c8a192a2439564acd70675 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:33:21 -0700 Subject: [PATCH 106/642] Support Debian GitHub CLI on remote runners --- .../agents/remote/github-runner-executor.ts | 29 ++++++++++---- .../test/github-runner-executor.test.ts | 38 ++++++++++++++++++- packages/runner-protocol/README.md | 5 ++- 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index 6a19ccb8c..c152253e7 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -111,9 +111,8 @@ export class GitHubRunnerExecutor { "--git-protocol", "https", "--web", - // Runner services have no desktop keyring. gh owns the file in the - // workload account's private config; no caller sees the credential. - "--insecure-storage", + // gh chooses the workload account's native store and falls back to + // its private config when running headless without a keyring. ]); connection.throwIfAborted(); const child = spawn(command.bin, command.args, { @@ -179,6 +178,24 @@ export class GitHubRunnerExecutor { this.failed = false; } + private async logout(login: string, signal: AbortSignal) { + try { + await this.run(["auth", "logout", ...hostArgs, "--user", login], signal); + } catch (error) { + const { stderr } = error as { stderr?: string }; + if (stderr?.split("\n", 1)[0] !== "unknown flag: --user") throw error; + // Debian 12's gh only has one account per host. Its --hostname form + // removes that account. Limit the fallback to the verified version. + const version = await this.run(["--version"], signal); + if ( + !/^gh version 2\.23\.0(?:\s|$)/.test(version) || + (await this.configuredUser(signal)) !== login + ) + throw error; + await this.run(["auth", "logout", ...hostArgs], signal); + } + } + private async statusOperation( operation: GitHubOperation, signal: AbortSignal @@ -211,11 +228,7 @@ export class GitHubRunnerExecutor { await this.stopLogin(); this.failed = false; const login = await this.configuredUser(signal); - if (login) - await this.run( - ["auth", "logout", ...hostArgs, "--user", login], - signal - ); + if (login) await this.logout(login, signal); return this.account(signal); } default: diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts index ebc499ab0..24873f69d 100644 --- a/apps/server/test/github-runner-executor.test.ts +++ b/apps/server/test/github-runner-executor.test.ts @@ -23,6 +23,10 @@ async function fixture( String.raw`#!/bin/sh set -eu cd "$HOME" +if [ "$1" = '--version' ]; then + cat gh-version + exit 0 +fi case "$1 $2" in 'config get') test "$*" = 'config get user --host github.com' @@ -33,7 +37,7 @@ case "$1 $2" in ;; 'auth login') test "$GH_PROMPT_DISABLED" = '1' - test "$*" = 'auth login --hostname github.com --git-protocol https --web --insecure-storage' + test "$*" = 'auth login --hostname github.com --git-protocol https --web' printf '! First copy your one-time code: ABCD-' >&2 printf '1234\nOpen this URL to continue in your web browser: https://github.com/login/device\n' >&2 until [ -f authorize ] || [ -f reject ]; do sleep .02; done @@ -45,7 +49,15 @@ case "$1 $2" in git config --global credential.https://github.com.helper "!$0 auth git-credential" ;; 'auth logout') - test "$*" = 'auth logout --hostname github.com --user fixture-user' + if [ -f gh-version ]; then + if [ "$#" = '6' ]; then + printf 'unknown flag: --user\n' >&2 + exit 1 + fi + test "$*" = 'auth logout --hostname github.com' + else + test "$*" = 'auth logout --hostname github.com --user fixture-user' + fi rm -f login ;; 'auth git-credential') @@ -183,3 +195,25 @@ it("clears pending device codes on cancel, disconnect and failed authorization", } }); }); + +it("uses host-only logout only for the verified single-account CLI version", async () => { + await fixture(async ({ executor, root }) => { + const signal = new AbortController().signal; + await writeFile(path.join(root, "login"), "fixture-user"); + await writeFile(path.join(root, "gh-version"), "gh version 2.24.0"); + expect(await executor.handle({ type: "logout" }, signal)).toEqual({ + status: "failed", + }); + expect(await executor.handle({ type: "status" }, signal)).toEqual({ + status: "signed-in", + login: "fixture-user", + }); + await writeFile( + path.join(root, "gh-version"), + "gh version 2.23.0 (Debian)" + ); + expect(await executor.handle({ type: "logout" }, signal)).toEqual({ + status: "signed-out", + }); + }); +}); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 55d9ec31f..34fff2494 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -222,8 +222,9 @@ code only to the authenticated operator and should keep it out of logs, inventory, and durable state. The Linux implementation uses the runner's dedicated workload account. -Headless GitHub CLI login stores its credential in the workload user's gh -configuration file. Managed checkouts and agent HTTPS Git operations use +GitHub CLI login uses the workload user's native credential store and falls +back to the user's gh configuration file on headless systems without a +keyring. Managed checkouts and agent HTTPS Git operations use the same account through the gh credential helper. A transport disconnect ends a pending login, and a completed credential remains with that workload account. Logout removes the active account locally. GitHub From 9e013d78e4e81036ee9655ead8e550a0ef1c805e Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:33:44 -0700 Subject: [PATCH 107/642] Show fresh runner activity in the Settings roster --- apps/web/src/components/app/runner-health.tsx | 15 +++++-- .../components/app/runner-settings.test.tsx | 45 +++++++++++++++++++ .../src/components/app/runner-settings.tsx | 37 +++++++++++---- 3 files changed, 86 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index d40471a38..591165e4e 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -55,6 +55,17 @@ const memory = (bytes: number) => ? `${Math.round(bytes / 1024 ** 2)} MiB` : `${(bytes / 1024 ** 3).toFixed(1)} GiB`; +export function isRunnerHealthFresh( + { status, healthReceivedAt }: Runner, + now = Date.now() +) { + return ( + status === "online" && + healthReceivedAt !== undefined && + now - Date.parse(healthReceivedAt) <= 90_000 + ); +} + export function RunnerHealthDetails({ runner }: { runner: Runner }) { const { health, healthReceivedAt } = runner; const [open, setOpen] = useState(false); @@ -70,9 +81,7 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) { tag && /^v?\d+\.\d+\.\d+$/.test(health.version) && isVersionNewer(tag, health.version); - const stale = - runner.status !== "online" || - Date.now() - Date.parse(healthReceivedAt) > 90_000; + const stale = !isRunnerHealthFresh(runner); return (
{ + const freshTime = new Date().toISOString(); + const staleTime = new Date(Date.now() - 91_000).toISOString(); + const health = { + version: "1.2.3", + sessions: 3, + working: 2, + cpuPercent: 10, + memoryUsed: 256, + memoryTotal: 1024, + }; + vi.mocked(api).mockImplementation(async (path) => { + if (path === "/api/v1/runners/connect") return { requests: [] }; + if (path !== "/api/runners") throw new Error(`Unexpected endpoint ${path}`); + return { + runners: [ + { ...online, health, healthReceivedAt: freshTime }, + { ...offline, health, healthReceivedAt: freshTime }, + { ...online, id: "stale", health, healthReceivedAt: staleTime }, + { ...online, id: "legacy" }, + { + ...online, + id: "idle", + health: { ...health, sessions: 0, working: 0 }, + healthReceivedAt: freshTime, + }, + ], + }; + }); + + renderSettings(); + const roster = await screen.findByTestId("runner-list"); + expect( + within(roster).getByTestId("runner-select-build").textContent + ).toContain("Online · 2 working"); + expect( + within(roster).getByTestId("runner-select-idle").textContent + ).toContain("Online · 0 sessions"); + for (const id of ["spare", "stale", "legacy"]) { + expect( + within(roster).getByTestId(`runner-select-${id}`).textContent + ).not.toContain(" · "); + } +}); diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index 580927bb1..f861ea6c6 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -19,7 +19,7 @@ import { } from "@/hooks/use-runners"; import { cn } from "@/lib/utils"; import { RunnerGitHubAccount } from "./runner-github-account"; -import { RunnerHealthDetails } from "./runner-health"; +import { isRunnerHealthFresh, RunnerHealthDetails } from "./runner-health"; import { RunnerOnboarding, RunnerPairingRequests } from "./runner-onboarding"; const STATUS_LABEL: Record = { @@ -39,23 +39,38 @@ const STATUS_DOT: Record = { function RunnerStatusLabel({ runner, inRoster, + checkedAt, }: { runner: Runner; inRoster?: boolean; + checkedAt?: number; }) { + const health = + checkedAt !== undefined && isRunnerHealthFresh(runner, checkedAt) + ? runner.health + : undefined; return ( - + ); } @@ -72,6 +87,8 @@ export function RunnerSettings(): JSX.Element { const history = (runners.data ?? []).filter( (runner) => runner.status === "revoked" ); + // Recheck freshness after each poll, even if the roster data is unchanged. + const checkedAt = Math.max(runners.dataUpdatedAt, runners.errorUpdatedAt); const selected = roster.find((runner) => runner.id === selectedId); useEffect(() => { @@ -180,7 +197,11 @@ export function RunnerSettings(): JSX.Element { {runner.name} - + Date: Wed, 18 Nov 2026 23:35:10 -0700 Subject: [PATCH 108/642] Exercise runner GitHub access with isolated accounts and a private checkout --- .../components/app/runner-github-account.tsx | 59 +++++---- docs/remote-runner-linux.md | 24 ++-- e2e/remote-runner/acceptance.spec.ts | 7 +- e2e/remote-runner/fixture-gh.sh | 46 +++++++ e2e/remote-runner/github-account.spec.ts | 119 ++++++++++++++++++ e2e/remote-runner/github-fixture-server.cjs | 65 ++++++++++ e2e/remote-runner/github-fixture.sh | 24 ++++ e2e/remote-runner/harness.ts | 30 ++++- 8 files changed, 325 insertions(+), 49 deletions(-) create mode 100644 e2e/remote-runner/fixture-gh.sh create mode 100644 e2e/remote-runner/github-account.spec.ts create mode 100644 e2e/remote-runner/github-fixture-server.cjs create mode 100644 e2e/remote-runner/github-fixture.sh diff --git a/apps/web/src/components/app/runner-github-account.tsx b/apps/web/src/components/app/runner-github-account.tsx index 759f8f0f1..2ea503e5c 100644 --- a/apps/web/src/components/app/runner-github-account.tsx +++ b/apps/web/src/components/app/runner-github-account.tsx @@ -1,3 +1,4 @@ +import { githubDeviceUrl, type GitHubStatus } from "@dispatch/runner-protocol"; import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { ExternalLink, Github } from "lucide-react"; @@ -15,13 +16,6 @@ import { import type { Runner } from "@/hooks/use-runners"; import { api } from "@/lib/api"; -type GitHubAccount = { - status: "signed-out" | "signed-in" | "pending" | "unavailable" | "failed"; - login?: string; - code?: string; - message?: string; -}; - export function RunnerGitHubAccount({ runner }: { runner: Runner }) { if (runner.status === "revoked") return null; if (runner.status !== "online" || !runner.githubManagement) { @@ -47,6 +41,23 @@ function AccountHeading() { ); } +function accountSummary(account: GitHubStatus) { + switch (account.status) { + case "signed-in": + return `Signed in as @${account.login}`; + case "signed-out": + return "Sign in to use your repositories from agents on this runner."; + case "pending": + return account.code + ? "Waiting for GitHub approval" + : "Requesting a device code…"; + case "failed": + return "Sign-in did not complete. Try again."; + case "unavailable": + return "Couldn’t reach GitHub from this runner. Check its connection and GitHub CLI installation."; + } +} + function ConnectedAccount({ runner }: { runner: Runner }) { const client = useQueryClient(); const [confirmLogout, setConfirmLogout] = useState(false); @@ -55,14 +66,15 @@ function ConnectedAccount({ runner }: { runner: Runner }) { const account = useQuery({ queryKey: key, queryFn: ({ signal }) => - api(path, { signal, cache: "no-store" }), + api(path, { signal, cache: "no-store" }), refetchInterval: (q) => (q.state.data?.status === "pending" ? 2000 : false), retry: false, gcTime: 0, }); const action = useMutation({ + gcTime: 0, mutationFn: (op: "login" | "logout" | "cancel") => - api(op === "logout" ? path : path + "/login", { + api(op === "logout" ? path : path + "/login", { method: op === "login" ? "POST" : "DELETE", }), onMutate: () => client.cancelQueries({ queryKey: key }), @@ -81,19 +93,9 @@ function ConnectedAccount({ runner }: { runner: Runner }) { const unavailable = state?.status === "unavailable"; const statusText = account.isError ? "Couldn’t read the account." - : account.isPending - ? "Checking account…" - : signedIn - ? `Signed in as @${state.login}` - : unavailable - ? state.message || "GitHub CLI is unavailable on this runner." - : state?.status === "failed" - ? state.message || "Sign-in did not complete." - : pending - ? state.code - ? "Waiting for GitHub approval" - : "Requesting a device code…" - : "Signed out"; + : state + ? accountSummary(state) + : "Checking account…"; return (
@@ -160,11 +162,7 @@ function ConnectedAccount({ runner }: { runner: Runner }) {
+

Connect tools that can send work and context to your Dispatch agents.

diff --git a/apps/web/src/components/app/runner-github-account.tsx b/apps/web/src/components/app/runner-github-account.tsx index 2ea503e5c..9ebeeba31 100644 --- a/apps/web/src/components/app/runner-github-account.tsx +++ b/apps/web/src/components/app/runner-github-account.tsx @@ -46,7 +46,7 @@ function accountSummary(account: GitHubStatus) { case "signed-in": return `Signed in as @${account.login}`; case "signed-out": - return "Sign in to use your repositories from agents on this runner."; + return "Signed out"; case "pending": return account.code ? "Waiting for GitHub approval" @@ -103,7 +103,7 @@ function ConnectedAccount({ runner }: { runner: Runner }) {

{statusText}

@@ -142,9 +142,10 @@ function ConnectedAccount({ runner }: { runner: Runner }) { type="button" size="sm" disabled={action.isPending} + aria-label="Sign in to GitHub" onClick={() => action.mutate("login")} > - Sign in to GitHub + {action.isPending ? "Starting…" : "Sign in"} ) )} @@ -152,7 +153,8 @@ function ConnectedAccount({ runner }: { runner: Runner }) { {pending && state.code && !account.isError && (

- Enter this code on GitHub to authorize {runner.name}. + Enter this code on GitHub. Agents on {runner.name} will use the + account you approve.

diff --git a/apps/web/src/components/app/settings-pane.test.tsx b/apps/web/src/components/app/settings-pane.test.tsx index 4d869ba8f..07ea95ed9 100644 --- a/apps/web/src/components/app/settings-pane.test.tsx +++ b/apps/web/src/components/app/settings-pane.test.tsx @@ -281,7 +281,8 @@ describe("SettingsContent", () => { ["workspace", ["IdeSettings", "WorktreeLocationSettings"]], ["security", ["SecuritySettings"]], ["notifications", ["NotificationSettings"]], - ["connections", ["BrowserExtensionSettings", "RunnerSettings"]], + ["connections", ["BrowserExtensionSettings"]], + ["runners", ["RunnerSettings"]], ["resources", ["ServiceResourcesSettings"]], ["updates", ["UpdatesSection", "PluginUpdateSettings"]], ["help", ["DocsContent"]], diff --git a/apps/web/src/components/app/settings-pane.tsx b/apps/web/src/components/app/settings-pane.tsx index 3e6464865..601fa46d6 100644 --- a/apps/web/src/components/app/settings-pane.tsx +++ b/apps/web/src/components/app/settings-pane.tsx @@ -232,14 +232,8 @@ export function SettingsContent({ )} {activeSection === "notifications" && } - {activeSection === "connections" && ( - <> - -
- -
- - )} + {activeSection === "connections" && } + {activeSection === "runners" && } {activeSection === "resources" && } {activeSection === "updates" && (
diff --git a/apps/web/src/components/app/settings-state.test.ts b/apps/web/src/components/app/settings-state.test.ts index 6cba6d494..b74631ff0 100644 --- a/apps/web/src/components/app/settings-state.test.ts +++ b/apps/web/src/components/app/settings-state.test.ts @@ -28,6 +28,7 @@ const NON_ADMIN_SECTIONS = [ "help", "notifications", "resources", + "runners", "security", "updates", "workspace", @@ -115,6 +116,7 @@ describe("useSettingsState", () => { "help", "notifications", "resources", + "runners", "security", "updates", "workspace", diff --git a/apps/web/src/components/app/settings-state.ts b/apps/web/src/components/app/settings-state.ts index 78a53bd83..967f77924 100644 --- a/apps/web/src/components/app/settings-state.ts +++ b/apps/web/src/components/app/settings-state.ts @@ -7,6 +7,7 @@ import { Package, Gauge, Settings, + Server, Users, FolderGit2, Shield, @@ -20,6 +21,7 @@ export type SettingsSection = | "workspace" | "security" | "connections" + | "runners" | "notifications" | "updates" | "resources" @@ -37,6 +39,7 @@ const BASE_SECTIONS: Array<{ { id: "security", label: "Security", icon: Shield }, { id: "connections", label: "Connections", icon: Cable }, { id: "notifications", label: "Notifications", icon: Bell }, + { id: "runners", label: "Runners", icon: Server }, { id: "resources", label: "Resources", icon: Gauge }, { id: "updates", label: "Updates", icon: ArrowDownToLine }, ]; @@ -58,6 +61,7 @@ const ALL_VALID_SECTIONS: SettingsSection[] = [ "workspace", "security", "connections", + "runners", "notifications", "updates", "resources", diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index cd216eaa8..bf0bd585d 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -11,8 +11,8 @@ The instructions below describe the manual prototype path. 1. Prepare the Linux runner binary, workload account, workspace and `/etc/dispatch-runner/runner.json` as described below. Configure the workload settings before pairing. -2. In **Settings → Connections → Remote runners**, enter a name and choose - **Pair runner**. Run the displayed one-time command as root on the runner. +2. In **Settings → Runners**, choose **Add runner**. Run the connect command + on the runner, then enter its pairing code and name in Dispatch. Dispatch issues the certificate. The private key is generated on the runner. 3. Start the runner supervisor with its updated configuration. In Settings, wait for **Online** and check the advertised workspace list. diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index 45960ff62..622efa754 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -10,7 +10,7 @@ The published binary bundles Bun and runs on glibc-based Linux. Session supervision requires a kernel with pidfd signaling (introduced in Linux 5.1). For manual source runs, use Bun. -1. In Dispatch, open **Settings → Connections → Remote runners** and run +1. In Dispatch, open **Settings → Runners → Add runner** and run the installation command for the available release. The installer prepares the workload account and configuration, and adds `dispatch-runner` to `/usr/local/bin`. @@ -90,7 +90,7 @@ For custom engine install paths, edit the `bins` object in ## Private GitHub repositories -In **Settings → Connections**, select the runner and choose **Sign in to GitHub**. +In **Settings → Runners**, select the runner and choose **Sign in to GitHub**. Open GitHub in your browser and enter the code shown for that runner. Once GitHub approves, the runner shows the account name and configures Git to use that login for HTTPS. The runner needs GitHub CLI at `/usr/bin/gh`. diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index f6008b2fb..14ecaf4e2 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -503,7 +503,7 @@ test("managed scratch launch reports health and archive removes the guest sessio guest("scratch", `cat /var/lib/runner/hosts/${id}/host.pid`).trim() ).toBe(scratchPid); - await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.goto("/settings/runners", { waitUntil: "domcontentloaded" }); await page.getByTestId(`runner-select-${runnerId}`).click(); const health = page.getByTestId("runner-detail").getByTestId("runner-health"); const summary = health.locator("summary"); diff --git a/e2e/remote-runner/github-account.spec.ts b/e2e/remote-runner/github-account.spec.ts index f15989de9..11872b26e 100644 --- a/e2e/remote-runner/github-account.spec.ts +++ b/e2e/remote-runner/github-account.spec.ts @@ -50,7 +50,7 @@ test("GitHub sign-in, private checkout and sign-out belong to the selected runne ids.set(name, row?.id ?? (await enrollViaUi(page, request, name))); } const openAccount = async (name: "scratch" | "beta") => { - await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.goto("/settings/runners", { waitUntil: "domcontentloaded" }); await page.getByTestId("runner-select-" + ids.get(name)).click(); return page.getByTestId("runner-github"); }; diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 2272c32f0..86869ca3a 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -120,7 +120,7 @@ export const runnerRow = async (request: APIRequestContext, name: string) => (await runnerRows(request)).find((r) => r.name === name); async function connectCommand(page: Page) { - await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.goto("/settings/runners", { waitUntil: "domcontentloaded" }); await page.getByRole("button", { name: "Add runner", exact: true }).click(); const command = page.getByTestId("runner-connect-command"); await expect(command).toContainText("dispatch-runner connect"); @@ -188,7 +188,7 @@ export async function requestConnection( .toBeTruthy(); const { code, reference } = approval()!; expect(output).toContain( - `Approve at: ${new URL("/settings/connections", page.url()).href}` + `Approve at: ${new URL("/settings/runners", page.url()).href}` ); const form = page.getByTestId("runner-approval").filter({ has: page.getByText(`Connection request · ${reference}`, { exact: true }), @@ -252,7 +252,7 @@ export async function enrollViaUi( } export async function revokeViaUi(page: Page, id: string) { - await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.goto("/settings/runners", { waitUntil: "domcontentloaded" }); await page.getByTestId(`runner-select-${id}`).click(); await page.getByTestId(`runner-revoke-${id}`).click(); await page.getByTestId(`runner-revoke-confirm-${id}`).click(); From da2d045837d54752da28283a6060ef4278afdaa6 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:44:29 -0700 Subject: [PATCH 112/642] Simplify runner settings into a list and URL-driven detail --- apps/web/src/components/app/runner-health.tsx | 18 +- .../src/components/app/runner-onboarding.tsx | 36 +- .../components/app/runner-settings.test.tsx | 78 ++- .../src/components/app/runner-settings.tsx | 533 ++++++++++-------- .../runner-engines/runner-engines.test.tsx | 2 +- .../runner-engines/runner-engines.tsx | 59 +- 6 files changed, 413 insertions(+), 313 deletions(-) diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index 591165e4e..095423396 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -73,9 +73,12 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) { const tag = installer.data?.tag; if (!health || !healthReceivedAt) return ( -

- No health report received. -

+
+

Health

+

+ No health report received. +

+
); const update = tag && @@ -89,9 +92,12 @@ export function RunnerHealthDetails({ runner }: { runner: Runner }) { data-testid="runner-health" > - {stale && "Last report · "} - {health.sessions} {health.sessions === 1 ? "session" : "sessions"} ·{" "} - {health.working} working + Health + + {stale && "Last report · "} + {health.sessions} {health.sessions === 1 ? "session" : "sessions"} ·{" "} + {health.working} working +
CPU
diff --git a/apps/web/src/components/app/runner-onboarding.tsx b/apps/web/src/components/app/runner-onboarding.tsx index 683b961c9..4d9382913 100644 --- a/apps/web/src/components/app/runner-onboarding.tsx +++ b/apps/web/src/components/app/runner-onboarding.tsx @@ -25,9 +25,9 @@ export function RunnerCommand({ }) { const [copied, copy] = useCopyText(); return ( -
+
         {value}
@@ -36,12 +36,12 @@ export function RunnerCommand({
         type="button"
         size="sm"
         variant="ghost"
-        className="gap-1.5 border border-border"
+        className="shrink-0 gap-1.5"
         onClick={() => copy(value)}
-        aria-label={`Copy ${label.toLowerCase()} command`}
+        aria-label={`${copied ? "Copied" : "Copy"} ${label.toLowerCase()} command`}
       >
-        
-        {copied ? "Copied" : "Copy command"}
+        
); @@ -97,11 +97,9 @@ function ApproveRunner({ request }: { request: PairRequest }) { }} data-testid="runner-approval" > -

- Connection request · {request.id.slice(-8)} -

+

Request {request.id.slice(-8)}

- Match the request reference and enter the code printed on the runner. + Enter the pairing code printed on the runner.

+ )} + )} ); @@ -256,155 +307,149 @@ export function RunnerSettings(): JSX.Element { function RunnerDetail({ runner, - onBack, + heading, onRevoked, }: { runner: Runner; - onBack: () => void; + heading: React.RefObject; onRevoked: () => void; }) { - const heading = useRef(null); - const [enginesOpen, setEnginesOpen] = useState(false); - const [confirmOpen, setConfirmOpen] = useState(false); - const { revoke } = useRunnerMutations(); - - useEffect(() => { - heading.current?.focus(); - }, []); - return ( -
-
- -
-

+
+
+

{runner.name} -

+

- {runner.workspaces.length > 0 && !runner.managedWorkspace && ( -

- Folders: {runner.workspaces.join(", ")} -

- )} -
- -
-

Health

- -
+ + -
+
-
-
-

Agent engines

- {runner.status === "online" && runner.engineManagement && ( - - )} -
+
+

Agent engines

{runner.status !== "online" ? (

- Engine management is available when the runner is online. + Available when the runner is online.

) : !runner.engineManagement ? (

- This runner doesn’t support engine management. + Engine management isn’t supported on this runner.

) : ( - + )}
-
- { - if (revoke.isPending) return; - if (open) revoke.reset(); - setConfirmOpen(open); +
+ + {runner.workspaces.length > 0 && !runner.managedWorkspace && ( +

+ Folders: {runner.workspaces.join(", ")} +

+ )} +
+
+ ); +} + +function RunnerConnectionActions({ + runner, + onRevoked, +}: { + runner: Runner; + onRevoked: () => void; +}) { + const trigger = useRef(null); + const [confirmOpen, setConfirmOpen] = useState(false); + const { revoke } = useRunnerMutations(); + + return ( + <> + + + + + { + if (confirmOpen) event.preventDefault(); }} > - - - Revoke access for {runner.name}? - - - This disconnects the runner from this Dispatch instance and blocks - new sessions on it. To reconnect it, pair it again. - - {revoke.isError && ( -

- {revoke.error.message} -

- )} -
- - Cancel - - -
-
- + { + revoke.reset(); + setConfirmOpen(true); + }} + > + Revoke connection + +
+
+ { + if (!revoke.isPending) setConfirmOpen(open); + }} + > + { + event.preventDefault(); + trigger.current?.focus(); + }} + > + + Revoke access for {runner.name}? + + + This disconnects the runner and blocks new sessions on it. To + reconnect it, pair it again. + + {revoke.isError && ( +

+ {revoke.error.message} +

+ )} +
+ + Cancel + - - -
-
+
+ + + ); } diff --git a/apps/web/src/components/runner-engines/runner-engines.test.tsx b/apps/web/src/components/runner-engines/runner-engines.test.tsx index aed624a48..ef9b4d0a4 100644 --- a/apps/web/src/components/runner-engines/runner-engines.test.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.test.tsx @@ -69,7 +69,7 @@ it("renders each engine's installed/signed-in state and available actions", asyn expect(screen.getByTestId("runner-engine-claude-update")).toBeTruthy(); expect(screen.getByTestId("runner-engine-codex").textContent).toContain( - "not installed" + "Not installed" ); expect(screen.getByTestId("runner-engine-codex-install")).toBeTruthy(); }); diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index b01f799ce..f0927df56 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -6,7 +6,6 @@ import type { EngineLoginView, } from "@dispatch/runner-protocol/engine-management"; -import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { CopyButton } from "@/components/ui/copy-button"; import { Input } from "@/components/ui/input"; @@ -30,7 +29,10 @@ export function RunnerEngines({ scope }: { scope: EngineScope }): JSX.Element { if (inventory.isLoading) { return ( -

+

@@ -39,15 +41,25 @@ export function RunnerEngines({ scope }: { scope: EngineScope }): JSX.Element { if (inventory.isError) { return ( -

- Could not load engines for this scope. -

+
+

+ Could not load engines. +

+ +
); } return (
{entries.length === 0 && ( @@ -139,22 +151,20 @@ function EngineRow({ data-testid={`runner-engine-${entry.id}`} >
-
- - {entry.label} - - {entry.installed ? ( - - {entry.version ? `v${entry.version}` : "installed"} - - ) : ( - not installed - )} - {entry.installed && entry.signedIn !== null && ( - - {entry.signedIn ? "signed in" : "signed out"} - - )} +
+
{entry.label}
+

+ {entry.installed ? ( + <> + {entry.version ? `v${entry.version}` : "Installed"} + {entry.signedIn === true && " · signed in"} + {entry.signedIn === false && " · signed out"} + {entry.detail && entry.signedIn && ` · ${entry.detail}`} + + ) : ( + "Not installed" + )} +

{canInstall && ( @@ -173,7 +183,6 @@ function EngineRow({
- {entry.detail && entry.signedIn && ( -

{entry.detail}

- )} - {entry.issue === "install-unavailable" && (

Install isn't available on this runner — its install command couldn't From f595d9ab590e542c682c6192d2d5cf27d3572f2c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:46:36 -0700 Subject: [PATCH 113/642] Drive runner approval and account management through Settings navigation --- docs/remote-runner-linux.md | 2 +- e2e/remote-runner/github-account.spec.ts | 11 ++++++++++- e2e/remote-runner/harness.ts | 13 +++++++++---- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index 622efa754..b97c52316 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -25,7 +25,7 @@ For manual source runs, use Bun. and starts the service once enrollment succeeds. Wait for **Online** in Settings. -3. Open **Manage engines** on the runner in Dispatch. Choose **Install** for +3. Select the runner in **Settings → Runners**. Under **Agent engines**, choose **Install** for the engine you want, then **Sign in** for Codex or Claude. The runner uses Node.js and npm from its workload PATH to install engine binaries under `/var/lib/dispatch-runner/home/.local/bin`. Install Node.js and npm on diff --git a/e2e/remote-runner/github-account.spec.ts b/e2e/remote-runner/github-account.spec.ts index 11872b26e..fcc4e81e0 100644 --- a/e2e/remote-runner/github-account.spec.ts +++ b/e2e/remote-runner/github-account.spec.ts @@ -54,7 +54,16 @@ test("GitHub sign-in, private checkout and sign-out belong to the selected runne await page.getByTestId("runner-select-" + ids.get(name)).click(); return page.getByTestId("runner-github"); }; - let account = await openAccount("scratch"); + // Bookmarks from the earlier pairing flow still lead to the runner list. + await page.goto("/settings/connections", { waitUntil: "domcontentloaded" }); + await page.getByRole("link", { name: "Manage runners" }).click(); + await expect(page).toHaveURL(/\/settings\/runners$/); + await page.getByTestId("runner-select-" + ids.get("scratch")).click(); + await expect + .poll(() => new URL(page.url()).searchParams.get("runner")) + .toBe(ids.get("scratch")); + await page.reload({ waitUntil: "domcontentloaded" }); + let account = page.getByTestId("runner-detail").getByTestId("runner-github"); await account.getByRole("button", { name: "Sign in to GitHub" }).click(); await expect(account.getByText("B123-C456", { exact: true })).toBeVisible(); await expect( diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 86869ca3a..25d07b511 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -190,10 +190,14 @@ export async function requestConnection( expect(output).toContain( `Approve at: ${new URL("/settings/runners", page.url()).href}` ); - const form = page.getByTestId("runner-approval").filter({ - has: page.getByText(`Connection request · ${reference}`, { exact: true }), - }); - await expect(form).toHaveCount(1, { timeout: 15_000 }); + const label = `Review request ${reference}`; + const review = page.getByRole("button", { name: label, exact: true }); + await expect(review).toBeVisible({ timeout: 15_000 }); + await review.click(); + const form = page + .getByRole("dialog", { name: label, exact: true }) + .getByTestId("runner-approval"); + await expect(form).toBeVisible(); return { form, code, finished }; } @@ -254,6 +258,7 @@ export async function enrollViaUi( export async function revokeViaUi(page: Page, id: string) { await page.goto("/settings/runners", { waitUntil: "domcontentloaded" }); await page.getByTestId(`runner-select-${id}`).click(); + await page.getByTestId(`runner-actions-${id}`).click(); await page.getByTestId(`runner-revoke-${id}`).click(); await page.getByTestId(`runner-revoke-confirm-${id}`).click(); await page.getByText(/^Revoked runners \(/).click(); From c629ec05acee1b08f82ef2b68fb997b1127bdb3b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Wed, 18 Nov 2026 23:46:19 -0700 Subject: [PATCH 114/642] Review pending runner pairings in a dialog --- .../src/components/app/runner-onboarding.tsx | 181 +++++++++++------- .../components/app/runner-settings.test.tsx | 19 +- 2 files changed, 121 insertions(+), 79 deletions(-) diff --git a/apps/web/src/components/app/runner-onboarding.tsx b/apps/web/src/components/app/runner-onboarding.tsx index 4d9382913..d3d168996 100644 --- a/apps/web/src/components/app/runner-onboarding.tsx +++ b/apps/web/src/components/app/runner-onboarding.tsx @@ -1,6 +1,6 @@ import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { Copy, Plus } from "lucide-react"; +import { Copy, Plus, X } from "lucide-react"; import { useCopyText } from "@/hooks/use-copy"; import { Button } from "@/components/ui/button"; import { @@ -49,7 +49,8 @@ export function RunnerCommand({ type PairRequest = { id: string; createdAt: string; expiresAt: string }; -function ApproveRunner({ request }: { request: PairRequest }) { +function RunnerPairingRequest({ request }: { request: PairRequest }) { + const reference = request.id.slice(-8); const queryClient = useQueryClient(); const [name, setName] = useState(""); const [code, setCode] = useState(""); @@ -83,75 +84,109 @@ function ApproveRunner({ request }: { request: PairRequest }) { queryClient.invalidateQueries({ queryKey: ["runner-pairing-requests"] }), }); return ( -

{ - e.preventDefault(); - if ( - name.trim() && - code.trim() && - !approve.isPending && - !dismiss.isPending - ) - approve.mutate(); - }} - data-testid="runner-approval" +
  • -

    Request {request.id.slice(-8)}

    -

    - Enter the pairing code printed on the runner. -

    -
    - - -
    -
    - - -
    - {(approve.error || dismiss.error) && ( -

    - {(approve.error ?? dismiss.error)?.message} -

    - )} -
  • + Request {reference} + + + + + + + Review request {reference} + + Enter the pairing code printed on the runner. + + + + + +
    { + e.preventDefault(); + if ( + name.trim() && + code.trim() && + !approve.isPending && + !dismiss.isPending + ) { + approve.mutate(); + } + }} + data-testid="runner-approval" + > +
    + + +
    +
    + + +
    + {(approve.error || dismiss.error) && ( +

    + {(approve.error ?? dismiss.error)?.message} +

    + )} +
    +
    +
    + ); } @@ -200,11 +235,11 @@ export function RunnerPairingRequests() {

    Pending approvals

    -
    +
      {requests.map((request) => ( - + ))} -
    +
    ); } diff --git a/apps/web/src/components/app/runner-settings.test.tsx b/apps/web/src/components/app/runner-settings.test.tsx index 57db52dcf..ccc0717a9 100644 --- a/apps/web/src/components/app/runner-settings.test.tsx +++ b/apps/web/src/components/app/runner-settings.test.tsx @@ -151,12 +151,10 @@ it("leaves pairing approvals actionable after closing the Add runner dialog", as }); renderSettings(); - const approval = await screen.findByTestId("runner-approval"); - const submit = within(approval).getByRole("button", { - name: "Approve runner", - }) as HTMLButtonElement; - expect(submit.disabled).toBe(true); - expect(screen.queryByRole("dialog")).toBeNull(); + const review = await screen.findByRole("button", { + name: "Review request deadbeef", + }); + expect(screen.queryByTestId("runner-approval")).toBeNull(); fireEvent.click(screen.getByRole("button", { name: "Add runner" })); const dialog = screen.getByRole("dialog", { name: "Add runner" }); @@ -167,6 +165,15 @@ it("leaves pairing approvals actionable after closing the Add runner dialog", as fireEvent.click(within(dialog).getByRole("button", { name: "Done" })); expect(screen.queryByRole("dialog")).toBeNull(); + fireEvent.click(review); + const request = screen.getByRole("dialog", { + name: "Review request deadbeef", + }); + const approval = within(request).getByTestId("runner-approval"); + const submit = within(approval).getByRole("button", { + name: "Approve runner", + }) as HTMLButtonElement; + expect(submit.disabled).toBe(true); fireEvent.change(within(approval).getByLabelText("Runner name"), { target: { value: " Build machine " }, }); From 8d7c4f65f2c87fd2aad1746c0f3cce80d479d885 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 08:43:52 -0700 Subject: [PATCH 115/642] Launch runner children in the parent checkout --- apps/server/src/agents/checkout-inspection.ts | 26 +++++- apps/server/src/agents/manager.ts | 85 ++++++++++--------- apps/server/src/server/mcp-handlers.ts | 38 ++++++--- .../server/src/server/mcp-persona-handlers.ts | 60 +++++++++++-- apps/server/test/checkout-inspection.test.ts | 9 ++ apps/server/test/db/agent-manager.test.ts | 13 ++- docs/design/runner-capability-inventory.md | 2 +- e2e/remote-runner/owner-review.spec.ts | 37 +++++++- 8 files changed, 200 insertions(+), 70 deletions(-) diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index 659310766..82400a8d1 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -1,7 +1,13 @@ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { constants } from "node:fs"; -import { lstat, open, readlink, type FileHandle } from "node:fs/promises"; +import { + lstat, + open, + readlink, + realpath, + type FileHandle, +} from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { @@ -33,7 +39,12 @@ const execFileAsync = promisify(execFile); const run: CommandRunner = async (command, args, options = {}) => { const { stdout, stderr, exitCode } = await execFileAsync(command, args, { cwd: options.cwd, - env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1" }, + env: { + ...process.env, + LC_ALL: "C", + GIT_TERMINAL_PROMPT: "0", + GH_PROMPT_DISABLED: "1", + }, maxBuffer: MAX_REPLY_BYTES, timeout: options.timeoutMs ?? 5_000, killSignal: "SIGKILL", @@ -393,11 +404,18 @@ export async function inspectCheckout( ): Promise { const validated = parseQuery(query); // Preserve whitespace in the root, removing only Git's terminating newline. - const { stdout } = await run("git", ["rev-parse", "--show-toplevel"], { + const probe = await run("git", ["rev-parse", "--show-toplevel"], { cwd, trimOutput: false, + allowedExitCodes: validated.kind === "readFile" ? [0, 128] : [0], }); - const root = stdout.replace(/\n$/, ""); + if (probe.exitCode && !probe.stderr.startsWith("fatal: not a git repository")) + throw new Error( + `Could not resolve checkout root: ${probe.stderr.slice(0, MAX_ERROR_BYTES)}` + ); + const root = probe.exitCode + ? await realpath(cwd) + : probe.stdout.replace(/\n$/, ""); if (!path.isAbsolute(root)) throw new Error("Could not resolve checkout root"); const reply: CheckoutReply = diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index b79c8526c..407b9c9a3 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1391,8 +1391,9 @@ export class AgentManager { input: CreateAgentInput, options: { detachLaunch?: boolean; - /** Trusted owner review launch, never accepted from an HTTP launch payload. */ + /** Trusted shared-checkout launch, never accepted from an HTTP launch payload. */ useWorktreeOf?: string; + taskPersonaBody?: string; /** Commit owner state before the engine can discover tools or run a turn. */ beforeLaunch?: (agentId: string) => Promise; } = {} @@ -1403,23 +1404,32 @@ export class AgentManager { const owner = await this.getAgent(useWorktreeOf); if ( !owner || - input.role !== "review" || input.launchedByAgentId !== owner.id || !input.parentAgentId || - !input.persona || input.repository || input.useWorktree || (input.cwd !== owner.cwd && input.cwd !== reviewerWorkspace(owner)) || (input.projectId !== undefined && input.projectId !== owner.projectId) ) - throw new AgentError("Invalid reviewer checkout binding.", 400); - const reviewerParent = + throw new AgentError("Invalid shared checkout binding.", 400); + if (input.role === "review") { + if (!input.persona) + throw new AgentError("Missing reviewer persona.", 400); + } else if ( + input.parentAgentId !== owner.id || + !remotePlacement(owner.cwd) || + (input.fullAccess && !owner.fullAccess) || + (input.persona && !options.taskPersonaBody) + ) { + throw new AgentError("Invalid child checkout binding.", 400); + } + const displayParent = input.parentAgentId === owner.id ? owner : await this.getAgent(input.parentAgentId); - if (!reviewerParent || reviewerParent.projectId !== owner.projectId) + if (!displayParent || displayParent.projectId !== owner.projectId) throw new AgentError( - "Review parent must belong to the requester's project.", + "Display parent must belong to the requester's project.", 400 ); input.cwd = reviewerWorkspace(owner); @@ -1469,7 +1479,7 @@ export class AgentManager { } if (useWorktreeOf && !this.remote.supportsSharedWorktree(placement)) throw new AgentError( - "Update the runner to launch a reviewer in an existing checkout.", + "Update the runner to launch an agent in an existing checkout.", 409 ); input.useWorktree = false; @@ -1544,20 +1554,21 @@ export class AgentManager { if (matches.length === 1) input.projectId = matches[0]!.id; } const taskPersona = Boolean(input.persona && input.role !== "review"); + const taskPersonaBody = async () => + options.taskPersonaBody ?? + ( + await resolveLaunchPersona( + input.cwd, + input.persona!, + "task", + input.personaSource ?? "catalog" + ) + ).body; if (taskPersona && !options.detachLaunch) { - const persona = await resolveLaunchPersona( - input.cwd, - input.persona!, - "task", - input.personaSource ?? "catalog" - ); + const body = await taskPersonaBody(); input = { ...input, - agentArgs: [ - ...(input.agentArgs ?? []), - PERSONA_CONTEXT_ARG, - persona.body, - ], + agentArgs: [...(input.agentArgs ?? []), PERSONA_CONTEXT_ARG, body], }; } const runnerRepository = repository?.url @@ -1651,21 +1662,12 @@ export class AgentManager { preparePersona: taskPersona && options.detachLaunch ? async () => { - const persona = await resolveLaunchPersona( - input.cwd, - input.persona!, - "task", - input.personaSource ?? "catalog" - ); + const body = await taskPersonaBody(); const result = await this.pool.query( "UPDATE agents SET agent_args = $2::jsonb, updated_at = NOW() WHERE id = $1 AND status = 'creating' RETURNING id", [ p.id, - JSON.stringify([ - ...p.agentArgs, - PERSONA_CONTEXT_ARG, - persona.body, - ]), + JSON.stringify([...p.agentArgs, PERSONA_CONTEXT_ARG, body]), ] ); if (!result.rowCount) @@ -2257,18 +2259,17 @@ export class AgentManager { "The runner workspace mode changed since this agent was created.", 409 ); - const binding = - placement && (agent.runnerManaged || agent.role === "review") - ? ( - await this.pool.query<{ - runner_repository: RunnerRepository | null; - runner_worktree_owner: string | null; - }>( - "SELECT runner_repository, runner_worktree_owner FROM agents WHERE id = $1", - [agent.id] - ) - ).rows[0] - : undefined; + const binding = placement + ? ( + await this.pool.query<{ + runner_repository: RunnerRepository | null; + runner_worktree_owner: string | null; + }>( + "SELECT runner_repository, runner_worktree_owner FROM agents WHERE id = $1", + [agent.id] + ) + ).rows[0] + : undefined; return this.runtime.launch({ agentId: agent.id, repository: binding?.runner_repository ?? undefined, diff --git a/apps/server/src/server/mcp-handlers.ts b/apps/server/src/server/mcp-handlers.ts index 8e752f6e9..8a4dd42c9 100644 --- a/apps/server/src/server/mcp-handlers.ts +++ b/apps/server/src/server/mcp-handlers.ts @@ -56,7 +56,11 @@ import type { SendAgentPrompt, } from "./mcp-handler-types.js"; import { resolveLaunchPersona } from "../personas/resolve.js"; -import { createPersonaHandlers } from "./mcp-persona-handlers.js"; +import { remotePlacement } from "@dispatch/runner-protocol"; +import { + createPersonaHandlers, + resolveRunnerPersona, +} from "./mcp-persona-handlers.js"; import { activatePersonality, createPersonality, @@ -357,14 +361,18 @@ async function handleLaunchAgent( if (input.templateId && !template) { throw new Error(`Template ${input.templateId} not found.`); } + const parentCwd = agentWorkspaceDir(parent) ?? parent.cwd; + const cwd = input.cwd ?? template?.directory ?? parentCwd; + const runnerParent = remotePlacement(parent.cwd); + if (runnerParent && cwd !== parent.cwd) + throw new AgentError( + "A runner agent must launch in its own runner workspace.", + 400 + ); const selectedPersona = input.persona - ? await resolveLaunchPersona( - input.cwd ?? - template?.directory ?? - agentWorkspaceDir(parent) ?? - parent.cwd, - input.persona - ) + ? runnerParent + ? await resolveRunnerPersona(deps.agentManager, parent, input.persona) + : await resolveLaunchPersona(cwd, input.persona) : null; if (selectedPersona && (selectedPersona.type ?? "review") === "review") { if (template) @@ -449,7 +457,6 @@ async function handleLaunchAgent( // explicitly at the call site still wins. const fromTemplate = templateWorktreeConfig(template); - const parentCwd = agentWorkspaceDir(parent) ?? parent.cwd; const useWorktree = input.useWorktree ?? fromTemplate.useWorktree; // Templates have no createNewBranch column, so the decision keys off where // the worktree came from: a template-supplied one follows the template's @@ -508,10 +515,10 @@ async function handleLaunchAgent( throw new Error("Project template directory cannot be overridden."); } - const agent = await deps.agentManager.createAgent({ + const launch: Parameters[0] = { name: input.name, type: agentType as (typeof CLI_AGENT_TYPES)[number], - cwd: input.cwd ?? template?.directory ?? parentCwd, + cwd, fullAccess, model, effort, @@ -529,7 +536,14 @@ async function handleLaunchAgent( templateId: input.templateId, persona: input.persona ?? template?.persona ?? undefined, personaSource: "workspace", - }); + }; + const agent = + child && runnerParent + ? await deps.agentManager.createAgent(launch, { + useWorktreeOf: parent.id, + taskPersonaBody: selectedPersona?.body, + }) + : await deps.agentManager.createAgent(launch); deps.publishUiEvent({ type: "agent.upsert", diff --git a/apps/server/src/server/mcp-persona-handlers.ts b/apps/server/src/server/mcp-persona-handlers.ts index 54aecc1be..1019cbe2b 100644 --- a/apps/server/src/server/mcp-persona-handlers.ts +++ b/apps/server/src/server/mcp-persona-handlers.ts @@ -42,6 +42,38 @@ export type CreatePersonaHandlersDeps = { withStreamFlag: (agent: AgentRecord) => AgentRecord & { hasStream: boolean }; }; +async function readAgentCheckoutFile( + manager: AgentManager, + agent: AgentRecord, + path: string +) { + const reply = await manager.inspectCheckout(agent, { + kind: "readFile", + path, + }); + if (reply.kind !== "readFile") + throw new Error("Runner did not return the checkout file."); + return reply.content; +} + +export async function resolveRunnerPersona( + manager: AgentManager, + agent: AgentRecord, + slug: string +) { + const persona = + (await loadPersonaFromCheckout(slug, (path) => + readAgentCheckoutFile(manager, agent, path) + )) ?? getBuiltInPersona(slug); + if (!persona) + throw new Error( + `Persona "${slug}" not found in this checkout or built-ins.` + ); + if (!persona.body.trim()) + throw new Error(`Persona "${slug}" has no instructions.`); + return persona; +} + export type PersonaLaunchOptions = { persona: string; /** The briefing the launcher wrote: what was built, what to look at. */ @@ -163,6 +195,23 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { ) { const parent = await agentManager.getAgent(parentId); if (!parent) throw new Error("Parent agent not found."); + if (remotePlacement(parent.cwd)) { + return launchReviewer( + parent, + opts, + () => + prepareReviewLaunch( + parent, + opts, + parent.cwd, + false, + () => + opts.resolvedPersona ?? + resolveRunnerPersona(agentManager, parent, opts.persona) + ), + parent.id + ); + } return launchReviewer(parent, opts, () => preparePersonaLaunch(parent, opts) ); @@ -246,15 +295,8 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { if (!parent) throw new Error("Parent agent not found."); const changes = await inspectReviewChanges(parent); const reviewedState = { head: changes.head, stateId: changes.stateId }; - const readCheckoutFile = async (path: string) => { - const reply = await agentManager.inspectCheckout(parent, { - kind: "readFile", - path, - }); - if (reply.kind !== "readFile") - throw new Error("Runner did not return the checkout file."); - return reply.content; - }; + const readCheckoutFile = (path: string) => + readAgentCheckoutFile(agentManager, parent, path); let ownersPath = OWNERS_PATH; let content = await readCheckoutFile(ownersPath); if (content === null) { diff --git a/apps/server/test/checkout-inspection.test.ts b/apps/server/test/checkout-inspection.test.ts index 675f00782..1aa63eca7 100644 --- a/apps/server/test/checkout-inspection.test.ts +++ b/apps/server/test/checkout-inspection.test.ts @@ -329,6 +329,15 @@ exec "$CHECKOUT_TEST_GIT" "$@" ).rejects.toThrow(/origin\/main/); }); + it("reads a scratch-session persona without requiring a repository", async () => { + const path = ".agents/personas/scratch.md"; + put(fixture, path, "Scratch reviewer"); + expect(await inspect(fixture, { kind: "readFile", path })).toEqual({ + kind: "readFile", + content: "Scratch reviewer", + }); + }); + it("fails with a Git diagnostic outside a worktree", async () => { await expect( inspect(fixture, { kind: "changes", baseBranch: "main" }) diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index 0f49214fb..a67f26f4f 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -353,7 +353,18 @@ describe("AgentManager", () => { { ...launch, cwd: "runner://unrelated/@session" }, { useWorktreeOf: parent.id } ) - ).rejects.toThrow("Invalid reviewer"); + ).rejects.toThrow("Invalid shared checkout binding"); + await expect( + first.createAgent( + { + cwd, + parentAgentId: parent.id, + launchedByAgentId: parent.id, + fullAccess: true, + }, + { useWorktreeOf: parent.id } + ) + ).rejects.toThrow("Invalid child checkout binding"); supportsSharedWorktree.mockReturnValueOnce(false); await expect( first.createAgent(launch, { useWorktreeOf: parent.id }) diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 6e50191f6..dfd1bbbad 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -22,7 +22,7 @@ The outer protocol already covers launch, attach, liveness, stop, discard, log t - Check a new branch, a direct existing branch, a busy branch, a missing package manager and a retry after partial setup. In the field test a valid checkout still lacked dependencies and the guest install exited 137. [Workspace preparation](../../apps/server/src/agents/workspace-prep.ts) · [File seeding](../../apps/server/src/agents/file-seed.ts) · [Runner Git](../../apps/server/src/agents/remote/repository.ts) -**Track the effective checkout.** **Present for owner reviews.** A reviewer can borrow the author’s effective checkout by opaque agent ID on This Mac or on a capable Linux runner. Each reviewer has its own session. A managed runner retains the checkout until its owner and borrowers have released it. General child launches and workspace moves still need parity coverage. +**Track the effective checkout.** **Present for shared child launches.** An ordinary child or reviewer can borrow the author’s effective checkout by opaque agent ID on This Mac or on a capable Linux runner. Each child has its own session. A managed runner retains the checkout until its owner and borrowers have released it. Independent worktrees and workspace moves still need parity coverage. - Launch a child in the author’s current checkout and another in a separate checkout. Reviewers keep separate sessions and see the author’s uncommitted files. A cross-runner reference is rejected. [Workspace selection](../../apps/server/src/agents/workspace-target.ts) · [Child launch options](../../apps/server/src/shared/mcp/agent-launch-tools.ts) · [Runner supervisor](../../apps/server/src/agents/remote/session-supervisor.ts) diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts index 5ff157303..9d9289523 100644 --- a/e2e/remote-runner/owner-review.spec.ts +++ b/e2e/remote-runner/owner-review.spec.ts @@ -20,7 +20,15 @@ function seed(directory: string, marker: string) { git("init", "-b", "main"); git("config", "user.name", "Runner review fixture"); git("config", "user.email", "fixture@localhost"); - mkdirSync(path.join(directory, ".agents")); + mkdirSync(path.join(directory, ".agents/personas"), { recursive: true }); + writeFileSync( + path.join(directory, ".agents/personas/fixture-review.md"), + "Review the working checkout." + ); + writeFileSync( + path.join(directory, ".agents/personas/fixture-task.md"), + "---\ntype: task\n---\nWork in the shared checkout." + ); writeFileSync( path.join(directory, ".agents/owners.json"), JSON.stringify({ @@ -134,6 +142,33 @@ for (const placement of ["This Mac", "Linux runner"] as const) { "proof-reviewed-checkout", "Checkout marker " + marker ); + for (const persona of [undefined, "fixture-review", "fixture-task"]) { + const reply = await callMcpToolViaAPI(request, author, "launch_agent", { + prompt: "proof-reviewed-checkout", + name: persona ?? "Ordinary child", + ...(persona ? { persona } : {}), + type: "claude", + }); + const { agentId } = ( + reply.result as { structuredContent: { agentId: string } } + ).structuredContent; + agents.push(agentId); + await page.goto("/agents/" + agentId, { + waitUntil: "domcontentloaded", + }); + // Review personas receive a separate kickoff. Ask explicitly in both sessions. + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45000 }); + await newSettledTurn( + page, + "proof-reviewed-checkout", + "Checkout marker " + marker + ); + await page.screenshot({ + path: testInfo.outputPath((persona ?? "ordinary-child") + ".png"), + }); + await deleteAgentViaAPI(request, agentId); + agents.pop(); + } } finally { for (const id of agents.reverse()) await deleteAgentViaAPI(request, id); rmSync(tmp, { recursive: true, force: true }); From 092f8747d7457b987d9fa37b80b788ce0d69beb4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 09:29:28 -0700 Subject: [PATCH 116/642] Run native agent hosts through the runner lifecycle contract --- apps/server/src/agents/acp/engine-spec.ts | 2 +- apps/server/src/agents/acp/host-client.ts | 45 +- apps/server/src/agents/acp/host-command.ts | 108 +++++ apps/server/src/agents/acp/runtime.ts | 452 +++--------------- apps/server/src/agents/engine-login.ts | 2 +- apps/server/src/agents/local-runner.ts | 265 ++++++++++ apps/server/src/agents/remote/runner.ts | 2 +- .../test/acp-background-host-client.test.ts | 5 +- apps/server/test/acp-host.test.ts | 85 ++++ .../test/mcp-inventory-host-client.test.ts | 5 +- docs/design/runner-capability-inventory.md | 6 + packages/runner-protocol/src/execution.ts | 10 +- 12 files changed, 569 insertions(+), 418 deletions(-) create mode 100644 apps/server/src/agents/acp/host-command.ts create mode 100644 apps/server/src/agents/local-runner.ts diff --git a/apps/server/src/agents/acp/engine-spec.ts b/apps/server/src/agents/acp/engine-spec.ts index 5516f79c8..94ff220ef 100644 --- a/apps/server/src/agents/acp/engine-spec.ts +++ b/apps/server/src/agents/acp/engine-spec.ts @@ -2,7 +2,7 @@ import path from "node:path"; import type { AgentType } from "@dispatch/shared"; -import { selfCommand } from "./runtime.js"; +import { selfCommand } from "./host-command.js"; /** The engines the ACP runtime can drive. `agents.type` names one of these. */ export const ACP_ENGINE_IDS = ["claude", "codex", "opencode"] as const; diff --git a/apps/server/src/agents/acp/host-client.ts b/apps/server/src/agents/acp/host-client.ts index d410cb42b..b327ef084 100644 --- a/apps/server/src/agents/acp/host-client.ts +++ b/apps/server/src/agents/acp/host-client.ts @@ -5,7 +5,7 @@ import type { AgentPermissionsResponse, } from "@dispatch/shared"; import type { PromptImage, PromptSource } from "./prompt-source.js"; -import net from "node:net"; + import type { Duplex } from "node:stream"; import type { SessionConfigOption } from "@agentclientprotocol/sdk"; @@ -19,7 +19,6 @@ import { ndjsonDecoder, } from "./host-protocol.js"; -const CONNECT_TIMEOUT_MS = 5_000; const RECONNECT_BASE_MS = 500; const RECONNECT_MAX_MS = 10_000; @@ -27,8 +26,8 @@ export type HostWelcome = Extract; export type HostClientDeps = { agentId: string; - socketPath: string; - openSocket?: () => Promise; + remote: boolean; + openSocket: () => Promise; reconnectError?: (error: unknown) => "retry" | "gone" | undefined; onReady?: () => void; logger: DriverLogger; @@ -180,36 +179,18 @@ export class HostClient { } private async dial(): Promise { - if (this.deps.openSocket) { - const socket = await this.deps.openSocket(); - if (this.closed) { - socket.destroy(); - throw new Error("the agent host client was closed"); - } - this.connected(socket); - return; + const socket = await this.deps.openSocket(); + if (this.closed) { + socket.destroy(); + throw new Error("the agent host client was closed"); } - return new Promise((resolve, reject) => { - const socket = net.createConnection(this.deps.socketPath); - const timer = setTimeout(() => { - socket.destroy(new Error("connect timed out")); - }, CONNECT_TIMEOUT_MS); - socket.once("connect", () => { - clearTimeout(timer); - this.connected(socket); - resolve(); - }); - socket.once("error", (err) => { - clearTimeout(timer); - if (this.socket !== socket) reject(err); - }); - }); + this.connected(socket); } private connected(socket: Duplex): void { this.attempts = 0; this.lastWelcome = null; - this.replayReady = !this.deps.openSocket; + this.replayReady = !this.deps.remote; this.socket = socket; this.wire(socket); this.sentFromSeq = this.deps.fromSeq(); @@ -217,7 +198,7 @@ export class HostClient { type: "hello", fromSeq: this.sentFromSeq, journalId: this.deps.journalId(), - ...(this.deps.openSocket ? { replayComplete: true } : {}), + ...(this.deps.remote ? { replayComplete: true } : {}), }); } @@ -227,7 +208,7 @@ export class HostClient { for (const message of decode(chunk)) { if (socket.destroyed || this.socket !== socket) break; if ( - this.deps.openSocket && + this.deps.remote && ((message.type === "welcome" && (message.agentId !== this.deps.agentId || !message.journalId)) || (message.type === "event" && @@ -255,7 +236,7 @@ export class HostClient { this.socket = null; this.failPending( new Error( - this.deps.openSocket + this.deps.remote ? "Runner connection dropped before acknowledgement; execution is unknown." : "the agent host connection closed" ) @@ -550,7 +531,7 @@ export class HostClient { type: "prompt", id, text, - ...(this.deps.openSocket + ...(this.deps.remote ? { journalId: this.lastWelcome?.journalId } : {}), ...(source ? { source } : {}), diff --git a/apps/server/src/agents/acp/host-command.ts b/apps/server/src/agents/acp/host-command.ts new file mode 100644 index 000000000..14ec0447d --- /dev/null +++ b/apps/server/src/agents/acp/host-command.ts @@ -0,0 +1,108 @@ +import { existsSync } from "node:fs"; +import path from "node:path"; + +/** + * The command that runs the host: the same executable as the server. Under + * `bun src/main.ts` that is bun plus the script; a compiled binary is + * itself. `DISPATCH_AGENT_HOST_COMMAND` (JSON array or whitespace-separated) + * overrides both, for tests and e2e. + */ +export function hostCommand(env: NodeJS.ProcessEnv = process.env): string[] { + const override = env.DISPATCH_AGENT_HOST_COMMAND; + if (override) { + try { + const parsed = JSON.parse(override); + if (Array.isArray(parsed)) return parsed.map(String); + } catch { + // Not JSON: a plain command line. + } + return override.split(/\s+/).filter(Boolean); + } + return selfCommand("agent-host"); +} + +/** + * This executable plus one of its modes. Under `bun src/main.ts` that is bun + * plus the script; a compiled binary is itself. Both the agent host and the + * bundled ACP adapters are modes of this binary, so both are spawned this way. + */ +export function selfCommand(mode: string): string[] { + const script = process.argv[1]; + if (script && /\.[cm]?[jt]s$/.test(script) && existsSync(script)) { + return [process.execPath, script, mode]; + } + return [process.execPath, mode]; +} + +/** + * Wrap a command so it runs through the user's login shell: the host, and + * so the engine, gets the PATH, ssh agent and tool config the user's own + * shell has. + */ +export function loginShellCommand( + command: string[], + shell = process.env.SHELL || "/bin/bash" +): { bin: string; args: string[] } { + const base = path.basename(shell); + // ~/.dispatch/env is the documented place for agent-session overrides; + // it is read after the profile so it wins. + const posix = + '[ -f "$HOME/.dispatch/env" ] && . "$HOME/.dispatch/env"; exec "$@"'; + if (base === "fish") { + return { + bin: shell, + args: [ + "-lc", + 'test -f "$HOME/.dispatch/env"; and source "$HOME/.dispatch/env"; exec $argv', + ...command, + ], + }; + } + if (base === "bash" || base === "zsh" || base === "sh") { + return { + bin: shell, + args: ["-lc", posix, "dispatch-agent-host", ...command], + }; + } + return { + bin: "/bin/bash", + args: ["-lc", posix, "dispatch-agent-host", ...command], + }; +} + +/** What the host must not inherit from the server process. */ +const ENV_DENY_EXACT = new Set([ + "ANTHROPIC_API_KEY", + "OPENAI_API_KEY", + "CODEX_API_KEY", + "DATABASE_URL", + "TEST_DATABASE_URL", + "PGPASSWORD", + "PGUSER", + "PGHOST", + "PGPORT", + "PGDATABASE", + "DISPATCH_FILES_ROOT", + "TLS_CERT", + "TLS_KEY", + "TLS_CA", +]); + +/** The fake ACP adapter test seam must reach the detached host process. */ +const ENV_ALLOW_DISPATCH = new Set(["DISPATCH_ACP_ADAPTER_COMMAND"]); + +export function hostProcessEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(base)) { + if (value === undefined) continue; + if ( + ENV_DENY_EXACT.has(key) || + (key.startsWith("DISPATCH_") && + !ENV_ALLOW_DISPATCH.has(key) && + !/^DISPATCH_OWNED_[a-f0-9]{32}$/.test(key)) + ) + continue; + env[key] = value; + } + return env; +} diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 96605274a..5930d2cfd 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -1,21 +1,18 @@ -import { - ownedEnvironment, - killOwnedProcesses, -} from "../../shared/process/owned-processes.js"; -import { preparePersonaContext } from "./persona-context.js"; import { sameConversation, type PromptConversation } from "@dispatch/shared"; -import { spawn } from "node:child_process"; -import { existsSync, openSync } from "node:fs"; -import { - appendFile, - mkdir, - readdir, - readFile, - rm, - unlink, - writeFile, -} from "node:fs/promises"; +import { appendFile, mkdir, rm } from "node:fs/promises"; import path from "node:path"; +import { + createLocalRunner, + type LocalLaunchSettings, + type SessionResult, +} from "../local-runner.js"; +import type { SessionLifecycleOperation } from "@dispatch/runner-protocol"; +export { + selfCommand, + hostCommand, + loginShellCommand, + hostProcessEnv, +} from "./host-command.js"; import type { FastifyBaseLogger } from "fastify"; import type { @@ -49,19 +46,11 @@ import { import type { Placement } from "../remote/protocol.js"; import type { RemoteEventInbox } from "../remote/event-inbox.js"; import { HostClient } from "./host-client.js"; -import { - type HostLaunch, - hostFile, - type JournalEntry, -} from "./host-protocol.js"; +import { type JournalEntry } from "./host-protocol.js"; /** The engine's ACP handshake can take a while on a cold adapter. */ const LAUNCH_TIMEOUT_MS = 60_000; const ATTACH_TIMEOUT_MS = 5_000; -const STOP_GRACE_MS = 8_000; -const KILL_GRACE_MS = 2_000; -const LOG_TAIL_LINES = 20; - /** * Posts that queued up behind a turn go to the agent together, as one * prompt, rather than one turn apiece. A backlog longer than this carries @@ -71,143 +60,6 @@ const LOG_TAIL_LINES = 20; export const COMBINE_MAX_PROMPTS = 8; export const COMBINE_MAX_CHARS = 32_000; -/** - * The command that runs the host: the same executable as the server. Under - * `bun src/main.ts` that is bun plus the script; a compiled binary is - * itself. `DISPATCH_AGENT_HOST_COMMAND` (JSON array or whitespace-separated) - * overrides both, for tests and e2e. - */ -export function hostCommand(env: NodeJS.ProcessEnv = process.env): string[] { - const override = env.DISPATCH_AGENT_HOST_COMMAND; - if (override) { - try { - const parsed = JSON.parse(override); - if (Array.isArray(parsed)) return parsed.map(String); - } catch { - // Not JSON: a plain command line. - } - return override.split(/\s+/).filter(Boolean); - } - return selfCommand("agent-host"); -} - -/** - * This executable plus one of its modes. Under `bun src/main.ts` that is bun - * plus the script; a compiled binary is itself. Both the agent host and the - * bundled ACP adapters are modes of this binary, so both are spawned this way. - */ -export function selfCommand(mode: string): string[] { - const script = process.argv[1]; - if (script && /\.[cm]?[jt]s$/.test(script) && existsSync(script)) { - return [process.execPath, script, mode]; - } - return [process.execPath, mode]; -} - -/** - * Wrap a command so it runs through the user's login shell: the host, and - * so the engine, gets the PATH, ssh agent and tool config the user's own - * shell has. - */ -export function loginShellCommand( - command: string[], - shell = process.env.SHELL || "/bin/bash" -): { bin: string; args: string[] } { - const base = path.basename(shell); - // ~/.dispatch/env is the documented place for agent-session overrides; - // it is read after the profile so it wins. - const posix = - '[ -f "$HOME/.dispatch/env" ] && . "$HOME/.dispatch/env"; exec "$@"'; - if (base === "fish") { - return { - bin: shell, - args: [ - "-lc", - 'test -f "$HOME/.dispatch/env"; and source "$HOME/.dispatch/env"; exec $argv', - ...command, - ], - }; - } - if (base === "bash" || base === "zsh" || base === "sh") { - return { - bin: shell, - args: ["-lc", posix, "dispatch-agent-host", ...command], - }; - } - return { - bin: "/bin/bash", - args: ["-lc", posix, "dispatch-agent-host", ...command], - }; -} - -/** What the host must not inherit from the server process. */ -const ENV_DENY_EXACT = new Set([ - "ANTHROPIC_API_KEY", - "OPENAI_API_KEY", - "CODEX_API_KEY", - "DATABASE_URL", - "TEST_DATABASE_URL", - "PGPASSWORD", - "PGUSER", - "PGHOST", - "PGPORT", - "PGDATABASE", - "DISPATCH_FILES_ROOT", - "TLS_CERT", - "TLS_KEY", - "TLS_CA", -]); - -/** The fake ACP adapter test seam must reach the detached host process. */ -const ENV_ALLOW_DISPATCH = new Set(["DISPATCH_ACP_ADAPTER_COMMAND"]); - -export function hostProcessEnv(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - const env: NodeJS.ProcessEnv = {}; - for (const [key, value] of Object.entries(base)) { - if (value === undefined) continue; - if ( - ENV_DENY_EXACT.has(key) || - (key.startsWith("DISPATCH_") && - !ENV_ALLOW_DISPATCH.has(key) && - !/^DISPATCH_OWNED_[a-f0-9]{32}$/.test(key)) - ) - continue; - env[key] = value; - } - return env; -} - -async function readPid(stateDir: string): Promise { - try { - const text = await readFile(hostFile(stateDir, "pid"), "utf8"); - const pid = Number(text.trim()); - return Number.isInteger(pid) && pid > 0 ? pid : null; - } catch { - return null; - } -} - -function pidAlive(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -function signalGroup(pid: number, signal: NodeJS.Signals): void { - try { - process.kill(-pid, signal); - } catch { - try { - process.kill(pid, signal); - } catch { - // Already gone. - } - } -} - /** A prompt waiting for the turn ahead of it to settle. */ type Waiting = { /** Explicit Send now choice, scoped to the turn current when selected. */ @@ -415,6 +267,17 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const stateDir = (agentId: string) => path.join(config.agentStateRoot, agentId); + const local = createLocalRunner(config.agentStateRoot, logger); + function requestSession( + placement: Placement | null | undefined, + operation: SessionLifecycleOperation, + settings?: LocalLaunchSettings + ): Promise { + return placement + ? remoteService().requestSession(placement, operation) + : local.requestSession(operation, settings); + } + function finishDecision(w: Waiting, outcome: SteeringOutcome) { if (w.steering) w.steering.outcome = outcome; w.steering?.decision?.finish(outcome); @@ -823,18 +686,18 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }; entry.client = new HostClient({ agentId, - socketPath: hostFile(stateDir(agentId), "socket"), + remote: Boolean(placement), + openSocket: async () => { + if (placement) await entry.events; + const { channel } = await requestSession(placement, { + kind: "attach", + agentId, + }); + if (!channel) throw new Error("Runner returned no session channel"); + return channel; + }, ...(placement ? { - openSocket: async () => { - await entry.events; - return ( - await remoteService().requestSession(placement, { - kind: "attach", - agentId, - }) - ).channel!; - }, reconnectError: (error: unknown) => { if ( error instanceof RunnerRevoked || @@ -933,24 +796,11 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { async function readLogTail(agentId: string): Promise { const placement = await placementOf(agentId); - if (placement) { - const response = await remoteService() - .requestSession(placement, { - kind: "log", - agentId, - }) - .catch(() => null); - return String(response?.value ?? ""); - } - try { - const log = await readFile(hostFile(stateDir(agentId), "log"), "utf8"); - const tail = log.trim().split("\n").slice(-LOG_TAIL_LINES).join("\n"); - return tail - ? `\n\nHost log (last ${LOG_TAIL_LINES} lines):\n${tail}` - : ""; - } catch { - return ""; - } + const response = await requestSession(placement, { + kind: "log", + agentId, + }).catch(() => null); + return String(response?.value ?? ""); } function enqueuePrompt( @@ -1169,105 +1019,23 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }, async launch(input) { - const placement = input.placement; - if (placement) { - const { - cwd, - bins, - env, - pathPrefix, - placement: _placement, - ...launch - } = input; - await remoteService().requestSession(placement, { - kind: "launch", - agentId: input.agentId, - launch, - }); - const entry = await connect(input.agentId, LAUNCH_TIMEOUT_MS); - const welcome = entry.client.welcome!; - return { sessionId: welcome.sessionId, resumed: welcome.resumed }; - } - const dir = stateDir(input.agentId); - await mkdir(dir, { recursive: true, mode: 0o700 }); - const launch: HostLaunch = { - agentId: input.agentId, - cwd: input.cwd, - engine: input.engine, - bins: input.bins, - model: input.model, - effort: input.effort ?? null, - fullAccess: input.fullAccess ?? true, - systemPrompt: input.systemPrompt, - personaContext: await preparePersonaContext(dir, input.personaContext), - mcp: input.mcp, - env: input.env, - pathPrefix: input.pathPrefix, - resumeSessionId: input.resumeSessionId, - }; - await writeFile( - hostFile(dir, "launch"), - JSON.stringify(launch, null, 2), - { - mode: 0o600, - } - ); - // A stale socket from a dead host would make connect() spin on - // ECONNREFUSED until the new host replaces it; clear it first. - await unlink(hostFile(dir, "socket")).catch(() => {}); - const logFd = openSync(hostFile(dir, "log"), "a"); - const { bin, args } = loginShellCommand([ - ...hostCommand(), - "--state", - dir, - ]); - const owned = ownedEnvironment(hostProcessEnv(process.env)); - await writeFile(path.join(dir, "ownership"), owned.marker, { - mode: 0o600, - }); - const child = spawn(bin, args, { - cwd: input.cwd, - env: owned.env, - detached: true, - stdio: ["ignore", logFd, logFd], - }); - // The shell execs the host, so this is the host's own exit; a host - // that dies during startup fails the launch at once instead of after - // the whole connect timeout. - let exited = false; - child.on("exit", () => { - exited = true; - try { - killOwnedProcesses(owned.marker); - } catch (err) { - logger.warn( - { err, agentId: input.agentId }, - "host descendant cleanup failed" - ); - } - }); - child.on("error", (err) => { - exited = true; - logger.error( - { err, agentId: input.agentId }, - "agent host spawn failed" - ); - }); - child.unref(); - logger.info( - { agentId: input.agentId, pid: child.pid, bin, args: args.slice(0, 3) }, - "agent host spawned" + const { placement, cwd, bins, env, pathPrefix, ...launch } = input; + const { launchExited } = await requestSession( + placement, + { kind: "launch", agentId: input.agentId, launch }, + { cwd, bins, env, pathPrefix } ); try { const entry = await connect( input.agentId, LAUNCH_TIMEOUT_MS, - () => exited + launchExited ); const welcome = entry.client.welcome; if (!welcome) throw new Error("no welcome from the agent host"); return { sessionId: welcome.sessionId, resumed: welcome.resumed }; } catch (err) { + if (placement) throw err; // A disconnected remote host may still be running. const message = err instanceof Error ? err.message : String(err); const tail = await readLogTail(input.agentId); // A host whose engine never came up has nothing to serve. @@ -1288,22 +1056,8 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const current = live.get(agentId); if (current) return !current.remote || current.client.isReady(); const placement = await placementOf(agentId); - if (placement) { - if ( - !deps.remote?.available(placement) || - !(await runtime.isAlive(agentId)) - ) - return false; - try { - await connect(agentId, ATTACH_TIMEOUT_MS); - return true; - } catch { - return false; - } - } - const dir = stateDir(agentId); - const pid = await readPid(dir); - if (!pid || !pidAlive(pid)) return false; + if (placement && !deps.remote?.available(placement)) return false; + if (!(await runtime.isAlive(agentId))) return false; try { await connect(agentId, ATTACH_TIMEOUT_MS); return true; @@ -1317,21 +1071,17 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const entry = live.get(agentId); if (entry?.client.isConnected()) return true; const placement = await placementOf(agentId); - if (placement) { - try { - const { value } = await remoteService().requestSession(placement, { - kind: "alive", - agentId, - }); - return value === true; - } catch (error) { - if (error instanceof RunnerRevoked) return false; - if (error instanceof RunnerUnavailable) return true; // Disconnected is not host death. - throw error; - } + try { + const { value } = await requestSession(placement, { + kind: "alive", + agentId, + }); + return value === true; + } catch (error) { + if (error instanceof RunnerRevoked) return false; + if (error instanceof RunnerUnavailable) return true; + throw error; } - const pid = await readPid(stateDir(agentId)); - return pid !== null && pidAlive(pid); }, prompt(agentId, text, source, opts) { @@ -1518,78 +1268,26 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { async stop(agentId, force) { const placement = await placementOf(agentId); - if (placement) { - await remoteService().requestSession(placement, { - kind: "stop", - agentId, - force, - }); - const entry = live.get(agentId); - live.delete(agentId); - if (entry) { - failWaiting(entry, new Error("The agent stopped before delivery.")); - entry.client.close(); - } - return; - } - const dir = stateDir(agentId); + const operation = { kind: "stop", agentId, force } as const; + if (placement) await requestSession(placement, operation); const entry = live.get(agentId); - const pid = await readPid(dir); if (entry) { live.delete(agentId); failWaiting(entry, new Error("The agent stopped before delivery.")); - try { - entry.client.shutdown(force); - } catch { - // Not connected; fall through to the signal. - } - } - if (pid && pidAlive(pid)) { - const deadline = Date.now() + (force ? 0 : STOP_GRACE_MS); - while (Date.now() < deadline && pidAlive(pid)) { - await new Promise((resolve) => setTimeout(resolve, 200)); - } - if (pidAlive(pid)) { - signalGroup(pid, "SIGTERM"); - const killAt = Date.now() + KILL_GRACE_MS; - while (Date.now() < killAt && pidAlive(pid)) { - await new Promise((resolve) => setTimeout(resolve, 200)); + if (!placement) { + try { + entry.client.shutdown(force); + } catch { + // A disconnected local host can still be stopped by its supervisor. } - if (pidAlive(pid)) signalGroup(pid, "SIGKILL"); } } - const marker = await readFile(path.join(dir, "ownership"), "utf8").catch( - () => null - ); - if (marker) { - killOwnedProcesses(marker); - await unlink(path.join(dir, "ownership")).catch(() => {}); - } + if (!placement) await requestSession(null, operation); entry?.client.close(); - await unlink(hostFile(dir, "socket")).catch(() => {}); - await unlink(hostFile(dir, "pid")).catch(() => {}); - }, - - async listHosted() { - let ids: string[] = []; - try { - ids = await readdir(config.agentStateRoot); - } catch { - return []; - } - const hosted: string[] = []; - for (const id of ids) { - if (!id.startsWith("agt_")) continue; - const pid = await readPid(stateDir(id)); - if (pid && pidAlive(pid)) hosted.push(id); - } - return hosted; }, - async hostPid(agentId) { - const pid = await readPid(stateDir(agentId)); - return pid && pidAlive(pid) ? pid : null; - }, + listHosted: local.listHosted, + hostPid: local.hostPid, onEvent(listener) { listeners.add(listener); @@ -1602,18 +1300,16 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { async discard(agentId) { const placement = await placementOf(agentId); - if (placement) { - await remoteService().requestSession(placement, { - kind: "discard", - agentId, - }); - } + const operation = { kind: "discard", agentId } as const; + if (placement) await requestSession(placement, operation); const entry = live.get(agentId); if (entry) { live.delete(agentId); entry.client.close(); } - await rm(stateDir(agentId), { recursive: true, force: true }); + if (placement) + await rm(stateDir(agentId), { recursive: true, force: true }); + else await requestSession(null, operation); }, }; return runtime; diff --git a/apps/server/src/agents/engine-login.ts b/apps/server/src/agents/engine-login.ts index abda6a07f..54e61cba4 100644 --- a/apps/server/src/agents/engine-login.ts +++ b/apps/server/src/agents/engine-login.ts @@ -10,7 +10,7 @@ import type { EngineLoginEngine, } from "@dispatch/shared"; -import { hostProcessEnv, loginShellCommand } from "./acp/runtime.js"; +import { hostProcessEnv, loginShellCommand } from "./acp/host-command.js"; /** * Signing an engine CLI in from the browser. The CLI's own login runs here, diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts new file mode 100644 index 000000000..44de4c077 --- /dev/null +++ b/apps/server/src/agents/local-runner.ts @@ -0,0 +1,265 @@ +import { spawn } from "node:child_process"; +import { closeSync, openSync } from "node:fs"; +import { + mkdir, + readdir, + readFile, + rm, + unlink, + writeFile, +} from "node:fs/promises"; +import net from "node:net"; +import path from "node:path"; +import type { Duplex } from "node:stream"; +import type { FastifyBaseLogger } from "fastify"; +import type { SessionLifecycleOperation } from "@dispatch/runner-protocol"; +import { + killOwnedProcesses, + ownedEnvironment, +} from "../shared/process/owned-processes.js"; +import { + hostCommand, + hostProcessEnv, + loginShellCommand, +} from "./acp/host-command.js"; +import { preparePersonaContext } from "./acp/persona-context.js"; +import { hostFile, type HostLaunch } from "./acp/host-protocol.js"; + +export type LocalLaunchSettings = Pick< + HostLaunch, + "cwd" | "env" | "bins" | "pathPrefix" +>; +export type SessionResult = { + value?: string | boolean; + channel?: Duplex; + launchExited?: () => boolean; +}; + +const STOP_GRACE_MS = 8_000; +const KILL_GRACE_MS = 2_000; +const LOG_TAIL_LINES = 20; +const CONNECT_TIMEOUT_MS = 5_000; + +async function readPid(stateDir: string): Promise { + try { + const text = await readFile(hostFile(stateDir, "pid"), "utf8"); + const pid = Number(text.trim()); + return Number.isInteger(pid) && pid > 0 ? pid : null; + } catch { + return null; + } +} + +function pidAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +function signalGroup(pid: number, signal: NodeJS.Signals): void { + try { + process.kill(-pid, signal); + } catch { + try { + process.kill(pid, signal); + } catch { + // Already gone. + } + } +} + +/** In-process implementation of runner lifecycle operations for native agent hosts. + * Launch settings come from Dispatch's trusted local workspace preparation. State + * paths and host sockets must stay compatible with hosts from earlier versions. + */ +export function createLocalRunner( + agentStateRoot: string, + logger: FastifyBaseLogger +) { + function stateDir(agentId: string) { + if ( + !agentId || + agentId === "." || + agentId === ".." || + path.basename(agentId) !== agentId + ) + throw new Error("Invalid agent state directory"); + return path.join(agentStateRoot, agentId); + } + async function launch(input: HostLaunch) { + const dir = stateDir(input.agentId); + await mkdir(dir, { recursive: true, mode: 0o700 }); + const launch: HostLaunch = { + agentId: input.agentId, + cwd: input.cwd, + engine: input.engine, + bins: input.bins, + model: input.model, + effort: input.effort ?? null, + fullAccess: input.fullAccess ?? true, + systemPrompt: input.systemPrompt, + personaContext: await preparePersonaContext(dir, input.personaContext), + mcp: input.mcp, + env: input.env, + pathPrefix: input.pathPrefix, + resumeSessionId: input.resumeSessionId, + }; + await writeFile(hostFile(dir, "launch"), JSON.stringify(launch, null, 2), { + mode: 0o600, + }); + // A stale socket from a dead host would make connect() spin on + // ECONNREFUSED until the new host replaces it; clear it first. + await unlink(hostFile(dir, "socket")).catch(() => {}); + + const { bin, args } = loginShellCommand([...hostCommand(), "--state", dir]); + const owned = ownedEnvironment(hostProcessEnv(process.env)); + await writeFile(path.join(dir, "ownership"), owned.marker, { + mode: 0o600, + }); + const logFd = openSync(hostFile(dir, "log"), "a"); + let child; + try { + child = spawn(bin, args, { + cwd: input.cwd, + env: owned.env, + detached: true, + stdio: ["ignore", logFd, logFd], + }); + } finally { + closeSync(logFd); + } + // The shell execs the host, so this is the host's own exit; a host + // that dies during startup fails the launch at once instead of after + // the whole connect timeout. + let exited = false; + child.on("exit", () => { + exited = true; + try { + killOwnedProcesses(owned.marker); + } catch (err) { + logger.warn( + { err, agentId: input.agentId }, + "host descendant cleanup failed" + ); + } + }); + child.on("error", (err) => { + exited = true; + logger.error({ err, agentId: input.agentId }, "agent host spawn failed"); + }); + child.unref(); + logger.info( + { agentId: input.agentId, pid: child.pid, bin, args: args.slice(0, 3) }, + "agent host spawned" + ); + return { launchExited: () => exited }; + } + async function stop(agentId: string, force: boolean) { + const dir = stateDir(agentId); + const pid = await readPid(dir); + if (pid && pidAlive(pid)) { + const deadline = Date.now() + (force ? 0 : STOP_GRACE_MS); + while (Date.now() < deadline && pidAlive(pid)) { + await new Promise((resolve) => setTimeout(resolve, 200)); + } + if (pidAlive(pid)) { + signalGroup(pid, "SIGTERM"); + const killAt = Date.now() + KILL_GRACE_MS; + while (Date.now() < killAt && pidAlive(pid)) { + await new Promise((resolve) => setTimeout(resolve, 200)); + } + if (pidAlive(pid)) signalGroup(pid, "SIGKILL"); + } + } + const marker = await readFile(path.join(dir, "ownership"), "utf8").catch( + () => null + ); + if (marker) { + killOwnedProcesses(marker); + await unlink(path.join(dir, "ownership")).catch(() => {}); + } + await unlink(hostFile(dir, "socket")).catch(() => {}); + await unlink(hostFile(dir, "pid")).catch(() => {}); + } + async function readLogTail(agentId: string) { + try { + const log = await readFile(hostFile(stateDir(agentId), "log"), "utf8"); + const tail = log.trim().split("\n").slice(-LOG_TAIL_LINES).join("\n"); + return tail + ? `\n\nHost log (last ${LOG_TAIL_LINES} lines):\n${tail}` + : ""; + } catch { + return ""; + } + } + + async function requestSession( + operation: SessionLifecycleOperation, + settings?: LocalLaunchSettings + ): Promise { + const { agentId } = operation; + const dir = stateDir(agentId); + switch (operation.kind) { + case "launch": + if (!settings || operation.launch.agentId !== agentId) + throw new Error("Missing or mismatched native launch settings"); + return launch({ ...operation.launch, ...settings }); + case "attach": { + const channel = await new Promise((resolve, reject) => { + const socket = net.createConnection(hostFile(dir, "socket")); + const timer = setTimeout( + () => socket.destroy(new Error("connect timed out")), + CONNECT_TIMEOUT_MS + ); + socket.once("connect", () => { + clearTimeout(timer); + resolve(socket); + }); + socket.once("error", (err) => { + clearTimeout(timer); + reject(err); + }); + }); + return { channel }; + } + case "alive": { + const pid = await readPid(dir); + return { value: pid !== null && pidAlive(pid) }; + } + case "stop": + await stop(agentId, operation.force); + return {}; + case "discard": + await rm(dir, { recursive: true, force: true }); + return {}; + case "log": + return { value: await readLogTail(agentId) }; + } + } + return { + requestSession, + async listHosted() { + let ids: string[] = []; + try { + ids = await readdir(agentStateRoot); + } catch { + return []; + } + const hosted: string[] = []; + for (const id of ids) { + if (!id.startsWith("agt_")) continue; + const pid = await readPid(stateDir(id)); + if (pid && pidAlive(pid)) hosted.push(id); + } + return hosted; + }, + + async hostPid(agentId: string) { + const pid = await readPid(stateDir(agentId)); + return pid && pidAlive(pid) ? pid : null; + }, + }; +} diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 5ec9af2c3..b6b24bc0c 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -10,7 +10,7 @@ import type { HostLaunch } from "../acp/host-protocol.js"; import type { WorkloadCommand } from "./session-storage.js"; import { createSessionSupervisor } from "./session-supervisor.js"; export { runnerStorageKey } from "./session-supervisor.js"; -import { hostCommand, selfCommand } from "../acp/runtime.js"; +import { hostCommand, selfCommand } from "../acp/host-command.js"; import { isOpaqueId, MANAGED_WORKSPACE, diff --git a/apps/server/test/acp-background-host-client.test.ts b/apps/server/test/acp-background-host-client.test.ts index f3d454594..528c64546 100644 --- a/apps/server/test/acp-background-host-client.test.ts +++ b/apps/server/test/acp-background-host-client.test.ts @@ -3,7 +3,10 @@ import { HostClient } from "../src/agents/acp/host-client.js"; function fixture(supported = true) { const client = new HostClient({ agentId: "a", - socketPath: "/tmp/unused", + remote: false, + openSocket: async () => { + throw new Error("unused"); + }, logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, fromSeq: () => 0, journalId: () => null, diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index 6eabcac2f..1a55c5e13 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -598,6 +598,91 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); expect(await replacement.runtime.listHosted()).toEqual([]); }, 60_000); + it("reattaches to an active native host after its controller exits", async () => { + const id = "agt_native_handoff"; + const folder = mkdtempSync(path.join(cwd, "session-")); + const input = launchFor(id, folder); + input.bins.adapter = { + bin: "bun", + args: [path.join(here, "helpers/remote-acp-fixture.ts")], + }; + const controller = path.join(stateRoot, "handoff.ts"); + // Exit only after the engine has begun the turn. Nothing in this process + // runs the host's stop path or can resolve a promise in the new controller. + writeFileSync( + controller, + ` + import {createAcpRuntime} from ${JSON.stringify(pathToFileURL(path.join(here, "../src/agents/acp/runtime.ts")).href)}; + const runtime = createAcpRuntime({ + config: { agentStateRoot: ${JSON.stringify(stateRoot)} }, + logger: {info(){}, warn(){}, debug(){}, error(){}}, + hostSeq:async()=>({seq:0,journalId:null}), syncJournal:async()=>{} + }); + const input = ${JSON.stringify(input)}; + const {sessionId}=await runtime.launch(input); + const pid=await runtime.hostPid(input.agentId); + runtime.onEvent((_, event, seq)=>{ + if(event.type==="update" && event.update.content?.text==="Guest turn waiting for reconnect.") { + console.log(JSON.stringify({sessionId,pid,seq})); + process.exit(0); + } + }); + await runtime.prompt(input.agentId,"proof-delay:2500 proof-count").settled; + throw new Error("Controller never received the in-flight checkpoint"); + ` + ); + const result = execFileSync("bun", [controller], { + timeout: 20_000, + encoding: "utf8", + }); + const checkpoint = JSON.parse(result.trim()); + expect(checkpoint.pid).toBeGreaterThan(0); + const journalId = readFileSync( + path.join(stateRoot, id, "journal.id"), + "utf8" + ).trim(); + const { runtime, seen } = runtimeWith( + stateRoot, + () => checkpoint.seq, + journalId + ); + try { + expect(await runtime.attach(id)).toBe(true); + expect(await runtime.hostPid(id)).toBe(checkpoint.pid); + await until(() => + seen.some( + ({ event }) => event.type === "turn" && event.state === "settled" + ) + ); + expect( + seen.filter( + ({ event }) => event.type === "turn" && event.state === "settled" + ) + ).toHaveLength(1); + expect(seen[0]?.seq).toBe(checkpoint.seq + 1); + expect( + readFileSync(path.join(folder, "provider-invocations"), "utf8") + ).toBe("called\n"); + writeFileSync(path.join(folder, "review-marker.txt"), "native-handoff"); + await runtime.prompt(id, "proof-reviewed-checkout").settled; + await until(() => + seen.some( + ({ event }) => + event.type === "update" && + event.update.sessionUpdate === "agent_message_chunk" && + event.update.content.type === "text" && + event.update.content.text.includes("Checkout marker native-handoff") + ) + ); + } finally { + await runtime.stop(id, true); + await runtime.discard(id); + } + expect(readFileSync(path.join(folder, "review-marker.txt"), "utf8")).toBe( + "native-handoff" + ); + }, 40_000); + it("replays a remote prompt receipt after a lost acknowledgement without invoking the provider again", async () => { const id = "agt_host_receipt"; const { runtime } = runtimeWith(stateRoot, () => 0); diff --git a/apps/server/test/mcp-inventory-host-client.test.ts b/apps/server/test/mcp-inventory-host-client.test.ts index c2ac7143b..5957d94d0 100644 --- a/apps/server/test/mcp-inventory-host-client.test.ts +++ b/apps/server/test/mcp-inventory-host-client.test.ts @@ -5,7 +5,10 @@ import type { HostMessage } from "../src/agents/acp/host-protocol.js"; function fixture(supported = true) { const client = new HostClient({ agentId: "a", - socketPath: "/tmp/unused", + remote: false, + openSocket: async () => { + throw new Error("unused"); + }, logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, fromSeq: () => 0, journalId: () => null, diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index dfd1bbbad..e3af7d1e9 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -40,6 +40,12 @@ The outer protocol already covers launch, attach, liveness, stop, discard, log t - A real Codex session lists and calls its tool over authenticated TLS on first launch. In the field test, provider login succeeded while the tool connection failed until the guest trusted the service CA. Also run a session with MCP omitted. [MCP routes](../../apps/server/src/routes/mcp.ts) · [Access ceiling](../../apps/server/src/shared/access-ceiling.ts) · [Host environment](../../apps/server/src/agents/acp/host-env.ts) +### Native runner and Dispatch updates + +Local and Linux sessions now start, attach, probe liveness, stop, read logs, and discard state through the same lifecycle operations. The local runner executes these in process and opens the existing Unix socket. Local workspace preparation still supplies the native working directory, engine paths, and environment. Native host discovery remains available to reconciliation and update recovery. [Local runner](../../apps/server/src/agents/local-runner.ts) · [Runtime](../../apps/server/src/agents/acp/runtime.ts) + +A native host can complete an accepted turn while its controller is down. A replacement controller can reattach to that host and read events after its saved journal position. The process-level test verifies one provider invocation, one completion, and continued use of the original folder. Before allowing an update with active work, exercise a released old host against a new controller and its rollback version, verify database migration and cursor compatibility, and fence new launches during the handoff. The existing maintenance policy still applies. [Restart test](../../apps/server/test/acp-host.test.ts) · [Update recovery](../../apps/server/src/server/update-recovery-runtime.ts) + ### Working with a checkout **Select and launch owner reviewers.** **Present.** Dispatch requests changed paths, HEAD, a checkout state identifier and bounded file reads from the author’s runner. Dispatch loads ownership rules, selects review personas, checks that the review state still matches, and launches a reviewer in the same checkout. Dispatch owns review threads and findings. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 2210cdf7b..f6aaf0ec7 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -47,13 +47,17 @@ export type RemoteLaunch = { useWorktreeOf?: string; }; -export type SessionOperation = { agentId: string } & ( +export type SessionLifecycleOperation = { agentId: string } & ( | { kind: "launch"; launch: RemoteLaunch } - | { kind: "inspectCheckout"; query: CheckoutQuery } - | { kind: "attach" | "alive" | "discard" | "log" | "repo" } + | { kind: "attach" | "alive" | "discard" | "log" } | { kind: "stop"; force: boolean } ); +export type SessionOperation = + | SessionLifecycleOperation + | { agentId: string; kind: "inspectCheckout"; query: CheckoutQuery } + | { agentId: string; kind: "repo" }; + export type RunnerOperation = | { kind: "engine"; operation: EngineOperation } | { kind: "github"; operation: GitHubOperation }; From 0aea7504dbc9e7412148c3224466d30854def695 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 09:31:57 -0700 Subject: [PATCH 117/642] Exercise shared owner reviews with a restricted-capable engine --- apps/server/test/mcp-persona-codeowners.test.ts | 4 ++-- docs/design/runner-capability-inventory.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/server/test/mcp-persona-codeowners.test.ts b/apps/server/test/mcp-persona-codeowners.test.ts index ffa8d7cf6..7919941f7 100644 --- a/apps/server/test/mcp-persona-codeowners.test.ts +++ b/apps/server/test/mcp-persona-codeowners.test.ts @@ -162,7 +162,7 @@ describe("code owner launches through the checkout boundary", () => { const result = await handlers.launchOwnerReviews(parent.id, { context, - agentType: "opencode", + agentType: "codex", }); expect(result).toEqual({ ...preview, @@ -184,7 +184,7 @@ describe("code owner launches through the checkout boundary", () => { expect(agentManager.createAgent).toHaveBeenCalledWith( expect.objectContaining({ cwd, - type: "opencode", + type: "codex", persona: "owner-one", projectId: "project", parentAgentId: "launcher", diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index e3af7d1e9..3d0ccf2d1 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -42,7 +42,7 @@ The outer protocol already covers launch, attach, liveness, stop, discard, log t ### Native runner and Dispatch updates -Local and Linux sessions now start, attach, probe liveness, stop, read logs, and discard state through the same lifecycle operations. The local runner executes these in process and opens the existing Unix socket. Local workspace preparation still supplies the native working directory, engine paths, and environment. Native host discovery remains available to reconciliation and update recovery. [Local runner](../../apps/server/src/agents/local-runner.ts) · [Runtime](../../apps/server/src/agents/acp/runtime.ts) +Local and Linux sessions now start, attach, probe liveness, stop, read logs, and discard state through the same lifecycle operations. The local runner executes these in process and opens the existing Unix socket. Local workspace preparation still supplies the native working directory, engine paths, and environment. Native host discovery remains available to reconciliation and update recovery. The lifecycle implementation includes the local changes through Dispatch 1.7.28 (main at `8f0bac1a`), including cross-conversation interruption and OpenCode V2 startup and resume. OpenCode V2 requires full access, so a restricted owner review needs an engine that supports restricted sessions. [Local runner](../../apps/server/src/agents/local-runner.ts) · [Runtime](../../apps/server/src/agents/acp/runtime.ts) A native host can complete an accepted turn while its controller is down. A replacement controller can reattach to that host and read events after its saved journal position. The process-level test verifies one provider invocation, one completion, and continued use of the original folder. Before allowing an update with active work, exercise a released old host against a new controller and its rollback version, verify database migration and cursor compatibility, and fence new launches during the handoff. The existing maintenance policy still applies. [Restart test](../../apps/server/test/acp-host.test.ts) · [Update recovery](../../apps/server/src/server/update-recovery-runtime.ts) From 72fe76545ee7b012d72b89110e133b678a865915 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 09:33:07 -0700 Subject: [PATCH 118/642] Record the released Mac host handoff and remaining update checks --- docs/design/runner-capability-inventory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 3d0ccf2d1..4fba7a2d4 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -44,7 +44,7 @@ The outer protocol already covers launch, attach, liveness, stop, discard, log t Local and Linux sessions now start, attach, probe liveness, stop, read logs, and discard state through the same lifecycle operations. The local runner executes these in process and opens the existing Unix socket. Local workspace preparation still supplies the native working directory, engine paths, and environment. Native host discovery remains available to reconciliation and update recovery. The lifecycle implementation includes the local changes through Dispatch 1.7.28 (main at `8f0bac1a`), including cross-conversation interruption and OpenCode V2 startup and resume. OpenCode V2 requires full access, so a restricted owner review needs an engine that supports restricted sessions. [Local runner](../../apps/server/src/agents/local-runner.ts) · [Runtime](../../apps/server/src/agents/acp/runtime.ts) -A native host can complete an accepted turn while its controller is down. A replacement controller can reattach to that host and read events after its saved journal position. The process-level test verifies one provider invocation, one completion, and continued use of the original folder. Before allowing an update with active work, exercise a released old host against a new controller and its rollback version, verify database migration and cursor compatibility, and fence new launches during the handoff. The existing maintenance policy still applies. [Restart test](../../apps/server/test/acp-host.test.ts) · [Update recovery](../../apps/server/src/server/update-recovery-runtime.ts) +A native host can complete an accepted turn while its controller is down. A replacement controller can reattach to that host and read events after its saved journal position. The process-level test verifies one provider invocation, one completion, and continued use of the original folder. A separate isolated macOS trial started a parent and child with the packaged 1.7.28 server, then started this branch against their database and host state during an accepted fixture turn. Both hosts retained their PIDs, the turn completed once, and the child could still read the original non-repository folder. Before allowing an update with active work, test the installer’s actual restart sequence and rollback, including database and cursor compatibility, and fence new launches during the handoff. The existing maintenance policy still applies. [Restart test](../../apps/server/test/acp-host.test.ts) · [Update recovery](../../apps/server/src/server/update-recovery-runtime.ts) ### Working with a checkout From ac037e343b329f5f42045fa0b2d52e4bf0a881b2 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 09:37:02 -0700 Subject: [PATCH 119/642] Keep native agent folder choices on the selected machine --- .../src/components/app/agents-view.test.tsx | 14 ++++++++++ apps/web/src/components/app/agents-view.tsx | 12 ++++++--- .../app/create-agent-dialog-utils.ts | 4 ++- .../components/app/create-agent-dialog.tsx | 1 + .../src/components/app/path-input-utils.ts | 7 +++++ apps/web/src/components/app/path-input.tsx | 27 ++++++++++++++----- .../app/use-create-agent-form.test.tsx | 11 ++++++++ .../components/app/use-create-agent-form.ts | 9 ++++--- 8 files changed, 69 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/app/agents-view.test.tsx b/apps/web/src/components/app/agents-view.test.tsx index 74cf64ea4..a526a6cf5 100644 --- a/apps/web/src/components/app/agents-view.test.tsx +++ b/apps/web/src/components/app/agents-view.test.tsx @@ -697,6 +697,20 @@ describe("AgentsView dialogs", () => { expect(resolve()).toBe("/repos/selected"); }); + it("skips remote selections and history when suggesting a local folder", () => { + const remote = makeAgent({ id: "r1", cwd: "runner://linux/@session" }); + window.localStorage.setItem("dispatch:lastUsedAgentCwd", remote.cwd); + Object.assign(H.state, { + agents: [remote, makeAgent({ id: "a1", cwd: "/repos/local" })], + validatedSelectedAgentId: "r1", + selectedAgent: remote, + }); + mount(); + expect( + (propsOf("AgentsViewDialogs").resolveCreateDefaultCwd as () => string)() + ).toBe("/repos/local"); + }); + it("falls back to the newest agent, then nothing", () => { Object.assign(H.state, { agents: [makeAgent({ id: "a3", cwd: "/repos/newest" })], diff --git a/apps/web/src/components/app/agents-view.tsx b/apps/web/src/components/app/agents-view.tsx index 5ba00c121..45a5da381 100644 --- a/apps/web/src/components/app/agents-view.tsx +++ b/apps/web/src/components/app/agents-view.tsx @@ -22,6 +22,7 @@ const FilesPane = lazy(() => ); import { Routes, Route, useParams, useSearchParams } from "react-router-dom"; +import { isLocalFolder } from "./path-input-utils"; import { type CenterTab } from "@/lib/store"; import { AgentPane, ChatFiltersButton } from "@/components/app/agent-pane"; @@ -367,13 +368,16 @@ export function AgentsView({ const resolveCreateDefaultCwd = useCallback((): string => { const activeCwd = agentProjectRoot(selectedAgent); - if (activeCwd) return activeCwd; + if (isLocalFolder(selectedAgent?.cwd) && isLocalFolder(activeCwd)) + return activeCwd; const lastUsedCwd = window.localStorage .getItem("dispatch:lastUsedAgentCwd") ?.trim(); - if (lastUsedCwd) return lastUsedCwd; - const latestAgentCwd = agentProjectRoot(agents[0]); - if (latestAgentCwd) return latestAgentCwd; + if (isLocalFolder(lastUsedCwd)) return lastUsedCwd; + for (const agent of agents) { + const cwd = agentProjectRoot(agent); + if (isLocalFolder(agent.cwd) && isLocalFolder(cwd)) return cwd; + } return ""; }, [agents, selectedAgent]); diff --git a/apps/web/src/components/app/create-agent-dialog-utils.ts b/apps/web/src/components/app/create-agent-dialog-utils.ts index 554af1557..d05f95bb8 100644 --- a/apps/web/src/components/app/create-agent-dialog-utils.ts +++ b/apps/web/src/components/app/create-agent-dialog-utils.ts @@ -1,3 +1,4 @@ +import { isLocalFolder } from "./path-input-utils"; import { useCallback, useMemo, useState } from "react"; import { useQuery } from "@tanstack/react-query"; import { useAtom } from "jotai"; @@ -33,7 +34,8 @@ export function readStoredString(key: string): string { } export function readLastUsedCwd(): string { - return readStoredString(LAST_USED_CWD_KEY) || "~/"; + const cwd = readStoredString(LAST_USED_CWD_KEY); + return isLocalFolder(cwd) ? cwd : "~/"; } export function readLastUsedAgentType(): AgentType | null { diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index 3d9ca0a9b..7e2e091b5 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -220,6 +220,7 @@ function CreateAgentDialogContent({ }} > ( - () => mergeHistoryOptions(filteredHistoryOptions, projectSuggestionOptions), - [filteredHistoryOptions, projectSuggestionOptions] - ); + const options = useMemo(() => { + const merged = mergeHistoryOptions( + filteredHistoryOptions, + projectSuggestionOptions + ); + return localFoldersOnly + ? merged.filter((option) => isLocalFolder(option.path)) + : merged; + }, [filteredHistoryOptions, projectSuggestionOptions, localFoldersOnly]); const [selectedIndex, setSelectedIndex] = useState(0); const projectSuggestionsRequestRef = useRef(0); const listboxRef = useRef(null); @@ -191,10 +199,13 @@ export function PathInput({ }; }, [dropdownOpen, historyFilter]); + const runnerInLocalField = + localFoldersOnly && !!value.trim() && !isLocalFolder(value); + // Debounced path validation useEffect(() => { const trimmed = value.trim(); - if (!trimmed) { + if (!trimmed || runnerInLocalField) { validationRequestRef.current += 1; setPathValidation(null); onPathInfoChange?.(null); @@ -246,7 +257,7 @@ export function PathInput({ validationRequestRef.current += 1; setValidating(false); }; - }, [value, showValidation, onPathInfoChange]); + }, [value, showValidation, onPathInfoChange, runnerInLocalField]); // Debounced inline ghost completion useEffect(() => { @@ -468,7 +479,9 @@ export function PathInput({ {showValidation ? (
    - {validating ? ( + {runnerInLocalField ? ( + Choose a folder on this machine. + ) : validating ? ( ) : pathValidation ? ( pathValidation.isDirectory ? ( diff --git a/apps/web/src/components/app/use-create-agent-form.test.tsx b/apps/web/src/components/app/use-create-agent-form.test.tsx index f955bec6e..3bf0ad3f5 100644 --- a/apps/web/src/components/app/use-create-agent-form.test.tsx +++ b/apps/web/src/components/app/use-create-agent-form.test.tsx @@ -502,6 +502,17 @@ describe("cwd seeding", () => { expect(result.current.createCwd).toBe("/repo/spaced"); }); + it("keeps remote locators out of native launches, including saved values", async () => { + const locator = "runner://linux/@session"; + window.localStorage.setItem(LAST_USED_CWD_KEY, locator); + const { result } = await setup({ resolveDefaultCwd: () => locator }); + expect(result.current.createCwd).toBe("~/"); + act(() => result.current.setCreateCwd(locator)); + expect(result.current.locationReady).toBe(false); + act(() => result.current.setCreateCwd("/local/folder")); + expect(result.current.locationReady).toBe(true); + }); + it("falls back to the stored last-used cwd, then to ~/", async () => { window.localStorage.setItem(LAST_USED_CWD_KEY, "/last/used"); const stored = await setup({ resolveDefaultCwd: () => "" }); diff --git a/apps/web/src/components/app/use-create-agent-form.ts b/apps/web/src/components/app/use-create-agent-form.ts index 6ac74f707..63c15d7d1 100644 --- a/apps/web/src/components/app/use-create-agent-form.ts +++ b/apps/web/src/components/app/use-create-agent-form.ts @@ -1,3 +1,4 @@ +import { isLocalFolder } from "./path-input-utils"; import { createClientId } from "@/lib/client-id"; import { MANAGED_WORKSPACE } from "@dispatch/runner-protocol"; import { useQuery } from "@tanstack/react-query"; @@ -157,9 +158,6 @@ export function useCreateAgentForm({ (!repository.trim() || (isRepositoryUrl(repository.trim()) && (branchMode === "new" || Boolean(runnerBranch.trim()))))); - const locationReady = runnerId - ? Boolean(remoteCwd) && repoReady && (!selectedProjectId || projectsLoaded) - : !selectedProjectId || projectsLoaded; const setCreateProjectId = (id: string | null) => { if (managedSession) { setRunnerProjectId(id); @@ -188,9 +186,12 @@ export function useCreateAgentForm({ }); const [folderCwd, setCreateCwd] = useState(() => { const resolved = resolveDefaultCwd().trim(); - return resolved || readLastUsedCwd(); + return isLocalFolder(resolved) ? resolved : readLastUsedCwd(); }); const createCwd = remote ? remoteCwd : (project?.repoRoot ?? folderCwd); + const locationReady = runnerId + ? Boolean(remoteCwd) && repoReady && (!selectedProjectId || projectsLoaded) + : isLocalFolder(createCwd) && (!selectedProjectId || projectsLoaded); const [createCwdInitialized, setCreateCwdInitialized] = useState( () => createCwd.trim().length > 0 ); From b36b6a1b5d49232a9a47a6eaa65702a9bb6c12ce Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 10:08:09 -0700 Subject: [PATCH 120/642] Serve live Files and Changes views from the session runner --- apps/server/src/agents/checkout-inspection.ts | 77 +---- apps/server/src/agents/checkout-observers.ts | 116 ++++++++ apps/server/src/agents/checkout-runner.ts | 113 +++++++- apps/server/src/agents/checkout-view-cli.ts | 35 +++ apps/server/src/agents/checkout-view.ts | 48 ++++ apps/server/src/agents/checkout-watch.ts | 122 ++++++++ .../server/src/agents/diff-stats-refresher.ts | 14 +- apps/server/src/agents/manager.ts | 17 +- apps/server/src/agents/remote/runner.ts | 66 ++++- apps/server/src/agents/remote/service.ts | 22 +- apps/server/src/files/open-workspace-file.ts | 62 ++++ apps/server/src/files/workspace-view.ts | 250 ++++++++++++++++ apps/server/src/main.ts | 6 + .../src/routes/agents/checkout-response.ts | 40 +++ .../src/routes/agents/lifecycle-routes.ts | 168 ++++------- apps/server/src/routes/agents/shared.ts | 1 + .../src/routes/agents/workspace-routes.ts | 270 ++---------------- apps/server/src/server.ts | 21 +- apps/server/src/shared/git/agent-diff.ts | 16 ++ apps/server/src/shared/git/diff-file-rules.ts | 39 ++- apps/server/src/shared/git/diff-image.ts | 62 ++-- apps/server/test/agent-diff.test.ts | 1 + apps/server/test/diff-image.test.ts | 20 ++ .../test/runner-checkout-watches.test.ts | 79 +++++ .../test/runner-protocol-consumer.test.ts | 34 +++ .../test/workspace-directory-race.test.ts | 2 + apps/server/test/workspace-routes.test.ts | 2 + .../components/app/changes-diff-section.tsx | 1 + apps/web/src/components/app/changes-tab.tsx | 32 ++- .../src/components/app/diff-image-view.tsx | 23 +- apps/web/src/components/app/files-pane.tsx | 63 ++-- apps/web/src/hooks/use-agent-diff.ts | 16 +- apps/web/src/hooks/use-sse.test.ts | 14 + apps/web/src/hooks/use-sse.ts | 18 ++ docs/03-api-spec.md | 1 + docs/design/remote-runner-prototype.md | 4 + docs/design/runner-capability-inventory.md | 4 +- e2e/remote-runner/harness.ts | 2 +- e2e/remote-runner/owner-review.spec.ts | 88 ++++++ packages/runner-protocol/README.md | 6 + packages/runner-protocol/src/checkout-view.ts | 172 +++++++++++ packages/runner-protocol/src/connection.ts | 1 + packages/runner-protocol/src/execution.ts | 9 + packages/runner-protocol/src/index.ts | 1 + packages/shared/src/diff-types.ts | 2 + packages/shared/src/ui-event-types.ts | 1 + 46 files changed, 1638 insertions(+), 523 deletions(-) create mode 100644 apps/server/src/agents/checkout-observers.ts create mode 100644 apps/server/src/agents/checkout-view-cli.ts create mode 100644 apps/server/src/agents/checkout-view.ts create mode 100644 apps/server/src/agents/checkout-watch.ts create mode 100644 apps/server/src/files/open-workspace-file.ts create mode 100644 apps/server/src/files/workspace-view.ts create mode 100644 apps/server/src/routes/agents/checkout-response.ts create mode 100644 apps/server/test/runner-checkout-watches.test.ts create mode 100644 packages/runner-protocol/src/checkout-view.ts diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index 82400a8d1..6f09c7b04 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -1,13 +1,12 @@ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; -import { constants } from "node:fs"; import { - lstat, - open, - readlink, - realpath, - type FileHandle, -} from "node:fs/promises"; + DARWIN_NOFOLLOW_ANY, + openRegularFile, + openLinuxDirectory, +} from "../files/open-workspace-file.js"; +import { constants } from "node:fs"; +import { lstat, open, readlink, realpath } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { @@ -101,66 +100,6 @@ function validateFilePath(file: string): string[] { return segments; } -// These flags are provided by the operating systems but aren't exposed by Node. -const DARWIN_NOFOLLOW_ANY = 0x20000000; -const LINUX_OPEN_PATH = 0x200000; - -async function openRegularFile( - root: string, - segments: string[] -): Promise { - const target = path.join(root, ...segments); - if (process.platform === "darwin") { - if (!(await lstat(target)).isFile()) - throw new Error("Expected a regular worktree file"); - return open( - target, - constants.O_RDONLY | constants.O_NONBLOCK | DARWIN_NOFOLLOW_ANY - ); - } - if (process.platform !== "linux") { - throw new Error("Checkout file inspection requires macOS or Linux"); - } - - const directory = await openLinuxDirectory(path.dirname(target)); - try { - const entry = await open( - `/proc/self/fd/${directory.fd}/${segments.at(-1)}`, - LINUX_OPEN_PATH | constants.O_NOFOLLOW - ); - try { - if (!(await entry.stat()).isFile()) - throw new Error("Expected a regular worktree file"); - return await open(`/proc/self/fd/${entry.fd}`, constants.O_RDONLY); - } finally { - await entry.close(); - } - } finally { - await directory.close(); - } -} - -// Pin every directory component so a symlink replacement cannot redirect -// traversal. The procfs path acts as openat for Node's pathname APIs. -async function openLinuxDirectory(target: string): Promise { - let directory = await open("/", LINUX_OPEN_PATH | constants.O_DIRECTORY); - try { - for (const segment of target.split("/").filter(Boolean)) { - const next = await open( - `/proc/self/fd/${directory.fd}/${segment}`, - LINUX_OPEN_PATH | constants.O_DIRECTORY | constants.O_NOFOLLOW - ); - const previous = directory; - directory = next; - await previous.close(); - } - return directory; - } catch (error) { - await directory.close(); - throw error; - } -} - async function readWorktreeFile( root: string, segments: string[] @@ -195,11 +134,11 @@ async function readWorktreeFile( } } -async function recordedReviewBase(root: string): Promise { +export async function recordedReviewBase(root: string): Promise { const { stdout: ref, exitCode } = await run( "git", ["symbolic-ref", "--quiet", "HEAD"], - { cwd: root, allowedExitCodes: [0, 1] } + { cwd: root, allowedExitCodes: [0, 1, 128] } ); if (exitCode !== 0 || !ref.startsWith("refs/heads/")) return null; const branch = ref.slice("refs/heads/".length); diff --git a/apps/server/src/agents/checkout-observers.ts b/apps/server/src/agents/checkout-observers.ts new file mode 100644 index 000000000..f3614fead --- /dev/null +++ b/apps/server/src/agents/checkout-observers.ts @@ -0,0 +1,116 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; +import { + agentWorkspaceDir, + type WorkspaceTargetAgent, +} from "./workspace-target.js"; +import { SharedCheckoutWatches, watchCheckout } from "./checkout-watch.js"; +import type { RemoteRunnerService } from "./remote/service.js"; + +type Interest = { + runner?: string; + watching: boolean; + key: string; + expires: number; + close: () => void; +}; + +/** HTTP reads renew interest. A disconnected subscription reopens on the next + * read, and an active view periodically rereads even if the OS drops an event. */ +export class CheckoutObservers { + private readonly local = new SharedCheckoutWatches(watchCheckout); + private readonly agents = new Map(); + private readonly unsubscribe?: () => void; + private readonly timer: ReturnType; + constructor( + private readonly remote: + | Pick + | undefined, + private readonly changed: (id: string) => void + ) { + this.unsubscribe = remote?.onConnectionChange((runnerId) => { + for (const [id, item] of this.agents) { + if (item.runner !== runnerId) continue; + item.watching = false; + item.close(); + if (item.expires >= Date.now()) this.changed(id); + } + }); + this.timer = setInterval(() => { + for (const [id, item] of this.agents) + if (item.expires < Date.now()) { + this.agents.delete(id); + item.close(); + } + }, 15_000); + this.timer.unref(); + } + observe(agent: WorkspaceTargetAgent & { id: string }) { + const id = agent.id; + const placement = agent.cwd && remotePlacement(agent.cwd); + const key = placement ? agent.cwd : agentWorkspaceDir(agent); + if (!key) return; + const expires = Date.now() + 75_000; + const prev = this.agents.get(id); + if (prev?.key === key) { + prev.expires = expires; + if (prev.watching) return; + } + prev?.close(); + const item: Interest = { + key, + runner: placement ? placement.runner : undefined, + watching: true, + expires, + close: () => {}, + }; + this.agents.set(id, item); + const active = () => this.agents.get(id) === item; + let timer: ReturnType | undefined; + const notify = () => { + if (!active() || timer) return; + timer = setTimeout(() => { + timer = undefined; + if (active()) this.changed(id); + }, 100); + }; + const ended = () => { + if (active()) item.watching = false; + clearTimeout(timer); + }; + if (!placement) { + item.close = this.local.subscribe(key, notify, ended); + return; + } + if (!this.remote) { + this.agents.delete(id); + return; + } + void this.remote + .requestSession(placement, { kind: "watchCheckout", agentId: id }) + .then(({ channel }) => { + if (!channel || !active()) { + ended(); + channel?.destroy(); + return; + } + item.close = () => channel.destroy(); + channel.on("data", notify); + channel.once("end", () => { + ended(); + channel.destroy(); + }); + channel.once("close", () => { + if (active()) item.watching = false; + }); + }) + .catch(() => { + ended(); + }); + } + close() { + this.unsubscribe?.(); + clearInterval(this.timer); + for (const item of this.agents.values()) item.close(); + this.agents.clear(); + } +} diff --git a/apps/server/src/agents/checkout-runner.ts b/apps/server/src/agents/checkout-runner.ts index 36e4bff46..9b38c562f 100644 --- a/apps/server/src/agents/checkout-runner.ts +++ b/apps/server/src/agents/checkout-runner.ts @@ -1,4 +1,14 @@ +import type { DiffStats } from "@dispatch/shared"; import { + getDiffStatsComputation, + type DiffStatsComputation, +} from "../shared/git/diff-stats.js"; +import { readCheckoutView } from "./checkout-view.js"; +import { + isCheckoutView, + isCheckoutViewData, + MAX_CHECKOUT_VIEW_BYTES, + type CheckoutView, isCheckoutQuery, isCheckoutReply, remotePlacement, @@ -8,9 +18,13 @@ import { } from "@dispatch/runner-protocol"; import { inspectCheckout } from "./checkout-inspection.js"; import { AgentError } from "./errors.js"; -import type { RemoteRunnerService } from "./remote/service.js"; +import { RunnerRevoked, type RemoteRunnerService } from "./remote/service.js"; import type { AgentRecord } from "./types.js"; -import { agentWorkspaceDir } from "./workspace-target.js"; +import { + agentWorkspaceDir, + agentDiffTarget, + type WorkspaceTargetAgent, +} from "./workspace-target.js"; type Inspect = Extract; @@ -59,3 +73,98 @@ export async function inspectAgentCheckout( export function reviewerWorkspace(owner: AgentRecord) { return agentWorkspaceDir(owner) ?? owner.cwd; } + +export function decodeCheckoutView(raw: unknown, view: CheckoutView) { + if ( + typeof raw !== "string" || + Buffer.byteLength(raw) > MAX_CHECKOUT_VIEW_BYTES + ) + throw new AgentError("Invalid runner checkout response.", 502); + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + throw new AgentError("Invalid runner checkout response.", 502); + } + if ( + value !== null && + typeof value === "object" && + "status" in value && + "error" in value && + [400, 403, 404, 409, 413, 500].includes(Number(value.status)) && + typeof value.error === "string" + ) + throw new AgentError(value.error.slice(0, 256), Number(value.status)); + if ( + !value || + typeof value !== "object" || + !("data" in value) || + !isCheckoutViewData(view, value.data) + ) + throw new AgentError("Invalid runner checkout response.", 502); + return value.data; +} + +/** Resolve the selected session once for both foreground and background reads. */ +export async function readAgentView( + agent: WorkspaceTargetAgent & { id: string }, + view: CheckoutView, + remote?: RemoteRunnerService | null +): Promise { + if (!isCheckoutView(view)) + throw new AgentError("Invalid workspace path or options.", 400); + const placement = agent.cwd && remotePlacement(agent.cwd); + if (placement) { + if (!remote) throw new AgentError("The runner is unavailable.", 503); + try { + const { value } = await remote.requestSession(placement, { + kind: "viewCheckout", + agentId: agent.id, + query: view, + }); + return decodeCheckoutView(value, view); + } catch (error) { + if (error instanceof AgentError) throw error; + throw new AgentError( + error instanceof Error + ? error.message + : "Unable to read the runner checkout.", + error instanceof RunnerRevoked ? 403 : 503 + ); + } + } + const target = agentDiffTarget(agent); + const cwd = "baseBranch" in view ? target?.path : agentWorkspaceDir(agent); + if (!cwd) { + if (view.kind === "stats") return null; + throw new AgentError("This agent has no workspace.", 404); + } + return readCheckoutView( + cwd, + "baseBranch" in view + ? { ...view, baseBranch: view.baseBranch ?? target?.baseRef ?? null } + : view + ); +} + +export async function readAgentStats( + id: string, + agent: WorkspaceTargetAgent, + remote?: RemoteRunnerService | null +): Promise { + const placement = agent.cwd && remotePlacement(agent.cwd); + if (placement) { + const stats = (await readAgentView( + { ...agent, id }, + { kind: "stats", baseBranch: null, includeUncommitted: true }, + remote + )) as DiffStats | null; + return stats + ? { kind: "success", stats } + : { kind: "no-data", stats: null }; + } + const target = agentDiffTarget(agent); + return target + ? getDiffStatsComputation(target.path, target.baseRef) + : { kind: "no-data", stats: null }; +} diff --git a/apps/server/src/agents/checkout-view-cli.ts b/apps/server/src/agents/checkout-view-cli.ts new file mode 100644 index 000000000..d39da0ee8 --- /dev/null +++ b/apps/server/src/agents/checkout-view-cli.ts @@ -0,0 +1,35 @@ +import { + isCheckoutView, + MAX_CHECKOUT_VIEW_BYTES, +} from "@dispatch/runner-protocol"; +import { WorkspaceError } from "../files/workspace-view.js"; +import { readCheckoutView } from "./checkout-view.js"; + +export async function runCheckoutViewCli(cwd: string, managed: boolean) { + try { + const chunks: Buffer[] = []; + let size = 0; + for await (const bytes of process.stdin) { + const buf = Buffer.from(bytes); + if ((size += buf.length) > 16 * 1024) throw new Error("Query too large"); + chunks.push(buf); + } + const view: unknown = JSON.parse(Buffer.concat(chunks).toString()); + if (!isCheckoutView(view)) throw new Error("Invalid checkout view"); + const output = JSON.stringify({ + data: await readCheckoutView(cwd, view, managed), + }); + if (Buffer.byteLength(output) + 1 > MAX_CHECKOUT_VIEW_BYTES) + throw new WorkspaceError("Checkout response is too large.", 413); + process.stdout.write(output + "\n"); + } catch (error) { + if (error instanceof WorkspaceError) + process.stdout.write( + JSON.stringify({ status: error.status, error: error.message }) + "\n" + ); + else { + process.stderr.write("Unable to read the session checkout.\n"); + process.exitCode = 1; + } + } +} diff --git a/apps/server/src/agents/checkout-view.ts b/apps/server/src/agents/checkout-view.ts new file mode 100644 index 000000000..86b43b833 --- /dev/null +++ b/apps/server/src/agents/checkout-view.ts @@ -0,0 +1,48 @@ +import type { CheckoutView } from "@dispatch/runner-protocol"; +import { readWorkspaceView, WorkspaceError } from "../files/workspace-view.js"; +import { getAgentDiff, getAgentFileDiff } from "../shared/git/agent-diff.js"; +import { getAgentDiffImage } from "../shared/git/diff-image.js"; +import { getDiffStatsComputation } from "../shared/git/diff-stats.js"; +import { recordedReviewBase } from "./checkout-inspection.js"; +/** Runs under the workload account on Linux, or in process for a native session. */ +export async function readCheckoutView( + cwd: string, + view: CheckoutView, + managed = false +) { + if (!("baseBranch" in view)) return readWorkspaceView(cwd, view); + const base = + view.baseBranch ?? (managed ? await recordedReviewBase(cwd) : null); + switch (view.kind) { + case "stats": { + const computation = await getDiffStatsComputation(cwd, base, view); + if (computation.kind === "failure") + throw new Error("Git status unavailable."); + return computation.stats; + } + case "diff": + return ( + (await getAgentDiff(cwd, base, undefined, view)) ?? { + baseRef: null, + files: [], + } + ); + case "fileDiff": + return getAgentFileDiff(cwd, base, view.path, undefined, view); + case "image": { + const result = await getAgentDiffImage( + cwd, + base, + view.path, + view.side, + view + ); + if (!result.ok) + throw new WorkspaceError( + "Image not available.", + result.reason === "too-large" ? 413 : 404 + ); + return result.buffer.toString("base64"); + } + } +} diff --git a/apps/server/src/agents/checkout-watch.ts b/apps/server/src/agents/checkout-watch.ts new file mode 100644 index 000000000..7c8dc34ca --- /dev/null +++ b/apps/server/src/agents/checkout-watch.ts @@ -0,0 +1,122 @@ +import { watch } from "node:fs"; +import { stat } from "node:fs/promises"; +import path from "node:path"; +import type { ChildProcessWithoutNullStreams } from "node:child_process"; + +type Close = () => void; +type Open = (root: string, changed: () => void, closed: () => void) => Close; + +/** One OS watch per checkout, even if a reviewer and author both have it open. */ +export class SharedCheckoutWatches { + private readonly roots = new Map< + string, + { listeners: Map<() => void, () => void>; close: Close } + >(); + constructor(private readonly open: Open) {} + subscribe(root: string, changed: () => void, closed: () => void): Close { + let group = this.roots.get(root); + if (!group) { + const listeners = new Map([[changed, closed]]); + group = { listeners, close: () => {} }; + this.roots.set(root, group); + group.close = this.open( + root, + () => { + for (const notify of listeners.keys()) notify(); + }, + () => { + if (this.roots.get(root) !== group) return; + this.roots.delete(root); + for (const end of listeners.values()) end(); + } + ); + } else group.listeners.set(changed, closed); + return () => { + group.listeners.delete(changed); + if (!group.listeners.size && this.roots.get(root) === group) { + this.roots.delete(root); + group.close(); + } + }; + } +} + +/** Run in the native process or the Linux workload account. Never recursively + * watch an arbitrary non-repository cwd (it may be a user's home directory). */ +export const watchCheckout: Open = (root, changed, closed) => { + let stopped = false; + let watcher: ReturnType | undefined; + let timer: ReturnType | undefined; + const close = () => { + stopped = true; + watcher?.close(); + clearTimeout(timer); + }; + void stat(path.join(root, ".git")) + .then( + () => true, + () => false + ) + .then((recursive) => { + if (stopped) return; + try { + watcher = watch(root, { recursive, persistent: false }, (_, name) => { + if ( + name && + (/(^|\/)(node_modules|\.dispatch)(\/|$)/.test(name) || + /(^|\/)\.git\/(objects\/|logs\/|.*\.lock$)/.test(name)) + ) + return; + if (!timer) + timer = setTimeout(() => { + timer = undefined; + changed(); + }, 450); + }); + changed(); // Reconcile edits during asynchronous watch setup. + watcher.once("error", () => { + close(); + closed(); + }); + } catch { + close(); + closed(); + } + }); + return close; +}; + +export function childWatch( + child: ChildProcessWithoutNullStreams, + changed: () => void, + closed: () => void +): Close { + child.stdout.on("data", changed); + child.stderr.resume(); + child.stdin.on("error", () => {}); + let closing = false; + child.on("error", () => {}); + child.once("close", () => { + if (!closing) closed(); + }); + return () => { + closing = true; + child.stdin.end(); + child.kill(); + }; +} + +export function runCheckoutWatchCli(cwd: string) { + const close = watchCheckout( + cwd, + () => process.stdout.write("1\n"), + () => process.exit(1) + ); + // The root supervisor closing its pipe (including on a crash) releases the watcher. + process.stdin + .on("end", () => { + close(); + process.exit(0); + }) + .resume(); +} diff --git a/apps/server/src/agents/diff-stats-refresher.ts b/apps/server/src/agents/diff-stats-refresher.ts index 0b6955cfe..24ef36348 100644 --- a/apps/server/src/agents/diff-stats-refresher.ts +++ b/apps/server/src/agents/diff-stats-refresher.ts @@ -30,6 +30,10 @@ type WarnLogger = { export type DiffStatsRefresherOptions = { getAgent: (id: string) => Promise; publishEvent: (event: DiffStatsChangedEvent) => void; + computeAgentStats?: ( + id: string, + agent: DiffStatsAgent + ) => Promise; computeDiffStats?: ComputeDiffStats; /** Override Git command execution while retaining the default adapter. */ runGitCommand?: GetDiffStatsOptions["runCommand"]; @@ -65,12 +69,14 @@ export class DiffStatsRefresher { baseRef: string | null ) => Promise; private readonly freshnessMs: number; + private readonly computeAgentStats: DiffStatsRefresherOptions["computeAgentStats"]; private readonly logger: WarnLogger | null; private readonly tracker: SubsystemTracker | null; private signals = 0; private dedupedSignals = 0; constructor(options: DiffStatsRefresherOptions) { + this.computeAgentStats = options.computeAgentStats; this.getAgent = options.getAgent; this.publishEvent = options.publishEvent; const customComputeDiffStats = options.computeDiffStats; @@ -160,10 +166,10 @@ export class DiffStatsRefresher { const agent = await this.getAgent(agentId); // `getDiffStats` returns null when the path isn't inside a repo. const target = agent ? agentDiffTarget(agent) : null; - if (!target) { - nextStats = null; - } else { - computation = await this.computeDiffStats(target.path, target.baseRef); + if (agent && (this.computeAgentStats || target)) { + computation = this.computeAgentStats + ? await this.computeAgentStats(agentId, agent) + : await this.computeDiffStats(target!.path, target!.baseRef); if (computation.kind === "failure") throw computation.error; nextStats = computation.stats; } diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 8e629d2a1..678640478 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,6 +1,12 @@ +import { readAgentView } from "./checkout-runner.js"; +import type { CheckoutView } from "@dispatch/runner-protocol"; import { AttentionHistory } from "../notifications/attention-history.js"; import { matchingProjects } from "../projects/matching.js"; -import { attentionPreview, type Effort } from "@dispatch/shared"; +import { + attentionPreview, + type Effort, + type FileDiffResponse, +} from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; import { randomUUID } from "node:crypto"; import { mkdir, readFile, rm, stat, unlink } from "node:fs/promises"; @@ -1357,6 +1363,15 @@ export class AgentManager { return updated; } + viewCheckout( + agent: AgentRecord, + query: Extract + ): Promise; + viewCheckout(agent: AgentRecord, query: CheckoutView): Promise; + viewCheckout(agent: AgentRecord, query: CheckoutView): Promise { + return readAgentView(agent, query, this.remote); + } + async inspectCheckout( agent: AgentRecord, query: CheckoutQuery diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index b6b24bc0c..be947cca2 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -1,5 +1,6 @@ import { runnerHealthSampler } from "./health.js"; -import { execFile } from "node:child_process"; +import { SharedCheckoutWatches, childWatch } from "../checkout-watch.js"; +import { execFile, spawn } from "node:child_process"; import { readFileSync } from "node:fs"; import { createConnection, isIP } from "node:net"; import path from "node:path"; @@ -15,6 +16,7 @@ import { isOpaqueId, MANAGED_WORKSPACE, RUNNER_WIRE_VERSION, + MAX_CHECKOUT_VIEW_BYTES, wireFrames, parseServiceFrame, runnerRequestId, @@ -276,6 +278,18 @@ export async function runRemoteRunner(filename: string) { samplingEngines = false; } }; + const watches = new Map void>(); + const sharedWatches = new SharedCheckoutWatches((cwd, changed, closed) => + childWatch( + spawn( + setpriv, + [...childArgs, ...selfCommand("runner-watch-checkout"), cwd], + { env, stdio: ["pipe", "pipe", "pipe"] } + ), + changed, + closed + ) + ); const channels = new Map>(); const timeout = setTimeout(() => socket.destroy(), 5000); socket.on("error", (error: Error) => @@ -283,6 +297,8 @@ export async function runRemoteRunner(filename: string) { ); socket.on("close", () => { connection.abort(); + for (const close of watches.values()) close(); + watches.clear(); clearTimeout(timeout); clearInterval(healthInterval); for (const channel of channels.values()) channel.destroy(); @@ -355,6 +371,30 @@ export async function runRemoteRunner(filename: string) { } if (socket.destroyed) return; switch (command.kind) { + case "watchCheckout": { + const cwd = await supervisor.checkoutDirectory( + agentId, + workspace, + target?.cwd + ); + if (socket.destroyed) return; + if (watches.size >= 512) + throw new Error("Too many open checkout watches."); + watches.set( + id, + sharedWatches.subscribe( + cwd, + () => safeSend({ type: "data", id, data: "MQ==" }), + () => { + watches.delete(id); + safeSend({ type: "close", id }); + } + ) + ); + result(true); + break; + } + case "viewCheckout": case "inspectCheckout": { const cwd = await supervisor.checkoutDirectory( agentId, @@ -363,7 +403,16 @@ export async function runRemoteRunner(filename: string) { ); const child = execute( setpriv, - [...childArgs, ...selfCommand("runner-inspect-checkout"), cwd], + [ + ...childArgs, + ...selfCommand( + command.kind === "viewCheckout" + ? "runner-view-checkout" + : "runner-inspect-checkout" + ), + cwd, + ...(managed ? ["--managed"] : []), + ], { env: { ...env, @@ -371,7 +420,10 @@ export async function runRemoteRunner(filename: string) { GH_PROMPT_DISABLED: "1", }, timeout: 90_000, - maxBuffer: 4 * 1024 * 1024, + maxBuffer: + command.kind === "viewCheckout" + ? MAX_CHECKOUT_VIEW_BYTES + : 4 * 1024 * 1024, } ); child.child.stdin?.on("error", () => {}); // execFile reports early child failure. @@ -496,8 +548,11 @@ export async function runRemoteRunner(filename: string) { if (channel && channel.writableLength > 32 * 1024 * 1024) channel.destroy(); else channel?.write(Buffer.from(frame.data, "base64")); - } else if (frame.type === "close") channels.get(frame.id)?.destroy(); - else socket.destroy(); + } else if (frame.type === "close") { + watches.get(frame.id)?.(); + watches.delete(frame.id); + channels.get(frame.id)?.destroy(); + } else socket.destroy(); }); socket.once("secureConnect", () => { connectedAt = performance.now(); @@ -513,6 +568,7 @@ export async function runRemoteRunner(filename: string) { engineManagement: true, githubManagement: true, checkoutInspection: true, + checkoutViews: true, sharedWorktree: true, }); }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index fa0ee9d34..1582de34f 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -144,6 +144,7 @@ type Peer = { engineManagement: boolean; githubManagement: boolean; checkoutInspection: boolean; + checkoutViews: boolean; sharedWorktree: boolean; /** Last pushed, validated engine inventory; absent until the runner first reports one. */ engines?: EngineInventoryEntry[]; @@ -275,6 +276,11 @@ export function configuredRunner(input?: { export class RemoteRunnerService { /** Connected runners by placement name; each is an independent peer. */ + private readonly connectionListeners = new Set<(runnerId: string) => void>(); + onConnectionChange(listener: (runnerId: string) => void) { + this.connectionListeners.add(listener); + return () => this.connectionListeners.delete(listener); + } private readonly peers = new Map(); /** Enrolled, unrevoked registrations by client certificate fingerprint. */ private readonly enrolled = new Map(); @@ -632,7 +638,10 @@ export class RemoteRunnerService { socket.on("close", () => { clearTimeout(deadline); if (!peer) return; - if (this.peers.get(gate.key) === peer) this.peers.delete(gate.key); + if (this.peers.get(gate.key) === peer) { + this.peers.delete(gate.key); + for (const notify of this.connectionListeners) notify(gate.key); + } peer.connection.close(); if (gate.registrationId) void this.enrollment?.registry @@ -650,6 +659,7 @@ export class RemoteRunnerService { reportsHealth: ready.health === true, engineManagement: ready.engineManagement === true, githubManagement: ready.githubManagement === true, + checkoutViews: ready.checkoutViews === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, connection: new RunnerConnection(send), @@ -662,6 +672,7 @@ export class RemoteRunnerService { this.peers.set(gate.key, peer); previous?.socket.destroy(); gate.ready?.(ready.workspaces, peer.managedWorkspace); + for (const notify of this.connectionListeners) notify(gate.key); if (peer.reportsHealth) { send({ type: "accept_health", @@ -1178,7 +1189,7 @@ export class RemoteRunnerService { return this.request( placement, { ...operation, workspace: placement.workspace }, - operation.kind === "attach" + operation.kind === "attach" || operation.kind === "watchCheckout" ); } @@ -1320,6 +1331,13 @@ export class RemoteRunnerService { "The enrolled runner is disconnected or the workspace is unavailable." ); } + if ( + (command.kind === "viewCheckout" || command.kind === "watchCheckout") && + !peer.checkoutViews + ) + throw new RunnerCapabilityUnavailable( + "Update this runner to open Files and Changes." + ); if (command.kind === "inspectCheckout" && !peer.checkoutInspection) throw new RunnerCapabilityUnavailable( "Update the runner to inspect a session checkout." diff --git a/apps/server/src/files/open-workspace-file.ts b/apps/server/src/files/open-workspace-file.ts new file mode 100644 index 000000000..7b5ab4531 --- /dev/null +++ b/apps/server/src/files/open-workspace-file.ts @@ -0,0 +1,62 @@ +import { constants } from "node:fs"; +import { lstat, open, type FileHandle } from "node:fs/promises"; +import path from "node:path"; +// These flags are provided by the operating systems but aren't exposed by Node. +export const DARWIN_NOFOLLOW_ANY = 0x20000000; +const LINUX_OPEN_PATH = 0x200000; + +export async function openRegularFile( + root: string, + segments: string[] +): Promise { + const target = path.join(root, ...segments); + if (process.platform === "darwin") { + if (!(await lstat(target)).isFile()) + throw new Error("Expected a regular worktree file"); + return open( + target, + constants.O_RDONLY | constants.O_NONBLOCK | DARWIN_NOFOLLOW_ANY + ); + } + if (process.platform !== "linux") { + throw new Error("Checkout file inspection requires macOS or Linux"); + } + + const directory = await openLinuxDirectory(path.dirname(target)); + try { + const entry = await open( + `/proc/self/fd/${directory.fd}/${segments.at(-1)}`, + LINUX_OPEN_PATH | constants.O_NOFOLLOW + ); + try { + if (!(await entry.stat()).isFile()) + throw new Error("Expected a regular worktree file"); + return await open(`/proc/self/fd/${entry.fd}`, constants.O_RDONLY); + } finally { + await entry.close(); + } + } finally { + await directory.close(); + } +} + +// Pin every directory component so a symlink replacement cannot redirect +// traversal. The procfs path acts as openat for Node's pathname APIs. +export async function openLinuxDirectory(target: string): Promise { + let directory = await open("/", LINUX_OPEN_PATH | constants.O_DIRECTORY); + try { + for (const segment of target.split("/").filter(Boolean)) { + const next = await open( + `/proc/self/fd/${directory.fd}/${segment}`, + LINUX_OPEN_PATH | constants.O_DIRECTORY | constants.O_NOFOLLOW + ); + const previous = directory; + directory = next; + await previous.close(); + } + return directory; + } catch (error) { + await directory.close(); + throw error; + } +} diff --git a/apps/server/src/files/workspace-view.ts b/apps/server/src/files/workspace-view.ts new file mode 100644 index 000000000..4c7895d06 --- /dev/null +++ b/apps/server/src/files/workspace-view.ts @@ -0,0 +1,250 @@ +import type { WorkspaceView } from "@dispatch/runner-protocol"; +import { openWorkspaceDirectory } from "./workspace-directory.js"; +import { ignoredWorkspacePaths } from "./workspace-ignore.js"; +import { createWorkspaceFileIndexer } from "./workspace-file-index.js"; +import { constants } from "node:fs"; +import { lstat, open, realpath } from "node:fs/promises"; +import path from "node:path"; +import { imageDimensionsFromBuffer } from "./image-dimensions.js"; +import { detectFileType } from "./file-type.js"; + +const MAX_ENTRIES = 500; +const MAX_BYTES = 1_048_576; +export class WorkspaceError extends Error { + constructor( + message: string, + readonly status = 400 + ) { + super(message); + } +} + +// Do not follow links, including directory links. Recheck after opening a file +// as well, so an ordinary concurrent rename cannot return unrelated contents. +async function resolveEntry(root: string, relative: string): Promise { + if ( + path.isAbsolute(relative) || + relative.includes("\\") || + relative.includes("\0") + ) { + throw new WorkspaceError("Invalid workspace path."); + } + const parts = relative ? relative.split("/") : []; + if ( + parts.some( + (part) => + !part || part === "." || part === ".." || part.toLowerCase() === ".git" + ) + ) { + throw new WorkspaceError("Invalid workspace path."); + } + let target = root; + for (const part of parts) { + target = path.join(target, part); + if ((await lstat(target)).isSymbolicLink()) { + throw new WorkspaceError( + "Symbolic links are not followed in Files.", + 403 + ); + } + } + const resolved = await realpath(target); + const inside = path.relative(root, resolved); + if ( + inside.startsWith(".." + path.sep) || + inside === ".." || + path.isAbsolute(inside) + ) { + throw new WorkspaceError("Path is outside the workspace.", 403); + } + return resolved; +} + +const fileIndex = createWorkspaceFileIndexer(); +export async function readWorkspaceView( + workspace: string, + query: WorkspaceView +) { + try { + const root = await realpath(workspace); + if (query.kind === "index") { + const generation = + typeof query.generation === "string" + ? query.generation.slice(0, 64) + : "initial"; + return await fileIndex(root, generation); + } + const relative = query.path; + const target = await resolveEntry(root, relative); + if (query.kind === "directory") { + const { directory, verify } = await openWorkspaceDirectory(root, target); + const entries: Array<{ + name: string; + path: string; + kind: "directory" | "file" | "link" | "other"; + }> = []; + const visible: typeof entries = []; + let truncated = false; + let scanned = 0; + const deadline = Date.now() + 2000; + const flush = async () => { + const ignored = await ignoredWorkspacePaths( + target, + entries.map((entry) => entry.name) + ); + visible.push(...entries.filter((entry) => !ignored.has(entry.name))); + entries.length = 0; + }; + for await (const entry of directory) { + if (entry.name.toLowerCase() === ".git") continue; + if (++scanned > 20_000 || Date.now() > deadline) { + truncated = true; + break; + } + entries.push({ + name: entry.name, + path: relative ? `${relative}/${entry.name}` : entry.name, + kind: entry.isSymbolicLink() + ? "link" + : entry.isDirectory() + ? "directory" + : entry.isFile() + ? "file" + : "other", + }); + if (entries.length === 500) { + await flush(); + if (visible.length > MAX_ENTRIES) { + truncated = true; + break; + } + } + } + await verify(); + if (entries.length) await flush(); + await verify(); + if (visible.length > MAX_ENTRIES) truncated = true; + visible.sort( + (a, b) => + Number(b.kind === "directory") - Number(a.kind === "directory") || + a.name.localeCompare(b.name) + ); + return { entries: visible.slice(0, MAX_ENTRIES), truncated }; + } + const initial = await lstat(target); + if (!initial.isFile()) + throw new WorkspaceError("Only regular files can be previewed."); + const handle = await open( + target, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK + ); + try { + const stat = await handle.stat(); + if (!stat.isFile()) + throw new WorkspaceError("Only regular files can be previewed."); + const checked = await resolveEntry(root, relative); + const current = await lstat(checked); + if ( + checked !== target || + stat.ino !== current.ino || + stat.dev !== current.dev + ) { + throw new WorkspaceError( + "File changed while opening. Refresh to retry.", + 409 + ); + } + if (stat.size > MAX_BYTES) + return { + kind: "unsupported", + size: stat.size, + message: "Preview limited to files up to 1 MiB.", + }; + const buffer = Buffer.alloc(MAX_BYTES + 1); + let length = 0; + while (length < buffer.length) { + const { bytesRead } = await handle.read( + buffer, + length, + buffer.length - length, + null + ); + if (!bytesRead) break; + length += bytesRead; + } + if (length > MAX_BYTES) + return { + kind: "unsupported", + size: length, + message: "File grew beyond the 1 MiB preview limit.", + }; + const data = buffer.subarray(0, length); + // Keep image preview dependency-free and bounded. Animated formats are + // deliberately excluded from this first read-only explorer. + const detected = detectFileType(data, relative); + if (detected.ok && detected.mimeType === "image/svg+xml") { + return { + kind: "svg", + size: length, + text: data.toString("utf8"), + src: `data:image/svg+xml;base64,${data.toString("base64")}`, + }; + } + if ( + detected.ok && + detected.mimeType.startsWith("image/") && + detected.mimeType !== "image/svg+xml" + ) { + const dimensions = imageDimensionsFromBuffer(data); + const staticImage = + detected.mimeType === "image/jpeg" || + (detected.mimeType === "image/png" && + !data.includes(Buffer.from("acTL"))); + if ( + staticImage && + dimensions && + dimensions.width * dimensions.height <= 16_000_000 + ) { + return { + kind: "image", + size: length, + src: `data:${detected.mimeType};base64,${data.toString("base64")}`, + }; + } + return { + kind: "unsupported", + size: length, + message: + "MVP image previews support static PNG/JPEG with readable dimensions up to 16 megapixels.", + }; + } + try { + if (data.includes(0)) throw new Error("binary"); + return { + kind: "text", + size: length, + text: new TextDecoder("utf-8", { fatal: true }).decode(data), + }; + } catch { + return { + kind: "unsupported", + size: length, + message: "Binary or non-UTF-8 file. Preview unavailable.", + }; + } + } finally { + await handle.close(); + } + } catch (error) { + if (error instanceof WorkspaceError) throw error; + const code = (error as NodeJS.ErrnoException).code; + if (code === "ESTALE") + throw new WorkspaceError("Directory changed. Refresh to retry.", 409); + if (code === "ENOENT" || code === "ENOTDIR") + throw new WorkspaceError("File or workspace no longer exists.", 404); + if (code === "EACCES" || code === "EPERM" || code === "ELOOP") + throw new WorkspaceError("This path cannot be read.", 403); + + throw new WorkspaceError("Unable to read workspace.", 500); + } +} diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index e6ce1bdb5..c97b68d5b 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -43,6 +43,12 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "connect") { const { runRunnerConnect } = await import("./agents/remote/enrollment.js"); await runRunnerConnect(process.argv.slice(3)); +} else if (process.argv[2] === "runner-watch-checkout") { + const { runCheckoutWatchCli } = await import("./agents/checkout-watch.js"); + runCheckoutWatchCli(process.argv[3]!); +} else if (process.argv[2] === "runner-view-checkout") { + const { runCheckoutViewCli } = await import("./agents/checkout-view-cli.js"); + await runCheckoutViewCli(process.argv[3]!, process.argv[4] === "--managed"); } else if (process.argv[2] === "runner-inspect-checkout") { const { runCheckoutInspectionCli } = await import("./agents/checkout-inspection.js"); diff --git a/apps/server/src/routes/agents/checkout-response.ts b/apps/server/src/routes/agents/checkout-response.ts new file mode 100644 index 000000000..c9ab2e5d1 --- /dev/null +++ b/apps/server/src/routes/agents/checkout-response.ts @@ -0,0 +1,40 @@ +import type { FastifyReply } from "fastify"; +import type { CheckoutView } from "@dispatch/runner-protocol"; +import { imageMimeType } from "../../shared/git/diff-image.js"; +import { WorkspaceError } from "../../files/workspace-view.js"; +import { AgentError } from "../../agents/errors.js"; +import type { AgentManager, AgentRecord } from "../../agents/manager.js"; +export async function serveCheckoutView( + agent: AgentRecord, + view: CheckoutView, + manager: Pick, + reply: FastifyReply +) { + try { + const value = await manager.viewCheckout(agent, view); + if (view.kind === "image") { + const mime = imageMimeType(view.path); + if (!mime || typeof value !== "string") + throw new AgentError("Image not available.", 404); + return reply + .header("X-Content-Type-Options", "nosniff") + .header("Cache-Control", "private, no-cache") + .type(mime) + .send(Buffer.from(value, "base64")); + } + if (view.kind === "fileDiff" && !value) + throw new AgentError("File not found in diff.", 404); + return view.kind === "stats" ? { diffStats: value } : value; + } catch (error) { + const status = + error instanceof WorkspaceError + ? error.status + : error instanceof AgentError + ? error.statusCode + : 500; + return reply.code(status).send({ + error: + status === 500 ? "Unable to read checkout." : (error as Error).message, + }); + } +} diff --git a/apps/server/src/routes/agents/lifecycle-routes.ts b/apps/server/src/routes/agents/lifecycle-routes.ts index 5d29a3037..237869ed3 100644 --- a/apps/server/src/routes/agents/lifecycle-routes.ts +++ b/apps/server/src/routes/agents/lifecycle-routes.ts @@ -1,3 +1,4 @@ +import { AgentError } from "../../agents/errors.js"; import { SESSION_RENAME_ASK } from "../../shared/lib/agent-strings.js"; import type { FastifyInstance } from "fastify"; import { BLOCK_TEXT_MAX_CHARS } from "@dispatch/shared"; @@ -7,11 +8,9 @@ import { getEnabledAgentTypes, } from "../../agent-type-settings.js"; import { shouldSuggestSessionRename } from "../../agents/launch-guidance.js"; -import { agentDiffTarget } from "../../agents/workspace-target.js"; import { StreamServiceError } from "../../chat/service.js"; -import { getAgentDiff, getAgentFileDiff } from "../../shared/git/agent-diff.js"; -import { getAgentDiffImage, isImageFile } from "../../shared/git/diff-image.js"; -import { getDiffStats } from "../../shared/git/diff-stats.js"; +import { serveCheckoutView } from "./checkout-response.js"; +import { isImageFile } from "../../shared/git/diff-image.js"; import type { AgentRouteDeps } from "./shared.js"; /** @@ -284,18 +283,22 @@ export async function registerAgentLifecycleRoutes( return reply.code(404).send({ error: "Agent not found." }); } + deps.observeCheckout?.(agent); const includeUncommitted = (request.query as { includeUncommitted?: string }).includeUncommitted !== "false"; if (!includeUncommitted) { - const target = agentDiffTarget(agent); - if (!target) return { diffStats: null }; - return { - diffStats: await getDiffStats(target.path, target.baseRef, { + return serveCheckoutView( + agent, + { + kind: "stats", + baseBranch: null, includeUncommitted: false, - }), - }; + }, + deps.agentManager, + reply + ); } // Await the signal so first-paint always sees a fresh value rather @@ -317,33 +320,22 @@ export async function registerAgentLifecycleRoutes( return reply.code(404).send({ error: "Agent not found." }); } - const target = agentDiffTarget(agent); - if (!target) { - return reply - .code(404) - .send({ error: "Agent has no associated worktree." }); - } - const { path: worktreePath, baseRef } = target; - - try { - const query = request.query as { - ignoreWhitespace?: string; - includeUncommitted?: string; - }; - const ignoreWhitespace = query.ignoreWhitespace !== "false"; - const includeUncommitted = query.includeUncommitted !== "false"; - const result = await getAgentDiff(worktreePath, baseRef, undefined, { - ignoreWhitespace, - includeUncommitted, - }); - if (!result) { - return { baseRef: null, files: [] }; - } - return result; - } catch (error) { - deps.appLog.warn({ err: error, agentId: id }, "Agent diff failed"); - return reply.code(500).send({ error: "Failed to compute diff." }); - } + deps.observeCheckout?.(agent); + const query = request.query as { + ignoreWhitespace?: string; + includeUncommitted?: string; + }; + return serveCheckoutView( + agent, + { + kind: "diff", + baseBranch: null, + ignoreWhitespace: query.ignoreWhitespace !== "false", + includeUncommitted: query.includeUncommitted !== "false", + }, + deps.agentManager, + reply + ); }); app.get("/api/v1/agents/:id/diff/file", async (request, reply) => { @@ -369,35 +361,18 @@ export async function registerAgentLifecycleRoutes( return reply.code(404).send({ error: "Agent not found." }); } - const target = agentDiffTarget(agent); - if (!target) { - return reply - .code(404) - .send({ error: "Agent has no associated worktree." }); - } - const { path: worktreePath, baseRef } = target; - - try { - const ignoreWhitespace = query.ignoreWhitespace !== "false"; - const includeUncommitted = query.includeUncommitted !== "false"; - const result = await getAgentFileDiff( - worktreePath, - baseRef, - query.path, - undefined, - { ignoreWhitespace, includeUncommitted } - ); - if (!result) { - return reply.code(404).send({ error: "File not found in diff." }); - } - return result; - } catch (error) { - deps.appLog.warn( - { err: error, agentId: id, filePath: query.path }, - "Agent file diff failed" - ); - return reply.code(500).send({ error: "Failed to compute file diff." }); - } + return serveCheckoutView( + agent, + { + kind: "fileDiff", + path: query.path, + baseBranch: null, + ignoreWhitespace: query.ignoreWhitespace !== "false", + includeUncommitted: query.includeUncommitted !== "false", + }, + deps.agentManager, + reply + ); }); app.get("/api/v1/agents/:id/diff/image", async (request, reply) => { @@ -428,39 +403,18 @@ export async function registerAgentLifecycleRoutes( return reply.code(404).send({ error: "Agent not found." }); } - const target = agentDiffTarget(agent); - if (!target) { - return reply - .code(404) - .send({ error: "Agent has no associated worktree." }); - } - const { path: worktreePath, baseRef } = target; - const includeUncommitted = query.includeUncommitted !== "false"; - - try { - const result = await getAgentDiffImage( - worktreePath, - baseRef, - query.path, + return serveCheckoutView( + agent, + { + kind: "image", + path: query.path, side, - { includeUncommitted } - ); - if (!result.ok) { - return reply - .code(result.reason === "too-large" ? 413 : 404) - .send({ error: "Image not available." }); - } - - reply.header("X-Content-Type-Options", "nosniff"); - reply.header("Cache-Control", "private, max-age=30"); - return reply.type(result.contentType).send(result.buffer); - } catch (error) { - deps.appLog.warn( - { err: error, agentId: id, filePath: query.path }, - "Agent diff image failed" - ); - return reply.code(500).send({ error: "Failed to read image." }); - } + baseBranch: null, + includeUncommitted: query.includeUncommitted !== "false", + }, + deps.agentManager, + reply + ); }); app.post("/api/v1/agents/:id/diff/comment", async (request, reply) => { @@ -511,22 +465,22 @@ export async function registerAgentLifecycleRoutes( return reply.code(404).send({ error: "Agent not found." }); } - const target = agentDiffTarget(agent); - if (!target) { - return reply - .code(404) - .send({ error: "Agent has no associated worktree." }); - } - const { path: worktreePath, baseRef } = target; - let fileDiff; try { - fileDiff = await getAgentFileDiff(worktreePath, baseRef, body.filePath); + fileDiff = await deps.agentManager.viewCheckout(agent, { + kind: "fileDiff", + path: body.filePath, + baseBranch: null, + includeUncommitted: true, + ignoreWhitespace: false, + }); } catch (error) { deps.appLog.warn( { err: error, agentId: id, filePath: body.filePath }, "Diff comment: failed to get file diff" ); + if (error instanceof AgentError) + return deps.handleAgentError(reply, error); return reply.code(500).send({ error: "Failed to retrieve diff." }); } diff --git a/apps/server/src/routes/agents/shared.ts b/apps/server/src/routes/agents/shared.ts index bcebbd294..a7eea0d46 100644 --- a/apps/server/src/routes/agents/shared.ts +++ b/apps/server/src/routes/agents/shared.ts @@ -49,6 +49,7 @@ export type AgentRouteDeps = { agentId: string, stream: NodeJS.WritableStream ) => () => void; + observeCheckout?: (agent: AgentRecord) => void; diffStatsRefresher: DiffStatsRefresher; onArchivedAgentsDeleted: (deletedIds: string[]) => void; onArchiveError: (agentId: string, error: unknown) => void; diff --git a/apps/server/src/routes/agents/workspace-routes.ts b/apps/server/src/routes/agents/workspace-routes.ts index 8153f4854..4a1df243b 100644 --- a/apps/server/src/routes/agents/workspace-routes.ts +++ b/apps/server/src/routes/agents/workspace-routes.ts @@ -1,72 +1,13 @@ -import { openWorkspaceDirectory } from "../../files/workspace-directory.js"; -import { ignoredWorkspacePaths } from "../../files/workspace-ignore.js"; -import { createWorkspaceFileIndexer } from "../../files/workspace-file-index.js"; -import { constants } from "node:fs"; -import { lstat, open, realpath } from "node:fs/promises"; -import path from "node:path"; import type { FastifyInstance } from "fastify"; -import { imageDimensionsFromBuffer } from "../../files/image-dimensions.js"; -import { detectFileType } from "../../files/file-type.js"; +import { remotePlacement, type WorkspaceView } from "@dispatch/runner-protocol"; import { agentWorkspaceDir } from "../../agents/workspace-target.js"; +import { serveCheckoutView } from "./checkout-response.js"; import type { AgentRouteDeps } from "./shared.js"; -const MAX_ENTRIES = 500; -const MAX_BYTES = 1_048_576; -class WorkspaceError extends Error { - constructor( - message: string, - readonly status = 400 - ) { - super(message); - } -} - -// Do not follow links, including directory links. Recheck after opening a file -// as well, so an ordinary concurrent rename cannot return unrelated contents. -async function resolveEntry(root: string, relative: string): Promise { - if ( - path.isAbsolute(relative) || - relative.includes("\\") || - relative.includes("\0") - ) { - throw new WorkspaceError("Invalid workspace path."); - } - const parts = relative ? relative.split("/") : []; - if ( - parts.some( - (part) => - !part || part === "." || part === ".." || part.toLowerCase() === ".git" - ) - ) { - throw new WorkspaceError("Invalid workspace path."); - } - let target = root; - for (const part of parts) { - target = path.join(target, part); - if ((await lstat(target)).isSymbolicLink()) { - throw new WorkspaceError( - "Symbolic links are not followed in Files.", - 403 - ); - } - } - const resolved = await realpath(target); - const inside = path.relative(root, resolved); - if ( - inside.startsWith(".." + path.sep) || - inside === ".." || - path.isAbsolute(inside) - ) { - throw new WorkspaceError("Path is outside the workspace.", 403); - } - return resolved; -} - export async function registerAgentWorkspaceRoutes( app: FastifyInstance, - deps: Pick + deps: Pick ): Promise { - const fileIndex = createWorkspaceFileIndexer(); app.get("/api/v1/agents/:id/workspace", async (request, reply) => { const { id } = request.params as { id: string }; const query = request.query as { @@ -86,203 +27,28 @@ export async function registerAgentWorkspaceRoutes( } const agent = await deps.agentManager.getAgent(id); if (!agent) return reply.code(404).send({ error: "Agent not found." }); - const workspace = agentWorkspaceDir(agent); + const workspace = remotePlacement(agent.cwd) + ? agent.cwd + : agentWorkspaceDir(agent); if (!workspace) return reply.code(404).send({ error: "This agent has no workspace." }); if (query.workspace !== workspace) return reply .code(409) .send({ error: "Workspace changed. Reopen Files to continue." }); + deps.observeCheckout?.(agent); reply.header("Cache-Control", "no-store"); - try { - const root = await realpath(workspace); - if (query.index === "true") { - const generation = - typeof query.generation === "string" - ? query.generation.slice(0, 64) - : "initial"; - return await fileIndex(root, generation); - } - const relative = (query.path as string | undefined) ?? ""; - const target = await resolveEntry(root, relative); - if (query.file !== "true") { - const { directory, verify } = await openWorkspaceDirectory( - root, - target - ); - const entries: Array<{ - name: string; - path: string; - kind: "directory" | "file" | "link" | "other"; - }> = []; - const visible: typeof entries = []; - let truncated = false; - let scanned = 0; - const deadline = Date.now() + 2000; - const flush = async () => { - const ignored = await ignoredWorkspacePaths( - target, - entries.map((entry) => entry.name) - ); - visible.push(...entries.filter((entry) => !ignored.has(entry.name))); - entries.length = 0; - }; - for await (const entry of directory) { - if (entry.name.toLowerCase() === ".git") continue; - if (++scanned > 20_000 || Date.now() > deadline) { - truncated = true; - break; - } - entries.push({ - name: entry.name, - path: relative ? `${relative}/${entry.name}` : entry.name, - kind: entry.isSymbolicLink() - ? "link" - : entry.isDirectory() - ? "directory" - : entry.isFile() - ? "file" - : "other", - }); - if (entries.length === 500) { - await flush(); - if (visible.length > MAX_ENTRIES) { - truncated = true; - break; - } + const path = typeof query.path === "string" ? query.path : ""; + const view: WorkspaceView = + query.index === "true" + ? { + kind: "index", + generation: + typeof query.generation === "string" + ? query.generation.slice(0, 64) + : "initial", } - } - await verify(); - if (entries.length) await flush(); - await verify(); - if (visible.length > MAX_ENTRIES) truncated = true; - visible.sort( - (a, b) => - Number(b.kind === "directory") - Number(a.kind === "directory") || - a.name.localeCompare(b.name) - ); - return { entries: visible.slice(0, MAX_ENTRIES), truncated }; - } - const initial = await lstat(target); - if (!initial.isFile()) - throw new WorkspaceError("Only regular files can be previewed."); - const handle = await open( - target, - constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK - ); - try { - const stat = await handle.stat(); - if (!stat.isFile()) - throw new WorkspaceError("Only regular files can be previewed."); - const checked = await resolveEntry(root, relative); - const current = await lstat(checked); - if ( - checked !== target || - stat.ino !== current.ino || - stat.dev !== current.dev - ) { - throw new WorkspaceError( - "File changed while opening. Refresh to retry.", - 409 - ); - } - if (stat.size > MAX_BYTES) - return { - kind: "unsupported", - size: stat.size, - message: "Preview limited to files up to 1 MiB.", - }; - const buffer = Buffer.alloc(MAX_BYTES + 1); - let length = 0; - while (length < buffer.length) { - const { bytesRead } = await handle.read( - buffer, - length, - buffer.length - length, - null - ); - if (!bytesRead) break; - length += bytesRead; - } - if (length > MAX_BYTES) - return { - kind: "unsupported", - size: length, - message: "File grew beyond the 1 MiB preview limit.", - }; - const data = buffer.subarray(0, length); - // Keep image preview dependency-free and bounded. Animated formats are - // deliberately excluded from this first read-only explorer. - const detected = detectFileType(data, relative); - if (detected.ok && detected.mimeType === "image/svg+xml") { - return { - kind: "svg", - size: length, - text: data.toString("utf8"), - src: `data:image/svg+xml;base64,${data.toString("base64")}`, - }; - } - if ( - detected.ok && - detected.mimeType.startsWith("image/") && - detected.mimeType !== "image/svg+xml" - ) { - const dimensions = imageDimensionsFromBuffer(data); - const staticImage = - detected.mimeType === "image/jpeg" || - (detected.mimeType === "image/png" && - !data.includes(Buffer.from("acTL"))); - if ( - staticImage && - dimensions && - dimensions.width * dimensions.height <= 16_000_000 - ) { - return { - kind: "image", - size: length, - src: `data:${detected.mimeType};base64,${data.toString("base64")}`, - }; - } - return { - kind: "unsupported", - size: length, - message: - "MVP image previews support static PNG/JPEG with readable dimensions up to 16 megapixels.", - }; - } - try { - if (data.includes(0)) throw new Error("binary"); - return { - kind: "text", - size: length, - text: new TextDecoder("utf-8", { fatal: true }).decode(data), - }; - } catch { - return { - kind: "unsupported", - size: length, - message: "Binary or non-UTF-8 file. Preview unavailable.", - }; - } - } finally { - await handle.close(); - } - } catch (error) { - if (error instanceof WorkspaceError) - return reply.code(error.status).send({ error: error.message }); - const code = (error as NodeJS.ErrnoException).code; - if (code === "ESTALE") - return reply - .code(409) - .send({ error: "Directory changed. Refresh to retry." }); - if (code === "ENOENT" || code === "ENOTDIR") - return reply - .code(404) - .send({ error: "File or workspace no longer exists." }); - if (code === "EACCES" || code === "EPERM" || code === "ELOOP") - return reply.code(403).send({ error: "This path cannot be read." }); - request.log.warn({ err: error }, "Workspace read failed"); - return reply.code(500).send({ error: "Unable to read workspace." }); - } + : { kind: query.file === "true" ? "preview" : "directory", path }; + return serveCheckoutView(agent, view, deps.agentManager, reply); }); } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1f5d38a30..0525247ec 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,3 +1,5 @@ +import { CheckoutObservers } from "./agents/checkout-observers.js"; +import { readAgentStats } from "./agents/checkout-runner.js"; import { discoverSlackLinkOrigins } from "./notifications/slack-link-origins.js"; import { QuestionAlerts } from "./notifications/question-alerts.js"; import { notifyForm } from "./notifications/notify-form.js"; @@ -391,21 +393,16 @@ const pullRequests = new PullRequestRefresher({ warn: (error) => app.log.warn({ err: error }, "PR status refresh failed"), }); const diffStatsRefresher = new DiffStatsRefresher({ - getAgent: async (id) => { - const agent = await agentManager.getAgent(id); - if (!agent) return null; - return { - worktreePath: agent.worktreePath, - cwd: agent.cwd, - baseBranch: agent.baseBranch, - workspacePath: agent.workspacePath, - workspaceBaseBranch: agent.workspaceBaseBranch, - }; - }, + getAgent: (id) => agentManager.getAgent(id), + computeAgentStats: (id, agent) => readAgentStats(id, agent, remoteRunner), publishEvent: (event) => uiEventBroker.publish(event), logger: app.log, tracker: gitRefreshTracker, }); +const checkoutObservers = new CheckoutObservers(remoteRunner, (id) => { + uiEventBroker.publish({ type: "agent.checkout_changed", agentId: id }); + void diffStatsRefresher.signal(id); +}); agentManager.attachDiffStatsRefresher(diffStatsRefresher); const loginLinkStore = new LoginLinkStore(); const jobService = new JobService(pool, agentManager, app.log, config); @@ -1343,6 +1340,7 @@ async function registerRoutes() { addStreamViewer: (agentId, stream) => streamManager.addViewer(agentId, stream), diffStatsRefresher, + observeCheckout: (agent) => checkoutObservers.observe(agent), pullRequests, riskExplanations: new RiskExplanations({ pool, @@ -1558,6 +1556,7 @@ async function cleanupAppResources(): Promise { return; } shuttingDown = true; + checkoutObservers.close(); remoteRunner?.close(); const stage = async (name: string, close: () => Promise) => { app.log.info({ stage: name }, "Shutdown stage started"); diff --git a/apps/server/src/shared/git/agent-diff.ts b/apps/server/src/shared/git/agent-diff.ts index 35ffd0878..6a7e3a58b 100644 --- a/apps/server/src/shared/git/agent-diff.ts +++ b/apps/server/src/shared/git/agent-diff.ts @@ -393,6 +393,22 @@ export async function getAgentFileDiff( if (entries.length === 0) { if (includeUncommitted) { + const listed = await run( + "git", + [ + "-C", + worktreePath, + "--literal-pathspecs", + "ls-files", + "--others", + "--exclude-standard", + "-z", + "--", + filePath, + ], + { timeoutMs: GIT_TIMEOUT_MS, trimOutput: false } + ); + if (!listed.stdout.split("\0").includes(filePath)) return null; const { lines, content } = await readUntrackedFile( worktreePath, filePath diff --git a/apps/server/src/shared/git/diff-file-rules.ts b/apps/server/src/shared/git/diff-file-rules.ts index 91e70eb62..29eb354cf 100644 --- a/apps/server/src/shared/git/diff-file-rules.ts +++ b/apps/server/src/shared/git/diff-file-rules.ts @@ -1,4 +1,5 @@ -import { lstat, readFile } from "node:fs/promises"; +import { openRegularFile } from "../../files/open-workspace-file.js"; +import { realpath } from "node:fs/promises"; import path from "node:path"; const EXCLUDED_BASENAMES = new Set([ @@ -71,14 +72,34 @@ export async function readUntrackedFile( return { lines: 0, content: null }; } try { - const info = await lstat(fullPath); - if (!info.isFile()) return { lines: 0, content: null }; - if (info.size === 0) return { lines: 0, content: null }; - if (info.size > UNTRACKED_MAX_BYTES) return { lines: 0, content: null }; - const buffer = await readFile(fullPath); - if (looksBinary(buffer)) return { lines: 0, content: null }; - const text = buffer.toString("utf8"); - return { lines: countLines(text), content: text }; + const file = await openRegularFile( + await realpath(realWorktree), + path.relative(realWorktree, fullPath).split(path.sep) + ); + try { + const info = await file.stat(); + if (!info.isFile()) return { lines: 0, content: null }; + if (info.size === 0) return { lines: 0, content: null }; + if (info.size > UNTRACKED_MAX_BYTES) return { lines: 0, content: null }; + const bytes = Buffer.alloc(info.size); + let offset = 0; + while (offset < bytes.length) { + const { bytesRead } = await file.read( + bytes, + offset, + bytes.length - offset, + offset + ); + if (!bytesRead) break; + offset += bytesRead; + } + const buffer = bytes.subarray(0, offset); + if (looksBinary(buffer)) return { lines: 0, content: null }; + const text = buffer.toString("utf8"); + return { lines: countLines(text), content: text }; + } finally { + await file.close(); + } } catch { return { lines: 0, content: null }; } diff --git a/apps/server/src/shared/git/diff-image.ts b/apps/server/src/shared/git/diff-image.ts index d6140a9fc..541f3aef4 100644 --- a/apps/server/src/shared/git/diff-image.ts +++ b/apps/server/src/shared/git/diff-image.ts @@ -1,6 +1,6 @@ import { spawn } from "node:child_process"; -import { constants } from "node:fs"; -import { lstat, open, type FileHandle } from "node:fs/promises"; +import { openRegularFile } from "../../files/open-workspace-file.js"; +import { realpath, type FileHandle } from "node:fs/promises"; import path from "node:path"; import { DIFF_IMAGE_MAX_BYTES, type DiffImageInfo } from "@dispatch/shared"; @@ -31,13 +31,14 @@ export type ImageSide = "old" | "new"; * worth of images; paths absent from the tree simply don't come back, which is * exactly the "did not exist on this side" answer the caller wants. */ -async function treeBlobSizes( +type ImageVersion = { size: number; revision: string }; +async function treeImages( worktreePath: string, ref: string, paths: string[], run: CommandRunner -): Promise> { - const sizes = new Map(); +): Promise> { + const sizes = new Map(); if (paths.length === 0) return sizes; const result = await run( "git", @@ -52,20 +53,33 @@ async function treeBlobSizes( const meta = record.slice(0, tabIndex).trim().split(/\s+/); const size = Number.parseInt(meta[3] ?? "", 10); if (!Number.isFinite(size)) continue; - sizes.set(record.slice(tabIndex + 1), size); + sizes.set(record.slice(tabIndex + 1), { size, revision: meta[2]! }); } return sizes; } -async function worktreeFileSize( +async function worktreeImageVersion( worktreePath: string, filePath: string -): Promise { +): Promise { const resolved = resolveInsideWorktree(worktreePath, filePath); if (!resolved) return null; try { - const info = await lstat(resolved); - return info.isFile() ? info.size : null; + const handle = await openRegularFile( + await realpath(worktreePath), + path.relative(worktreePath, resolved).split(path.sep) + ); + try { + const info = await handle.stat({ bigint: true }); + return info.isFile() + ? { + size: Number(info.size), + revision: [info.ino, info.ctimeNs, info.mtimeNs].join("-"), + } + : null; + } finally { + await handle.close(); + } } catch { return null; } @@ -113,24 +127,28 @@ export async function collectImageInfo( .map((e) => e.path); const [oldSizes, headSizes] = await Promise.all([ - treeBlobSizes(worktreePath, mergeBaseSha, oldPaths, run), + treeImages(worktreePath, mergeBaseSha, oldPaths, run), options.includeUncommitted - ? Promise.resolve(new Map()) - : treeBlobSizes(worktreePath, "HEAD", newPaths, run), + ? Promise.resolve(new Map()) + : treeImages(worktreePath, "HEAD", newPaths, run), ]); for (const entry of entries) { - const oldSize = + const oldSide = entry.status === "added" ? null : (oldSizes.get(entry.oldPath ?? entry.path) ?? null); - let newSize: number | null = null; + let newSide: ImageVersion | null = null; if (entry.status !== "deleted") { - newSize = options.includeUncommitted - ? await worktreeFileSize(worktreePath, entry.path) + newSide = options.includeUncommitted + ? await worktreeImageVersion(worktreePath, entry.path) : (headSizes.get(entry.path) ?? null); } - info.set(entry.path, { oldSize, newSize }); + info.set(entry.path, { + oldSize: oldSide?.size ?? null, + newSize: newSide?.size ?? null, + revision: [oldSide?.revision, newSide?.revision].join("."), + }); } return info; @@ -160,7 +178,7 @@ export async function readImageSide( if (fromWorktree) { const resolved = resolveInsideWorktree(worktreePath, filePath); if (!resolved) return { ok: false, reason: "not-found" }; - return await readWorktreeImage(resolved, contentType); + return await readWorktreeImage(worktreePath, resolved, contentType); } const buffer = await gitShowBinary(worktreePath, `${ref}:${filePath}`); @@ -180,12 +198,16 @@ export async function readImageSide( * two calls, which would read past both the containment check and the cap. */ async function readWorktreeImage( + root: string, fullPath: string, contentType: string ): Promise { let handle: FileHandle | null = null; try { - handle = await open(fullPath, constants.O_RDONLY | constants.O_NOFOLLOW); + handle = await openRegularFile( + await realpath(root), + path.relative(root, fullPath).split(path.sep) + ); const info = await handle.stat(); if (!info.isFile()) return { ok: false, reason: "not-found" }; if (info.size > DIFF_IMAGE_MAX_BYTES) { diff --git a/apps/server/test/agent-diff.test.ts b/apps/server/test/agent-diff.test.ts index 6952b21cc..424aa96dc 100644 --- a/apps/server/test/agent-diff.test.ts +++ b/apps/server/test/agent-diff.test.ts @@ -476,6 +476,7 @@ describe("getAgentFileDiff (force load)", () => { const joined = args.join(" "); if (joined.includes("rev-parse --verify")) return ok(BASE_REF); if (joined.includes("merge-base")) return ok(MERGE_BASE_SHA); + if (args.includes("ls-files")) return ok("new.ts\0"); if (joined.includes("--numstat")) return ok(""); if (joined.includes("--name-status")) return ok(""); if (joined.includes("-U3")) return ok(""); diff --git a/apps/server/test/diff-image.test.ts b/apps/server/test/diff-image.test.ts index a2b1c547c..465148f23 100644 --- a/apps/server/test/diff-image.test.ts +++ b/apps/server/test/diff-image.test.ts @@ -124,12 +124,14 @@ describe("getAgentDiff image metadata", () => { const added = byPath.get("assets/added.png")!; expect(added.image).toEqual({ + revision: expect.any(String), oldSize: null, newSize: expect.any(Number), }); const deleted = byPath.get("assets/gone.png")!; expect(deleted.image).toEqual({ + revision: expect.any(String), oldSize: expect.any(Number), newSize: null, }); @@ -141,6 +143,24 @@ describe("getAgentDiff image metadata", () => { expect(untracked.image?.newSize).toBeGreaterThan(0); }); + it("refreshes a same-size image edit without invalidating unchanged images", async () => { + const read = async () => + (await getAgentDiff(repo, "main"))!.files.find( + (f) => f.path === "assets/logo.png" + )!.image!; + const before = await read(); + expect(await read()).toEqual(before); + const filename = path.join(repo, "assets/logo.png"); + const original = await readFile(filename); + try { + await writeFile(filename, Buffer.alloc(before.newSize!, 7)); + const after = await read(); + expect(after.newSize).toEqual(before.newSize); + expect(after.revision).not.toBe(before.revision); + } finally { + await writeFile(filename, original); + } + }); it("leaves non-image files without image metadata", async () => { const result = await getAgentDiff(repo, "main"); for (const file of result!.files) { diff --git a/apps/server/test/runner-checkout-watches.test.ts b/apps/server/test/runner-checkout-watches.test.ts new file mode 100644 index 000000000..826c9e70c --- /dev/null +++ b/apps/server/test/runner-checkout-watches.test.ts @@ -0,0 +1,79 @@ +import { PassThrough } from "node:stream"; +import { expect, it, vi } from "vitest"; +import { CheckoutObservers } from "../src/agents/checkout-observers.js"; +import { SharedCheckoutWatches } from "../src/agents/checkout-watch.js"; + +it("shares one watch between readers and reopens after an OS watch fails", () => { + const close = vi.fn(); + const open = vi.fn( + (_root: string, _changed: () => void, _closed: () => void) => close + ); + const watches = new SharedCheckoutWatches(open); + const first = vi.fn(), + second = vi.fn(), + end = vi.fn(); + const unsubscribe = watches.subscribe("/checkout", first, end); + watches.subscribe("/checkout", second, end); + expect(open).toHaveBeenCalledTimes(1); + open.mock.calls[0]![1](); + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledTimes(1); + unsubscribe(); + expect(close).not.toHaveBeenCalled(); + open.mock.calls[0]![2](); + expect(end).toHaveBeenCalledTimes(1); + watches.subscribe("/checkout", first, end)(); + expect(open).toHaveBeenCalledTimes(2); + expect(close).toHaveBeenCalledTimes(1); +}); +it("reconnects interested sessions and releases leases that stop receiving reads", async () => { + vi.useFakeTimers(); + let ready!: (id: string) => void; + const unsubscribe = vi.fn(); + const requestSession = vi.fn(async () => ({ + channel: new PassThrough(), + value: true, + })); + const changed = vi.fn(); + const observers = new CheckoutObservers( + { + onConnectionChange(listener) { + ready = listener; + return unsubscribe; + }, + requestSession, + }, + changed + ); + const agent = { + id: "author", + cwd: "runner://alpha/@session", + worktreePath: null, + baseBranch: null, + }; + try { + observers.observe(agent); + observers.observe(agent); + expect(requestSession).toHaveBeenCalledTimes(1); + const channel = (await requestSession.mock.results[0]!.value).channel; + channel.write("1"); + channel.write("1"); + await vi.advanceTimersByTimeAsync(150); + expect(changed.mock.calls).toEqual([["author"]]); + ready("beta"); + expect(channel.destroyed).toBe(false); + ready("alpha"); + expect(channel.destroyed).toBe(true); + expect(changed).toHaveBeenCalledTimes(2); + observers.observe(agent); + const replacement = (await requestSession.mock.results[1]!.value).channel; + await vi.advanceTimersByTimeAsync(95_000); + expect(replacement.destroyed).toBe(true); + ready("alpha"); + expect(changed).toHaveBeenCalledTimes(2); + } finally { + observers.close(); + vi.useRealTimers(); + } + expect(unsubscribe).toHaveBeenCalledOnce(); +}); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index d2f65191e..83f0145be 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -12,6 +12,7 @@ import { sessionCommandId, isOpaqueId, isCheckoutReply, + isCheckoutViewData, remotePlacement, workspaceLocator, } from "@dispatch/runner-protocol"; @@ -110,6 +111,7 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () engineManagement: true, githubManagement: true, checkoutInspection: true, + checkoutViews: true, sharedWorktree: true, }; expect(parseReadyFrame(managed)).toEqual(managed); @@ -138,6 +140,38 @@ it("validates runner-scoped GitHub command payloads", () => { ).not.toBeNull(); }); +it("validates the checkout view commands and matching results", () => { + const parse = (command: unknown) => + parseServiceFrame({ type: "request", id: "read", command }); + const session = { agentId: "author", workspace: "@session" }; + const query = { kind: "preview", path: "src/example.ts" } as const; + expect(parse({ ...session, kind: "watchCheckout" })).not.toBeNull(); + expect(parse({ ...session, kind: "viewCheckout", query })).not.toBeNull(); + for (const path of ["/etc/config", "../elsewhere", "a/.git/config", "a//b"]) + expect( + parse({ ...session, kind: "viewCheckout", query: { ...query, path } }) + ).toBeNull(); + expect( + isCheckoutViewData(query, { kind: "text", text: "contents", size: 8 }) + ).toBe(true); + expect( + isCheckoutViewData(query, { + kind: "image", + src: "https://example.com", + size: 8, + }) + ).toBe(false); + expect( + isCheckoutViewData( + { kind: "directory", path: "src" }, + { + truncated: false, + entries: [{ kind: "file", name: "A", path: "other/A" }], + } + ) + ).toBe(false); +}); + it("validates checkout queries, results and borrowed launches", () => { const parse = (command: unknown) => parseServiceFrame({ type: "request", id: "request-1", command }); diff --git a/apps/server/test/workspace-directory-race.test.ts b/apps/server/test/workspace-directory-race.test.ts index 7128f6cbd..25a04dae1 100644 --- a/apps/server/test/workspace-directory-race.test.ts +++ b/apps/server/test/workspace-directory-race.test.ts @@ -12,6 +12,7 @@ import { } from "node:fs/promises"; import path from "node:path"; import { tmpdir } from "node:os"; +import { readAgentView } from "../src/agents/checkout-runner.js"; import { registerAgentWorkspaceRoutes } from "../src/routes/agents/workspace-routes.js"; import { buildWorkspaceFileIndex } from "../src/files/workspace-file-index.js"; import type { AgentRouteDeps } from "../src/routes/agents/shared.js"; @@ -62,6 +63,7 @@ test("directory route rejects replacement with an outside symlink before open", try { await registerAgentWorkspaceRoutes(app, { agentManager: { + viewCheckout: readAgentView, getAgent: async () => ({ cwd: root, workspacePath: null, diff --git a/apps/server/test/workspace-routes.test.ts b/apps/server/test/workspace-routes.test.ts index 21c4bc2c8..fd61787d0 100644 --- a/apps/server/test/workspace-routes.test.ts +++ b/apps/server/test/workspace-routes.test.ts @@ -5,6 +5,7 @@ import { mkdtemp, mkdir, writeFile, symlink, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { readAgentView } from "../src/agents/checkout-runner.js"; import { registerAgentWorkspaceRoutes } from "../src/routes/agents/workspace-routes.js"; import type { AgentRouteDeps } from "../src/routes/agents/shared.js"; @@ -22,6 +23,7 @@ describe("workspace browsing", () => { app = Fastify(); await registerAgentWorkspaceRoutes(app, { agentManager: { + viewCheckout: readAgentView, getAgent: async (id: string) => id === "missing" ? null diff --git a/apps/web/src/components/app/changes-diff-section.tsx b/apps/web/src/components/app/changes-diff-section.tsx index 8047209ba..f4922a02a 100644 --- a/apps/web/src/components/app/changes-diff-section.tsx +++ b/apps/web/src/components/app/changes-diff-section.tsx @@ -443,6 +443,7 @@ function FileDiffContent({ if (file.image) { return ( + {error.message} + {data && " Showing the last loaded changes."} +

    + ); if (files.length === 0) { return (
    {toolbar} -
    - -

    - {hideTestFiles && data?.files.length - ? "No non-test changes" - : "No changes yet"} -

    -
    + {refreshError} + {!error && ( +
    + +

    + {hideTestFiles && data?.files.length + ? "No non-test changes" + : "No changes yet"} +

    +
    + )}
    ); } @@ -546,6 +559,7 @@ export const ChangesTab = memo(function ChangesTab({ return (
    {toolbar} + {refreshError}
    (null); @@ -182,7 +187,13 @@ export function DiffImageView({ const oldSide: SideState = { src: agentId && hasOld - ? imageUrl(agentId, oldPath ?? filePath, "old", includeUncommitted) + ? imageUrl( + agentId, + oldPath ?? filePath, + "old", + includeUncommitted, + revision + ) : null, bytes: image.oldSize, dimensions: oldDim, @@ -193,7 +204,7 @@ export function DiffImageView({ const newSide: SideState = { src: agentId && hasNew - ? imageUrl(agentId, filePath, "new", includeUncommitted) + ? imageUrl(agentId, filePath, "new", includeUncommitted, revision) : null, bytes: image.newSize, dimensions: newDim, diff --git a/apps/web/src/components/app/files-pane.tsx b/apps/web/src/components/app/files-pane.tsx index 50574e4e3..e19fd5e88 100644 --- a/apps/web/src/components/app/files-pane.tsx +++ b/apps/web/src/components/app/files-pane.tsx @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import { useAtom } from "jotai"; import { filesBrowserStateFamily } from "./files-browser-state"; import { WorkspaceSvgPreview } from "./workspace-svg-preview"; @@ -27,7 +28,7 @@ import { import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { api } from "@/lib/api"; +import { api, ApiError } from "@/lib/api"; import { FileActions } from "./file-lightbox-actions"; import { cn } from "@/lib/utils"; @@ -52,6 +53,7 @@ type Row = | { entry: Entry; depth: number } | { message: string; depth: number; retry?: string }; const queryOptions = { + refetchInterval: 30_000, staleTime: Infinity, gcTime: 30_000, refetchOnWindowFocus: false, @@ -306,7 +308,6 @@ function WorkspaceFiles({ const browse = browserState.browse ?? !selected; const setBrowse = (browse: boolean) => setBrowserState((old) => ({ ...old, browse })); - const indexGeneration = useRef("initial"); const [search, setSearch] = useState(filter.trim().toLowerCase()); useEffect(() => { const timer = setTimeout(() => setSearch(filter.trim().toLowerCase()), 180); @@ -341,13 +342,15 @@ function WorkspaceFiles({ enabled: !!selected, ...queryOptions, }); + const keepPreview = + !preview.isError || + (preview.error instanceof ApiError && preview.error.status === 503); const fileIndex = useQuery({ queryKey: [...prefix, "index"], queryFn: ({ signal }) => - api( - url("") + "&index=true&generation=" + indexGeneration.current, - { signal } - ), + api(url("") + "&index=true&generation=" + Date.now(), { + signal, + }), enabled: !!search, ...queryOptions, }); @@ -380,7 +383,8 @@ function WorkspaceFiles({ } if (query.isError) { rows.push({ depth, message: query.error.message, retry: directory }); - return; + if (!(query.error instanceof ApiError && query.error.status === 503)) + return; } if (!query.data) return; for (const entry of query.data.entries) { @@ -401,9 +405,13 @@ function WorkspaceFiles({ rows.length = 0; if (fileIndex.isPending) rows.push({ depth: 0, message: "Finding filenames…" }); - else if (fileIndex.isError) + if (fileIndex.isError) rows.push({ depth: 0, message: fileIndex.error.message, retry: "index" }); - else + if ( + fileIndex.data && + (!fileIndex.isError || + (fileIndex.error instanceof ApiError && fileIndex.error.status === 503)) + ) for (const path of matches.slice(0, 200)) rows.push({ depth: 0, @@ -452,15 +460,21 @@ function WorkspaceFiles({
    -
    - {workspace.split("/").filter(Boolean).at(-1)} -
    -
    - {workspace} -
    + {remotePlacement(workspace) ? ( +
    Session files
    + ) : ( + <> +
    + {workspace.split("/").filter(Boolean).at(-1)} +
    +
    + {workspace} +
    + + )}
    {!isSplit && !isMobile && (
    + {preview.isError && keepPreview && preview.data && ( +

    + {preview.error.message} Showing the last loaded preview. +

    + )} {preview.isPending ? (
    Loading preview…
    - ) : preview.isError ? ( + ) : preview.isError && (!keepPreview || !preview.data) ? (
    void; } { const queryClient = useQueryClient(); @@ -53,6 +54,7 @@ export function useAgentDiff( }, enabled: enabled && !!agentId, refetchOnWindowFocus: true, + refetchInterval: 30_000, staleTime: 5_000, }); @@ -64,7 +66,16 @@ export function useAgentDiff( } }, [agentId, queryClient]); - return { data: query.data, isLoading: query.isLoading, refresh }; + return { + data: + query.isError && + !(query.error instanceof ApiError && query.error.status === 503) + ? undefined + : query.data, + isLoading: query.isLoading, + error: query.error, + refresh, + }; } export function useAgentFileDiff( @@ -91,6 +102,7 @@ export function useAgentFileDiff( ); }, enabled: enabled && !!agentId && !!filePath, + refetchInterval: 30_000, staleTime: 10_000, }); diff --git a/apps/web/src/hooks/use-sse.test.ts b/apps/web/src/hooks/use-sse.test.ts index 5d26add06..0433e49a4 100644 --- a/apps/web/src/hooks/use-sse.test.ts +++ b/apps/web/src/hooks/use-sse.test.ts @@ -980,6 +980,16 @@ describe("useSSE message handling", () => { ).toEqual(["newer", "older"]); }); + it("refreshes only the changed session's Files and Changes queries", () => { + const { emit, invalidateQueries } = renderMessages(); + emit({ type: "agent.checkout_changed", agentId: "author" }); + expectInvalidatedSet(invalidateQueries, [ + ["workspace-files", "author"], + ["agent-diff-content", "author"], + ["agent-diff-file", "author"], + ["agent-diff", "author"], + ]); + }); it("refetches the state a snapshot does not carry", () => { // The snapshot payload only carries agents. Everything else the UI holds // could have changed during the gap. @@ -988,6 +998,10 @@ describe("useSSE message handling", () => { emit({ type: "snapshot", agents: [] }); expectInvalidatedSet(invalidateQueries, [ + ["workspace-files"], + ["agent-diff-content"], + ["agent-diff-file"], + ["agent-diff"], ["message-metadata"], ["routing-pending"], ["routing-experiment-settings"], diff --git a/apps/web/src/hooks/use-sse.ts b/apps/web/src/hooks/use-sse.ts index e01278146..aac62fdaf 100644 --- a/apps/web/src/hooks/use-sse.ts +++ b/apps/web/src/hooks/use-sse.ts @@ -67,6 +67,19 @@ import { MAC_APP_UPDATE_QUERY_KEY } from "@/hooks/use-mac-app-update"; const routingPendingKey = (streamId: string) => ["routing-pending", streamId] as const; +function invalidateCheckoutViews(client: QueryClient, agentId?: string) { + for (const key of [ + "workspace-files", + "agent-diff-content", + "agent-diff-file", + "agent-diff", + ]) { + void client.invalidateQueries({ + queryKey: agentId ? [key, agentId] : [key], + }); + } +} + /** Backoff bounds for self-driven reconnects after a fatal EventSource error. */ const INITIAL_RECONNECT_DELAY_MS = 1_000; const MAX_RECONNECT_DELAY_MS = 30_000; @@ -532,6 +545,7 @@ export function useSSE(authState: AuthState): void { ["agents"], sortAgentsByCreatedAtDesc(payload.agents) ); + invalidateCheckoutViews(queryClient); // A snapshot means a fresh SSE connection (initial or reconnect). // Invalidate the queries that aren't carried in the snapshot // payload — jobs and the cached release info — so they refetch. @@ -707,6 +721,10 @@ export function useSSE(authState: AuthState): void { return; } + if (payload.type === "agent.checkout_changed") { + invalidateCheckoutViews(queryClient, payload.agentId); + return; + } if (payload.type === "agent.diff_state_changed") { applyDiffStateChanged( queryClient, diff --git a/docs/03-api-spec.md b/docs/03-api-spec.md index d3b58f0f1..3d205dd02 100644 --- a/docs/03-api-spec.md +++ b/docs/03-api-spec.md @@ -138,6 +138,7 @@ Server-Sent Events stream. Used by the frontend for real-time UI updates. Event | ----------------------------- | ----------------------------------------------------------------- | | `snapshot` | Full agent list (sent on initial connection) | | `agent.upsert` | Single agent record (created or updated) | +| `agent.checkout_changed` | Reread open Files and Changes views for this agent ID | | `agent.diff_state_changed` | Diff stats for an agent (or `null` when cleared) | | `agent.deleted` | Agent ID that was deleted | | `files.changed` | Agent ID whose file list changed | diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index bf0bd585d..bfb16260c 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -224,6 +224,10 @@ established guest hosts continue. The client checks the service hostname. ### Inspecting and sharing a live checkout +Peers advertising `checkoutViews: true` support two session operations. `viewCheckout` takes an agent ID, workspace handle and a typed query for a directory, preview, file index, diff, file diff, image or stats. The runner resolves the agent’s bound checkout and returns a JSON result with `data` or a bounded error with `status` and `error`. Older peers surface an update prompt when a view needs this capability. + +`watchCheckout` uses the same binding and opens a channel. The runner sends a one-byte notification after watch setup and when the checkout changes. Each notification tells the consumer to reread its current view. Consumers may coalesce notifications. Closing the channel releases the subscription. The Linux implementation reads and watches as the workload account. Dispatch shares watches for active views, expires interest after 75 seconds without a read, and forwards invalidations over the existing browser event stream. An open view also reconciles every 30 seconds for missed filesystem notifications, including nested changes under a non-repository directory. Session history continues to use its existing replay protocol. + A service can inspect the checkout bound to an existing agent ID when the connected peer advertises `checkoutInspection: true`. The built-in local runner handles the same typed query in process. The Linux runner resolves the session binding and executes the inspection as the workload account. | Request | Reply | diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 4fba7a2d4..9082c1532 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -52,7 +52,7 @@ A native host can complete an accepted turn while its controller is down. A repl - The original field test failed when Dispatch passed a runner URL to local Git. The [placement parity test](../../e2e/remote-runner/owner-review.spec.ts) checks an unpublished commit and an untracked marker, reads it through each reviewer, archives the reviewer, and confirms the author retains access. Staged, unstaged and renamed path handling have [checkout-level tests](../../apps/server/test/checkout-inspection.test.ts). [Owner handler](../../apps/server/src/server/mcp-persona-handlers.ts) · [Changed-file collection](../../apps/server/src/personas/codeowners.ts) · [Review workflow](../code-owner-reviews.md) -**Display Changes and worktree state.** **Gap.** Base/ref resolution, file lists, diff stats, individual hunks, image diffs, repo identity and dirty/unmerged state read the checkout. Dispatch owns diff comments, rendering and refresh timing. Background refreshers must use the same placement as foreground requests. +**Display Changes and worktree state.** **Partial.** The runner supplies the diff, individual hunks, image bytes and stats from the session checkout. Dispatch stores comments and forwards checkout notifications to the browser. Repo identity and archive-time dirty/unmerged checks are separate operations. - Compare an untracked file, rename, image and dirty worktree against the same base. Handle a missing base without probing another machine. [Agent diff](../../apps/server/src/shared/git/agent-diff.ts) · [Agent routes](../../apps/server/src/routes/agents/lifecycle-routes.ts) · [Stats refresher](../../apps/server/src/agents/diff-stats-refresher.ts) @@ -60,7 +60,7 @@ A native host can complete an accepted turn while its controller is down. A repl - From a fresh runner account, sign in to GitHub, clone a private test repo, fetch a fork PR, and verify the identity used for push and PR creation. Sign out and verify isolation from other runners. Local-only review must also work with no published branch. [Search](../../apps/server/src/routes/runner-repositories.ts) · [PR reader](../../apps/server/src/agents/pull-request-reader.ts) · [Refresh](../../apps/server/src/agents/pull-request-refresher.ts) · [Risk inputs](../../apps/server/src/agents/merge-risk/sources.ts) -**Browse workspace files.** **Gap.** Directory listing, filtering/ignore rules, indexing and bounded text/image reads require the effective workspace. Preserve traversal, symlink, size and binary-file handling on the execution side. +**Browse workspace files.** **Present.** Both placements serve directory listings, ignored-file filtering, filename searches and bounded previews from the session checkout. Open tabs refresh on runner notifications and reconcile after a disconnect. - Expand a directory and open a file in the runner checkout. A path escaping the workspace is refused there. [Workspace routes](../../apps/server/src/routes/agents/workspace-routes.ts) · [File explorer](../file-explorer.md) diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 25d07b511..6ab464639 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -91,7 +91,7 @@ export function guestDiagnostics(name: GuestName) { /** Fault injection on the runner's TCP path (TLS stays end to end). */ export async function lane( - name: RunnerName, + name: GuestName, action: "sever" | "block" | "allow" | "status" ) { const res = await fetch( diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts index 9d9289523..6cf05aa79 100644 --- a/e2e/remote-runner/owner-review.spec.ts +++ b/e2e/remote-runner/owner-review.spec.ts @@ -7,6 +7,7 @@ import path from "node:path"; import { authHeaders, callMcpToolViaAPI, deleteAgentViaAPI } from "../helpers"; import { enrollViaUi, + lane, newSettledTurn, runnerRow, settledTurns, @@ -92,6 +93,93 @@ for (const placement of ["This Mac", "Linux runner"] as const) { directory, ]); } + // Leave both views mounted. Mutate outside the agent so ACP turn events + // and a navigation-triggered refetch cannot account for the update. + const files = await page.context().newPage(); + const changes = await page.context().newPage(); + const edit = (value: string) => { + if (remote) { + execFileSync( + "docker", + [ + "exec", + "-i", + "-u", + "1500:1500", + state.runners.scratch.container, + "tee", + "/var/lib/runner/sessions/" + author + "/review-marker.txt", + ], + { input: value, stdio: ["pipe", "ignore", "pipe"] } + ); + } else writeFileSync(path.join(tmp, "review-marker.txt"), value); + }; + try { + await files.goto( + "/agents/" + author + "/files?files.path=review-marker.txt", + { waitUntil: "domcontentloaded" } + ); + await changes.goto("/agents/" + author + "/changes", { + waitUntil: "domcontentloaded", + }); + const visibleOnBoth = async (value: string, timeout: number) => { + await Promise.all( + [files, changes].map((tab) => + expect(tab.getByText(value, { exact: false }).last()).toBeVisible( + { timeout } + ) + ) + ); + }; + await visibleOnBoth(marker, 20_000); + const live = randomUUID(); + edit(live); + await visibleOnBoth(live, 9_000); + if (remote) { + await lane("scratch", "block"); + try { + await expect + .poll(async () => (await runnerRow(request, "scratch"))?.status) + .toBe("offline"); + await expect( + files.getByText(/Showing the last loaded preview/) + ).toBeVisible({ timeout: 12_000 }); + await expect( + files.getByText(live, { exact: false }).last() + ).toBeVisible(); + edit(marker); + } finally { + await lane("scratch", "allow"); + } + } else edit(marker); + await visibleOnBoth(marker, 12_000); + for (const [label, tab] of [ + ["files", files], + ["changes", changes], + ] as const) { + const screenshot = testInfo.outputPath(label + ".png"); + await tab.screenshot({ path: screenshot }); + await testInfo.attach(label, { + path: screenshot, + contentType: "image/png", + }); + } + if (remote) { + await files.setViewportSize({ width: 390, height: 844 }); + await expect( + files.getByText(marker, { exact: false }).last() + ).toBeVisible(); + const screenshot = testInfo.outputPath("files-mobile.png"); + await files.screenshot({ path: screenshot }); + await testInfo.attach("Mobile runner file preview", { + path: screenshot, + contentType: "image/png", + }); + } + } finally { + await files.close(); + await changes.close(); + } const review = await callMcpToolViaAPI( request, author, diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 34fff2494..b6aafbe99 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -137,6 +137,12 @@ The portable session types cover commands received by the host, journal replay, and prompt receipts. Dispatch-specific host replies and event payloads are defined in `apps/server/src/agents/acp/host-protocol.ts`. +### Files and Changes + +When `ready.checkoutViews` is true, the service can send `viewCheckout` with the bound agent ID, workspace handle and a `CheckoutView` query. The runner resolves the checkout. Successful results carry a JSON string containing `{data}`. Use `isCheckoutViewData(query, data)` to validate the result. An expected read error carries `{status,error}`. The complete UTF-8 response is capped at 16 MiB. + +To receive changes, send `watchCheckout` with the same agent and workspace and open its channel. A one-byte pulse (ASCII `1`) signals that setup completed or that contents changed. Coalesce pulses and reread the current view. Release the channel when interest ends. After a transport disconnect, reopen the subscription and reread. Consumers that need durable turn history use session journal replay. + ### Surviving a daemon restart On Linux, the runner's session supervisor records each new host's identity diff --git a/packages/runner-protocol/src/checkout-view.ts b/packages/runner-protocol/src/checkout-view.ts new file mode 100644 index 000000000..7e2ceba82 --- /dev/null +++ b/packages/runner-protocol/src/checkout-view.ts @@ -0,0 +1,172 @@ +import { isRecord } from "./validation.js"; +import { validBranch } from "./checkout.js"; + +export type WorkspaceView = + | { kind: "directory" | "preview"; path: string } + | { kind: "index"; generation: string }; + +type DiffOptions = { baseBranch: string | null; includeUncommitted: boolean }; +export type CheckoutView = + | WorkspaceView + | (DiffOptions & + ( + | { kind: "stats" } + | { kind: "diff"; ignoreWhitespace: boolean } + | { kind: "fileDiff"; path: string; ignoreWhitespace: boolean } + | { kind: "image"; path: string; side: "old" | "new" } + )); + +function relative(path: unknown) { + return ( + typeof path === "string" && + path.length <= 4096 && + !path.includes("\\") && + !path.includes("\0") && + path + .split("/") + .every( + (part) => + part && part !== "." && part !== ".." && part.toLowerCase() !== ".git" + ) + ); +} + +export function isCheckoutView(value: unknown): value is CheckoutView { + if (!isRecord(value)) return false; + if (value.kind === "index") + return ( + typeof value.generation === "string" && value.generation.length <= 64 + ); + if (value.kind === "directory") + return value.path === "" || relative(value.path); + if (value.kind === "preview") return relative(value.path); + if ( + typeof value.includeUncommitted !== "boolean" || + !(value.baseBranch === null || validBranch(value.baseBranch)) + ) + return false; + switch (value.kind) { + case "stats": + return true; + case "diff": + return typeof value.ignoreWhitespace === "boolean"; + case "fileDiff": + return ( + relative(value.path) && typeof value.ignoreWhitespace === "boolean" + ); + case "image": + return ( + relative(value.path) && (value.side === "old" || value.side === "new") + ); + default: + return false; + } +} + +export const MAX_CHECKOUT_VIEW_BYTES = 16 * 1024 * 1024; +function count(value: unknown) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +function totals(value: unknown) { + return ( + isRecord(value) && + [value.files, value.added, value.deleted].every( + (n) => Number.isSafeInteger(n) && Number(n) >= 0 + ) + ); +} +function isFileDiff(value: unknown) { + return ( + isRecord(value) && + typeof value.path === "string" && + (value.oldPath === undefined || typeof value.oldPath === "string") && + ["modified", "added", "deleted", "renamed"].includes( + String(value.status) + ) && + count(value.added) && + count(value.deleted) && + (value.diff === null || typeof value.diff === "string") + ); +} +export function isCheckoutViewData(view: CheckoutView, data: unknown) { + switch (view.kind) { + case "stats": + return ( + data === null || + (isRecord(data) && + totals(data) && + totals(data.excludingTests) && + count(data.computedAt)) + ); + case "image": + return ( + typeof data === "string" && + data.length <= 4 * Math.ceil((10 * 1024 * 1024) / 3) && + /^[A-Za-z0-9+/]*={0,2}$/.test(data) + ); + case "fileDiff": + return ( + data === null || + (isFileDiff(data) && isRecord(data) && typeof data.diff === "string") + ); + case "diff": + return ( + isRecord(data) && + (data.baseRef === null || typeof data.baseRef === "string") && + Array.isArray(data.files) && + (data.truncatedFileCount === undefined || + count(data.truncatedFileCount)) && + data.files.every( + (f) => + isFileDiff(f) && + isRecord(f) && + typeof f.isTest === "boolean" && + typeof f.truncated === "boolean" && + (f.image === undefined || + (isRecord(f.image) && + (f.image.revision === undefined || + typeof f.image.revision === "string") && + [f.image.oldSize, f.image.newSize].every( + (n) => n === null || count(n) + ))) + ) + ); + case "index": + return ( + isRecord(data) && + (data.source === "git" || data.source === "folders") && + Array.isArray(data.paths) && + data.paths.every((p) => typeof p === "string") && + typeof data.truncated === "boolean" + ); + case "directory": + return ( + isRecord(data) && + typeof data.truncated === "boolean" && + Array.isArray(data.entries) && + data.entries.length <= 500 && + data.entries.every( + (e) => + isRecord(e) && + typeof e.name === "string" && + e.path === (view.path ? view.path + "/" + e.name : e.name) && + !e.name.includes("/") && + ["file", "directory", "link", "other"].includes(String(e.kind)) + ) + ); + case "preview": + return ( + isRecord(data) && + count(data.size) && + ((data.kind === "text" && typeof data.text === "string") || + (data.kind === "image" && + typeof data.src === "string" && + /^data:image\/(?:jpeg|png);base64,/.test(data.src)) || + (data.kind === "svg" && + typeof data.text === "string" && + typeof data.src === "string" && + data.src.startsWith("data:image/svg+xml;base64,")) || + (data.kind === "unsupported" && typeof data.message === "string")) + ); + } +} diff --git a/packages/runner-protocol/src/connection.ts b/packages/runner-protocol/src/connection.ts index ddf69fe92..ab6da7e6c 100644 --- a/packages/runner-protocol/src/connection.ts +++ b/packages/runner-protocol/src/connection.ts @@ -65,6 +65,7 @@ export class RunnerConnection { // Repository fetches and engine package installs can run for minutes. const timeoutMs = command.kind === "inspectCheckout" || + command.kind === "viewCheckout" || command.kind === "engine" || (command.kind === "launch" && command.launch.repository) ? 300_000 diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index f6aaf0ec7..cdb57d564 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,3 +1,4 @@ +import { isCheckoutView, type CheckoutView } from "./checkout-view.js"; import { isCheckoutQuery, validBranch, @@ -55,6 +56,8 @@ export type SessionLifecycleOperation = { agentId: string } & ( export type SessionOperation = | SessionLifecycleOperation + | { agentId: string; kind: "watchCheckout" } + | { agentId: string; kind: "viewCheckout"; query: CheckoutView } | { agentId: string; kind: "inspectCheckout"; query: CheckoutQuery } | { agentId: string; kind: "repo" }; @@ -77,6 +80,7 @@ export type ReadyFrame = { engineManagement?: true; githubManagement?: true; checkoutInspection?: true; + checkoutViews?: true; sharedWorktree?: true; }; @@ -100,6 +104,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { type: "ready", version: RUNNER_WIRE_VERSION, workspaces: frame.workspaces, + ...(frame.checkoutViews === true && { checkoutViews: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), ...(frame.health === true && { health: true }), @@ -231,6 +236,10 @@ function isCommand(value: unknown): value is Command { (value.launch.useWorktreeOf === undefined || value.agentId === value.launch.agentId) ); + case "watchCheckout": + return true; + case "viewCheckout": + return isCheckoutView(value.query); case "inspectCheckout": return isCheckoutQuery(value.query); case "attach": diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index 8328a7ab6..285173c49 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -5,3 +5,4 @@ export * from "./session.js"; export * from "./health.js"; export * from "./checkout.js"; export * from "./github.js"; +export * from "./checkout-view.js"; diff --git a/packages/shared/src/diff-types.ts b/packages/shared/src/diff-types.ts index 3db1ad5eb..7b24cb6e4 100644 --- a/packages/shared/src/diff-types.ts +++ b/packages/shared/src/diff-types.ts @@ -41,6 +41,8 @@ export const DIFF_IMAGE_MAX_BYTES = 10 * 1024 * 1024; * deleted has no new side). */ export type DiffImageInfo = { + /** Changes when either image side changes, including same-size working edits. */ + revision?: string; oldSize: number | null; newSize: number | null; }; diff --git a/packages/shared/src/ui-event-types.ts b/packages/shared/src/ui-event-types.ts index 15ce4fe8d..095acf743 100644 --- a/packages/shared/src/ui-event-types.ts +++ b/packages/shared/src/ui-event-types.ts @@ -30,6 +30,7 @@ import type { MacAppUpdateSnapshot } from "./mac-app-update-types.js"; * it across the boundary instead. */ export type SharedUiEvent = + | { type: "agent.checkout_changed"; agentId: string } | { type: "attention.history_changed" } | { type: "routing.pending"; From 3f68833e796febb5d3ddedf14488d814c9c37480 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 10:09:48 -0700 Subject: [PATCH 121/642] Cover image diff contracts in owner reviews --- .agents/owners.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.agents/owners.json b/.agents/owners.json index 7eb3f25ea..a0e24954b 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -37,6 +37,8 @@ "apps/server/src/shared/process/**", "apps/server/src/server/agent-*.ts", "apps/server/src/shared/git/**", + "apps/server/test/diff-image.test.ts", + "packages/shared/src/diff-types.ts", "apps/server/src/agents/acp/**", "docs/opencode-acp.md", "scripts/opencode-v2-smoke.mjs", From 9cae457416757eb254efcf87004fd9ad142fec9d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 13:59:13 -0700 Subject: [PATCH 122/642] Scope pull request status and CI checks to the agent's runner --- .agents/owners.json | 1 + apps/server/src/agents/pull-request-reader.ts | 143 +++++++++----- .../src/agents/pull-request-refresher.ts | 179 +++++++++++++----- .../agents/remote/github-runner-executor.ts | 21 ++ apps/server/src/agents/remote/runner.ts | 1 + apps/server/src/agents/remote/service.ts | 31 +++ apps/server/src/routes/runner-github.ts | 15 +- apps/server/src/server.ts | 17 +- apps/server/test/engine-wire.test.ts | 7 + .../test/github-runner-executor.test.ts | 39 ++++ .../server/test/helpers/remote-acp-fixture.ts | 53 ++++-- apps/server/test/pull-request-notices.test.ts | 7 +- .../test/pull-request-refresher.test.ts | 80 +++++++- apps/server/test/pull-requests.test.ts | 2 +- .../test/runner-protocol-consumer.test.ts | 17 ++ docs/design/runner-capability-inventory.md | 2 +- docs/design/runner-parity-rollout.md | 28 +++ e2e/remote-runner/fixture-gh.sh | 7 + e2e/remote-runner/github-account.spec.ts | 21 +- packages/runner-protocol/README.md | 10 + packages/runner-protocol/src/execution.ts | 2 + packages/runner-protocol/src/github.ts | 35 +++- 22 files changed, 594 insertions(+), 124 deletions(-) create mode 100644 docs/design/runner-parity-rollout.md diff --git a/.agents/owners.json b/.agents/owners.json index a0e24954b..5ecc80c54 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -32,6 +32,7 @@ "packages/runner-protocol/**", "docs/design/remote-runner-handoff.md", "docs/design/runner-capability-inventory.md", + "docs/design/runner-parity-rollout.md", "scripts/e2e-remote-runners.sh", "scripts/remote-runner/codex-offline-preflight.sh", "apps/server/src/shared/process/**", diff --git a/apps/server/src/agents/pull-request-reader.ts b/apps/server/src/agents/pull-request-reader.ts index 4527b4b5e..27c40406c 100644 --- a/apps/server/src/agents/pull-request-reader.ts +++ b/apps/server/src/agents/pull-request-reader.ts @@ -1,3 +1,4 @@ +import type { GitHubPullRequestObservation } from "@dispatch/runner-protocol"; import type { AgentPullRequest } from "@dispatch/shared"; import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; @@ -36,52 +37,14 @@ export function createPullRequestReader(run: CommandRunner = runCommand) { ); const result = await run( "gh", - [ - "api", - "graphql", - "--hostname", - "github.com", - "-f", - `query=${CHECKS_QUERY}`, - "-f", - `owner=${owner}`, - "-f", - `repo=${repo}`, - "-F", - `number=${number}`, - ], + pullRequestQueryArgs(owner, repo, number), { timeoutMs: 10_000, allowedExitCodes: [0, 1] } ); - const response = JSON.parse(result.stdout); - const pr = response.data?.repository?.pullRequest; - if (!pr) return fallback; - const commit = pr.commits?.nodes?.[0]?.commit; - const contexts = commit?.statusCheckRollup?.contexts; - // A null rollup means no checks; partial/error/truncated data is unavailable. - const rollup = - !response.errors?.length && commit?.oid === pr.headRefOid - ? commit.statusCheckRollup === null - ? [] - : contexts && !contexts.pageInfo?.hasNextPage - ? contexts.nodes - : undefined - : undefined; - const status = - pr.state === "MERGED" - ? "Merged" - : pr.state === "CLOSED" - ? "Closed" - : pr.state === "OPEN" - ? pr.isDraft - ? "Draft" - : "Open" - : "Unavailable"; - return { - url: canonical, - title: typeof pr.title === "string" ? pr.title : title, - status, - ci: mapPullRequestChecks(pr.headRefOid, rollup), - }; + return projectPullRequest( + canonical, + title, + pullRequestObservation(JSON.parse(result.stdout)) + ); } catch { return fallback; } @@ -91,6 +54,94 @@ export function createPullRequestReader(run: CommandRunner = runCommand) { }; } +export function pullRequestQueryArgs( + owner: string, + repo: string, + number: string +) { + return [ + "api", + "graphql", + "--hostname", + "github.com", + "-f", + `query=${CHECKS_QUERY}`, + "-f", + `owner=${owner}`, + "-f", + `repo=${repo}`, + "-F", + `number=${number}`, + ]; +} + +function record(value: unknown): Record { + return value !== null && typeof value === "object" + ? (value as Record) + : {}; +} + +/** Only the fields selected by the fixed query travel back to Dispatch. In + * particular, gh diagnostics and the GraphQL errors array stay on the runner. */ +export function pullRequestObservation( + result: unknown +): GitHubPullRequestObservation { + const response = record(result); + const repository = record(record(response.data).repository); + const pr = record(repository.pullRequest); + const nodes = record(pr.commits).nodes; + const commit = record(Array.isArray(nodes) && record(nodes[0]).commit); + const contexts = record(record(commit.statusCheckRollup).contexts); + const complete = + (response.errors === undefined || + (Array.isArray(response.errors) && response.errors.length === 0)) && + typeof pr.headRefOid === "string" && + commit.oid === pr.headRefOid; + return { + state: + pr.state === "OPEN" || pr.state === "CLOSED" || pr.state === "MERGED" + ? pr.state + : null, + draft: pr.isDraft === true, + title: typeof pr.title === "string" ? pr.title : null, + head: typeof pr.headRefOid === "string" ? pr.headRefOid : null, + rollup: + complete && commit.statusCheckRollup === null + ? [] + : complete && + record(contexts.pageInfo).hasNextPage === false && + Array.isArray(contexts.nodes) && + contexts.nodes.length <= 100 + ? contexts.nodes + : null, + }; +} + +export function projectPullRequest( + url: string, + title: string, + observation: GitHubPullRequestObservation +): AgentPullRequest { + const { state, draft, head, rollup, title: observedTitle } = observation; + const status = + state === "MERGED" + ? "Merged" + : state === "CLOSED" + ? "Closed" + : state === "OPEN" + ? draft === true + ? "Draft" + : "Open" + : "Unavailable"; + if (status === "Unavailable") return { url, title, status }; + return { + url, + status, + title: typeof observedTitle === "string" ? observedTitle : title, + ci: mapPullRequestChecks(head, rollup), + }; +} + const CHECKS_QUERY = `query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { @@ -125,7 +176,7 @@ export function mapPullRequestChecks( }, checks: [], }; - if (!ci.headSha || !Array.isArray(rollup)) return ci; + if (!ci.headSha || !Array.isArray(rollup) || rollup.length > 100) return ci; const checks = new Map(); const latest = new Map(); for (const raw of rollup) { @@ -139,6 +190,7 @@ export function mapPullRequestChecks( ? "PENDING" : "COMPLETED" : raw.status; + if (typeof status !== "string") return ci; const conclusion = context ? status === "PENDING" ? null @@ -146,6 +198,7 @@ export function mapPullRequestChecks( ? "FAILURE" : raw.state : raw.conclusion || null; + if (conclusion !== null && typeof conclusion !== "string") return ci; const url = context ? raw.targetUrl : raw.detailsUrl; // Reruns replace earlier attempts of a job from the same provider. In // particular an earlier cancelled attempt must not fail a passing rerun. diff --git a/apps/server/src/agents/pull-request-refresher.ts b/apps/server/src/agents/pull-request-refresher.ts index 1fa581284..d383d870a 100644 --- a/apps/server/src/agents/pull-request-refresher.ts +++ b/apps/server/src/agents/pull-request-refresher.ts @@ -13,9 +13,14 @@ export type CommitPullRequestNotice = ( type Options = { pool: Pool; - listAgentIds: () => Promise; + listAgents: () => Promise<{ id: string; runnerId: string | null }[]>; publish: PublishUiEvent; read?: (url: string, title: string) => Promise; + readRemote?: ( + runnerId: string, + url: string, + title: string + ) => Promise; notify?: ( agentId: string, previous: AgentPullRequest, @@ -126,6 +131,38 @@ export class PullRequestRefresher { this.stopped = false; this.signal(); } + private placements = new Map(); + private trackingKey(agentId: string, url: string) { + return JSON.stringify([this.placements.get(agentId), url]); + } + private readonly runnerRevision = new Map(); + /** A changed connection or GitHub account cannot reuse the previous peer's observations. */ + invalidateRunner(runnerId: string) { + const owners = [...this.placements].filter( + ([, runner]) => runner === runnerId + ); + if (!owners.length) return; + this.runnerRevision.set( + runnerId, + (this.runnerRevision.get(runnerId) ?? 0) + 1 + ); + for (const [id] of owners) { + const current = this.get(id); + if (!current.length) continue; + const pending = current.map(({ url }) => { + this.urls.delete(this.trackingKey(id, url)); + return { url, title: url, status: "Pending" as const }; + }); + this.snapshots.set(id, pending); + this.options.publish({ + type: "agent.pull_requests_changed", + agentId: id, + pullRequests: pending, + }); + } + this.signal(); + } + private reviewGeneration = new Map(); private reviewStates = new Map(); /** Explicit PR posts and edits to previously tracked posts reconcile inventory. */ @@ -148,10 +185,11 @@ export class PullRequestRefresher { // Review updates otherwise reconcile inventory but leave the five-minute // GitHub freshness deadline intact. Reuse the existing bounded queue. for (const pr of this.get(current.toAgentId)) { - const entry = this.urls.get(pr.url); + const key = this.trackingKey(current.toAgentId, pr.url); + const entry = this.urls.get(key); this.reviewGeneration.set( - pr.url, - (this.reviewGeneration.get(pr.url) ?? 0) + 1 + key, + (this.reviewGeneration.get(key) ?? 0) + 1 ); if (entry) entry.due = 0; } @@ -251,7 +289,11 @@ export class PullRequestRefresher { } } private async reconcile(target?: { agentId: string; url: string }) { - const ids = await this.options.listAgentIds(); + const placements = await this.options.listAgents(); + this.placements = new Map( + placements.map(({ id, runnerId }) => [id, runnerId]) + ); + const ids = [...this.placements.keys()]; const tombstones = await this.options.pool.query<{ agent_id: string; url: string; @@ -283,7 +325,10 @@ export class PullRequestRefresher { ]) ); const agents = new Map>(); - const links = new Map(); + const links = new Map< + string, + { url: string; title: string; runnerId: string | null } + >(); for (const row of rows) for (const attachment of row.attachments) { if (attachment.type !== "pr") continue; @@ -294,9 +339,21 @@ export class PullRequestRefresher { continue; } if (url.protocol !== "https:" && url.protocol !== "http:") continue; - const key = githubPullRequestUrl(attachment.url) ?? attachment.url; - if (this.isDismissed(row.author_agent_id, key)) continue; - if (!links.has(key)) links.set(key, attachment.title ?? key); + const canonical = + githubPullRequestUrl(attachment.url) ?? attachment.url; + const runnerId = this.placements.get(row.author_agent_id); + if ( + runnerId === undefined || + this.isDismissed(row.author_agent_id, canonical) + ) + continue; + const key = this.trackingKey(row.author_agent_id, canonical); + if (!links.has(key)) + links.set(key, { + url: canonical, + title: attachment.title ?? canonical, + runnerId, + }); const own = agents.get(row.author_agent_id) ?? new Set(); own.add(key); agents.set(row.author_agent_id, own); @@ -304,15 +361,17 @@ export class PullRequestRefresher { const publishSnapshots = () => { if (this.stopped) return; for (const id of new Set([...ids, ...this.snapshots.keys()])) { - const next = [...(agents.get(id) ?? [])].flatMap((url) => - this.isDismissed(id, url) - ? [] - : (this.urls.get(url)?.value ?? { - url, - title: links.get(url) ?? url, - status: "Pending" as const, - }) - ); + const next = [...(agents.get(id) ?? [])].flatMap((key) => { + const { url, title } = links.get(key)!; + if (this.isDismissed(id, url)) return []; + return ( + this.urls.get(key)?.value ?? { + url, + title, + status: "Pending" as const, + } + ); + }); if (JSON.stringify(this.get(id)) !== JSON.stringify(next)) { this.snapshots.set(id, next); this.options.publish({ @@ -331,6 +390,7 @@ export class PullRequestRefresher { ]) ); const notices: Array<() => Promise> = []; + let refreshError: Error | undefined; publishSnapshots(); this.pendingUrls = new Set( [...links.keys()].filter((url) => !this.urls.has(url)) @@ -339,7 +399,9 @@ export class PullRequestRefresher { this.attempts = this.attempts.filter((at) => at > now - 60_000); if (target) { if ( - !agents.get(target.agentId)?.has(target.url) || + !agents + .get(target.agentId) + ?.has(this.trackingKey(target.agentId, target.url)) || this.isDismissed(target.agentId, target.url) ) throw new Error("PR is no longer tracked by this agent."); @@ -348,7 +410,9 @@ export class PullRequestRefresher { } const queue = [...links] .filter(([url]) => - target ? url === target.url : (this.urls.get(url)?.due ?? 0) <= now + target + ? url === this.trackingKey(target.agentId, target.url) + : (this.urls.get(url)?.due ?? 0) <= now ) .sort( ([a], [b]) => @@ -359,29 +423,46 @@ export class PullRequestRefresher { await Promise.all( Array.from({ length: Math.min(2, queue.length) }, async () => { while (queue.length && !this.stopped) { - const [url, title] = queue.shift()!; - const reviewGeneration = this.reviewGeneration.get(url) ?? 0; + const [key, { url, title, runnerId }] = queue.shift()!; + const reviewGeneration = this.reviewGeneration.get(key) ?? 0; + const revision = + runnerId === null ? undefined : this.runnerRevision.get(runnerId); + const peerChanged = () => + runnerId !== null && this.runnerRevision.get(runnerId) !== revision; this.attempts.push(Date.now()); let value: AgentPullRequest; try { - value = await this.read(url, title); + if (runnerId === null) value = await this.read(url, title); + else if (this.options.readRemote) + value = await this.options.readRemote(runnerId, url, title); + else value = { url, title, status: "Unavailable" }; } catch { value = { url, title, status: "Unavailable" }; } + if (peerChanged()) { + if (target) + throw new Error( + "Runner connection or account changed. Please retry." + ); + continue; + } if ( target && (value.status === "Unavailable" || value.ci?.availability === "unavailable") - ) - throw new Error( + ) { + refreshError = new Error( "Could not refresh PR. Check GitHub authentication and try again." ); - const previous = this.urls.get(url); + if (runnerId === null) throw refreshError; + } + const previous = this.urls.get(key); // An assessor failure cannot establish that history is still enabled. let assessed = false; - if (this.options.assess) { + // Merge-risk evidence still depends on the native checkout and GitHub account. + if (this.options.assess && runnerId === null) { const owners = [...agents] - .filter(([, urls]) => urls.has(url)) + .filter(([, urls]) => urls.has(key)) .map(([id]) => id); try { const mergeRisk = await this.options.assess( @@ -392,7 +473,7 @@ export class PullRequestRefresher { if ( this.stopped || this.riskHidden || - (this.reviewGeneration.get(url) ?? 0) !== reviewGeneration + (this.reviewGeneration.get(key) ?? 0) !== reviewGeneration ) return; for (const id of owners) { @@ -433,7 +514,11 @@ export class PullRequestRefresher { // nor keep displaying old-head checks as current. // CI-only errors must not delay healthy lifecycle reads/notices. const unavailable = value.status === "Unavailable"; - if (value.status === "Unavailable" && previous?.lifecycle) { + if ( + runnerId === null && + value.status === "Unavailable" && + previous?.lifecycle + ) { value = { ...previous.lifecycle, mergeRisk: value.mergeRisk, @@ -466,7 +551,9 @@ export class PullRequestRefresher { value.status ) ? value - : previous?.lifecycle; + : runnerId !== null && unavailable + ? undefined + : previous?.lifecycle; const lifecycleChanged = lifecycle === value && previous?.lifecycle && @@ -475,18 +562,18 @@ export class PullRequestRefresher { previous && checkChanges(previous.checks ?? previous.value, value).length > 0; const reviewChanged = - (this.reviewGeneration.get(url) ?? 0) !== reviewGeneration; + (this.reviewGeneration.get(key) ?? 0) !== reviewGeneration; for (const notify of [ lifecycleChanged ? this.options.notify : undefined, checksChanged ? this.options.notifyChecks : undefined, - !reviewChanged && !this.riskHidden + runnerId === null && !reviewChanged && !this.riskHidden ? this.options.notifyRisk : undefined, ]) { if (!notify) continue; for (const [id, urls] of agents) { if ( - urls.has(url) && + urls.has(key) && (notify === this.options.notifyRisk || existingOwners.get(id)?.has(url)) && notify @@ -496,28 +583,29 @@ export class PullRequestRefresher { ? (previous!.checks ?? previous!.value) : (previous?.lifecycle ?? value); notices.push(async () => { - if (!this.isDismissed(id, url)) + if (!peerChanged() && !this.isDismissed(id, url)) await notify(id, before, value, async (write) => { if ( + peerChanged() || this.isDismissed(id, url) || (notify === this.options.notifyRisk && (this.riskHidden || - (this.reviewGeneration.get(url) ?? 0) !== + (this.reviewGeneration.get(key) ?? 0) !== reviewGeneration)) ) return undefined; - const key = `${id}:${url}`; + const noticeKey = `${id}:${url}`; const writes = - this.noticeWrites.get(key) ?? + this.noticeWrites.get(noticeKey) ?? new Set>(); const flight = Promise.resolve().then(write); writes.add(flight); - this.noticeWrites.set(key, writes); + this.noticeWrites.set(noticeKey, writes); try { return await flight; } finally { writes.delete(flight); - if (!writes.size) this.noticeWrites.delete(key); + if (!writes.size) this.noticeWrites.delete(noticeKey); } }); }); @@ -528,16 +616,20 @@ export class PullRequestRefresher { // URL due so the dirty follow-up consumes the new evidence, even on // its first refresh when no cache entry existed at invalidation time. if (reviewChanged) value = { ...value, mergeRisk: undefined }; - this.urls.set(url, { + this.urls.set(key, { value, lifecycle, checks: - value.ci?.availability === "available" ? value : previous?.checks, + value.ci?.availability === "available" + ? value + : runnerId !== null && unavailable + ? undefined + : previous?.checks, failures, checkedAt: Date.now(), due: reviewChanged ? 0 : Date.now() + delay, }); - this.pendingUrls.delete(url); + this.pendingUrls.delete(key); } }) ); @@ -557,5 +649,6 @@ export class PullRequestRefresher { } }) ); + if (refreshError) throw refreshError; } } diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index c152253e7..c22d3ebe6 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -1,3 +1,7 @@ +import { + pullRequestObservation, + pullRequestQueryArgs, +} from "../pull-request-reader.js"; import { execFile, spawn, type ChildProcess } from "node:child_process"; import { promisify } from "node:util"; import { @@ -265,6 +269,23 @@ export class GitHubRunnerExecutor { })) ); } + case "pullRequestStatus": { + const { owner, repo, number } = operation; + const result = await this.run( + pullRequestQueryArgs(owner, repo, String(number)), + signal + ).catch((error) => { + // GraphQL can return a usable PR and a check-level error together. + if ( + error.code === 1 && + typeof error.stdout === "string" && + error.stdout + ) + return error.stdout; + throw error; + }); + return pullRequestObservation(JSON.parse(result)); + } case "pullRequestHead": { const { owner, repo, number } = operation; const head = await this.run( diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index be947cca2..e5b273c76 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -567,6 +567,7 @@ export async function runRemoteRunner(filename: string) { ...(managedWorkspace ? { managedWorkspace: true } : {}), engineManagement: true, githubManagement: true, + pullRequestStatus: true, checkoutInspection: true, checkoutViews: true, sharedWorktree: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 1582de34f..6f294e7bb 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1,3 +1,7 @@ +import { + githubPullRequestUrl, + projectPullRequest, +} from "../pull-request-reader.js"; import { X509Certificate } from "node:crypto"; import { readFileSync, watchFile, unwatchFile } from "node:fs"; import http from "node:http"; @@ -32,6 +36,7 @@ import { type GitHubOperation, type GitHubStatus, parseGitHubStatus, + isGitHubPullRequestObservation, githubPullRequestHead, githubRepositoryResults, type SessionOperation, @@ -143,6 +148,7 @@ type Peer = { /** Advertised in `ready`; whether this peer answers the `"engine"` command. */ engineManagement: boolean; githubManagement: boolean; + pullRequestStatus: boolean; checkoutInspection: boolean; checkoutViews: boolean; sharedWorktree: boolean; @@ -658,6 +664,7 @@ export class RemoteRunnerService { socket, reportsHealth: ready.health === true, engineManagement: ready.engineManagement === true, + pullRequestStatus: ready.pullRequestStatus === true, githubManagement: ready.githubManagement === true, checkoutViews: ready.checkoutViews === true, checkoutInspection: ready.checkoutInspection === true, @@ -1208,6 +1215,15 @@ export class RemoteRunnerService { : "Update the runner to manage its GitHub account." ); + if ( + operation.kind === "github" && + operation.operation.type === "pullRequestStatus" && + !peer.pullRequestStatus + ) + throw new RunnerCapabilityUnavailable( + "Update the runner to read pull request status." + ); + // V1 requires a routable workspace and an id even for a runner-wide operation. for (const workspace of peer.workspaces) { if (peer.gate.allows(workspace)) @@ -1280,6 +1296,21 @@ export class RemoteRunnerService { return githubRepositoryResults(response.repositories); } + async readPullRequest(runnerId: string, url: string, title: string) { + const canonical = githubPullRequestUrl(url); + if (!canonical) return { url, title, status: "Unavailable" as const }; + const [, owner, repo, , number] = new URL(canonical).pathname.split("/"); + const response = await this.requestGitHub(runnerId, { + type: "pullRequestStatus", + owner, + repo, + number: Number(number), + }); + if (!isGitHubPullRequestObservation(response)) + throw new Error("Invalid runner pull request observation."); + return projectPullRequest(canonical, title, response); + } + async lookupGitHubPullRequestHead( runnerId: string, owner: string, diff --git a/apps/server/src/routes/runner-github.ts b/apps/server/src/routes/runner-github.ts index ede5915ab..3fd861244 100644 --- a/apps/server/src/routes/runner-github.ts +++ b/apps/server/src/routes/runner-github.ts @@ -10,8 +10,10 @@ declare module "fastify" { export function registerRunnerGitHub( app: FastifyInstance, - runners: Pick + runners: Pick, + onIdentityChange?: (runnerId: string) => void ) { + const identities = new Map(); const base = "/api/v1/runners/:id/github"; const operations = [ ["GET", base, "status"], @@ -26,7 +28,16 @@ export function registerRunnerGitHub( config: { validateSuppliedAuthorization: true }, async handler(req, reply) { reply.header("Cache-Control", "no-store"); - return runners.githubAccount(req.params.id, operation); + const id = req.params.id; + const result = await runners.githubAccount(id, operation); + if (result.status === "signed-in" || result.status === "signed-out") { + const login = result.status === "signed-in" ? result.login : null; + if (identities.get(id) !== login) { + identities.set(id, login); + onIdentityChange?.(id); + } + } + return result; }, }); } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 0525247ec..0709d6c23 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import { CheckoutObservers } from "./agents/checkout-observers.js"; import { readAgentStats } from "./agents/checkout-runner.js"; import { discoverSlackLinkOrigins } from "./notifications/slack-link-origins.js"; @@ -376,8 +377,15 @@ const mergeRiskAssessor = new MergeRiskAssessor({ }); const pullRequests = new PullRequestRefresher({ pool, - listAgentIds: async () => - (await agentManager.listAgents()).map((agent) => agent.id), + listAgents: async () => + (await agentManager.listAgents()).map((agent) => ({ + id: agent.id, + runnerId: remotePlacement(agent.cwd)?.runner ?? null, + })), + readRemote: async (runnerId, url, title) => { + if (!remoteRunner) throw new Error("Runner unavailable."); + return remoteRunner.readPullRequest(runnerId, url, title); + }, publish: (event) => uiEventBroker.publish(event), assess: (url, value, owners, onProgress) => mergeRiskAssessor.assess(url, value, owners, onProgress), @@ -392,6 +400,7 @@ const pullRequests = new PullRequestRefresher({ }, warn: (error) => app.log.warn({ err: error }, "PR status refresh failed"), }); +remoteRunner?.onConnectionChange((id) => pullRequests.invalidateRunner(id)); const diffStatsRefresher = new DiffStatsRefresher({ getAgent: (id) => agentManager.getAgent(id), computeAgentStats: (id, agent) => readAgentStats(id, agent, remoteRunner), @@ -1372,7 +1381,9 @@ async function registerRoutes() { await registerQuickPhraseRoutes(app, { pool }); if (remoteRunner) { - registerRunnerGitHub(app, remoteRunner); + registerRunnerGitHub(app, remoteRunner, (id) => + pullRequests.invalidateRunner(id) + ); registerRunnerRepositorySearch(app, remoteRunner); registerRunnerInstaller(app, pool); } diff --git a/apps/server/test/engine-wire.test.ts b/apps/server/test/engine-wire.test.ts index 9bfd58590..149d35302 100644 --- a/apps/server/test/engine-wire.test.ts +++ b/apps/server/test/engine-wire.test.ts @@ -312,6 +312,13 @@ describe("engine wire integration", () => { { name: "org/project", url: "https://github.com/org/project" }, ], }); + await expect( + service.readPullRequest( + alpha.created.id, + "https://github.com/org/project/pull/42", + "Fixture" + ) + ).rejects.toThrow("Update the runner"); expect(await service.githubAccount(beta.created.id, "login")).toMatchObject( { status: "unavailable", diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts index 24873f69d..f363521a7 100644 --- a/apps/server/test/github-runner-executor.test.ts +++ b/apps/server/test/github-runner-executor.test.ts @@ -66,6 +66,13 @@ case "$1 $2" in test -f login printf 'username=fixture-user\npassword=synthetic-token\n' ;; + 'api graphql') + test "$3 $4" = '--hostname github.com' + test "$7 $8 $9" = '-f owner=org -f' + test -f login + cat graphql-response + exit 1 + ;; 'api --hostname') test "$3" = 'github.com' case "$4" in @@ -153,6 +160,38 @@ it("completes a device login and configures the same credential helper for an ag connection.signal ) ).toEqual({ url: "https://github.com/fork/project.git", branch: "fix" }); + await writeFile( + path.join(root, "graphql-response"), + JSON.stringify({ + errors: [{ message: "private diagnostic" }], + data: { + repository: { + pullRequest: { + state: "OPEN", + title: "Partial status", + headRefOid: "sha", + }, + }, + }, + }) + ); + expect( + await executor.handle( + { + type: "pullRequestStatus", + owner: "org", + repo: "project", + number: 42, + }, + connection.signal + ) + ).toEqual({ + state: "OPEN", + title: "Partial status", + head: "sha", + draft: false, + rollup: null, + }); await writeFile(path.join(root, "revoked"), ""); expect(await handle("status")).toEqual({ status: "signed-out" }); expect(await handle("logout")).toEqual({ status: "signed-out" }); diff --git a/apps/server/test/helpers/remote-acp-fixture.ts b/apps/server/test/helpers/remote-acp-fixture.ts index 9c52d76fb..1d58a6f59 100644 --- a/apps/server/test/helpers/remote-acp-fixture.ts +++ b/apps/server/test/helpers/remote-acp-fixture.ts @@ -52,11 +52,7 @@ const fake = createFakeAcpAgent({ } await report("Guest permission answered."); } - if (prompt.includes("prove-marker")) { - const marker = ( - await readFile(path.join(session.cwd, "marker.txt"), "utf8") - ).trim(); - await report(`Guest marker ${marker}`); + if (prompt.includes("prove-marker") || prompt.includes("post-private-pr")) { const endpoint = session.mcpServers.find( (entry) => "url" in entry && "headers" in entry ); @@ -76,19 +72,40 @@ const fake = createFakeAcpAgent({ }) ); try { - const post = await client.callTool({ - name: "post", - arguments: { text: `Posted from Lima: ${marker}` }, - }); - if (post.isError) throw new Error(JSON.stringify(post.content)); - const repo = await client.callTool({ - name: "repo_runner_workspace", - arguments: {}, - }); - if (repo.isError) throw new Error(JSON.stringify(repo.content)); - await report( - ` Approved repo operation: ${JSON.stringify(repo.content)}` - ); + if (prompt.includes("post-private-pr")) { + const post = await client.callTool({ + name: "post", + arguments: { + text: "Private checkout PR", + attachments: [ + { + type: "pr", + url: "https://github.com/fixture-scratch/private/pull/42", + title: "Fixture PR", + }, + ], + }, + }); + if (post.isError) throw new Error(JSON.stringify(post.content)); + } else { + const marker = ( + await readFile(path.join(session.cwd, "marker.txt"), "utf8") + ).trim(); + await report(`Guest marker ${marker}`); + const post = await client.callTool({ + name: "post", + arguments: { text: `Posted from Lima: ${marker}` }, + }); + if (post.isError) throw new Error(JSON.stringify(post.content)); + const repo = await client.callTool({ + name: "repo_runner_workspace", + arguments: {}, + }); + if (repo.isError) throw new Error(JSON.stringify(repo.content)); + await report( + ` Approved repo operation: ${JSON.stringify(repo.content)}` + ); + } } finally { await client.close(); } diff --git a/apps/server/test/pull-request-notices.test.ts b/apps/server/test/pull-request-notices.test.ts index fba8dedcb..beabb1497 100644 --- a/apps/server/test/pull-request-notices.test.ts +++ b/apps/server/test/pull-request-notices.test.ts @@ -134,7 +134,7 @@ describe("PR observation delivery", () => { }); const refresher = new PullRequestRefresher({ pool, - listAgentIds: async () => ["child"], + listAgents: async () => [{ id: "child", runnerId: null }], publish: () => {}, warn: () => {}, read: async () => current, @@ -162,7 +162,10 @@ describe("PR observation delivery", () => { }); const restarted = new PullRequestRefresher({ pool, - listAgentIds: async () => ["child", "parent"], + listAgents: async () => [ + { id: "child", runnerId: null }, + { id: "parent", runnerId: null }, + ], publish: () => {}, warn: () => {}, read: async () => current, diff --git a/apps/server/test/pull-request-refresher.test.ts b/apps/server/test/pull-request-refresher.test.ts index be35f1785..5767cbc2c 100644 --- a/apps/server/test/pull-request-refresher.test.ts +++ b/apps/server/test/pull-request-refresher.test.ts @@ -38,20 +38,86 @@ function fixture(count = 1) { > >() .mockResolvedValue(undefined); - const listAgentIds = vi.fn().mockResolvedValue(["a", "b"]); + const listAgents = vi.fn().mockResolvedValue([ + { id: "a", runnerId: null }, + { id: "b", runnerId: null }, + ]); const service = new PullRequestRefresher({ pool: { query } as unknown as Pool, read, publish, notify, notifyChecks: notify, - listAgentIds, + listAgents, warn: vi.fn(), }); - return { rows, query, read, publish, notify, service, listAgentIds }; + return { rows, query, read, publish, notify, service, listAgents }; } afterEach(() => vi.useRealTimers()); describe("server PR orchestration", () => { + it("isolates background and manual reads of the same URL by runner and drops a late reply after replacement", async () => { + const f = fixture(); + f.rows.push({ ...f.rows[0], author_agent_id: "b" }); + const url = f.rows[0].attachments[0].url; + const readRemote = vi.fn( + async ( + runnerId: string, + url: string, + title: string + ): Promise => { + if (runnerId === "beta") throw new Error("Access denied"); + return { url, title: "Visible to alpha", status: "Open" }; + } + ); + const assess = vi.fn(); + const service = new PullRequestRefresher({ + pool: { query: f.query } as unknown as Pool, + listAgents: async () => [ + { id: "a", runnerId: "alpha" }, + { id: "b", runnerId: "beta" }, + ], + publish: f.publish, + read: f.read, + readRemote, + assess, + warn: vi.fn(), + }); + try { + await service.refresh(); + expect(service.get("a")[0]).toMatchObject({ + title: "Visible to alpha", + status: "Open", + }); + expect(service.get("b")[0]).toMatchObject({ + title: "PR 0", + status: "Unavailable", + }); + expect(f.read).not.toHaveBeenCalled(); + expect(assess).not.toHaveBeenCalled(); + readRemote.mockClear(); + await expect(service.refreshOne("b", url)).rejects.toThrow("GitHub"); + expect(readRemote.mock.calls.map(([id]) => id)).toEqual(["beta"]); + let finish!: (pr: AgentPullRequest) => void; + readRemote.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }) + ); + const refreshing = service.refreshOne("a", url); + await vi.waitFor(() => expect(finish).toBeTypeOf("function")); + service.invalidateRunner("alpha"); + finish({ url, title: "Previous account", status: "Merged" }); + await expect(refreshing).rejects.toThrow("changed"); + expect(service.get("a")[0]).toMatchObject({ + status: "Pending", + title: url, + }); + expect(service.get("b")[0].status).toBe("Unavailable"); + } finally { + await service.stop(); + } + }); it("persists canonical agent-scoped dismissal through rediscovery and a reconstructed refresher", async () => { const f = fixture(); f.rows.push({ ...f.rows[0], author_agent_id: "b" }); @@ -64,7 +130,7 @@ describe("server PR orchestration", () => { await f.service.stop(); const restarted = new PullRequestRefresher({ pool: { query: f.query } as unknown as Pool, - listAgentIds: f.listAgentIds, + listAgents: f.listAgents, read: f.read, publish: f.publish, warn: vi.fn(), @@ -645,7 +711,7 @@ it("attaches merge-risk assessments to observed heads and carries them while the pool: { query: f.query } as unknown as Pool, read: f.read, publish: f.publish, - listAgentIds: f.listAgentIds, + listAgents: f.listAgents, assess, warn: vi.fn(), }); @@ -711,7 +777,7 @@ it("clears cached risk immediately on disable and suppresses in-flight progress" const service = new PullRequestRefresher({ notifyRisk, pool: { query: f.query } as unknown as Pool, - listAgentIds: f.listAgentIds, + listAgents: f.listAgents, read: f.read, publish: f.publish, warn: vi.fn(), @@ -749,7 +815,7 @@ it.each([false, true])( const service = new PullRequestRefresher({ notifyRisk, pool: { query: f.query } as unknown as Pool, - listAgentIds: f.listAgentIds, + listAgents: f.listAgents, read: f.read, publish: f.publish, warn: vi.fn(), diff --git a/apps/server/test/pull-requests.test.ts b/apps/server/test/pull-requests.test.ts index 6a6dcd100..94aa9d104 100644 --- a/apps/server/test/pull-requests.test.ts +++ b/apps/server/test/pull-requests.test.ts @@ -124,7 +124,7 @@ describe("session pull requests", () => { ); const pullRequests = new PullRequestRefresher({ pool: { query } as any, - listAgentIds: async () => ["agent"], + listAgents: async () => [{ id: "agent", runnerId: null }], publish: vi.fn(), warn: vi.fn(), }); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 83f0145be..115d72a05 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -110,6 +110,7 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () health: true, engineManagement: true, githubManagement: true, + pullRequestStatus: true, checkoutInspection: true, checkoutViews: true, sharedWorktree: true, @@ -129,6 +130,22 @@ it("validates runner-scoped GitHub command payloads", () => { operation, }, }); + expect( + parse({ + type: "pullRequestStatus", + owner: "example", + repo: "project", + number: 42, + }) + ).not.toBeNull(); + expect( + parse({ + type: "pullRequestStatus", + owner: "example", + repo: "project", + number: 0, + }) + ).toBeNull(); expect(parse({ type: "login" })).not.toBeNull(); expect(parse({ type: "repositorySearch", query: "org/repo" })).not.toBeNull(); expect(parse({ type: "repositorySearch", query: "--help\n" })).toBeNull(); diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 9082c1532..d77a64f92 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -56,7 +56,7 @@ A native host can complete an accepted turn while its controller is down. A repl - Compare an untracked file, rename, image and dirty worktree against the same base. Handle a missing base without probing another machine. [Agent diff](../../apps/server/src/shared/git/agent-diff.ts) · [Agent routes](../../apps/server/src/routes/agents/lifecycle-routes.ts) · [Stats refresher](../../apps/server/src/agents/diff-stats-refresher.ts) -**Discover repositories and interact with GitHub.** **Partial.** Runner Git can provision a checkout. Repository search, branch/PR lookup, PR status/checks and risk analysis have separate callers. Decide explicitly whether each uses a Dispatch GitHub identity or the workload’s GitHub identity. A project association alone grants no GitHub access. +**Discover repositories and interact with GitHub.** **Partial.** Runner Git can provision a checkout. Repository search, PR head lookup and tracked PR status/checks use the selected runner’s GitHub account. Dispatch schedules reads and publishes the results to the UI. Moving merge-risk evidence to the runner and having the runner push PR changes are the next steps in the [parity rollout](runner-parity-rollout.md). A project association alone grants no GitHub access. - From a fresh runner account, sign in to GitHub, clone a private test repo, fetch a fork PR, and verify the identity used for push and PR creation. Sign out and verify isolation from other runners. Local-only review must also work with no published branch. [Search](../../apps/server/src/routes/runner-repositories.ts) · [PR reader](../../apps/server/src/agents/pull-request-reader.ts) · [Refresh](../../apps/server/src/agents/pull-request-refresher.ts) · [Risk inputs](../../apps/server/src/agents/merge-risk/sources.ts) diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md new file mode 100644 index 000000000..ae8143281 --- /dev/null +++ b/docs/design/runner-parity-rollout.md @@ -0,0 +1,28 @@ +# Runner parity rollout + +The runner owns observations and actions that require a session checkout, machine process or workload credential. Dispatch owns project membership, user permissions, schedules, notification policy, history and delivery to browsers. The built-in Mac/Linux runner keeps native execution and arbitrary local folders. Use the [capability inventory](runner-capability-inventory.md) to trace callers. + +The branch already exercises session supervision, shared reviewer checkouts, checkout inspection, scoped GitHub login, and live Files and Changes. Work through the following in order. Each step should leave existing callers usable. + +| Order | Work | What proves it | +| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Move PR lifecycle and CI reads to the agent’s runner. Partition deduplication, manual refresh, notices and evidence by placement. Move merge-risk source collection to the same account, then let runners observe tracked PRs and send changed snapshots. | Two machines track the same URL with different visibility. A forced refresh, disconnect, account switch and reconnect produce the right card and notifications for each. An old runner reports unavailable. | +| 2 | Finish repository identity, worktree changes and archive decisions. Use the owning runner for dirty/unmerged checks, moves and cleanup. Exercise every launch caller including tasks, jobs, templates and nested children. | Replay both archive orders with a live borrower, offline cleanup and restart. Recover an existing native folder session and its project association. | +| 3 | Deliver prompt files and collect posted files across the runner boundary. Keep durable copies in Dispatch. | An agent reads an uploaded image and posts a generated file. The browser can still open it after archive. Cover interrupted transfers and size limits. | +| 4 | Resolve repo manifests, persona definitions, instructions and lifecycle hooks in the effective checkout. Execute only service-authorized operations under the workload identity. | Two checkouts with different tools and identical paths produce different catalogs. Stop and move use the right hooks. | +| 5 | Audit model and effort choices, provider usage, plugins, and all account-dependent probes. Separate terminal processes on the execution machine from clipboard, IDE and browser actions on the operator desktop. | Compare two workload homes and exercise native Mac/Linux flows. An unsupported action has an explicit result. Scope remote port forwarding separately. | +| 6 | Run the native/remote contract suite and repeat a real task with a child and owner review. Audit HTTP, MCP, jobs, background refresh, recovery and archive for residual local filesystem/process calls. | Verify version negotiation, replay, reconnect, revocation and retained sessions after a Dispatch restart. Record which updates can safely reattach to existing hosts before changing update policy. | + +## First checkpoint + +Scheduled and manual PR reads now use the selected runner. The optional `pullRequestStatus` capability returns lifecycle and current-head checks. Dispatch isolates cached observations, in-flight replies and notices by runner and URL. The Linux browser fixture posts a private PR, observes an initial check, changes the fixture on the runner, then refreshes to see the new check. + +Two pieces remain in this stage. First, move the PR details and assessment diff readers to the owning workload. Scope assessment reservations, prior decisions, explanations and their evidence to the placement before enabling remote assessments. The current assessment history looks up by URL alone. Existing unscoped rows should remain native-only. Second, let the runner watch the tracked set, send a current snapshot on subscribe or reconnect, and send subsequent changes. Test stale connections, bounded polling, manual refresh and the last subscriber leaving. Browser updates continue through the existing Dispatch event stream. + +## Live updates + +Each observation needs an owning machine/account, freshness, a bounded payload, and a way to reconcile after a disconnect. Dispatch tracks which resources matter and projects observations into existing UI events. Test missed events and late replies from replaced connections. Preserve the difference between an empty result and unavailable data. Use the existing refresh budget while migrating PR reads, then test subscription and reconciliation behavior independently of browser count. + +## Checkpoints + +Ship each capability through its normal local and remote entry points, test older peers, and update the inventory with evidence. Keep release/update policy changes separate until the restart and mixed-version tests establish what can safely coexist. diff --git a/e2e/remote-runner/fixture-gh.sh b/e2e/remote-runner/fixture-gh.sh index 65fc713fd..6d409c2f0 100644 --- a/e2e/remote-runner/fixture-gh.sh +++ b/e2e/remote-runner/fixture-gh.sh @@ -30,6 +30,13 @@ case "$1 ${2:-}" in grep -qx 'host=github.com' || exit 1 printf 'username=%s\npassword=test-only-%s\n\n' "$login" "$name" ;; + 'api graphql') + test -s "$key" + test "$login" = "fixture-scratch" + job=build + if [ -f /tmp/runner-ci-finished ]; then job=integration; fi + printf '{"data":{"repository":{"pullRequest":{"state":"OPEN","title":"Private runner change","headRefOid":"a1b2c3d","commits":{"nodes":[{"commit":{"oid":"a1b2c3d","statusCheckRollup":{"contexts":{"pageInfo":{"hasNextPage":false},"nodes":[{"__typename":"CheckRun","name":"%s","status":"COMPLETED","conclusion":"SUCCESS"}]}}}}]}}}}}' "$job" + ;; 'api user'|'api --hostname') test -s "$key" case " $* " in diff --git a/e2e/remote-runner/github-account.spec.ts b/e2e/remote-runner/github-account.spec.ts index fcc4e81e0..15f14685c 100644 --- a/e2e/remote-runner/github-account.spec.ts +++ b/e2e/remote-runner/github-account.spec.ts @@ -95,7 +95,7 @@ test("GitHub sign-in, private checkout and sign-out belong to the selected runne repository: "fixture-scratch/private", pullRequest: "https://github.com/fixture-scratch/private/pull/42", name: "Private checkout", - prompt: "proof-reviewed-checkout", + prompt: "proof-reviewed-checkout post-private-pr", }); expect(agent.id).toBeTruthy(); try { @@ -105,6 +105,25 @@ test("GitHub sign-in, private checkout and sign-out belong to the selected runne ).toContainText("Checkout marker private PR on scratch", { timeout: 45000, }); + await page + .getByRole("button", { name: /Details for pull request #42: Open/i }) + .click(); + const details = page.getByRole("dialog"); + await expect(details.getByText("build", { exact: true })).toBeVisible(); + guest("scratch", "touch /tmp/runner-ci-finished"); + await details + .getByRole("button", { name: "Refresh pull request checks" }) + .click(); + await expect( + details.getByText("integration", { exact: true }) + ).toBeVisible(); + const screenshot = testInfo.outputPath("runner-private-pr-checks.png"); + await page.screenshot({ path: screenshot }); + await testInfo.attach("Refreshed checks using the runner GitHub account", { + path: screenshot, + contentType: "image/png", + }); + await page.keyboard.press("Escape"); // Uses the ordinary workload user's installed helper, independent of the provisioning helper. const fetch = "setpriv --reuid 1500 --regid 1500 --clear-groups env HOME=/home/guest GIT_TERMINAL_PROMPT=0 git ls-remote https://github.com/fixture-scratch/private.git HEAD"; diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index b6aafbe99..65bad111e 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -235,3 +235,13 @@ the same account through the gh credential helper. A transport disconnect ends a pending login, and a completed credential remains with that workload account. Logout removes the active account locally. GitHub authorization can be revoked separately in GitHub settings. + +A peer advertising both `githubManagement` and `pullRequestStatus` accepts +`{type: "pullRequestStatus", owner, repo, number}`. Run the fixed current-head +GitHub query under the workload account. Return the GitHub state, draft flag, +title, head SHA and rollup in `{state, draft, title, head, rollup}`. Rollup +contains up to 100 current-head CheckRun or StatusContext nodes. An empty +array means no checks. Null means incomplete, unavailable, truncated, or +mismatched head. An inaccessible PR has no state. Leave CLI output and +GraphQL diagnostics on the runner. Consumers validate the result and +scope cached observations and notifications to the runner and canonical URL. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index cdb57d564..1a7d96d81 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -79,6 +79,7 @@ export type ReadyFrame = { /** Advertises support for the `"engine"` command and inventory push. */ engineManagement?: true; githubManagement?: true; + pullRequestStatus?: true; checkoutInspection?: true; checkoutViews?: true; sharedWorktree?: true; @@ -109,6 +110,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.sharedWorktree === true && { sharedWorktree: true }), ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), + ...(frame.pullRequestStatus === true && { pullRequestStatus: true }), ...(frame.githubManagement === true && { githubManagement: true }), ...(frame.managedWorkspace === true && { managedWorkspace: true }), }; diff --git a/packages/runner-protocol/src/github.ts b/packages/runner-protocol/src/github.ts index 4dc01c653..407eb1df8 100644 --- a/packages/runner-protocol/src/github.ts +++ b/packages/runner-protocol/src/github.ts @@ -6,7 +6,39 @@ export const githubDeviceUrl = "https://github.com/login/device"; export type GitHubOperation = | { type: "status" | "login" | "cancel" | "logout" } | { type: "repositorySearch"; query: string } - | { type: "pullRequestHead"; owner: string; repo: string; number: number }; + | { + type: "pullRequestHead" | "pullRequestStatus"; + owner: string; + repo: string; + number: number; + }; + +/** Result of the fixed current-head query. An inaccessible PR has a null state. + * An empty rollup is authoritative. A null rollup is incomplete or unavailable. */ +export type GitHubPullRequestObservation = { + state: "OPEN" | "CLOSED" | "MERGED" | null; + draft: boolean; + title: string | null; + head: string | null; + rollup: unknown[] | null; +}; + +export function isGitHubPullRequestObservation( + value: unknown +): value is GitHubPullRequestObservation { + return ( + isRecord(value) && + (value.state === null || + value.state === "OPEN" || + value.state === "CLOSED" || + value.state === "MERGED") && + typeof value.draft === "boolean" && + (value.title === null || typeof value.title === "string") && + (value.head === null || typeof value.head === "string") && + (value.rollup === null || + (Array.isArray(value.rollup) && value.rollup.length <= 100)) + ); +} export type GitHubStatus = | { status: "signed-in"; login: string } @@ -49,6 +81,7 @@ export function isGitHubOperation(value: unknown): value is GitHubOperation { return true; case "repositorySearch": return validRepositorySearch(value.query); + case "pullRequestStatus": case "pullRequestHead": return ( validGitHubRepoPart(value.owner) && From f29733fa6a12a5f9e370486ec33abfcc154498a5 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 14:00:21 -0700 Subject: [PATCH 123/642] Inject placement-aware PR reads into the refresh queue --- apps/server/src/agents/pull-request-reader.ts | 25 +++++++++++++++++++ .../src/agents/pull-request-refresher.ts | 22 +++++----------- apps/server/src/server.ts | 6 ++--- .../test/pull-request-refresher.test.ts | 7 ++++-- apps/server/test/pull-requests.test.ts | 1 + 5 files changed, 39 insertions(+), 22 deletions(-) diff --git a/apps/server/src/agents/pull-request-reader.ts b/apps/server/src/agents/pull-request-reader.ts index 27c40406c..44417e256 100644 --- a/apps/server/src/agents/pull-request-reader.ts +++ b/apps/server/src/agents/pull-request-reader.ts @@ -16,6 +16,31 @@ export function githubPullRequestUrl(value: string): string | null { } } +/** Bind the built-in and connected runner implementations at service startup. + * A missing remote peer is an unavailable read for that placement. */ +export function createRunnerPullRequestReader( + remote: + | { + readPullRequest( + runnerId: string, + url: string, + title: string + ): Promise; + } + | undefined, + readLocal = createPullRequestReader() +) { + return async ( + url: string, + title: string, + runnerId: string | null + ): Promise => { + if (runnerId === null) return readLocal(url, title); + if (!remote) return { url, title, status: "Unavailable" }; + return remote.readPullRequest(runnerId, url, title); + }; +} + /** TTL and in-flight coalescing collapse duplicate scheduler requests. */ export function createPullRequestReader(run: CommandRunner = runCommand) { const cache = new Map< diff --git a/apps/server/src/agents/pull-request-refresher.ts b/apps/server/src/agents/pull-request-refresher.ts index d383d870a..a75c59587 100644 --- a/apps/server/src/agents/pull-request-refresher.ts +++ b/apps/server/src/agents/pull-request-refresher.ts @@ -2,10 +2,7 @@ import { checkChanges } from "./pull-request-check-notice.js"; import type { AgentPullRequest, Block } from "@dispatch/shared"; import type { Pool } from "pg"; import type { PublishUiEvent } from "../server/ui-events.js"; -import { - createPullRequestReader, - githubPullRequestUrl, -} from "./pull-request-reader.js"; +import { githubPullRequestUrl } from "./pull-request-reader.js"; export type CommitPullRequestNotice = ( write: () => Promise @@ -15,11 +12,10 @@ type Options = { pool: Pool; listAgents: () => Promise<{ id: string; runnerId: string | null }[]>; publish: PublishUiEvent; - read?: (url: string, title: string) => Promise; - readRemote?: ( - runnerId: string, + read: ( url: string, - title: string + title: string, + runnerId: string | null ) => Promise; notify?: ( agentId: string, @@ -92,10 +88,7 @@ export class PullRequestRefresher { private flight?: Promise; private stopped = false; private dirty = false; - private read: NonNullable; - constructor(private options: Options) { - this.read = options.read ?? createPullRequestReader(); - } + constructor(private options: Options) {} get(agentId: string): AgentPullRequest[] { return this.snapshots.get(agentId) ?? []; } @@ -432,10 +425,7 @@ export class PullRequestRefresher { this.attempts.push(Date.now()); let value: AgentPullRequest; try { - if (runnerId === null) value = await this.read(url, title); - else if (this.options.readRemote) - value = await this.options.readRemote(runnerId, url, title); - else value = { url, title, status: "Unavailable" }; + value = await this.options.read(url, title, runnerId); } catch { value = { url, title, status: "Unavailable" }; } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 0709d6c23..2724d72d1 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -10,6 +10,7 @@ import { SteeringDecisions } from "./chat/steering-decisions.js"; import { RoutingSettings } from "./chat/routing-settings.js"; import { RoutingShadow, RoutingShadowStore } from "./chat/routing-shadow.js"; import { registerRoutingShadowRoutes } from "./routes/routing-shadow.js"; +import { createRunnerPullRequestReader } from "./agents/pull-request-reader.js"; import { PullRequestRefresher } from "./agents/pull-request-refresher.js"; import { MergeRiskAssessor } from "./agents/merge-risk/assessor.js"; import { @@ -382,10 +383,7 @@ const pullRequests = new PullRequestRefresher({ id: agent.id, runnerId: remotePlacement(agent.cwd)?.runner ?? null, })), - readRemote: async (runnerId, url, title) => { - if (!remoteRunner) throw new Error("Runner unavailable."); - return remoteRunner.readPullRequest(runnerId, url, title); - }, + read: createRunnerPullRequestReader(remoteRunner), publish: (event) => uiEventBroker.publish(event), assess: (url, value, owners, onProgress) => mergeRiskAssessor.assess(url, value, owners, onProgress), diff --git a/apps/server/test/pull-request-refresher.test.ts b/apps/server/test/pull-request-refresher.test.ts index 5767cbc2c..a8a5bd1be 100644 --- a/apps/server/test/pull-request-refresher.test.ts +++ b/apps/server/test/pull-request-refresher.test.ts @@ -1,3 +1,4 @@ +import { createRunnerPullRequestReader } from "../src/agents/pull-request-reader.js"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Pool } from "pg"; import type { AgentPullRequest, Block } from "@dispatch/shared"; @@ -77,8 +78,10 @@ describe("server PR orchestration", () => { { id: "b", runnerId: "beta" }, ], publish: f.publish, - read: f.read, - readRemote, + read: createRunnerPullRequestReader( + { readPullRequest: readRemote }, + f.read + ), assess, warn: vi.fn(), }); diff --git a/apps/server/test/pull-requests.test.ts b/apps/server/test/pull-requests.test.ts index 94aa9d104..fc8eceafa 100644 --- a/apps/server/test/pull-requests.test.ts +++ b/apps/server/test/pull-requests.test.ts @@ -125,6 +125,7 @@ describe("session pull requests", () => { const pullRequests = new PullRequestRefresher({ pool: { query } as any, listAgents: async () => [{ id: "agent", runnerId: null }], + read: async (url, title) => ({ url, title, status: "Unavailable" }), publish: vi.fn(), warn: vi.fn(), }); From 9b71874c892309bc658b066c4a33288a303b6c5d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 14:39:11 -0700 Subject: [PATCH 124/642] Keep runner prompt metadata behind the host adapter --- apps/server/src/agents/acp/driver.ts | 4 + apps/server/src/agents/acp/host-protocol.ts | 66 ++- apps/server/src/agents/acp/host/main.ts | 10 +- apps/server/src/agents/acp/prompt-source.ts | 109 ++++- apps/server/src/agents/acp/runtime.ts | 4 +- apps/server/src/agents/local-runner.ts | 1 - apps/server/test/acp-host.test.ts | 48 ++- .../test/runner-protocol-consumer.test.ts | 376 +++++++++++++++++- packages/runner-protocol/README.md | 105 +++-- packages/runner-protocol/src/session.ts | 132 ++---- 10 files changed, 656 insertions(+), 199 deletions(-) diff --git a/apps/server/src/agents/acp/driver.ts b/apps/server/src/agents/acp/driver.ts index dd3bd4961..290d8ff73 100644 --- a/apps/server/src/agents/acp/driver.ts +++ b/apps/server/src/agents/acp/driver.ts @@ -1133,6 +1133,10 @@ export class AcpDriver { } } + hasEngineInitiatedTurn(agentId: string): boolean { + return Boolean(this.live.get(agentId)?.selfTurn); + } + supportsSteering(agentId: string): boolean { return this.live.get(agentId)?.steeringSupported ?? false; } diff --git a/apps/server/src/agents/acp/host-protocol.ts b/apps/server/src/agents/acp/host-protocol.ts index ffabb32c2..518861670 100644 --- a/apps/server/src/agents/acp/host-protocol.ts +++ b/apps/server/src/agents/acp/host-protocol.ts @@ -1,16 +1,15 @@ -import type { - HostEvent, - HostWelcome, - JournalEntry as RunnerJournalEntry, - PromptReceipt, - RemoteLaunch, - ReplayComplete, - SessionCommand, +import { + parseSessionCommand, + type HostWelcome, + type JournalEntry as RunnerJournalEntry, + type RemoteLaunch, + type SessionCommand, + type SessionReply, } from "@dispatch/runner-protocol"; import type { BackgroundSnapshot } from "@dispatch/shared"; import type { AgentMcpInventoryResponse } from "@dispatch/shared"; import type { AgentPermissionRequest } from "@dispatch/shared"; -import type { PromptSource } from "./prompt-source.js"; +import { isPromptSource, type PromptSource } from "./prompt-source.js"; import path from "node:path"; import { StringDecoder } from "node:string_decoder"; @@ -59,42 +58,39 @@ export function hostFile( /** One journal line: an event with its position in the host's stream. */ export type JournalEntry = RunnerJournalEntry; -export type ClientMessage = SessionCommand; +export type ClientMessage = SessionCommand; + +export function parseClientMessage(value: unknown): ClientMessage | null { + const message = parseSessionCommand(value); + if (message?.type !== "prompt" && message?.type !== "steer") return message; + // Keep validating the legacy Dispatch source shape. Other services can + // omit it or use their own metadata with a host that understands it. + const { source, ...command } = message; + if (source === undefined) return command; + return isPromptSource(source) ? { ...command, source } : null; +} + +type DispatchWelcome = HostWelcome & { + /** The open turn, if one is running. */ + turn: { seq: number; startedAt: string; source?: PromptSource } | null; + /** Current ACP commands, including skills; refreshed on each reconnect. */ + commands: AvailableCommand[]; + /** The session's config options as they stand; absent from older hosts. */ + configOptions?: SessionConfigOption[]; + permissions?: AgentPermissionRequest[]; +}; export type HostMessage = - | (HostWelcome & { - /** Absent on older hosts: keep queuing when they cannot steer. */ - mcpInventorySupported?: boolean; - /** Host snapshot RPC, absent on older hosts. */ - backgroundWorkSupported?: boolean; - steeringSupported?: boolean; - /** Targeted cancellation with an explicit completion response. */ - interruptSupported?: boolean; - /** The open turn, if one is running. */ - turn: { seq: number; startedAt: string; source?: PromptSource } | null; - /** Current ACP commands, including skills; refreshed on each reconnect. */ - commands: AvailableCommand[]; - /** The session's config options as they stand; absent from older hosts. */ - configOptions?: SessionConfigOption[]; - permissions?: AgentPermissionRequest[]; - }) - | HostEvent - | ReplayComplete - | PromptReceipt - | { type: "interrupt_result"; id: string } - | { type: "steer_result"; id: string; outcome: "injected" | "promptRequired" } + | SessionReply /** A set_config took; the engine's options after it. */ | { type: "config_set"; id: string; options: SessionConfigOption[] } - | { type: "error"; id?: string; message: string } | { type: "permissions"; requests: AgentPermissionRequest[] } - | { type: "permission_answered"; id: string } | { type: "mcp_inventory_result"; id: string; result: AgentMcpInventoryResponse; } - | { type: "background_work_result"; id: string; result: BackgroundSnapshot } - | { type: "pong" }; + | { type: "background_work_result"; id: string; result: BackgroundSnapshot }; /** * Split a byte stream into newline-delimited JSON messages. Returns a diff --git a/apps/server/src/agents/acp/host/main.ts b/apps/server/src/agents/acp/host/main.ts index 7607ef588..9152439b0 100644 --- a/apps/server/src/agents/acp/host/main.ts +++ b/apps/server/src/agents/acp/host/main.ts @@ -1,7 +1,4 @@ -import { - parseSessionCommand, - sessionCommandId, -} from "@dispatch/runner-protocol"; +import { sessionCommandId } from "@dispatch/runner-protocol"; import { applyLaunchEffort } from "../launch-effort.js"; import { firstPromptContext } from "../persona-context.js"; import type { PromptSource } from "../prompt-source.js"; @@ -42,6 +39,7 @@ import { hostFile, type JournalEntry, ndjsonDecoder, + parseClientMessage, } from "../host-protocol.js"; /** How long a crashed engine's host stays up so the server can read the exit. */ @@ -302,7 +300,7 @@ async function main(): Promise { const decode = ndjsonDecoder(() => rejectCommand()); socket.on("data", (chunk) => { for (const value of decode(chunk)) { - const message = parseSessionCommand(value); + const message = parseClientMessage(value); if (!message) { rejectCommand(sessionCommandId(value)); continue; @@ -403,7 +401,7 @@ async function main(): Promise { } // A turn the engine started itself raced this prompt: hand it back // to the server's queue rather than hold it here unacknowledged. - if (openTurn?.source?.source === "engine") { + if (openTurn && driver.hasEngineInitiatedTurn(agentId)) { send(socket, { type: "prompt_deferred", id: message.id }); return; } diff --git a/apps/server/src/agents/acp/prompt-source.ts b/apps/server/src/agents/acp/prompt-source.ts index 09cf41355..7da7da1cf 100644 --- a/apps/server/src/agents/acp/prompt-source.ts +++ b/apps/server/src/agents/acp/prompt-source.ts @@ -1,5 +1,110 @@ -import type { PromptImage, PromptSource } from "@dispatch/runner-protocol"; -export type { PromptImage, PromptSource } from "@dispatch/runner-protocol"; +import type { PromptImage } from "@dispatch/runner-protocol"; +export type { PromptImage } from "@dispatch/runner-protocol"; + +/** + * What a prompt sent to the harness was, for the prompt a turn entry + * renders. The wire text is an envelope Dispatch built; the feed wants the + * human-facing source behind it, not the envelope. + */ +export type PromptSource = { + /** Source discussion for batching and steering, retained through the host journal. + * User-thread turns use their validated source discussion for output at turn start. */ + conversation?: { streamId: string; threadId: string | null }; + /** + * A person's post. With a conversation, a prompt steers only that + * conversation; another agent's post without one steers any open turn. + */ + userMessage?: boolean; + /** Structured answers and commands retain their dedicated delivery policy. */ + steeringExcluded?: boolean; + /** Agent-authored scheduled content, explicitly eligible for steering. */ + scheduleId?: string; + scheduleDeliveryId?: string; + /** + * The recipient is waiting on this: a review it launched, a finding + * thread it is a side of, a finding settled or reopened. It joins the + * active turn whatever conversation that turn is in, rather than + * waiting behind the very work that is waiting on it. + */ + awaited?: boolean; +} & ( + | { + source: "chat"; + /** The post that opened the turn: the first, when there were several. */ + chatMessageId: string; + /** + * Every post the turn was given, in order, when posts that queued up + * behind a turn were delivered to it together. + */ + chatMessageIds?: string[]; + /** + * The block whose thread this prompt's answer belongs in, when the + * prompt says so rather than leaving it to what the post is: a + * notice that a finding changed is answered under the finding. + * Retained when prompts from this conversation are delivered together. + */ + answerIn?: string; + } + | { source: "agent"; senderId: string; senderName: string; text: string } + | { source: "system"; text: string } + /** + * A turn the engine started on its own between prompts (a background + * task finished, a goal continued). `after` is the block that answered + * the turn before it: this is source context; new ordinary work uses the agent home. + */ + | { source: "engine"; text: string; after?: string } +); + +export function isPromptSource(value: unknown): value is PromptSource { + if (!isSourceRecord(value)) return false; + const { conversation } = value; + if ( + conversation !== undefined && + (!isSourceRecord(conversation) || + typeof conversation.streamId !== "string" || + (conversation.threadId !== null && + typeof conversation.threadId !== "string")) + ) + return false; + if ( + ![value.userMessage, value.steeringExcluded, value.awaited].every( + (flag) => flag === undefined || typeof flag === "boolean" + ) || + ![value.scheduleId, value.scheduleDeliveryId].every( + (id) => id === undefined || typeof id === "string" + ) + ) + return false; + switch (value.source) { + case "chat": + return ( + typeof value.chatMessageId === "string" && + (value.chatMessageIds === undefined || + (Array.isArray(value.chatMessageIds) && + value.chatMessageIds.every((id) => typeof id === "string"))) && + (value.answerIn === undefined || typeof value.answerIn === "string") + ); + case "agent": + return ( + typeof value.senderId === "string" && + typeof value.senderName === "string" && + typeof value.text === "string" + ); + case "system": + return typeof value.text === "string"; + case "engine": + return ( + typeof value.text === "string" && + (value.after === undefined || typeof value.after === "string") + ); + default: + return false; + } +} + +function isSourceRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} const SYSTEM_MAX = 500; diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index e3ee7945d..f2bf4927d 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -1309,7 +1309,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { entry?.client.close(); }, - listHosted: local.listHosted, + async listHosted() { + return (await local.listHosted()).filter((id) => id.startsWith("agt_")); + }, hostPid: local.hostPid, onEvent(listener) { diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index 44de4c077..6e06d4446 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -250,7 +250,6 @@ export function createLocalRunner( } const hosted: string[] = []; for (const id of ids) { - if (!id.startsWith("agt_")) continue; const pid = await readPid(stateDir(id)); if (pid && pidAlive(pid)) hosted.push(id); } diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index 1a55c5e13..84bc3b7de 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -712,23 +712,37 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); const welcome = first.messages.find( (message) => message.type === "welcome" )!; - first.socket.write( - encodeMessage({ - type: "prompt", - id: "malformed-operation", - text: "proof-count", - journalId: welcome.journalId, - images: [{ path: true, mimeType: "image/png" }], - }) - ); - await until(() => - first.messages.some( - (message) => - message.type === "error" && - message.id === "malformed-operation" && - message.message === "Invalid host command." - ) - ); + for (const [id, fields] of [ + ["malformed-image", { images: [{ path: true, mimeType: "image/png" }] }], + [ + "malformed-source", + { + source: { + source: "chat", + chatMessageId: "post:1", + conversation: { streamId: "stream:1" }, + }, + }, + ], + ] as const) { + first.socket.write( + encodeMessage({ + type: "prompt", + id, + text: "proof-count", + journalId: welcome.journalId, + ...fields, + }) + ); + await until(() => + first.messages.some( + (message) => + message.type === "error" && + message.id === id && + message.message === "Invalid host command." + ) + ); + } const command = { type: "prompt", id: "first-operation", diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 115d72a05..9fed9bfe8 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -1,6 +1,10 @@ import { Duplex } from "node:stream"; import { type Frame, + type RemoteLaunch, + type RunnerFrame, + type SessionReply, + parseRunnerHealth, type ServiceFrame, type Command, parseReadyFrame, @@ -16,6 +20,11 @@ import { remotePlacement, workspaceLocator, } from "@dispatch/runner-protocol"; +import { + parseEngineInventory, + type EngineInventoryEntry, + type EngineOperationAck, +} from "@dispatch/runner-protocol/engine-management"; import { hostChannel, wireFrames } from "@dispatch/runner-protocol/node"; import { RunnerConnection, @@ -457,6 +466,7 @@ it("decodes the host session vocabulary including legacy and extended prompts", { type: "hello", fromSeq: 1, journalId: null, replayComplete: true }, { type: "prompt", id: "legacy", text: "Hello" }, prompt, + { ...prompt, source: { ticket: 42, tags: ["intake"] } }, { type: "steer", id: "steer:1", text: "Follow-up", source }, { type: "cancel" }, { type: "interrupt", id: "interrupt:1", turnSeq: 2 }, @@ -481,8 +491,6 @@ it("decodes the host session vocabulary including legacy and extended prompts", { type: "hello", fromSeq: 1.5 }, { type: "hello", fromSeq: 0, replayComplete: "true" }, { ...prompt, journalId: 7 }, - { ...prompt, source: { ...source, conversation: { streamId: "stream" } } }, - { ...prompt, source: { ...source, chatMessageIds: [null] } }, { ...prompt, images: [{ path: "/fixture/image" }] }, { type: "steer", id: "steer:1", text: 1 }, { type: "interrupt", id: "interrupt:1", turnSeq: 2 ** 53 }, @@ -548,3 +556,367 @@ it("recognizes only supported enrollment replies and retains their extensions", expect(parseConnectPoll(reply)).toBeNull(); } }); + +// Independent service and deterministic runner peer. Both sides speak NDJSON; +// runner session state outlives the service's authenticated connection. +function fixtureRunner(current: boolean) { + const workspace = current ? "@session" : "workload/β"; + const agentId = "collector/requests%2F:42"; + const session = { workspace, agentId }; + const ready: RunnerFrame = { + type: "ready", + version: 1, + workspaces: [workspace], + ...(current && { + managedWorkspace: true, + health: true, + engineManagement: true, + }), + }; + const sample = { + version: "fixture", + sessions: 1, + working: 0, + cpuPercent: null, + memoryUsed: 64, + memoryTotal: 128, + }; + const inventory: EngineInventoryEntry[] = [ + { + id: "codex", + label: "Codex", + installed: true, + signedIn: null, + version: null, + actions: [], + }, + ]; + const sessionId = "engine/session:42"; + const journalId = "journal/42"; + type Report = { text: string; context?: unknown }; + type Event = Extract, { type: "event" }>; + const journal: Event[] = []; + let running = false; + let resumed = false; + const requests: ServiceFrame[] = []; + + function connect() { + const service = new Duplex({ + read() {}, + write(chunk, _encoding, done) { + runner.push(chunk); + done(); + }, + }); + const runner = new Duplex({ + read() {}, + write(chunk, _encoding, done) { + service.push(chunk); + done(); + }, + }); + const channels = new Map(); + const reports: RunnerFrame[] = []; + const send = wireFrames(service, (frame) => { + switch (frame.type) { + case "result": + case "data": + case "close": + connection.receive(frame); + break; + default: + reports.push(frame); + } + }); + const connection = new RunnerConnection(send); + service.once("close", () => connection.close()); + const reply = wireFrames(runner, (value) => { + const frame = parseServiceFrame(value); + if (!frame) throw new Error("Malformed fixture service frame"); + requests.push(frame); + switch (frame.type) { + case "accept_health": + if (!current) throw new Error("Reports were not advertised"); + reply({ type: "health", sample }); + if (frame.engineInventory) + reply({ type: "engine_inventory", entries: inventory }); + break; + case "data": + channels.get(frame.id)?.push(Buffer.from(frame.data, "base64")); + break; + case "close": + channels.get(frame.id)?.destroy(); + break; + case "request": { + const { command, id } = frame; + const result = (value: boolean | string) => + reply({ type: "result", id, value }); + if ( + current && + command.kind === "engine" && + command.workspace === workspace && + command.operation.type === "status" + ) { + const ack: EngineOperationAck = { ok: true }; + result(JSON.stringify(ack)); + } else if ( + command.workspace !== workspace || + command.agentId !== agentId + ) { + reply({ type: "result", id, error: "Unknown session binding" }); + } else if (command.kind === "launch") { + resumed = command.launch.resumeSessionId === sessionId; + running = true; + result(true); + } else if (command.kind === "stop") { + running = false; + result(true); + } else if (command.kind === "attach") { + if (!running) { + reply({ type: "result", id, code: "host-gone" }); + break; + } + const channel = hostChannel(id, reply, () => channels.delete(id)); + channels.set(id, channel); + const report = wireFrames>( + channel, + (raw) => { + const message = parseSessionCommand(raw); + if (message?.type === "hello") { + report({ + type: "welcome", + agentId, + engine: "codex", + sessionId, + resumed, + running, + journalSeq: journal.length, + journalId, + }); + const cursor = + message.journalId === journalId ? message.fromSeq : 0; + for (const event of journal.slice(cursor)) report(event); + if (message.replayComplete) + report({ type: "replay_complete" }); + } else if ( + message?.type === "prompt" && + message.journalId === journalId + ) { + report({ type: "prompt_accepted", id: message.id }); + const event: Event = { + type: "event", + seq: journal.length + 1, + journalId, + at: "2030-01-01T00:00:00.000Z", + event: { text: message.text, context: message.source }, + }; + journal.push(event); + report(event); + } else { + report({ + type: "error", + id: sessionCommandId(raw), + message: "Unsupported session request", + }); + } + } + ); + result(true); + } else { + reply({ type: "result", id, error: "Unsupported runner request" }); + } + break; + } + } + }); + reply(ready); + return { + connection, + reports, + send, + close() { + for (const channel of channels.values()) channel.destroy(); + connection.close(); + service.destroy(); + runner.destroy(); + }, + }; + } + return { + connect, + session, + sample, + inventory, + requests, + sessionId, + journalId, + }; +} + +it.each([true, false])( + "independent service starts and resumes a runner session (current capabilities: %s)", + async (current) => { + const runner = fixtureRunner(current); + let peer = runner.connect(); + const launch: RemoteLaunch = { + agentId: runner.session.agentId, + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + }; + async function attach() { + const { channel } = await peer.connection.request( + { ...runner.session, kind: "attach" }, + { openChannel: true } + ); + if (!channel) throw new Error("Missing session channel"); + const messages: SessionReply[] = []; + const send = wireFrames(channel, (frame) => + messages.push(frame) + ); + const take = async () => { + await vi.waitFor(() => expect(messages.length).toBeGreaterThan(0)); + return messages.shift(); + }; + return { send, take }; + } + + try { + await vi.waitFor(() => expect(peer.reports[0]).toBeDefined()); + const ready = parseReadyFrame(peer.reports[0]); + expect(ready?.workspaces).toEqual([runner.session.workspace]); + if (ready?.health) { + peer.send({ + type: "accept_health", + engineInventory: ready.engineManagement, + }); + await vi.waitFor(() => expect(peer.reports).toHaveLength(3)); + const [, health, inventory] = peer.reports; + expect( + health?.type === "health" && parseRunnerHealth(health.sample) + ).toEqual(runner.sample); + expect( + inventory?.type === "engine_inventory" && + parseEngineInventory(inventory.entries) + ).toEqual(runner.inventory); + } + + await expect( + peer.connection.request({ ...runner.session, kind: "attach" }) + ).rejects.toBeInstanceOf(RunnerHostGone); + await expect( + peer.connection.request({ + ...runner.session, + workspace: "unknown", + kind: "launch", + launch, + }) + ).rejects.toThrow("Unknown session binding"); + expect( + ( + await peer.connection.request({ + ...runner.session, + kind: "launch", + launch, + }) + ).value + ).toBe(true); + const status = ready?.engineManagement + ? await peer.connection.request({ + kind: "engine", + workspace: runner.session.workspace, + agentId: "service/status", + operation: { type: "status" }, + }) + : { unavailable: true }; + expect(status).toMatchObject( + current + ? { value: JSON.stringify({ ok: true }) } + : { unavailable: true } + ); + + const first = await attach(); + first.send({ type: "hello", fromSeq: 0, replayComplete: true }); + const welcome = await first.take(); + expect(welcome).toMatchObject({ + type: "welcome", + sessionId: runner.sessionId, + resumed: false, + running: true, + journalId: runner.journalId, + }); + expect(await first.take()).toEqual({ type: "replay_complete" }); + first.send({ type: "future_request", id: "bad:1" }); + expect(await first.take()).toMatchObject({ type: "error", id: "bad:1" }); + if (welcome?.type !== "welcome") throw new Error("Missing host welcome"); + const context = { ticket: 42 }; + for (const [index, text] of ["first report", "second report"].entries()) { + const id = `operation/${index}`; + first.send({ + type: "prompt", + id, + text, + journalId: welcome.journalId, + ...(current && { source: context }), + }); + expect(await first.take()).toEqual({ type: "prompt_accepted", id }); + expect(await first.take()).toMatchObject({ + type: "event", + seq: index + 1, + event: current ? { text, context } : { text }, + }); + } + + await peer.connection.request({ + ...runner.session, + kind: "stop", + force: false, + }); + peer.close(); + peer = runner.connect(); + await vi.waitFor(() => + expect(parseReadyFrame(peer.reports[0])).not.toBeNull() + ); + const resume = { ...launch, resumeSessionId: welcome.sessionId }; + expect( + ( + await peer.connection.request({ + ...runner.session, + kind: "launch", + launch: resume, + }) + ).value + ).toBe(true); + const second = await attach(); + second.send({ + type: "hello", + fromSeq: 1, + journalId: welcome.journalId, + replayComplete: true, + }); + expect(await second.take()).toMatchObject({ + type: "welcome", + sessionId: runner.sessionId, + resumed: true, + journalSeq: 2, + }); + expect(await second.take()).toMatchObject({ + type: "event", + seq: 2, + event: { text: "second report" }, + }); + expect(await second.take()).toEqual({ type: "replay_complete" }); + expect( + runner.requests.filter((frame) => frame.type === "accept_health") + ).toHaveLength(current ? 1 : 0); + expect( + runner.requests.filter( + (frame) => frame.type === "request" && frame.command.kind === "engine" + ) + ).toHaveLength(current ? 1 : 0); + } finally { + peer.close(); + } + } +); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 65bad111e..f03547474 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -20,8 +20,9 @@ constructor takes a frame sender. Route incoming `result`, `data`, and `close` to `receive`. Call `close()` when the transport disconnects and create a fresh connection when the runner returns. Call `request(command, { openChannel: true })` to buffer channel data from the -moment an attach or engine operation is sent. Dispatch owns the registration -lookup, authorization, dashboard state, and durable journal storage. +moment an attach or engine operation is sent. The service owns registration lookup, authorization and durable journal +storage. Enrollment and attachment require no project, task board, review +workflow, notification system or UI. Treat those as service concerns. To extend v1, define the message in its sending direction and document its receipt or failure semantics. For an optional operation, advertise support in @@ -41,8 +42,14 @@ issued certificate and CA before saving credentials. Run the in-memory consumer tests from the repository root with `pnpm run test:runner-protocol`. -They use the package's public exports and require no database, TLS certificates, -agent process, or running Dispatch instance. +The independent consumer uses only public package exports for the wire +contract. It launches without MCP, reads prompt receipts and journal events, +stops, reconnects, relaunches with an engine session handle, and resumes from +a journal cursor. It also checks correlated failures and consumes health and +inventory when offered. The deterministic in-memory peer runs with current +and baseline v1 capabilities. Extend this fixture for new wire operations +with both advertised and unsupported cases. It requires no database, TLS +certificates, agent process or running Dispatch instance. For changes beyond the portable contract, the implementation tests in `apps/server/test/` exercise different boundaries: @@ -64,8 +71,13 @@ Runner registration is a service-side identity bound to its authenticated connection. The runner's `ready` frame advertises version 1 and the workspace handles available on that connection. Route an operation by registration and workspace, then send the selected workspace and agent IDs in the command. A -runner binds an agent to a workspace and checks the binding on later commands. -The command's agent ID is authoritative for a launch. +runner binds a session handle to a workspace and checks the binding on later +commands. `agentId` is the legacy wire name for a caller-assigned session +handle. It need not follow a product prefix. Send the same handle in the +envelope and launch payload. The envelope is authoritative. The +engine-assigned `sessionId` in `welcome` is separate. Send it as +`resumeSessionId` to request an engine resume on a later launch and check +`welcome.resumed` to confirm. Identifiers are case-sensitive strings of 1 to 128 UTF-16 code units and exclude control characters and unpaired surrogates. Treat them as opaque, @@ -106,36 +118,75 @@ The optional launch field `mcp` supplies one service-scoped MCP endpoint using an HTTPS `url`, bearer `token`, and optional `name`. Absence starts the ACP session with an empty service MCP list. v1 launches with the original `{ url, token }` shape use the server name `dispatch`. Prototype runner -binaries require that shape, so keep sending it when interoperating with -those binaries. +binaries require MCP in that shape. For modern runners, omit `mcp` +if there is no endpoint. Use `name` to name a configured endpoint on hosts +that support it. An older host can ignore the additive name and retain its +legacy default. `systemPrompt` is optional in effect (`null` disables it). +The legacy `personaContext` field is optional text for first-prompt context. +The service prepares this text and any instructions it wants included. ## Commands and results -| Command | Successful `result.value` | Channel | -| --------- | ----------------------------------------------------- | ---------------------------------------------------------------------- | -| `launch` | `true` after spawning the host | None | -| `attach` | `true` after connecting to the host | Bidirectional host protocol until close | -| `alive` | Boolean indicating host presence | None | -| `stop` | `true` after stopping the host | None | -| `discard` | `true` after retiring session state | None | -| `log` | A short guest host diagnostic string | None | -| `repo` | Standard output of the workspace's configured command | None | -| `engine` | JSON-encoded `EngineOperationAck` | Newline-delimited `EngineOperationEvent` records in base64 data frames | - -An agent command addresses its bound workspace. Engine management is -runner-wide. Dispatch callers use `requestSession(placement, operation)` or -`requestRunner(runnerId, operation)`. Only the v1 adapter fills in the routing -fields for runner-wide operations. The engine command’s v1 envelope still carries an advertised workspace and an -agent ID placeholder. Gate it on the runner's `engineManagement` capability. +| Command | Runner behavior and successful `result.value` | Capability or configuration | +| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | +| `launch` | Prepare machine-local state, start the host, return `true`. Wait for a running `welcome` before prompting. | Advertised workspace. Use `managedWorkspace` for managed storage and `sharedWorktree` before sending `useWorktreeOf`. | +| `attach` | Connect to a running host, return `true`, relay bytes until close. | Open a channel. | +| `alive` | Return a boolean for host presence. | Baseline. | +| `stop` | Stop the host and return `true`. The caller chooses graceful or forced stop. | Baseline. | +| `discard` | Retire stopped session state and return `true`. | Baseline. | +| `log` | Return a short host diagnostic string. | Baseline. | +| `repo` | Run the workspace's configured repository tool and return stdout. | Requires a workspace with a configured tool. | +| `inspectCheckout` | Run a `CheckoutQuery` against the bound checkout and return a JSON-encoded `CheckoutReply`. Validate it with `isCheckoutReply`. | `checkoutInspection`. | +| `viewCheckout` / `watchCheckout` | Read a checkout view or subscribe to change pulses. See below. | `checkoutViews`. | +| `engine` | Run an `EngineOperation` and return a JSON-encoded `EngineOperationAck`. When progress is available, stream NDJSON `EngineOperationEvent` records. | `engineManagement`. Open a channel when consuming progress. | +| `github` | Perform a `GitHubOperation` using the runner account and return its JSON reply. See below. | `githubManagement`, plus `pullRequestStatus` for current-head checks. | + +Use an advertised workspace and an opaque placeholder `agentId` for the +runner-wide `engine` and `github` operations. The runner routes those +operations independently of session bindings. With `useWorktreeOf`, the +value is the handle of a session with an existing checkout on the same runner +and workspace. Omit `repository` for a borrowed checkout. + +Negotiate again on each connection. Require an explicit `true` for optional +capabilities and ignore unknown advertisements. For an absent capability, +omit the command and report that the operation is unavailable. A configured +workspace can support baseline lifecycle operations without managed storage. +An unsupported wire version cannot establish a v1 connection. An execution error uses `result.error`. An attach to a known missing host also sets `result.code` to `host-gone`. Losing the connection before the result leaves the outcome unknown. The service can reattach using the durable cursor described below. -The portable session types cover commands received by the host, journal replay, -and prompt receipts. Dispatch-specific host replies and event payloads are -defined in `apps/server/src/agents/acp/host-protocol.ts`. +## Attached session operations + +`SessionCommand` and `SessionReply` describe the common host vocabulary. +The public decoder preserves optional `source` on `prompt` and `steer` as +opaque service metadata. The built-in Dispatch ACP host accepts commands +with no `source`, and its adapter validates the legacy Dispatch shape when +present. Omit `source` when connecting to that host from an independent +service. Keep conversation, attribution and scheduling metadata in your +service unless the attached host explicitly supports your schema. Prompt +`images`, if used, must already be readable on the execution machine. +Dispatch-specific event payloads and host reply extensions are in +`apps/server/src/agents/acp/host-protocol.ts`. + +| Command | Host behavior and service handling | +| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `hello` | Send `welcome`, journal entries after the supplied cursor, and `replay_complete` when requested. See Receipts and replay. | +| `prompt` | Submit to the engine and send a receipt. Use journaled events to observe the turn outcome. | +| `steer` | With `steeringSupported`, send `steer_result` with `injected` or `promptRequired`. Queue a normal prompt if steering is unavailable or a prompt is required. | +| `interrupt` | With `interruptSupported`, cancel the named open turn and send `interrupt_result`. A stale turn sequence never cancels a later turn. | +| `cancel` | Cancel the current turn without a correlated acknowledgement. Use only when current-turn cancellation is intended. | +| `answer_permission` | Answer the request using the advertised option ID, or `null` to decline. The host confirms with `permission_answered` or returns a correlated error. | +| `set_config` | Set an advertised engine option. Dispatch replies with `config_set` and the current options or a correlated error. Omit this command when the host publishes no options. | +| `mcp_inventory` / `background_work` | With `mcpInventorySupported` / `backgroundWorkSupported`, query the current engine session ID. The built-in host replies with `mcp_inventory_result` / `background_work_result` and a Dispatch snapshot payload. | +| `ping` | Reply with `pong`. | +| `shutdown` | Ask the host to exit. Closure ends the channel. | + +An older host may lack journal identity and the optional `welcome` flags. +Use its supported baseline, keep such a cursor scoped to a known host +incarnation and avoid automatic retries when a prompt's outcome is unknown. ### Files and Changes diff --git a/packages/runner-protocol/src/session.ts b/packages/runner-protocol/src/session.ts index 90716f0b3..aa56bb875 100644 --- a/packages/runner-protocol/src/session.ts +++ b/packages/runner-protocol/src/session.ts @@ -18,6 +18,10 @@ export type HostWelcome = { running: boolean; journalSeq: number; journalId?: string; + steeringSupported?: boolean; + interruptSupported?: boolean; + mcpInventorySupported?: boolean; + backgroundWorkSupported?: boolean; }; export type JournalEntry = { @@ -38,6 +42,7 @@ export type HostPrompt = { id: string; text: string; journalId?: string; + /** Opaque application metadata. The wire decoder preserves it as supplied. */ source?: Source; images?: Image[]; }; @@ -47,67 +52,13 @@ export type PromptReceipt = /** An engine-initiated turn is open and the host did not submit this prompt. */ | { type: "prompt_deferred"; id: string }; -/** - * What a prompt sent to the harness was, for the prompt a turn entry - * renders. The wire text is an envelope Dispatch built; the feed wants the - * human-facing source behind it, not the envelope. - */ -export type PromptSource = { - /** Source discussion for batching and steering, retained through the host journal. - * User-thread turns use their validated source discussion for output at turn start. */ - conversation?: { streamId: string; threadId: string | null }; - /** - * A person's post. With a conversation, a prompt steers only that - * conversation; another agent's post without one steers any open turn. - */ - userMessage?: boolean; - /** Structured answers and commands retain their dedicated delivery policy. */ - steeringExcluded?: boolean; - /** Agent-authored scheduled content, explicitly eligible for steering. */ - scheduleId?: string; - scheduleDeliveryId?: string; - /** - * The recipient is waiting on this: a review it launched, a finding - * thread it is a side of, a finding settled or reopened. It joins the - * active turn whatever conversation that turn is in, rather than - * waiting behind the very work that is waiting on it. - */ - awaited?: boolean; -} & ( - | { - source: "chat"; - /** The post that opened the turn: the first, when there were several. */ - chatMessageId: string; - /** - * Every post the turn was given, in order, when posts that queued up - * behind a turn were delivered to it together. - */ - chatMessageIds?: string[]; - /** - * The block whose thread this prompt's answer belongs in, when the - * prompt says so rather than leaving it to what the post is: a - * notice that a finding changed is answered under the finding. - * Retained when prompts from this conversation are delivered together. - */ - answerIn?: string; - } - | { source: "agent"; senderId: string; senderName: string; text: string } - | { source: "system"; text: string } - /** - * A turn the engine started on its own between prompts (a background - * task finished, a goal continued). `after` is the block that answered - * the turn before it: this is source context; new ordinary work uses the agent home. - */ - | { source: "engine"; text: string; after?: string } -); - -/** Server-resolved files, kept out of turn journals and encoded only for ACP. */ +/** Path to a prompt attachment on the execution machine. */ export type PromptImage = { path: string; mimeType: string }; -export type SessionCommand = +export type SessionCommand = | ReplayHello - | HostPrompt - | { type: "steer"; id: string; text: string; source?: PromptSource } + | HostPrompt + | { type: "steer"; id: string; text: string; source?: Source } | { type: "cancel" } | { type: "interrupt"; id: string; turnSeq: number } | { @@ -123,51 +74,20 @@ export type SessionCommand = | { type: "background_work"; id: string; sessionId: string } | { type: "ping" }; -function isPromptSource(value: unknown): value is PromptSource { - if (!isRecord(value)) return false; - const { conversation } = value; - if ( - conversation !== undefined && - (!isRecord(conversation) || - typeof conversation.streamId !== "string" || - !isNullableString(conversation.threadId)) - ) - return false; - if ( - ![value.userMessage, value.steeringExcluded, value.awaited].every( - (flag) => flag === undefined || typeof flag === "boolean" - ) || - ![value.scheduleId, value.scheduleDeliveryId].every( - (id) => id === undefined || typeof id === "string" - ) - ) - return false; - switch (value.source) { - case "chat": - return ( - typeof value.chatMessageId === "string" && - (value.chatMessageIds === undefined || - (Array.isArray(value.chatMessageIds) && - value.chatMessageIds.every((id) => typeof id === "string"))) && - (value.answerIn === undefined || typeof value.answerIn === "string") - ); - case "agent": - return ( - typeof value.senderId === "string" && - typeof value.senderName === "string" && - typeof value.text === "string" - ); - case "system": - return typeof value.text === "string"; - case "engine": - return ( - typeof value.text === "string" && - (value.after === undefined || typeof value.after === "string") - ); - default: - return false; - } -} +/** Replies without application-specific payload schemas. */ +export type SessionReply< + Event = unknown, + Welcome extends HostWelcome = HostWelcome, +> = + | Welcome + | HostEvent + | ReplayComplete + | PromptReceipt + | { type: "interrupt_result"; id: string } + | { type: "steer_result"; id: string; outcome: "injected" | "promptRequired" } + | { type: "error"; id?: string; message: string } + | { type: "permission_answered"; id: string } + | { type: "pong" }; function isPromptImage(value: unknown): value is PromptImage { return ( @@ -178,11 +98,7 @@ function isPromptImage(value: unknown): value is PromptImage { } function isPromptInput(value: Record): boolean { - return ( - typeof value.id === "string" && - typeof value.text === "string" && - (value.source === undefined || isPromptSource(value.source)) - ); + return typeof value.id === "string" && typeof value.text === "string"; } export function sessionCommandId(value: unknown): string | undefined { From f96097685518ed6c50d1e693334a9785a427adaf Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 14:50:01 -0700 Subject: [PATCH 125/642] Scope merge-risk GitHub evidence to the owning runner credential --- .../agents/github-pull-request-evidence.ts | 146 ++++++++++++++++ apps/server/src/agents/merge-risk/assessor.ts | 113 ++++++++++--- .../src/agents/merge-risk/explanations.ts | 86 ++++++++-- .../src/agents/merge-risk/github-source.ts | 98 +++++++++++ apps/server/src/agents/pull-request-reader.ts | 18 +- .../src/agents/pull-request-refresher.ts | 19 ++- .../agents/remote/github-runner-executor.ts | 28 +++- apps/server/src/agents/remote/runner.ts | 13 +- apps/server/src/agents/remote/service.ts | 54 ++++++ .../0058_merge_risk_evidence_scope.sql | 11 ++ .../src/routes/agents/pull-request-routes.ts | 8 +- apps/server/src/server.ts | 28 +++- .../test/github-runner-executor.test.ts | 106 +++++++++++- apps/server/test/merge-risk.test.ts | 156 ++++++++++++++++++ apps/server/test/migrations.test.ts | 3 + .../test/pull-request-refresher.test.ts | 18 +- ...ll-request-risk-explanation-routes.test.ts | 6 +- .../test/remote-runner-enrollment.test.ts | 46 ++++++ .../test/runner-protocol-consumer.test.ts | 81 +++++++++ docs/design/runner-capability-inventory.md | 2 +- docs/design/runner-parity-rollout.md | 4 +- packages/runner-protocol/README.md | 37 ++++- packages/runner-protocol/src/execution.ts | 2 + packages/runner-protocol/src/github.ts | 120 +++++++++++++- 24 files changed, 1129 insertions(+), 74 deletions(-) create mode 100644 apps/server/src/agents/github-pull-request-evidence.ts create mode 100644 apps/server/src/agents/merge-risk/github-source.ts create mode 100644 apps/server/src/db/migrations/0058_merge_risk_evidence_scope.sql diff --git a/apps/server/src/agents/github-pull-request-evidence.ts b/apps/server/src/agents/github-pull-request-evidence.ts new file mode 100644 index 000000000..212fdaa9b --- /dev/null +++ b/apps/server/src/agents/github-pull-request-evidence.ts @@ -0,0 +1,146 @@ +import { execFile } from "node:child_process"; +import { createHash, createHmac } from "node:crypto"; +import { promisify } from "node:util"; +import { + isGitHubPullRequestDetails, + isGitHubPullRequestDiff, + type GitHubOperation, + type GitHubPullRequestTarget, +} from "@dispatch/runner-protocol"; +import { + pullRequestObservation, + pullRequestQueryArgs, +} from "./pull-request-reader.js"; + +type Run = ( + args: string[], + signal: AbortSignal, + token?: string +) => Promise; +const host = ["--hostname", "github.com"]; +const execute = promisify(execFile); + +export function nativeGitHubEvidence() { + return new GitHubPullRequestEvidence(async (args, signal, token) => { + const { stdout } = await execute("gh", args, { + signal, + timeout: 7000, + killSignal: "SIGKILL", + maxBuffer: 128 * 1024, + env: { + ...process.env, + GH_PROMPT_DISABLED: "1", + ...(token && { GH_TOKEN: token }), + }, + }); + return stdout.trim(); + }); +} + +const DETAILS_QUERY = `query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + number title body baseRefName headRefName baseRefOid headRefOid additions deletions + files(first: 100) { pageInfo { hasNextPage } nodes { path additions deletions } } + } + } +}`; + +/** Every provider read in an operation uses the same token, even if gh's + * active account changes while the request is running. */ +export class GitHubPullRequestEvidence { + constructor( + private readonly run: Run, + private readonly credentialKey?: Buffer + ) {} + + private async credential(signal: AbortSignal) { + const token = await this.run(["auth", "token", ...host], signal); + if (!token || !/^[\w.-]{1,1024}$/.test(token)) + throw new Error("GitHub credential unavailable."); + const digest = this.credentialKey + ? createHmac("sha256", this.credentialKey) + : createHash("sha256"); + const credentialContext = digest + .update("github.com/pull-request-evidence\0") + .update(token) + .digest("hex"); + return { token, credentialContext }; + } + + async status(target: GitHubPullRequestTarget, signal: AbortSignal) { + const { token, credentialContext } = await this.credential(signal); + const result = await this.run( + pullRequestQueryArgs(target.owner, target.repo, String(target.number)), + signal, + token + ).catch((error) => { + if (error.code === 1 && typeof error.stdout === "string" && error.stdout) + return error.stdout; + throw error; + }); + return { ...pullRequestObservation(JSON.parse(result)), credentialContext }; + } + + async details( + { owner, repo, number }: GitHubPullRequestTarget, + signal: AbortSignal + ) { + const { token, credentialContext } = await this.credential(signal); + const result = JSON.parse( + await this.run( + [ + "api", + "graphql", + ...host, + "-f", + `query=${DETAILS_QUERY}`, + "-f", + `owner=${owner}`, + "-f", + `repo=${repo}`, + "-F", + `number=${number}`, + ], + signal, + token + ) + ); + const pr = result?.data?.repository?.pullRequest; + if (pr?.number !== number || pr.files?.pageInfo?.hasNextPage !== false) + return null; + const value: unknown = { ...pr, credentialContext, files: pr.files.nodes }; + return isGitHubPullRequestDetails(value) ? value : null; + } + + async diff( + operation: Extract, + signal: AbortSignal + ) { + const { owner, repo, number, base, head } = operation; + const { token, credentialContext } = await this.credential(signal); + if (operation.credentialContext !== credentialContext) return null; + const repository = `repos/${owner}/${repo}`; + const accessible = await this.run( + ["api", ...host, `${repository}/pulls/${number}`, "--jq", ".number"], + signal, + token + ); + if (accessible !== String(number)) return null; + const files: unknown = JSON.parse( + await this.run( + [ + "api", + ...host, + `${repository}/compare/${base}...${head}`, + "--jq", + '[.files[] | {path: .filename, additions, deletions, patch: (.patch | if type == "string" and length <= 32768 then . else null end)} | del(.patch | nulls)]', + ], + signal, + token + ) + ); + const value = { files }; + return isGitHubPullRequestDiff(value) ? value : null; + } +} diff --git a/apps/server/src/agents/merge-risk/assessor.ts b/apps/server/src/agents/merge-risk/assessor.ts index 99b8fa5ae..b2adad490 100644 --- a/apps/server/src/agents/merge-risk/assessor.ts +++ b/apps/server/src/agents/merge-risk/assessor.ts @@ -1,3 +1,5 @@ +import { pullRequestCredentialContext } from "../pull-request-reader.js"; +import { mergeRiskScope, type MergeRiskGitHubSource } from "./github-source.js"; import { mergeRiskCapacity } from "./budget.js"; /** * Produces one merge-risk recommendation per (pull request, head, review @@ -45,6 +47,11 @@ type Options = { settings: RoutingSettings; /** Checkout root for an owning agent, used to read its ownership map. */ agentRoot: (agentId: string) => Promise; + remoteOwners?: ( + agentId: string, + runnerId: string + ) => Promise; + github?: Pick; readDetails?: (url: string) => Promise; transport?: typeof fetch; warn?: (error: unknown) => void; @@ -81,14 +88,38 @@ export class MergeRiskAssessor { url: string, pr: AgentPullRequest, ownerAgentIds: string[], - onProgress?: (risk: MergeRiskSummary) => void + onProgress?: (risk: MergeRiskSummary) => void, + runnerId: string | null = null ): Promise { const headSha = pr.ci?.headSha ?? ""; // Off means off: no reads, no lookups, and no recommendation shown. const config = await this.options.settings.configuration(); if (!config.mergeRiskEnabled || !config.apiKey) return displaySummary("disabled", headSha); - const previous = await this.history(url); + const github = this.options.github; + const observedContext = pullRequestCredentialContext(pr); + if ( + (!github && runnerId !== null) || + (github && (!headSha || !observedContext)) + ) + return displaySummary("unavailable", headSha); + const scopedDetails = github ? await github.details(runnerId, url) : null; + if ( + github && + (!scopedDetails || + scopedDetails.credentialContext !== observedContext || + scopedDetails.headRefOid !== headSha) + ) + return displaySummary("unavailable", headSha); + const scope = scopedDetails + ? mergeRiskScope(runnerId, scopedDetails.credentialContext) + : ""; + const current = async () => + !scopedDetails || + (await github?.details(runnerId, url))?.credentialContext === + scopedDetails.credentialContext; + const includeHistorical = runnerId === null; + const previous = await this.history(url, scope, includeHistorical); const display = (state: NonNullable) => ({ ...displaySummary(state, headSha), ...(previous ? { previous } : {}), @@ -98,8 +129,13 @@ export class MergeRiskAssessor { settlementProvenance: true, }); const fingerprint = reviewFingerprint(reviews); - if (pr.status === "Merged") - return (await this.latest(url, headSha)) ?? display("not_ready"); + if (pr.status === "Merged") { + const merged = await this.latest(url, headSha, scope); + return ( + merged ?? + (previous?.headSha === headSha ? previous : display("not_ready")) + ); + } const gateHolds = (pr.status === "Open" || pr.status === "Draft") && allFindingsResolved(reviews); @@ -109,7 +145,7 @@ export class MergeRiskAssessor { ? "not_ready" : "waiting_review" ); - const stored = await this.latest(url, headSha, fingerprint); + const stored = await this.latest(url, headSha, scope, fingerprint); if (stored) return stored.status === "ok" ? stored @@ -118,11 +154,17 @@ export class MergeRiskAssessor { displayState: stored.displayState ?? "failure", ...(previous ? { previous } : {}), }; - const id = await this.reserve(url, headSha, fingerprint); + const id = await this.reserve( + url, + headSha, + fingerprint, + scope, + scopedDetails?.baseRefOid + ); if (!id) { const record = await this.options.pool.query<{ status: string }>( - "SELECT status FROM merge_risk_decision_records WHERE url=$1 AND head_sha=$2 AND review_fingerprint=$3 ORDER BY created_at DESC,id DESC LIMIT 1", - [url, headSha, fingerprint] + "SELECT status FROM merge_risk_decision_records WHERE url=$1 AND head_sha=$2 AND review_fingerprint=$3 AND evidence_scope=$4 ORDER BY created_at DESC,id DESC LIMIT 1", + [url, headSha, fingerprint, scope] ); return display( record.rows[0]?.status === "pending" @@ -134,12 +176,12 @@ export class MergeRiskAssessor { } onProgress?.(display("evaluating")); try { - const details = await this.readDetails(url); + const details = scopedDetails ?? (await this.readDetails(url)); if (!details || details.headRefOid !== headSha) { await this.finish(id, "skipped_stale_head", {}); return display("unavailable"); } - const owners = await this.owners(ownerAgentIds); + const owners = await this.owners(ownerAgentIds, runnerId); const evidence = buildMergeRiskEvidence({ pullRequest: { number: details.number, @@ -165,6 +207,10 @@ export class MergeRiskAssessor { } : null, }); + if (!(await current())) { + await this.finish(id, "skipped_credential_changed", {}); + return displaySummary("unavailable", headSha); + } // The setting can change while evidence is being gathered. if (!(await this.options.settings.configuration()).mergeRiskEnabled) { await this.finish(id, "skipped_config_changed", {}); @@ -220,7 +266,8 @@ export class MergeRiskAssessor { const finalConfig = await this.options.settings.configuration(); if (!finalConfig.mergeRiskEnabled || !finalConfig.apiKey) return displaySummary("disabled", headSha); - const result = await this.latest(url, headSha, fingerprint); + if (!(await current())) return displaySummary("unavailable", headSha); + const result = await this.latest(url, headSha, scope, fingerprint); return result?.status === "ok" ? result : { @@ -234,17 +281,29 @@ export class MergeRiskAssessor { }; } - private async history(url: string): Promise { + private async history( + url: string, + scope: string, + includeHistorical: boolean + ): Promise { const rows = await this.options.pool.query( - "SELECT id, status, head_sha, prompt_version, created_at, result FROM merge_risk_decision_records WHERE url=$1 AND status = 'ok' ORDER BY created_at DESC,id DESC LIMIT 1", - [url] + "SELECT id, status, head_sha, prompt_version, created_at, result FROM merge_risk_decision_records WHERE url=$1 AND (evidence_scope=$2 OR ($3 AND evidence_scope='')) AND status = 'ok' ORDER BY created_at DESC,id DESC LIMIT 1", + [url, scope, includeHistorical] ); return rows.rows[0] ? toSummary(rows.rows[0]) : undefined; } - private async owners(agentIds: string[]): Promise { + private async owners( + agentIds: string[], + runnerId: string | null + ): Promise { for (const agentId of agentIds) { try { + if (runnerId !== null) { + const config = await this.options.remoteOwners?.(agentId, runnerId); + if (config) return config; + continue; + } const root = await this.options.agentRoot(agentId); if (root) return await loadCodeowners(root); } catch { @@ -257,20 +316,28 @@ export class MergeRiskAssessor { private async latest( url: string, headSha: string, + scope: string, fingerprint?: string ): Promise { const rows = await this.options.pool.query( `SELECT id, status, head_sha, prompt_version, created_at, result FROM merge_risk_decision_records WHERE url = $1 AND head_sha = $2 AND ($3::text IS NULL OR review_fingerprint = $3) + AND evidence_scope = $4 AND status NOT IN ('pending') AND status NOT LIKE 'skipped%' ORDER BY created_at DESC, id DESC LIMIT 1`, - [url, headSha, fingerprint ?? null] + [url, headSha, fingerprint ?? null, scope] ); const row = rows.rows[0]; return row ? toSummary(row) : undefined; } - private async reserve(url: string, headSha: string, fingerprint: string) { + private async reserve( + url: string, + headSha: string, + fingerprint: string, + scope: string, + baseSha?: string + ) { const client = await this.options.pool.connect(); try { await client.query("BEGIN"); @@ -280,11 +347,11 @@ export class MergeRiskAssessor { // predate the removal of Dispatch's daily cap and revive the same way; // before this, a skipped head showed its limit forever. const record = await client.query<{ id: string }>( - `INSERT INTO merge_risk_decision_records(url,head_sha,review_fingerprint,status,prompt_version,result) - VALUES($1,$2,$3,$4,$5,$6) - ON CONFLICT(url,head_sha,review_fingerprint) DO UPDATE - SET status=EXCLUDED.status,created_at=now(),prompt_version=EXCLUDED.prompt_version,result=EXCLUDED.result - WHERE merge_risk_decision_records.status IN ('skipped_daily_cap','skipped_concurrency') + `INSERT INTO merge_risk_decision_records(url,head_sha,review_fingerprint,status,prompt_version,result,evidence_scope,base_sha) + VALUES($1,$2,$3,$4,$5,$6,$7,$8) + ON CONFLICT(url,head_sha,review_fingerprint,evidence_scope) DO UPDATE + SET status=EXCLUDED.status,created_at=now(),prompt_version=EXCLUDED.prompt_version,result=EXCLUDED.result,base_sha=EXCLUDED.base_sha + WHERE merge_risk_decision_records.status IN ('skipped_daily_cap','skipped_concurrency','skipped_credential_changed') AND merge_risk_decision_records.status <> EXCLUDED.status RETURNING id`, [ @@ -294,6 +361,8 @@ export class MergeRiskAssessor { status, MERGE_RISK_PROMPT_VERSION, JSON.stringify({ model: DECISIONS_MODEL }), + scope, + baseSha ?? null, ] ); await client.query("COMMIT"); diff --git a/apps/server/src/agents/merge-risk/explanations.ts b/apps/server/src/agents/merge-risk/explanations.ts index 9247d9623..c1eded9d1 100644 --- a/apps/server/src/agents/merge-risk/explanations.ts +++ b/apps/server/src/agents/merge-risk/explanations.ts @@ -1,3 +1,5 @@ +import { githubPullRequestUrl } from "../pull-request-reader.js"; +import { mergeRiskScope, type MergeRiskGitHubSource } from "./github-source.js"; import { retainedEvidence } from "./explanation-evidence.js"; import { mergeRiskCapacity } from "./budget.js"; import { readAssessedDiff } from "./explanation-diff.js"; @@ -9,7 +11,7 @@ import { type ExplanationFailure, } from "./explanation-client.js"; -type Input = { assessmentId: string }; +type Input = { assessmentId: string; url?: string; runnerId?: string | null }; /** * Why no explanation could start. Safe to show and log; never private data. * `not_found` means no completed assessment has that id (unknown or pruned). @@ -33,6 +35,7 @@ type Reply = ExplanationReply; type Assessment = { url: string; head_sha: string; + base_sha: string | null; created_at: Date; result: Record; /** Null when the record predates evidence retention or retention failed. */ @@ -44,7 +47,8 @@ type Assessment = { * * Explains one saved assessment by id, as it was made. Nothing about the * PR's current head, reviews, status or the in-memory inventory gates it. - * Request auth and the browser-only route are the only access controls. + * The requesting placement must still be able to read the PR with the + * credential that supplied the assessment. */ export class RiskExplanations { constructor( @@ -52,18 +56,25 @@ export class RiskExplanations { pool: Pool; settings: RoutingSettings; transport?: typeof fetch; + github?: Pick; /** Hunks for the assessed commit; injectable so tests never call gh. */ readDiff?: typeof readAssessedDiff; } ) {} - private async find(id: string): Promise { + private async find( + id: string, + url: string | null, + scope: string, + includeHistorical: boolean + ): Promise { const { rows } = await this.deps.pool.query( - `SELECT r.url,r.head_sha,r.created_at,r.result,s.evidence + `SELECT r.url,r.head_sha,r.base_sha,r.created_at,r.result,s.evidence FROM merge_risk_decision_records r LEFT JOIN merge_risk_evidence_snapshots s ON s.assessment_id=r.id - WHERE r.id=$1 AND r.status='ok'`, - [id] + WHERE r.id=$1 AND r.status='ok' AND ($2::text IS NULL OR r.url=$2) + AND (r.evidence_scope=$3 OR ($4 AND r.evidence_scope=''))`, + [id, url, scope, includeHistorical] ); return rows[0]; } @@ -77,7 +88,26 @@ export class RiskExplanations { const config = await this.deps.settings.configuration(); if (!config.mergeRiskEnabled || !config.apiKey) return { state: "unavailable", reason: "disabled" }; - const assessment = await this.find(input.assessmentId); + const github = this.deps.github; + const runnerId = input.runnerId ?? null; + const url = input.url ? githubPullRequestUrl(input.url) : null; + const details = github && url ? await github.details(runnerId, url) : null; + if ((github && !details) || (!github && runnerId !== null)) + return { state: "unavailable", reason: "not_found" }; + const scope = details + ? mergeRiskScope(runnerId, details.credentialContext) + : ""; + const authorized = async () => + !details || + (!!url && + (await github?.details(runnerId, url))?.credentialContext === + details.credentialContext); + const assessment = await this.find( + input.assessmentId, + url, + scope, + runnerId === null + ); if (!assessment) return { state: "unavailable", reason: "not_found" }; const limitedEvidence = assessment.evidence == null; // Settings are re-read after every await; a change aborts before spend. @@ -105,13 +135,17 @@ export class RiskExplanations { // An explanation from an older prompt/model is not reused: it regenerates. if (stored?.status === "pending") { await client.query("COMMIT"); - return { state: "pending" }; + return (await authorized()) + ? { state: "pending" } + : { state: "unavailable", reason: "not_found" }; } if ( stored?.status === "ok" && stored.result.version === EXPLANATION_VERSION ) { await client.query("COMMIT"); + if (!(await authorized())) + return { state: "unavailable", reason: "not_found" }; return { state: "ready", text: stored.result.text, @@ -138,11 +172,24 @@ export class RiskExplanations { // Without saved evidence the model may not name files, so no hunks. const diff = limitedEvidence ? null - : await (this.deps.readDiff ?? readAssessedDiff)( - assessment.url, - assessment.head_sha, - assessment.evidence - ).catch(() => null); + : github && details + ? await github.diff( + runnerId, + assessment.url, + assessment.base_sha ?? details.baseRefOid, + assessment.head_sha, + details.credentialContext, + assessment.evidence + ) + : await (this.deps.readDiff ?? readAssessedDiff)( + assessment.url, + assessment.head_sha, + assessment.evidence + ).catch(() => null); + if (!(await authorized())) { + await this.finish(input.assessmentId, "stale", { reason: "not_found" }); + return { state: "unavailable", reason: "not_found" }; + } if (!(await unchanged())) { await this.finish(input.assessmentId, "stale", { reason: "config_changed", @@ -164,16 +211,23 @@ export class RiskExplanations { ), this.deps.transport ); - const current = await unchanged(); + const stillAuthorized = await authorized(); + const current = stillAuthorized && (await unchanged()); // Results from replaced settings retain only accounting, never text. const { text, ...accounting } = result; await this.finish(input.assessmentId, current ? result.status : "stale", { ...accounting, - ...(current ? {} : { reason: "config_changed" }), + ...(current + ? {} + : { reason: stillAuthorized ? "config_changed" : "not_found" }), ...(current && text ? { text } : {}), ...(limitedEvidence ? { limitedEvidence: true } : {}), }); - if (!current) return { state: "unavailable", reason: "config_changed" }; + if (!current) + return { + state: "unavailable", + reason: stillAuthorized ? "config_changed" : "not_found", + }; return result.status === "ok" ? { state: "ready", diff --git a/apps/server/src/agents/merge-risk/github-source.ts b/apps/server/src/agents/merge-risk/github-source.ts new file mode 100644 index 000000000..059c2589f --- /dev/null +++ b/apps/server/src/agents/merge-risk/github-source.ts @@ -0,0 +1,98 @@ +import type { GitHubPullRequestDetails } from "@dispatch/runner-protocol"; +import { nativeGitHubEvidence } from "../github-pull-request-evidence.js"; +import { + createPullRequestReader, + githubPullRequestTarget, + projectPullRequest, +} from "../pull-request-reader.js"; +import type { RemoteRunnerService } from "../remote/service.js"; +import { mentionedText, selectHunks } from "./explanation-diff.js"; + +type Runners = Pick< + RemoteRunnerService, + "readPullRequestDetails" | "readPullRequestDiff" +>; + +export function mergeRiskScope( + runnerId: string | null, + credentialContext: string +) { + return JSON.stringify([runnerId, credentialContext]); +} + +export function createMergeRiskGitHubSource(remote: Runners | undefined) { + const native = nativeGitHubEvidence(); + const oldStatus = createPullRequestReader(); + return { + async nativeStatus(url: string, title: string) { + const target = githubPullRequestTarget(url); + if (target) { + const observation = await native + .status(target, AbortSignal.timeout(12000)) + .catch(() => null); + if (observation) return projectPullRequest(url, title, observation); + } + return oldStatus(url, title); + }, + async details( + runnerId: string | null, + url: string + ): Promise { + const target = githubPullRequestTarget(url); + if (!target) return null; + try { + return runnerId === null + ? await native.details(target, AbortSignal.timeout(12000)) + : ((await remote?.readPullRequestDetails(runnerId, url)) ?? null); + } catch { + return null; + } + }, + async diff( + runnerId: string | null, + url: string, + base: string, + head: string, + credentialContext: string, + evidence: unknown + ) { + const target = githubPullRequestTarget(url); + if ( + !target || + !/^[0-9a-f]{40}$/i.test(base) || + !/^[0-9a-f]{40}$/i.test(head) + ) + return null; + try { + const result = + runnerId === null + ? await native.diff( + { + ...target, + type: "pullRequestDiff", + base, + head, + credentialContext, + }, + AbortSignal.timeout(20000) + ) + : await remote?.readPullRequestDiff( + runnerId, + url, + base, + head, + credentialContext + ); + return result?.files.length + ? { base, ...selectHunks(result.files, mentionedText(evidence)) } + : null; + } catch { + return null; + } + }, + }; +} + +export type MergeRiskGitHubSource = ReturnType< + typeof createMergeRiskGitHubSource +>; diff --git a/apps/server/src/agents/pull-request-reader.ts b/apps/server/src/agents/pull-request-reader.ts index 44417e256..8dd575495 100644 --- a/apps/server/src/agents/pull-request-reader.ts +++ b/apps/server/src/agents/pull-request-reader.ts @@ -2,6 +2,19 @@ import type { GitHubPullRequestObservation } from "@dispatch/runner-protocol"; import type { AgentPullRequest } from "@dispatch/shared"; import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; +const credentialContexts = new WeakMap(); + +export function pullRequestCredentialContext(pr: AgentPullRequest) { + return credentialContexts.get(pr); +} + +export function githubPullRequestTarget(url: string) { + const canonical = githubPullRequestUrl(url); + if (!canonical) return null; + const [, owner, repo, , number] = new URL(canonical).pathname.split("/"); + return { owner, repo, number: Number(number) }; +} + export function githubPullRequestUrl(value: string): string | null { try { const url = new URL(value); @@ -159,12 +172,15 @@ export function projectPullRequest( : "Open" : "Unavailable"; if (status === "Unavailable") return { url, title, status }; - return { + const pr: AgentPullRequest = { url, status, title: typeof observedTitle === "string" ? observedTitle : title, ci: mapPullRequestChecks(head, rollup), }; + if (observation.credentialContext) + credentialContexts.set(pr, observation.credentialContext); + return pr; } const CHECKS_QUERY = `query($owner: String!, $repo: String!, $number: Int!) { diff --git a/apps/server/src/agents/pull-request-refresher.ts b/apps/server/src/agents/pull-request-refresher.ts index a75c59587..ac23879af 100644 --- a/apps/server/src/agents/pull-request-refresher.ts +++ b/apps/server/src/agents/pull-request-refresher.ts @@ -30,7 +30,8 @@ type Options = { url: string, value: AgentPullRequest, ownerAgentIds: string[], - onProgress?: (risk: NonNullable) => void + onProgress?: (risk: NonNullable) => void, + runnerId?: string | null ) => Promise; warn: (error: unknown) => void; }; @@ -449,8 +450,7 @@ export class PullRequestRefresher { const previous = this.urls.get(key); // An assessor failure cannot establish that history is still enabled. let assessed = false; - // Merge-risk evidence still depends on the native checkout and GitHub account. - if (this.options.assess && runnerId === null) { + if (this.options.assess) { const owners = [...agents] .filter(([, urls]) => urls.has(key)) .map(([id]) => id); @@ -462,6 +462,7 @@ export class PullRequestRefresher { (risk) => { if ( this.stopped || + peerChanged() || this.riskHidden || (this.reviewGeneration.get(key) ?? 0) !== reviewGeneration ) @@ -480,7 +481,8 @@ export class PullRequestRefresher { pullRequests: next, }); } - } + }, + runnerId ); assessed = true; if ( @@ -492,6 +494,13 @@ export class PullRequestRefresher { this.options.warn(error); } } + if (peerChanged()) { + if (target) + throw new Error( + "Runner connection or account changed. Please retry." + ); + continue; + } if ( !this.options.assess && !assessed && @@ -556,7 +565,7 @@ export class PullRequestRefresher { for (const notify of [ lifecycleChanged ? this.options.notify : undefined, checksChanged ? this.options.notifyChecks : undefined, - runnerId === null && !reviewChanged && !this.riskHidden + !reviewChanged && !this.riskHidden ? this.options.notifyRisk : undefined, ]) { diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index c22d3ebe6..f09aa7461 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -1,3 +1,4 @@ +import { GitHubPullRequestEvidence } from "../github-pull-request-evidence.js"; import { pullRequestObservation, pullRequestQueryArgs, @@ -36,6 +37,7 @@ type CommandWrapper = ( /** Commands run with the same dedicated workload HOME as checkout and agents. */ export class GitHubRunnerExecutor { + private readonly evidence: GitHubPullRequestEvidence; private readonly env: NodeJS.ProcessEnv; private login?: Login; private failed = false; @@ -43,7 +45,8 @@ export class GitHubRunnerExecutor { constructor( env: NodeJS.ProcessEnv, - private readonly wrap: CommandWrapper + private readonly wrap: CommandWrapper, + credentialKey?: Buffer ) { this.env = { ...env, @@ -54,12 +57,16 @@ export class GitHubRunnerExecutor { NO_COLOR: "1", LC_ALL: "C", }; + this.evidence = new GitHubPullRequestEvidence( + this.run.bind(this), + credentialKey + ); } - private async run(args: string[], signal: AbortSignal) { + private async run(args: string[], signal: AbortSignal, token?: string) { const command = this.wrap(gh, args); const { stdout } = await execute(command.bin, command.args, { - env: this.env, + env: token ? { ...this.env, GH_TOKEN: token } : this.env, signal, killSignal: "SIGKILL", timeout: 7_000, @@ -269,7 +276,22 @@ export class GitHubRunnerExecutor { })) ); } + case "pullRequestDetails": + return this.evidence.details(operation, signal); + case "pullRequestDiff": + return this.evidence.diff( + operation, + AbortSignal.any([signal, AbortSignal.timeout(18000)]) + ); case "pullRequestStatus": { + if (operation.withCredentialContext) { + // Older workload installations may support the status query but + // lack an exportable credential. Keep status usable without a scope. + const scoped = await this.evidence + .status(operation, signal) + .catch(() => null); + if (scoped) return scoped; + } const { owner, repo, number } = operation; const result = await this.run( pullRequestQueryArgs(owner, repo, String(number)), diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index e5b273c76..c49d2c60e 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -186,10 +186,14 @@ export async function runRemoteRunner(filename: string) { key: readFileSync(config.key), }; const sampleHealth = runnerHealthSampler(); - const github = new GitHubRunnerExecutor(env, (bin, args) => ({ - bin: setpriv, - args: [...childArgs, bin, ...args], - })); + const github = new GitHubRunnerExecutor( + env, + (bin, args) => ({ + bin: setpriv, + args: [...childArgs, bin, ...args], + }), + credentials.key + ); const engineExecutor = new EngineRunnerExecutor({ uid: config.uid, gid: config.gid, @@ -568,6 +572,7 @@ export async function runRemoteRunner(filename: string) { engineManagement: true, githubManagement: true, pullRequestStatus: true, + pullRequestEvidence: true, checkoutInspection: true, checkoutViews: true, sharedWorktree: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 6f294e7bb..f9bf6237a 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1,5 +1,6 @@ import { githubPullRequestUrl, + githubPullRequestTarget, projectPullRequest, } from "../pull-request-reader.js"; import { X509Certificate } from "node:crypto"; @@ -37,6 +38,8 @@ import { type GitHubStatus, parseGitHubStatus, isGitHubPullRequestObservation, + isGitHubPullRequestDetails, + isGitHubPullRequestDiff, githubPullRequestHead, githubRepositoryResults, type SessionOperation, @@ -149,6 +152,7 @@ type Peer = { engineManagement: boolean; githubManagement: boolean; pullRequestStatus: boolean; + pullRequestEvidence: boolean; checkoutInspection: boolean; checkoutViews: boolean; sharedWorktree: boolean; @@ -665,6 +669,7 @@ export class RemoteRunnerService { reportsHealth: ready.health === true, engineManagement: ready.engineManagement === true, pullRequestStatus: ready.pullRequestStatus === true, + pullRequestEvidence: ready.pullRequestEvidence === true, githubManagement: ready.githubManagement === true, checkoutViews: ready.checkoutViews === true, checkoutInspection: ready.checkoutInspection === true, @@ -1224,6 +1229,18 @@ export class RemoteRunnerService { "Update the runner to read pull request status." ); + if ( + operation.kind === "github" && + (operation.operation.type === "pullRequestDetails" || + operation.operation.type === "pullRequestDiff" || + (operation.operation.type === "pullRequestStatus" && + operation.operation.withCredentialContext)) && + !peer.pullRequestEvidence + ) + throw new RunnerCapabilityUnavailable( + "Update the runner to read pull request evidence." + ); + // V1 requires a routable workspace and an id even for a runner-wide operation. for (const workspace of peer.workspaces) { if (peer.gate.allows(workspace)) @@ -1240,10 +1257,13 @@ export class RemoteRunnerService { runnerId: string, operation: GitHubOperation ): Promise { + const peer = this.peers.get(runnerId); const { value } = await this.requestRunner(runnerId, { kind: "github", operation, }); + if (this.peers.get(runnerId) !== peer || !peer?.gate.approved()) + throw new RunnerUnavailable("The runner connection changed."); if (typeof value !== "string") throw new Error("Invalid GitHub reply."); return JSON.parse(value); } @@ -1305,12 +1325,46 @@ export class RemoteRunnerService { owner, repo, number: Number(number), + ...(this.peers.get(runnerId)?.pullRequestEvidence && { + withCredentialContext: true, + }), }); if (!isGitHubPullRequestObservation(response)) throw new Error("Invalid runner pull request observation."); return projectPullRequest(canonical, title, response); } + async readPullRequestDetails(runnerId: string, url: string) { + const target = githubPullRequestTarget(url); + if (!target) return null; + const value = await this.requestGitHub(runnerId, { + ...target, + type: "pullRequestDetails", + }); + return isGitHubPullRequestDetails(value) && value.number === target.number + ? value + : null; + } + + async readPullRequestDiff( + runnerId: string, + url: string, + base: string, + head: string, + credentialContext: string + ) { + const target = githubPullRequestTarget(url); + if (!target) return null; + const value = await this.requestGitHub(runnerId, { + ...target, + type: "pullRequestDiff", + base, + head, + credentialContext, + }); + return isGitHubPullRequestDiff(value) ? value : null; + } + async lookupGitHubPullRequestHead( runnerId: string, owner: string, diff --git a/apps/server/src/db/migrations/0058_merge_risk_evidence_scope.sql b/apps/server/src/db/migrations/0058_merge_risk_evidence_scope.sql new file mode 100644 index 000000000..7f694d474 --- /dev/null +++ b/apps/server/src/db/migrations/0058_merge_risk_evidence_scope.sql @@ -0,0 +1,11 @@ +-- The empty scope is reserved for historical native assessments. +-- Explanations and evidence snapshots inherit their scope through assessment_id. +ALTER TABLE merge_risk_decision_records + ADD COLUMN evidence_scope text NOT NULL DEFAULT '', + ADD COLUMN base_sha text, + DROP CONSTRAINT merge_risk_decision_records_url_head_sha_review_fingerprint_key, + ADD UNIQUE (url, head_sha, review_fingerprint, evidence_scope); + +DROP INDEX merge_risk_decision_records_url; +CREATE INDEX merge_risk_decision_records_scope_history + ON merge_risk_decision_records(url, evidence_scope, created_at DESC, id DESC); diff --git a/apps/server/src/routes/agents/pull-request-routes.ts b/apps/server/src/routes/agents/pull-request-routes.ts index cfce4dd67..81192bcd9 100644 --- a/apps/server/src/routes/agents/pull-request-routes.ts +++ b/apps/server/src/routes/agents/pull-request-routes.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import type { FastifyInstance } from "fastify"; import type { AgentRouteDeps } from "./shared.js"; @@ -30,13 +31,14 @@ export async function registerAgentPullRequestRoutes( return reply .code(403) .send({ error: "Use the browser to explain an assessment." }); - if (!(await deps.agentManager.getAgent(request.params.id))) - return reply.code(404).send({ error: "Agent not found." }); + const agent = await deps.agentManager.getAgent(request.params.id); + if (!agent) return reply.code(404).send({ error: "Agent not found." }); if (!deps.riskExplanations) return reply.code(503).send({ error: "Explanation unavailable." }); - // The id alone identifies the assessment; url stays in the body contract. const result = await deps.riskExplanations.explain({ assessmentId: request.body.assessmentId, + url: request.body.url, + runnerId: remotePlacement(agent.cwd)?.runner ?? null, }); // Reason codes only: never the URL, evidence or provider payload. if (result.state !== "ready" && result.state !== "pending") diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 2724d72d1..b83bd7f2c 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -112,6 +112,9 @@ import { import { BrainStore } from "./brain/store.js"; import { registerActivityRoutes } from "./routes/activity/index.js"; import { createProviderPlansReporter } from "./agents/provider-plans.js"; +import { parseCodeowners } from "./personas/codeowners.js"; +import { LEGACY_OWNERS_PATH, OWNERS_PATH } from "./personas/paths.js"; +import { createMergeRiskGitHubSource } from "./agents/merge-risk/github-source.js"; import { RiskExplanations } from "./agents/merge-risk/explanations.js"; import { registerAgentRoutes } from "./routes/agents/index.js"; import { registerBrainRoutes } from "./routes/brain.js"; @@ -367,8 +370,23 @@ const updateCheckTracker = new SubsystemTracker({ description: "Checks the configured release channel for Dispatch updates.", expectedCadenceMs: 6 * 60 * 60 * 1000, }); +const mergeRiskGitHub = createMergeRiskGitHubSource(remoteRunner); const mergeRiskAssessor = new MergeRiskAssessor({ pool, + github: mergeRiskGitHub, + remoteOwners: async (id, runnerId) => { + const agent = await agentManager.getAgent(id); + if (!agent || remotePlacement(agent.cwd)?.runner !== runnerId) return null; + for (const path of [OWNERS_PATH, LEGACY_OWNERS_PATH]) { + const reply = await agentManager.inspectCheckout(agent, { + kind: "readFile", + path, + }); + if (reply.kind === "readFile" && reply.content !== null) + return parseCodeowners(reply.content, path); + } + return null; + }, settings: routingSettings, agentRoot: async (id) => { const agent = await agentManager.getAgent(id); @@ -383,10 +401,13 @@ const pullRequests = new PullRequestRefresher({ id: agent.id, runnerId: remotePlacement(agent.cwd)?.runner ?? null, })), - read: createRunnerPullRequestReader(remoteRunner), + read: createRunnerPullRequestReader( + remoteRunner, + mergeRiskGitHub.nativeStatus + ), publish: (event) => uiEventBroker.publish(event), - assess: (url, value, owners, onProgress) => - mergeRiskAssessor.assess(url, value, owners, onProgress), + assess: (url, value, owners, onProgress, runnerId) => + mergeRiskAssessor.assess(url, value, owners, onProgress, runnerId), notify: async (id, previous, current, commit) => { await streamService.pullRequestTransition(id, previous, current, commit); }, @@ -1351,6 +1372,7 @@ async function registerRoutes() { pullRequests, riskExplanations: new RiskExplanations({ pool, + github: mergeRiskGitHub, settings: routingSettings, }), onArchivedAgentsDeleted: (deletedIds) => diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts index f363521a7..ee1fefcbb 100644 --- a/apps/server/test/github-runner-executor.test.ts +++ b/apps/server/test/github-runner-executor.test.ts @@ -44,6 +44,10 @@ case "$1 $2" in if [ -f reject ]; then printf 'synthetic-secret\n' >&2; exit 1; fi printf 'fixture-user\n' > login ;; + 'auth token') + test "$*" = 'auth token --hostname github.com' + cat active-token + ;; 'auth setup-git') test "$*" = 'auth setup-git --hostname github.com' git config --global credential.https://github.com.helper "!$0 auth git-credential" @@ -69,15 +73,34 @@ case "$1 $2" in 'api graphql') test "$3 $4" = '--hostname github.com' test "$7 $8 $9" = '-f owner=org -f' - test -f login - cat graphql-response - exit 1 + case "$6" in + *'baseRefOid headRefOid'*) + test "$GH_TOKEN" = 'approved-token' + cat detail-response + ;; + *) + test -f login + cat graphql-response + exit 1 + ;; + esac ;; 'api --hostname') test "$3" = 'github.com' case "$4" in user) if [ -f revoked ]; then printf '(HTTP 401)\n' >&2; exit 1; fi; cat login ;; - repos/org/project/pulls/42) printf '%s' '{"url":"https://github.com/fork/project.git","branch":"fix"}' ;; + repos/org/project/pulls/42) + if [ "$6" = '.number' ]; then + test "$GH_TOKEN" = 'approved-token' + printf '42' + exit 0 + fi + printf '%s' '{"url":"https://github.com/fork/project.git","branch":"fix"}' ;; + repos/org/project/compare/*) + test "$GH_TOKEN" = 'approved-token' + test "$4" = "$(cat compare-path)" + printf '%s' '[{"path":"src/example.ts","additions":1,"deletions":0,"patch":"@@ -1 +1 @@"}]' + ;; *) exit 1 ;; esac ;; @@ -201,6 +224,81 @@ it("completes a device login and configures the same credential helper for an ag }); }); +it("binds bounded PR details and an assessed diff to the workload credential", async () => { + await fixture(async ({ executor, root }) => { + const target = { owner: "org", repo: "project", number: 42 }; + const signal = new AbortController().signal; + const base = "a".repeat(40); + const head = "b".repeat(40); + const metadata = { + number: 42, + title: "Private PR", + body: "Description", + baseRefName: "main", + headRefName: "fix", + baseRefOid: base, + headRefOid: head, + additions: 1, + deletions: 0, + }; + const files = [{ path: "src/example.ts", additions: 1, deletions: 0 }]; + const writeDetails = (hasNextPage: boolean) => + writeFile( + path.join(root, "detail-response"), + JSON.stringify({ + data: { + repository: { + pullRequest: { + ...metadata, + files: { pageInfo: { hasNextPage }, nodes: files }, + }, + }, + }, + }) + ); + await writeFile(path.join(root, "active-token"), "approved-token"); + await writeDetails(false); + await writeFile( + path.join(root, "compare-path"), + `repos/org/project/compare/${base}...${head}` + ); + const details = await executor.handle( + { ...target, type: "pullRequestDetails" }, + signal + ); + expect(details).toEqual({ + ...metadata, + files, + credentialContext: expect.stringMatching(/^[a-f0-9]{64}$/), + }); + if ( + !details || + !("credentialContext" in details) || + !details.credentialContext + ) + throw new Error("Missing credential context"); + const diff = { + ...target, + type: "pullRequestDiff" as const, + base, + head, + credentialContext: details.credentialContext, + }; + expect(await executor.handle(diff, signal)).toEqual({ + files: [{ ...files[0], patch: "@@ -1 +1 @@" }], + }); + await writeDetails(true); + expect( + await executor.handle({ ...target, type: "pullRequestDetails" }, signal) + ).toBeNull(); + await writeFile(path.join(root, "active-token"), "denied-token"); + expect(await executor.handle(diff, signal)).toBeNull(); + await expect( + executor.handle({ ...target, type: "pullRequestDetails" }, signal) + ).rejects.toThrow(); + }); +}); + it("clears pending device codes on cancel, disconnect and failed authorization", async () => { await fixture(async ({ executor, root }) => { let controller = new AbortController(); diff --git a/apps/server/test/merge-risk.test.ts b/apps/server/test/merge-risk.test.ts index 53d25bc03..12fbd0427 100644 --- a/apps/server/test/merge-risk.test.ts +++ b/apps/server/test/merge-risk.test.ts @@ -1,3 +1,5 @@ +import { projectPullRequest } from "../src/agents/pull-request-reader.js"; +import { RiskExplanations } from "../src/agents/merge-risk/explanations.js"; import { afterAll, beforeAll, @@ -607,6 +609,160 @@ describe("merge-risk assessor", () => { readDetails: details, transport, }); + it("isolates PR evidence, reservations and explanations by runner and active credential", async () => { + const url = pr().url; + const head = "1".repeat(40); + const base = "2".repeat(40); + const alpha = "a".repeat(64); + const beta = "b".repeat(64); + const placement = new Map([ + ["first", alpha], + ["second", beta], + ]); + const observe = (credentialContext?: string) => + projectPullRequest(url, "PR", { + title: "PR", + state: "OPEN", + draft: false, + head, + rollup: [], + credentialContext, + }); + const github = { + details: vi.fn(async (runnerId: string | null) => { + const credentialContext = + runnerId === null ? alpha : placement.get(runnerId); + if (!credentialContext) return null; + return { + credentialContext, + number: 9, + title: "PR", + body: + credentialContext === alpha + ? "Alpha private evidence" + : "Beta private evidence", + baseRefName: "main", + headRefName: "topic", + baseRefOid: base, + headRefOid: head, + additions: 2, + deletions: 0, + files: [], + }; + }), + diff: vi.fn(async () => null), + }; + const assessor = new MergeRiskAssessor({ + pool, + settings, + github, + agentRoot: async () => null, + transport, + }); + const explanationTransport = vi.fn(async () => + Response.json({ + status: "completed", + output: [ + { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "Private explanation" }], + }, + ], + }) + ); + const explanations = new RiskExplanations({ + pool, + settings, + github, + transport: explanationTransport, + }); + const legacy = ( + await pool.query( + "INSERT INTO merge_risk_decision_records(url,head_sha,review_fingerprint,status,prompt_version) VALUES($1,$2,$3,'ok','v') RETURNING id", + [url, head, reviewFingerprint([])] + ) + ).rows[0].id; + const first = await assessor.assess( + url, + observe(alpha), + [], + undefined, + "first" + ); + const second = await assessor.assess( + url, + observe(beta), + [], + undefined, + "second" + ); + expect(first?.status).toBe("ok"); + expect(second?.status).toBe("ok"); + expect(first?.assessmentId).not.toBe(second?.assessmentId); + expect(first?.assessmentId).not.toBe(legacy); + expect(transport).toHaveBeenCalledTimes(2); + expect(JSON.stringify(transport.mock.calls[0][1]?.body)).toContain( + "Alpha private evidence" + ); + expect(JSON.stringify(transport.mock.calls[1][1]?.body)).toContain( + "Beta private evidence" + ); + expect( + ( + await pool.query( + "SELECT count(*)::int AS count FROM merge_risk_evidence_snapshots" + ) + ).rows[0].count + ).toBe(2); + + const explain = (assessmentId: string, runnerId: string | null) => + explanations.explain({ assessmentId, runnerId, url }); + const denied = { state: "unavailable", reason: "not_found" }; + expect(await explain(first!.assessmentId!, "first")).toMatchObject({ + state: "ready", + }); + expect(github.diff).toHaveBeenCalledWith( + "first", + url, + base, + head, + alpha, + expect.anything() + ); + expect(await explain(first!.assessmentId!, "second")).toEqual(denied); + expect(await explain(legacy, "first")).toEqual(denied); + expect(await explain(first!.assessmentId!, null)).toEqual(denied); + expect(explanationTransport).toHaveBeenCalledTimes(1); + expect(await explain(legacy, null)).toMatchObject({ state: "ready" }); + + placement.set("first", beta); + expect(await explain(first!.assessmentId!, "first")).toEqual(denied); + expect( + await assessor.assess(url, observe(alpha), [], undefined, "first") + ).toMatchObject({ displayState: "unavailable" }); + const switched = await assessor.assess( + url, + observe(beta), + [], + undefined, + "first" + ); + expect(switched?.status).toBe("ok"); + expect(switched?.assessmentId).not.toBe(first?.assessmentId); + expect(switched?.assessmentId).not.toBe(second?.assessmentId); + expect(transport).toHaveBeenCalledTimes(3); + placement.delete("second"); + expect(await explain(second!.assessmentId!, "second")).toEqual(denied); + expect( + await assessor.assess(url, observe(beta), [], undefined, "second") + ).toMatchObject({ displayState: "unavailable" }); + expect( + await assessor.assess(url, observe(), [], undefined, "older-runner") + ).toMatchObject({ displayState: "unavailable" }); + expect(transport).toHaveBeenCalledTimes(3); + expect(explanationTransport).toHaveBeenCalledTimes(2); + }); async function review(findings: { resolved: boolean }[]) { const posted = await blocks.insert({ streamId: reviewer, diff --git a/apps/server/test/migrations.test.ts b/apps/server/test/migrations.test.ts index afb1133d0..6ed6dc310 100644 --- a/apps/server/test/migrations.test.ts +++ b/apps/server/test/migrations.test.ts @@ -149,6 +149,9 @@ async function dropTasks(): Promise { await pool.query( "DELETE FROM pgmigrations WHERE name = '0042_visualization_blocks'" ); + await pool.query( + "DELETE FROM pgmigrations WHERE name = '0058_merge_risk_evidence_scope'" + ); await pool.query( "DROP TABLE IF EXISTS merge_risk_decision_records, merge_risk_decision_daily" ); diff --git a/apps/server/test/pull-request-refresher.test.ts b/apps/server/test/pull-request-refresher.test.ts index a8a5bd1be..1cc95353d 100644 --- a/apps/server/test/pull-request-refresher.test.ts +++ b/apps/server/test/pull-request-refresher.test.ts @@ -96,7 +96,20 @@ describe("server PR orchestration", () => { status: "Unavailable", }); expect(f.read).not.toHaveBeenCalled(); - expect(assess).not.toHaveBeenCalled(); + expect(assess).toHaveBeenCalledWith( + url, + expect.objectContaining({ status: "Open" }), + ["a"], + expect.any(Function), + "alpha" + ); + expect(assess).toHaveBeenCalledWith( + url, + expect.objectContaining({ status: "Unavailable" }), + ["b"], + expect.any(Function), + "beta" + ); readRemote.mockClear(); await expect(service.refreshOne("b", url)).rejects.toThrow("GitHub"); expect(readRemote.mock.calls.map(([id]) => id)).toEqual(["beta"]); @@ -723,7 +736,8 @@ it("attaches merge-risk assessments to observed heads and carries them while the "https://github.com/a/b/pull/0", expect.objectContaining({ status: "Open" }), ["a"], - expect.any(Function) + expect.any(Function), + null ); expect(service.get("a")[0]!.mergeRisk?.verdict).toBe("routine"); // A later observation of the same head without a fresh assessment keeps the verdict; diff --git a/apps/server/test/pull-request-risk-explanation-routes.test.ts b/apps/server/test/pull-request-risk-explanation-routes.test.ts index 1eb758b19..f6ec703f7 100644 --- a/apps/server/test/pull-request-risk-explanation-routes.test.ts +++ b/apps/server/test/pull-request-risk-explanation-routes.test.ts @@ -7,7 +7,8 @@ it("validates the click contract, rejects agent bearer requests and scopes calls const explain = vi.fn().mockResolvedValue({ state: "unavailable" }); await registerAgentPullRequestRoutes(app, { agentManager: { - getAgent: async (id: string) => (id === "owner" ? { id } : null), + getAgent: async (id: string) => + id === "owner" ? { id, cwd: "runner://runner-a/workspace" } : null, }, riskExplanations: { explain }, } as unknown as AgentRouteDeps); @@ -53,7 +54,8 @@ it("validates the click contract, rejects agent bearer requests and scopes calls expect(res.statusCode).toBe(200); expect(res.headers["cache-control"]).toBe("no-store"); expect(explain).toHaveBeenCalledWith({ - assessmentId: payload.assessmentId, + ...payload, + runnerId: "runner-a", }); } finally { await app.close(); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index b59ee2928..60b508455 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -60,6 +60,8 @@ function dialRunner(input: { managedWorkspace?: true; sharedWorktree?: true; checkoutInspection?: true; + githubManagement?: true; + pullRequestStatus?: true; }): Promise { const url = new URL(input.endpoint); return new Promise((resolve, reject) => { @@ -90,6 +92,8 @@ function dialRunner(input: { managedWorkspace: input.managedWorkspace, sharedWorktree: input.sharedWorktree, checkoutInspection: input.checkoutInspection, + githubManagement: input.githubManagement, + pullRequestStatus: input.pullRequestStatus, }); resolve({ socket, closed, requests }); }); @@ -198,6 +202,48 @@ describe("runner enrollment service", () => { await teardownTestDb(); }); + it("keeps PR status enabled on a peer without the evidence capability", async () => { + const service = makeService(); + const enrolled = await enroll(service, "legacy-github"); + const peer = await dialRunner({ + ...enrolled, + workspaces: ["work"], + githubManagement: true, + pullRequestStatus: true, + label: JSON.stringify({ + state: "OPEN", + draft: false, + title: "PR", + head: null, + rollup: null, + }), + }); + runners.push(peer); + const runnerId = enrolled.created.id; + await waitFor(() => + service.available({ runner: runnerId, workspace: "work" }) + ); + const url = "https://github.com/example/repo/pull/1"; + expect( + await service.readPullRequest(runnerId, url, "fallback") + ).toMatchObject({ status: "Open" }); + await expect(service.readPullRequestDetails(runnerId, url)).rejects.toThrow( + /update.*evidence/i + ); + await expect( + service.readPullRequestDiff( + runnerId, + url, + "a".repeat(40), + "b".repeat(40), + "a".repeat(64) + ) + ).rejects.toThrow(/update.*evidence/i); + expect( + peer.requests.filter((frame) => frame.type === "request") + ).toHaveLength(1); + }); + it("pairs with a one-time code over a pinned CA and lists the runner", async () => { const service = makeService(); const created = await service.createRegistration("alpha"); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 9fed9bfe8..639979b95 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -16,6 +16,8 @@ import { sessionCommandId, isOpaqueId, isCheckoutReply, + isGitHubPullRequestDetails, + isGitHubPullRequestDiff, isCheckoutViewData, remotePlacement, workspaceLocator, @@ -120,6 +122,7 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () engineManagement: true, githubManagement: true, pullRequestStatus: true, + pullRequestEvidence: true, checkoutInspection: true, checkoutViews: true, sharedWorktree: true, @@ -559,6 +562,24 @@ it("recognizes only supported enrollment replies and retains their extensions", // Independent service and deterministic runner peer. Both sides speak NDJSON; // runner session state outlives the service's authenticated connection. +const githubTarget = { owner: "example", repo: "repo", number: 42 }; +const githubDetails = { + credentialContext: "c".repeat(64), + number: 42, + title: "Sample", + body: "Private source", + baseRefName: "main", + headRefName: "feature", + baseRefOid: "a".repeat(40), + headRefOid: "b".repeat(40), + additions: 1, + deletions: 0, + files: [{ path: "source.ts", additions: 1, deletions: 0 }], +}; +const githubDiff = { + files: [{ ...githubDetails.files[0], patch: "@@ -1 +1 @@\n-old\n+new" }], +}; + function fixtureRunner(current: boolean) { const workspace = current ? "@session" : "workload/β"; const agentId = "collector/requests%2F:42"; @@ -571,6 +592,8 @@ function fixtureRunner(current: boolean) { managedWorkspace: true, health: true, engineManagement: true, + githubManagement: true, + pullRequestEvidence: true, }), }; const sample = { @@ -659,6 +682,22 @@ function fixtureRunner(current: boolean) { ) { const ack: EngineOperationAck = { ok: true }; result(JSON.stringify(ack)); + } else if ( + current && + command.kind === "github" && + command.workspace === workspace + ) { + if (command.operation.type === "pullRequestDetails") + result(JSON.stringify(githubDetails)); + else if ( + command.operation.type === "pullRequestDiff" && + command.operation.credentialContext === + githubDetails.credentialContext && + command.operation.base === githubDetails.baseRefOid && + command.operation.head === githubDetails.headRefOid + ) + result(JSON.stringify(githubDiff)); + else result("null"); } else if ( command.workspace !== workspace || command.agentId !== agentId @@ -836,6 +875,48 @@ it.each([true, false])( : { unavailable: true } ); + if (ready?.githubManagement && ready.pullRequestEvidence) { + const route = { + kind: "github" as const, + workspace: runner.session.workspace, + agentId: "collector/evidence", + }; + const details = JSON.parse( + String( + ( + await peer.connection.request({ + ...route, + operation: { type: "pullRequestDetails", ...githubTarget }, + }) + ).value + ) + ); + expect(isGitHubPullRequestDetails(details)).toBe(true); + expect(details).toEqual(githubDetails); + const diff = JSON.parse( + String( + ( + await peer.connection.request({ + ...route, + operation: { + type: "pullRequestDiff", + ...githubTarget, + credentialContext: details.credentialContext, + base: details.baseRefOid, + head: details.headRefOid, + }, + }) + ).value + ) + ); + expect(isGitHubPullRequestDiff(diff)).toBe(true); + expect(diff).toEqual(githubDiff); + } + expect( + runner.requests.some( + (frame) => frame.type === "request" && frame.command.kind === "github" + ) + ).toBe(current); const first = await attach(); first.send({ type: "hello", fromSeq: 0, replayComplete: true }); const welcome = await first.take(); diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index d77a64f92..6cd2f664b 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -58,7 +58,7 @@ A native host can complete an accepted turn while its controller is down. A repl **Discover repositories and interact with GitHub.** **Partial.** Runner Git can provision a checkout. Repository search, PR head lookup and tracked PR status/checks use the selected runner’s GitHub account. Dispatch schedules reads and publishes the results to the UI. Moving merge-risk evidence to the runner and having the runner push PR changes are the next steps in the [parity rollout](runner-parity-rollout.md). A project association alone grants no GitHub access. -- From a fresh runner account, sign in to GitHub, clone a private test repo, fetch a fork PR, and verify the identity used for push and PR creation. Sign out and verify isolation from other runners. Local-only review must also work with no published branch. [Search](../../apps/server/src/routes/runner-repositories.ts) · [PR reader](../../apps/server/src/agents/pull-request-reader.ts) · [Refresh](../../apps/server/src/agents/pull-request-refresher.ts) · [Risk inputs](../../apps/server/src/agents/merge-risk/sources.ts) +- From a fresh runner account, sign in to GitHub, clone a private test repo, fetch a fork PR, and verify the identity used for push and PR creation. Sign out and verify isolation from other runners. Local-only review must also work with no published branch. [Search](../../apps/server/src/routes/runner-repositories.ts) · [PR reader](../../apps/server/src/agents/pull-request-reader.ts) · [Refresh](../../apps/server/src/agents/pull-request-refresher.ts) · [Risk inputs](../../apps/server/src/agents/merge-risk/github-source.ts) **Browse workspace files.** **Present.** Both placements serve directory listings, ignored-file filtering, filename searches and bounded previews from the session checkout. Open tabs refresh on runner notifications and reconcile after a disconnect. diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index ae8143281..d81448b18 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -17,7 +17,9 @@ The branch already exercises session supervision, shared reviewer checkouts, che Scheduled and manual PR reads now use the selected runner. The optional `pullRequestStatus` capability returns lifecycle and current-head checks. Dispatch isolates cached observations, in-flight replies and notices by runner and URL. The Linux browser fixture posts a private PR, observes an initial check, changes the fixture on the runner, then refreshes to see the new check. -Two pieces remain in this stage. First, move the PR details and assessment diff readers to the owning workload. Scope assessment reservations, prior decisions, explanations and their evidence to the placement before enabling remote assessments. The current assessment history looks up by URL alone. Existing unscoped rows should remain native-only. Second, let the runner watch the tracked set, send a current snapshot on subscribe or reconnect, and send subsequent changes. Test stale connections, bounded polling, manual refresh and the last subscriber leaving. Browser updates continue through the existing Dispatch event stream. +Merge-risk details and commit comparisons now use the owning runner's GitHub credential. Dispatch matches the credential context from the status and details reads, partitions assessment reservations and history by runner and credential, and checks current PR access before using saved explanations. Unscoped assessments are visible only to the native placement. The wire returns GitHub source fields. Dispatch retains evidence selection, review history, policy and paid calls. An older runner can still report lifecycle and checks. + +Tracked-PR subscriptions remain to be implemented. Let the runner watch the tracked set, send current snapshots on subscribe or reconnect, and send subsequent changes. Test stale connections, bounded polling, manual refresh and the last subscriber leaving. Browser updates continue through the existing Dispatch event stream. ## Live updates diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index f03547474..67183ef48 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -139,7 +139,7 @@ The service prepares this text and any instructions it wants included. | `inspectCheckout` | Run a `CheckoutQuery` against the bound checkout and return a JSON-encoded `CheckoutReply`. Validate it with `isCheckoutReply`. | `checkoutInspection`. | | `viewCheckout` / `watchCheckout` | Read a checkout view or subscribe to change pulses. See below. | `checkoutViews`. | | `engine` | Run an `EngineOperation` and return a JSON-encoded `EngineOperationAck`. When progress is available, stream NDJSON `EngineOperationEvent` records. | `engineManagement`. Open a channel when consuming progress. | -| `github` | Perform a `GitHubOperation` using the runner account and return its JSON reply. See below. | `githubManagement`, plus `pullRequestStatus` for current-head checks. | +| `github` | Perform a `GitHubOperation` using the runner account and return its JSON reply. See below. | `githubManagement`, plus `pullRequestStatus` for current-head checks or `pullRequestEvidence` for details and diffs. | Use an advertised workspace and an opaque placeholder `agentId` for the runner-wide `engine` and `github` operations. The runner routes those @@ -296,3 +296,38 @@ array means no checks. Null means incomplete, unavailable, truncated, or mismatched head. An inaccessible PR has no state. Leave CLI output and GraphQL diagnostics on the runner. Consumers validate the result and scope cached observations and notifications to the runner and canonical URL. + +A peer advertising `githubManagement` and `pullRequestEvidence` accepts +two additional GitHub operations. Both use the same `owner`, `repo` and +positive PR `number` as the status request. + +- `{type: "pullRequestDetails", owner, repo, number}` returns + `{credentialContext, number, title, body, baseRefName, headRefName, +baseRefOid, headRefOid, additions, deletions, files}`. The files contain + provider paths and line counts. The fixed query includes up to 100 files. + An incomplete, denied, or oversized read is unavailable. +- `{type: "pullRequestDiff", owner, repo, number, base, head, credentialContext}` + returns `{files}` for the GitHub comparison between those full commit SHAs. + The runner checks that the supplied credential context is still active and + can read the PR before it compares the commits. GitHub supplies up to 300 + changed files. Files can include a `patch` of up to 32,768 characters. + +Replies use the existing JSON string carried by the `github` result. A +JSON `null` or unsuccessful result means unavailable. The supplied Linux +runner caps CLI output at 128 KiB per call and discards provider error +details. It pins the credential across all GitHub calls within an operation. + +When the peer also advertises `pullRequestStatus`, a consumer may request +`withCredentialContext: true` on a status operation. A scoped observation +includes `credentialContext` alongside the original fields. A status-only +observation can still be returned if a credential context was unavailable. +Send the flag and the new operations only after negotiation. Existing +consumers can continue to use the original status request and response. + +A credential context is an opaque 64-character lowercase hexadecimal handle +for equality comparisons. Treat it as runner-local and sensitive metadata. +It does not grant authority to read GitHub. Credential or runner key changes +can invalidate it. To join provider data or reuse a saved result, match the +runner, repository and PR, relevant commits, and credential context from a +successful fresh read. Keep application policy, derived judgments, and +history in the service that requested the GitHub data. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 1a7d96d81..3cc5008a0 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -80,6 +80,7 @@ export type ReadyFrame = { engineManagement?: true; githubManagement?: true; pullRequestStatus?: true; + pullRequestEvidence?: true; checkoutInspection?: true; checkoutViews?: true; sharedWorktree?: true; @@ -110,6 +111,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.sharedWorktree === true && { sharedWorktree: true }), ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), + ...(frame.pullRequestEvidence === true && { pullRequestEvidence: true }), ...(frame.pullRequestStatus === true && { pullRequestStatus: true }), ...(frame.githubManagement === true && { githubManagement: true }), ...(frame.managedWorkspace === true && { managedWorkspace: true }), diff --git a/packages/runner-protocol/src/github.ts b/packages/runner-protocol/src/github.ts index 407eb1df8..0b17456bc 100644 --- a/packages/runner-protocol/src/github.ts +++ b/packages/runner-protocol/src/github.ts @@ -3,15 +3,111 @@ import { isRecord } from "./validation.js"; export const githubDeviceUrl = "https://github.com/login/device"; +export type GitHubPullRequestTarget = { + owner: string; + repo: string; + number: number; +}; + export type GitHubOperation = | { type: "status" | "login" | "cancel" | "logout" } | { type: "repositorySearch"; query: string } - | { - type: "pullRequestHead" | "pullRequestStatus"; - owner: string; - repo: string; - number: number; - }; + | (GitHubPullRequestTarget & + ( + | { type: "pullRequestHead" | "pullRequestDetails" } + | { type: "pullRequestStatus"; withCredentialContext?: true } + | { + type: "pullRequestDiff"; + base: string; + head: string; + credentialContext: string; + } + )); + +export type GitHubChangedFile = { + path: string; + additions: number; + deletions: number; + patch?: string; +}; + +export type GitHubPullRequestDetails = { + credentialContext: string; + number: number; + title: string; + body: string; + baseRefName: string; + headRefName: string; + baseRefOid: string; + headRefOid: string; + additions: number; + deletions: number; + files: GitHubChangedFile[]; +}; + +export type GitHubPullRequestDiff = { + files: GitHubChangedFile[]; +}; + +export function validGitHubCommit(value: unknown): value is string { + return typeof value === "string" && /^[0-9a-f]{40}$/i.test(value); +} + +function validCredentialContext(value: unknown): value is string { + return typeof value === "string" && /^[0-9a-f]{64}$/.test(value); +} + +function count(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} + +function boundedString(value: unknown, limit: number): value is string { + return typeof value === "string" && value.length <= limit; +} + +function validFile(value: unknown, diff: boolean): boolean { + return ( + isRecord(value) && + boundedString(value.path, 4096) && + value.path.length > 0 && + count(value.additions) && + count(value.deletions) && + (value.patch === undefined || (diff && boundedString(value.patch, 32768))) + ); +} + +export function isGitHubPullRequestDetails( + value: unknown +): value is GitHubPullRequestDetails { + return ( + isRecord(value) && + validCredentialContext(value.credentialContext) && + count(value.number) && + value.number > 0 && + boundedString(value.title, 1024) && + boundedString(value.body, 65536) && + boundedString(value.baseRefName, 1024) && + boundedString(value.headRefName, 1024) && + validGitHubCommit(value.baseRefOid) && + validGitHubCommit(value.headRefOid) && + count(value.additions) && + count(value.deletions) && + Array.isArray(value.files) && + value.files.length <= 100 && + value.files.every((file) => validFile(file, false)) + ); +} + +export function isGitHubPullRequestDiff( + value: unknown +): value is GitHubPullRequestDiff { + return ( + isRecord(value) && + Array.isArray(value.files) && + value.files.length <= 300 && + value.files.every((file) => validFile(file, true)) + ); +} /** Result of the fixed current-head query. An inaccessible PR has a null state. * An empty rollup is authoritative. A null rollup is incomplete or unavailable. */ @@ -21,6 +117,7 @@ export type GitHubPullRequestObservation = { title: string | null; head: string | null; rollup: unknown[] | null; + credentialContext?: string; }; export function isGitHubPullRequestObservation( @@ -32,6 +129,8 @@ export function isGitHubPullRequestObservation( value.state === "OPEN" || value.state === "CLOSED" || value.state === "MERGED") && + (value.credentialContext === undefined || + validCredentialContext(value.credentialContext)) && typeof value.draft === "boolean" && (value.title === null || typeof value.title === "string") && (value.head === null || typeof value.head === "string") && @@ -83,7 +182,16 @@ export function isGitHubOperation(value: unknown): value is GitHubOperation { return validRepositorySearch(value.query); case "pullRequestStatus": case "pullRequestHead": + case "pullRequestDetails": + case "pullRequestDiff": return ( + (value.type !== "pullRequestStatus" || + value.withCredentialContext === undefined || + value.withCredentialContext === true) && + (value.type !== "pullRequestDiff" || + (validGitHubCommit(value.base) && + validGitHubCommit(value.head) && + validCredentialContext(value.credentialContext))) && validGitHubRepoPart(value.owner) && validGitHubRepoPart(value.repo) && typeof value.number === "number" && From cd048d2e6352a62a9c659fd14413a3ed78a18f69 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 14:54:10 -0700 Subject: [PATCH 126/642] Keep historical explanations pinned to assessed commits --- .../src/agents/merge-risk/explanation-diff.ts | 28 ++- .../src/agents/merge-risk/explanations.ts | 147 ++++++++-------- .../pull-request-risk-explanations.test.ts | 163 ++++++++++++++---- 3 files changed, 215 insertions(+), 123 deletions(-) diff --git a/apps/server/src/agents/merge-risk/explanation-diff.ts b/apps/server/src/agents/merge-risk/explanation-diff.ts index 3a1fb3881..308fc295a 100644 --- a/apps/server/src/agents/merge-risk/explanation-diff.ts +++ b/apps/server/src/agents/merge-risk/explanation-diff.ts @@ -1,6 +1,6 @@ /** * Diff hunks for an explanation, read at click time and pinned to the - * assessed commit: the PR's base sha compared with the assessed head sha, so + * assessed base and head SHAs, so * later pushes never change what is explained. Never stored; read-only `gh`. * Any failure yields null and the explanation proceeds without hunks. */ @@ -116,7 +116,7 @@ function repoOf(url: string) { const match = new URL(url).pathname.match( /^\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)\/?$/ ); - return match ? { repo: `${match[1]}/${match[2]}`, number: match[3]! } : null; + return match ? `${match[1]}/${match[2]}` : null; } /** Text of review findings, used only to rank files they mention. */ @@ -136,30 +136,24 @@ export function mentionedText(evidence: unknown): string { export async function readAssessedDiff( url: string, + base: string, headSha: string, evidence: unknown, run: CommandRunner = runCommand ): Promise { try { - const target = repoOf(url); - if (!target || !/^[0-9a-f]{7,40}$/i.test(headSha)) return null; - const pull = await run( - "gh", - [ - "api", - `repos/${target.repo}/pulls/${target.number}`, - "--jq", - ".base.sha", - ], - { timeoutMs: 15_000, allowedExitCodes: [0, 1] } - ); - const base = pull.stdout.trim(); - if (pull.exitCode !== 0 || !/^[0-9a-f]{40}$/i.test(base)) return null; + const repo = repoOf(url); + if ( + !repo || + !/^[0-9a-f]{40}$/i.test(base) || + !/^[0-9a-f]{7,40}$/i.test(headSha) + ) + return null; const compare = await run( "gh", [ "api", - `repos/${target.repo}/compare/${base}...${headSha}`, + `repos/${repo}/compare/${base}...${headSha}`, "--jq", "[.files[] | {path: .filename, additions, deletions, patch}]", ], diff --git a/apps/server/src/agents/merge-risk/explanations.ts b/apps/server/src/agents/merge-risk/explanations.ts index c1eded9d1..a386ab232 100644 --- a/apps/server/src/agents/merge-risk/explanations.ts +++ b/apps/server/src/agents/merge-risk/explanations.ts @@ -32,6 +32,7 @@ export type ExplanationReply = | { state: "limited"; reason: "concurrency" } | { state: "failed"; reason: ExplanationFailure | "unknown" }; type Reply = ExplanationReply; +type ExistingReply = Extract; type Assessment = { url: string; head_sha: string; @@ -115,77 +116,30 @@ export class RiskExplanations { config === (await this.deps.settings.configuration()); if (!(await unchanged())) return { state: "unavailable", reason: "config_changed" }; - const client = await this.deps.pool.connect(); - try { - await client.query("BEGIN"); - const capacity = await mergeRiskCapacity(client); - const stored = ( - await client.query<{ - status: string; - result: { - text?: string; - limitedEvidence?: boolean; - version?: string; - }; - }>( - "SELECT status,result FROM merge_risk_explanations WHERE assessment_id=$1", - [input.assessmentId] - ) - ).rows[0]; - // An explanation from an older prompt/model is not reused: it regenerates. - if (stored?.status === "pending") { - await client.query("COMMIT"); - return (await authorized()) - ? { state: "pending" } - : { state: "unavailable", reason: "not_found" }; - } - if ( - stored?.status === "ok" && - stored.result.version === EXPLANATION_VERSION - ) { - await client.query("COMMIT"); - if (!(await authorized())) - return { state: "unavailable", reason: "not_found" }; - return { - state: "ready", - text: stored.result.text, - ...(stored.result.limitedEvidence - ? { limitedEvidence: true as const } - : {}), - }; - } - if (capacity !== "pending") { - await client.query("COMMIT"); - return { state: "limited", reason: "concurrency" }; - } - await client.query( - "INSERT INTO merge_risk_explanations(assessment_id,status) VALUES($1,'pending') ON CONFLICT(assessment_id) DO UPDATE SET status='pending',created_at=now()", - [input.assessmentId] - ); - await client.query("COMMIT"); - } catch (error) { - await client.query("ROLLBACK"); - throw error; - } finally { - client.release(); + const existing = await this.reserve(input.assessmentId); + if (existing) { + if (existing.state === "limited" || (await authorized())) return existing; + return { state: "unavailable", reason: "not_found" }; } - // Without saved evidence the model may not name files, so no hunks. - const diff = limitedEvidence - ? null - : github && details - ? await github.diff( - runnerId, - assessment.url, - assessment.base_sha ?? details.baseRefOid, - assessment.head_sha, - details.credentialContext, - assessment.evidence - ) - : await (this.deps.readDiff ?? readAssessedDiff)( - assessment.url, - assessment.head_sha, - assessment.evidence - ).catch(() => null); + // Hunks require saved evidence and both commits from the assessment. + const diff = + limitedEvidence || !assessment.base_sha + ? null + : github && details + ? await github.diff( + runnerId, + assessment.url, + assessment.base_sha, + assessment.head_sha, + details.credentialContext, + assessment.evidence + ) + : await (this.deps.readDiff ?? readAssessedDiff)( + assessment.url, + assessment.base_sha, + assessment.head_sha, + assessment.evidence + ).catch(() => null); if (!(await authorized())) { await this.finish(input.assessmentId, "stale", { reason: "not_found" }); return { state: "unavailable", reason: "not_found" }; @@ -239,6 +193,59 @@ export class RiskExplanations { reason: result.status === "error" ? result.reason : "unknown", }; } + private async reserve( + assessmentId: string + ): Promise { + const client = await this.deps.pool.connect(); + try { + await client.query("BEGIN"); + const capacity = await mergeRiskCapacity(client); + const stored = ( + await client.query<{ + status: string; + result: { + text?: string; + limitedEvidence?: boolean; + version?: string; + }; + }>( + "SELECT status,result FROM merge_risk_explanations WHERE assessment_id=$1", + [assessmentId] + ) + ).rows[0]; + let reply: ExistingReply | undefined; + // An explanation from an older prompt/model is regenerated. + if (stored?.status === "pending") { + reply = { state: "pending" }; + } else if ( + stored?.status === "ok" && + stored.result.version === EXPLANATION_VERSION + ) { + reply = { + state: "ready", + text: stored.result.text, + ...(stored.result.limitedEvidence + ? { limitedEvidence: true as const } + : {}), + }; + } else if (capacity !== "pending") { + reply = { state: "limited", reason: "concurrency" }; + } else { + await client.query( + "INSERT INTO merge_risk_explanations(assessment_id,status) VALUES($1,'pending') ON CONFLICT(assessment_id) DO UPDATE SET status='pending',created_at=now()", + [assessmentId] + ); + } + await client.query("COMMIT"); + return reply; + } catch (error) { + await client.query("ROLLBACK"); + throw error; + } finally { + client.release(); + } + } + private async finish(id: string, status: string, result: unknown) { await this.deps.pool.query( `UPDATE merge_risk_explanations SET status=$2,result=(result || $3::jsonb) || diff --git a/apps/server/test/pull-request-risk-explanations.test.ts b/apps/server/test/pull-request-risk-explanations.test.ts index 32c2c9c09..bb8e39e4c 100644 --- a/apps/server/test/pull-request-risk-explanations.test.ts +++ b/apps/server/test/pull-request-risk-explanations.test.ts @@ -1,9 +1,14 @@ import { retainedEvidence } from "../src/agents/merge-risk/explanation-evidence.js"; import { beforeAll, beforeEach, afterAll, it, expect, vi } from "vitest"; import { createHash } from "node:crypto"; -import type { Pool } from "pg"; +import { Pool } from "pg"; import type { AgentPullRequest } from "@dispatch/shared"; -import { setupTestDb, runTestMigrations, teardownTestDb } from "./db/setup.js"; +import { + getTestDatabaseUrl, + setupTestDb, + runTestMigrations, + teardownTestDb, +} from "./db/setup.js"; import { RiskExplanations, followupEvidence, @@ -786,8 +791,13 @@ it("regenerates explanations saved under an older prompt version and reuses the expect(transport).toHaveBeenCalledTimes(1); }); it("sends assessed-commit hunks with the evidence, redacted", async () => { + const base = "b".repeat(40); + await pool.query( + "UPDATE merge_risk_decision_records SET base_sha=$2 WHERE id=$1", + [id, base] + ); readDiff.mockResolvedValue({ - base: "b".repeat(40), + base, files: [ { path: "auth/session.ts", @@ -799,6 +809,7 @@ it("sends assessed-commit hunks with the evidence, redacted", async () => { expect((await service().explain(input())).state).toBe("ready"); expect(readDiff).toHaveBeenCalledWith( "https://github.com/example/repo/pull/1", + base, "abc", expect.anything() ); @@ -808,6 +819,101 @@ it("sends assessed-commit hunks with the evidence, redacted", async () => { expect(payload).toContain("auth/session.ts"); expect(payload).not.toContain("sk-abcdefghijklmnop"); }); +const currentDetails = { + credentialContext: "a".repeat(64), + number: 1, + title: "Sessions", + body: "Current PR description", + baseRefName: "release", + headRefName: "topic", + baseRefOid: "d".repeat(40), + headRefOid: "e".repeat(40), + additions: 1, + deletions: 0, + files: [], +}; + +it("uses the saved snapshot without fetching hunks for a legacy PR retargeted since assessment", async () => { + await pool.query( + "UPDATE merge_risk_evidence_snapshots SET evidence=evidence || $2::jsonb WHERE assessment_id=$1", + [id, JSON.stringify({ pull_request: { base: "main" } })] + ); + const github = { + details: vi.fn(async () => currentDetails), + diff: vi.fn(async () => null), + }; + const explanations = new RiskExplanations({ + pool, + settings, + github, + transport, + }); + expect( + await explanations.explain({ assessmentId: id, url: pr.url }) + ).toMatchObject({ state: "ready" }); + expect(github.diff).not.toHaveBeenCalled(); + const request = JSON.parse(String(transport.mock.calls[0]![1]!.body)); + const payload = JSON.parse(request.input[0].content[0].text); + expect(payload.context.evidenceRetained).toBe(true); + expect(payload.evidence.pull_request.base).toBe("main"); + expect(payload).not.toHaveProperty("diff"); +}); + +it.each([ + ["pending", null, { state: "unavailable", reason: "not_found" }], + ["ok", currentDetails, { state: "ready", text: "Saved explanation" }], +] as const)( + "releases the single pool connection during authorization of a stored %s reply", + async (status, recheckedDetails, expected) => { + await pool.query( + "INSERT INTO merge_risk_explanations(assessment_id,status,result) VALUES($1,$2,$3)", + [ + id, + status, + JSON.stringify({ + version: EXPLANATION_VERSION, + text: "Saved explanation", + }), + ] + ); + const single = new Pool({ + connectionString: getTestDatabaseUrl(), + max: 1, + connectionTimeoutMillis: 1000, + }); + let release!: (details: typeof currentDetails | null) => void; + const delayed = new Promise((resolve) => { + release = resolve; + }); + const github = { + details: vi + .fn() + .mockResolvedValueOnce(currentDetails) + .mockImplementationOnce(() => delayed), + diff: vi.fn(async () => null), + }; + const explanations = new RiskExplanations({ + pool: single, + settings, + github, + transport, + }); + const explaining = explanations.explain({ assessmentId: id, url: pr.url }); + try { + await vi.waitFor(() => expect(github.details).toHaveBeenCalledTimes(2)); + expect(single.totalCount).toBe(1); + expect(await single.query("SELECT 1 AS available")).toMatchObject({ + rows: [{ available: 1 }], + }); + } finally { + release(recheckedDetails); + await explaining.finally(() => single.end()); + } + expect(await explaining).toEqual(expected); + expect(transport).not.toHaveBeenCalled(); + } +); + it("prioritises source and migrations over tests, docs and lockfiles within the budget", () => { const patch = (n: number) => Array.from({ length: n }, (_, i) => `@@ -${i} +${i} @@\n+line ${i}`).join( @@ -882,42 +988,27 @@ it("never sends hunks from secret-bearing files", () => { expect(picked.files.map((f) => f.path)).toEqual(["src/env.ts"]); expect(picked.omitted_files).toBe(files.length); }); -it("reads hunks pinned to the PR base sha and assessed head, and degrades to none on gh failure", async () => { +it("reads hunks pinned to the assessed base and head, and degrades to none on gh failure", async () => { const base = "c".repeat(40); - const run = vi.fn(async (_cmd: string, args: string[]) => - args[1]!.includes("/compare/") - ? { - exitCode: 0, - stderr: "", - stdout: JSON.stringify([ - { - path: "src/a.ts", - additions: 1, - deletions: 0, - patch: "@@ -1 +1 @@\n+a", - }, - ]), - } - : { exitCode: 0, stderr: "", stdout: `${base}\n` } - ); - const diff = await readAssessedDiff( - "https://github.com/o/r/pull/9", - "abc1234", - {}, - run - ); - expect(run.mock.calls[0]![1]).toContain("repos/o/r/pulls/9"); - expect(run.mock.calls[1]![1]).toContain( + const run = vi.fn(async (_cmd: string, _args: string[]) => ({ + exitCode: 0, + stderr: "", + stdout: JSON.stringify([ + { + path: "src/a.ts", + additions: 1, + deletions: 0, + patch: "@@ -1 +1 @@\n+a", + }, + ]), + })); + const url = "https://github.com/o/r/pull/9"; + const diff = await readAssessedDiff(url, base, "abc1234", {}, run); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]![1]).toContain( `repos/o/r/compare/${base}...abc1234` ); expect(diff?.files).toEqual([{ path: "src/a.ts", patch: "@@ -1 +1 @@\n+a" }]); const failing = vi.fn(async () => ({ exitCode: 1, stdout: "", stderr: "x" })); - expect( - await readAssessedDiff( - "https://github.com/o/r/pull/9", - "abc1234", - {}, - failing - ) - ).toBeNull(); + expect(await readAssessedDiff(url, base, "abc1234", {}, failing)).toBeNull(); }); From b8030d05abb0485b44a2cd8c7faf8ffdd41f8f25 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 15:09:58 -0700 Subject: [PATCH 127/642] Subscribe to pull request observations on owning runners --- .../src/agents/pull-request-observations.ts | 130 +++++++++++++ apps/server/src/agents/pull-request-reader.ts | 20 +- .../src/agents/pull-request-refresher.ts | 152 +++++++++++++--- .../remote/github-pull-request-watches.ts | 172 ++++++++++++++++++ .../agents/remote/github-runner-executor.ts | 3 + apps/server/src/agents/remote/runner.ts | 62 ++++++- apps/server/src/agents/remote/service.ts | 79 +++++++- apps/server/src/server.ts | 1 + .../test/github-pull-request-watches.test.ts | 111 +++++++++++ .../test/pull-request-refresher.test.ts | 80 ++++++++ .../test/runner-protocol-consumer.test.ts | 84 ++++++++- docs/design/runner-parity-rollout.md | 4 +- e2e/remote-runner/github-account.spec.ts | 43 ++++- packages/runner-protocol/README.md | 36 ++++ packages/runner-protocol/src/execution.ts | 2 + packages/runner-protocol/src/github.ts | 78 +++++++- 16 files changed, 994 insertions(+), 63 deletions(-) create mode 100644 apps/server/src/agents/pull-request-observations.ts create mode 100644 apps/server/src/agents/remote/github-pull-request-watches.ts create mode 100644 apps/server/test/github-pull-request-watches.test.ts diff --git a/apps/server/src/agents/pull-request-observations.ts b/apps/server/src/agents/pull-request-observations.ts new file mode 100644 index 000000000..678fe948f --- /dev/null +++ b/apps/server/src/agents/pull-request-observations.ts @@ -0,0 +1,130 @@ +import { + isGitHubPullRequestTarget, + MAX_PULL_REQUEST_WATCH_TARGETS, + type GitHubPullRequestWatchEvent, +} from "@dispatch/runner-protocol"; +import { githubPullRequestTarget } from "./pull-request-reader.js"; +import type { RemoteRunnerService } from "./remote/service.js"; + +type Sample = Extract; +type Watch = { + urls: Set; + samples: Map; + until: number; + close?: () => void; +}; + +const freshness = 7 * 60_000; + +/** Track one union of the host's interests per authenticated runner. */ +export class PullRequestObservations { + private readonly watches = new Map(); + private readonly retries = new Map(); + + constructor( + private readonly remote: Pick< + RemoteRunnerService, + "canWatchPullRequests" | "watchPullRequests" + >, + private readonly changed: () => void, + private readonly reset: (runnerId: string) => void + ) {} + + update(groups: Map) { + for (const id of this.retries.keys()) + if (!groups.has(id)) this.retries.delete(id); + for (const id of this.watches.keys()) if (!groups.has(id)) this.remove(id); + for (const [id, urls] of groups) { + const targets = new Set( + urls + .filter((url) => + isGitHubPullRequestTarget(githubPullRequestTarget(url)) + ) + .sort() + .slice(0, MAX_PULL_REQUEST_WATCH_TARGETS) + ); + if (!targets.size || !this.remote.canWatchPullRequests(id)) { + this.remove(id); + continue; + } + const previous = this.watches.get(id); + if ( + previous && + targets.size === previous.urls.size && + [...targets].every((url) => previous.urls.has(url)) + ) + continue; + if ((this.retries.get(id) ?? 0) > Date.now()) continue; + this.retries.delete(id); + const watch: Watch = { + urls: targets, + samples: new Map(), + until: Date.now() + freshness, + }; + this.watches.set(id, watch); + const ended = () => { + if (this.watches.get(id) !== watch) return; + this.remove(id); + this.retries.set(id, Date.now() + 30_000); + this.changed(); + }; + void this.remote + .watchPullRequests( + id, + [...targets], + (event) => { + if (this.watches.get(id) !== watch) return; + if (event.type === "reset") { + watch.samples.clear(); + watch.until = Date.now() + freshness; + this.reset(id); + } else { + const url = + "https://github.com/" + + `${event.target.owner.toLowerCase()}/${event.target.repo.toLowerCase()}/pull/${event.target.number}`; + if (!targets.has(url)) return; + if ( + (watch.samples.get(url)?.sample.observedAt ?? -1) > + event.observedAt + ) + return; + watch.samples.set(url, { + sample: event, + until: Date.now() + freshness, + }); + this.changed(); + } + }, + ended + ) + .then((close) => { + if (this.watches.get(id) !== watch) close(); + else watch.close = close; + }) + .catch(ended) + .finally(() => previous?.close?.()); + } + } + + get(id: string | null, url: string) { + const watch = id === null ? undefined : this.watches.get(id); + if (!watch?.urls.has(url)) return undefined; + return watch.samples.get(url) ?? { sample: undefined, until: watch.until }; + } + + get retryAt() { + return Math.min(Infinity, ...this.retries.values()); + } + + remove(id: string) { + const watch = this.watches.get(id); + this.watches.delete(id); + this.retries.delete(id); + watch?.close?.(); + } + + close() { + for (const id of this.watches.keys()) this.remove(id); + this.retries.clear(); + } +} diff --git a/apps/server/src/agents/pull-request-reader.ts b/apps/server/src/agents/pull-request-reader.ts index 8dd575495..c2c39ca3d 100644 --- a/apps/server/src/agents/pull-request-reader.ts +++ b/apps/server/src/agents/pull-request-reader.ts @@ -37,7 +37,8 @@ export function createRunnerPullRequestReader( readPullRequest( runnerId: string, url: string, - title: string + title: string, + refreshWatch?: boolean ): Promise; } | undefined, @@ -46,11 +47,14 @@ export function createRunnerPullRequestReader( return async ( url: string, title: string, - runnerId: string | null + runnerId: string | null, + refreshWatch?: boolean ): Promise => { if (runnerId === null) return readLocal(url, title); if (!remote) return { url, title, status: "Unavailable" }; - return remote.readPullRequest(runnerId, url, title); + return refreshWatch + ? remote.readPullRequest(runnerId, url, title, true) + : remote.readPullRequest(runnerId, url, title); }; } @@ -158,7 +162,8 @@ export function pullRequestObservation( export function projectPullRequest( url: string, title: string, - observation: GitHubPullRequestObservation + observation: GitHubPullRequestObservation, + observedAt?: number ): AgentPullRequest { const { state, draft, head, rollup, title: observedTitle } = observation; const status = @@ -176,7 +181,7 @@ export function projectPullRequest( url, status, title: typeof observedTitle === "string" ? observedTitle : title, - ci: mapPullRequestChecks(head, rollup), + ci: mapPullRequestChecks(head, rollup, observedAt), }; if (observation.credentialContext) credentialContexts.set(pr, observation.credentialContext); @@ -201,10 +206,11 @@ const CHECKS_QUERY = `query($owner: String!, $repo: String!, $number: Int!) { /** gh returns the current head rollup (CheckRun and StatusContext), not history. */ export function mapPullRequestChecks( head: unknown, - rollup: unknown + rollup: unknown, + observedAt = Date.now() ): NonNullable { const ci: NonNullable = { - checkedAt: new Date().toISOString(), + checkedAt: new Date(observedAt).toISOString(), headSha: typeof head === "string" ? head : "", availability: "unavailable", summary: { diff --git a/apps/server/src/agents/pull-request-refresher.ts b/apps/server/src/agents/pull-request-refresher.ts index ac23879af..d44d7a087 100644 --- a/apps/server/src/agents/pull-request-refresher.ts +++ b/apps/server/src/agents/pull-request-refresher.ts @@ -2,7 +2,13 @@ import { checkChanges } from "./pull-request-check-notice.js"; import type { AgentPullRequest, Block } from "@dispatch/shared"; import type { Pool } from "pg"; import type { PublishUiEvent } from "../server/ui-events.js"; -import { githubPullRequestUrl } from "./pull-request-reader.js"; +import { PullRequestObservations } from "./pull-request-observations.js"; +import type { RemoteRunnerService } from "./remote/service.js"; +import { + githubPullRequestUrl, + projectPullRequest, + pullRequestCredentialContext, +} from "./pull-request-reader.js"; export type CommitPullRequestNotice = ( write: () => Promise @@ -10,12 +16,17 @@ export type CommitPullRequestNotice = ( type Options = { pool: Pool; + remote?: Pick< + RemoteRunnerService, + "canWatchPullRequests" | "watchPullRequests" + >; listAgents: () => Promise<{ id: string; runnerId: string | null }[]>; publish: PublishUiEvent; read: ( url: string, title: string, - runnerId: string | null + runnerId: string | null, + refreshWatch?: boolean ) => Promise; notify?: ( agentId: string, @@ -76,7 +87,8 @@ export class PullRequestRefresher { checks?: AgentPullRequest; due: number; failures: number; - checkedAt: number; + observedAt?: number; + assessment?: { context?: string; until: number }; } >(); private attempts: number[] = []; @@ -89,7 +101,16 @@ export class PullRequestRefresher { private flight?: Promise; private stopped = false; private dirty = false; - constructor(private options: Options) {} + private readonly observations?: PullRequestObservations; + private watchDeadlines = new Map(); + constructor(private options: Options) { + if (options.remote) + this.observations = new PullRequestObservations( + options.remote, + () => this.signal(), + (id) => this.invalidateRunner(id, false) + ); + } get(agentId: string): AgentPullRequest[] { return this.snapshots.get(agentId) ?? []; } @@ -131,7 +152,8 @@ export class PullRequestRefresher { } private readonly runnerRevision = new Map(); /** A changed connection or GitHub account cannot reuse the previous peer's observations. */ - invalidateRunner(runnerId: string) { + invalidateRunner(runnerId: string, reconnect = true) { + if (reconnect) this.observations?.remove(runnerId); const owners = [...this.placements].filter( ([, runner]) => runner === runnerId ); @@ -209,9 +231,13 @@ export class PullRequestRefresher { const now = Date.now(); this.attempts = this.attempts.filter((at) => at > now - 60_000); let due = this.pendingUrls.size ? now : Infinity; - for (const entry of this.urls.values()) due = Math.min(due, entry.due); + for (const [key, until] of this.watchDeadlines) + due = Math.min(due, Math.max(until, this.urls.get(key)?.due ?? 0)); + for (const [key, entry] of this.urls) + if (!this.watchDeadlines.has(key)) due = Math.min(due, entry.due); if (this.attempts.length >= 12) due = Math.max(due, this.attempts[0] + 60_001); + due = Math.min(due, this.observations?.retryAt ?? Infinity); if (Number.isFinite(this.inventoryRetryAt)) due = this.inventoryRetryAt; if (!Number.isFinite(due)) return; this.timer = setTimeout( @@ -230,6 +256,7 @@ export class PullRequestRefresher { clearTimeout(this.pending); this.timer = undefined; this.pending = undefined; + this.observations?.close(); await this.flight; } /** Coalesce inventory events without bypassing lookup freshness or rate limits. */ @@ -352,6 +379,15 @@ export class PullRequestRefresher { own.add(key); agents.set(row.author_agent_id, own); } + if (this.stopped) return; + const groups = new Map(); + for (const { url, runnerId } of links.values()) { + if (runnerId === null) continue; + const group = groups.get(runnerId) ?? []; + group.push(url); + groups.set(runnerId, group); + } + this.observations?.update(groups); const publishSnapshots = () => { if (this.stopped) return; for (const id of new Set([...ids, ...this.snapshots.keys()])) { @@ -386,10 +422,29 @@ export class PullRequestRefresher { const notices: Array<() => Promise> = []; let refreshError: Error | undefined; publishSnapshots(); - this.pendingUrls = new Set( - [...links.keys()].filter((url) => !this.urls.has(url)) - ); const now = Date.now(); + this.watchDeadlines.clear(); + const pushed: typeof links = new Map(); + const dueReads: typeof links = new Map(); + for (const [key, link] of links) { + const cached = this.urls.get(key); + const watch = this.observations?.get(link.runnerId, link.url); + const deadline = watch?.until ?? 0; + const sample = deadline > now ? watch?.sample : undefined; + if (target) { + if (key === this.trackingKey(target.agentId, target.url)) + dueReads.set(key, link); + } else if ( + sample && + (sample.observedAt !== cached?.observedAt || cached.due === 0) + ) { + pushed.set(key, link); + } else if (deadline <= now && (cached?.due ?? 0) <= now) { + dueReads.set(key, link); + } + if (watch) this.watchDeadlines.set(key, deadline); + } + if (!target) this.pendingUrls = new Set(dueReads.keys()); this.attempts = this.attempts.filter((at) => at > now - 60_000); if (target) { if ( @@ -402,17 +457,15 @@ export class PullRequestRefresher { if (this.attempts.length >= 12) throw new Error("PR refresh budget reached. Please retry in a minute."); } - const queue = [...links] - .filter(([url]) => - target - ? url === this.trackingKey(target.agentId, target.url) - : (this.urls.get(url)?.due ?? 0) <= now - ) - .sort( - ([a], [b]) => - (this.urls.get(a)?.due ?? 0) - (this.urls.get(b)?.due ?? 0) - ) - .slice(0, Math.max(0, 12 - this.attempts.length)); + const queue = [ + ...pushed, + ...[...dueReads] + .sort( + ([a], [b]) => + (this.urls.get(a)?.due ?? 0) - (this.urls.get(b)?.due ?? 0) + ) + .slice(0, Math.max(0, 12 - this.attempts.length)), + ]; // Global rolling budget and two workers, regardless of clients or agents. await Promise.all( Array.from({ length: Math.min(2, queue.length) }, async () => { @@ -423,11 +476,37 @@ export class PullRequestRefresher { runnerId === null ? undefined : this.runnerRevision.get(runnerId); const peerChanged = () => runnerId !== null && this.runnerRevision.get(runnerId) !== revision; - this.attempts.push(Date.now()); + let observation = pushed.has(key) + ? this.observations?.get(runnerId, url)?.sample + : undefined; + if (pushed.has(key) && !observation) continue; let value: AgentPullRequest; try { - value = await this.options.read(url, title, runnerId); - } catch { + if (observation) { + value = observation.observation + ? projectPullRequest( + url, + title, + observation.observation, + observation.observedAt + ) + : { url, title, status: "Unavailable" }; + } else { + this.attempts.push(Date.now()); + value = this.watchDeadlines.has(key) + ? await this.options.read(url, title, runnerId, true) + : await this.options.read(url, title, runnerId); + if (value.status !== "Unavailable") + observation = this.observations?.get(runnerId, url)?.sample; + } + } catch (error) { + if (target && this.watchDeadlines.has(key) && !peerChanged()) { + // A failed refresh request can be a busy runner. Leave the last + // card intact until the watch confirms the source is unavailable. + throw new Error("Could not refresh PR. Please try again.", { + cause: error, + }); + } value = { url, title, status: "Unavailable" }; } if (peerChanged()) { @@ -448,9 +527,22 @@ export class PullRequestRefresher { if (runnerId === null) throw refreshError; } const previous = this.urls.get(key); - // An assessor failure cannot establish that history is still enabled. - let assessed = false; - if (this.options.assess) { + const context = pullRequestCredentialContext(value); + let assessment = previous?.assessment; + const reuseAssessment = + observation && + !target && + previous && + previous.due !== 0 && + assessment && + assessment.until > Date.now() && + assessment.context === context && + previous.value.status === value.status && + previous.value.ci?.headSha === value.ci?.headSha; + if (reuseAssessment) { + value = { ...value, mergeRisk: previous.value.mergeRisk }; + } else if (this.options.assess) { + assessment = undefined; const owners = [...agents] .filter(([, urls]) => urls.has(key)) .map(([id]) => id); @@ -484,7 +576,7 @@ export class PullRequestRefresher { }, runnerId ); - assessed = true; + assessment = { context, until: Date.now() + 5 * 60_000 }; if ( mergeRisk && (!this.riskHidden || mergeRisk.displayState === "disabled") @@ -503,7 +595,6 @@ export class PullRequestRefresher { } if ( !this.options.assess && - !assessed && !value.mergeRisk && previous?.value.mergeRisk && previous.value.mergeRisk.headSha === value.ci?.headSha @@ -565,7 +656,7 @@ export class PullRequestRefresher { for (const notify of [ lifecycleChanged ? this.options.notify : undefined, checksChanged ? this.options.notifyChecks : undefined, - !reviewChanged && !this.riskHidden + !reuseAssessment && !reviewChanged && !this.riskHidden ? this.options.notifyRisk : undefined, ]) { @@ -625,7 +716,8 @@ export class PullRequestRefresher { ? undefined : previous?.checks, failures, - checkedAt: Date.now(), + observedAt: observation?.observedAt ?? previous?.observedAt, + assessment, due: reviewChanged ? 0 : Date.now() + delay, }); this.pendingUrls.delete(key); diff --git a/apps/server/src/agents/remote/github-pull-request-watches.ts b/apps/server/src/agents/remote/github-pull-request-watches.ts new file mode 100644 index 000000000..db5b28637 --- /dev/null +++ b/apps/server/src/agents/remote/github-pull-request-watches.ts @@ -0,0 +1,172 @@ +import { + githubPullRequestTargetKey, + MAX_PULL_REQUEST_WATCH_TARGETS, + type GitHubPullRequestObservation, + type GitHubPullRequestTarget, + type GitHubPullRequestWatchEvent, +} from "./protocol.js"; + +type Sample = Extract; +type Receiver = (event: GitHubPullRequestWatchEvent) => void; +type Entry = { + target: GitHubPullRequestTarget; + receivers: Set; + due: number; + sample?: Sample; + flight?: Promise; +}; + +/** One bounded queue per workload account, including across transport reconnects. */ +export class GitHubPullRequestWatches { + private entries = new Map(); + private attempts: number[] = []; + private active = 0; + private subscriptions = 0; + private paused = 0; + private revision = 0; + private credential?: string; + private timer?: ReturnType; + + constructor( + private readonly read: ( + target: GitHubPullRequestTarget, + signal: AbortSignal + ) => Promise, + private readonly interval = 30_000 + ) {} + + subscribe(targets: GitHubPullRequestTarget[], receiver: Receiver) { + const entries = new Map( + targets.map(({ owner, repo, number }) => { + const target = { owner, repo, number }; + return [githubPullRequestTargetKey(target), target]; + }) + ); + const additions = [...entries.keys()].filter( + (key) => !this.entries.has(key) + ); + if ( + this.subscriptions >= 16 || + this.entries.size + additions.length > 2 * MAX_PULL_REQUEST_WATCH_TARGETS + ) + throw new Error("Runner pull request watch capacity reached."); + this.subscriptions++; + for (const [key, target] of entries) { + const entry = this.entry(key, target); + entry.receivers.add(receiver); + if (entry.sample) receiver(entry.sample); + } + this.schedule(); + return () => { + this.subscriptions--; + for (const key of entries.keys()) { + const entry = this.entries.get(key)!; + entry.receivers.delete(receiver); + if (!entry.receivers.size && !entry.flight) this.entries.delete(key); + } + this.schedule(); + }; + } + + reset() { + this.revision++; + this.credential = undefined; + const receivers = new Set(); + for (const entry of this.entries.values()) { + entry.sample = undefined; + entry.due = 0; + for (const receiver of entry.receivers) receivers.add(receiver); + } + for (const receiver of receivers) receiver({ type: "reset" }); + this.schedule(); + } + + async accountOperation(run: () => Promise) { + this.paused++; + this.reset(); + try { + return await run(); + } finally { + this.paused--; + this.schedule(); + } + } + + refreshIfWatched(target: GitHubPullRequestTarget) { + const key = githubPullRequestTargetKey(target); + const entry = this.entries.get(key); + if (!entry?.receivers.size) return undefined; + return this.refresh(key, entry); + } + + private async refresh(key: string, entry: Entry) { + if (entry.flight) return (await entry.flight).observation; + if (this.paused || this.active >= 2 || this.budgetDue() > Date.now()) + throw new Error("Runner pull request refresh budget reached."); + return (await this.sample(key, entry)).observation; + } + + private entry(key: string, target: GitHubPullRequestTarget) { + let entry = this.entries.get(key); + if (!entry) { + entry = { target, due: 0, receivers: new Set() }; + this.entries.set(key, entry); + } + return entry; + } + + private budgetDue() { + this.attempts = this.attempts.filter((at) => at > Date.now() - 60_000); + return this.attempts.length >= 12 ? this.attempts[0] + 60_000 : 0; + } + + private schedule() { + clearTimeout(this.timer); + if (this.paused || this.active >= 2) return; + const next = [...this.entries] + .filter(([, entry]) => entry.receivers.size && !entry.flight) + .sort(([, a], [, b]) => a.due - b.due)[0]; + if (!next) return; + this.timer = setTimeout( + () => { + void this.sample(...next).catch(() => {}); + this.schedule(); + }, + Math.max(0, next[1].due - Date.now(), this.budgetDue() - Date.now()) + ); + this.timer.unref(); + } + + private sample(key: string, entry: Entry) { + this.active++; + this.attempts.push(Date.now()); + const revision = this.revision; + entry.flight = this.read(entry.target, AbortSignal.timeout(17_000)) + .catch(() => null) + .then((observation): Sample => { + if (revision !== this.revision) + throw new Error("Runner GitHub account changed."); + const credential = observation?.credentialContext; + if (credential && this.credential && this.credential !== credential) + this.reset(); + if (credential) this.credential = credential; + const sample: Sample = { + type: "observation", + target: entry.target, + observedAt: Date.now(), + observation, + }; + entry.sample = sample; + entry.due = sample.observedAt + this.interval; + for (const receiver of entry.receivers) receiver(sample); + return sample; + }) + .finally(() => { + this.active--; + entry.flight = undefined; + if (!entry.receivers.size) this.entries.delete(key); + this.schedule(); + }); + return entry.flight; + } +} diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index f09aa7461..bd6f81a99 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -163,6 +163,7 @@ export class GitHubRunnerExecutor { clearTimeout(codeDeadline); session.code = undefined; if (code === 0) { + this.onLogin?.(); try { // gh's non-interactive login does not prompt to install this helper. await this.run( @@ -247,6 +248,8 @@ export class GitHubRunnerExecutor { } } + onLogin?: () => void; + async handle(operation: GitHubOperation, signal: AbortSignal) { signal.throwIfAborted(); switch (operation.type) { diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index c49d2c60e..e29557690 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -14,6 +14,8 @@ export { runnerStorageKey } from "./session-supervisor.js"; import { hostCommand, selfCommand } from "../acp/host-command.js"; import { isOpaqueId, + isGitHubPullRequestObservation, + MAX_PULL_REQUEST_WATCH_EVENT_BYTES, MANAGED_WORKSPACE, RUNNER_WIRE_VERSION, MAX_CHECKOUT_VIEW_BYTES, @@ -24,6 +26,7 @@ import { type RunnerFrame, type RunnerEngine, } from "./protocol.js"; +import { GitHubPullRequestWatches } from "./github-pull-request-watches.js"; import { GitHubRunnerExecutor } from "./github-runner-executor.js"; import { EngineRunnerExecutor, @@ -194,6 +197,16 @@ export async function runRemoteRunner(filename: string) { }), credentials.key ); + const pullRequests = new GitHubPullRequestWatches(async (target, signal) => { + const result = await github.handle( + { type: "pullRequestStatus", ...target, withCredentialContext: true }, + signal + ); + if (!isGitHubPullRequestObservation(result)) + throw new Error("Invalid GitHub observation."); + return result; + }); + github.onLogin = () => pullRequests.reset(); const engineExecutor = new EngineRunnerExecutor({ uid: config.uid, gid: config.gid, @@ -344,10 +357,50 @@ export async function runRemoteRunner(filename: string) { } if (command.kind === "github") { try { - const value = await github.handle( - command.operation, - connection.signal - ); + const operation = command.operation; + if (operation.type === "watchPullRequests") { + if (watches.has(id)) throw new Error("Duplicate watch ID."); + const close = pullRequests.subscribe( + operation.targets, + (event) => { + let line = JSON.stringify(event) + "\n"; + if ( + event.type === "observation" && + Buffer.byteLength(line) > MAX_PULL_REQUEST_WATCH_EVENT_BYTES + ) + line = + JSON.stringify({ ...event, observation: null }) + "\n"; + safeSend({ + type: "data", + id, + data: Buffer.from(line).toString("base64"), + }); + } + ); + watches.set(id, close); + safeSend({ type: "result", id, value: true }); + return; + } + const run = () => github.handle(operation, connection.signal); + const watched = + operation.type === "pullRequestStatus" && operation.refreshWatch + ? pullRequests.refreshIfWatched(operation) + : undefined; + let value = await (watched ?? + (operation.type === "logout" || operation.type === "login" + ? pullRequests.accountOperation(run) + : run())); + if (watched && value === null) + throw new Error("Runner pull request observation unavailable."); + if ( + watched && + operation.type === "pullRequestStatus" && + !operation.withCredentialContext && + isGitHubPullRequestObservation(value) + ) { + const { credentialContext: _, ...publicValue } = value; + value = publicValue; + } safeSend({ type: "result", id, value: JSON.stringify(value) }); } catch { safeSend({ @@ -572,6 +625,7 @@ export async function runRemoteRunner(filename: string) { engineManagement: true, githubManagement: true, pullRequestStatus: true, + pullRequestWatch: true, pullRequestEvidence: true, checkoutInspection: true, checkoutViews: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index f9bf6237a..c41122bb3 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -36,6 +36,10 @@ import { type RunnerOperation, type GitHubOperation, type GitHubStatus, + type GitHubPullRequestWatchEvent, + isGitHubPullRequestTarget, + parseGitHubPullRequestWatchEvent, + MAX_PULL_REQUEST_WATCH_EVENT_BYTES, parseGitHubStatus, isGitHubPullRequestObservation, isGitHubPullRequestDetails, @@ -152,6 +156,7 @@ type Peer = { engineManagement: boolean; githubManagement: boolean; pullRequestStatus: boolean; + pullRequestWatch: boolean; pullRequestEvidence: boolean; checkoutInspection: boolean; checkoutViews: boolean; @@ -669,6 +674,7 @@ export class RemoteRunnerService { reportsHealth: ready.health === true, engineManagement: ready.engineManagement === true, pullRequestStatus: ready.pullRequestStatus === true, + pullRequestWatch: ready.pullRequestWatch === true, pullRequestEvidence: ready.pullRequestEvidence === true, githubManagement: ready.githubManagement === true, checkoutViews: ready.checkoutViews === true, @@ -1241,13 +1247,25 @@ export class RemoteRunnerService { "Update the runner to read pull request evidence." ); + if ( + operation.kind === "github" && + (operation.operation.type === "watchPullRequests" || + (operation.operation.type === "pullRequestStatus" && + operation.operation.refreshWatch)) && + !peer.pullRequestWatch + ) + throw new RunnerCapabilityUnavailable( + "Runner does not support PR watches." + ); + // V1 requires a routable workspace and an id even for a runner-wide operation. for (const workspace of peer.workspaces) { if (peer.gate.allows(workspace)) return this.request( { runner: runnerId, workspace }, { ...operation, agentId: `@${operation.kind}`, workspace }, - operation.kind === "engine" + operation.kind === "engine" || + operation.operation.type === "watchPullRequests" ); } throw new RunnerUnavailable("The runner has no available workspace."); @@ -1316,7 +1334,62 @@ export class RemoteRunnerService { return githubRepositoryResults(response.repositories); } - async readPullRequest(runnerId: string, url: string, title: string) { + canWatchPullRequests(runnerId: string) { + const peer = this.peers.get(runnerId); + return ( + peer?.gate.approved() === true && + peer.githubManagement && + peer.pullRequestWatch + ); + } + + async watchPullRequests( + runnerId: string, + urls: string[], + event: (value: GitHubPullRequestWatchEvent) => void, + closed: () => void + ) { + const peer = this.peers.get(runnerId); + const active = () => + this.peers.get(runnerId) === peer && peer?.gate.approved(); + const { value, channel } = await this.requestRunner(runnerId, { + kind: "github", + operation: { + type: "watchPullRequests", + targets: urls + .map(githubPullRequestTarget) + .filter(isGitHubPullRequestTarget), + }, + }); + if (!active() || !channel || value !== true) { + channel?.destroy(); + throw new RunnerUnavailable("Runner PR watch is unavailable."); + } + // A runner sends one complete JSON line per channel data frame. + channel.on("data", (chunk: Buffer) => { + if (!active() || channel.destroyed) return; + try { + if (chunk.length > MAX_PULL_REQUEST_WATCH_EVENT_BYTES) + throw new Error(); + const observation = parseGitHubPullRequestWatchEvent( + JSON.parse(chunk.toString()) + ); + if (!observation) throw new Error(); + event(observation); + } catch { + channel.destroy(); + } + }); + channel.once("close", closed); + return () => channel.destroy(); + } + + async readPullRequest( + runnerId: string, + url: string, + title: string, + refreshWatch = false + ) { const canonical = githubPullRequestUrl(url); if (!canonical) return { url, title, status: "Unavailable" as const }; const [, owner, repo, , number] = new URL(canonical).pathname.split("/"); @@ -1325,6 +1398,8 @@ export class RemoteRunnerService { owner, repo, number: Number(number), + ...(refreshWatch && + this.canWatchPullRequests(runnerId) && { refreshWatch: true }), ...(this.peers.get(runnerId)?.pullRequestEvidence && { withCredentialContext: true, }), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index b83bd7f2c..6871feba9 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -396,6 +396,7 @@ const mergeRiskAssessor = new MergeRiskAssessor({ }); const pullRequests = new PullRequestRefresher({ pool, + remote: remoteRunner, listAgents: async () => (await agentManager.listAgents()).map((agent) => ({ id: agent.id, diff --git a/apps/server/test/github-pull-request-watches.test.ts b/apps/server/test/github-pull-request-watches.test.ts new file mode 100644 index 000000000..a090f5e95 --- /dev/null +++ b/apps/server/test/github-pull-request-watches.test.ts @@ -0,0 +1,111 @@ +import { expect, it, vi } from "vitest"; +import { GitHubPullRequestWatches } from "../src/agents/remote/github-pull-request-watches.js"; +import type { GitHubPullRequestObservation } from "@dispatch/runner-protocol"; + +const target = { owner: "owner", repo: "repo", number: 42 }; +const observation: GitHubPullRequestObservation = { + state: "OPEN", + draft: false, + title: "Original", + head: "a".repeat(40), + rollup: [], +}; +const event = (title: string) => ({ + type: "observation", + observation: expect.objectContaining({ title }), +}); + +it("shares samples, repairs a missed update with a full observation, and stops after the last close", async () => { + vi.useFakeTimers(); + try { + let title = "Original"; + const read = vi.fn(async () => ({ ...observation, title })); + const watches = new GitHubPullRequestWatches(read); + const first = vi.fn(); + const second = vi.fn(); + const closeFirst = watches.subscribe([target], first); + await vi.advanceTimersByTimeAsync(1); + const closeSecond = watches.subscribe( + [{ ...target, owner: "OWNER" }], + second + ); + expect(read).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenLastCalledWith(first.mock.lastCall![0]); + + title = "Changed"; + await vi.advanceTimersByTimeAsync(30_000); + expect(first).toHaveBeenLastCalledWith( + expect.objectContaining(event(title)) + ); + second.mockClear(); // Simulate a host missing the change. + await vi.advanceTimersByTimeAsync(30_000); + expect(second).toHaveBeenLastCalledWith( + expect.objectContaining({ + ...event(title), + observedAt: expect.any(Number), + }) + ); + title = "Manual"; + expect(await watches.refreshIfWatched(target)).toMatchObject({ title }); + expect(first).toHaveBeenLastCalledWith( + expect.objectContaining(event(title)) + ); + closeFirst(); + closeSecond(); + const count = read.mock.calls.length; + await vi.advanceTimersByTimeAsync(5 * 60_000); + expect(read).toHaveBeenCalledTimes(count); + } finally { + vi.useRealTimers(); + } +}); + +it("bounds provider calls and drops an in-flight private sample at logout", async () => { + vi.useFakeTimers(); + try { + let finish!: (value: GitHubPullRequestObservation) => void; + const read = vi + .fn(async () => observation) + .mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }) + ); + const watches = new GitHubPullRequestWatches(read); + const receiver = vi.fn(); + const close = watches.subscribe([target], receiver); + await vi.advanceTimersByTimeAsync(1); + const manual = watches.refreshIfWatched(target)!; + const rejected = expect(manual).rejects.toThrow("account changed"); + let resume!: () => void; + const logout = watches.accountOperation( + () => + new Promise((resolve) => { + resume = resolve; + }) + ); + finish(observation); + await rejected; + expect(receiver.mock.calls).toEqual([[{ type: "reset" }]]); + read.mockRejectedValue(new Error("Signed out")); + resume(); + await logout; + await vi.advanceTimersByTimeAsync(1); + expect(receiver).toHaveBeenLastCalledWith( + expect.objectContaining({ observation: null }) + ); + + const closeMany = watches.subscribe( + Array.from({ length: 16 }, (_, i) => ({ ...target, number: i + 1 })), + vi.fn() + ); + await vi.advanceTimersByTimeAsync(100); + expect(read).toHaveBeenCalledTimes(12); + await expect(watches.refreshIfWatched(target)!).rejects.toThrow("budget"); + closeMany(); + close(); + } finally { + vi.useRealTimers(); + } +}); diff --git a/apps/server/test/pull-request-refresher.test.ts b/apps/server/test/pull-request-refresher.test.ts index 1cc95353d..26c7e1d0a 100644 --- a/apps/server/test/pull-request-refresher.test.ts +++ b/apps/server/test/pull-request-refresher.test.ts @@ -1,5 +1,6 @@ import { createRunnerPullRequestReader } from "../src/agents/pull-request-reader.js"; import { afterEach, describe, expect, it, vi } from "vitest"; +import type { GitHubPullRequestWatchEvent } from "@dispatch/runner-protocol"; import type { Pool } from "pg"; import type { AgentPullRequest, Block } from "@dispatch/shared"; import { PullRequestRefresher } from "../src/agents/pull-request-refresher.js"; @@ -56,6 +57,85 @@ function fixture(count = 1) { } afterEach(() => vi.useRealTimers()); describe("server PR orchestration", () => { + it("shares runner subscriptions, projects pushed updates and rejects events from a replaced connection", async () => { + const f = fixture(2); + const row = f.rows[1]; + f.rows.splice( + 0, + 1, + { ...row, author_agent_id: "b" }, + { ...row, author_agent_id: "c" } + ); + const url = row.attachments[0].url; + type Receiver = (event: GitHubPullRequestWatchEvent) => void; + const events = new Map(); + const close = vi.fn(); + const watchPullRequests = vi.fn( + async (id: string, _urls: string[], receive: Receiver) => { + events.set(id, receive); + return close; + } + ); + const service = new PullRequestRefresher({ + pool: { query: f.query } as unknown as Pool, + listAgents: async () => [ + { id: "a", runnerId: "alpha" }, + { id: "b", runnerId: "alpha" }, + { id: "c", runnerId: "beta" }, + ], + publish: f.publish, + read: f.read, + remote: { canWatchPullRequests: () => true, watchPullRequests }, + warn: vi.fn(), + }); + const sample = ( + observedAt: number, + state: "OPEN" | "MERGED" | null + ): GitHubPullRequestWatchEvent => ({ + type: "observation", + target: { owner: "a", repo: "b", number: 1 }, + observedAt, + observation: state + ? { state, draft: false, title: "Private", head: "sha", rollup: [] } + : null, + }); + try { + await service.refresh(); + expect( + watchPullRequests.mock.calls.map(([id, urls]) => [id, urls]) + ).toEqual([ + ["alpha", [url]], + ["beta", [url]], + ]); + const old = events.get("alpha")!; + old(sample(1, "OPEN")); + events.get("beta")!(sample(2, null)); + await service.refresh(); + expect(service.get("a")[0].status).toBe("Open"); + expect(service.get("b")[0].status).toBe("Open"); + expect(service.get("c")[0].status).toBe("Unavailable"); + expect(f.read).not.toHaveBeenCalled(); + + service.invalidateRunner("alpha"); + await service.refresh(); + old(sample(4, "MERGED")); + events.get("alpha")!(sample(3, "OPEN")); + await service.refresh(); + expect(service.get("a")[0].status).toBe("Open"); + events.get("alpha")!({ type: "reset" }); + expect(service.get("a")[0].status).toBe("Pending"); + events.get("alpha")!(sample(5, null)); + await service.refresh(); + expect(service.get("a")[0].status).toBe("Unavailable"); + await service.dismiss("a", url); + await service.dismiss("b", url); + await service.refresh(); + expect(close).toHaveBeenCalledTimes(2); + } finally { + await service.stop(); + } + }); + it("isolates background and manual reads of the same URL by runner and drops a late reply after replacement", async () => { const f = fixture(); f.rows.push({ ...f.rows[0], author_agent_id: "b" }); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 639979b95..b4a1b70df 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -16,6 +16,7 @@ import { sessionCommandId, isOpaqueId, isCheckoutReply, + parseGitHubPullRequestWatchEvent, isGitHubPullRequestDetails, isGitHubPullRequestDiff, isCheckoutViewData, @@ -122,6 +123,7 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () engineManagement: true, githubManagement: true, pullRequestStatus: true, + pullRequestWatch: true, pullRequestEvidence: true, checkoutInspection: true, checkoutViews: true, @@ -158,6 +160,31 @@ it("validates runner-scoped GitHub command payloads", () => { number: 0, }) ).toBeNull(); + const target = { owner: "example", repo: "project", number: 42 }; + expect( + parse({ type: "watchPullRequests", targets: [target] }) + ).not.toBeNull(); + expect(parse({ type: "watchPullRequests", targets: [] })).toBeNull(); + expect( + parse({ type: "watchPullRequests", targets: Array(65).fill(target) }) + ).toBeNull(); + expect( + parse({ type: "watchPullRequests", targets: [{ ...target, owner: ".." }] }) + ).toBeNull(); + expect( + parse({ ...target, type: "pullRequestStatus", refreshWatch: true }) + ).not.toBeNull(); + expect( + parse({ ...target, type: "pullRequestStatus", refreshWatch: "yes" }) + ).toBeNull(); + expect( + parseGitHubPullRequestWatchEvent({ + type: "observation", + target, + observedAt: -1, + observation: null, + }) + ).toBeNull(); expect(parse({ type: "login" })).not.toBeNull(); expect(parse({ type: "repositorySearch", query: "org/repo" })).not.toBeNull(); expect(parse({ type: "repositorySearch", query: "--help\n" })).toBeNull(); @@ -594,6 +621,7 @@ function fixtureRunner(current: boolean) { engineManagement: true, githubManagement: true, pullRequestEvidence: true, + pullRequestWatch: true, }), }; const sample = { @@ -687,7 +715,27 @@ function fixtureRunner(current: boolean) { command.kind === "github" && command.workspace === workspace ) { - if (command.operation.type === "pullRequestDetails") + if (command.operation.type === "watchPullRequests") { + const channel = hostChannel(id, reply, () => channels.delete(id)); + channels.set(id, channel); + result(true); + for (const target of command.operation.targets) { + channel.write( + JSON.stringify({ + type: "observation", + target, + observedAt: Date.now(), + observation: { + state: "OPEN", + title: "Tracked", + draft: false, + head: githubDetails.headRefOid, + rollup: [], + }, + }) + "\n" + ); + } + } else if (command.operation.type === "pullRequestDetails") result(JSON.stringify(githubDetails)); else if ( command.operation.type === "pullRequestDiff" && @@ -875,6 +923,40 @@ it.each([true, false])( : { unavailable: true } ); + if (ready?.githubManagement && ready.pullRequestWatch) { + const { value, channel } = await peer.connection.request( + { + kind: "github", + workspace: runner.session.workspace, + agentId: "independent-watcher", + operation: { type: "watchPullRequests", targets: [githubTarget] }, + }, + { openChannel: true } + ); + expect(value).toBe(true); + const snapshots: unknown[] = []; + wireFrames(channel!, (raw) => + snapshots.push(parseGitHubPullRequestWatchEvent(raw)) + ); + await vi.waitFor(() => + expect(snapshots).toEqual([ + expect.objectContaining({ + type: "observation", + target: githubTarget, + observedAt: expect.any(Number), + observation: expect.objectContaining({ rollup: [] }), + }), + ]) + ); + channel!.destroy(); + await vi.waitFor(() => + expect(runner.requests).toContainEqual( + expect.objectContaining({ type: "close" }) + ) + ); + } else { + expect(ready?.pullRequestWatch).toBeUndefined(); + } if (ready?.githubManagement && ready.pullRequestEvidence) { const route = { kind: "github" as const, diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index d81448b18..9cff94b39 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -15,11 +15,11 @@ The branch already exercises session supervision, shared reviewer checkouts, che ## First checkpoint -Scheduled and manual PR reads now use the selected runner. The optional `pullRequestStatus` capability returns lifecycle and current-head checks. Dispatch isolates cached observations, in-flight replies and notices by runner and URL. The Linux browser fixture posts a private PR, observes an initial check, changes the fixture on the runner, then refreshes to see the new check. +Scheduled and manual PR reads now use the selected runner. The optional `pullRequestStatus` capability returns lifecycle and current-head checks. Dispatch isolates cached observations, in-flight replies and notices by runner and URL. The Linux browser fixture posts a private PR, observes the initial and changed checks in an open card, and forces a fresh read from the same runner. Merge-risk details and commit comparisons now use the owning runner's GitHub credential. Dispatch matches the credential context from the status and details reads, partitions assessment reservations and history by runner and credential, and checks current PR access before using saved explanations. Unscoped assessments are visible only to the native placement. The wire returns GitHub source fields. Dispatch retains evidence selection, review history, policy and paid calls. An older runner can still report lifecycle and checks. -Tracked-PR subscriptions remain to be implemented. Let the runner watch the tracked set, send current snapshots on subscribe or reconnect, and send subsequent changes. Test stale connections, bounded polling, manual refresh and the last subscriber leaving. Browser updates continue through the existing Dispatch event stream. +Dispatch now sends the union of tracked PRs to each capable runner. Runner observations include sampling time and full current state so a missed update can be recovered on the next sample. Reconnect reopens the watch, and account reset clears the previous credential’s snapshots. Older peers continue using scheduled reads. The Dispatch host still owns browser events, dismissals, and notices. ## Live updates diff --git a/e2e/remote-runner/github-account.spec.ts b/e2e/remote-runner/github-account.spec.ts index 15f14685c..796f50c7e 100644 --- a/e2e/remote-runner/github-account.spec.ts +++ b/e2e/remote-runner/github-account.spec.ts @@ -108,22 +108,43 @@ test("GitHub sign-in, private checkout and sign-out belong to the selected runne await page .getByRole("button", { name: /Details for pull request #42: Open/i }) .click(); - const details = page.getByRole("dialog"); + const details = page.getByRole("dialog").filter({ + has: page.getByRole("heading", { name: "Pull request #42", exact: true }), + }); await expect(details.getByText("build", { exact: true })).toBeVisible(); guest("scratch", "touch /tmp/runner-ci-finished"); - await details - .getByRole("button", { name: "Refresh pull request checks" }) - .click(); - await expect( - details.getByText("integration", { exact: true }) - ).toBeVisible(); + await expect(details.getByText("integration", { exact: true })).toBeVisible( + { timeout: 45_000 } + ); const screenshot = testInfo.outputPath("runner-private-pr-checks.png"); await page.screenshot({ path: screenshot }); - await testInfo.attach("Refreshed checks using the runner GitHub account", { + await testInfo.attach("Open PR card received checks from the runner", { path: screenshot, contentType: "image/png", }); await page.keyboard.press("Escape"); + await page.setViewportSize({ width: 390, height: 844 }); + await page.getByTitle("Open sidebar").click(); + await page + .getByRole("button", { name: /Details for pull request #42: Open/i }) + .click(); + guest("scratch", "rm /tmp/runner-ci-finished"); + await details + .getByRole("button", { name: "Refresh pull request checks" }) + .click(); + await expect(details.getByText("build", { exact: true })).toBeVisible({ + timeout: 10_000, + }); + const mobileScreenshot = testInfo.outputPath( + "runner-private-pr-mobile-refresh.png" + ); + await page.screenshot({ path: mobileScreenshot }); + await testInfo.attach("Manual runner refresh on mobile", { + path: mobileScreenshot, + contentType: "image/png", + }); + await page.keyboard.press("Escape"); + await page.setViewportSize({ width: 1280, height: 720 }); // Uses the ordinary workload user's installed helper, independent of the provisioning helper. const fetch = "setpriv --reuid 1500 --regid 1500 --clear-groups env HOME=/home/guest GIT_TERMINAL_PROMPT=0 git ls-remote https://github.com/fixture-scratch/private.git HEAD"; @@ -138,6 +159,12 @@ test("GitHub sign-in, private checkout and sign-out belong to the selected runne account.getByRole("button", { name: "Sign in to GitHub" }) ).toBeVisible(); expect(guestOk("scratch", fetch + " >/dev/null 2>&1")).toBe(false); + await page.goto("/agents/" + agent.id, { waitUntil: "domcontentloaded" }); + await expect( + page.getByRole("button", { + name: /Details for pull request #42: Unavailable/i, + }) + ).toBeVisible({ timeout: 15_000 }); await expect( (await openAccount("beta")).getByText("Signed in as @fixture-beta") ).toBeVisible(); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 67183ef48..c08af61ea 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -331,3 +331,39 @@ can invalidate it. To join provider data or reuse a saved result, match the runner, repository and PR, relevant commits, and credential context from a successful fresh read. Keep application policy, derived judgments, and history in the service that requested the GitHub data. + +### Watching pull requests + +A v1 peer advertising both `githubManagement: true` and +`pullRequestWatch: true` accepts the GitHub operation +`{type: "watchPullRequests", targets: [{owner, repo, number}, ...]}`. +Use a regular GitHub command envelope with an advertised workspace and any +opaque routing ID. The ID does not need to identify a session. Open the channel +when issuing the request and expect a boolean `true` acknowledgement. Cached +observations may arrive before the acknowledgement. Older peers continue to +use `pullRequestStatus` if advertised. + +Each runner-to-service channel data frame contains one UTF-8 JSON line of at +most 1 MiB, validated by `parseGitHubPullRequestWatchEvent`. An observation +includes the target, the runner's sampling time in Unix milliseconds +(`observedAt`), and the same full observation as the scoped status read. +A null observation indicates a lookup failure. A null check rollup indicates +unavailable or incomplete checks, while an empty rollup is authoritative. +The initial snapshot arrives one target at a time as samples become available. +Subsequent full observations include changes and refresh the timestamp even +when the source is unchanged, so a receiver can recover a missed update without +applying deltas. A `{type: "reset"}` event invalidates all prior observations on +the channel after a credential transition. A consumer should discard state on +disconnect or reset, fence off the old connection, and subscribe again after +reconnect. A service can use its own receipt time for expiry. + +Send the desired set of up to 64 targets when opening each channel. To update +the set, open a replacement and close the previous channel. The ordinary +channel `close` frame releases the subscription. The runner deduplicates +case-insensitively, shares up to two concurrent samples and 12 sample attempts +per rolling minute, and normally resamples each active target after 30 seconds +subject to that budget. A host can pass `refreshWatch: true` on +`pullRequestStatus` when the watch capability is advertised. For a watched +target this forces a new sample or joins one already in flight, and may return +an error when capacity is exhausted. Regular status reads retain their +existing behavior. All samples use the runner's workload credential. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 3cc5008a0..c518eca32 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -80,6 +80,7 @@ export type ReadyFrame = { engineManagement?: true; githubManagement?: true; pullRequestStatus?: true; + pullRequestWatch?: true; pullRequestEvidence?: true; checkoutInspection?: true; checkoutViews?: true; @@ -112,6 +113,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), ...(frame.pullRequestEvidence === true && { pullRequestEvidence: true }), + ...(frame.pullRequestWatch === true && { pullRequestWatch: true }), ...(frame.pullRequestStatus === true && { pullRequestStatus: true }), ...(frame.githubManagement === true && { githubManagement: true }), ...(frame.managedWorkspace === true && { managedWorkspace: true }), diff --git a/packages/runner-protocol/src/github.ts b/packages/runner-protocol/src/github.ts index 0b17456bc..a4fb13380 100644 --- a/packages/runner-protocol/src/github.ts +++ b/packages/runner-protocol/src/github.ts @@ -9,13 +9,56 @@ export type GitHubPullRequestTarget = { number: number; }; +export const MAX_PULL_REQUEST_WATCH_TARGETS = 64; +export const MAX_PULL_REQUEST_WATCH_EVENT_BYTES = 1024 * 1024; + +export type GitHubPullRequestWatchEvent = + | { type: "reset" } + | { + type: "observation"; + target: GitHubPullRequestTarget; + observedAt: number; + observation: GitHubPullRequestObservation | null; + }; + +export function parseGitHubPullRequestWatchEvent( + value: unknown +): GitHubPullRequestWatchEvent | null { + if (!isRecord(value)) return null; + if (value.type === "reset") return { type: "reset" }; + if ( + value.type !== "observation" || + !isGitHubPullRequestTarget(value.target) || + !count(value.observedAt) || + value.observedAt > 8_640_000_000_000_000 || + (value.observation !== null && + !isGitHubPullRequestObservation(value.observation)) + ) + return null; + return { + type: "observation", + target: value.target, + observedAt: value.observedAt, + observation: value.observation, + }; +} + +export function githubPullRequestTargetKey(target: GitHubPullRequestTarget) { + return `${target.owner.toLowerCase()}/${target.repo.toLowerCase()}/${target.number}`; +} + export type GitHubOperation = + | { type: "watchPullRequests"; targets: GitHubPullRequestTarget[] } | { type: "status" | "login" | "cancel" | "logout" } | { type: "repositorySearch"; query: string } | (GitHubPullRequestTarget & ( | { type: "pullRequestHead" | "pullRequestDetails" } - | { type: "pullRequestStatus"; withCredentialContext?: true } + | { + type: "pullRequestStatus"; + withCredentialContext?: true; + refreshWatch?: true; + } | { type: "pullRequestDiff"; base: string; @@ -170,6 +213,19 @@ export function validGitHubRepoPart(value: unknown): value is string { ); } +export function isGitHubPullRequestTarget( + value: unknown +): value is GitHubPullRequestTarget { + return ( + isRecord(value) && + validGitHubRepoPart(value.owner) && + validGitHubRepoPart(value.repo) && + count(value.number) && + value.number > 0 && + value.number <= 9_999_999_999 + ); +} + export function isGitHubOperation(value: unknown): value is GitHubOperation { if (!isRecord(value)) return false; switch (value.type) { @@ -178,6 +234,13 @@ export function isGitHubOperation(value: unknown): value is GitHubOperation { case "cancel": case "logout": return true; + case "watchPullRequests": + return ( + Array.isArray(value.targets) && + value.targets.length > 0 && + value.targets.length <= MAX_PULL_REQUEST_WATCH_TARGETS && + value.targets.every(isGitHubPullRequestTarget) + ); case "repositorySearch": return validRepositorySearch(value.query); case "pullRequestStatus": @@ -186,18 +249,15 @@ export function isGitHubOperation(value: unknown): value is GitHubOperation { case "pullRequestDiff": return ( (value.type !== "pullRequestStatus" || - value.withCredentialContext === undefined || - value.withCredentialContext === true) && + ((value.withCredentialContext === undefined || + value.withCredentialContext === true) && + (value.refreshWatch === undefined || + value.refreshWatch === true))) && (value.type !== "pullRequestDiff" || (validGitHubCommit(value.base) && validGitHubCommit(value.head) && validCredentialContext(value.credentialContext))) && - validGitHubRepoPart(value.owner) && - validGitHubRepoPart(value.repo) && - typeof value.number === "number" && - Number.isSafeInteger(value.number) && - value.number > 0 && - value.number <= 9_999_999_999 + isGitHubPullRequestTarget(value) ); default: return false; From 0ed92e3501c547313393749837ad256c5aed6107 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 15:17:02 -0700 Subject: [PATCH 128/642] Preserve PR watch polling and failure backoff --- .agents/owners.json | 1 + .../src/agents/pull-request-observations.ts | 45 +++++----- .../src/agents/pull-request-refresher.ts | 21 ++--- .../remote/github-pull-request-watches.ts | 76 +++++++++++++--- .../test/github-pull-request-watches.test.ts | 88 +++++++++++++++++++ .../test/pull-request-refresher.test.ts | 76 ++++++++++++++++ packages/runner-protocol/README.md | 19 ++-- 7 files changed, 270 insertions(+), 56 deletions(-) diff --git a/.agents/owners.json b/.agents/owners.json index 5ecc80c54..e9845a4c3 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -28,6 +28,7 @@ "apps/server/test/remote-*.test.ts", "apps/server/test/checkout-inspection.test.ts", "apps/server/test/runner-*.test.ts", + "apps/server/test/github-pull-request-watches.test.ts", "apps/server/test/helpers/remote-acp-fixture.ts", "packages/runner-protocol/**", "docs/design/remote-runner-handoff.md", diff --git a/apps/server/src/agents/pull-request-observations.ts b/apps/server/src/agents/pull-request-observations.ts index 678fe948f..abd8408f2 100644 --- a/apps/server/src/agents/pull-request-observations.ts +++ b/apps/server/src/agents/pull-request-observations.ts @@ -9,17 +9,20 @@ import type { RemoteRunnerService } from "./remote/service.js"; type Sample = Extract; type Watch = { urls: Set; - samples: Map; - until: number; + samples: Map; + renewAt: number; close?: () => void; + ended?: true; }; -const freshness = 7 * 60_000; +// Receipt deadlines only govern channel recovery. Samples carry their +// own provider timestamp, which a replay leaves unchanged. +const deliveryTimeout = 7 * 60_000; +const retryDelay = 30_000; /** Track one union of the host's interests per authenticated runner. */ export class PullRequestObservations { private readonly watches = new Map(); - private readonly retries = new Map(); constructor( private readonly remote: Pick< @@ -31,8 +34,6 @@ export class PullRequestObservations { ) {} update(groups: Map) { - for (const id of this.retries.keys()) - if (!groups.has(id)) this.retries.delete(id); for (const id of this.watches.keys()) if (!groups.has(id)) this.remove(id); for (const [id, urls] of groups) { const targets = new Set( @@ -50,22 +51,21 @@ export class PullRequestObservations { const previous = this.watches.get(id); if ( previous && + previous.renewAt > Date.now() && targets.size === previous.urls.size && [...targets].every((url) => previous.urls.has(url)) ) continue; - if ((this.retries.get(id) ?? 0) > Date.now()) continue; - this.retries.delete(id); const watch: Watch = { urls: targets, samples: new Map(), - until: Date.now() + freshness, + renewAt: Date.now() + deliveryTimeout, }; this.watches.set(id, watch); const ended = () => { if (this.watches.get(id) !== watch) return; - this.remove(id); - this.retries.set(id, Date.now() + 30_000); + watch.ended = true; + watch.renewAt = Date.now() + retryDelay; this.changed(); }; void this.remote @@ -73,10 +73,10 @@ export class PullRequestObservations { id, [...targets], (event) => { - if (this.watches.get(id) !== watch) return; + if (this.watches.get(id) !== watch || watch.ended) return; + watch.renewAt = Date.now() + deliveryTimeout; if (event.type === "reset") { watch.samples.clear(); - watch.until = Date.now() + freshness; this.reset(id); } else { const url = @@ -84,14 +84,10 @@ export class PullRequestObservations { `${event.target.owner.toLowerCase()}/${event.target.repo.toLowerCase()}/pull/${event.target.number}`; if (!targets.has(url)) return; if ( - (watch.samples.get(url)?.sample.observedAt ?? -1) > - event.observedAt + (watch.samples.get(url)?.observedAt ?? -1) >= event.observedAt ) return; - watch.samples.set(url, { - sample: event, - until: Date.now() + freshness, - }); + watch.samples.set(url, event); this.changed(); } }, @@ -109,22 +105,23 @@ export class PullRequestObservations { get(id: string | null, url: string) { const watch = id === null ? undefined : this.watches.get(id); if (!watch?.urls.has(url)) return undefined; - return watch.samples.get(url) ?? { sample: undefined, until: watch.until }; + return { sample: watch.samples.get(url) }; } - get retryAt() { - return Math.min(Infinity, ...this.retries.values()); + get nextAt() { + return Math.min( + Infinity, + ...[...this.watches.values()].map((watch) => watch.renewAt) + ); } remove(id: string) { const watch = this.watches.get(id); this.watches.delete(id); - this.retries.delete(id); watch?.close?.(); } close() { for (const id of this.watches.keys()) this.remove(id); - this.retries.clear(); } } diff --git a/apps/server/src/agents/pull-request-refresher.ts b/apps/server/src/agents/pull-request-refresher.ts index d44d7a087..a6a504b28 100644 --- a/apps/server/src/agents/pull-request-refresher.ts +++ b/apps/server/src/agents/pull-request-refresher.ts @@ -102,7 +102,7 @@ export class PullRequestRefresher { private stopped = false; private dirty = false; private readonly observations?: PullRequestObservations; - private watchDeadlines = new Map(); + private watchedKeys = new Set(); constructor(private options: Options) { if (options.remote) this.observations = new PullRequestObservations( @@ -231,13 +231,11 @@ export class PullRequestRefresher { const now = Date.now(); this.attempts = this.attempts.filter((at) => at > now - 60_000); let due = this.pendingUrls.size ? now : Infinity; - for (const [key, until] of this.watchDeadlines) - due = Math.min(due, Math.max(until, this.urls.get(key)?.due ?? 0)); for (const [key, entry] of this.urls) - if (!this.watchDeadlines.has(key)) due = Math.min(due, entry.due); + if (!this.watchedKeys.has(key)) due = Math.min(due, entry.due); if (this.attempts.length >= 12) due = Math.max(due, this.attempts[0] + 60_001); - due = Math.min(due, this.observations?.retryAt ?? Infinity); + due = Math.min(due, this.observations?.nextAt ?? Infinity); if (Number.isFinite(this.inventoryRetryAt)) due = this.inventoryRetryAt; if (!Number.isFinite(due)) return; this.timer = setTimeout( @@ -423,14 +421,13 @@ export class PullRequestRefresher { let refreshError: Error | undefined; publishSnapshots(); const now = Date.now(); - this.watchDeadlines.clear(); + this.watchedKeys.clear(); const pushed: typeof links = new Map(); const dueReads: typeof links = new Map(); for (const [key, link] of links) { const cached = this.urls.get(key); const watch = this.observations?.get(link.runnerId, link.url); - const deadline = watch?.until ?? 0; - const sample = deadline > now ? watch?.sample : undefined; + const sample = watch?.sample; if (target) { if (key === this.trackingKey(target.agentId, target.url)) dueReads.set(key, link); @@ -439,10 +436,10 @@ export class PullRequestRefresher { (sample.observedAt !== cached?.observedAt || cached.due === 0) ) { pushed.set(key, link); - } else if (deadline <= now && (cached?.due ?? 0) <= now) { + } else if (!watch && (cached?.due ?? 0) <= now) { dueReads.set(key, link); } - if (watch) this.watchDeadlines.set(key, deadline); + if (watch) this.watchedKeys.add(key); } if (!target) this.pendingUrls = new Set(dueReads.keys()); this.attempts = this.attempts.filter((at) => at > now - 60_000); @@ -493,14 +490,14 @@ export class PullRequestRefresher { : { url, title, status: "Unavailable" }; } else { this.attempts.push(Date.now()); - value = this.watchDeadlines.has(key) + value = this.watchedKeys.has(key) ? await this.options.read(url, title, runnerId, true) : await this.options.read(url, title, runnerId); if (value.status !== "Unavailable") observation = this.observations?.get(runnerId, url)?.sample; } } catch (error) { - if (target && this.watchDeadlines.has(key) && !peerChanged()) { + if (target && this.watchedKeys.has(key) && !peerChanged()) { // A failed refresh request can be a busy runner. Leave the last // card intact until the watch confirms the source is unavailable. throw new Error("Could not refresh PR. Please try again.", { diff --git a/apps/server/src/agents/remote/github-pull-request-watches.ts b/apps/server/src/agents/remote/github-pull-request-watches.ts index db5b28637..e8872f901 100644 --- a/apps/server/src/agents/remote/github-pull-request-watches.ts +++ b/apps/server/src/agents/remote/github-pull-request-watches.ts @@ -11,11 +11,25 @@ type Receiver = (event: GitHubPullRequestWatchEvent) => void; type Entry = { target: GitHubPullRequestTarget; receivers: Set; - due: number; + readAt: number; + deliverAt: number; + failures: number; sample?: Sample; flight?: Promise; }; +const activeInterval = 30_000; +const deliveryInterval = 60_000; +const minute = 60_000; +const hour = 60 * minute; + +function readDelay(sample: Sample, failures: number) { + if (failures) return Math.min(4 * hour, 15 * minute * 2 ** (failures - 1)); + if (sample.observation?.state === "MERGED") return Infinity; + if (sample.observation?.state === "CLOSED") return 6 * hour; + return activeInterval; +} + /** One bounded queue per workload account, including across transport reconnects. */ export class GitHubPullRequestWatches { private entries = new Map(); @@ -31,8 +45,7 @@ export class GitHubPullRequestWatches { private readonly read: ( target: GitHubPullRequestTarget, signal: AbortSignal - ) => Promise, - private readonly interval = 30_000 + ) => Promise ) {} subscribe(targets: GitHubPullRequestTarget[], receiver: Receiver) { @@ -74,7 +87,9 @@ export class GitHubPullRequestWatches { const receivers = new Set(); for (const entry of this.entries.values()) { entry.sample = undefined; - entry.due = 0; + entry.readAt = 0; + entry.deliverAt = Infinity; + entry.failures = 0; for (const receiver of entry.receivers) receivers.add(receiver); } for (const receiver of receivers) receiver({ type: "reset" }); @@ -109,7 +124,13 @@ export class GitHubPullRequestWatches { private entry(key: string, target: GitHubPullRequestTarget) { let entry = this.entries.get(key); if (!entry) { - entry = { target, due: 0, receivers: new Set() }; + entry = { + target, + readAt: 0, + deliverAt: Infinity, + failures: 0, + receivers: new Set(), + }; this.entries.set(key, entry); } return entry; @@ -122,21 +143,45 @@ export class GitHubPullRequestWatches { private schedule() { clearTimeout(this.timer); - if (this.paused || this.active >= 2) return; - const next = [...this.entries] - .filter(([, entry]) => entry.receivers.size && !entry.flight) - .sort(([, a], [, b]) => a.due - b.due)[0]; - if (!next) return; + if (this.paused) return; + let read: [string, Entry] | undefined; + let delivery: Entry | undefined; + for (const item of this.entries) { + const [, entry] = item; + if (!entry.receivers.size) continue; + if ( + this.active < 2 && + !entry.flight && + entry.readAt < (read?.[1].readAt ?? Infinity) + ) + read = item; + if (entry.deliverAt < (delivery?.deliverAt ?? Infinity)) delivery = entry; + } + const nextRead = read + ? Math.max(read[1].readAt, this.budgetDue()) + : Infinity; + const nextDelivery = delivery?.deliverAt ?? Infinity; + const next = Math.min(nextRead, nextDelivery); + if (!Number.isFinite(next)) return; this.timer = setTimeout( () => { - void this.sample(...next).catch(() => {}); + if (read && nextRead <= nextDelivery) { + void this.sample(...read).catch(() => {}); + } else if (delivery?.sample) { + this.deliver(delivery, delivery.sample); + } this.schedule(); }, - Math.max(0, next[1].due - Date.now(), this.budgetDue() - Date.now()) + Math.max(0, next - Date.now()) ); this.timer.unref(); } + private deliver(entry: Entry, sample: Sample) { + entry.deliverAt = Date.now() + deliveryInterval; + for (const receiver of entry.receivers) receiver(sample); + } + private sample(key: string, entry: Entry) { this.active++; this.attempts.push(Date.now()); @@ -157,8 +202,11 @@ export class GitHubPullRequestWatches { observation, }; entry.sample = sample; - entry.due = sample.observedAt + this.interval; - for (const receiver of entry.receivers) receiver(sample); + // A response with no accessible PR is a failed lifecycle read. + // An unavailable checks rollup alone leaves a healthy lifecycle due. + entry.failures = observation?.state ? 0 : entry.failures + 1; + entry.readAt = sample.observedAt + readDelay(sample, entry.failures); + this.deliver(entry, sample); return sample; }) .finally(() => { diff --git a/apps/server/test/github-pull-request-watches.test.ts b/apps/server/test/github-pull-request-watches.test.ts index a090f5e95..d93e2d068 100644 --- a/apps/server/test/github-pull-request-watches.test.ts +++ b/apps/server/test/github-pull-request-watches.test.ts @@ -109,3 +109,91 @@ it("bounds provider calls and drops an in-flight private sample at logout", asyn vi.useRealTimers(); } }); + +it("keeps open PRs responsive while replaying merged snapshots without provider reads", async () => { + vi.useFakeTimers(); + try { + const merged = { ...observation, state: "MERGED" as const }; + const open = { ...target, number: 1 }; + const closed = { ...target, number: 2 }; + const targets = [ + ...Array.from({ length: 10 }, (_, i) => ({ ...target, number: i + 3 })), + open, + closed, + ]; + const read = vi.fn(async ({ number }: typeof target) => + number === open.number + ? observation + : number === closed.number + ? { ...observation, state: "CLOSED" as const } + : merged + ); + const watches = new GitHubPullRequestWatches(read); + const receive = vi.fn(); + const close = watches.subscribe(targets, receive); + await vi.advanceTimersByTimeAsync(100); + expect(read).toHaveBeenCalledTimes(12); + const cached = receive.mock.calls.find( + ([sample]) => sample.observation?.state === "MERGED" + )![0]; + + // The first minute is at capacity. Merged PRs no longer contend for + // provider work after that window, and their original snapshot replays. + receive.mockClear(); + await vi.advanceTimersByTimeAsync(120_000); + const newReads = read.mock.calls.slice(12); + expect(newReads.length).toBeGreaterThanOrEqual(3); + expect(newReads.every(([pr]) => pr.number === open.number)).toBe(true); + expect(receive).toHaveBeenCalledWith(cached); + const replacement = vi.fn(); + const closeReplacement = watches.subscribe(targets, replacement); + close(); + expect(replacement).toHaveBeenCalledWith(cached); + + expect(await watches.refreshIfWatched(cached.target)).toEqual(merged); + expect(read).toHaveBeenLastCalledWith( + cached.target, + expect.any(AbortSignal) + ); + closeReplacement(); + } finally { + vi.useRealTimers(); + } +}); + +it("backs off repeated failed lifecycle reads while replaying the original failure timestamp", async () => { + vi.useFakeTimers(); + try { + const read = vi + .fn(async () => observation) + .mockRejectedValueOnce(new Error("GitHub unreachable")) + .mockResolvedValueOnce({ ...observation, state: null }); + const watches = new GitHubPullRequestWatches(read); + const receive = vi.fn(); + const close = watches.subscribe([target], receive); + const minute = 60_000; + await vi.advanceTimersByTimeAsync(1); + const first = receive.mock.lastCall![0]; + expect(first.observation).toBeNull(); + receive.mockClear(); + await vi.advanceTimersByTimeAsync(14 * minute); + expect(read).toHaveBeenCalledTimes(1); + expect(receive).toHaveBeenLastCalledWith(first); + + await vi.advanceTimersByTimeAsync(minute); + expect(read).toHaveBeenCalledTimes(2); + expect(receive.mock.lastCall![0].observation.state).toBeNull(); + await vi.advanceTimersByTimeAsync(29 * minute); + expect(read).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(minute); + expect(read).toHaveBeenCalledTimes(3); + expect(receive.mock.lastCall![0].observation).toEqual(observation); + + // A successful read clears the backoff and restores the open cadence. + await vi.advanceTimersByTimeAsync(30_000); + expect(read).toHaveBeenCalledTimes(4); + close(); + } finally { + vi.useRealTimers(); + } +}); diff --git a/apps/server/test/pull-request-refresher.test.ts b/apps/server/test/pull-request-refresher.test.ts index 26c7e1d0a..8824d36a2 100644 --- a/apps/server/test/pull-request-refresher.test.ts +++ b/apps/server/test/pull-request-refresher.test.ts @@ -136,6 +136,82 @@ describe("server PR orchestration", () => { } }); + it("recovers a silent watch by resubscribing without forcing provider reads", async () => { + vi.useFakeTimers(); + const f = fixture(3); + f.rows.shift(); + type Receiver = (event: GitHubPullRequestWatchEvent) => void; + const close = vi.fn(); + const watchPullRequests = vi.fn( + async ( + _id: string, + _urls: string[], + _receive: Receiver, + _ended: () => void + ) => close + ); + const service = new PullRequestRefresher({ + pool: { query: f.query } as unknown as Pool, + listAgents: async () => [{ id: "a", runnerId: "alpha" }], + publish: f.publish, + read: f.read, + remote: { canWatchPullRequests: () => true, watchPullRequests }, + warn: vi.fn(), + }); + try { + service.start(); + await vi.advanceTimersByTimeAsync(200); + const receive = watchPullRequests.mock.calls[0][2]; + const observedAt = Date.now(); + const merged: GitHubPullRequestWatchEvent = { + type: "observation", + target: { owner: "a", repo: "b", number: 1 }, + observedAt, + observation: { + state: "MERGED", + draft: false, + title: "Merged", + head: "sha", + rollup: [], + }, + }; + const failed: GitHubPullRequestWatchEvent = { + type: "observation", + target: { owner: "a", repo: "b", number: 2 }, + observedAt, + observation: null, + }; + receive(merged); + receive(failed); + await vi.advanceTimersByTimeAsync(200); + expect(service.get("a").map((pr) => pr.status)).toEqual([ + "Merged", + "Unavailable", + ]); + receive(failed); // Replay keeps the provider timestamp unchanged. + await vi.advanceTimersByTimeAsync(7 * 60_000 + 1_000); + expect(watchPullRequests).toHaveBeenCalledTimes(2); + expect(close).toHaveBeenCalledTimes(1); + const replacement = watchPullRequests.mock.calls[1]; + replacement[2](merged); + replacement[2](failed); + replacement[3](); // An ended channel also retries through subscribe. + await vi.advanceTimersByTimeAsync(31_000); + expect(watchPullRequests).toHaveBeenCalledTimes(3); + expect(f.read).not.toHaveBeenCalled(); + + await service.refreshOne("a", f.rows[0].attachments[0].url); + expect(f.read).toHaveBeenCalledExactlyOnceWith( + f.rows[0].attachments[0].url, + "PR 1", + "alpha", + true + ); + } finally { + await service.stop(); + } + }); + it("isolates background and manual reads of the same URL by runner and drops a late reply after replacement", async () => { const f = fixture(); f.rows.push({ ...f.rows[0], author_agent_id: "b" }); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index c08af61ea..24fe95696 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -350,19 +350,26 @@ includes the target, the runner's sampling time in Unix milliseconds A null observation indicates a lookup failure. A null check rollup indicates unavailable or incomplete checks, while an empty rollup is authoritative. The initial snapshot arrives one target at a time as samples become available. -Subsequent full observations include changes and refresh the timestamp even -when the source is unchanged, so a receiver can recover a missed update without -applying deltas. A `{type: "reset"}` event invalidates all prior observations on +Each new sample carries the time of its provider read. The runner also +replays the latest full observation after a minute without a new delivery, +keeping its original `observedAt`. This allows a receiver to recover a missed +event without applying deltas or mistaking a replay for a fresh provider read. A `{type: "reset"}` event invalidates all prior observations on the channel after a credential transition. A consumer should discard state on disconnect or reset, fence off the old connection, and subscribe again after -reconnect. A service can use its own receipt time for expiry. +reconnect. A service can use receipt time to detect a silent subscription. +Renew the subscription to recover delivery while preserving the runner's +provider schedule. Send the desired set of up to 64 targets when opening each channel. To update the set, open a replacement and close the previous channel. The ordinary channel `close` frame releases the subscription. The runner deduplicates case-insensitively, shares up to two concurrent samples and 12 sample attempts -per rolling minute, and normally resamples each active target after 30 seconds -subject to that budget. A host can pass `refreshWatch: true` on +per rolling minute. Subject to that budget, automatic provider reads run +every 30 seconds for open or draft PRs and every six hours for closed PRs. +Merged PRs have no automatic reads after their initial sample. Failed +lifecycle reads back off from 15 minutes to four hours. Cached delivery +does not consume the provider budget. A new subscription without a cached +sample and an account reset require a fresh initial read. A host can pass `refreshWatch: true` on `pullRequestStatus` when the watch capability is advertised. For a watched target this forces a new sample or joins one already in flight, and may return an error when capacity is exhausted. Regular status reads retain their From e9320d884e28c4f4334195a56c4af2c32caed929 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 15:35:55 -0700 Subject: [PATCH 129/642] Prepare launch workspaces on their owning runner --- apps/server/src/agents/acp/runtime.ts | 19 +- apps/server/src/agents/local-runner.ts | 27 +- .../src/agents/local-workspace-probes.ts | 119 ++++++ apps/server/src/agents/manager.ts | 364 ++++++++++-------- apps/server/src/agents/remote/runner.ts | 22 +- apps/server/src/agents/remote/service.ts | 42 +- .../src/agents/remote/session-storage.ts | 94 +++-- .../src/agents/remote/session-supervisor.ts | 58 ++- apps/server/src/agents/runtime.ts | 11 +- apps/server/src/agents/workspace-prep.ts | 14 +- apps/server/src/agents/workspace.ts | 315 ++++++++++++--- apps/server/src/main.ts | 8 + apps/server/src/projects/matching.ts | 13 +- apps/server/src/routes/system.ts | 122 +----- .../db/agent-archive-branch-cleanup.test.ts | 16 +- .../test/local-workspace-preparation.test.ts | 130 +++++++ .../test/remote-runner-supervisor.test.ts | 95 ++++- .../test/remote-session-storage.test.ts | 71 +++- .../test/runner-protocol-consumer.test.ts | 85 ++++ docs/design/runner-parity-rollout.md | 16 + e2e/remote-runner/acceptance.spec.ts | 12 +- e2e/remote-runner/entrypoint.sh | 2 +- e2e/remote-runner/setup.mjs | 5 +- packages/runner-protocol/README.md | 17 + packages/runner-protocol/src/connection.ts | 32 +- packages/runner-protocol/src/execution.ts | 37 ++ 26 files changed, 1304 insertions(+), 442 deletions(-) create mode 100644 apps/server/src/agents/local-workspace-probes.ts create mode 100644 apps/server/test/local-workspace-preparation.test.ts diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index f2bf4927d..0ac0f78fb 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -1,3 +1,4 @@ +import type { RuntimeLaunch } from "../runtime.js"; import { sameConversation, type PromptConversation } from "@dispatch/shared"; import { appendFile, mkdir, rm } from "node:fs/promises"; import path from "node:path"; @@ -292,10 +293,11 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { function requestSession( placement: Placement | null | undefined, operation: SessionLifecycleOperation, - settings?: LocalLaunchSettings + settings?: LocalLaunchSettings, + onProgress?: RuntimeLaunch["onWorkspaceProgress"] ): Promise { return placement - ? remoteService().requestSession(placement, operation) + ? remoteService().requestSession(placement, operation, onProgress) : local.requestSession(operation, settings); } @@ -1040,11 +1042,20 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }, async launch(input) { - const { placement, cwd, bins, env, pathPrefix, ...launch } = input; + const { + placement, + cwd, + bins, + env, + pathPrefix, + onWorkspaceProgress, + ...launch + } = input; const { launchExited } = await requestSession( placement, { kind: "launch", agentId: input.agentId, launch }, - { cwd, bins, env, pathPrefix } + { cwd, bins, env, pathPrefix }, + onWorkspaceProgress ); try { const entry = await connect( diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index 6e06d4446..339b6ba3f 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -4,6 +4,7 @@ import { mkdir, readdir, readFile, + realpath, rm, unlink, writeFile, @@ -25,6 +26,14 @@ import { import { preparePersonaContext } from "./acp/persona-context.js"; import { hostFile, type HostLaunch } from "./acp/host-protocol.js"; +import { + createWorkspacePreparation, + resolveLaunchDirectory, +} from "./workspace.js"; +import { resolveWorkspace } from "./workspace-target.js"; +import { resolveProjectRoot } from "../projects/resolve-root.js"; +import { inferRepositoryUrl } from "./remote/repository.js"; + export type LocalLaunchSettings = Pick< HostLaunch, "cwd" | "env" | "bins" | "pathPrefix" @@ -72,7 +81,7 @@ function signalGroup(pid: number, signal: NodeJS.Signals): void { } /** In-process implementation of runner lifecycle operations for native agent hosts. - * Launch settings come from Dispatch's trusted local workspace preparation. State + * The native workload and the host service share an OS account. State * paths and host sockets must stay compatible with hosts from earlier versions. */ export function createLocalRunner( @@ -89,6 +98,7 @@ export function createLocalRunner( throw new Error("Invalid agent state directory"); return path.join(agentStateRoot, agentId); } + const workspace = createWorkspacePreparation(logger); async function launch(input: HostLaunch) { const dir = stateDir(input.agentId); await mkdir(dir, { recursive: true, mode: 0o700 }); @@ -241,6 +251,21 @@ export function createLocalRunner( } return { requestSession, + resolveLaunchDirectory, + canonicalPath: (directory: string) => realpath(directory).catch(() => null), + resolveWorkspace, + resolveProjectRoot, + inferRepositoryUrl, + prepareWorkspace: ( + agentId: string, + directory: Parameters[1], + request: Parameters[2], + progress: Parameters[3] + ) => workspace.prepare(stateDir(agentId), directory, request, progress), + resumeWorkspace: ( + agentId: string, + progress: Parameters[1] + ) => workspace.resume(stateDir(agentId), progress), async listHosted() { let ids: string[] = []; try { diff --git a/apps/server/src/agents/local-workspace-probes.ts b/apps/server/src/agents/local-workspace-probes.ts new file mode 100644 index 000000000..031d2491a --- /dev/null +++ b/apps/server/src/agents/local-workspace-probes.ts @@ -0,0 +1,119 @@ +import os from "node:os"; +import path from "node:path"; +import { readdir, stat } from "node:fs/promises"; +import { runCommand } from "../shared/lib/run-command.js"; +import { resolveTilde } from "../shared/lib/resolve-tilde.js"; +import { shouldSkipAutomaticMacPathProbe } from "../shared/mac-path-privacy.js"; + +export async function inspectLocalPath(resolved: string) { + if (!path.isAbsolute(resolved)) { + return { + exists: false, + isDirectory: false, + isGitRepo: false, + privacyRestricted: false, + resolvedPath: resolved, + }; + } + if (shouldSkipAutomaticMacPathProbe(resolved, os.homedir())) { + return { + exists: false, + isDirectory: false, + isGitRepo: false, + privacyRestricted: true, + resolvedPath: resolved, + }; + } + try { + const info = await stat(resolved).catch(() => null); + const exists = info !== null; + const isDirectory = exists && info.isDirectory(); + let isGitRepo = false; + if (isDirectory) { + const result = await runCommand( + "git", + ["-C", resolved, "rev-parse", "--is-inside-work-tree"], + { timeoutMs: 3_000, allowedExitCodes: [0, 1, 128] } + ); + isGitRepo = result.exitCode === 0 && result.stdout.trim() === "true"; + } + return { + exists, + isDirectory, + isGitRepo, + privacyRestricted: false, + resolvedPath: resolved, + }; + } catch { + return { + exists: false, + isDirectory: false, + isGitRepo: false, + privacyRestricted: false, + resolvedPath: resolved, + }; + } +} + +export async function completeLocalPath(raw: string) { + const resolved = resolveTilde(raw); + if (!path.isAbsolute(resolved)) { + return { completions: [] }; + } + try { + const parentDir = path.dirname(resolved); + const partial = path.basename(resolved).toLowerCase(); + const isExactDir = raw.endsWith("/"); + const searchDir = isExactDir ? resolved : parentDir; + const searchPartial = isExactDir ? "" : partial; + + if (shouldSkipAutomaticMacPathProbe(searchDir, os.homedir())) { + return { completions: [], privacyRestricted: true }; + } + + const entries = await readdir(searchDir, { withFileTypes: true }); + const dirs = entries + .filter((entry) => { + if (!entry.isDirectory()) return false; + if (entry.name.startsWith(".") && !searchPartial.startsWith(".")) { + return false; + } + return entry.name.toLowerCase().startsWith(searchPartial); + }) + .sort((a, b) => a.name.localeCompare(b.name)) + .slice(0, 20) + .map((entry) => path.join(searchDir, entry.name)); + + const homeDir = os.homedir(); + const completions = dirs.map((dir) => + raw.startsWith("~") && dir.startsWith(homeDir) + ? "~" + dir.slice(homeDir.length) + : dir + ); + + return { completions, privacyRestricted: false }; + } catch { + return { completions: [], privacyRestricted: false }; + } +} + +export async function listLocalRemoteBranches(input: string) { + const cwd = resolveTilde(input); + const result = await runCommand( + "git", + ["-C", cwd, "ls-remote", "--heads", "origin"], + { timeoutMs: 15_000 } + ); + const branches = result.stdout + .split("\n") + .map((line) => line.replace(/^.*refs\/heads\//, "").trim()) + .filter(Boolean) + .sort((a, b) => { + if (a === "main") return -1; + if (b === "main") return 1; + if (a === "master") return -1; + if (b === "master") return 1; + return a.localeCompare(b); + }); + return branches; +} diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 678640478..08abdbbb0 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,7 +1,7 @@ import { readAgentView } from "./checkout-runner.js"; import type { CheckoutView } from "@dispatch/runner-protocol"; import { AttentionHistory } from "../notifications/attention-history.js"; -import { matchingProjects } from "../projects/matching.js"; +import { matchProjectIdentity } from "../projects/matching.js"; import { attentionPreview, type Effort, @@ -9,7 +9,7 @@ import { } from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; import { randomUUID } from "node:crypto"; -import { mkdir, readFile, rm, stat, unlink } from "node:fs/promises"; +import { mkdir, readFile, rm, unlink } from "node:fs/promises"; import path from "node:path"; import type { FastifyBaseLogger } from "fastify"; @@ -22,10 +22,8 @@ import { } from "../diagnostics.js"; import { assertSafeRefName, - createGitWorktree, GitWorktreeError, normalizeBaseBranch, - worktreePathSlug, } from "../shared/git/worktree.js"; import { readWorktreeStatus } from "../shared/git/worktree-status.js"; import { resolveFilesDir } from "../shared/files.js"; @@ -65,8 +63,8 @@ import { type ChatLaunchPost, shouldSuggestSessionRename, } from "./launch-guidance.js"; -import { prepareWorkspace } from "./workspace.js"; -import { resolveWorkspace } from "./workspace-target.js"; +import { createLocalRunner } from "./local-runner.js"; +import type { LaunchDirectory, WorktreeRequest } from "./workspace.js"; import { createAgentMcpToken, createJobMcpToken } from "../auth.js"; import type { SessionConfigOption } from "@agentclientprotocol/sdk"; import type { AvailableCommand } from "@agentclientprotocol/sdk"; @@ -85,10 +83,11 @@ import { MANAGED_WORKSPACE, remotePlacement, type RunnerRepository, + type LaunchProgress, type CheckoutQuery, type CheckoutReply, } from "./remote/protocol.js"; -import { inferRepositoryUrl, parseRepository } from "./remote/repository.js"; +import { parseRepository } from "./remote/repository.js"; import { RunnerRevoked, type RemoteRunnerService } from "./remote/service.js"; import { buildLaunchEnv } from "./acp/launch-env.js"; import { dispatchMcpUrl } from "./acp/mcp-url.js"; @@ -218,11 +217,8 @@ type PreparedCreateInputs = { model: string | undefined; effort: Effort | null; fullAccess: boolean; - useWorktree: boolean; - createNewBranch: boolean; normalizedBaseBranch: string | undefined; - worktreeBranchName: string | undefined; - worktreePathOverride: string | undefined; + worktree: WorktreeRequest | null; cliSessionId: string | null; initialSetupPhase: SetupPhase; }; @@ -360,6 +356,7 @@ export class AgentManager { private readonly diagnostics: DiagnosticsRecorder; private readonly eventBus: AgentEventBus; private readonly runtime: AgentRuntime; + private readonly localRunner: ReturnType; private readonly reconciler: Reconciler; private readonly streamStore: StreamStore; private readonly streamRecorder: StreamRecorder; @@ -413,6 +410,7 @@ export class AgentManager { }); this.logger = logger; this.config = config; + this.localRunner = createLocalRunner(config.agentStateRoot, logger); this.remote = options.remote; this.diagnostics = createDiagnosticsRecorder(logger); this.eventBus = createAgentEventBus(logger); @@ -1343,7 +1341,7 @@ export class AgentManager { const agent = await this.getRequiredAgent(id); if (remotePlacement(agent.cwd)) throw new AgentError("Runner workspace is fixed for this agent.", 409); - const resolved = await resolveWorkspace(agent, input); + const resolved = await this.localRunner.resolveWorkspace(agent, input); await this.pool.query( `UPDATE agents @@ -1532,7 +1530,9 @@ export class AgentManager { if (!project) throw new AgentError("Project not found.", 404); if (repository && !repository.url) { try { - repository.url = await inferRepositoryUrl(project.repo_root); + repository.url = await this.localRunner.inferRepositoryUrl( + project.repo_root + ); } catch (error) { throw new AgentError(errorMessage(error), 400); } @@ -1541,25 +1541,36 @@ export class AgentManager { // A child can use its parent's worktree while retaining explicit membership. if (!placement && !input.parentAgentId) { input.cwd = project.repo_root; - // Plain-folder projects have no Git to branch from; only an explicit - // useWorktree: true should attempt (and fail) a worktree there. - if (input.useWorktree === undefined) { - const git = await probeGitContext(project.repo_root); - if (git.status === "ok" && git.value === null) - input.useWorktree = false; - } } } + const directory = placement + ? null + : await this.localRunner.resolveLaunchDirectory(input.cwd); + // A project selected explicitly can represent a folder without Git. + if ( + directory?.git.status === "ok" && + directory.git.value === null && + input.projectId && + !input.parentAgentId && + input.useWorktree === undefined + ) + input.useWorktree = false; // Resolve only new, unscoped launches. Membership inherited from a parent // (including no project) and explicit/template selections remain authoritative. - if (!placement && !input.projectId && !input.parentAgentId) { + if (directory && !input.projectId && !input.parentAgentId) { const projects = ( await this.pool.query( 'SELECT id, name, repo_root AS "repoRoot" FROM projects' ) ).rows; - const cwd = await this.validateWorkingDirectory(input.cwd); - const matches = await matchingProjects(cwd, projects); + const matches = await matchProjectIdentity( + directory.canonicalPath, + projects.length + ? await this.localRunner.resolveProjectRoot(directory.canonicalPath) + : directory.canonicalPath, + projects, + (candidate) => this.localRunner.canonicalPath(candidate) + ); if (matches.length > 1) throw new AgentError( `Multiple projects match this directory. Choose a project: ${matches.map((p) => `${p.name} (${p.id})`).join(", ")}.`, @@ -1595,7 +1606,10 @@ export class AgentManager { "Enter a repository URL or select a project with a repository origin.", 400 ); - const p = await this.prepareCreateInputs(input); + const p = await this.prepareCreateInputs( + input, + directory?.cwd ?? input.cwd + ); await this.insertAgentRecord( p, input, @@ -1662,14 +1676,10 @@ export class AgentManager { const launch = this.launchAgent({ id: p.id, - name: p.name, type: p.type, originalCwd: p.originalCwd, - useWorktree: p.useWorktree, - createNewBranch: p.createNewBranch, - worktreeBranchName: p.worktreeBranchName, - normalizedBaseBranch: p.normalizedBaseBranch, - worktreePathOverride: p.worktreePathOverride, + directory, + worktree: p.worktree, initialPrompt: input.initialPrompt, initialFiles, resolveLaunchPost, @@ -1837,12 +1847,10 @@ export class AgentManager { } private async prepareCreateInputs( - input: CreateAgentInput + input: CreateAgentInput, + originalCwd: string ): Promise { - const placement = remotePlacement(input.cwd); - const originalCwd = placement - ? input.cwd - : await this.validateWorkingDirectory(input.cwd); + const placement = remotePlacement(originalCwd); // Remember the icon of the directory the user chose, before a managed // worktree can change the agent's effective cwd. if (!placement) await getDirectoryIconPath(this.pool, originalCwd); @@ -1891,33 +1899,19 @@ export class AgentManager { } throw err; } - if (useWorktree) { - normalizedBaseBranch = normalizedBaseBranch ?? "main"; - } - - let worktreeBranchName: string | undefined; - let worktreePathOverride: string | undefined; - if (useWorktree) { - if (createNewBranch) { - const slugName = name - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-+|-+$/g, ""); - worktreeBranchName = - normalizedWorktreeBranch || `${id}/${slugName || "work"}`; - } else { - worktreeBranchName = normalizedBaseBranch || "main"; - } - const worktreeLocation = input.worktreeLocation ?? "sibling"; - if (worktreeLocation === "nested") { - worktreePathOverride = path.join( - originalCwd, - ".dispatch", - "worktrees", - worktreePathSlug(worktreeBranchName, { createNewBranch }) - ); - } - } + const slugName = name + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + const worktree = useWorktree + ? { + name, + branch: normalizedWorktreeBranch || `${id}/${slugName || "work"}`, + createNewBranch, + baseBranch: normalizedBaseBranch, + location: input.worktreeLocation, + } + : null; // The engine mints the ACP session id at launch; a caller-supplied one // is a session to resume. @@ -1935,11 +1929,8 @@ export class AgentManager { model: input.model, effort, fullAccess, - useWorktree, - createNewBranch, normalizedBaseBranch, - worktreeBranchName, - worktreePathOverride, + worktree, cliSessionId, initialSetupPhase, }; @@ -1992,14 +1983,10 @@ export class AgentManager { */ private async launchAgent(opts: { id: string; - name: string; type: AgentType; originalCwd: string; - useWorktree: boolean; - createNewBranch: boolean; - worktreeBranchName: string | undefined; - normalizedBaseBranch: string | undefined; - worktreePathOverride: string | undefined; + directory: LaunchDirectory | null; + worktree: WorktreeRequest | null; initialPrompt: string | undefined; initialFiles: SeededFile[]; /** Writes the launch post once the workspace is ready; see createAgent. */ @@ -2012,62 +1999,32 @@ export class AgentManager { const { id } = opts; try { await opts.preparePersona?.(); - const workspace = remotePlacement(opts.originalCwd) - ? { - effectiveCwd: opts.originalCwd, - worktreePath: null, - worktreeBranch: null, - } - : await prepareWorkspace( - { - agentName: opts.name, - originalCwd: opts.originalCwd, - useWorktree: opts.useWorktree, - createNewBranch: opts.createNewBranch, - worktreeBranchName: opts.worktreeBranchName, - baseBranch: opts.normalizedBaseBranch, - worktreePathOverride: opts.worktreePathOverride, - onStepResult: async (progress) => { - await this.recordStartup(() => - this.launchContextRecorder?.recordStartupStep?.({ - agentId: id, - label: "Installing dependencies", - ...progress, - }) - ); - }, - onPhase: async (phase) => { - await this.setSetupPhase(id, phase); - await this.reportStartupPhase(id, phase, opts.type); - }, - }, - this.logger - ); - await this.pool.query( - `UPDATE agents SET cwd = $2, worktree_path = $3, worktree_branch = $4, updated_at = NOW() WHERE id = $1`, - [ - id, - workspace.effectiveCwd, - workspace.worktreePath, - workspace.worktreeBranch, - ] - ); + const progress = this.workspaceProgress(id, opts.type); + const workspace = opts.directory + ? await this.localRunner.prepareWorkspace( + id, + opts.directory, + opts.worktree, + progress + ) + : null; + if (workspace) await this.storePreparedWorkspace(id, workspace); const agent = await this.getRequiredAgent(id); const chatLaunchPost = await opts.resolveLaunchPost(); await opts.beforeLaunch?.(id); const { sessionId } = await this.startHost(agent, { resumeSessionId: null, jobRunId: opts.jobRunId, + recordWorkspaceProgress: true, }); await this.pool.query( `UPDATE agents SET status = 'running', cli_session_id = $2, setup_phase = NULL, updated_at = NOW() WHERE id = $1`, [id, sessionId] ); - await this.populateGitContext(id); await this.recordStartup(() => this.launchContextRecorder?.recordStartupDone?.({ agentId: id, - cwd: workspace.effectiveCwd, + cwd: workspace?.effectiveCwd ?? opts.originalCwd, }) ); @@ -2111,6 +2068,48 @@ export class AgentManager { } } + private workspaceProgress( + id: string, + type: AgentType + ): Parameters[1] { + return async (step) => { + if ("status" in step && step.status) { + await this.recordStartup(() => + this.launchContextRecorder?.recordStartupStep?.({ + agentId: id, + label: "Installing dependencies", + ...step, + }) + ); + } else { + await this.setSetupPhase(id, step.phase); + await this.reportStartupPhase(id, step.phase, type); + } + }; + } + + private async storePreparedWorkspace( + id: string, + workspace: Awaited> + ) { + const git = workspace.git; + await this.pool.query( + `UPDATE agents SET cwd = $2, worktree_path = $3, worktree_branch = $4, + base_branch = COALESCE($5, base_branch), git_context = $6::jsonb, + git_context_stale = $7, git_context_updated_at = NOW(), updated_at = NOW() + WHERE id = $1`, + [ + id, + workspace.effectiveCwd, + workspace.worktreePath, + workspace.worktreeBranch, + workspace.baseBranch, + git.status === "ok" && git.value ? JSON.stringify(git.value) : null, + git.status === "error", + ] + ); + } + /** Record setup progress in the stream's workspace block. */ private async reportStartupPhase( id: string, @@ -2164,6 +2163,7 @@ export class AgentManager { resumeSessionId: string | null; jobRunId: string | undefined; previousJobFinished?: boolean; + recordWorkspaceProgress?: boolean; } ): Promise<{ sessionId: string; resumed: boolean }> { if (!isAcpEngine(agent.type)) { @@ -2286,37 +2286,75 @@ export class AgentManager { ) ).rows[0] : undefined; - return this.runtime.launch({ - agentId: agent.id, - repository: binding?.runner_repository ?? undefined, - ...(binding?.runner_worktree_owner && { - useWorktreeOf: binding.runner_worktree_owner, - }), - cwd: agent.cwd, - placement, - engine: agent.type, - fullAccess: agent.type === "opencode" || agent.fullAccess, - bins, - model: agent.model ?? null, - effort: agent.effort ?? null, - systemPrompt, - personaContext: extractPersonaContext(agent.agentArgs ?? []), - mcp: mcpUrl - ? { - url: mcpUrl, - token: opts.jobRunId - ? createJobMcpToken( - this.config.authToken, - opts.jobRunId, - agent.id - ) - : createAgentMcpToken(this.config.authToken, agent.id), - } - : undefined, - env, - pathPrefix, - resumeSessionId: opts.resumeSessionId, - }); + let progressWrites = Promise.resolve(); + const onWorkspaceProgress = placement + ? (step: LaunchProgress) => { + if (!opts.recordWorkspaceProgress) return; + const write = this.workspaceProgress(agent.id, agent.type); + progressWrites = progressWrites + .then(async () => { + if (step.phase === "workspace") { + if (binding?.runner_repository) + await write({ phase: "worktree" }); + } else if (step.phase === "ready") { + await write({ phase: "session" }); + } else if ("status" in step) { + await write({ + phase: "deps", + status: step.status, + ...(step.status === "failed" && { + detail: + "The runner could not install dependencies. Launch is continuing.", + }), + }); + } else { + await write({ phase: "deps" }); + } + }) + .catch((err) => + this.logger.warn( + { err, agentId: agent.id }, + "Could not record runner preparation" + ) + ); + } + : undefined; + try { + return await this.runtime.launch({ + agentId: agent.id, + repository: binding?.runner_repository ?? undefined, + ...(binding?.runner_worktree_owner && { + useWorktreeOf: binding.runner_worktree_owner, + }), + cwd: agent.cwd, + placement, + engine: agent.type, + fullAccess: agent.type === "opencode" || agent.fullAccess, + bins, + model: agent.model ?? null, + effort: agent.effort ?? null, + systemPrompt, + personaContext: extractPersonaContext(agent.agentArgs ?? []), + mcp: mcpUrl + ? { + url: mcpUrl, + token: opts.jobRunId + ? createJobMcpToken( + this.config.authToken, + opts.jobRunId, + agent.id + ) + : createAgentMcpToken(this.config.authToken, agent.id), + } + : undefined, + env, + pathPrefix, + resumeSessionId: opts.resumeSessionId, + ...(onWorkspaceProgress && { onWorkspaceProgress }), + }); + } finally { + await progressWrites; + } } /** @@ -2377,7 +2415,7 @@ export class AgentManager { } private async startAgentClaimed(id: string): Promise { - const agent = await this.getRequiredAgent(id); + let agent = await this.getRequiredAgent(id); if (await this.runtime.attach(id)) { this.streamRecorder.setCwd(id, agent.workspacePath ?? agent.cwd); await this.setAgentStatus(id, "running", null); @@ -2387,6 +2425,16 @@ export class AgentManager { await this.setAgentStatus(id, "creating", null); try { + if (!remotePlacement(agent.cwd) && !agent.worktreePath) { + const workspace = await this.localRunner.resumeWorkspace( + id, + this.workspaceProgress(id, agent.type) + ); + if (workspace) { + await this.storePreparedWorkspace(id, workspace); + agent = await this.getRequiredAgent(id); + } + } // A stopped job still needs its run-scoped tools and launch rules when // its host is recreated. Reattaching above keeps the existing context. const jobRun = await this.pool.query<{ id: string }>( @@ -2399,7 +2447,7 @@ export class AgentManager { previousJobFinished: Boolean(agent.jobRun) && !jobRun.rows.length, }); await this.pool.query( - `UPDATE agents SET status = 'running', cli_session_id = $2, last_error = NULL, updated_at = NOW() WHERE id = $1`, + `UPDATE agents SET status = 'running', cli_session_id = $2, last_error = NULL, setup_phase = NULL, updated_at = NOW() WHERE id = $1`, [id, sessionId] ); // Re-populate gitContext on every restart so drift from external git @@ -2636,28 +2684,6 @@ export class AgentManager { return agent.cwd; } - private async validateWorkingDirectory(rawCwd: string): Promise { - const cwd = rawCwd.startsWith("~/") - ? path.join(process.env.HOME ?? "/", rawCwd.slice(2)) - : rawCwd === "~" - ? (process.env.HOME ?? "/") - : rawCwd; - - if (!path.isAbsolute(cwd)) { - throw new AgentError("Working directory must be an absolute path.", 400); - } - - const directory = await stat(cwd).catch(() => null); - if (!directory || !directory.isDirectory()) { - throw new AgentError( - "Working directory does not exist or is not a directory.", - 400 - ); - } - - return cwd; - } - private async getRequiredAgent(id: string): Promise { const agent = await this.getAgent(id); if (!agent) { diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index e29557690..967d9c0e7 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -244,6 +244,18 @@ export async function runRemoteRunner(filename: string) { env, workspaces: new Set(configuredHandles), asWorkload, + async prepareDependencies(cwd) { + await execute( + setpriv, + [...childArgs, ...selfCommand("runner-prepare-dependencies"), cwd], + { + env: { ...env, GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1" }, + timeout: 135_000, + maxBuffer: 8_192, + } + ); + return true; + }, hostCommand: () => [setpriv, ...childArgs, ...hostCommand()], }); @@ -422,7 +434,14 @@ export async function runRemoteRunner(filename: string) { const result = (value?: string | boolean) => safeSend({ type: "result", id, value }); if (command.kind === "launch") { - await supervisor.launch(command, target?.cwd); + await supervisor.launch( + command, + target?.cwd, + command.launch.prepareWorkspace + ? (progress) => + safeSend({ type: "launch_progress", id, progress }) + : undefined + ); result(true); return; } @@ -628,6 +647,7 @@ export async function runRemoteRunner(filename: string) { pullRequestWatch: true, pullRequestEvidence: true, checkoutInspection: true, + workspacePreparation: true, checkoutViews: true, sharedWorktree: true, }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index c41122bb3..74081352a 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -47,6 +47,8 @@ import { githubPullRequestHead, githubRepositoryResults, type SessionOperation, + type LaunchProgress, + parseLaunchProgress, type EngineInventoryEntry, type Placement, } from "./protocol.js"; @@ -161,6 +163,7 @@ type Peer = { checkoutInspection: boolean; checkoutViews: boolean; sharedWorktree: boolean; + workspacePreparation: boolean; /** Last pushed, validated engine inventory; absent until the runner first reports one. */ engines?: EngineInventoryEntry[]; }; @@ -680,6 +683,7 @@ export class RemoteRunnerService { checkoutViews: ready.checkoutViews === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, + workspacePreparation: ready.workspacePreparation === true, connection: new RunnerConnection(send), workspaces: new Set(ready.workspaces), managedWorkspace: ready.managedWorkspace === true, @@ -728,6 +732,13 @@ export class RemoteRunnerService { const entries = parseEngineInventory(frame.entries); if (entries === null) return socket.destroy(); peer.engines = entries; + } else if ( + frame.type === "launch_progress" && + peer.workspacePreparation + ) { + const progress = parseLaunchProgress(frame); + if (!progress) return socket.destroy(); + peer.connection.receive(progress); } else if ( frame.type === "result" || frame.type === "data" || @@ -1203,11 +1214,16 @@ export class RemoteRunnerService { return peer?.gate.approved() ? peer.engines : undefined; } - requestSession(placement: Placement, operation: SessionOperation) { + requestSession( + placement: Placement, + operation: SessionOperation, + onProgress?: (progress: LaunchProgress) => void + ) { return this.request( placement, { ...operation, workspace: placement.workspace }, - operation.kind === "attach" || operation.kind === "watchCheckout" + operation.kind === "attach" || operation.kind === "watchCheckout", + onProgress ); } @@ -1473,7 +1489,12 @@ export class RemoteRunnerService { ); } - async request(placement: Placement, command: Command, open = false) { + async request( + placement: Placement, + command: Command, + open = false, + onProgress?: (progress: LaunchProgress) => void + ) { const peer = this.peers.get(placement.runner); if ( !this.registrationById(placement.runner) && @@ -1510,7 +1531,20 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to launch a reviewer in an existing checkout." ); - return peer.connection.request(command, { openChannel: open }); + if (command.kind === "launch" && peer.workspacePreparation && onProgress) + command = { + ...command, + launch: { ...command.launch, prepareWorkspace: true }, + }; + if ( + command.kind === "launch" && + command.launch.prepareWorkspace && + !peer.workspacePreparation + ) + throw new RunnerCapabilityUnavailable( + "Update the runner to prepare session workspaces." + ); + return peer.connection.request(command, { openChannel: open, onProgress }); } close() { diff --git a/apps/server/src/agents/remote/session-storage.ts b/apps/server/src/agents/remote/session-storage.ts index d057552fd..f3c7d8ad9 100644 --- a/apps/server/src/agents/remote/session-storage.ts +++ b/apps/server/src/agents/remote/session-storage.ts @@ -32,6 +32,19 @@ function worktreePaths(list: string): string[] { ); } +type CheckoutPlan = { + commit: string; + fastForward: boolean; + reviewBase?: string; + trackRemote: boolean; +}; + +type CheckoutJournal = { + read: () => Promise; + write: (plan: CheckoutPlan) => Promise; + clear: () => Promise; +}; + // Serialize provisioning and removal for each shared bare repository. export class RunnerRepositories { private readonly pending = new Map>(); @@ -65,7 +78,8 @@ export class RunnerRepositories { async prepare( session: string, - repository: RunnerRepository + repository: RunnerRepository, + journal: CheckoutJournal ): Promise { const { url, checkout } = repository; const cwd = path.join(session, "checkout"); @@ -79,6 +93,34 @@ export class RunnerRepositories { const git = (...args: string[]) => this.git(`--git-dir=${cache}`, ...args); await this.git("init", "--quiet", "--bare", "--template=", cache); + const branch = checkout.branch; + const finish = async (plan: CheckoutPlan) => { + try { + if (plan.fastForward) + await this.git("-C", cwd, "merge", "--ff-only", "--", plan.commit); + if (plan.reviewBase) + await git( + "config", + "--replace-all", + `branch.${branch}.dispatchReviewBase`, + plan.reviewBase + ); + if (plan.trackRemote) + await git( + "branch", + `--set-upstream-to=refs/remotes/origin/${branch}`, + "--", + branch + ); + } catch (error) { + // Keep the worktree reserved. A repeat launch can finish this plan + // without deleting the checkout or mistaking its branch for someone else's. + throw new Error("Could not update the runner session branch.", { + cause: error, + }); + } + await journal.clear(); + }; const worktrees = worktreePaths( await git("worktree", "list", "--porcelain", "-z") ); @@ -89,6 +131,21 @@ export class RunnerRepositories { ).trimEnd() !== cwd ) throw new Error("The runner session checkout is unavailable."); + const plan = await journal.read(); + if (plan) { + const current = await this.git( + "-C", + cwd, + "symbolic-ref", + "--short", + "HEAD" + ); + if (current.trim() !== branch) + throw new Error( + "The runner session checkout changed during preparation." + ); + await finish(plan); + } return cwd; } @@ -133,7 +190,6 @@ export class RunnerRepositories { throw new Error("Could not fetch the runner repository."); }); - const branch = checkout.branch; const refCommit = async (ref: string) => { const output = await git( "for-each-ref", @@ -195,34 +251,22 @@ export class RunnerRepositories { const args = local ? ["--", cwd, branch] : ["--no-track", "-b", branch, "--", cwd, commit]; + const plan: CheckoutPlan = { + commit, + fastForward: needsFastForward, + reviewBase: + checkout.kind === "new" + ? (checkout.base ?? defaultBranch) + : undefined, + trackRemote: checkout.kind !== "new" && Boolean(remote), + }; + await journal.write(plan); await git("worktree", "add", ...args).catch(() => { throw new Error( "Could not create the session checkout. The branch may already be occupied." ); }); - try { - if (needsFastForward) - await this.git("-C", cwd, "merge", "--ff-only", "--", commit); - if (checkout.kind === "new") - await git( - "config", - "--replace-all", - `branch.${branch}.dispatchReviewBase`, - checkout.base ?? defaultBranch - ); - if (checkout.kind !== "new" && remote) - await git( - "branch", - `--set-upstream-to=refs/remotes/origin/${branch}`, - "--", - branch - ); - } catch (error) { - await git("worktree", "remove", "--force", "--", cwd); - throw new Error("Could not update the runner session branch.", { - cause: error, - }); - } + await finish(plan); return cwd; }); } diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 68de29783..05e159959 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -21,6 +21,7 @@ import { MANAGED_WORKSPACE, isOpaqueId, type Command, + type LaunchProgress, type RunnerRepository, } from "./protocol.js"; import { parseRepository } from "./repository.js"; @@ -59,6 +60,7 @@ type SupervisorOptions = { workspaces: ReadonlySet; hostCommand: () => string[]; asWorkload: WorkloadCommand; + prepareDependencies?: (cwd: string) => Promise; }; const managedBinding = "\0managed"; @@ -205,6 +207,9 @@ export async function createSessionSupervisor( const retireFile = (key: string) => path.join(bindings, `${key}.retired`); const repositoryFile = (key: string) => path.join(bindings, `${key}.repository`); + const planFile = (key: string) => path.join(bindings, `${key}.checkout-plan`); + const dependenciesFile = (key: string) => + path.join(bindings, `${key}.dependencies`); const cwdFile = (key: string) => path.join(bindings, `${key}.cwd`); const markerFile = (key: string) => path.join(bindings, `${key}.owner`); const identityFile = (key: string) => path.join(bindings, `${key}.host`); @@ -338,13 +343,16 @@ export async function createSessionSupervisor( await removeGuestDirectory(session); if (repository) await repositories.remove(session, repository); await rm(repositoryFile(key), { force: true }); + await rm(planFile(key), { force: true }); + await rm(dependenciesFile(key), { force: true }); } async function launch( command: LaunchCommand, cwd: string | undefined, key: string, - owner: string | null + owner: string | null, + progress?: (step: LaunchProgress) => void ) { const { agentId, workspace } = command; const { mcp } = command.launch; @@ -366,6 +374,7 @@ export async function createSessionSupervisor( : workspace; if (binding !== null && binding !== bindingValue) throw new Error("Agent is not bound to this workspace or checkout"); + progress?.({ phase: "workspace" }); if (owner) { if ((await readBinding(owner)) !== managedBinding) throw new Error("The author does not own a checkout on this runner."); @@ -410,21 +419,51 @@ export async function createSessionSupervisor( const checkout = path.join(cwd, "checkout"); if (await lstat(checkout).catch(missingPath)) await checkedDirectory(checkout); - await repositories.prepare(cwd, repository); + await repositories.prepare(cwd, repository, { + read: async () => { + const storedPlan = await readOptional(planFile(key)); + return storedPlan === null ? null : JSON.parse(storedPlan); + }, + write: (plan) => + writePrivateState(planFile(key), JSON.stringify(plan)), + clear: () => rm(planFile(key), { force: true }), + }); cwd = await managedDirectory(key); + if ( + command.launch.prepareWorkspace && + config.prepareDependencies && + (await readOptional(dependenciesFile(key))) === null + ) { + progress?.({ phase: "dependencies" }); + const installed = await config + .prepareDependencies(cwd) + .catch(() => false); + if (installed) await writePrivateState(dependenciesFile(key), "done"); + progress?.({ + phase: "dependencies", + status: installed ? "done" : "failed", + }); + } } } if (!cwd) throw new Error("Guest workspace is unavailable"); if (!managed) { - if (command.launch.useWorktreeOf === undefined) cwd = await realpath(cwd); + if (command.launch.useWorktreeOf === undefined) + cwd = command.launch.prepareWorkspace + ? (await asWorkload("realpath", ["-e", "--", cwd])).trimEnd() + : await realpath(cwd); + if (command.launch.prepareWorkspace) + await asWorkload("test", ["-d", cwd]); await checkedDirectory(cwd); await writePrivateState(cwdFile(key), cwd); } + progress?.({ phase: "ready" }); const dir = path.join(hostRoot, key); const files = path.join(dir, "files"); const { repository: _repository, useWorktreeOf: _owner, + prepareWorkspace: _preparation, ...launchOptions } = command.launch; const launch: HostLaunch = { @@ -534,11 +573,15 @@ export async function createSessionSupervisor( sweep.unref(); return { - async launch(command: LaunchCommand, cwd: string | undefined) { + async launch( + command: LaunchCommand, + cwd: string | undefined, + progress?: (step: LaunchProgress) => void + ) { const key = runnerStorageKey(command.agentId); const { useWorktreeOf } = command.launch; if (useWorktreeOf === undefined) - return serialize(key, () => launch(command, cwd, key, null)); + return serialize(key, () => launch(command, cwd, key, null, progress)); if (!isOpaqueId(useWorktreeOf) || useWorktreeOf === command.agentId) throw new Error("Invalid author for a shared runner checkout."); if (command.launch.repository !== undefined) @@ -557,7 +600,8 @@ export async function createSessionSupervisor( command, await configuredDirectory(author, cwd), key, - null + null, + progress ); }); } @@ -571,7 +615,7 @@ export async function createSessionSupervisor( (await readOptional(retireFile(author))) !== null) ) throw new Error("The author does not own a checkout on this runner."); - return launch(command, cwd, key, owner); + return launch(command, cwd, key, owner, progress); }); }, checkoutDirectory( diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index 815405611..92529e177 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -5,7 +5,11 @@ import type { AgentPermissionsResponse } from "@dispatch/shared"; import type { PromptSource, PromptOptions } from "./acp/prompt-source.js"; import type { FastifyBaseLogger } from "fastify"; -import type { Placement, RunnerRepository } from "./remote/protocol.js"; +import type { + LaunchProgress, + Placement, + RunnerRepository, +} from "./remote/protocol.js"; import type { HostLaunch } from "./acp/host-protocol.js"; import type { AppConfig } from "../config.js"; import type { DriverEvent } from "./acp/driver.js"; @@ -17,12 +21,13 @@ import { createAcpRuntime, type AcpRuntimeDeps } from "./acp/runtime.js"; /** * What the manager hands to `runtime.launch()` to start an agent's host. - * The workspace (worktree, deps) already exists; this is only about the - * process. See docs/design/acp-runtime.md. + * Native preparation supplies an effective cwd before launch. Enrolled + * runners prepare their own session workspace as part of launch. */ export type RuntimeLaunch = HostLaunch & { placement?: Placement; repository?: RunnerRepository; + onWorkspaceProgress?: (progress: LaunchProgress) => void; }; export type RuntimeEventListener = ( diff --git a/apps/server/src/agents/workspace-prep.ts b/apps/server/src/agents/workspace-prep.ts index aad8e964f..f54525e3a 100644 --- a/apps/server/src/agents/workspace-prep.ts +++ b/apps/server/src/agents/workspace-prep.ts @@ -49,7 +49,7 @@ export type WorkspaceProgress = { export async function setupAgentWorkspace( originalCwd: string, worktreePath: string, - logger: FastifyBaseLogger, + logger: Pick, onProgress?: (progress: WorkspaceProgress) => Promise ): Promise { await onProgress?.({ phase: "env" }); @@ -61,6 +61,14 @@ export async function setupAgentWorkspace( ); } + await installWorkspaceDependencies(worktreePath, logger, onProgress); +} + +export async function installWorkspaceDependencies( + worktreePath: string, + logger: Pick, + onProgress?: (progress: WorkspaceProgress) => Promise +): Promise { await onProgress?.({ phase: "deps" }); for (const [lockfile, bin, args] of LOCKFILE_INSTALL_COMMANDS) { const lockPath = path.join(worktreePath, lockfile); @@ -86,6 +94,7 @@ export async function setupAgentWorkspace( status: "done", detail: `${bin} install completed`, }); + return true; } catch (error) { await onProgress?.({ phase: "deps", @@ -96,8 +105,8 @@ export async function setupAgentWorkspace( { err: error, worktreePath, packageManager: bin }, "Dependency install failed." ); + return false; } - return; } await onProgress?.({ phase: "deps", @@ -105,4 +114,5 @@ export async function setupAgentWorkspace( detail: "No supported lockfile found; automatic dependency installation skipped.", }); + return true; } diff --git a/apps/server/src/agents/workspace.ts b/apps/server/src/agents/workspace.ts index ea0f306a4..01b06ffbb 100644 --- a/apps/server/src/agents/workspace.ts +++ b/apps/server/src/agents/workspace.ts @@ -1,79 +1,272 @@ +import { randomUUID } from "node:crypto"; +import { + mkdir, + readFile, + realpath, + rename, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import path from "node:path"; import type { FastifyBaseLogger } from "fastify"; -import { createGitWorktree } from "../shared/git/worktree.js"; +import { + probeGitContext, + resolveCurrentBranch, +} from "../shared/git/git-context.js"; +import { + createGitWorktree, + GitWorktreeError, + worktreePathSlug, +} from "../shared/git/worktree.js"; +import { AgentError } from "./errors.js"; import { setupAgentWorkspace, type WorkspaceProgress, } from "./workspace-prep.js"; -import type { SetupPhase } from "./types.js"; +import { detectDefaultBranch } from "./workspace-target.js"; -export type PrepareWorkspaceInput = { - agentName: string; - originalCwd: string; - useWorktree: boolean; +export async function resolveLaunchDirectory(rawCwd: string) { + const home = process.env.HOME ?? "/"; + const cwd = + rawCwd === "~" + ? home + : rawCwd.startsWith("~/") + ? path.join(home, rawCwd.slice(2)) + : rawCwd; + if (!path.isAbsolute(cwd)) + throw new AgentError("Working directory must be an absolute path.", 400); + const directory = await stat(cwd).catch(() => null); + if (!directory?.isDirectory()) + throw new AgentError( + "Working directory does not exist or is not a directory.", + 400 + ); + const canonicalPath = await realpath(cwd); + const git = await probeGitContext(canonicalPath, { timeoutMs: 5_000 }); + return { cwd, canonicalPath, git }; +} + +export type LaunchDirectory = Awaited< + ReturnType +>; +export type WorktreeRequest = { + name: string; + branch: string; + baseBranch?: string; createNewBranch: boolean; - worktreeBranchName: string | undefined; - baseBranch: string | undefined; - worktreePathOverride: string | undefined; - /** Phase transitions, for the sidebar's setup progress. */ - onPhase: (phase: SetupPhase) => Promise; - onStepResult?: (progress: WorkspaceProgress) => Promise; + location?: "nested" | "sibling"; }; - -export type PreparedWorkspace = { - effectiveCwd: string; - worktreePath: string | null; - worktreeBranch: string | null; +type Progress = ( + step: WorkspaceProgress | { phase: "worktree" | "session" } +) => Promise; +type Receipt = { + source: string; + sourceIdentity: string; + cwd: string; + request: WorktreeRequest; + worktree?: { + path: string; + branch: string; + base: string; + identity: string; + complete: boolean; + }; }; -/** - * Make an agent's workspace: the worktree (when asked for), the copied - * local config files, the installed dependencies. This is the one place the - * server touches an agent's filesystem before launch; when a remote host - * exists, this call becomes a host RPC with the same shape. - * - * Throws on a failed worktree creation (a `GitWorktreeError` carries its - * status code); a failed dependency install is logged and tolerated, as it - * was in the pane script. - */ -export async function prepareWorkspace( - input: PrepareWorkspaceInput, - logger: FastifyBaseLogger -): Promise { - if (!input.useWorktree || !input.worktreeBranchName) { - await input.onPhase("session"); +async function readReceipt(dir: string): Promise { + try { + return JSON.parse( + await readFile(path.join(dir, "workspace-preparation"), "utf8") + ); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } +} + +async function writeReceipt(dir: string, receipt: Receipt) { + const temporary = path.join(dir, `workspace-preparation-${randomUUID()}`); + try { + await writeFile(temporary, JSON.stringify(receipt), { + mode: 0o600, + flag: "wx", + }); + await rename(temporary, path.join(dir, "workspace-preparation")); + } finally { + await rm(temporary, { force: true }); + } +} + +async function directoryIdentity(cwd: string) { + const evidence = await stat(cwd, { bigint: true }); + return `${evidence.dev}:${evidence.ino}:${evidence.birthtimeNs}`; +} + +export function createWorkspacePreparation(logger: FastifyBaseLogger) { + const pending = new Map>(); + + async function serialize( + dir: string, + action: () => Promise + ): Promise { + const current = (pending.get(dir) ?? Promise.resolve()) + .catch(() => {}) + .then(action); + pending.set(dir, current); + try { + return await current; + } finally { + if (pending.get(dir) === current) pending.delete(dir); + } + } + + async function prepareWorktree(receipt: Receipt, progress: Progress) { + await progress({ phase: "worktree" }); + const { cwd, request, source } = receipt; + if ( + (await realpath(cwd).catch(() => null)) !== source || + (await directoryIdentity(source).catch(() => null)) !== + receipt.sourceIdentity + ) + throw new GitWorktreeError( + "The launch directory was moved or replaced.", + 409 + ); + const base = + request.baseBranch ?? + (await detectDefaultBranch(cwd)) ?? + (await resolveCurrentBranch(cwd).catch(() => null)) ?? + "main"; + const branch = request.createNewBranch ? request.branch : base; + const worktreePath = + request.location === "nested" + ? path.join( + cwd, + ".dispatch", + "worktrees", + worktreePathSlug(branch, request) + ) + : undefined; + const result = await createGitWorktree({ + cwd, + name: request.name, + branchName: request.createNewBranch ? branch : undefined, + baseBranch: base, + worktreePath, + createNewBranch: request.createNewBranch, + }).catch((error: unknown) => { + if ( + error instanceof Error && + !(error instanceof GitWorktreeError) && + /already (?:checked out|used by worktree)/i.test(error.message) + ) + throw new GitWorktreeError( + "The requested branch is already checked out in another worktree.", + 409 + ); + throw error; + }); return { - effectiveCwd: input.originalCwd, - worktreePath: null, - worktreeBranch: null, + path: result.worktreePath, + branch: result.branchName, + base, + identity: await directoryIdentity(result.worktreePath), + complete: false, }; } - await input.onPhase("worktree"); - const result = await createGitWorktree({ - cwd: input.originalCwd, - name: input.agentName, - branchName: input.createNewBranch ? input.worktreeBranchName : undefined, - baseBranch: input.baseBranch, - worktreePath: input.worktreePathOverride, - createNewBranch: input.createNewBranch, - }); - logger.info( - { worktreePath: result.worktreePath, worktreeBranch: result.branchName }, - "Created worktree." - ); - await setupAgentWorkspace( - input.originalCwd, - result.worktreePath, - logger, - async (progress) => { - if (progress.status) await input.onStepResult?.(progress); - else await input.onPhase(progress.phase); + + async function finish(dir: string, receipt: Receipt, progress: Progress) { + const worktree = + receipt.worktree ?? (await prepareWorktree(receipt, progress)); + if (!receipt.worktree) await writeReceipt(dir, { ...receipt, worktree }); + if ( + (await directoryIdentity(worktree.path).catch(() => null)) !== + worktree.identity + ) + throw new GitWorktreeError( + "The prepared worktree was removed or replaced.", + 409 + ); + + if (!worktree.complete) { + if ( + (await directoryIdentity(receipt.source).catch(() => null)) !== + receipt.sourceIdentity + ) + throw new GitWorktreeError( + "The launch directory was moved or replaced.", + 409 + ); + await setupAgentWorkspace( + receipt.source, + worktree.path, + logger, + progress + ); + await writeReceipt(dir, { + ...receipt, + worktree: { ...worktree, complete: true }, + }); } - ); - await input.onPhase("session"); + await progress({ phase: "session" }); + return { + effectiveCwd: worktree.path, + worktreePath: worktree.path, + worktreeBranch: worktree.branch, + baseBranch: worktree.base, + git: await probeGitContext(worktree.path), + }; + } + return { - effectiveCwd: result.worktreePath, - worktreePath: result.worktreePath, - worktreeBranch: result.branchName, + async prepare( + dir: string, + directory: LaunchDirectory, + request: WorktreeRequest | null, + progress: Progress + ) { + if (!request) { + await progress({ phase: "session" }); + return { + effectiveCwd: directory.cwd, + worktreePath: null, + worktreeBranch: null, + baseBranch: null, + git: directory.git, + }; + } + return serialize(dir, async () => { + const source = directory.canonicalPath; + const receipt = await readReceipt(dir); + if (receipt) { + if ( + receipt.source !== source || + JSON.stringify(receipt.request) !== JSON.stringify(request) + ) + throw new GitWorktreeError( + "This launch already owns a different worktree.", + 409 + ); + return finish(dir, receipt, progress); + } + await mkdir(dir, { recursive: true, mode: 0o700 }); + const intent = { + cwd: directory.cwd, + source, + sourceIdentity: await directoryIdentity(source), + request, + }; + await writeReceipt(dir, intent); + return finish(dir, intent, progress); + }); + }, + resume(dir: string, progress: Progress) { + return serialize(dir, async () => { + const receipt = await readReceipt(dir); + return receipt ? finish(dir, receipt, progress) : null; + }); + }, }; } diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index c97b68d5b..ff9da5adb 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -46,6 +46,14 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "runner-watch-checkout") { const { runCheckoutWatchCli } = await import("./agents/checkout-watch.js"); runCheckoutWatchCli(process.argv[3]!); +} else if (process.argv[2] === "runner-prepare-dependencies") { + const { installWorkspaceDependencies } = + await import("./agents/workspace-prep.js"); + const installed = await installWorkspaceDependencies(process.argv[3]!, { + info() {}, + warn() {}, + }); + if (!installed) process.exitCode = 1; } else if (process.argv[2] === "runner-view-checkout") { const { runCheckoutViewCli } = await import("./agents/checkout-view-cli.js"); await runCheckoutViewCli(process.argv[3]!, process.argv[4] === "--managed"); diff --git a/apps/server/src/projects/matching.ts b/apps/server/src/projects/matching.ts index 50299aaf9..881c1f304 100644 --- a/apps/server/src/projects/matching.ts +++ b/apps/server/src/projects/matching.ts @@ -13,10 +13,21 @@ export async function matchingProjects( if (!projects.length) return []; const directory = await realpath(resolveTilde(cwd)); const root = await resolveProjectRoot(directory); + return matchProjectIdentity(directory, root, projects, (root) => + realpath(root).catch(() => null) + ); +} + +export async function matchProjectIdentity( + directory: string, + root: string, + projects: Project[], + canonicalPath: (path: string) => Promise +): Promise { const matches = await Promise.all( projects.map(async (project) => { // A stale/offline project must not prevent an unrelated launch. - const projectRoot = await realpath(project.repoRoot).catch(() => null); + const projectRoot = await canonicalPath(project.repoRoot); if (!projectRoot) return null; const suffix = relative(projectRoot, directory); return projectRoot === root || diff --git a/apps/server/src/routes/system.ts b/apps/server/src/routes/system.ts index f05723b93..c9183077a 100644 --- a/apps/server/src/routes/system.ts +++ b/apps/server/src/routes/system.ts @@ -1,3 +1,8 @@ +import { + completeLocalPath, + inspectLocalPath, + listLocalRemoteBranches, +} from "../agents/local-workspace-probes.js"; import { remotePlacement, type Placement } from "../agents/remote/protocol.js"; import { isAllowedSlackLinkOrigin, @@ -5,8 +10,6 @@ import { } from "../notifications/slack-link-origins.js"; import type { SlackAnswers } from "../notifications/slack-answers.js"; import os from "node:os"; -import path from "node:path"; -import { readdir, stat } from "node:fs/promises"; import type { FastifyBaseLogger, @@ -24,9 +27,7 @@ import { } from "../agent-type-settings.js"; import { IDE_TYPES, getEnabledIdes, setEnabledIdes } from "../ide-settings.js"; import { SlackNotifier, slackDelayError } from "../notifications/slack.js"; -import { runCommand } from "../shared/lib/run-command.js"; import { resolveTilde } from "../shared/lib/resolve-tilde.js"; -import { shouldSkipAutomaticMacPathProbe } from "../shared/mac-path-privacy.js"; import { agentModelCatalog, agentModelDefaults, @@ -209,53 +210,7 @@ export async function registerSystemRoutes( resolvedPath: resolved, }; } - if (!path.isAbsolute(resolved)) { - return { - exists: false, - isDirectory: false, - isGitRepo: false, - privacyRestricted: false, - resolvedPath: resolved, - }; - } - if (shouldSkipAutomaticMacPathProbe(resolved, os.homedir())) { - return { - exists: false, - isDirectory: false, - isGitRepo: false, - privacyRestricted: true, - resolvedPath: resolved, - }; - } - try { - const info = await stat(resolved).catch(() => null); - const exists = info !== null; - const isDirectory = exists && info.isDirectory(); - let isGitRepo = false; - if (isDirectory) { - const result = await runCommand( - "git", - ["-C", resolved, "rev-parse", "--is-inside-work-tree"], - { timeoutMs: 3_000, allowedExitCodes: [0, 1, 128] } - ); - isGitRepo = result.exitCode === 0 && result.stdout.trim() === "true"; - } - return { - exists, - isDirectory, - isGitRepo, - privacyRestricted: false, - resolvedPath: resolved, - }; - } catch { - return { - exists: false, - isDirectory: false, - isGitRepo: false, - privacyRestricted: false, - resolvedPath: resolved, - }; - } + return inspectLocalPath(resolved); }); app.get("/api/v1/system/path-completions", async (request, reply) => { @@ -265,46 +220,7 @@ export async function registerSystemRoutes( .code(400) .send({ error: "prefix query parameter is required." }); } - const raw = query.prefix.trim(); - const resolved = resolveTilde(raw); - if (!path.isAbsolute(resolved)) { - return { completions: [] }; - } - try { - const parentDir = path.dirname(resolved); - const partial = path.basename(resolved).toLowerCase(); - const isExactDir = raw.endsWith("/"); - const searchDir = isExactDir ? resolved : parentDir; - const searchPartial = isExactDir ? "" : partial; - - if (shouldSkipAutomaticMacPathProbe(searchDir, os.homedir())) { - return { completions: [], privacyRestricted: true }; - } - - const entries = await readdir(searchDir, { withFileTypes: true }); - const dirs = entries - .filter((entry) => { - if (!entry.isDirectory()) return false; - if (entry.name.startsWith(".") && !searchPartial.startsWith(".")) { - return false; - } - return entry.name.toLowerCase().startsWith(searchPartial); - }) - .sort((a, b) => a.name.localeCompare(b.name)) - .slice(0, 20) - .map((entry) => path.join(searchDir, entry.name)); - - const homeDir = os.homedir(); - const completions = dirs.map((dir) => - raw.startsWith("~") && dir.startsWith(homeDir) - ? "~" + dir.slice(homeDir.length) - : dir - ); - - return { completions, privacyRestricted: false }; - } catch { - return { completions: [], privacyRestricted: false }; - } + return completeLocalPath(query.prefix.trim()); }); app.get("/api/v1/git/branches", async (request, reply) => { @@ -315,29 +231,7 @@ export async function registerSystemRoutes( .send({ error: "cwd query parameter is required." }); } try { - const cwd = resolveTilde(query.cwd.trim()); - const result = await runCommand( - "git", - ["-C", cwd, "ls-remote", "--heads", "origin"], - { timeoutMs: 15_000 } - ); - if (result.exitCode !== 0) { - return reply - .code(500) - .send({ error: "Failed to list remote branches." }); - } - const branches = result.stdout - .split("\n") - .map((line) => line.replace(/^.*refs\/heads\//, "").trim()) - .filter(Boolean) - .sort((a, b) => { - if (a === "main") return -1; - if (b === "main") return 1; - if (a === "master") return -1; - if (b === "master") return 1; - return a.localeCompare(b); - }); - return { branches }; + return { branches: await listLocalRemoteBranches(query.cwd.trim()) }; } catch { return reply.code(500).send({ error: "Failed to list remote branches." }); } diff --git a/apps/server/test/db/agent-archive-branch-cleanup.test.ts b/apps/server/test/db/agent-archive-branch-cleanup.test.ts index f2c31a476..101f45b7d 100644 --- a/apps/server/test/db/agent-archive-branch-cleanup.test.ts +++ b/apps/server/test/db/agent-archive-branch-cleanup.test.ts @@ -15,6 +15,9 @@ import { beforeEach, vi, } from "vitest"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; import type { Pool } from "pg"; import { setupTestDb, teardownTestDb, runTestMigrations } from "./setup.js"; @@ -26,6 +29,8 @@ vi.mock("../../src/shared/lib/run-command.js", () => ({ // Stub the worktree helpers so we can (a) skip real git work during archive // and (b) observe what AgentManager asks us to do. +let fixtureRoot: string; + const cleanupGitWorktreeSpy = vi.fn(async () => ({ repoRoot: "/tmp/repo", worktreePath: "/tmp/repo-wt", @@ -45,7 +50,7 @@ vi.mock("../../src/shared/git/worktree.js", async () => { cleanupGitWorktree: cleanupGitWorktreeSpy, createGitWorktree: vi.fn(async (input) => ({ repoRoot: "/tmp/repo", - worktreePath: "/tmp/repo-wt", + worktreePath: await mkdtemp(path.join(fixtureRoot, "worktree-")), worktreeName: "repo-wt", branchName: input.createNewBranch === false @@ -94,10 +99,17 @@ let manager: InstanceType; beforeAll(async () => { pool = await setupTestDb(); await runTestMigrations(); - manager = new AgentManager(pool, noopLogger, inertConfig); + fixtureRoot = await mkdtemp( + path.join(tmpdir(), "dispatch-archive-worktree-") + ); + manager = new AgentManager(pool, noopLogger, { + ...inertConfig, + agentStateRoot: path.join(fixtureRoot, "hosts"), + }); }); afterAll(async () => { + if (fixtureRoot) await rm(fixtureRoot, { recursive: true, force: true }); await teardownTestDb(); }); diff --git a/apps/server/test/local-workspace-preparation.test.ts b/apps/server/test/local-workspace-preparation.test.ts new file mode 100644 index 000000000..bf740b885 --- /dev/null +++ b/apps/server/test/local-workspace-preparation.test.ts @@ -0,0 +1,130 @@ +import { + mkdtemp, + mkdir, + readFile, + realpath, + rm, + writeFile, +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { FastifyBaseLogger } from "fastify"; +import { expect, it, vi } from "vitest"; +import { createLocalRunner } from "../src/agents/local-runner.js"; +import { runCommand } from "../src/shared/lib/run-command.js"; + +const logger = { info: vi.fn(), warn: vi.fn() } as unknown as FastifyBaseLogger; + +it("prepares native folders, direct checkouts and independent worktrees", async () => { + const root = await mkdtemp( + path.join(await realpath(os.tmpdir()), "runner-workspace-") + ); + const checkout = path.join(root, "repository"); + const folder = path.join(root, "folder"); + const hosts = path.join(root, "hosts"); + const runner = createLocalRunner(hosts, logger); + const git = async (cwd: string, ...args: string[]) => + (await runCommand("git", ["-C", cwd, ...args])).stdout; + const progress = vi.fn().mockResolvedValue(undefined); + try { + await mkdir(folder); + await mkdir(checkout); + await git(checkout, "init", "-b", "main"); + await writeFile(path.join(checkout, ".gitignore"), ".env\n"); + await git(checkout, "add", ".gitignore"); + const commit = (message: string) => + git( + checkout, + "-c", + "user.name=Runner", + "-c", + "user.email=runner@example.test", + "commit", + "--allow-empty", + "-m", + message + ); + await commit("main"); + await git(checkout, "switch", "-c", "develop"); + await commit("develop"); + const base = await git(checkout, "rev-parse", "HEAD"); + await git(checkout, "switch", "main"); + await writeFile(path.join(checkout, ".env"), "LOCAL_CONFIG=fixture\n"); + + const native = await runner.resolveLaunchDirectory(checkout); + expect( + await runner.prepareWorkspace( + "folder", + await runner.resolveLaunchDirectory(folder), + null, + progress + ) + ).toMatchObject({ + effectiveCwd: folder, + git: { status: "ok", value: null }, + }); + expect( + await runner.prepareWorkspace("direct", native, null, progress) + ).toMatchObject({ + effectiveCwd: checkout, + worktreePath: null, + git: { value: { branch: "main", repoRoot: checkout } }, + }); + await expect( + runner.prepareWorkspace( + "busy", + native, + { + name: "Busy", + branch: "main", + createNewBranch: false, + }, + progress + ) + ).rejects.toMatchObject({ statusCode: 409 }); + + const request = { + name: "Work", + branch: "session/work", + baseBranch: "develop", + createNewBranch: true, + }; + await expect( + runner.prepareWorkspace("work", native, request, async (step) => { + if (step.phase === "deps") throw new Error("interrupted preparation"); + }) + ).rejects.toThrow("interrupted preparation"); + const restartedRunner = createLocalRunner(hosts, logger); + const resumed = await restartedRunner.resumeWorkspace("work", progress); + expect(resumed).toMatchObject({ + baseBranch: "develop", + worktreeBranch: "session/work", + }); + const worktree = resumed!.effectiveCwd; + expect(await git(worktree, "rev-parse", "HEAD")).toBe(base); + expect(await readFile(path.join(worktree, ".env"), "utf8")).toBe( + "LOCAL_CONFIG=fixture\n" + ); + await expect( + restartedRunner.prepareWorkspace("other", native, request, progress) + ).rejects.toMatchObject({ statusCode: 409 }); + expect(await git(worktree, "branch", "--show-current")).toBe( + "session/work" + ); + expect( + (await git(checkout, "worktree", "list", "--porcelain")).match( + /^worktree /gm + ) + ).toHaveLength(2); + // The failed request can retry once its branch is available again. + await git(checkout, "switch", "develop"); + const available = await restartedRunner.resumeWorkspace("busy", progress); + expect(available).toMatchObject({ + baseBranch: "main", + worktreeBranch: "main", + }); + expect(await git(checkout, "branch", "--show-current")).toBe("develop"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index 2f2971645..7c69d1221 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -95,7 +95,8 @@ describe("runner session supervision", () => { workspaces: string[], asWorkload: Parameters< typeof createSessionSupervisor - >[0]["asWorkload"] = vi.fn() + >[0]["asWorkload"] = vi.fn(), + prepareDependencies?: (cwd: string) => Promise ) { supervisor = await createSessionSupervisor( { @@ -108,6 +109,7 @@ describe("runner session supervision", () => { workspaces: new Set(workspaces), hostCommand: () => ["/test-host"], asWorkload, + prepareDependencies, }, processes ); @@ -138,6 +140,29 @@ describe("runner session supervision", () => { await rm(root, { recursive: true, force: true }); }); + it("prepares managed scratch and reports request-scoped progress before starting the host", async () => { + const runner = await start([]); + const progress = vi.fn(); + const command = launch(MANAGED_WORKSPACE); + await runner.launch( + { + ...command, + launch: { ...command.launch, prepareWorkspace: true }, + }, + undefined, + progress + ); + const cwd = path.join(state, "sessions", agentId); + expect(await runner.checkoutDirectory(agentId, MANAGED_WORKSPACE)).toBe( + cwd + ); + expect((await stat(cwd)).isDirectory()).toBe(true); + expect(progress.mock.calls).toEqual([ + [{ phase: "workspace" }], + [{ phase: "ready" }], + ]); + }); + it.each([ { config: ["configured", "other"], workspace: "configured" }, { config: [], workspace: "@session" }, @@ -621,7 +646,7 @@ describe("runner session supervision", () => { await expect(stat(author)).rejects.toMatchObject({ code: "ENOENT" }); }); - it("records the review base of new branches without assigning an upstream", async () => { + it("records review bases and retries dependency preparation in the same checkout", async () => { const git = (...args: string[]) => execFileSync("git", args, { encoding: "utf8" }); const workspace = MANAGED_WORKSPACE; @@ -642,14 +667,21 @@ describe("runner session supervision", () => { "seed" ); git("-C", seed, "branch", "release"); - const running = await start([], async (bin, args) => - execFileSync( - bin, - args.some((arg) => arg === "ls-remote" || arg === "fetch") - ? args.map((arg) => (arg === url ? seed : arg)) - : args, - { encoding: "utf8" } - ) + const prepareDependencies = vi + .fn() + .mockResolvedValueOnce(false) + .mockResolvedValue(true); + const running = await start( + [], + async (bin, args) => + execFileSync( + bin, + args.some((arg) => arg === "ls-remote" || arg === "fetch") + ? args.map((arg) => (arg === url ? seed : arg)) + : args, + { encoding: "utf8" } + ), + prepareDependencies ); for (const [branch, base] of [ @@ -657,19 +689,40 @@ describe("runner session supervision", () => { ["default-base", undefined], ] as const) { const id = `review-${branch}`; - processes.spawn.mockResolvedValueOnce(); - await running.launch( - { - ...launch(workspace), - agentId: id, - launch: { - ...launch(workspace).launch, - repository: { url, checkout: { kind: "new", branch, base } }, - }, + const command = { + ...launch(workspace), + agentId: id, + launch: { + ...launch(workspace).launch, + prepareWorkspace: true as const, + repository: { url, checkout: { kind: "new" as const, branch, base } }, }, - undefined - ); + }; + const startCheckout = async () => { + processes.spawn.mockResolvedValueOnce(); + const progress = vi.fn(); + await running.launch(command, undefined, progress); + return progress.mock.calls.map(([step]) => step); + }; + const steps = await startCheckout(); const cwd = await running.checkoutDirectory(id, workspace); + expect(prepareDependencies).toHaveBeenLastCalledWith(cwd); + if (base) { + expect(steps).toContainEqual({ + phase: "dependencies", + status: "failed", + }); + expect(await startCheckout()).toContainEqual({ + phase: "dependencies", + status: "done", + }); + expect(await running.checkoutDirectory(id, workspace)).toBe(cwd); + expect(await startCheckout()).toEqual([ + { phase: "workspace" }, + { phase: "ready" }, + ]); + expect(prepareDependencies).toHaveBeenCalledTimes(2); + } const config = git( "-C", cwd, diff --git a/apps/server/test/remote-session-storage.test.ts b/apps/server/test/remote-session-storage.test.ts index 05daf1d02..0c207b329 100644 --- a/apps/server/test/remote-session-storage.test.ts +++ b/apps/server/test/remote-session-storage.test.ts @@ -159,15 +159,39 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e const sessions = path.join(root, "sessions"); const uid = process.getuid!(); const gid = process.getgid!(); + let failReviewBase = false; const repositories = new RunnerRepositories( cache, uid, gid, (bin, args) => { expect(bin).toBe("git"); + if ( + failReviewBase && + args.some((arg) => arg.endsWith(".dispatchReviewBase")) + ) { + failReviewBase = false; + return Promise.reject(new Error("interrupted Git configuration")); + } return git("-c", `url.file://${origin}.insteadOf=${url}`, ...args); } ); + type Journal = Parameters[2]; + type Plan = Parameters[0]; + const plans = new Map(); + const prepare = ( + directory: string, + repository: Parameters[1] + ) => + repositories.prepare(directory, repository, { + read: async () => plans.get(directory) ?? null, + write: async (plan) => { + plans.set(directory, plan); + }, + clear: async () => { + plans.delete(directory); + }, + }); const spec = (checkout: RepositoryCheckout) => ({ url, checkout }); const session = (key: string) => prepareScratchSession(sessions, key, uid, gid); @@ -177,9 +201,25 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e const c = await session("c"); const newBranch = spec({ kind: "new", branch: "work" }); const existing = spec({ kind: "branch", branch: "topic" }); + const interrupted = await session("interrupted"); + const retry = spec({ kind: "new", branch: "retry", base: "topic" }); + failReviewBase = true; + await expect(prepare(interrupted, retry)).rejects.toThrow( + "Could not update" + ); + const retryPath = path.join(interrupted, "checkout"); + expect(await git("-C", retryPath, "rev-parse", "HEAD")).toBe(topic + "\n"); + await expect(prepare(interrupted, retry)).resolves.toBe(retryPath); + expect( + ( + await git("-C", retryPath, "config", "branch.retry.dispatchReviewBase") + ).trim() + ).toBe("topic"); + expect(plans.has(interrupted)).toBe(false); + const [first, second] = await Promise.all([ - repositories.prepare(a, newBranch), - repositories.prepare(b, existing), + prepare(a, newBranch), + prepare(b, existing), ]); expect((await git("-C", first, "rev-parse", "HEAD")).trim()).toBe(initial); expect((await git("-C", first, "branch", "--show-current")).trim()).toBe( @@ -189,13 +229,13 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e expect((await git("-C", second, "branch", "--show-current")).trim()).toBe( "topic" ); - expect(await repositories.prepare(a, newBranch)).toBe(first); - await expect(repositories.prepare(c, existing)).rejects.toThrow("occupied"); + expect(await prepare(a, newBranch)).toBe(first); + await expect(prepare(c, existing)).rejects.toThrow("occupied"); await expect( - repositories.prepare(c, spec({ kind: "branch", branch: "main" })) + prepare(c, spec({ kind: "branch", branch: "main" })) ).rejects.toThrow("default branch"); await expect( - repositories.prepare(c, spec({ kind: "new", branch: "topic" })) + prepare(c, spec({ kind: "new", branch: "topic" })) ).rejects.toThrow("already exists"); await repositories.remove(b, existing); @@ -205,16 +245,14 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e ).toBe(topic); const pr = spec({ kind: "pr", branch: "topic", number: 1 }); expect( - ( - await git("-C", await repositories.prepare(c, pr), "rev-parse", "HEAD") - ).trim() + (await git("-C", await prepare(c, pr), "rev-parse", "HEAD")).trim() ).toBe(topic); await repositories.remove(c, pr); await git("-C", origin, "switch", "topic"); const updatedTopic = await commit("updated PR head"); await git("-C", origin, "update-ref", "refs/pull/1/head", updatedTopic); await git("-C", origin, "switch", "main"); - const updated = await repositories.prepare(c, pr); + const updated = await prepare(c, pr); expect((await git("-C", updated, "rev-parse", "HEAD")).trim()).toBe( updatedTopic ); @@ -240,15 +278,13 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e await git("-C", origin, "switch", "topic"); const divergent = await commit("different remote work"); await git("-C", origin, "switch", "main"); - await expect(repositories.prepare(c, existing)).rejects.toThrow( - "has local work" - ); + await expect(prepare(c, existing)).rejects.toThrow("has local work"); expect( (await git("-C", first, "rev-parse", "refs/heads/topic")).trim() ).toBe(localHead); await expect( - repositories.prepare(c, spec({ kind: "pr", branch: "topic", number: 2 })) + prepare(c, spec({ kind: "pr", branch: "topic", number: 2 })) ).rejects.toThrow("does not match"); const selectedBase = spec({ kind: "new", @@ -257,12 +293,7 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e }); expect( ( - await git( - "-C", - await repositories.prepare(c, selectedBase), - "rev-parse", - "HEAD" - ) + await git("-C", await prepare(c, selectedBase), "rev-parse", "HEAD") ).trim() ).toBe(divergent); } finally { diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index b4a1b70df..2e202b43e 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -8,6 +8,8 @@ import { type ServiceFrame, type Command, parseReadyFrame, + parseLaunchProgress, + type LaunchProgress, parseServiceFrame, parseSessionCommand, parseConnectCreated, @@ -132,6 +134,89 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () expect(parseReadyFrame(managed)).toEqual(managed); }); +it("negotiates workspace progress per runner when workspace handles match", async () => { + const ready = { type: "ready", version: 1, workspaces: ["workspace"] }; + const placement = (runner: string) => + workspaceLocator({ runner, workspace: "workspace" }); + const legacy = placement("legacy"); + const current = placement("current"); + const peers = new Map( + [legacy, current].map((locator) => { + const advertised = parseReadyFrame({ + ...ready, + workspacePreparation: locator === current, + })!; + const messages: ServiceFrame[] = []; + const connection = new RunnerConnection((frame) => messages.push(frame)); + return [locator, { advertised, messages, connection }]; + }) + ); + const launch = (locator: string, received: LaunchProgress[]) => { + const { connection, advertised } = peers.get(locator)!; + return connection.request( + { + kind: "launch", + agentId: "host/session", + workspace: "workspace", + launch: { + agentId: "host/session", + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + ...(advertised.workspacePreparation && { prepareWorkspace: true }), + }, + }, + { onProgress: (event) => received.push(event) } + ); + }; + const legacyProgress: LaunchProgress[] = []; + const enhancedProgress: LaunchProgress[] = []; + const earlier = launch(legacy, legacyProgress); + const enhanced = launch(current, enhancedProgress); + const currentPeer = peers.get(current)!; + const legacyPeer = peers.get(legacy)!; + const request = (peer: typeof currentPeer) => { + const frame = parseServiceFrame(peer.messages[0]); + if (frame?.type !== "request" || frame.command.kind !== "launch") + throw new Error("Expected launch request."); + return { id: frame.id, launch: frame.command.launch }; + }; + const currentRequest = request(currentPeer); + const legacyRequest = request(legacyPeer); + expect(currentRequest.launch.prepareWorkspace).toBe(true); + expect(legacyRequest.launch).not.toHaveProperty("prepareWorkspace"); + const progress = parseLaunchProgress({ + type: "launch_progress", + id: currentRequest.id, + progress: { phase: "workspace" }, + })!; + currentPeer.connection.receive(progress); + legacyPeer.connection.receive(progress); + expect(enhancedProgress).toEqual([{ phase: "workspace" }]); + expect(legacyProgress).toEqual([]); + expect( + parseLaunchProgress({ + ...progress, + progress: { phase: "ready", status: "failed" }, + }) + ).toBeNull(); + for (const [peer, id] of [ + [currentPeer, currentRequest.id], + [legacyPeer, legacyRequest.id], + ] as const) { + expect(peer.advertised.workspaces).toEqual(["workspace"]); + peer.connection.receive({ type: "result", id, value: true }); + } + await expect(Promise.all([earlier, enhanced])).resolves.toEqual([ + { value: true, channel: undefined }, + { value: true, channel: undefined }, + ]); + currentPeer.connection.receive(progress); + expect(enhancedProgress).toHaveLength(1); + for (const peer of peers.values()) peer.connection.close(); +}); + it("validates runner-scoped GitHub command payloads", () => { const parse = (operation: unknown) => parseServiceFrame({ diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index 9cff94b39..e96db0014 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -21,6 +21,22 @@ Merge-risk details and commit comparisons now use the owning runner's GitHub cre Dispatch now sends the union of tracked PRs to each capable runner. Runner observations include sampling time and full current state so a missed update can be recovered on the next sample. Reconnect reopens the watch, and account reset clears the previous credential’s snapshots. Older peers continue using scheduled reads. The Dispatch host still owns browser events, dismissals, and notices. +## Workspace preparation + +The built-in runner probes the launch path and Git state, prepares native +worktrees, and returns the effective directory, selected base and Git context +to Dispatch. Dispatch still resolves project membership and picks launch +options. A selected native project's inferred HTTPS origin comes from the +native runner because that is where the project path is registered. + +Enrolled runners bind the workspace and session handles on the authenticated +connection. Their configured directories, managed scratch directories, and +repository checkouts are machine-local. Managed repository preparation can +report progress through the optional v1 `workspacePreparation` capability, +including dependency installation as the workload account. The service maps +that progress to its own startup UI. Existing v1 launchers can continue to use +the baseline launch request and result. + ## Live updates Each observation needs an owning machine/account, freshness, a bounded payload, and a way to reconcile after a disconnect. Dispatch tracks which resources matter and projects observations into existing UI events. Test missed events and late replies from replaced connections. Preserve the difference between an empty result and unavailable data. Use the existing refresh budget while migrating PR reads, then test subscription and reconciliation behavior independently of browser count. diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index 14ecaf4e2..dc613853e 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -27,7 +27,7 @@ import { } from "./harness"; // One serial fleet: a local agent plus two Docker runners that both expose a -// workspace named "proof". Marker files differ per runner, so any output or +// workspace named "proof" at the same absolute path. Markers differ, so any output or // file landing on the wrong side is visible. test.describe.configure({ mode: "serial" }); const WS = state.workspace; @@ -76,6 +76,9 @@ test("enroll two runners with identical workspace names", async ({ expect(row.status).toBe("online"); expect(row.workspaces).toContain(WS); } + expect(state.runners.alpha.workspaceDir).toBe( + state.runners.beta.workspaceDir + ); expect(marker("alpha")).not.toBe(marker("beta")); }); @@ -471,6 +474,13 @@ test("managed scratch launch reports health and archive removes the guest sessio await expect( settledTurns(page).last().getByTestId("harness-result") ).toContainText("Local or guest fixture turn completed."); + // The runner records workspace preparation on the launch request before + // the fixture engine can return its first turn. + const stream = await request.get(`/api/v1/streams/${id}/blocks`, { + headers: authHeaders(), + }); + expect(stream.ok(), await stream.text()).toBe(true); + expect(await stream.text()).toContain("Starting Claude"); const directory = `/var/lib/runner/sessions/${id}`; expect(guest("scratch", `stat -c '%u:%g %a' ${directory}`).trim()).toBe( "1500:1500 700" diff --git a/e2e/remote-runner/entrypoint.sh b/e2e/remote-runner/entrypoint.sh index a47a01d83..fd11f9020 100755 --- a/e2e/remote-runner/entrypoint.sh +++ b/e2e/remote-runner/entrypoint.sh @@ -12,7 +12,7 @@ install -d -m 700 /run/cfg /var/lib/runner install -d -m 755 /home/guest /etc/dispatch-runner cp /etc/runner/runner.json /run/cfg/runner.json && chmod 600 /run/cfg/runner.json if [ "$NAME" != scratch ]; then - WS="/opt/dispatch-guest-$NAME-proof" + WS="/opt/dispatch-guest-proof" mkdir -p "$WS" echo "marker-$NAME-$(cat /proc/sys/kernel/random/uuid)" > "$WS/marker.txt" chown -R 1500:1500 "$WS" diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs index f65eab367..09eafcd3a 100644 --- a/e2e/remote-runner/setup.mjs +++ b/e2e/remote-runner/setup.mjs @@ -22,6 +22,7 @@ const here = path.dirname(fileURLToPath(import.meta.url)); const root = path.resolve(here, "../.."); const RUNNERS = ["alpha", "beta", "scratch"]; const WORKSPACE = "proof"; // identical handle on every runner, on purpose +const WORKSPACE_DIR = "/opt/dispatch-guest-proof"; // Colima/Docker Desktop share $HOME, not /tmp, with the VM; bind mounts must live here. export const base = process.env.REMOTE_E2E_ROOT ?? @@ -144,7 +145,7 @@ async function up(run) { ? {} : { [WORKSPACE]: { - cwd: `/opt/dispatch-guest-${name}-proof`, + cwd: WORKSPACE_DIR, repoTool: ["/bin/sh", "-c", "echo ran > repo-op"], }, }, @@ -159,7 +160,7 @@ async function up(run) { state.runners[name] = { container: `dispatch-remote-e2e-${id}-${name}`, proxyPort, - workspaceDir: `/opt/dispatch-guest-${name}-proof`, + workspaceDir: WORKSPACE_DIR, }; } const child = spawn( diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 24fe95696..393965b28 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -114,6 +114,23 @@ An occupied or conflicting branch causes launch to fail. A successful cached branches. Services can retry discard after a lost acknowledgement. Configured workspace handles continue to use their configured directory. +A runner advertising `workspacePreparation: true` accepts +`launch.prepareWorkspace: true`. When requested, the runner sends +`launch_progress` frames on the same connection and request ID before the +ordinary launch result. Use `parseLaunchProgress` and route valid frames to +`RunnerConnection.receive`. A caller using `RunnerConnection.request` can +receive them through `onProgress`. Progress describes workspace selection +(`workspace`), optional dependency preparation (`dependencies` with a +separate `done` or `failed` event), and the handoff to host startup +(`ready`). Dependency failure permits the host to start and a later launch +can retry it. A launch result still acknowledges host startup. Progress is +advisory and does not replay. After a lost result, attach first. If the host +is absent, retry using the same session and repository handles. The runner +retains a prepared checkout, resumes interrupted checkout configuration, and +rejects conflicting checkout selections. Services can continue sending +baseline launches without this field to v1 peers that omit the capability. +A runner sends no progress frames on baseline launches. + The optional launch field `mcp` supplies one service-scoped MCP endpoint using an HTTPS `url`, bearer `token`, and optional `name`. Absence starts the ACP session with an empty service MCP list. v1 launches with the original diff --git a/packages/runner-protocol/src/connection.ts b/packages/runner-protocol/src/connection.ts index ab6da7e6c..87a7635fa 100644 --- a/packages/runner-protocol/src/connection.ts +++ b/packages/runner-protocol/src/connection.ts @@ -3,6 +3,8 @@ import type { ChannelFrame, Command, ResultFrame, + LaunchProgress, + LaunchProgressFrame, ServiceFrame, } from "./index.js"; import { hostChannel } from "./node.js"; @@ -13,13 +15,20 @@ export class RunnerHostGone extends Error {} /** Service side of one authenticated runner connection. Request IDs and channels are local to it. */ export class RunnerConnection { private readonly pending = new Map void>(); + private readonly progress = new Map< + string, + (progress: LaunchProgress) => void + >(); private readonly channels = new Map(); private closed = false; constructor(private readonly send: (frame: ServiceFrame) => void) {} - receive(frame: ChannelFrame | ResultFrame) { + receive(frame: ChannelFrame | ResultFrame | LaunchProgressFrame) { switch (frame.type) { + case "launch_progress": + this.progress.get(frame.id)?.(frame.progress); + break; case "result": this.pending.get(frame.id)?.(frame); break; @@ -39,7 +48,16 @@ export class RunnerConnection { this.channels.clear(); } - async request(command: Command, { openChannel = false } = {}) { + async request( + command: Command, + { + openChannel = false, + onProgress, + }: { + openChannel?: boolean; + onProgress?: (progress: LaunchProgress) => void; + } = {} + ) { if (this.closed) throw new RunnerUnavailable("The runner connection is closed."); const id = crypto.randomUUID(); @@ -49,6 +67,12 @@ export class RunnerConnection { // The consumer can attach its error listener after the request resolves. channel?.on("error", () => {}); if (channel) this.channels.set(id, channel); + if ( + command.kind === "launch" && + command.launch.prepareWorkspace && + onProgress + ) + this.progress.set(id, onProgress); try { const value = await this.sendRequest(id, command); return { value, channel }; @@ -67,13 +91,15 @@ export class RunnerConnection { command.kind === "inspectCheckout" || command.kind === "viewCheckout" || command.kind === "engine" || - (command.kind === "launch" && command.launch.repository) + (command.kind === "launch" && + (command.launch.repository || command.launch.prepareWorkspace)) ? 300_000 : 20_000; return new Promise((resolve, reject) => { const finish = (frame?: ResultFrame) => { clearTimeout(timer); this.pending.delete(id); + this.progress.delete(id); if (!frame) reject( new RunnerUnavailable( diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index c518eca32..ff31ffcbb 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -46,6 +46,8 @@ export type RemoteLaunch = { resumeSessionId: string | null; repository?: RunnerRepository; useWorktreeOf?: string; + /** Opt in to workspace preparation and request-scoped progress. */ + prepareWorkspace?: true; }; export type SessionLifecycleOperation = { agentId: string } & ( @@ -85,6 +87,7 @@ export type ReadyFrame = { checkoutInspection?: true; checkoutViews?: true; sharedWorktree?: true; + workspacePreparation?: true; }; /** Accept v1 extension fields and enable optional features only when explicitly true. */ @@ -110,6 +113,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.checkoutViews === true && { checkoutViews: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), + ...(frame.workspacePreparation === true && { workspacePreparation: true }), ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), ...(frame.pullRequestEvidence === true && { pullRequestEvidence: true }), @@ -137,11 +141,43 @@ export type ResultFrame = { code?: "host-gone"; }; +export type LaunchProgress = + | { phase: "workspace" | "dependencies" | "ready" } + | { phase: "dependencies"; status: "done" | "failed" }; + +export type LaunchProgressFrame = { + type: "launch_progress"; + id: string; + progress: LaunchProgress; +}; + +export function parseLaunchProgress( + value: unknown +): LaunchProgressFrame | null { + if ( + !isRecord(value) || + value.type !== "launch_progress" || + !isOpaqueId(value.id) || + !isRecord(value.progress) + ) + return null; + const { phase, status } = value.progress; + if (phase === "dependencies" && (status === "done" || status === "failed")) + return { type: value.type, id: value.id, progress: { phase, status } }; + if ( + status === undefined && + (phase === "workspace" || phase === "dependencies" || phase === "ready") + ) + return { type: value.type, id: value.id, progress: { phase } }; + return null; +} + export type RunnerFrame = | ReadyFrame | { type: "health"; sample: RunnerHealth } | { type: "engine_inventory"; entries: EngineInventoryEntry[] } | ResultFrame + | LaunchProgressFrame | ChannelFrame; export type Frame = ServiceFrame | RunnerFrame; @@ -219,6 +255,7 @@ function isRemoteLaunch(value: unknown): value is RemoteLaunch { (value.effort === undefined || isNullableString(value.effort)) && (value.personaContext === undefined || isNullableString(value.personaContext)) && + (value.prepareWorkspace === undefined || value.prepareWorkspace === true) && (value.mcp === undefined || isServiceMcp(value.mcp)) && (value.useWorktreeOf === undefined || (isOpaqueId(value.useWorktreeOf) && From 1e4ba5b291534cbdfc1f320b29b91fd20cde3e97 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 15:38:53 -0700 Subject: [PATCH 130/642] Bind native worktree intent before creating the session row --- .agents/owners.json | 1 + apps/server/src/agents/local-runner.ts | 5 ++ apps/server/src/agents/manager.ts | 4 ++ apps/server/src/agents/workspace.ts | 77 ++++++++++++++++------- apps/server/test/db/agent-manager.test.ts | 73 ++++++++++++++++++++- 5 files changed, 135 insertions(+), 25 deletions(-) diff --git a/.agents/owners.json b/.agents/owners.json index e9845a4c3..1f31c8723 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -58,6 +58,7 @@ "apps/server/test/lifecycle-routes.test.ts", "apps/server/test/*worktree*", "apps/server/test/workspace-target.test.ts", + "apps/server/test/local-workspace-preparation.test.ts", "apps/server/test/tasks-service.test.ts", "apps/server/test/*acp*", "e2e/worktree.spec.ts", diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index 339b6ba3f..0a04c248b 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -256,6 +256,11 @@ export function createLocalRunner( resolveWorkspace, resolveProjectRoot, inferRepositoryUrl, + bindWorkspace: ( + agentId: string, + directory: Parameters[1], + request: Parameters[2] + ) => workspace.bind(stateDir(agentId), directory, request), prepareWorkspace: ( agentId: string, directory: Parameters[1], diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 08abdbbb0..fe2963d21 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1610,6 +1610,10 @@ export class AgentManager { input, directory?.cwd ?? input.cwd ); + // Restart can see the row before persona and workspace preparation run. + // Persist the native request first so restart never treats it as a direct launch. + if (directory && p.worktree) + await this.localRunner.bindWorkspace(p.id, directory, p.worktree); await this.insertAgentRecord( p, input, diff --git a/apps/server/src/agents/workspace.ts b/apps/server/src/agents/workspace.ts index 01b06ffbb..5e8bc1d61 100644 --- a/apps/server/src/agents/workspace.ts +++ b/apps/server/src/agents/workspace.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import { mkdir, + open, readFile, realpath, rename, @@ -92,8 +93,15 @@ async function writeReceipt(dir: string, receipt: Receipt) { await writeFile(temporary, JSON.stringify(receipt), { mode: 0o600, flag: "wx", + flush: true, }); await rename(temporary, path.join(dir, "workspace-preparation")); + const directory = await open(dir, "r"); + try { + await directory.sync(); + } finally { + await directory.close(); + } } finally { await rm(temporary, { force: true }); } @@ -220,7 +228,49 @@ export function createWorkspacePreparation(logger: FastifyBaseLogger) { }; } + async function bind( + dir: string, + directory: LaunchDirectory, + request: WorktreeRequest + ) { + const source = directory.canonicalPath; + const receipt = await readReceipt(dir); + if (receipt) { + if ( + receipt.source !== source || + JSON.stringify(receipt.request) !== JSON.stringify(request) + ) + throw new GitWorktreeError( + "This launch already owns a different worktree.", + 409 + ); + return receipt; + } + await mkdir(dir, { recursive: true, mode: 0o700 }); + const intent = { + cwd: directory.cwd, + source, + sourceIdentity: await directoryIdentity(source), + request, + }; + await writeReceipt(dir, intent); + const parent = await open(path.dirname(dir), "r"); + try { + await parent.sync(); + } finally { + await parent.close(); + } + return intent; + } + return { + async bind( + dir: string, + directory: LaunchDirectory, + request: WorktreeRequest + ) { + await serialize(dir, () => bind(dir, directory, request)); + }, async prepare( dir: string, directory: LaunchDirectory, @@ -237,30 +287,9 @@ export function createWorkspacePreparation(logger: FastifyBaseLogger) { git: directory.git, }; } - return serialize(dir, async () => { - const source = directory.canonicalPath; - const receipt = await readReceipt(dir); - if (receipt) { - if ( - receipt.source !== source || - JSON.stringify(receipt.request) !== JSON.stringify(request) - ) - throw new GitWorktreeError( - "This launch already owns a different worktree.", - 409 - ); - return finish(dir, receipt, progress); - } - await mkdir(dir, { recursive: true, mode: 0o700 }); - const intent = { - cwd: directory.cwd, - source, - sourceIdentity: await directoryIdentity(source), - request, - }; - await writeReceipt(dir, intent); - return finish(dir, intent, progress); - }); + return serialize(dir, async () => + finish(dir, await bind(dir, directory, request), progress) + ); }, resume(dir: string, progress: Progress) { return serialize(dir, async () => { diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index a67f26f4f..8fc0701e7 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -1,7 +1,7 @@ import { personaCatalog } from "../../src/personas/catalog.js"; import * as gitContext from "../../src/shared/git/git-context.js"; import { upsertPersona } from "../../src/personas/authoring.js"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -1363,6 +1363,77 @@ describe("AgentManager", () => { } }); + it("restarts a native worktree launch after persona setup fails before checkout preparation", async () => { + const root = await mkdtemp( + path.join(os.tmpdir(), "dispatch-worktree-intent-") + ); + const cwd = path.join(root, "source"); + const worktreePath = path.join(root, "worktree"); + const config = { + ...testConfig, + agentStateRoot: path.join(root, "hosts"), + filesRoot: path.join(root, "files"), + }; + const firstRuntime = createSpyRuntime(); + const firstManager = new AgentManager(pool, noopLogger, config, { + runtime: firstRuntime, + }); + const catalog = vi + .spyOn(personaCatalog, "get") + .mockRejectedValueOnce(new Error("Persona lookup interrupted")); + try { + await Promise.all([mkdir(cwd), mkdir(worktreePath)]); + const agent = await firstManager.createAgent( + { + cwd, + persona: "builder", + useWorktree: true, + baseBranch: "develop", + worktreeBranch: "session/retry", + }, + { detachLaunch: true } + ); + await vi.waitFor(async () => + expect(await firstManager.getAgent(agent.id)).toMatchObject({ + status: "error", + lastError: "Persona lookup interrupted", + cwd, + worktreePath: null, + }) + ); + expect(createGitWorktree).not.toHaveBeenCalled(); + expect(firstRuntime.launch).not.toHaveBeenCalled(); + + vi.mocked(createGitWorktree).mockResolvedValueOnce({ + worktreePath, + branchName: "session/retry", + } as never); + const retryRuntime = createSpyRuntime(); + const restartedManager = new AgentManager(pool, noopLogger, config, { + runtime: retryRuntime, + }); + expect(await restartedManager.startAgent(agent.id)).toMatchObject({ + status: "running", + cwd: worktreePath, + worktreePath, + worktreeBranch: "session/retry", + }); + expect(createGitWorktree).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + cwd, + baseBranch: "develop", + branchName: "session/retry", + }) + ); + expect(retryRuntime.launch).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ cwd: worktreePath }) + ); + } finally { + catalog.mockRestore(); + await rm(root, { recursive: true, force: true }); + } + }); + it.each([false, true])( "returns a creating row while a detached persona lookup is pending (missing=%s)", async (missing) => { From b6e80eb404a1264b5b872ae79788167450ee7ea0 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 15:53:38 -0700 Subject: [PATCH 131/642] Bind runner workspace moves and independent launches --- apps/server/src/agents/checkout-observers.ts | 4 +- apps/server/src/agents/checkout-runner.ts | 9 +- apps/server/src/agents/manager.ts | 218 ++++++++++++++---- apps/server/src/agents/remote/runner.ts | 13 ++ apps/server/src/agents/remote/service.ts | 31 ++- .../src/agents/remote/session-supervisor.ts | 211 +++++++++++++++-- apps/server/src/agents/workspace-target.ts | 13 +- apps/server/src/jobs/service.ts | 45 ++-- apps/server/src/jobs/store.ts | 8 +- apps/server/src/personas/resolve.ts | 8 +- .../src/routes/agents/workspace-routes.ts | 12 +- apps/server/src/routes/mcp.ts | 7 + apps/server/src/server.ts | 2 + apps/server/src/server/mcp-handlers.ts | 54 +++-- .../src/shared/mcp/agent-launch-tools.ts | 2 +- .../src/shared/mcp/agent-lifecycle-tools.ts | 6 +- apps/server/src/templates/service.ts | 22 +- apps/server/src/templates/store.ts | 8 +- apps/server/test/db/agent-manager.test.ts | 162 +++++++++++++ apps/server/test/mcp-handlers.test.ts | 45 ++++ .../test/remote-runner-enrollment.test.ts | 18 +- .../test/remote-runner-supervisor.test.ts | 84 +++++++ .../test/runner-protocol-consumer.test.ts | 81 +++++++ apps/server/test/tasks-service.test.ts | 36 +++ docs/design/runner-parity-rollout.md | 10 + e2e/remote-runner/acceptance.spec.ts | 82 ++++++- packages/runner-protocol/README.md | 26 +++ packages/runner-protocol/src/checkout.ts | 16 ++ packages/runner-protocol/src/connection.ts | 1 + packages/runner-protocol/src/execution.ts | 26 +++ 30 files changed, 1135 insertions(+), 125 deletions(-) diff --git a/apps/server/src/agents/checkout-observers.ts b/apps/server/src/agents/checkout-observers.ts index f3614fead..a4826ed2e 100644 --- a/apps/server/src/agents/checkout-observers.ts +++ b/apps/server/src/agents/checkout-observers.ts @@ -47,7 +47,9 @@ export class CheckoutObservers { observe(agent: WorkspaceTargetAgent & { id: string }) { const id = agent.id; const placement = agent.cwd && remotePlacement(agent.cwd); - const key = placement ? agent.cwd : agentWorkspaceDir(agent); + const key = placement + ? JSON.stringify([agent.cwd, agent.workspacePath]) + : agentWorkspaceDir(agent); if (!key) return; const expires = Date.now() + 75_000; const prev = this.agents.get(id); diff --git a/apps/server/src/agents/checkout-runner.ts b/apps/server/src/agents/checkout-runner.ts index 9b38c562f..28ef1ad94 100644 --- a/apps/server/src/agents/checkout-runner.ts +++ b/apps/server/src/agents/checkout-runner.ts @@ -120,7 +120,14 @@ export async function readAgentView( const { value } = await remote.requestSession(placement, { kind: "viewCheckout", agentId: agent.id, - query: view, + query: + "baseBranch" in view + ? { + ...view, + baseBranch: + view.baseBranch ?? agent.workspaceBaseBranch ?? null, + } + : view, }); return decodeCheckoutView(value, view); } catch (error) { diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index fe2963d21..0f8700922 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -77,10 +77,14 @@ import type { PromptImage, } from "./acp/prompt-source.js"; import { type EngineBins, isAcpEngine } from "./acp/engine-spec.js"; +import { agentWorkspaceDir } from "./workspace-target.js"; import { inspectAgentCheckout, reviewerWorkspace } from "./checkout-runner.js"; import { RemoteEventInbox } from "./remote/event-inbox.js"; import { MANAGED_WORKSPACE, + isCheckoutPath, + isSessionCheckout, + validBranch, remotePlacement, type RunnerRepository, type LaunchProgress, @@ -1007,13 +1011,20 @@ export class AgentManager { const attached: string[] = []; const lost: string[] = []; const pending: string[] = []; - const result = await this.pool.query<{ id: string; cwd: string }>( - `SELECT id, COALESCE(workspace_path, cwd) AS cwd FROM agents + const result = await this.pool.query<{ + id: string; + cwd: string; + workspacePath: string | null; + }>( + `SELECT id, cwd, workspace_path AS "workspacePath" FROM agents WHERE status IN ('running', 'creating') AND deleted_at IS NULL ORDER BY created_at` ); for (const row of result.rows) { - this.streamRecorder.setCwd(row.id, row.cwd); + this.streamRecorder.setCwd( + row.id, + remotePlacement(row.cwd) ? row.cwd : (row.workspacePath ?? row.cwd) + ); if (await this.runtime.attach(row.id)) { attached.push(row.id); continue; @@ -1330,35 +1341,86 @@ export class AgentManager { /** * Point the agent's workspace at the directory it now works in, or back at - * its launch worktree/cwd with `path: null`. Everything that reads its - * files follows the workspace; the engine's cwd (resume) and the managed - * worktree (archive cleanup) are left as they were. + * its launch worktree/cwd with `path: null`. A remote runner confirms and + * journals the selection for checkout reads and future launches. Archive + * ownership remains tied to the original binding. */ async setWorkspace( id: string, input: { path: string | null; baseBranch?: string | null } ): Promise { - const agent = await this.getRequiredAgent(id); - if (remotePlacement(agent.cwd)) - throw new AgentError("Runner workspace is fixed for this agent.", 409); - const resolved = await this.localRunner.resolveWorkspace(agent, input); + return this.serializeLifecycle(id, async () => { + const agent = await this.getRequiredAgent(id); + const placement = remotePlacement(agent.cwd); + const resolved = placement + ? await this.selectRunnerCheckout(agent, input) + : await this.localRunner.resolveWorkspace(agent, input); + await this.pool.query( + `UPDATE agents + SET workspace_path = $2, workspace_base_branch = $3, updated_at = NOW() + WHERE id = $1`, + [id, resolved.path, resolved.baseBranch] + ); + await this.populateGitContext(id); + this.diffStatsRefresher?.clear(id); + void this.diffStatsRefresher?.signal(id); - await this.pool.query( - `UPDATE agents - SET workspace_path = $2, workspace_base_branch = $3, updated_at = NOW() - WHERE id = $1`, - [id, resolved.path, resolved.baseBranch] - ); - await this.populateGitContext(id); - this.diffStatsRefresher?.clear(id); - void this.diffStatsRefresher?.signal(id); + const updated = await this.getRequiredAgent(id); + this.streamRecorder.setCwd(id, agentWorkspaceDir(updated) ?? updated.cwd); + this.eventBus.publish(updated); + return updated; + }); + } - // Read back rather than trusting `resolved`: an overlapping call may - // have landed after this one's UPDATE, and the recorder follows the row. - const updated = await this.getRequiredAgent(id); - this.streamRecorder.setCwd(id, updated.workspacePath ?? updated.cwd); - this.eventBus.publish(updated); - return updated; + private async runnerCheckout( + agent: AgentRecord, + operation: { kind: "describe" } | { kind: "select"; path: string | null } + ) { + const placement = remotePlacement(agent.cwd); + if (!placement || !this.remote) + throw new AgentError("The session runner is unavailable.", 409); + let value: unknown; + try { + ({ value } = await this.remote.requestSession(placement, { + agentId: agent.id, + kind: "sessionCheckout", + operation, + })); + } catch (error) { + throw new AgentError( + errorMessage(error), + error instanceof RunnerRevoked ? 403 : 409 + ); + } + let result: unknown; + try { + if (typeof value === "string") result = JSON.parse(value); + } catch { + // Treat malformed acknowledgements like missing results. + } + if (!isSessionCheckout(result)) + throw new AgentError("Invalid runner checkout response.", 502); + return result; + } + + private async selectRunnerCheckout( + agent: AgentRecord, + input: { path: string | null; baseBranch?: string | null } + ) { + const path = input.path?.trim() || null; + const baseBranch = input.baseBranch?.trim() || null; + if (path !== null && !isCheckoutPath(path)) + throw new AgentError( + "Workspace path must be absolute on the bound runner.", + 400 + ); + if (baseBranch !== null && !validBranch(baseBranch)) + throw new AgentError("Invalid base branch.", 400); + const selected = await this.runnerCheckout(agent, { kind: "select", path }); + return { + path: selected.moved || (path && baseBranch) ? selected.path : null, + baseBranch: path ? baseBranch : null, + }; } viewCheckout( @@ -1374,8 +1436,18 @@ export class AgentManager { agent: AgentRecord, query: CheckoutQuery ): Promise { + if ( + query.kind === "changes" && + query.baseBranch === null && + agent.workspaceBaseBranch + ) + query = { ...query, baseBranch: agent.workspaceBaseBranch }; + const placement = remotePlacement(agent.cwd); if ( agent.runnerManaged && + placement && + !this.remote?.supportsSessionCheckout?.(placement) && + !agent.workspacePath && query.kind === "changes" && query.baseBranch === null ) { @@ -1407,13 +1479,31 @@ export class AgentManager { detachLaunch?: boolean; /** Trusted shared-checkout launch, never accepted from an HTTP launch payload. */ useWorktreeOf?: string; + /** Trusted MCP launch with its own checkout on the caller's runner. */ + independentCheckoutOf?: string; taskPersonaBody?: string; /** Commit owner state before the engine can discover tools or run a turn. */ beforeLaunch?: (agentId: string) => Promise; } = {} ): Promise { input = { ...input }; - const { useWorktreeOf } = options; + const { useWorktreeOf, independentCheckoutOf } = options; + const independentSource = independentCheckoutOf + ? await this.getAgent(independentCheckoutOf) + : null; + if ( + independentCheckoutOf && + (!independentSource || + !remotePlacement(independentSource.cwd) || + input.cwd !== independentSource.cwd || + input.launchedByAgentId !== independentSource.id || + (input.parentAgentId && input.parentAgentId !== independentSource.id) || + (input.fullAccess && !independentSource.fullAccess) || + (input.persona && !options.taskPersonaBody) || + useWorktreeOf) + ) + throw new AgentError("Invalid independent runner checkout binding.", 400); + if (independentSource) input.projectId = independentSource.projectId; if (useWorktreeOf !== undefined) { const owner = await this.getAgent(useWorktreeOf); if ( @@ -1478,13 +1568,18 @@ export class AgentManager { ); } if ( - (!useWorktreeOf && - (input.parentAgentId || (input.projectId && !managed))) || - input.templateId || - (input.persona && !useWorktreeOf) || - input.jobRunId || - input.initialFiles?.length || - input.useWorktree + (!useWorktreeOf && !independentSource && input.parentAgentId) || + (!managed && + (input.projectId || + input.templateId || + input.jobRunId || + input.useWorktree)) || + (input.persona && + !useWorktreeOf && + !options.taskPersonaBody && + !input.templateId && + !input.jobRunId) || + input.initialFiles?.length ) { throw new AgentError( "Runner launches require a standalone agent and runner-managed storage.", @@ -1496,8 +1591,9 @@ export class AgentManager { "Update the runner to launch an agent in an existing checkout.", 409 ); - input.useWorktree = false; + input.useWorktree = !repository && input.useWorktree === true; } + let projectRoot: string | undefined; if (input.templateId) { const template = ( await this.pool.query("SELECT project_id FROM templates WHERE id=$1", [ @@ -1528,6 +1624,7 @@ export class AgentManager { ]) ).rows[0]; if (!project) throw new AgentError("Project not found.", 404); + projectRoot = project.repo_root; if (repository && !repository.url) { try { repository.url = await this.localRunner.inferRepositoryUrl( @@ -1538,8 +1635,8 @@ export class AgentManager { } } - // A child can use its parent's worktree while retaining explicit membership. - if (!placement && !input.parentAgentId) { + // Project membership only supplies a location when none was selected. + if (!placement && !input.parentAgentId && !input.cwd) { input.cwd = project.repo_root; } } @@ -1581,11 +1678,27 @@ export class AgentManager { if (matches.length === 1) input.projectId = matches[0]!.id; } const taskPersona = Boolean(input.persona && input.role !== "review"); + const derivedRepositoryUrl = + placement && input.useWorktree + ? independentSource + ? (await this.runnerCheckout(independentSource, { kind: "describe" })) + .origin + : projectRoot + ? await this.localRunner + .inferRepositoryUrl(projectRoot) + .catch(() => null) + : null + : undefined; + if (derivedRepositoryUrl === null) + throw new AgentError( + "An independent runner worktree needs a repository with an HTTPS origin.", + 400 + ); const taskPersonaBody = async () => options.taskPersonaBody ?? ( await resolveLaunchPersona( - input.cwd, + placement ? (projectRoot ?? null) : input.cwd, input.persona!, "task", input.personaSource ?? "catalog" @@ -1598,7 +1711,7 @@ export class AgentManager { agentArgs: [...(input.agentArgs ?? []), PERSONA_CONTEXT_ARG, body], }; } - const runnerRepository = repository?.url + let runnerRepository = repository?.url ? { url: repository.url, checkout: repository.checkout } : null; if (repository && !runnerRepository) @@ -1610,6 +1723,26 @@ export class AgentManager { input, directory?.cwd ?? input.cwd ); + if (derivedRepositoryUrl && p.worktree) { + const { branch, baseBranch } = p.worktree; + runnerRepository = { + url: derivedRepositoryUrl, + checkout: + input.createNewBranch === false && input.worktreeBranch + ? { kind: "branch", branch } + : { + kind: "new", + branch, + ...(baseBranch ? { base: baseBranch } : {}), + }, + }; + try { + parseRepository(runnerRepository); + } catch (error) { + throw new AgentError(errorMessage(error), 400); + } + } + await mkdir(p.filesDir, { recursive: true }); // Restart can see the row before persona and workspace preparation run. // Persist the native request first so restart never treats it as a direct launch. if (directory && p.worktree) @@ -1875,8 +2008,6 @@ export class AgentManager { : (input.agentArgs ?? []); const name = input.name?.trim() || `agent-${id.slice(-6)}`; const filesDir = path.join(this.config.filesRoot, id); - await mkdir(filesDir, { recursive: true }); - const useWorktree = input.useWorktree !== false; const createNewBranch = input.createNewBranch ?? true; @@ -2260,7 +2391,7 @@ export class AgentManager { "launching agent on engine CLI" ); } - this.streamRecorder.setCwd(agent.id, agent.workspacePath ?? agent.cwd); + this.streamRecorder.setCwd(agent.id, agentWorkspaceDir(agent) ?? agent.cwd); // Rows a previous host left open (a crash mid-turn) settle first, so the // feed never shows a turn that can no longer finish. await this.streamRecorder.reconcile(agent.id); @@ -2268,7 +2399,10 @@ export class AgentManager { ? this.remote?.originFor(placement) : undefined; const mcpUrl = placement - ? remoteMcpOrigin && `${remoteMcpOrigin}/api/mcp/${agent.id}` + ? remoteMcpOrigin && + (opts.jobRunId + ? `${remoteMcpOrigin}/api/mcp/jobs/${opts.jobRunId}/${agent.id}` + : `${remoteMcpOrigin}/api/mcp/${agent.id}`) : dispatchMcpUrl(this.config, agent.id, opts.jobRunId); if ( placement?.workspace === MANAGED_WORKSPACE && diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 967d9c0e7..1f9bce505 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -447,6 +447,18 @@ export async function runRemoteRunner(filename: string) { } if (socket.destroyed) return; switch (command.kind) { + case "sessionCheckout": + result( + JSON.stringify( + await supervisor.sessionCheckout( + agentId, + workspace, + command.operation, + target?.cwd + ) + ) + ); + break; case "watchCheckout": { const cwd = await supervisor.checkoutDirectory( agentId, @@ -648,6 +660,7 @@ export async function runRemoteRunner(filename: string) { pullRequestEvidence: true, checkoutInspection: true, workspacePreparation: true, + sessionCheckout: true, checkoutViews: true, sharedWorktree: true, }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 74081352a..3b82fd2e8 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -161,6 +161,7 @@ type Peer = { pullRequestWatch: boolean; pullRequestEvidence: boolean; checkoutInspection: boolean; + sessionCheckout: boolean; checkoutViews: boolean; sharedWorktree: boolean; workspacePreparation: boolean; @@ -255,6 +256,7 @@ export function configuredRunner(input?: { apiPort: number; apiTls: boolean; validAgentToken?: (token: string, agentId: string) => boolean; + validJobToken?: (token: string, runId: string, agentId: string) => boolean; }) { const filename = process.env.DISPATCH_REMOTE_SERVICE_CONFIG; const legacy: LegacyConfig | undefined = filename @@ -287,6 +289,7 @@ export function configuredRunner(input?: { port: input.apiPort, tls: input.apiTls, validAgentToken: input.validAgentToken, + validJobToken: input.validJobToken, } ) : undefined; @@ -325,8 +328,13 @@ export class RemoteRunnerService { host: string; port: number; tls: boolean; - /** Accept only agent-scoped MCP credentials through the proxy. */ + /** Accept only session-scoped MCP credentials through the proxy. */ validAgentToken?: (token: string, agentId: string) => boolean; + validJobToken?: ( + token: string, + runId: string, + agentId: string + ) => boolean; } ) { if (legacy) { @@ -681,6 +689,7 @@ export class RemoteRunnerService { pullRequestEvidence: ready.pullRequestEvidence === true, githubManagement: ready.githubManagement === true, checkoutViews: ready.checkoutViews === true, + sessionCheckout: ready.sessionCheckout === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, workspacePreparation: ready.workspacePreparation === true, @@ -819,7 +828,7 @@ export class RemoteRunnerService { } /** - * Forward bearer-authenticated agent MCP calls, `/ping`, and the two + * Forward bearer-authenticated session MCP calls, `/ping`, and the two * runner-initiated ("connect") bootstrap calls to the local API. The * bootstrap calls carry no Dispatch credentials — none exist yet — so * they are allow-listed by path and method alone, exactly like `/ping`; @@ -840,14 +849,17 @@ export class RemoteRunnerService { /^\/api\/(?:v1\/)?runners\/connect\/conn_[A-Za-z0-9_-]{24}$/.test(url) && request.method === "GET"; const agentId = /^\/api\/mcp\/(agt_[a-z0-9]+)$/.exec(url)?.[1]; + const job = /^\/api\/mcp\/jobs\/([0-9a-f-]{36})\/(agt_[a-z0-9]+)$/.exec( + url + ); const token = /^Bearer (\S+)$/.exec( request.headers.authorization ?? "" )?.[1]; const mcp = Boolean( - agentId && token && ["GET", "POST", "DELETE"].includes(request.method ?? "") && - target?.validAgentToken?.(token, agentId) + ((agentId && target?.validAgentToken?.(token, agentId)) || + (job && target?.validJobToken?.(token, job[1]!, job[2]!))) ); const allowed = ping || mcp || connectCreate || connectPoll; if (!allowed || !target) { @@ -1472,6 +1484,13 @@ export class RemoteRunnerService { ); } + supportsSessionCheckout(placement: Placement) { + return ( + this.available(placement) && + this.peers.get(placement.runner)?.sessionCheckout === true + ); + } + supportsSharedWorktree(placement: Placement) { return ( this.available(placement) && @@ -1519,6 +1538,10 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update this runner to open Files and Changes." ); + if (command.kind === "sessionCheckout" && !peer.sessionCheckout) + throw new RunnerCapabilityUnavailable( + "Update the runner to select or describe a session checkout." + ); if (command.kind === "inspectCheckout" && !peer.checkoutInspection) throw new RunnerCapabilityUnavailable( "Update the runner to inspect a session checkout." diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 05e159959..726fd50b3 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -20,11 +20,14 @@ import { hostFile, type HostLaunch } from "../acp/host-protocol.js"; import { MANAGED_WORKSPACE, isOpaqueId, + isCheckoutPath, + type SessionCheckout, + type SessionOperation, type Command, type LaunchProgress, type RunnerRepository, } from "./protocol.js"; -import { parseRepository } from "./repository.js"; +import { parseRepository, repositoryUrl } from "./repository.js"; import { createSessionProcesses, parseSessionIdentity, @@ -50,6 +53,11 @@ type LaunchCommand = Extract & { launch: { useWorktreeOf?: unknown }; }; +type CheckoutOperation = Extract< + SessionOperation, + { kind: "sessionCheckout" } +>["operation"]; + type SupervisorOptions = { state: string; uid: number; @@ -77,6 +85,10 @@ function checkoutOwner(binding: string | null) { return key; } +function containsDirectory(root: string, dir: string) { + return dir === root || dir.startsWith(root === "/" ? root : root + "/"); +} + const logTailBytes = 2 * 1024; async function readLogTail(file: string) { @@ -211,6 +223,10 @@ export async function createSessionSupervisor( const dependenciesFile = (key: string) => path.join(bindings, `${key}.dependencies`); const cwdFile = (key: string) => path.join(bindings, `${key}.cwd`); + const selectedFile = (key: string) => + path.join(bindings, `${key}.selected-cwd`); + const borrowedFile = (key: string) => + path.join(bindings, `${key}.borrowed-cwd`); const markerFile = (key: string) => path.join(bindings, `${key}.owner`); const identityFile = (key: string) => path.join(bindings, `${key}.host`); function managedTarget(workspace: string) { @@ -315,6 +331,108 @@ export async function createSessionSupervisor( return checkout; } + async function initialDirectory( + key: string, + workspace: string, + configuredCwd?: string + ) { + const binding = await readBinding(key); + if (!matchesWorkspace(binding, workspace)) + throw new Error("Agent is not bound to this workspace"); + const managed = managedTarget(workspace); + const owner = checkoutOwner(binding); + if (managed && (await readOptional(retireFile(key))) !== null) + throw new Error("This runner session has been archived."); + if (owner && (await readBinding(owner)) !== managedBinding) + throw new Error("The author does not own a checkout on this runner."); + const launch = managed + ? await managedDirectory(owner ?? key) + : await configuredDirectory(key, configuredCwd); + const borrowed = await readOptional(borrowedFile(key)); + return borrowed && borrowed !== launch + ? authorizedDirectory(borrowed, launch, managed, owner ?? key) + : launch; + } + + async function authorizedDirectory( + requested: string, + launch: string, + managed: boolean, + owner: string + ) { + if (!isCheckoutPath(requested)) + throw new Error("Invalid checkout directory."); + let dir: string; + try { + dir = (await asWorkload("realpath", ["-e", "--", requested])).replace( + /\n$/, + "" + ); + if (!isCheckoutPath(dir)) throw new Error("Invalid checkout directory."); + await asWorkload("test", ["-d", dir]); + await asWorkload("test", ["-x", dir]); + } catch { + throw new Error( + "The checkout directory is unavailable to the runner workload." + ); + } + // Configured workspaces are allowlisted. Managed sessions may select + // workload directories, but another session's storage needs a binding. + const allowed = managed + ? !containsDirectory(storage, dir) || + containsDirectory(path.join(sessions, owner), dir) + : containsDirectory(launch, dir); + if (!allowed) + throw new Error("Directory is outside the bound runner checkout."); + await checkedDirectory(dir); + return dir; + } + + async function selectedDirectory( + key: string, + workspace: string, + initial: string + ) { + const selected = await readOptional(selectedFile(key)); + if (!selected) return initial; + return authorizedDirectory( + selected, + managedTarget(workspace) ? initial : await configuredDirectory(key), + managedTarget(workspace), + checkoutOwner(await readBinding(key)) ?? key + ); + } + + async function describeCheckout( + dir: string, + initial: string + ): Promise { + const configured = await asWorkload( + "git", + [ + "-C", + dir, + "config", + "--local", + "--no-includes", + "--null", + "--get-all", + "remote.origin.url", + ], + { git: true } + ).catch(() => ""); + let origin: string | null = null; + const [url, end, ...extra] = configured.split("\0"); + if (url && end === "" && extra.length === 0) { + try { + origin = repositoryUrl(url, true); + } catch { + // Only return a recognized, credential-free repository URL. + } + } + return { path: dir, moved: dir !== initial, origin }; + } + async function hasBorrowers(key: string) { for (const entry of await readdir(bindings)) { if ( @@ -457,6 +575,11 @@ export async function createSessionSupervisor( await checkedDirectory(cwd); await writePrivateState(cwdFile(key), cwd); } + cwd = await selectedDirectory( + key, + workspace, + await initialDirectory(key, workspace, managed ? undefined : cwd) + ); progress?.({ phase: "ready" }); const dir = path.join(hostRoot, key); const files = path.join(dir, "files"); @@ -596,6 +719,13 @@ export async function createSessionSupervisor( ); if (cwd === undefined) throw new Error("Guest workspace is unavailable"); + if (!(await readOptional(borrowedFile(key)))) { + const initial = await initialDirectory(author, workspace, cwd); + await writePrivateState( + borrowedFile(key), + await selectedDirectory(author, workspace, initial) + ); + } return launch( command, await configuredDirectory(author, cwd), @@ -615,6 +745,22 @@ export async function createSessionSupervisor( (await readOptional(retireFile(author))) !== null) ) throw new Error("The author does not own a checkout on this runner."); + if ( + (await readBinding(key)) === null && + !(await readOptional(borrowedFile(key))) + ) { + if ((await readBinding(owner)) !== managedBinding) + throw new Error( + "The author does not own a checkout on this runner." + ); + if ((await readOptional(retireFile(owner))) !== null) + throw new Error("The author checkout has been archived."); + const initial = await initialDirectory(author, workspace); + await writePrivateState( + borrowedFile(key), + await selectedDirectory(author, workspace, initial) + ); + } return launch(command, cwd, key, owner, progress); }); }, @@ -624,23 +770,58 @@ export async function createSessionSupervisor( // Only the runner's configured path may supply a missing legacy cwd. configuredCwd?: string ): Promise { + const key = runnerStorageKey(agentId); + return serialize(key, async () => + selectedDirectory( + key, + workspace, + await initialDirectory(key, workspace, configuredCwd) + ) + ); + }, + sessionCheckout( + agentId: string, + workspace: string, + operation: CheckoutOperation, + configuredCwd?: string + ): Promise { const key = runnerStorageKey(agentId); return serialize(key, async () => { - const managed = managedTarget(workspace); - const binding = await readBinding(key); - if (!matchesWorkspace(binding, workspace)) - throw new Error("Agent is not bound to this workspace"); - if (managed) { - if ((await readOptional(retireFile(key))) !== null) - throw new Error("This runner session has been archived."); - const owner = checkoutOwner(binding); - if (owner && (await readBinding(owner)) !== managedBinding) - throw new Error( - "The author does not own a checkout on this runner." + const initial = await initialDirectory(key, workspace, configuredCwd); + if (operation.kind === "describe") + return describeCheckout( + await selectedDirectory(key, workspace, initial), + initial + ); + let dir = initial; + if (operation.path !== null) { + const managed = managedTarget(workspace); + const owner = checkoutOwner(await readBinding(key)) ?? key; + const launch = managed + ? initial + : await configuredDirectory(key, configuredCwd); + dir = await authorizedDirectory( + operation.path, + launch, + managed, + owner + ); + const root = await asWorkload( + "git", + ["-C", dir, "rev-parse", "--show-toplevel"], + { git: true } + ).catch(() => ""); + if (root) + dir = await authorizedDirectory( + root.trimEnd(), + launch, + managed, + owner ); - return managedDirectory(owner ?? key); } - return configuredDirectory(key, configuredCwd); + const result = await describeCheckout(dir, initial); + await writePrivateState(selectedFile(key), result.moved ? dir : ""); + return result; }); }, async alive(agentId: string, workspace: string) { @@ -738,6 +919,8 @@ export async function createSessionSupervisor( await rm(cwdFile(key), { force: true }); } await removeGuestDirectory(dir); + await rm(selectedFile(key), { force: true }); + await rm(borrowedFile(key), { force: true }); await rm(path.join(bindings, key), { force: true }); if (managed) await syncBindings(); }); diff --git a/apps/server/src/agents/workspace-target.ts b/apps/server/src/agents/workspace-target.ts index b6681562c..dacd18176 100644 --- a/apps/server/src/agents/workspace-target.ts +++ b/apps/server/src/agents/workspace-target.ts @@ -1,4 +1,4 @@ -import { remotePlacement } from "./remote/protocol.js"; +import { remotePlacement, workspaceLocator } from "./remote/protocol.js"; import { realpath, stat } from "node:fs/promises"; import path from "node:path"; @@ -20,6 +20,8 @@ const WORKSPACE_PROBE_TIMEOUT_MS = 5_000; * * Deliberately separate from `cwd` (the engine spawns and resumes there) and * `worktreePath` (the worktree Dispatch created and archive may delete). + * For remote sessions, `cwd` is the machine binding and `workspacePath` + * is runner-confirmed display metadata. Checkout operations go to the runner. */ export type WorkspaceTargetAgent = { cwd: string | null; @@ -33,6 +35,15 @@ export type WorkspaceTargetAgent = { } | null; }; +/** Persist a native directory or a runner locator without treating the latter as a path. */ +export function resolveLaunchLocation(directory: string): string { + const placement = remotePlacement(directory); + if (placement) return workspaceLocator(placement); + if (directory.startsWith("runner://")) + throw new AgentError("Invalid runner workspace locator.", 400); + return path.resolve(directory); +} + const DEFAULT_WORKTREE_BASE_BRANCH = "main"; export function agentWorkspaceDir(agent: WorkspaceTargetAgent): string | null { diff --git a/apps/server/src/jobs/service.ts b/apps/server/src/jobs/service.ts index ccd4f1035..3dd175731 100644 --- a/apps/server/src/jobs/service.ts +++ b/apps/server/src/jobs/service.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import { validateAgentEffort } from "../shared/agent-effort.js"; import { ProjectStore } from "../projects/store.js"; import { randomBytes, randomUUID } from "node:crypto"; @@ -522,14 +523,9 @@ export class JobService { const job = await this.store.getJob(run.jobId); if (!job?.continuationEnabled) return; const directory = destinationDirectory ?? run.config.directory; - let repoRoot: string; - try { - repoRoot = await resolveRepoRoot(directory); - } catch { - // Brain is scoped by a stable repository root when possible; plain - // directories are still valid job targets and use their normalized path. - repoRoot = normalizePath(directory); - } + const repoRoot = remotePlacement(directory) + ? directory + : await resolveRepoRoot(directory).catch(() => normalizePath(directory)); const key = continuationBrainKey(job.id); const terminalStatus = run.continuation?.action === "finish" @@ -634,14 +630,19 @@ export class JobService { continuationEnabled: input.continuationEnabled, }); + let projectRoot: string | undefined; if (input.projectId) { const project = await new ProjectStore(this.pool).get(input.projectId); if (!project) throw new Error("Project not found."); - input = { ...input, directory: project.repoRoot }; + projectRoot = project.repoRoot; + if (!remotePlacement(input.directory)) + input = { ...input, directory: project.repoRoot }; } if (input.persona) await resolveLaunchPersona( - input.directory, + remotePlacement(input.directory) + ? (projectRoot ?? null) + : input.directory, input.persona, "task", "catalog" @@ -774,11 +775,13 @@ export class JobService { const name = input.name === undefined ? existing.name : input.name.trim(); if (!name) throw new Error("Job name is required."); const previousDirectory = backingTemplate?.directory ?? existing.directory; - const directory = - projectDirectory ?? - (input.directory === undefined + const requestedDirectory = + input.directory === undefined ? previousDirectory - : normalizeJobDirectory(input.directory)); + : normalizeJobDirectory(input.directory); + const directory = remotePlacement(requestedDirectory) + ? requestedDirectory + : (projectDirectory ?? requestedDirectory); const branchName = normalizeNullableString(input.branchName); const baseBranch = normalizeNullableString(input.baseBranch); if (name !== existing.name || directory !== existing.directory) { @@ -836,7 +839,12 @@ export class JobService { persona && (persona !== previousPersona || directory !== previousDirectory) ) - await resolveLaunchPersona(directory, persona, "task", "catalog"); + await resolveLaunchPersona( + remotePlacement(directory) ? (projectDirectory ?? null) : directory, + persona, + "task", + "catalog" + ); if (input.persona !== undefined) config.persona = input.persona; if (input.agentType !== undefined) config.agentType = input.agentType; if (nextModel !== existing.model || input.model !== undefined) @@ -886,7 +894,7 @@ export class JobService { const templateUpdates: Record = {}; if (input.projectId !== undefined) { templateUpdates.projectId = input.projectId; - if (projectDirectory) templateUpdates.directory = projectDirectory; + if (projectDirectory) templateUpdates.directory = directory; } if (input.persona !== undefined) templateUpdates.persona = input.persona; @@ -1480,5 +1488,8 @@ function normalizeNullableString( function normalizeJobDirectory(directory: string): string { if (!directory.trim()) throw new Error("Job directory is required."); - return normalizePath(resolveTilde(directory.trim())); + const trimmed = directory.trim(); + return remotePlacement(trimmed) + ? trimmed + : normalizePath(resolveTilde(trimmed)); } diff --git a/apps/server/src/jobs/store.ts b/apps/server/src/jobs/store.ts index 99f157651..269850ce8 100644 --- a/apps/server/src/jobs/store.ts +++ b/apps/server/src/jobs/store.ts @@ -1,6 +1,6 @@ import type { Effort } from "@dispatch/shared"; import { randomUUID } from "node:crypto"; -import path from "node:path"; +import { resolveLaunchLocation } from "../agents/workspace-target.js"; import type { Pool } from "pg"; @@ -247,7 +247,7 @@ export class JobStore { `, [ id, - path.resolve(input.directory), + resolveLaunchLocation(input.directory), input.name, input.schedule, input.timeoutMs, @@ -959,7 +959,7 @@ export class JobStore { ): Promise { const result = await this.pool.query( `SELECT ${this.jobColumns()} FROM jobs WHERE directory = $1 AND name = $2`, - [path.resolve(directory), name] + [resolveLaunchLocation(directory), name] ); return result.rows[0] ? mapJob(result.rows[0]) : null; } @@ -1072,7 +1072,7 @@ export class JobStore { input.persona ?? null, input.directory === undefined ? undefined - : path.resolve(input.directory), + : resolveLaunchLocation(input.directory), input.effort !== undefined, input.effort ?? null, ] diff --git a/apps/server/src/personas/resolve.ts b/apps/server/src/personas/resolve.ts index cb716213b..c8338abef 100644 --- a/apps/server/src/personas/resolve.ts +++ b/apps/server/src/personas/resolve.ts @@ -37,18 +37,18 @@ export async function discoverPersonas( } export async function resolveLaunchPersona( - cwd: string, + cwd: string | null, slug: string, type?: "task" | "review", source: "catalog" | "workspace" = "workspace" ): Promise { if (slug.includes("/") || slug.includes("\\") || slug.includes("..")) throw new Error("Invalid persona slug."); - const root = await resolveWorktreeRoot(cwd).catch(() => cwd); + const root = cwd && (await resolveWorktreeRoot(cwd).catch(() => cwd)); // A malformed local override must fail explicitly, not fall back to a remote copy. let persona = - source === "workspace" ? await loadPersonaBySlug(root, slug) : null; - if (!persona) { + root && source === "workspace" ? await loadPersonaBySlug(root, slug) : null; + if (root && !persona) { const catalog = await personaCatalog.get(root, true); persona = catalog.personas.find((p) => p.slug === slug) ?? null; if (!persona && catalog.refreshing) diff --git a/apps/server/src/routes/agents/workspace-routes.ts b/apps/server/src/routes/agents/workspace-routes.ts index 4a1df243b..7f9f2b7b9 100644 --- a/apps/server/src/routes/agents/workspace-routes.ts +++ b/apps/server/src/routes/agents/workspace-routes.ts @@ -27,12 +27,16 @@ export async function registerAgentWorkspaceRoutes( } const agent = await deps.agentManager.getAgent(id); if (!agent) return reply.code(404).send({ error: "Agent not found." }); - const workspace = remotePlacement(agent.cwd) - ? agent.cwd - : agentWorkspaceDir(agent); + const placement = remotePlacement(agent.cwd); + const workspace = placement ? agent.cwd : agentWorkspaceDir(agent); if (!workspace) return reply.code(404).send({ error: "This agent has no workspace." }); - if (query.workspace !== workspace) + // Older clients identify a runner checkout by its binding. Clients that + // use the confirmed effective path still read through the same binding. + if ( + query.workspace !== workspace && + !(placement && query.workspace === agent.workspacePath) + ) return reply .code(409) .send({ error: "Workspace changed. Reopen Files to continue." }); diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index c6c4b20cf..309e229a1 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -210,6 +210,13 @@ export async function registerMcpRoutes( return reply.code(404).send({ error: "Agent not found." }); } + const placement = remotePlacement(agent.cwd); + if (placement && !deps.agentManager.permitsRemoteAgentMcp(placement)) { + return reply + .code(403) + .send({ error: "The runner registration is no longer active." }); + } + const run = await deps.jobService.getActiveRunForAgent(agentId); if (run && run.id !== runId) { return reply diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 6871feba9..52f33ea40 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -231,6 +231,8 @@ const remoteRunner = configuredRunner({ // authToken is resolved at startup; read it per request. validAgentToken: (token, agentId) => validateAgentMcpToken(config.authToken, token, agentId), + validJobToken: (token, runId, agentId) => + validateJobMcpToken(config.authToken, token, runId, agentId), }); const agentManager = new AgentManager(pool, app.log, config, { remote: remoteRunner, diff --git a/apps/server/src/server/mcp-handlers.ts b/apps/server/src/server/mcp-handlers.ts index cfc71a32a..2a230379f 100644 --- a/apps/server/src/server/mcp-handlers.ts +++ b/apps/server/src/server/mcp-handlers.ts @@ -298,7 +298,7 @@ async function handleSetWorkspace( ): Promise { const agent = await deps.agentManager.setWorkspace(agentId, input); return { - workspacePath: agentWorkspaceDir(agent) ?? agent.cwd, + workspacePath: agent.workspacePath ?? agentWorkspaceDir(agent) ?? agent.cwd, moved: agent.workspacePath !== null, repoRoot: agent.gitContext?.repoRoot ?? null, branch: agent.gitContext?.branch ?? null, @@ -362,18 +362,30 @@ async function handleLaunchAgent( throw new Error(`Template ${input.templateId} not found.`); } const parentCwd = agentWorkspaceDir(parent) ?? parent.cwd; - const cwd = input.cwd ?? template?.directory ?? parentCwd; const runnerParent = remotePlacement(parent.cwd); - if (runnerParent && cwd !== parent.cwd) + const templateRunner = template && remotePlacement(template.directory); + if ( + (runnerParent && + ((input.cwd !== undefined && input.cwd !== parent.cwd) || + (templateRunner && template?.directory !== parent.cwd) || + (template?.projectId && template.projectId !== parent.projectId))) || + (!runnerParent && remotePlacement(input.cwd ?? template?.directory ?? "")) + ) { throw new AgentError( - "A runner agent must launch in its own runner workspace.", + "A child launch cannot select a checkout on another runner or outside the caller's project.", 400 ); - const selectedPersona = input.persona - ? runnerParent - ? await resolveRunnerPersona(deps.agentManager, parent, input.persona) - : await resolveLaunchPersona(cwd, input.persona) - : null; + } + const cwd = runnerParent + ? parent.cwd + : (input.cwd ?? template?.directory ?? parentCwd); + const persona = input.persona ?? template?.persona ?? undefined; + const selectedPersona = + input.persona || (runnerParent && persona) + ? runnerParent + ? await resolveRunnerPersona(deps.agentManager, parent, persona!) + : await resolveLaunchPersona(cwd, persona!) + : null; if (selectedPersona && (selectedPersona.type ?? "review") === "review") { if (template) throw new Error( @@ -517,7 +529,12 @@ async function handleLaunchAgent( unknownArgs = rendered.unknownArgs; } - if (template?.projectId && input.cwd && input.cwd !== template.directory) { + if ( + !runnerParent && + template?.projectId && + input.cwd && + input.cwd !== template.directory + ) { throw new Error("Project template directory cannot be overridden."); } @@ -540,16 +557,17 @@ async function handleLaunchAgent( // template instructions or the launch header. launchContext: { prompt: input.prompt }, templateId: input.templateId, - persona: input.persona ?? template?.persona ?? undefined, + persona, personaSource: "workspace", }; - const agent = - child && runnerParent - ? await deps.agentManager.createAgent(launch, { - useWorktreeOf: parent.id, - taskPersonaBody: selectedPersona?.body, - }) - : await deps.agentManager.createAgent(launch); + const agent = runnerParent + ? await deps.agentManager.createAgent(launch, { + ...(child && !useWorktree + ? { useWorktreeOf: parent.id } + : { independentCheckoutOf: parent.id }), + taskPersonaBody: selectedPersona?.body, + }) + : await deps.agentManager.createAgent(launch); deps.publishUiEvent({ type: "agent.upsert", diff --git a/apps/server/src/shared/mcp/agent-launch-tools.ts b/apps/server/src/shared/mcp/agent-launch-tools.ts index 7ae9ba4b9..6dd1de8a6 100644 --- a/apps/server/src/shared/mcp/agent-launch-tools.ts +++ b/apps/server/src/shared/mcp/agent-launch-tools.ts @@ -159,7 +159,7 @@ export function registerAgentLaunchTools( .string() .optional() .describe( - "Working directory for the new agent. Defaults to the template’s directory when supplied, otherwise the parent’s working directory. Project template directories cannot be overridden." + "For native launches, defaults to the template directory or the caller’s workspace. A runner caller stays on its bound runner. Use useWorktree for an independent checkout there." ), child: z .boolean() diff --git a/apps/server/src/shared/mcp/agent-lifecycle-tools.ts b/apps/server/src/shared/mcp/agent-lifecycle-tools.ts index f7984f869..77719d030 100644 --- a/apps/server/src/shared/mcp/agent-lifecycle-tools.ts +++ b/apps/server/src/shared/mcp/agent-lifecycle-tools.ts @@ -100,21 +100,21 @@ export function registerAgentLifecycleTools( "set_workspace", { description: - "Tell Dispatch which directory you are working in when it is no longer the one you launched in — for example a git worktree you created yourself, or a different repo. Dispatch's diff view, branch, repo tools and brain follow it; your shell's working directory does not change. Omit path to return to the launch directory.", + "Tell Dispatch which directory you are working in when it is no longer the one you launched in — for example a git worktree you created yourself, or a different repo. Checkout reads follow your selection. On a remote runner, the next host start also uses the selected directory. Omit path to return to the launch directory.", inputSchema: { path: z .string() .min(1) .optional() .describe( - "Absolute path of the directory you now work in. Inside a git checkout, its root is used." + "Absolute directory on your session’s machine. Inside a git checkout, its root is used." ), baseBranch: z .string() .min(1) .optional() .describe( - "Branch the diff compares against. Defaults to the launch base in the same repo, else the repo's default branch." + "Branch the diff compares against. If omitted, Dispatch uses the selected checkout’s normal comparison base." ), }, }, diff --git a/apps/server/src/templates/service.ts b/apps/server/src/templates/service.ts index 56630afdf..1917d4e70 100644 --- a/apps/server/src/templates/service.ts +++ b/apps/server/src/templates/service.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import type { Effort } from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; import { ProjectStore } from "../projects/store.js"; @@ -74,14 +75,19 @@ export class TemplateService { ): Promise { if (input.agentType === "opencode") input = { ...input, fullAccess: true }; assertAccessCeiling(input.fullAccess ?? false, callerFullAccess); + let projectRoot: string | undefined; if (input.projectId) { const project = await this.projects.get(input.projectId); if (!project) throw new Error("Project not found."); - input = { ...input, directory: project.repoRoot }; + projectRoot = project.repoRoot; + if (!remotePlacement(input.directory)) + input = { ...input, directory: project.repoRoot }; } if (input.persona) await resolveLaunchPersona( - input.directory, + remotePlacement(input.directory) + ? (projectRoot ?? null) + : input.directory, input.persona, "task", "catalog" @@ -144,10 +150,13 @@ export class TemplateService { ); const projectId = input.projectId === undefined ? existing.projectId : input.projectId; + let projectRoot: string | undefined; if (projectId) { const project = await this.projects.get(projectId); if (!project) throw new Error("Project not found."); - input = { ...input, directory: project.repoRoot }; + projectRoot = project.repoRoot; + if (!remotePlacement(input.directory ?? existing.directory)) + input = { ...input, directory: project.repoRoot }; } const persona = input.persona !== undefined ? input.persona : existing.persona; @@ -158,7 +167,9 @@ export class TemplateService { input.directory !== existing.directory)) ) await resolveLaunchPersona( - input.directory ?? existing.directory, + remotePlacement(input.directory ?? existing.directory) + ? (projectRoot ?? null) + : (input.directory ?? existing.directory), persona, "task", "catalog" @@ -289,7 +300,8 @@ export class TemplateService { if ( template.projectId && input.directory && - input.directory !== template.directory + input.directory !== template.directory && + !remotePlacement(input.directory) ) throw new Error("Project template directory cannot be overridden."); const cwd = input.directory ?? template.directory; diff --git a/apps/server/src/templates/store.ts b/apps/server/src/templates/store.ts index 3b37a2c43..8a94f45d7 100644 --- a/apps/server/src/templates/store.ts +++ b/apps/server/src/templates/store.ts @@ -1,6 +1,6 @@ import type { Effort } from "@dispatch/shared"; import { randomUUID } from "node:crypto"; -import path from "node:path"; +import { resolveLaunchLocation } from "../agents/workspace-target.js"; import type { Pool } from "pg"; @@ -103,7 +103,7 @@ export class TemplateStore { `, [ id, - path.resolve(input.directory), + resolveLaunchLocation(input.directory), input.name, input.description, input.prompt, @@ -146,7 +146,7 @@ export class TemplateStore { ): Promise { const result = await this.pool.query( `SELECT ${this.columns()} FROM templates WHERE directory = $1 AND name = $2`, - [path.resolve(directory), name] + [resolveLaunchLocation(directory), name] ); return result.rows[0] ? mapTemplate(result.rows[0]) : null; } @@ -194,7 +194,7 @@ export class TemplateStore { "branchName" ); const resolvedDir = input.directory - ? path.resolve(input.directory) + ? resolveLaunchLocation(input.directory) : undefined; const result = await this.pool.query( ` diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index 8fc0701e7..7a7c55995 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -1,3 +1,5 @@ +import { JobService } from "../../src/jobs/service.js"; +import { TemplateService } from "../../src/templates/service.js"; import { personaCatalog } from "../../src/personas/catalog.js"; import * as gitContext from "../../src/shared/git/git-context.js"; import { upsertPersona } from "../../src/personas/authoring.js"; @@ -310,6 +312,166 @@ describe("AgentManager", () => { expect(discard).toHaveBeenCalledExactlyOnceWith(agent.id); }); + it("records a runner selection only after acknowledgement and binds independent children to the selected origin", async () => { + const cwd = "runner://runner-test/@session"; + const projectId = "managed-runner-project"; + await pool.query( + "INSERT INTO projects (id, name, repo_root) VALUES ($1, 'Runner', '/tmp/remote-project') ON CONFLICT DO NOTHING", + [projectId] + ); + const requestSession = vi.fn(async () => ({ + value: JSON.stringify({ + path: "/workload/moved", + moved: true, + origin: "https://example.test/moved.git", + }), + })); + const remote = { + available: () => true, + isManagedWorkspace: () => true, + requestSession, + originFor: () => "https://example.test", + } as unknown as RemoteRunnerService; + const first = new AgentManager(pool, noopLogger, testConfig, { + runtime, + remote, + }); + const parent = await first.createAgent({ cwd, projectId }); + expect(parent).toMatchObject({ cwd, projectId, workspacePath: null }); + const move = { path: "/workload/moved/src", baseBranch: "develop" }; + requestSession.mockRejectedValueOnce(new Error("runner offline")); + await expect(first.setWorkspace(parent.id, move)).rejects.toThrow( + "runner offline" + ); + expect(await first.getAgent(parent.id)).toMatchObject({ + workspacePath: null, + }); + await expect( + first.setWorkspace(parent.id, { path: "runner://other/@session" }) + ).rejects.toThrow("absolute on the bound runner"); + expect(requestSession).toHaveBeenCalledTimes(1); + await expect(first.setWorkspace(parent.id, move)).resolves.toMatchObject({ + cwd, + projectId, + workspacePath: "/workload/moved", + workspaceBaseBranch: "develop", + }); + expect(requestSession).toHaveBeenLastCalledWith( + { runner: "runner-test", workspace: "@session" }, + { + agentId: parent.id, + kind: "sessionCheckout", + operation: { kind: "select", path: move.path }, + } + ); + + const childInput = { + cwd, + launchedByAgentId: parent.id, + parentAgentId: parent.id, + useWorktree: true, + baseBranch: "develop", + }; + const binding = { independentCheckoutOf: parent.id }; + await expect( + first.createAgent( + { ...childInput, cwd: "runner://other/@session" }, + binding + ) + ).rejects.toThrow("Invalid independent runner checkout binding"); + const child = await first.createAgent(childInput, binding); + expect(child).toMatchObject({ cwd, projectId, parentAgentId: parent.id }); + const launch = expect.objectContaining({ + agentId: child.id, + repository: { + url: "https://example.test/moved.git", + checkout: { + kind: "new", + branch: expect.stringContaining(child.id), + base: "develop", + }, + }, + }); + expect(runtime.launch).toHaveBeenLastCalledWith(launch); + expect( + runtime.launch.mock.calls.at(-1)?.[0].useWorktreeOf + ).toBeUndefined(); + const restarted = new AgentManager(pool, noopLogger, testConfig, { + runtime, + remote, + }); + await restarted.stopAgent(child.id); + await restarted.startAgent(child.id); + expect(runtime.launch).toHaveBeenLastCalledWith(launch); + expect(await restarted.getAgent(parent.id)).toMatchObject({ + cwd, + projectId, + workspacePath: "/workload/moved", + }); + }); + + it("places project templates and scheduled jobs on their saved runner", async () => { + const cwd = "runner://runner-test/@session"; + const projectId = "managed-runner-project"; + await pool.query( + "INSERT INTO projects (id, name, repo_root) VALUES ($1, 'Runner', '/tmp/remote-project') ON CONFLICT DO NOTHING", + [projectId] + ); + const remote = { + available: () => true, + isManagedWorkspace: () => true, + originFor: () => "https://example.test", + } as unknown as RemoteRunnerService; + const manager = new AgentManager(pool, noopLogger, testConfig, { + runtime, + remote, + }); + const templates = new TemplateService(pool, manager, noopLogger); + const template = await templates.addTemplate({ + name: "Run remote template", + projectId, + directory: cwd, + prompt: "Work", + useWorktree: false, + }); + const { agent } = await templates.launchTemplate({ + templateId: template.id, + }); + expect(agent).toMatchObject({ cwd, projectId, templateId: template.id }); + const jobs = new JobService(pool, manager, noopLogger, testConfig); + try { + const job = await jobs.addJob({ + name: "Run remote job", + projectId, + directory: cwd, + prompt: "Work on the schedule", + schedule: "0 * * * *", + enabled: true, + useWorktree: false, + }); + const run = await jobs.runJob({ + jobId: job.id, + triggerSource: "scheduled", + wait: false, + }); + expect(await manager.getAgent(run.agentId!)).toMatchObject({ + cwd, + projectId, + }); + expect(runtime.launch).toHaveBeenLastCalledWith( + expect.objectContaining({ + agentId: run.agentId, + placement: { runner: "runner-test", workspace: "@session" }, + mcp: expect.objectContaining({ + url: `https://example.test/api/mcp/jobs/${run.runId}/${run.agentId}`, + }), + }) + ); + } finally { + await jobs.shutdown(); + } + }); + it("persists the actual reviewer checkout owner on the same runner and reuses it on restart", async () => { const supportsSharedWorktree = vi.fn(() => true); const requestSession = vi.fn(async () => ({ diff --git a/apps/server/test/mcp-handlers.test.ts b/apps/server/test/mcp-handlers.test.ts index faa0b2423..8cfda8963 100644 --- a/apps/server/test/mcp-handlers.test.ts +++ b/apps/server/test/mcp-handlers.test.ts @@ -887,6 +887,51 @@ describe("createMcpHandlers", () => { }); describe("launchAgent", () => { + it("keeps borrowed and independent launches on the caller runner", async () => { + const cwd = "runner://runner-test/@session"; + deps.agentManager.getAgent.mockResolvedValue({ + ...(await deps.agentManager.getAgent()), + cwd, + }); + deps.templateService.getTemplate.mockResolvedValue( + templateRecord({ + directory: "/native/project", + useWorktree: true, + baseBranch: "develop", + }) + ); + await handlers.launchAgent("agt_test1", { + name: "borrower", + prompt: "work", + }); + expect(deps.agentManager.createAgent).toHaveBeenLastCalledWith( + expect.objectContaining({ cwd, parentAgentId: "agt_test1" }), + expect.objectContaining({ useWorktreeOf: "agt_test1" }) + ); + await handlers.launchAgent("agt_test1", { + name: "independent", + prompt: "work", + templateId: "tmpl_123", + }); + expect(deps.agentManager.createAgent).toHaveBeenLastCalledWith( + expect.objectContaining({ + cwd, + parentAgentId: "agt_test1", + useWorktree: true, + baseBranch: "develop", + }), + expect.objectContaining({ independentCheckoutOf: "agt_test1" }) + ); + await expect( + handlers.launchAgent("agt_test1", { + name: "foreign", + prompt: "work", + cwd: "runner://another/@session", + }) + ).rejects.toThrow("another runner"); + expect(deps.agentManager.createAgent).toHaveBeenCalledTimes(2); + }); + it("rejects a review persona from a different requested workspace", async () => { await expect( handlers.launchAgent("agt_test1", { diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 60b508455..e6690a46e 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -160,6 +160,8 @@ describe("runner enrollment service", () => { port: (api.address() as AddressInfo).port, tls: false, validAgentToken: (token, agentId) => token === `agent-token:${agentId}`, + validJobToken: (token, runId, agentId) => + token === `job-token:${runId}:${agentId}`, } ); services.push(service); @@ -730,7 +732,7 @@ describe("runner enrollment service", () => { }); }); - it("proxies only agent-token MCP routes with allow-listed headers", async () => { + it("proxies only session-scoped MCP routes with allow-listed headers", async () => { const service = makeService(); const a = await enroll(service, "alpha"); const origin = new URL(a.endpoint); @@ -822,6 +824,20 @@ describe("runner enrollment service", () => { ).toBe(404); } expect(apiRequests).toHaveLength(0); + const runId = "50a552a3-9629-4bc5-8b16-d52351d6c9ab"; + const jobRoute = `/api/mcp/jobs/${runId}/agt_abc`; + for (const token of ["agent-token:agt_abc", `job-token:${runId}:agt_other`]) + expect( + (await get(jobRoute, { authorization: `Bearer ${token}` }, "POST")) + .status + ).toBe(404); + expect( + await get( + jobRoute, + { authorization: `Bearer job-token:${runId}:agt_abc` }, + "POST" + ) + ).toEqual({ status: 200, body: `api:${jobRoute}` }); // /ping carries no credentials upstream. apiRequests.length = 0; await get("/ping", { authorization: "Bearer agent-token:agt_abc" }); diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index 7c69d1221..78ad43bb3 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -485,6 +485,90 @@ describe("runner session supervision", () => { await expect(stat(author)).rejects.toMatchObject({ code: "ENOENT" }); }); + it("persists moved and borrowed checkouts independently across restarts", async () => { + const workspace = MANAGED_WORKSPACE; + const nested = "agt_nested"; + const independent = "agt_independent"; + const asWorkload = async (bin: string, args: string[]) => + bin === "realpath" + ? (await realpath(args.at(-1)!)) + "\n" + : execFileSync(bin, args, { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }); + const runner = await start([], asWorkload); + const checkout = path.join(await realpath(root), "moved"); + const subdir = path.join(checkout, "src"); + await mkdir(subdir, { recursive: true }); + await asWorkload("git", ["-C", checkout, "init"]); + await asWorkload("git", [ + "-C", + checkout, + "config", + "remote.origin.url", + "https://secret@example.test/org/project.git", + ]); + await runner.launch(launch(workspace), undefined); + await expect( + runner.sessionCheckout(agentId, workspace, { + kind: "select", + path: subdir, + }) + ).resolves.toEqual({ + path: checkout, + moved: true, + origin: "https://example.test/org/project.git", + }); + processes.spawn.mockResolvedValueOnce(); + await runner.launch(sharedLaunch(), undefined); + processes.spawn.mockResolvedValueOnce(); + await runner.launch( + { ...sharedLaunch(reviewerId), agentId: nested }, + undefined + ); + processes.spawn.mockResolvedValueOnce(); + await runner.launch( + { ...launch(workspace), agentId: independent }, + undefined + ); + const independentDir = await runner.checkoutDirectory( + independent, + workspace + ); + await expect( + runner.sessionCheckout(agentId, workspace, { + kind: "select", + path: independentDir, + }) + ).rejects.toThrow("outside the bound runner checkout"); + + await runner.stop(agentId, workspace, false); + runner.close(); + const recovered = await start([], asWorkload); + await recovered.launch(launch(workspace), undefined); + expect(processes.spawn.mock.calls.at(-1)?.[1]).toBe(checkout); + await expect( + recovered.checkoutDirectory(independent, workspace) + ).resolves.toBe(independentDir); + await recovered.sessionCheckout(agentId, workspace, { + kind: "select", + path: null, + }); + expect(await recovered.checkoutDirectory(agentId, workspace)).not.toBe( + checkout + ); + for (const borrower of [reviewerId, nested]) + await expect( + recovered.checkoutDirectory(borrower, workspace) + ).resolves.toBe(checkout); + processes.spawn.mockResolvedValueOnce(); + await recovered.launch( + { ...sharedLaunch(reviewerId), agentId: nested }, + undefined + ); + expect(processes.spawn.mock.calls.at(-1)?.[1]).toBe(checkout); + }); + it("shares a configured workspace with separate host state and no folder cleanup", async () => { const running = await start(["configured", "other"]); await running.launch(launch("configured"), root); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 2e202b43e..e9850eb82 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -18,6 +18,7 @@ import { sessionCommandId, isOpaqueId, isCheckoutReply, + isSessionCheckout, parseGitHubPullRequestWatchEvent, isGitHubPullRequestDetails, isGitHubPullRequestDiff, @@ -130,6 +131,7 @@ it("negotiates advertised v1 capabilities independently on each ready frame", () checkoutInspection: true, checkoutViews: true, sharedWorktree: true, + sessionCheckout: true, }; expect(parseReadyFrame(managed)).toEqual(managed); }); @@ -707,6 +709,7 @@ function fixtureRunner(current: boolean) { githubManagement: true, pullRequestEvidence: true, pullRequestWatch: true, + sessionCheckout: true, }), }; const sample = { @@ -736,6 +739,8 @@ function fixtureRunner(current: boolean) { let resumed = false; const requests: ServiceFrame[] = []; + let selectedCheckout = "/workload/launch"; + function connect() { const service = new Duplex({ read() {}, @@ -836,6 +841,16 @@ function fixtureRunner(current: boolean) { command.agentId !== agentId ) { reply({ type: "result", id, error: "Unknown session binding" }); + } else if (command.kind === "sessionCheckout" && current && running) { + if (command.operation.kind === "select") + selectedCheckout = command.operation.path ?? "/workload/launch"; + result( + JSON.stringify({ + path: selectedCheckout, + moved: selectedCheckout !== "/workload/launch", + origin: "https://example.test/project.git", + }) + ); } else if (command.kind === "launch") { resumed = command.launch.resumeSessionId === sessionId; running = true; @@ -925,6 +940,72 @@ function fixtureRunner(current: boolean) { }; } +it("lets an independent host select a checkout by opaque session handle after negotiation", async () => { + const runner = fixtureRunner(true); + const launch: RemoteLaunch = { + agentId: runner.session.agentId, + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + }; + const initial = runner.connect(); + try { + await vi.waitFor(() => + expect(parseReadyFrame(initial.reports[0])?.sessionCheckout).toBe(true) + ); + await initial.connection.request({ + ...runner.session, + kind: "launch", + launch, + }); + const move = { + ...runner.session, + kind: "sessionCheckout" as const, + operation: { kind: "select" as const, path: "/workload/moved" }, + }; + expect( + parseServiceFrame({ + type: "request", + id: "relative", + command: { + ...move, + operation: { kind: "select", path: "runner://foreign/@session" }, + }, + }) + ).toBeNull(); + await expect( + initial.connection.request({ ...move, agentId: "another/host" }) + ).rejects.toThrow("Unknown session binding"); + const { value } = await initial.connection.request(move); + const selected = JSON.parse(String(value)); + expect(isSessionCheckout(selected)).toBe(true); + expect(selected).toMatchObject({ path: "/workload/moved", moved: true }); + expect( + isSessionCheckout({ + ...selected, + origin: "https://user:token@example.test/repo", + }) + ).toBe(false); + } finally { + initial.close(); + } + const resumed = runner.connect(); + try { + const { value } = await resumed.connection.request({ + ...runner.session, + kind: "sessionCheckout", + operation: { kind: "describe" }, + }); + expect(JSON.parse(String(value))).toMatchObject({ + path: "/workload/moved", + moved: true, + }); + } finally { + resumed.close(); + } +}); + it.each([true, false])( "independent service starts and resumes a runner session (current capabilities: %s)", async (current) => { diff --git a/apps/server/test/tasks-service.test.ts b/apps/server/test/tasks-service.test.ts index 744eb7df6..a9f40b37c 100644 --- a/apps/server/test/tasks-service.test.ts +++ b/apps/server/test/tasks-service.test.ts @@ -1290,6 +1290,42 @@ describe("triggers", () => { } ); + it("preserves a project template's runner through manual and triggered task launches", async () => { + const cwd = "runner://runner-test/@session"; + const saved = template({ + id: TEMPLATE_ID, + directory: cwd, + useWorktree: false, + }); + const createAgent = vi.fn(async () => { + const id = `agt_launch_${++agentSeq}`; + await insertAgent(id, "running", "Builder"); + return { id } as AgentRecord; + }); + const templates = new TemplateService( + pool, + { createAgent } as never, + { info: vi.fn() } as never + ); + service = build(filesRoot, { + getTemplate: async (id) => (id === TEMPLATE_ID ? saved : null), + launchTemplate: async (input) => + (await templates.launchTemplate(input)).agent, + }); + const ready = await withTrigger("ready", { assign: false }); + const task = await service.createTask( + { projectId, title: "Run on the enrolled runner" }, + USER + ); + await service.updateTask(task.id, { columnId: ready }, USER); + await service.launchAgent(task.id, { templateId: TEMPLATE_ID }, USER); + expect(createAgent).toHaveBeenCalledTimes(2); + for (const args of createAgent.mock.calls) + expect(args).toEqual([ + expect.objectContaining({ cwd, projectId, templateId: TEMPLATE_ID }), + ]); + }); + it("launches a prompt-less persona template with the briefing as its prompt", async () => { // This test isolates prompt composition; discovery is validated separately. const persona = vi diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index e96db0014..7a727dab6 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -44,3 +44,13 @@ Each observation needs an owning machine/account, freshness, a bounded payload, ## Checkpoints Ship each capability through its normal local and remote entry points, test older peers, and update the inventory with evidence. Keep release/update policy changes separate until the restart and mixed-version tests establish what can safely coexist. + +Session checkout selection now runs on the owning runner. Dispatch preserves +the machine binding and project membership and records the selected path +after runner acknowledgement. Borrowers retain the effective directory +captured at launch. Independent MCP worktrees use the effective checkout's +HTTPS origin and a distinct repository preparation request. Project +templates and scheduled jobs retain explicit runner locators, and task +launches use the selected template placement. A new checkout uses a +published base from its origin. Borrowing shares the existing files, +including unpublished changes. diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index dc613853e..ca80fe1fd 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -450,7 +450,7 @@ test.describe("failure suite", () => { }); }); -test("managed scratch launch reports health and archive removes the guest session folder", async ({ +test("managed scratch checkout selection persists across host start and preserves archive ownership", async ({ page, request, }, testInfo) => { @@ -513,6 +513,83 @@ test("managed scratch launch reports health and archive removes the guest sessio guest("scratch", `cat /var/lib/runner/hosts/${id}/host.pid`).trim() ).toBe(scratchPid); + const selected = "/tmp/dispatch-selected-checkout"; + guest( + "scratch", + [ + `mkdir -p ${selected}/src`, + `git init -q ${selected}`, + `echo "Selected on the enrolled runner" > ${selected}/selected-checkout.txt`, + `chown -R 1500:1500 ${selected}`, + ].join(" && ") + ); + const workspaceRoute = `/api/v1/agents/${id}/workspace`; + const updateWorkspace = (path: string | null) => + request.patch(workspaceRoute, { + headers: authHeaders(), + data: { path }, + }); + const foreign = await updateWorkspace("runner://another-runner/@session"); + expect(foreign.status()).toBe(400); + const changed = await updateWorkspace(`${selected}/src`); + expect(changed.ok(), await changed.text()).toBe(true); + expect((await changed.json()).agent).toMatchObject({ + cwd: `runner://${runnerId}/@session`, + workspacePath: selected, + }); + for (const workspace of [`runner://${runnerId}/@session`, selected]) { + const files = await request.get(workspaceRoute, { + headers: authHeaders(), + params: { workspace, path: "" }, + }); + expect(files.ok(), await files.text()).toBe(true); + expect(await files.text()).toContain("selected-checkout.txt"); + } + const stop = await request.post(`/api/v1/agents/${id}/stop`, { + headers: authHeaders(), + }); + expect(stop.ok(), await stop.text()).toBe(true); + crashRunner("scratch"); + await expect + .poll(async () => (await runnerRow(request, "scratch"))?.status) + .toBe("offline"); + startRunner("scratch"); + await expect + .poll(async () => (await runnerRow(request, "scratch"))?.status, { + timeout: 30_000, + }) + .toBe("online"); + const resume = await request.post(`/api/v1/agents/${id}/start`, { + headers: authHeaders(), + }); + expect(resume.ok(), await resume.text()).toBe(true); + expect( + JSON.parse(guest("scratch", `cat /var/lib/runner/hosts/${id}/launch.json`)) + .cwd + ).toBe(selected); + await newSettledTurn( + page, + "proof-count selected-cwd", + "Local or guest fixture turn completed." + ); + expect(guest("scratch", `cat ${selected}/provider-invocations`).trim()).toBe( + "called" + ); + + const viewport = page.viewportSize()!; + for (const size of [viewport, { width: 390, height: 844 }]) { + await page.setViewportSize(size); + await page.goto(`/agents/${id}/files`, { waitUntil: "domcontentloaded" }); + const files = page.getByTestId("files-pane"); + await files.getByText("selected-checkout.txt", { exact: true }).click(); + await expect(files).toContainText("Selected on the enrolled runner"); + await testInfo.attach(`selected checkout files at ${size.width}px`, { + body: await page.screenshot(), + contentType: "image/png", + }); + } + await page.setViewportSize(viewport); + await page.goto("/settings/runners", { waitUntil: "domcontentloaded" }); await page.getByTestId(`runner-select-${runnerId}`).click(); const health = page.getByTestId("runner-detail").getByTestId("runner-health"); @@ -543,4 +620,7 @@ test("managed scratch launch reports health and archive removes the guest sessio timeout: 30_000, }) .toBe(true); + expect(guestOk("scratch", `test -f ${selected}/selected-checkout.txt`)).toBe( + true + ); }); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 393965b28..b66f872cb 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -164,6 +164,32 @@ operations independently of session bindings. With `useWorktreeOf`, the value is the handle of a session with an existing checkout on the same runner and workspace. Omit `repository` for a borrowed checkout. +Runners advertising `sessionCheckout: true` accept the bound +`sessionCheckout` command with the ordinary `agentId` and `workspace` +handles. `operation: {kind: "describe"}` reports the effective checkout. +`operation: {kind: "select", path}` selects an existing absolute directory +on that runner and resolves a Git subdirectory to its checkout root. Use a +null path to return to the session's launch or borrowed checkout. The result +is a JSON string validated by `isSessionCheckout`. It carries the canonical +`path`, whether it is `moved` from the initial checkout, and its +credential-free HTTPS `origin` when available. + +The runner checks directory access under the workload identity and durably +records an accepted selection before responding. Checkout reads and future +host starts use it. A running host keeps its current cwd. Retrying the same +selection is safe, and a service can describe the effective checkout after a +lost response. A selection cannot change the runner, transfer archive +ownership, or access another managed session's storage. Configured +workspaces additionally restrict selection to the configured directory. + +When a session borrows a checkout from a runner with this capability, +`useWorktreeOf` captures the source session's effective checkout on the +first launch. The borrower retains it across restarts and can make its own +selection. For an independent managed Git checkout, describe the source +session on that runner, then launch a different session with a new +`repository` request using the returned origin. The new checkout uses refs +from the origin. + Negotiate again on each connection. Require an explicit `true` for optional capabilities and ignore unknown advertisements. For an absent capability, omit the command and report that the operation is unavailable. A configured diff --git a/packages/runner-protocol/src/checkout.ts b/packages/runner-protocol/src/checkout.ts index 63c39113a..53139d15b 100644 --- a/packages/runner-protocol/src/checkout.ts +++ b/packages/runner-protocol/src/checkout.ts @@ -70,3 +70,19 @@ export function isCheckoutReply( value.files.every(relativePath) ); } + +/** A machine-local absolute directory, interpreted only by the bound runner. */ +export function isCheckoutPath(value: unknown): value is string { + return ( + typeof value === "string" && + value.startsWith("/") && + value.length <= 4096 && + !/[\x00-\x1f\x7f]/.test(value) + ); +} + +export type SessionCheckout = { + path: string; + moved: boolean; + origin: string | null; +}; diff --git a/packages/runner-protocol/src/connection.ts b/packages/runner-protocol/src/connection.ts index 87a7635fa..3240ad74b 100644 --- a/packages/runner-protocol/src/connection.ts +++ b/packages/runner-protocol/src/connection.ts @@ -88,6 +88,7 @@ export class RunnerConnection { ): Promise { // Repository fetches and engine package installs can run for minutes. const timeoutMs = + command.kind === "sessionCheckout" || command.kind === "inspectCheckout" || command.kind === "viewCheckout" || command.kind === "engine" || diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index ff31ffcbb..79728f362 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,8 +1,10 @@ import { isCheckoutView, type CheckoutView } from "./checkout-view.js"; import { isCheckoutQuery, + isCheckoutPath, validBranch, type CheckoutQuery, + type SessionCheckout, } from "./checkout.js"; import { MANAGED_WORKSPACE, isOpaqueId } from "./placement.js"; import { @@ -61,6 +63,11 @@ export type SessionOperation = | { agentId: string; kind: "watchCheckout" } | { agentId: string; kind: "viewCheckout"; query: CheckoutView } | { agentId: string; kind: "inspectCheckout"; query: CheckoutQuery } + | { + agentId: string; + kind: "sessionCheckout"; + operation: { kind: "describe" } | { kind: "select"; path: string | null }; + } | { agentId: string; kind: "repo" }; export type RunnerOperation = @@ -88,6 +95,7 @@ export type ReadyFrame = { checkoutViews?: true; sharedWorktree?: true; workspacePreparation?: true; + sessionCheckout?: true; }; /** Accept v1 extension fields and enable optional features only when explicitly true. */ @@ -113,6 +121,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.checkoutViews === true && { checkoutViews: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), + ...(frame.sessionCheckout === true && { sessionCheckout: true }), ...(frame.workspacePreparation === true && { workspacePreparation: true }), ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), @@ -208,6 +217,15 @@ export function parseRunnerRepositoryUrl( } } +export function isSessionCheckout(value: unknown): value is SessionCheckout { + return ( + isRecord(value) && + isCheckoutPath(value.path) && + typeof value.moved === "boolean" && + (value.origin === null || parseRunnerRepositoryUrl(value.origin) !== null) + ); +} + function isRepository(value: unknown): value is RunnerRepository { if ( !isRecord(value) || @@ -279,6 +297,14 @@ function isCommand(value: unknown): value is Command { (value.launch.useWorktreeOf === undefined || value.agentId === value.launch.agentId) ); + case "sessionCheckout": + return ( + isRecord(value.operation) && + (value.operation.kind === "describe" || + (value.operation.kind === "select" && + (value.operation.path === null || + isCheckoutPath(value.operation.path)))) + ); case "watchCheckout": return true; case "viewCheckout": From 19e4f20b7579cd9a329c5bb915306f831e2ae42c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 15:58:01 -0700 Subject: [PATCH 132/642] Preserve runner branch selection and isolate checkout roots --- apps/server/src/agents/manager.ts | 17 +++--- apps/server/src/agents/remote/repository.ts | 16 +++++- apps/server/src/agents/remote/service.ts | 12 ++++- .../src/agents/remote/session-storage.ts | 5 +- .../src/agents/remote/session-supervisor.ts | 6 +-- apps/server/test/db/agent-manager.test.ts | 53 +++++++++++++++++++ .../test/remote-runner-supervisor.test.ts | 35 ++++++++++++ .../test/remote-session-storage.test.ts | 13 +++++ .../test/runner-protocol-consumer.test.ts | 14 +++++ packages/runner-protocol/README.md | 8 ++- packages/runner-protocol/src/execution.ts | 6 ++- 11 files changed, 164 insertions(+), 21 deletions(-) diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 0f8700922..6148a1584 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1724,17 +1724,16 @@ export class AgentManager { directory?.cwd ?? input.cwd ); if (derivedRepositoryUrl && p.worktree) { - const { branch, baseBranch } = p.worktree; + const { branch, baseBranch, createNewBranch } = p.worktree; runnerRepository = { url: derivedRepositoryUrl, - checkout: - input.createNewBranch === false && input.worktreeBranch - ? { kind: "branch", branch } - : { - kind: "new", - branch, - ...(baseBranch ? { base: baseBranch } : {}), - }, + checkout: !createNewBranch + ? { kind: "branch", branch: baseBranch ?? "main", allowDefault: true } + : { + kind: "new", + branch, + ...(baseBranch ? { base: baseBranch } : {}), + }, }; try { parseRepository(runnerRepository); diff --git a/apps/server/src/agents/remote/repository.ts b/apps/server/src/agents/remote/repository.ts index 8d85bcccd..8a3b8e3b3 100644 --- a/apps/server/src/agents/remote/repository.ts +++ b/apps/server/src/agents/remote/repository.ts @@ -50,8 +50,20 @@ export function parseRepository(input: unknown): RepositoryInput { throw new Error("The checkout base must be a valid branch name."); return { url, checkout: { kind: "new", branch, base } }; } - case "branch": - return { url, checkout: { kind: "branch", branch } }; + case "branch": { + const allowDefault = + "allowDefault" in checkout ? checkout.allowDefault : undefined; + if (allowDefault !== undefined && allowDefault !== true) + throw new Error("allowDefault must be true when provided."); + return { + url, + checkout: { + kind: "branch", + branch, + ...(allowDefault && { allowDefault }), + }, + }; + } case "pr": { const number = "number" in checkout ? checkout.number : undefined; if ( diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 3b82fd2e8..aed93c0be 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1538,9 +1538,17 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update this runner to open Files and Changes." ); - if (command.kind === "sessionCheckout" && !peer.sessionCheckout) + const checkout = + command.kind === "launch" + ? command.launch.repository?.checkout + : undefined; + if ( + (command.kind === "sessionCheckout" || + (checkout?.kind === "branch" && checkout.allowDefault)) && + !peer.sessionCheckout + ) throw new RunnerCapabilityUnavailable( - "Update the runner to select or describe a session checkout." + "Update the runner to use these checkout options." ); if (command.kind === "inspectCheckout" && !peer.checkoutInspection) throw new RunnerCapabilityUnavailable( diff --git a/apps/server/src/agents/remote/session-storage.ts b/apps/server/src/agents/remote/session-storage.ts index f3c7d8ad9..19a15cbc7 100644 --- a/apps/server/src/agents/remote/session-storage.ts +++ b/apps/server/src/agents/remote/session-storage.ts @@ -166,7 +166,10 @@ export class RunnerRepositories { throw new Error( "The remote repository has no unambiguous default branch." ); - if (checkout.branch === defaultBranch) + if ( + checkout.branch === defaultBranch && + !(checkout.kind === "branch" && checkout.allowDefault) + ) throw new Error( "The default branch cannot be used as a session branch." ); diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 726fd50b3..41afeff15 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -377,10 +377,10 @@ export async function createSessionSupervisor( ); } // Configured workspaces are allowlisted. Managed sessions may select - // workload directories, but another session's storage needs a binding. + // their owner's checkout or an external root disjoint from runner state. const allowed = managed - ? !containsDirectory(storage, dir) || - containsDirectory(path.join(sessions, owner), dir) + ? containsDirectory(path.join(sessions, owner), dir) || + (!containsDirectory(storage, dir) && !containsDirectory(dir, storage)) : containsDirectory(launch, dir); if (!allowed) throw new Error("Directory is outside the bound runner checkout."); diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index 7a7c55995..e0b21aa6f 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -1,3 +1,4 @@ +import { createMcpHandlers } from "../../src/server/mcp-handlers.js"; import { JobService } from "../../src/jobs/service.js"; import { TemplateService } from "../../src/templates/service.js"; import { personaCatalog } from "../../src/personas/catalog.js"; @@ -410,6 +411,58 @@ describe("AgentManager", () => { }); }); + it("carries the MCP existing-branch default to the runner launch request", async () => { + const remote = { + available: () => true, + isManagedWorkspace: () => true, + originFor: () => "https://example.test", + requestSession: vi.fn(async () => ({ + value: JSON.stringify({ + path: "/workload/source", + moved: false, + origin: "https://example.test/source.git", + }), + })), + } as unknown as RemoteRunnerService; + const manager = new AgentManager(pool, noopLogger, testConfig, { + runtime, + remote, + }); + const parent = await manager.createAgent({ + cwd: "runner://runner-test/@session", + }); + const mcp = createMcpHandlers({ + pool, + agentManager: manager, + publishUiEvent: vi.fn(), + withStreamFlag: (agent) => ({ ...agent, hasStream: false }), + } as Parameters[0]); + const input = { + name: "existing", + prompt: "Work independently", + useWorktree: true, + }; + for (const [refs, branch] of [ + [{ baseBranch: "origin/feature/x" }, "feature/x"], + [ + { baseBranch: "origin/feature/x", worktreeBranch: "ignored" }, + "feature/x", + ], + [{}, "main"], + ] as const) { + const child = await mcp.launchAgent(parent.id, { ...input, ...refs }); + expect(runtime.launch).toHaveBeenLastCalledWith( + expect.objectContaining({ + agentId: child.agentId, + repository: { + url: "https://example.test/source.git", + checkout: { kind: "branch", branch, allowDefault: true }, + }, + }) + ); + } + }); + it("places project templates and scheduled jobs on their saved runner", async () => { const cwd = "runner://runner-test/@session"; const projectId = "managed-runner-project"; diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index 78ad43bb3..cbc81657e 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -509,6 +509,41 @@ describe("runner session supervision", () => { "https://secret@example.test/org/project.git", ]); await runner.launch(launch(workspace), undefined); + const select = (path: string) => + runner.sessionCheckout(agentId, workspace, { kind: "select", path }); + const owningDir = path.join(state, "sessions", agentId); + const owningSubdir = path.join(owningDir, "subdirectory"); + await mkdir(owningSubdir); + await expect(select(owningSubdir)).resolves.toMatchObject({ + path: owningSubdir, + }); + + const ancestor = path.dirname(state); + const alias = path.join(owningDir, "ancestor-link"); + await symlink(ancestor, alias); + for (const forbidden of [ + "/", + ancestor, + alias, + state, + path.join(state, "sessions"), + ]) + await expect(select(forbidden)).rejects.toThrow( + "outside the bound runner checkout" + ); + + // A harmless-looking sibling of the storage can resolve to a Git root + // that contains it. Confirm authorization is repeated on that root. + const sibling = path.join(ancestor, "sibling"); + await mkdir(sibling); + await asWorkload("git", ["-C", ancestor, "init"]); + await expect(select(sibling)).rejects.toThrow( + "outside the bound runner checkout" + ); + await expect(runner.checkoutDirectory(agentId, workspace)).resolves.toBe( + owningSubdir + ); + await expect( runner.sessionCheckout(agentId, workspace, { kind: "select", diff --git a/apps/server/test/remote-session-storage.test.ts b/apps/server/test/remote-session-storage.test.ts index 0c207b329..f674d9705 100644 --- a/apps/server/test/remote-session-storage.test.ts +++ b/apps/server/test/remote-session-storage.test.ts @@ -238,6 +238,19 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e prepare(c, spec({ kind: "new", branch: "topic" })) ).rejects.toThrow("already exists"); + const defaultBranch = spec({ + kind: "branch", + branch: "main", + allowDefault: true, + }); + const defaultCheckout = await prepare(c, defaultBranch); + expect( + (await git("-C", defaultCheckout, "branch", "--show-current")).trim() + ).toBe("main"); + const competing = await session("competing"); + await expect(prepare(competing, defaultBranch)).rejects.toThrow("occupied"); + await repositories.remove(c, defaultBranch); + await repositories.remove(b, existing); await repositories.remove(b, existing); expect( diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index e9850eb82..f5811b6d5 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -343,6 +343,20 @@ it("validates checkout queries, results and borrowed launches", () => { useWorktreeOf: "author", }; expect(parse({ ...command, launch })).not.toBeNull(); + const existingDefault = (allowDefault: boolean) => ({ + ...command, + launch: { + ...launch, + useWorktreeOf: undefined, + repository: { + url: "https://example.test/project.git", + checkout: { kind: "branch", branch: "main", allowDefault }, + }, + }, + }); + expect(parse(existingDefault(true))).not.toBeNull(); + expect(parse(existingDefault(false))).toBeNull(); + expect(parse({ ...command, agentId: "other", launch })).toBeNull(); expect( parse({ ...command, launch: { ...launch, useWorktreeOf: "reviewer" } }) diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index b66f872cb..cc0d93bf0 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -106,6 +106,9 @@ workload account’s GitHub login for `https://github.com`: - `{ kind: "new", branch, base? }` creates a branch from the named or default remote branch. - `{ kind: "branch", branch }` checks out an existing non-default branch. + Runners advertising `sessionCheckout: true` also accept `allowDefault: true` + on this checkout kind to let the existing branch be the origin's default. + Git still rejects a branch held by another worktree. - `{ kind: "pr", branch, number }` fetches `refs/pull//head` and checks it out under the supplied branch name. @@ -179,8 +182,9 @@ records an accepted selection before responding. Checkout reads and future host starts use it. A running host keeps its current cwd. Retrying the same selection is safe, and a service can describe the effective checkout after a lost response. A selection cannot change the runner, transfer archive -ownership, or access another managed session's storage. Configured -workspaces additionally restrict selection to the configured directory. +ownership, or select a root that contains runner storage. Outside its own +managed session directory, a checkout must be disjoint from runner storage. +Configured workspaces additionally restrict selection to the configured directory. When a session borrows a checkout from a runner with this capability, `useWorktreeOf` captures the source session's effective checkout on the diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 79728f362..2ee2e66ed 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -30,7 +30,7 @@ export type ServiceMcp = { export type RepositoryCheckout = | { kind: "new"; branch: string; base?: string } - | { kind: "branch"; branch: string } + | { kind: "branch"; branch: string; allowDefault?: true } | { kind: "pr"; branch: string; number: number }; export type RunnerRepository = { url: string; checkout: RepositoryCheckout }; @@ -239,7 +239,9 @@ function isRepository(value: unknown): value is RunnerRepository { case "new": return checkout.base === undefined || validBranch(checkout.base); case "branch": - return true; + return ( + checkout.allowDefault === undefined || checkout.allowDefault === true + ); case "pr": return ( typeof checkout.number === "number" && From 797bb66ac26ac6dd595e68c2ca7565d1e6f82512 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:02:30 -0700 Subject: [PATCH 133/642] Resolve omitted checkout branches on the owning runner --- apps/server/src/agents/manager.ts | 4 +- apps/server/src/agents/remote/repository.ts | 17 ++--- apps/server/src/agents/remote/service.ts | 1 + .../src/agents/remote/session-storage.ts | 56 +++++++++------ apps/server/test/db/agent-manager.test.ts | 17 +++-- .../test/remote-session-storage.test.ts | 71 +++++++++++++++++-- .../test/runner-protocol-consumer.test.ts | 14 ++++ packages/runner-protocol/README.md | 4 ++ packages/runner-protocol/src/execution.ts | 2 + 9 files changed, 144 insertions(+), 42 deletions(-) diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 6148a1584..91624e8af 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1728,7 +1728,9 @@ export class AgentManager { runnerRepository = { url: derivedRepositoryUrl, checkout: !createNewBranch - ? { kind: "branch", branch: baseBranch ?? "main", allowDefault: true } + ? baseBranch + ? { kind: "branch", branch: baseBranch, allowDefault: true } + : { kind: "default" } : { kind: "new", branch, diff --git a/apps/server/src/agents/remote/repository.ts b/apps/server/src/agents/remote/repository.ts index 8a3b8e3b3..e60b0191a 100644 --- a/apps/server/src/agents/remote/repository.ts +++ b/apps/server/src/agents/remote/repository.ts @@ -34,13 +34,14 @@ export function parseRepository(input: unknown): RepositoryInput { url = repositoryUrl(input.url); } const checkout = input.checkout; - if ( - !checkout || - typeof checkout !== "object" || - !("branch" in checkout) || - !validBranch(checkout.branch) || - !("kind" in checkout) - ) + if (!checkout || typeof checkout !== "object" || !("kind" in checkout)) + throw new Error("A valid checkout branch is required."); + if (checkout.kind === "default") { + if ("branch" in checkout && checkout.branch !== undefined) + throw new Error("A default checkout resolves its branch on the runner."); + return { url, checkout: { kind: "default" } }; + } + if (!("branch" in checkout) || !validBranch(checkout.branch)) throw new Error("A valid checkout branch is required."); const { branch } = checkout; switch (checkout.kind) { @@ -75,7 +76,7 @@ export function parseRepository(input: unknown): RepositoryInput { return { url, checkout: { kind: "pr", branch, number } }; } default: - throw new Error("Checkout kind must be new, branch, or pr."); + throw new Error("Checkout kind must be new, branch, default, or pr."); } } diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index aed93c0be..b983c2712 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1544,6 +1544,7 @@ export class RemoteRunnerService { : undefined; if ( (command.kind === "sessionCheckout" || + checkout?.kind === "default" || (checkout?.kind === "branch" && checkout.allowDefault)) && !peer.sessionCheckout ) diff --git a/apps/server/src/agents/remote/session-storage.ts b/apps/server/src/agents/remote/session-storage.ts index 19a15cbc7..ac3a1ce03 100644 --- a/apps/server/src/agents/remote/session-storage.ts +++ b/apps/server/src/agents/remote/session-storage.ts @@ -33,6 +33,8 @@ function worktreePaths(list: string): string[] { } type CheckoutPlan = { + /** The runner's resolved branch for an implicit default checkout. */ + branch?: string; commit: string; fastForward: boolean; reviewBase?: string; @@ -93,8 +95,10 @@ export class RunnerRepositories { const git = (...args: string[]) => this.git(`--git-dir=${cache}`, ...args); await this.git("init", "--quiet", "--bare", "--template=", cache); - const branch = checkout.branch; - const finish = async (plan: CheckoutPlan) => { + const pendingPlan = await journal.read(); + const requestedBranch = + checkout.kind === "default" ? pendingPlan?.branch : checkout.branch; + const finish = async (branch: string, plan: CheckoutPlan) => { try { if (plan.fastForward) await this.git("-C", cwd, "merge", "--ff-only", "--", plan.commit); @@ -131,8 +135,7 @@ export class RunnerRepositories { ).trimEnd() !== cwd ) throw new Error("The runner session checkout is unavailable."); - const plan = await journal.read(); - if (plan) { + if (pendingPlan) { const current = await this.git( "-C", cwd, @@ -140,34 +143,43 @@ export class RunnerRepositories { "--short", "HEAD" ); - if (current.trim() !== branch) + if (current.trim() !== requestedBranch || !requestedBranch) throw new Error( "The runner session checkout changed during preparation." ); - await finish(plan); + await finish(requestedBranch, pendingPlan); } return cwd; } - const defaultRef = await git( - "ls-remote", - "--symref", - "--", - url, - "HEAD" - ).catch(() => { - throw new Error( - "Could not read the remote repository's default branch." - ); - }); - const match = /^ref: refs\/heads\/(.+)\tHEAD$/m.exec(defaultRef); - const defaultBranch = match?.[1]; + const readDefaultBranch = async () => { + const defaultRef = await git( + "ls-remote", + "--symref", + "--", + url, + "HEAD" + ).catch(() => { + throw new Error( + "Could not read the remote repository's default branch." + ); + }); + return /^ref: refs\/heads\/(.+)\tHEAD$/m.exec(defaultRef)?.[1]; + }; + // A retry after reservation or a busy branch keeps the original choice + // even when the remote's HEAD starts pointing to a different branch. + const defaultBranch = + checkout.kind === "default" && requestedBranch + ? requestedBranch + : await readDefaultBranch(); if (!validBranch(defaultBranch)) throw new Error( "The remote repository has no unambiguous default branch." ); + const branch = requestedBranch ?? defaultBranch; if ( - checkout.branch === defaultBranch && + branch === defaultBranch && + checkout.kind !== "default" && !(checkout.kind === "branch" && checkout.allowDefault) ) throw new Error( @@ -216,6 +228,7 @@ export class RunnerRepositories { ); break; case "branch": + case "default": commit = remote; break; case "pr": @@ -255,6 +268,7 @@ export class RunnerRepositories { ? ["--", cwd, branch] : ["--no-track", "-b", branch, "--", cwd, commit]; const plan: CheckoutPlan = { + ...(checkout.kind === "default" && { branch }), commit, fastForward: needsFastForward, reviewBase: @@ -269,7 +283,7 @@ export class RunnerRepositories { "Could not create the session checkout. The branch may already be occupied." ); }); - await finish(plan); + await finish(branch, plan); return cwd; }); } diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index e0b21aa6f..40114d7d5 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -442,13 +442,20 @@ describe("AgentManager", () => { prompt: "Work independently", useWorktree: true, }; - for (const [refs, branch] of [ - [{ baseBranch: "origin/feature/x" }, "feature/x"], + for (const [refs, checkout] of [ + [ + { baseBranch: "origin/feature/x" }, + { kind: "branch", branch: "feature/x", allowDefault: true }, + ], [ { baseBranch: "origin/feature/x", worktreeBranch: "ignored" }, - "feature/x", + { kind: "branch", branch: "feature/x", allowDefault: true }, + ], + [ + { baseBranch: "main" }, + { kind: "branch", branch: "main", allowDefault: true }, ], - [{}, "main"], + [{}, { kind: "default" }], ] as const) { const child = await mcp.launchAgent(parent.id, { ...input, ...refs }); expect(runtime.launch).toHaveBeenLastCalledWith( @@ -456,7 +463,7 @@ describe("AgentManager", () => { agentId: child.agentId, repository: { url: "https://example.test/source.git", - checkout: { kind: "branch", branch, allowDefault: true }, + checkout, }, }) ); diff --git a/apps/server/test/remote-session-storage.test.ts b/apps/server/test/remote-session-storage.test.ts index f674d9705..132590b12 100644 --- a/apps/server/test/remote-session-storage.test.ts +++ b/apps/server/test/remote-session-storage.test.ts @@ -160,11 +160,9 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e const uid = process.getuid!(); const gid = process.getgid!(); let failReviewBase = false; - const repositories = new RunnerRepositories( - cache, - uid, - gid, - (bin, args) => { + let failTrunkTracking = false; + const makeRepositories = () => + new RunnerRepositories(cache, uid, gid, (bin, args) => { expect(bin).toBe("git"); if ( failReviewBase && @@ -173,9 +171,18 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e failReviewBase = false; return Promise.reject(new Error("interrupted Git configuration")); } + if ( + failTrunkTracking && + args.includes("--set-upstream-to=refs/remotes/origin/trunk") + ) { + failTrunkTracking = false; + return Promise.reject( + new Error("interrupted tracking configuration") + ); + } return git("-c", `url.file://${origin}.insteadOf=${url}`, ...args); - } - ); + }); + let repositories = makeRepositories(); type Journal = Parameters[2]; type Plan = Parameters[0]; const plans = new Map(); @@ -309,6 +316,56 @@ it("uses isolated worktrees, protects occupied and default branches, and keeps e await git("-C", await prepare(c, selectedBase), "rev-parse", "HEAD") ).trim() ).toBe(divergent); + + await git("-C", origin, "switch", "-c", "trunk"); + const trunk = await commit("trunk differs from main"); + const implicit = spec({ kind: "default" }); + const implicitSession = await session("implicit"); + const waitingSession = await session("waiting"); + const mainSession = await session("explicit-main"); + const currentBranch = async (cwd: string) => + (await git("-C", cwd, "branch", "--show-current")).trim(); + const implicitPath = path.join(implicitSession, "checkout"); + + failTrunkTracking = true; + await expect(prepare(implicitSession, implicit)).rejects.toThrow( + "Could not update" + ); + expect(await currentBranch(implicitPath)).toBe("trunk"); + expect((await git("-C", implicitPath, "rev-parse", "HEAD")).trim()).toBe( + trunk + ); + await expect(prepare(waitingSession, implicit)).rejects.toThrow("occupied"); + const mainPath = await prepare(mainSession, defaultBranch); + expect(await currentBranch(mainPath)).toBe("main"); + expect((await git("-C", mainPath, "rev-parse", "HEAD")).trim()).toBe( + initial + ); + + await git("-C", origin, "switch", "main"); + repositories = makeRepositories(); + await expect(prepare(implicitSession, implicit)).resolves.toBe( + implicitPath + ); + expect( + ( + await git( + "-C", + implicitPath, + "rev-parse", + "--abbrev-ref", + "@{upstream}" + ) + ).trim() + ).toBe("origin/trunk"); + await expect(prepare(waitingSession, implicit)).rejects.toThrow("occupied"); + await repositories.remove(implicitSession, implicit); + const recovered = await prepare(waitingSession, implicit); + expect(await currentBranch(recovered)).toBe("trunk"); + expect((await git("-C", recovered, "rev-parse", "HEAD")).trim()).toBe( + trunk + ); + await expect(prepare(waitingSession, implicit)).resolves.toBe(recovered); } finally { await rm(root, { force: true, recursive: true }); } diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index f5811b6d5..d45097582 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -356,6 +356,20 @@ it("validates checkout queries, results and borrowed launches", () => { }); expect(parse(existingDefault(true))).not.toBeNull(); expect(parse(existingDefault(false))).toBeNull(); + const implicitDefault = { + ...command, + launch: { + ...launch, + useWorktreeOf: undefined, + repository: { + url: "https://example.test/project.git", + checkout: { kind: "default" }, + }, + }, + }; + expect(parse(implicitDefault)).toMatchObject({ + command: { launch: { repository: { checkout: { kind: "default" } } } }, + }); expect(parse({ ...command, agentId: "other", launch })).toBeNull(); expect( diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index cc0d93bf0..697e64b8b 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -109,6 +109,10 @@ workload account’s GitHub login for `https://github.com`: Runners advertising `sessionCheckout: true` also accept `allowDefault: true` on this checkout kind to let the existing branch be the origin's default. Git still rejects a branch held by another worktree. +- `{ kind: "default" }` checks out the existing branch named by the origin's + HEAD symref. It requires `sessionCheckout: true`. The runner journals the + resolved branch before reserving the worktree, so recovery preserves the + branch even if the origin changes its default. - `{ kind: "pr", branch, number }` fetches `refs/pull//head` and checks it out under the supplied branch name. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 2ee2e66ed..be5d9dba0 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -31,6 +31,7 @@ export type ServiceMcp = { export type RepositoryCheckout = | { kind: "new"; branch: string; base?: string } | { kind: "branch"; branch: string; allowDefault?: true } + | { kind: "default" } | { kind: "pr"; branch: string; number: number }; export type RunnerRepository = { url: string; checkout: RepositoryCheckout }; @@ -234,6 +235,7 @@ function isRepository(value: unknown): value is RunnerRepository { ) return false; const checkout = value.checkout; + if (checkout.kind === "default") return checkout.branch === undefined; if (!validBranch(checkout.branch)) return false; switch (checkout.kind) { case "new": From eecc777bda4fb6cf237d5950a7864b9eef039ae9 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:16:03 -0700 Subject: [PATCH 134/642] Revalidate archive cleanup on the owning runner --- apps/server/src/agents/acp/runtime.ts | 4 + apps/server/src/agents/archive-checkout.ts | 137 ++++++++ apps/server/src/agents/archive.ts | 296 +++++++++--------- apps/server/src/agents/checkout-inspection.ts | 138 +++++++- apps/server/src/agents/manager.ts | 104 ++++-- apps/server/src/agents/remote/runner.ts | 27 ++ apps/server/src/agents/remote/service.ts | 6 + .../src/agents/remote/session-supervisor.ts | 135 +++++++- apps/server/src/agents/runtime.ts | 2 + .../0059_archive_checkout_state.sql | 1 + apps/server/src/main.ts | 12 + apps/server/src/routes/agents/crud-routes.ts | 15 +- apps/server/src/shared/git/worktree-status.ts | 4 + apps/server/test/agent-archive.test.ts | 79 +++-- apps/server/test/db/agent-manager.test.ts | 68 +++- apps/server/test/migrations.test.ts | 6 + .../test/remote-runner-supervisor.test.ts | 87 +++++ .../test/runner-protocol-consumer.test.ts | 82 +++++ .../components/app/delete-agent-dialog.tsx | 86 +++-- apps/web/src/hooks/use-agent-actions.ts | 3 +- docs/design/runner-parity-rollout.md | 8 + e2e/remote-runner/acceptance.spec.ts | 14 +- e2e/worktree.spec.ts | 63 +++- packages/runner-protocol/README.md | 18 ++ packages/runner-protocol/src/checkout.ts | 68 ++++ packages/runner-protocol/src/connection.ts | 1 + packages/runner-protocol/src/execution.ts | 7 + 27 files changed, 1213 insertions(+), 258 deletions(-) create mode 100644 apps/server/src/agents/archive-checkout.ts create mode 100644 apps/server/src/db/migrations/0059_archive_checkout_state.sql diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 0ac0f78fb..51099efdb 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -1334,6 +1334,10 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { readLogTail, + async clearRemoteState(agentId) { + await rm(stateDir(agentId), { recursive: true, force: true }); + }, + async discard(agentId) { const placement = await placementOf(agentId); const operation = { kind: "discard", agentId } as const; diff --git a/apps/server/src/agents/archive-checkout.ts b/apps/server/src/agents/archive-checkout.ts new file mode 100644 index 000000000..222bda8bc --- /dev/null +++ b/apps/server/src/agents/archive-checkout.ts @@ -0,0 +1,137 @@ +import { realpath } from "node:fs/promises"; +import { + isCheckoutObservation, + remotePlacement, + type CheckoutObservation, + type CheckoutReleaseResult, +} from "@dispatch/runner-protocol"; +import type { Pool } from "pg"; +import { normalizePath } from "../shared/git/git-context.js"; +import { observeGitCheckout } from "./checkout-inspection.js"; +import { AgentError } from "./errors.js"; +import type { RemoteRunnerService } from "./remote/service.js"; +import type { AgentRecord, WorktreeCleanupMode } from "./types.js"; + +export type ArchiveCheckoutAgent = Pick< + AgentRecord, + "id" | "cwd" | "worktreePath" | "baseBranch" | "worktreeBranch" +>; + +export async function nativeBorrowers(pool: Pool, agent: ArchiveCheckoutAgent) { + const path = agent.worktreePath; + if (!path) return []; + const canonical = await realpath(path) + .then(normalizePath) + .catch(() => path); + const { rows } = await pool.query<{ id: string }>( + `SELECT id FROM agents + WHERE deleted_at IS NULL AND id <> $1 + AND (worktree_path = ANY($2::text[]) + OR workspace_path = ANY($2::text[]) + OR cwd = ANY($2::text[])) ORDER BY id`, + [agent.id, [...new Set([path, canonical])]] + ); + return rows.map(({ id }) => id); +} + +export async function observeArchiveCheckout( + pool: Pool, + agent: ArchiveCheckoutAgent, + remote?: RemoteRunnerService +): Promise { + const placement = remotePlacement(agent.cwd); + if (placement) { + if (!remote) + throw new AgentError("The session runner is unavailable.", 503); + const { value } = await remote.requestSession(placement, { + kind: "checkoutRelease", + agentId: agent.id, + operation: { kind: "observe" }, + }); + const observation: unknown = + typeof value === "string" ? JSON.parse(value) : null; + if (!isCheckoutObservation(observation)) + throw new AgentError( + "Invalid checkout observation from the runner.", + 502 + ); + return observation; + } + if (!agent.worktreePath) + return { + ownership: "external", + owner: null, + borrowers: [], + checkout: null, + }; + const [checkout, borrowers] = await Promise.all([ + observeGitCheckout(agent.worktreePath, agent.baseBranch), + nativeBorrowers(pool, agent), + ]); + return { ownership: "owned", owner: agent.id, borrowers, checkout }; +} + +export async function archiveCheckoutState(pool: Pool, id: string) { + const { rows } = await pool.query<{ archive_checkout_state: string | null }>( + "SELECT archive_checkout_state FROM agents WHERE id = $1", + [id] + ); + return rows[0]?.archive_checkout_state ?? null; +} + +export async function rememberArchiveCheckoutState( + pool: Pool, + id: string, + state: string +) { + await pool.query( + "UPDATE agents SET archive_checkout_state = $2 WHERE id = $1", + [id, state] + ); +} + +export async function releaseRemoteCheckout( + pool: Pool, + agent: ArchiveCheckoutAgent, + mode: WorktreeCleanupMode, + remote: RemoteRunnerService +): Promise { + const placement = remotePlacement(agent.cwd); + if (!placement) throw new Error("Missing remote runner placement."); + let expectedState = + mode === "keep" ? null : await archiveCheckoutState(pool, agent.id); + if (mode === "auto") { + const { checkout, ownership } = await observeArchiveCheckout( + pool, + agent, + remote + ); + if ( + ownership === "owned" && + checkout && + !checkout.unmerged && + !checkout.uncommittedFiles.length && + (expectedState === null || expectedState === checkout.stateId) + ) { + expectedState = checkout.stateId; + // Record the observation before sending a request that can outlive + // the connection or be deferred while a borrower still holds it. + await rememberArchiveCheckoutState(pool, agent.id, expectedState); + } else if (ownership === "owned") { + expectedState = null; + // Persist the keep decision across a lost reply or server restart. + await pool.query( + "UPDATE agents SET archive_cleanup_mode = 'keep' WHERE id = $1", + [agent.id] + ); + } + } + const { value } = await remote.requestSession(placement, { + kind: "checkoutRelease", + agentId: agent.id, + operation: { kind: "release", expectedState }, + }); + if (value !== "released" && value !== "retained" && value !== "inUse") + throw new Error("Invalid checkout release result from the runner."); + return value; +} diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index 94594dd9f..024981d80 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -1,15 +1,18 @@ -import { realpath } from "node:fs/promises"; - import type { FastifyBaseLogger } from "fastify"; import type { Pool } from "pg"; -import { normalizePath } from "../shared/git/git-context.js"; +import { MANAGED_WORKSPACE, remotePlacement } from "@dispatch/runner-protocol"; import { cleanupGitWorktree } from "../shared/git/worktree.js"; import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; import { - getUncommittedChanges, - getUnmergedChanges, -} from "../shared/git/worktree-status.js"; + archiveCheckoutState, + nativeBorrowers, + observeArchiveCheckout, + releaseRemoteCheckout, + rememberArchiveCheckoutState, + type ArchiveCheckoutAgent, +} from "./archive-checkout.js"; +import type { RemoteRunnerService } from "./remote/service.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; import { AgentError } from "./errors.js"; import type { AgentRuntime } from "./runtime.js"; @@ -24,6 +27,7 @@ export type ArchiveDeps = { pool: Pool; logger: FastifyBaseLogger; runtime: AgentRuntime; + remote?: RemoteRunnerService; diffStatsRefresher: { clear(agentId: string): void } | null; getAgent: (id: string) => Promise; getRequiredAgent: (id: string) => Promise; @@ -41,8 +45,8 @@ export type ArchiveDeps = { /** * Children go with the parent, worktrees included. The parent's confirmation is - * the one answer for the whole cascade, so children are never checked or asked - * about separately. + * the one answer for the whole cascade. Native children retain the legacy + * force policy. Runner-managed children use automatic cleanup. */ const CASCADED_CHILD_CLEANUP: WorktreeCleanupMode = "force"; @@ -91,150 +95,149 @@ async function withTimeout( } } -/** - * `force` always removes, `keep` never does, `auto` removes only a worktree - * holding nothing. Never throws — an unremovable worktree is left on disk. - */ -async function cleanupAgentWorktree( +/** Returns whether cleanup should be retried after archive. */ +export async function cleanupAgentWorktree( pool: Pool, logger: FastifyBaseLogger, - agent: AgentRecord, - cleanupWorktree: WorktreeCleanupMode, + agent: ArchiveCheckoutAgent, + mode: WorktreeCleanupMode, durations: Record, onCleanupStart?: () => Promise -): Promise { - if (!agent.worktreePath) return; - const id = agent.id; - const worktreePath = agent.worktreePath; - +): Promise { + const { id, worktreePath } = agent; + if (!worktreePath || remotePlacement(agent.cwd) || mode === "keep") + return false; const run = async () => { - // No uniqueness constraint on either column, so two live rows can name one - // worktree; removing it would take the other agent's work. Another agent - // that moved its workspace into this worktree counts too. Workspaces are - // stored as real paths while worktree_path keeps the path it was created - // under, so match both spellings (/tmp vs /private/tmp, symlinked roots). - const worktreeSpellings = [ - ...new Set([worktreePath, await realpathOrSelf(worktreePath)]), - ]; - const coOwner = await pool.query<{ id: string }>( - `SELECT id - FROM agents - WHERE deleted_at IS NULL - AND id <> $1 - AND (worktree_path = $2 - OR workspace_path = ANY($4::text[]) - OR (role = 'review' AND cwd = ANY($4::text[])) - OR ($3::text IS NOT NULL AND worktree_branch = $3)) - LIMIT 1`, - [id, worktreePath, agent.worktreeBranch, worktreeSpellings] - ); - if ((coOwner.rowCount ?? 0) > 0) { - logger.warn( - { - agentId: id, - worktreePath, - worktreeBranch: agent.worktreeBranch, - sharedWithAgentId: coOwner.rows[0]?.id, - }, - "Another live agent references this worktree; leaving it on disk." - ); - return; - } - - const tCheck = Date.now(); - let shouldCleanup = cleanupWorktree === "force"; - let preserveReason: string | undefined; - - if (!shouldCleanup && cleanupWorktree === "auto") { - const [unmerged, uncommitted] = await Promise.all([ - getUnmergedChanges(worktreePath), - getUncommittedChanges(worktreePath), - ]); - const hasChanges = - unmerged.hasUnmergedCommits || uncommitted.hasUncommittedChanges; - shouldCleanup = !hasChanges; - if (hasChanges) { - const reasons: string[] = []; - if (unmerged.hasUnmergedCommits) - reasons.push(`${unmerged.changedFiles.length} unmerged file(s)`); - if (uncommitted.hasUncommittedChanges) - reasons.push( - `${uncommitted.uncommittedFiles.length} uncommitted file(s)` - ); - preserveReason = reasons.join(", "); + const started = Date.now(); + let expectedState = await archiveCheckoutState(pool, id); + const borrowers = await nativeBorrowers(pool, agent); + // Preserve legacy explicit force requests, which predate observation IDs. + if (mode === "auto" || expectedState !== null || borrowers.length) { + const { checkout } = await observeArchiveCheckout(pool, agent); + if ( + !checkout || + (expectedState !== null && expectedState !== checkout.stateId) || + (mode === "auto" && + (checkout.unmerged || checkout.uncommittedFiles.length)) + ) + return false; + expectedState = checkout.stateId; + if (borrowers.length) { + await rememberArchiveCheckoutState(pool, id, expectedState); + return true; } - } else if (!shouldCleanup && cleanupWorktree === "keep") { - preserveReason = "user chose keep"; } - durations.outstandingChangesCheck = Date.now() - tCheck; - - if (shouldCleanup) { - await onCleanupStart?.(); - - const tCleanup = Date.now(); - const dispatchOwnsBranch = - !!agent.worktreeBranch && - (!agent.baseBranch || agent.worktreeBranch !== agent.baseBranch); - const boundedGit: CommandRunner = (command, args, options) => - runCommand(command, args, { - ...options, - timeoutMs: options?.timeoutMs ?? WORKTREE_CLEANUP_TIMEOUT_MS, - }); - await cleanupGitWorktree( - { - cwd: worktreePath, - deleteBranch: dispatchOwnsBranch, - force: true, - originalBranch: agent.worktreeBranch, - }, - boundedGit - ); - durations.worktreeCleanup = Date.now() - tCleanup; - logger.info( - { agentId: id, worktreePath: worktreePath }, - "Cleaned up agent worktree." - ); - } else { - logger.info( - { - agentId: id, - worktreePath: worktreePath, - cleanupWorktree, - preserveReason, - }, - `Preserved agent worktree: ${preserveReason}.` - ); + durations.outstandingChangesCheck = Date.now() - started; + await onCleanupStart?.(); + if ((await nativeBorrowers(pool, agent)).length) { + if (expectedState === null) return false; + await rememberArchiveCheckoutState(pool, id, expectedState); + return true; + } + // Re-read after publishing the phase, including any file edited since the + // confirmation. Git is run by the built-in runner on this machine. + if (mode === "auto" || expectedState !== null) { + const { checkout } = await observeArchiveCheckout(pool, agent); + if ( + !checkout || + (expectedState !== null && checkout.stateId !== expectedState) || + (mode === "auto" && + (checkout.unmerged || checkout.uncommittedFiles.length)) + ) + return false; } + // A timed-out observation must never start removal in the background. + if (Date.now() - started >= WORKTREE_CLEANUP_TIMEOUT_MS) return false; + const boundedGit: CommandRunner = (command, args, options) => + runCommand(command, args, { + ...options, + timeoutMs: options?.timeoutMs ?? WORKTREE_CLEANUP_TIMEOUT_MS, + }); + const cleanupStarted = Date.now(); + await cleanupGitWorktree( + { + cwd: worktreePath, + deleteBranch: + !!agent.worktreeBranch && + (!agent.baseBranch || agent.worktreeBranch !== agent.baseBranch), + force: true, + originalBranch: agent.worktreeBranch, + }, + boundedGit + ); + durations.worktreeCleanup = Date.now() - cleanupStarted; + return false; }; - - // Cleanup never fails the archive around it — siblings still have to run. try { - await withTimeout( + return await withTimeout( run(), WORKTREE_CLEANUP_TIMEOUT_MS, - `Worktree cleanup timed out after ${WORKTREE_CLEANUP_TIMEOUT_MS}ms` + "Worktree cleanup timed out" ); - } catch (error) { + } catch (err) { logger.warn( - { err: error, agentId: id, worktreePath }, + { err, agentId: id, worktreePath }, "Worktree cleanup failed; leaving on disk." ); + return false; + } +} + +function managedCheckout(agent: Pick) { + return ( + Boolean(agent.runnerManaged) || + remotePlacement(agent.cwd)?.workspace === MANAGED_WORKSPACE + ); +} + +async function finishCheckout( + deps: ArchiveDeps, + agent: AgentRecord, + mode: WorktreeCleanupMode, + stopped: boolean, + durations: Record, + onCleanupStart?: () => Promise +) { + if (!managedCheckout(agent)) { + return cleanupAgentWorktree( + deps.pool, + deps.logger, + agent, + mode, + durations, + onCleanupStart + ); + } + if (!stopped || !deps.remote) return true; + try { + await onCleanupStart?.(); + return ( + (await releaseRemoteCheckout(deps.pool, agent, mode, deps.remote)) === + "inUse" + ); + } catch (err) { + deps.logger.warn( + { err, agentId: agent.id }, + "Runner checkout release remains pending." + ); + return true; } } export async function beginArchive( deps: ArchiveDeps, id: string, - cleanupWorktree: WorktreeCleanupMode = "auto" + cleanupWorktree: WorktreeCleanupMode = "auto", + checkoutState: string | null = null ): Promise { const { pool } = deps; const result = await pool.query( `UPDATE agents - SET status = 'archiving', archive_phase = 'stopping', archive_cleanup_mode = $2, updated_at = NOW() + SET status = 'archiving', archive_phase = 'stopping', archive_cleanup_mode = $2, archive_checkout_state = $3, updated_at = NOW() WHERE id = $1 AND deleted_at IS NULL AND status != 'archiving' RETURNING id`, - [id, cleanupWorktree] + [id, cleanupWorktree, checkoutState] ); if (result.rowCount === 0) { @@ -264,7 +267,7 @@ export async function executeArchive( try { const agent = await deps.getRequiredAgent(id); const cleanupWorktree = agent.archiveCleanupMode ?? "auto"; - let runnerCleanupPending = Boolean(agent.runnerManaged); + let stopped = false; // Phase: stopping — tear down session without changing agent status const t = Date.now(); @@ -280,8 +283,9 @@ export async function executeArchive( await deps.settleStream(id); // The state directory holds the launch file with the MCP token; the // stream is already in the database. - await runtime.discard(id); - runnerCleanupPending = false; + if (managedCheckout(agent)) await runtime.clearRemoteState?.(id); + else await runtime.discard(id); + stopped = true; } catch (err) { logger.warn( { err, agentId: id }, @@ -325,11 +329,11 @@ export async function executeArchive( // Phase: worktree-check await publishPhase("worktree-check"); - await cleanupAgentWorktree( - pool, - logger, + const runnerCleanupPending = await finishCheckout( + deps, agent, cleanupWorktree, + stopped, durations, () => publishPhase("worktree-cleanup") ); @@ -340,7 +344,7 @@ export async function executeArchive( const tDb = Date.now(); await pool.query( - "UPDATE agents SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = NULL, runner_cleanup_pending = $2, updated_at = NOW() WHERE id = $1", + "UPDATE agents SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = CASE WHEN $2 THEN archive_cleanup_mode END, archive_checkout_state = CASE WHEN $2 THEN archive_checkout_state END, runner_cleanup_pending = $2, updated_at = NOW() WHERE id = $1", [id, runnerCleanupPending] ); durations.db = Date.now() - tDb; @@ -384,14 +388,15 @@ export async function deleteAgentDirect( const durations: Record = {}; const agent = await deps.getRequiredAgent(id); + const mode = managedCheckout(agent) ? "auto" : CASCADED_CHILD_CLEANUP; // Claim before any teardown — an agent's own archive and an ancestor's // cascade can reach it at once. Same CAS `beginArchive` takes. const claimed = await pool.query( `UPDATE agents - SET status = 'archiving', archive_phase = 'stopping', updated_at = NOW() + SET status = 'archiving', archive_phase = 'stopping', archive_cleanup_mode = $2, updated_at = NOW() WHERE id = $1 AND deleted_at IS NULL AND status != 'archiving' RETURNING id`, - [id] + [id, mode] ); if (claimed.rowCount === 0) { logger.info( @@ -401,8 +406,8 @@ export async function deleteAgentDirect( return []; } - let runnerCleanupPending = Boolean(agent.runnerManaged); - if (agent.status !== "stopped" || runnerCleanupPending) { + let stopped = false; + if (agent.status !== "stopped" || managedCheckout(agent)) { const t = Date.now(); // Not stopAgent: it writes `stopping`/`stopped`, releasing the claim above // and letting a fresh archive take this agent mid-teardown. @@ -418,8 +423,9 @@ export async function deleteAgentDirect( await deps.settleStream(id); // The state directory holds the launch file with the MCP token; the // stream is already in the database. - await runtime.discard(id); - runnerCleanupPending = false; + if (managedCheckout(agent)) await runtime.clearRemoteState?.(id); + else await runtime.discard(id); + stopped = true; } catch (err) { logger.warn( { err, agentId: id }, @@ -460,17 +466,17 @@ export async function deleteAgentDirect( const tDb = Date.now(); // Keeping it would leave a worktree no agent record can reach. - await cleanupAgentWorktree( - pool, - logger, + const runnerCleanupPending = await finishCheckout( + deps, agent, - CASCADED_CHILD_CLEANUP, + mode, + stopped, durations ); await pool.query( `UPDATE agents - SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = NULL, runner_cleanup_pending = $2, updated_at = NOW() + SET deleted_at = NOW(), archive_phase = NULL, archive_cleanup_mode = CASE WHEN $2 THEN archive_cleanup_mode END, archive_checkout_state = CASE WHEN $2 THEN archive_checkout_state END, runner_cleanup_pending = $2, updated_at = NOW() WHERE id = $1`, [id, runnerCleanupPending] ); @@ -479,11 +485,3 @@ export async function deleteAgentDirect( return deletedIds; } - -async function realpathOrSelf(dir: string): Promise { - try { - return normalizePath(await realpath(dir)); - } catch { - return dir; - } -} diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index 6f09c7b04..2aa31ba9a 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -6,13 +6,15 @@ import { openLinuxDirectory, } from "../files/open-workspace-file.js"; import { constants } from "node:fs"; -import { lstat, open, readlink, realpath } from "node:fs/promises"; +import { lstat, open, readdir, readlink, realpath } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { isCheckoutQuery, type CheckoutQuery, type CheckoutReply, + type CheckoutState, + validBranch, } from "@dispatch/runner-protocol"; import { @@ -329,6 +331,140 @@ async function inspectChanges(root: string, baseBranch: string | null) { }; } +export async function observeScratchCheckout( + dir: string +): Promise { + const root = await realpath(dir); + const identity = await lstat(root); + const directories: string[] = []; + const files: string[] = []; + let entriesSeen = 0; + async function collect(relative: string): Promise { + for (const entry of await readdir(path.join(root, relative), { + withFileTypes: true, + })) { + if (++entriesSeen > MAX_FINGERPRINT_FILES) + throw new Error("Too many scratch checkout entries to fingerprint"); + const name = path.join(relative, entry.name); + if (entry.isDirectory()) { + directories.push(name); + await collect(name); + } else { + if (!entry.isFile() && !entry.isSymbolicLink()) + throw new Error("Unsupported scratch checkout entry"); + files.push(name); + } + } + } + await collect(""); + const stateId = await fingerprintCheckout( + root, + JSON.stringify([root, identity.dev, identity.ino, directories.sort()]), + "", + "", + "", + [], + files + ); + return { + path: root, + branch: null, + stateId, + unmerged: false, + changedFiles: [], + uncommittedFiles: [...directories, ...files].sort(), + }; +} + +/** Strict observation for deletion. Any Git or fingerprint failure is unknown. */ +export async function observeGitCheckout( + dir: string, + baseBranch: string | null = null +): Promise { + if (baseBranch !== null && !validBranch(baseBranch)) + throw new Error("Invalid checkout base branch"); + const root = await realpath(dir); + const cwd = { cwd: root, trimOutput: false }; + const top = await run("git", ["rev-parse", "--show-toplevel"], cwd); + if (top.stdout.replace(/\n$/, "") !== root) + throw new Error("The bound directory is not a Git checkout root"); + const identity = await lstat(root); + baseBranch ??= await recordedReviewBase(root); + const options = { + runCommand: run, + allowUpstreamFallback: baseBranch === null, + }; + await refreshRemoteBaseRef(root, baseBranch, options); + const baseRef = await resolveBaseRef(root, baseBranch, options); + if ( + !baseRef || + (baseBranch && baseRef !== baseBranch && baseRef !== `origin/${baseBranch}`) + ) + throw new Error("Could not resolve the checkout base"); + const [{ stdout: head }, { stdout: base }, branch] = await Promise.all([ + run("git", ["rev-parse", "--verify", "HEAD"], { cwd: root }), + run("git", ["rev-parse", "--verify", `${baseRef}^{commit}`], { cwd: root }), + run("git", ["symbolic-ref", "--short", "--quiet", "HEAD"], { + cwd: root, + allowedExitCodes: [0, 1], + }), + ]); + const [changes, staged, conflicts, merge, baseTree] = await Promise.all([ + collectOwnerReviewChanges(root, base, run, head), + run( + "git", + ["diff", "--cached", "--raw", "--no-abbrev", "-z", head, "--"], + cwd + ), + run("git", ["ls-files", "--unmerged", "-z"], cwd), + run("git", ["merge-tree", "--write-tree", base, head], { + cwd: root, + allowedExitCodes: [0, 1], + }), + run("git", ["rev-parse", "--verify", `${base}^{tree}`], { cwd: root }), + ]); + const unpublishedHistory = + changes.committed.length === 0 && + ( + await run("git", ["merge-base", "--is-ancestor", head, base], { + cwd: root, + allowedExitCodes: [0, 1], + }) + ).exitCode === 1; + const unmerged = + unpublishedHistory || + merge.exitCode !== 0 || + merge.stdout.split("\n")[0] !== baseTree.stdout; + const state = await fingerprintCheckout( + root, + base, + head, + staged.stdout, + conflicts.stdout, + changes.unstaged, + changes.untracked + ); + const stateId = createHash("sha256") + .update( + JSON.stringify([root, identity.dev, identity.ino, branch.stdout, state]) + ) + .digest("hex"); + return { + path: root, + branch: branch.exitCode === 0 ? branch.stdout : null, + stateId, + unmerged, + changedFiles: unmerged ? changes.committed : [], + uncommittedFiles: [ + ...new Set([ + ...changes.staged, + ...changes.unstaged, + ...changes.untracked, + ]), + ].sort(), + }; +} + function encodeReply(reply: CheckoutReply): string { const encoded = JSON.stringify(reply) + "\n"; if (Buffer.byteLength(encoded) > MAX_REPLY_BYTES) { diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 91624e8af..4952a8c84 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -25,7 +25,6 @@ import { GitWorktreeError, normalizeBaseBranch, } from "../shared/git/worktree.js"; -import { readWorktreeStatus } from "../shared/git/worktree-status.js"; import { resolveFilesDir } from "../shared/files.js"; import { getDirectoryIconPath } from "../shared/directory-icon-cache.js"; import { @@ -36,9 +35,15 @@ import { getActivePersonality } from "../db/personalities.js"; import { errorMessage } from "../shared/lib/error-message.js"; import { beginArchive as beginArchiveImpl, + cleanupAgentWorktree, executeArchive as executeArchiveImpl, type ArchiveDeps, } from "./archive.js"; +import { + observeArchiveCheckout, + releaseRemoteCheckout, + type ArchiveCheckoutAgent, +} from "./archive-checkout.js"; import { AgentError } from "./errors.js"; import { type AgentEventBus, createAgentEventBus } from "./events.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; @@ -2699,7 +2704,8 @@ export class AgentManager { async beginArchive( id: string, - cleanupWorktree: WorktreeCleanupMode = "auto" + cleanupWorktree: WorktreeCleanupMode = "auto", + checkoutState: string | null = null ): Promise { await this.cancelSchedules?.(id).catch((err) => this.logger.warn( @@ -2707,7 +2713,12 @@ export class AgentManager { "could not cancel scheduled messages" ) ); - return beginArchiveImpl(this.archiveDeps(), id, cleanupWorktree); + return beginArchiveImpl( + this.archiveDeps(), + id, + cleanupWorktree, + checkoutState + ); } async executeArchive( @@ -2724,19 +2735,34 @@ export class AgentManager { async checkWorktreeStatus(id: string): Promise { const agent = await this.getRequiredAgent(id); - if (!agent.worktreePath) { - return { - hasWorktree: false, - hasUnmergedCommits: false, - hasUncommittedChanges: false, - worktreePath: null, - branchName: null, - changedFiles: [], - uncommittedFiles: [], - }; + let observation; + try { + observation = await observeArchiveCheckout(this.pool, agent, this.remote); + } catch { + throw new AgentError( + "Checkout status is unavailable on the owning runner.", + 503 + ); } - - return readWorktreeStatus(agent.worktreePath); + const { checkout, ownership, owner, borrowers } = observation; + if (ownership === "owned" && !checkout) + throw new AgentError( + "Checkout status is unavailable on the owning runner.", + 503 + ); + return { + ownership, + owner, + borrowers, + checkoutState: checkout?.stateId, + hasWorktree: checkout !== null, + hasUnmergedCommits: checkout?.unmerged ?? false, + hasUncommittedChanges: Boolean(checkout?.uncommittedFiles.length), + worktreePath: checkout?.path ?? null, + branchName: checkout?.branch ?? null, + changedFiles: checkout?.changedFiles ?? [], + uncommittedFiles: checkout?.uncommittedFiles ?? [], + }; } /** Run the existing recorder before DB startup as well as on reconcile ticks. */ @@ -2768,22 +2794,49 @@ export class AgentManager { private runnerCleanupRunning = false; private async retryRunnerCleanup(): Promise { - if (!this.remote || this.runnerCleanupRunning) return; + if (this.runnerCleanupRunning) return; // Offline cleanup must never delay the status reconciliation loop. this.runnerCleanupRunning = true; try { - const { rows } = await this.pool.query<{ id: string; cwd: string }>( - "SELECT id, cwd FROM agents WHERE runner_cleanup_pending AND deleted_at IS NOT NULL ORDER BY id" + const { rows } = await this.pool.query< + ArchiveCheckoutAgent & { + mode: WorktreeCleanupMode | null; + } + >( + `SELECT id, cwd, worktree_path AS "worktreePath", base_branch AS "baseBranch", + worktree_branch AS "worktreeBranch", archive_cleanup_mode AS mode + FROM agents WHERE runner_cleanup_pending AND deleted_at IS NOT NULL ORDER BY id` ); - for (const { id, cwd } of rows) { - const placement = remotePlacement(cwd); - if (!placement || !this.remote.isManagedWorkspace(placement)) continue; + for (const agent of rows) { + const { id, cwd, mode } = agent; try { - await this.runtime.stop(id, true); - await this.streamRecorder.settleStopped(id); - await this.runtime.discard(id); + if (remotePlacement(cwd)) { + if (!this.remote) continue; + await this.runtime.stop(id, true); + await this.streamRecorder.settleStopped(id); + await this.runtime.clearRemoteState?.(id); + if ( + (await releaseRemoteCheckout( + this.pool, + agent, + mode ?? "auto", + this.remote + )) === "inUse" + ) + continue; + } else if ( + await cleanupAgentWorktree( + this.pool, + this.logger, + agent, + mode ?? "auto", + {} + ) + ) { + continue; + } await this.pool.query( - "UPDATE agents SET runner_cleanup_pending = false WHERE id = $1", + "UPDATE agents SET runner_cleanup_pending = false, archive_cleanup_mode = NULL, archive_checkout_state = NULL WHERE id = $1", [id] ); } catch (err) { @@ -2969,6 +3022,7 @@ export class AgentManager { pool: this.pool, logger: this.logger, runtime: this.runtime, + remote: this.remote, diffStatsRefresher: this.diffStatsRefresher, getAgent: (id) => this.getAgent(id), getRequiredAgent: (id) => this.getRequiredAgent(id), diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 1f9bce505..a156d0707 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -244,6 +244,19 @@ export async function runRemoteRunner(filename: string) { env, workspaces: new Set(configuredHandles), asWorkload, + async observeCheckout(cwd, scratch) { + const { stdout } = await execute( + setpriv, + [ + ...childArgs, + ...selfCommand("runner-observe-checkout"), + cwd, + ...(scratch ? ["--scratch"] : []), + ], + { env, timeout: 90_000, maxBuffer: 4 * 1024 * 1024 } + ); + return JSON.parse(stdout); + }, async prepareDependencies(cwd) { await execute( setpriv, @@ -447,6 +460,19 @@ export async function runRemoteRunner(filename: string) { } if (socket.destroyed) return; switch (command.kind) { + case "checkoutRelease": { + const observation = await supervisor.checkoutRelease( + agentId, + workspace, + command.operation + ); + result( + typeof observation === "string" + ? observation + : JSON.stringify(observation) + ); + break; + } case "sessionCheckout": result( JSON.stringify( @@ -661,6 +687,7 @@ export async function runRemoteRunner(filename: string) { checkoutInspection: true, workspacePreparation: true, sessionCheckout: true, + checkoutRelease: true, checkoutViews: true, sharedWorktree: true, }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index b983c2712..3a11ce088 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -162,6 +162,7 @@ type Peer = { pullRequestEvidence: boolean; checkoutInspection: boolean; sessionCheckout: boolean; + checkoutRelease: boolean; checkoutViews: boolean; sharedWorktree: boolean; workspacePreparation: boolean; @@ -690,6 +691,7 @@ export class RemoteRunnerService { githubManagement: ready.githubManagement === true, checkoutViews: ready.checkoutViews === true, sessionCheckout: ready.sessionCheckout === true, + checkoutRelease: ready.checkoutRelease === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, workspacePreparation: ready.workspacePreparation === true, @@ -1551,6 +1553,10 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to use these checkout options." ); + if (command.kind === "checkoutRelease" && !peer.checkoutRelease) + throw new RunnerCapabilityUnavailable( + "Update the runner to inspect and release a session checkout." + ); if (command.kind === "inspectCheckout" && !peer.checkoutInspection) throw new RunnerCapabilityUnavailable( "Update the runner to inspect a session checkout." diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 41afeff15..3cdfa62ee 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -22,6 +22,10 @@ import { isOpaqueId, isCheckoutPath, type SessionCheckout, + type CheckoutObservation, + type CheckoutRelease, + type CheckoutReleaseResult, + type CheckoutState, type SessionOperation, type Command, type LaunchProgress, @@ -68,6 +72,7 @@ type SupervisorOptions = { workspaces: ReadonlySet; hostCommand: () => string[]; asWorkload: WorkloadCommand; + observeCheckout?: (cwd: string, scratch: boolean) => Promise; prepareDependencies?: (cwd: string) => Promise; }; @@ -216,6 +221,7 @@ export async function createSessionSupervisor( } const readBinding = (key: string) => readOptional(path.join(bindings, key)); + const releaseFile = (key: string) => path.join(bindings, `${key}.released`); const retireFile = (key: string) => path.join(bindings, `${key}.retired`); const repositoryFile = (key: string) => path.join(bindings, `${key}.repository`); @@ -433,19 +439,123 @@ export async function createSessionSupervisor( return { path: dir, moved: dir !== initial, origin }; } - async function hasBorrowers(key: string) { + async function checkoutBorrowers(key: string) { + const borrowers: string[] = []; for (const entry of await readdir(bindings)) { if ( storageKeyPattern.test(entry) && checkoutOwner(await readBinding(entry)) === key ) - return true; + borrowers.push(entry); } - return false; + return borrowers.sort(); + } + + async function describeOwnedState(key: string): Promise { + const dir = await managedDirectory(key); + if (!config.observeCheckout) + throw new Error("Checkout observation is unavailable."); + const scratch = (await readOptional(repositoryFile(key))) === "null"; + return config.observeCheckout(dir, scratch); + } + + async function observeRelease( + key: string, + workspace: string + ): Promise { + const binding = await readBinding(key); + if (binding === null) { + if ( + managedTarget(workspace) && + ((await lstat(path.join(sessions, key)).catch(missingPath)) || + (await readOptional(repositoryFile(key))) !== null) + ) + throw new Error("The runner session binding is unavailable."); + return { ownership: "none", owner: null, borrowers: [], checkout: null }; + } + if (!matchesWorkspace(binding, workspace)) + throw new Error("Agent is not bound to this workspace"); + if (!managedTarget(workspace)) + return { + ownership: "external", + owner: null, + borrowers: [], + checkout: null, + }; + const owner = checkoutOwner(binding) ?? key; + return { + ownership: owner === key ? "owned" : "borrowed", + owner, + borrowers: await checkoutBorrowers(owner), + checkout: await describeOwnedState(owner).catch(() => null), + }; + } + + async function releaseCheckout( + key: string, + workspace: string, + expectedState: string | null + ): Promise { + const binding = await readBinding(key); + const receipt = await readOptional(releaseFile(key)); + if (receipt === "retained") return "retained"; + if (binding === null) { + // Fence a delayed managed launch even if it never registered a binding. + if (managedTarget(workspace)) { + if ( + (await lstat(path.join(sessions, key)).catch(missingPath)) || + (await readOptional(repositoryFile(key))) !== null + ) + throw new Error("The runner session binding is unavailable."); + await writePrivateState(retireFile(key), ""); + } + return "released"; + } + if (!matchesWorkspace(binding, workspace)) + throw new Error("Agent is not bound to this workspace"); + const identity = await readIdentity(key); + if (identity && processes.alive(identity)) + throw new Error("Stop the guest host before releasing it"); + const managed = managedTarget(workspace); + if (managed) await writePrivateState(retireFile(key), ""); + const dir = path.join(hostRoot, key); + await cleanHost(key, identity); + checkUntrackedSocket(dir); + await cleanLegacyHost(key); + await removeGuestDirectory(dir); + if (managed) await rm(path.join(logs, key), { force: true }); + if (binding === managedBinding) { + const session = path.join(sessions, key); + // Resume interrupted unregister after the checkout directory was removed. + const removed = + receipt === "removing" && !(await lstat(session).catch(missingPath)); + if (!removed) { + const observed = + expectedState === null + ? null + : await describeOwnedState(key).catch(() => null); + if (observed?.stateId !== expectedState || expectedState === null) { + await writePrivateState(releaseFile(key), "retained"); + return "retained"; + } + if ((await checkoutBorrowers(key)).length > 0) return "inUse"; + await writePrivateState(releaseFile(key), "removing"); + } + await discardManagedCheckout(key); + } + for (const file of [ + cwdFile(key), + selectedFile(key), + borrowedFile(key), + path.join(bindings, key), + ]) + await rm(file, { force: true }); + await syncBindings(); + return "released"; } async function discardManagedCheckout(key: string) { - if (await hasBorrowers(key)) + if ((await checkoutBorrowers(key)).length > 0) throw new Error("Runner checkout is still in use by a borrower."); const session = path.join(sessions, key); const stored = await readOptional(repositoryFile(key)); @@ -764,6 +874,21 @@ export async function createSessionSupervisor( return launch(command, cwd, key, owner, progress); }); }, + async checkoutRelease( + agentId: string, + workspace: string, + operation: CheckoutRelease + ) { + const key = runnerStorageKey(agentId); + const owner = checkoutOwner(await readBinding(key)) ?? key; + return withLaunchLocks([key, owner], async () => { + if ((checkoutOwner(await readBinding(key)) ?? key) !== owner) + throw new Error("The checkout binding changed; retry the request."); + return operation.kind === "observe" + ? observeRelease(key, workspace) + : releaseCheckout(key, workspace, operation.expectedState); + }); + }, checkoutDirectory( agentId: string, workspace: string, @@ -895,6 +1020,8 @@ export async function createSessionSupervisor( discard(agentId: string, workspace: string) { const key = runnerStorageKey(agentId); return serialize(key, async () => { + if ((await readOptional(releaseFile(key))) === "retained") + throw new Error("The checkout was retained."); const managed = managedTarget(workspace); if (!(await bound(key, workspace))) { if (managed && (await readBinding(key)) === null) { diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index 92529e177..1335db1ad 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -135,6 +135,8 @@ export type AgentRuntime = { readLogTail(agentId: string): Promise; /** Remove the agent's state directory (archive). */ discard(agentId: string): Promise; + /** Clear Dispatch-side delivery state after stopping a remote host. */ + clearRemoteState?(agentId: string): Promise; }; export function createAgentRuntime( diff --git a/apps/server/src/db/migrations/0059_archive_checkout_state.sql b/apps/server/src/db/migrations/0059_archive_checkout_state.sql new file mode 100644 index 000000000..13703e093 --- /dev/null +++ b/apps/server/src/db/migrations/0059_archive_checkout_state.sql @@ -0,0 +1 @@ +ALTER TABLE agents ADD COLUMN archive_checkout_state text; diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index ff9da5adb..f66e856ca 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -57,6 +57,18 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "runner-view-checkout") { const { runCheckoutViewCli } = await import("./agents/checkout-view-cli.js"); await runCheckoutViewCli(process.argv[3]!, process.argv[4] === "--managed"); +} else if (process.argv[2] === "runner-observe-checkout") { + const { observeGitCheckout, observeScratchCheckout } = + await import("./agents/checkout-inspection.js"); + try { + const observe = + process.argv[4] === "--scratch" + ? observeScratchCheckout + : observeGitCheckout; + process.stdout.write(JSON.stringify(await observe(process.argv[3]!))); + } catch { + process.exitCode = 1; + } } else if (process.argv[2] === "runner-inspect-checkout") { const { runCheckoutInspectionCli } = await import("./agents/checkout-inspection.js"); diff --git a/apps/server/src/routes/agents/crud-routes.ts b/apps/server/src/routes/agents/crud-routes.ts index 93e42fd88..273f6dc28 100644 --- a/apps/server/src/routes/agents/crud-routes.ts +++ b/apps/server/src/routes/agents/crud-routes.ts @@ -1,3 +1,4 @@ +import { isCheckoutStateId } from "@dispatch/runner-protocol"; import { MANAGED_WORKSPACE, remotePlacement, @@ -476,7 +477,10 @@ export async function registerAgentCrudRoutes( app.delete("/api/v1/agents/:id", async (request, reply) => { const params = request.params as { id?: unknown }; - const query = request.query as { cleanupWorktree?: unknown }; + const query = request.query as { + cleanupWorktree?: unknown; + checkoutState?: unknown; + }; if (typeof params.id !== "string") { return reply.code(400).send({ error: "Missing agent id." }); @@ -490,10 +494,17 @@ export async function registerAgentCrudRoutes( ? (query.cleanupWorktree as CleanupMode) : "auto"; + if ( + query.checkoutState !== undefined && + !isCheckoutStateId(query.checkoutState) + ) + return reply.code(400).send({ error: "Invalid checkout state." }); + try { const agent = await deps.agentManager.beginArchive( params.id, - cleanupWorktree + cleanupWorktree, + ...(isCheckoutStateId(query.checkoutState) ? [query.checkoutState] : []) ); deps.publishUiEvent({ type: "agent.upsert", diff --git a/apps/server/src/shared/git/worktree-status.ts b/apps/server/src/shared/git/worktree-status.ts index bb0398b69..69b1203e1 100644 --- a/apps/server/src/shared/git/worktree-status.ts +++ b/apps/server/src/shared/git/worktree-status.ts @@ -3,6 +3,10 @@ import { runCommand } from "../lib/run-command.js"; export type WorktreeStatus = { hasWorktree: boolean; + ownership?: "owned" | "borrowed" | "external" | "none"; + owner?: string | null; + borrowers?: string[]; + checkoutState?: string; hasUnmergedCommits: boolean; hasUncommittedChanges: boolean; worktreePath: string | null; diff --git a/apps/server/test/agent-archive.test.ts b/apps/server/test/agent-archive.test.ts index 1dd97e4d1..9785e9793 100644 --- a/apps/server/test/agent-archive.test.ts +++ b/apps/server/test/agent-archive.test.ts @@ -25,23 +25,22 @@ vi.mock("../src/shared/git/worktree.js", () => ({ cleanupGitWorktree: vi.fn().mockResolvedValue(undefined), })); -vi.mock("../src/shared/git/worktree-status.js", () => ({ - getUnmergedChanges: vi.fn().mockResolvedValue({ - hasUnmergedCommits: false, - changedFiles: [], - }), - getUncommittedChanges: vi.fn().mockResolvedValue({ - hasUncommittedChanges: false, - uncommittedFiles: [], - }), +vi.mock("../src/agents/checkout-inspection.js", () => ({ + observeGitCheckout: vi.fn(), })); import { runLifecycleHook } from "../src/agents/lifecycle-hooks.js"; import { cleanupGitWorktree } from "../src/shared/git/worktree.js"; -import { - getUnmergedChanges, - getUncommittedChanges, -} from "../src/shared/git/worktree-status.js"; +import { observeGitCheckout } from "../src/agents/checkout-inspection.js"; + +const cleanCheckout = { + path: "/tmp/wt", + branch: "feature", + stateId: "a".repeat(64), + unmerged: false, + changedFiles: [], + uncommittedFiles: [], +}; // ── Helpers ───────────────────────────────────────────────────────────── @@ -159,7 +158,7 @@ describe("beginArchive", () => { expect(result).toBe(agent); expect(pool.query).toHaveBeenCalledWith( expect.stringContaining("UPDATE agents"), - ["a1", "auto"] + ["a1", "auto", null] ); }); @@ -174,7 +173,7 @@ describe("beginArchive", () => { expect(pool.query).toHaveBeenCalledWith( expect.stringContaining("UPDATE agents"), - ["a1", "force"] + ["a1", "force", null] ); }); @@ -217,7 +216,11 @@ describe("beginArchive", () => { await beginArchive(deps, "a1"); - expect(pool.query).toHaveBeenCalledWith(expect.any(String), ["a1", "auto"]); + expect(pool.query).toHaveBeenCalledWith(expect.any(String), [ + "a1", + "auto", + null, + ]); }); }); @@ -226,14 +229,7 @@ describe("beginArchive", () => { describe("executeArchive", () => { beforeEach(() => { vi.clearAllMocks(); - vi.mocked(getUnmergedChanges).mockResolvedValue({ - hasUnmergedCommits: false, - changedFiles: [], - }); - vi.mocked(getUncommittedChanges).mockResolvedValue({ - hasUncommittedChanges: false, - uncommittedFiles: [], - }); + vi.mocked(observeGitCheckout).mockResolvedValue(cleanCheckout); }); describe("phase transitions", () => { @@ -310,8 +306,9 @@ describe("executeArchive", () => { }); it("preserves the worktree when there are unmerged commits", async () => { - vi.mocked(getUnmergedChanges).mockResolvedValue({ - hasUnmergedCommits: true, + vi.mocked(observeGitCheckout).mockResolvedValue({ + ...cleanCheckout, + unmerged: true, changedFiles: ["file1.ts", "file2.ts"], }); const agent = makeAgent("a1", { @@ -331,8 +328,8 @@ describe("executeArchive", () => { }); it("preserves the worktree when there are uncommitted changes", async () => { - vi.mocked(getUncommittedChanges).mockResolvedValue({ - hasUncommittedChanges: true, + vi.mocked(observeGitCheckout).mockResolvedValue({ + ...cleanCheckout, uncommittedFiles: ["dirty.ts"], }); const agent = makeAgent("a1", { @@ -352,12 +349,10 @@ describe("executeArchive", () => { }); it("preserves worktree when both unmerged and uncommitted changes exist", async () => { - vi.mocked(getUnmergedChanges).mockResolvedValue({ - hasUnmergedCommits: true, + vi.mocked(observeGitCheckout).mockResolvedValue({ + ...cleanCheckout, + unmerged: true, changedFiles: ["a.ts"], - }); - vi.mocked(getUncommittedChanges).mockResolvedValue({ - hasUncommittedChanges: true, uncommittedFiles: ["b.ts"], }); const agent = makeAgent("a1", { @@ -379,8 +374,9 @@ describe("executeArchive", () => { describe("worktree cleanup decision — force mode", () => { it("always cleans up when mode is force, even with outstanding changes", async () => { - vi.mocked(getUnmergedChanges).mockResolvedValue({ - hasUnmergedCommits: true, + vi.mocked(observeGitCheckout).mockResolvedValue({ + ...cleanCheckout, + unmerged: true, changedFiles: ["file.ts"], }); const agent = makeAgent("a1", { @@ -398,7 +394,7 @@ describe("executeArchive", () => { await executeArchive(deps, "a1", makeCallbacks()); expect(cleanupGitWorktree).toHaveBeenCalled(); - expect(getUnmergedChanges).not.toHaveBeenCalled(); + expect(observeGitCheckout).not.toHaveBeenCalled(); }); }); @@ -418,8 +414,7 @@ describe("executeArchive", () => { await executeArchive(deps, "a1", makeCallbacks()); expect(cleanupGitWorktree).not.toHaveBeenCalled(); - expect(getUnmergedChanges).not.toHaveBeenCalled(); - expect(getUncommittedChanges).not.toHaveBeenCalled(); + expect(observeGitCheckout).not.toHaveBeenCalled(); }); }); @@ -525,7 +520,7 @@ describe("executeArchive", () => { await executeArchive(deps, "a1", makeCallbacks()); expect(cleanupGitWorktree).not.toHaveBeenCalled(); - expect(getUnmergedChanges).not.toHaveBeenCalled(); + expect(observeGitCheckout).not.toHaveBeenCalled(); }); }); @@ -848,8 +843,8 @@ describe("executeArchive", () => { worktreePath: "/tmp/wt-child", worktreeBranch: "agt/child", }); - vi.mocked(getUncommittedChanges).mockResolvedValue({ - hasUncommittedChanges: true, + vi.mocked(observeGitCheckout).mockResolvedValue({ + ...cleanCheckout, uncommittedFiles: ["src/wip.ts"], }); @@ -915,7 +910,7 @@ describe("executeArchive", () => { }); const pool = makePool(async (sql: string, params?: unknown[]) => { - if (sql.includes("worktree_path = $2")) { + if (sql.includes("worktree_path = ANY")) { // A second live row points at the same worktree. return { rows: [{ id: "other" }], rowCount: 1 }; } diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index 40114d7d5..b215c22bf 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -18,6 +18,7 @@ import { vi, } from "vitest"; import type { Pool } from "pg"; +import type { SessionOperation } from "@dispatch/runner-protocol"; import type { RemoteRunnerService } from "../../src/agents/remote/service.js"; import { setupTestDb, teardownTestDb, runTestMigrations } from "./setup.js"; @@ -247,8 +248,35 @@ describe("AgentManager", () => { describe("createAgent", () => { it("persists managed placement across restart and retries archive when the original runner returns", async () => { const available = vi.fn(() => true); + const stateId = "2".repeat(64); + const requestSession = vi.fn( + async (_placement: unknown, operation: SessionOperation) => { + if (!available()) throw new Error("offline"); + if (operation.kind !== "checkoutRelease") + throw new Error("Unexpected request"); + return { + value: + operation.operation.kind === "release" + ? "released" + : JSON.stringify({ + ownership: "owned", + owner: "test-owner", + borrowers: [], + checkout: { + path: "/runner/checkout", + branch: "agent-work", + stateId, + unmerged: false, + changedFiles: [], + uncommittedFiles: [], + }, + }), + }; + } + ); const remote = { available, + requestSession, isManagedWorkspace: available, originFor: () => "https://example.test", } as unknown as RemoteRunnerService; @@ -286,8 +314,21 @@ describe("AgentManager", () => { expect(resumedRuntime.launch).toHaveBeenCalledWith( expect.objectContaining({ repository }) ); - await resumed.beginArchive(agent.id); + const observed = await resumed.checkWorktreeStatus(agent.id); + expect(observed).toMatchObject({ + ownership: "owned", + checkoutState: stateId, + }); + await resumed.beginArchive(agent.id, "auto", stateId); + // Simulate a row created before runner_managed was populated. + await pool.query( + "UPDATE agents SET runner_managed = false WHERE id = $1", + [agent.id] + ); available.mockReturnValue(false); + await expect(resumed.checkWorktreeStatus(agent.id)).rejects.toMatchObject( + { statusCode: 503 } + ); resumedRuntime.stop.mockRejectedValueOnce(new Error("offline")); await resumed.executeArchive(agent.id, { onPhaseChange: vi.fn(), @@ -303,14 +344,29 @@ describe("AgentManager", () => { ).rows[0]?.runner_cleanup_pending; expect(await pending()).toBe(true); const placement = { runner: "runner-test", workspace: "@session" }; - available.mockClear(); + requestSession.mockClear(); await resumed.reconcileAgentStatuses(); - await vi.waitFor(() => expect(available).toHaveBeenCalledWith(placement)); - expect(discard).not.toHaveBeenCalled(); + await vi.waitFor(() => + expect(requestSession).toHaveBeenCalledWith(placement, { + kind: "checkoutRelease", + agentId: agent.id, + operation: { kind: "observe" }, + }) + ); + expect(await pending()).toBe(true); + const reconnected = new AgentManager(pool, noopLogger, testConfig, { + runtime: { ...createSpyRuntime(), discard }, + remote, + }); available.mockReturnValue(true); - await resumed.reconcileAgentStatuses(); + await reconnected.reconcileAgentStatuses(); await vi.waitFor(async () => expect(await pending()).toBe(false)); - expect(discard).toHaveBeenCalledExactlyOnceWith(agent.id); + expect(requestSession).toHaveBeenLastCalledWith(placement, { + kind: "checkoutRelease", + agentId: agent.id, + operation: { kind: "release", expectedState: stateId }, + }); + expect(discard).not.toHaveBeenCalled(); }); it("records a runner selection only after acknowledgement and binds independent children to the selected origin", async () => { diff --git a/apps/server/test/migrations.test.ts b/apps/server/test/migrations.test.ts index 6ed6dc310..fb19caff4 100644 --- a/apps/server/test/migrations.test.ts +++ b/apps/server/test/migrations.test.ts @@ -75,6 +75,12 @@ describe("block_reactions uniqueness migration", () => { /** Rewinds task migrations, which depend on projects and agents, so older eras can replay. */ async function dropTasks(): Promise { + await pool.query( + "ALTER TABLE agents DROP COLUMN IF EXISTS archive_checkout_state" + ); + await pool.query( + "DELETE FROM pgmigrations WHERE name = '0059_archive_checkout_state'" + ); await pool.query( "ALTER TABLE agents DROP COLUMN IF EXISTS runner_worktree_owner" ); diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index cbc81657e..40cf528ba 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -23,6 +23,11 @@ import { } from "../src/agents/remote/session-processes.js"; import { createSessionSupervisor } from "../src/agents/remote/session-supervisor.js"; +import { + observeGitCheckout, + observeScratchCheckout, +} from "../src/agents/checkout-inspection.js"; + type Supervisor = Awaited>; const marker = "DISPATCH_OWNED_00000000000000000000000000000000=1"; @@ -109,6 +114,8 @@ describe("runner session supervision", () => { workspaces: new Set(workspaces), hostCommand: () => ["/test-host"], asWorkload, + observeCheckout: (dir, scratch) => + scratch ? observeScratchCheckout(dir) : observeGitCheckout(dir), prepareDependencies, }, processes @@ -419,6 +426,77 @@ describe("runner session supervision", () => { await expect(stat(author)).rejects.toMatchObject({ code: "ENOENT" }); }); + it.each(["owner-first", "borrower-first", "changed-after-observation"])( + "conditionally releases a scratch checkout: %s", + async (order) => { + const workspace = MANAGED_WORKSPACE; + const running = await start([]); + await running.launch(launch(workspace), undefined); + processes.spawn.mockResolvedValueOnce(); + await running.launch(sharedLaunch(), undefined); + await running.stop(agentId, workspace, true); + const observation = await running.checkoutRelease(agentId, workspace, { + kind: "observe", + }); + expect(observation).toMatchObject({ + ownership: "owned", + owner: agentId, + borrowers: [reviewerId], + }); + expect( + await running.checkoutRelease(reviewerId, workspace, { + kind: "observe", + }) + ).toMatchObject({ ownership: "borrowed", owner: agentId }); + if (typeof observation === "string" || !observation.checkout) + throw new Error("Missing fixture checkout observation"); + const ownerRelease = { + kind: "release", + expectedState: observation.checkout.stateId, + } as const; + const borrowerRelease = { kind: "release", expectedState: null } as const; + if (order !== "borrower-first") { + expect( + await running.checkoutRelease(agentId, workspace, ownerRelease) + ).toBe("inUse"); + expect(await stat(observation.checkout.path)).toBeDefined(); + } + expect( + await running.checkoutRelease(reviewerId, workspace, borrowerRelease) + ).toBe("released"); + if (order === "changed-after-observation") + await writeFile( + path.join(observation.checkout.path, "new.txt"), + "work" + ); + running.close(); + const recovered = await start([]); + const expected = + order === "changed-after-observation" ? "retained" : "released"; + expect( + await recovered.checkoutRelease(agentId, workspace, ownerRelease) + ).toBe(expected); + expect( + await recovered.checkoutRelease(agentId, workspace, ownerRelease) + ).toBe(expected); + if (expected === "retained") { + await expect(recovered.discard(agentId, workspace)).rejects.toThrow( + "retained" + ); + expect( + await readFile( + path.join(observation.checkout.path, "new.txt"), + "utf8" + ) + ).toBe("work"); + } else { + await expect(stat(observation.checkout.path)).rejects.toMatchObject({ + code: "ENOENT", + }); + } + } + ); + it("holds the owner checkout through a concurrent borrower launch", async () => { const workspace = MANAGED_WORKSPACE; const running = await start([]); @@ -744,6 +822,15 @@ describe("runner session supervision", () => { ); expect((await stat(author)).mode & 0o777).toBe(0o711); expect(workload).not.toHaveBeenCalled(); + const legacyHead = git("-C", checkout, "rev-parse", "HEAD").trim(); + git(`--git-dir=${cache}`, "update-ref", "refs/heads/main", legacyHead); + expect( + await running.checkoutRelease(agentId, workspace, { kind: "observe" }) + ).toMatchObject({ + ownership: "owned", + borrowers: [reviewerId], + checkout: { unmerged: false, uncommittedFiles: ["uncommitted.txt"] }, + }); await expect(running.discard(agentId, workspace)).rejects.toThrow( "still in use" ); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index d45097582..20c2b3aec 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -19,6 +19,7 @@ import { isOpaqueId, isCheckoutReply, isSessionCheckout, + isCheckoutObservation, parseGitHubPullRequestWatchEvent, isGitHubPullRequestDetails, isGitHubPullRequestDiff, @@ -738,6 +739,7 @@ function fixtureRunner(current: boolean) { pullRequestEvidence: true, pullRequestWatch: true, sessionCheckout: true, + checkoutRelease: true, }), }; const sample = { @@ -768,6 +770,8 @@ function fixtureRunner(current: boolean) { const requests: ServiceFrame[] = []; let selectedCheckout = "/workload/launch"; + const stateId = "b".repeat(64); + let released = false; function connect() { const service = new Duplex({ @@ -869,6 +873,34 @@ function fixtureRunner(current: boolean) { command.agentId !== agentId ) { reply({ type: "result", id, error: "Unknown session binding" }); + } else if (command.kind === "checkoutRelease" && current) { + if (command.operation.kind === "observe") { + result( + JSON.stringify({ + ownership: released ? "none" : "owned", + owner: released ? null : "machine/owner", + borrowers: released ? [] : ["machine/borrower"], + checkout: released + ? null + : { + path: selectedCheckout, + branch: "feature", + stateId, + unmerged: true, + changedFiles: ["retained.txt"], + uncommittedFiles: [], + }, + }) + ); + } else if ( + !running && + command.operation.expectedState === stateId + ) { + released = true; + result("released"); + } else { + result("retained"); + } } else if (command.kind === "sessionCheckout" && current && running) { if (command.operation.kind === "select") selectedCheckout = command.operation.path ?? "/workload/launch"; @@ -1034,6 +1066,56 @@ it("lets an independent host select a checkout by opaque session handle after ne } }); +it.each([true, false])( + "independent checkout release consumer negotiates capability: %s", + async (current) => { + const runner = fixtureRunner(current); + const peer = runner.connect(); + try { + await vi.waitFor(() => expect(peer.reports[0]).toBeDefined()); + const ready = parseReadyFrame(peer.reports[0]); + expect(ready?.checkoutRelease).toBe(current ? true : undefined); + if (!ready?.checkoutRelease) { + expect(runner.requests).toHaveLength(0); + return; + } + const observe = { + ...runner.session, + kind: "checkoutRelease", + operation: { kind: "observe" }, + } as const; + const observation: unknown = JSON.parse( + String((await peer.connection.request(observe)).value) + ); + expect(isCheckoutObservation(observation)).toBe(true); + if (!isCheckoutObservation(observation) || !observation.checkout) + throw new Error("Missing checkout observation"); + expect(observation.borrowers).toEqual(["machine/borrower"]); + const release = { + ...observe, + operation: { + kind: "release", + expectedState: observation.checkout.stateId, + }, + } as const; + expect( + parseServiceFrame({ + type: "request", + id: "bad", + command: { + ...release, + operation: { kind: "release", expectedState: "../bad" }, + }, + }) + ).toBeNull(); + expect((await peer.connection.request(release)).value).toBe("released"); + expect((await peer.connection.request(release)).value).toBe("released"); + } finally { + peer.close(); + } + } +); + it.each([true, false])( "independent service starts and resumes a runner session (current capabilities: %s)", async (current) => { diff --git a/apps/web/src/components/app/delete-agent-dialog.tsx b/apps/web/src/components/app/delete-agent-dialog.tsx index ac16951cf..9a907c90a 100644 --- a/apps/web/src/components/app/delete-agent-dialog.tsx +++ b/apps/web/src/components/app/delete-agent-dialog.tsx @@ -16,6 +16,9 @@ import { api } from "@/lib/api"; type WorktreeStatus = { hasWorktree: boolean; + ownership?: "owned" | "borrowed" | "external" | "none"; + borrowers?: string[]; + checkoutState?: string; hasUnmergedCommits: boolean; hasUncommittedChanges: boolean; worktreePath: string | null; @@ -33,7 +36,11 @@ type DeleteAgentDialogProps = { agents: Agent[]; setOpen: (open: boolean) => void; setDeleteTarget: (agent: Agent | null) => void; - onDelete: (agent: Agent, cleanupWorktree?: string) => Promise; + onDelete: ( + agent: Agent, + cleanupWorktree?: string, + checkoutState?: string + ) => Promise; }; export function DeleteAgentDialog({ @@ -49,6 +56,7 @@ export function DeleteAgentDialog({ null ); const [loading, setLoading] = useState(false); + const [statusUnavailable, setStatusUnavailable] = useState(false); const [deleting, setDeleting] = useState(false); // Archiving cascades to the target's sub agents, so the confirmation has to @@ -65,18 +73,23 @@ export function DeleteAgentDialog({ } archived too.` : ""; - // Fetch worktree status when dialog opens for an agent with a worktree + const runnerCheckout = Boolean( + deleteTarget?.runnerManaged || deleteTarget?.cwd.startsWith("runner://") + ); + + // Remote checkout ownership is known only to the session runner. useEffect(() => { + setStatusUnavailable(false); + setWorktreeStatus(null); if (!open || !deleteTarget) { setStep("confirm"); - setWorktreeStatus(null); setLoading(false); setDeleting(false); return; } - if (!deleteTarget.worktreePath) { - setWorktreeStatus(null); + if (!deleteTarget.worktreePath && !runnerCheckout) { + setLoading(false); return; } @@ -91,7 +104,7 @@ export function DeleteAgentDialog({ }) .catch(() => { if (!cancelled) { - setWorktreeStatus(null); + setStatusUnavailable(true); setLoading(false); } }); @@ -99,7 +112,7 @@ export function DeleteAgentDialog({ return () => { cancelled = true; }; - }, [open, deleteTarget]); + }, [open, deleteTarget, runnerCheckout]); const handleConfirmDelete = useCallback(async () => { if (!deleteTarget) return; @@ -107,6 +120,8 @@ export function DeleteAgentDialog({ // If there's a worktree with unmerged commits or uncommitted changes, transition to choice step if ( worktreeStatus?.hasWorktree && + worktreeStatus.ownership !== "borrowed" && + worktreeStatus.ownership !== "external" && (worktreeStatus.hasUnmergedCommits || worktreeStatus.hasUncommittedChanges) ) { @@ -114,10 +129,12 @@ export function DeleteAgentDialog({ return; } - // No worktree or no unmerged commits — standard delete with auto cleanup + // The server checks again before allowing automatic cleanup. setDeleting(true); try { - await onDelete(deleteTarget, "auto"); + if (worktreeStatus?.checkoutState) + await onDelete(deleteTarget, "auto", worktreeStatus.checkoutState); + else await onDelete(deleteTarget, "auto"); setOpen(false); setDeleteTarget(null); } finally { @@ -131,14 +148,20 @@ export function DeleteAgentDialog({ setDeleting(true); try { - await onDelete(deleteTarget, cleanupMode); + if (cleanupMode === "force" && worktreeStatus?.checkoutState) + await onDelete( + deleteTarget, + cleanupMode, + worktreeStatus.checkoutState + ); + else await onDelete(deleteTarget, cleanupMode); setOpen(false); setDeleteTarget(null); } finally { setDeleting(false); } }, - [deleteTarget, onDelete, setOpen, setDeleteTarget] + [deleteTarget, onDelete, setOpen, setDeleteTarget, worktreeStatus] ); const close = useCallback(() => { @@ -147,9 +170,7 @@ export function DeleteAgentDialog({ }, [setOpen, setDeleteTarget]); if (step === "worktree-choice" && worktreeStatus) { - const hasUnmerged = - worktreeStatus.hasUnmergedCommits && - worktreeStatus.changedFiles.length > 0; + const hasUnmerged = worktreeStatus.hasUnmergedCommits; const hasUncommitted = worktreeStatus.hasUncommittedChanges && worktreeStatus.uncommittedFiles.length > 0; @@ -167,11 +188,16 @@ export function DeleteAgentDialog({
    - Branch{" "} - - {worktreeStatus.branchName} - {" "} - has commits not merged to origin. + {worktreeStatus.branchName && ( + <> + Branch{" "} + + {worktreeStatus.branchName} + {" "} + + )} + {worktreeStatus.branchName ? "has" : "This checkout has"}{" "} + unmerged commits.
    @@ -198,6 +224,9 @@ export function DeleteAgentDialog({

    The agent will be archived either way. + {worktreeStatus.borrowers?.length + ? " Removal waits until the other sessions release the worktree." + : ""} {cascadeNote}

    @@ -243,11 +272,20 @@ export function DeleteAgentDialog({ Archive Agent - {deleteTarget?.runnerManaged - ? `Archive "${deleteTarget.name}"? The runner will delete its session folder, including uncommitted files. If the runner is offline, cleanup happens when it reconnects.${cascadeNote}` - : deleteTarget - ? `Archive "${deleteTarget.name}"? This removes the agent record and all files.${cascadeNote}` - : "Archive this agent?"} + {deleteTarget + ? `Archive "${deleteTarget.name}"?${cascadeNote}` + : "Archive this agent?"} + {statusUnavailable + ? runnerCheckout + ? " Checkout status is unavailable. The runner will check it when available and keep it if it cannot verify that it is clean." + : " Checkout status is unavailable. Archive will keep it unless it can verify that it is clean." + : worktreeStatus?.ownership === "borrowed" + ? " The shared checkout belongs to another session." + : worktreeStatus?.borrowers?.length + ? " Checkout removal waits until the other sessions release it." + : worktreeStatus?.ownership === "owned" + ? " Archive removes the checkout if it is still clean and unchanged." + : ""}
    diff --git a/apps/web/src/hooks/use-agent-actions.ts b/apps/web/src/hooks/use-agent-actions.ts index 22b35211d..b429de6e2 100644 --- a/apps/web/src/hooks/use-agent-actions.ts +++ b/apps/web/src/hooks/use-agent-actions.ts @@ -75,7 +75,7 @@ export function useAgentActions({ }, []); const deleteAgent = useCallback( - async (agent: Agent, cleanupWorktree?: string) => { + async (agent: Agent, cleanupWorktree?: string, checkoutState?: string) => { setExpandedAgentId((current) => (current === agent.id ? null : current)); if (routeAgentId === agent.id) { navigate("/agents", { @@ -87,6 +87,7 @@ export function useAgentActions({ if (cleanupWorktree) { searchParams.set("cleanupWorktree", cleanupWorktree); } + if (checkoutState) searchParams.set("checkoutState", checkoutState); const qs = searchParams.toString(); await api(`/api/v1/agents/${agent.id}${qs ? `?${qs}` : ""}`, { method: "DELETE", diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index 7a727dab6..974515f04 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -54,3 +54,11 @@ templates and scheduled jobs retain explicit runner locators, and task launches use the selected template placement. A new checkout uses a published base from its origin. Borrowing shares the existing files, including unpublished changes. + +Archive observes the checkout bound to the session on its owning runner. +Moving the session to another directory leaves archive ownership with the +original checkout. Dispatch stores the cleanup policy and the observed state +ID for retries. The runner checks that state again under its checkout lock +and defers removal while another session holds a borrower binding. Older +runners keep their legacy protocol, and managed cleanup requested by a newer +Dispatch waits for a runner that advertises conditional release. diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index ca80fe1fd..19a660df4 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -610,10 +610,18 @@ test("managed scratch checkout selection persists across host start and preserve if (!(await archive.isVisible())) await page.getByTestId(`agent-expand-toggle-${id}`).click(); await archive.click(); - await expect( - page.getByRole("dialog", { name: "Archive Agent" }) - ).toContainText("The runner will delete its session folder"); await page.getByTestId("delete-agent-confirm").click(); + const choice = page.getByRole("dialog", { + name: "Worktree Has Outstanding Changes", + }); + await expect( + choice.getByText("provider-invocations", { exact: true }) + ).toBeVisible(); + await testInfo.attach("runner-owned scratch archive choice", { + body: await page.screenshot(), + contentType: "image/png", + }); + await choice.getByTestId("delete-agent-force-worktree").click(); await expect(page.getByTestId(`agent-card-${id}`)).toHaveCount(0); await expect .poll(() => guestOk("scratch", `test ! -e ${directory}`), { diff --git a/e2e/worktree.spec.ts b/e2e/worktree.spec.ts index 996d9c7d4..68a7e57cd 100644 --- a/e2e/worktree.spec.ts +++ b/e2e/worktree.spec.ts @@ -125,7 +125,6 @@ test.describe("Safe worktree archive", () => { await loadApp(page); - const sidebar = page.getByTestId("agent-sidebar"); const agentCard = page.getByTestId(`agent-card-${agent.id}`); await expect(agentCard).toBeVisible({ timeout: 5_000 }); @@ -145,6 +144,20 @@ test.describe("Safe worktree archive", () => { await expect(page.getByTestId("delete-agent-keep-worktree")).toBeVisible(); await expect(page.getByTestId("delete-agent-force-worktree")).toBeVisible(); + for (const width of [page.viewportSize()!.width, 390]) { + await page.setViewportSize({ width, height: 844 }); + const choice = page.getByRole("dialog", { + name: "Worktree Has Outstanding Changes", + }); + await expect( + choice.getByText("ui-file.txt", { exact: true }) + ).toBeVisible(); + await testInfo.attach(`archive choice at ${width}px`, { + body: await page.screenshot(), + contentType: "image/png", + }); + } + // Choose "Leave worktree" const wtPath = agent.worktreePath!; await page.getByTestId("delete-agent-keep-worktree").click(); @@ -165,4 +178,52 @@ test.describe("Safe worktree archive", () => { stdio: "ignore", }); }); + + test("removes an unchanged clean checkout through Archive", async ({ + page, + request, + }, testInfo) => { + const agent = await createAgentViaAPI(request, { + name: "clean checkout archive", + cwd: repoPath, + useWorktree: true, + }); + await loadApp(page); + await page.getByTestId(`agent-expand-toggle-${agent.id}`).click(); + await page.getByTestId(`agent-archive-${agent.id}`).click(); + const dialog = page.getByRole("dialog", { name: "Archive Agent" }); + await expect(dialog).toContainText("still clean and unchanged"); + await testInfo.attach("clean checkout confirmation", { + body: await page.screenshot(), + contentType: "image/png", + }); + await dialog.getByTestId("delete-agent-confirm").click(); + await expect(page.getByTestId(`agent-card-${agent.id}`)).toHaveCount(0); + expect(existsSync(agent.worktreePath!)).toBe(false); + }); + + test("keeps a dirty checkout changed between confirmation and removal", async ({ + page, + request, + }) => { + const agent = await createAgentViaAPI(request, { + name: "changed checkout archive", + cwd: repoPath, + useWorktree: true, + }); + const file = path.join(agent.worktreePath!, "draft.txt"); + writeFileSync(file, "seen"); + await loadApp(page); + await page.getByTestId(`agent-expand-toggle-${agent.id}`).click(); + await page.getByTestId(`agent-archive-${agent.id}`).click(); + await page.getByTestId("delete-agent-confirm").click(); + const choice = page.getByRole("dialog", { + name: "Worktree Has Outstanding Changes", + }); + await expect(choice.getByText("draft.txt", { exact: true })).toBeVisible(); + writeFileSync(file, "edited while the dialog was open"); + await choice.getByTestId("delete-agent-force-worktree").click(); + await expect(page.getByTestId(`agent-card-${agent.id}`)).toHaveCount(0); + expect(existsSync(file)).toBe(true); + }); }); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 697e64b8b..76b436711 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -425,3 +425,21 @@ sample and an account reset require a fresh initial read. A host can pass `refre target this forces a new sample or joins one already in flight, and may return an error when capacity is exhausted. Regular status reads retain their existing behavior. All samples use the runner's workload credential. + +### Conditional checkout release + +Send `checkoutRelease` only to a v1 peer advertising `checkoutRelease: true` in +its ready frame. It uses the existing session and workspace handles. The +`observe` operation replies with a JSON-encoded `CheckoutObservation`. Owner +and borrower handles in that observation are opaque and machine-local. A null +`checkout` for an owned binding means the checkout could not be observed. +A rejected request or missing result is also unavailable. + +Stop the session before sending `release`. The host decides whether to pass +the observed `stateId` to authorize removal, or `null` to retain the checkout. +The runner rechecks the state before removal and keeps external checkouts. +`released` means the session is released, `retained` means the session is +released and its owned checkout was kept, and `inUse` means live borrower +bindings still hold the checkout. Retry a deferred release using the same +authorization. Repeating a release is safe, including after a lost reply. +The legacy `discard` command keeps its original behavior for clients using it. diff --git a/packages/runner-protocol/src/checkout.ts b/packages/runner-protocol/src/checkout.ts index 53139d15b..0f43eec36 100644 --- a/packages/runner-protocol/src/checkout.ts +++ b/packages/runner-protocol/src/checkout.ts @@ -1,3 +1,4 @@ +import { isOpaqueId } from "./placement.js"; import { isRecord } from "./validation.js"; /** Operations are relative to the bound session checkout. Paths never name host files. */ @@ -86,3 +87,70 @@ export type SessionCheckout = { moved: boolean; origin: string | null; }; + +/** Observe the bound checkout, or finalize the session with a conditional removal. */ +export type CheckoutRelease = + | { kind: "observe" } + | { kind: "release"; expectedState: string | null }; + +export type CheckoutObservation = { + ownership: "owned" | "borrowed" | "external" | "none"; + /** Opaque machine-local checkout owner and dependent session handles. */ + owner: string | null; + borrowers: string[]; + checkout: CheckoutState | null; +}; + +export type CheckoutState = { + path: string; + branch: string | null; + stateId: string; + unmerged: boolean; + changedFiles: string[]; + uncommittedFiles: string[]; +}; + +export type CheckoutReleaseResult = "released" | "retained" | "inUse"; + +export function isCheckoutStateId(value: unknown): value is string { + return typeof value === "string" && /^[a-f0-9]{64}$/.test(value); +} + +export function isCheckoutRelease(value: unknown): value is CheckoutRelease { + return ( + isRecord(value) && + (value.kind === "observe" || + (value.kind === "release" && + (value.expectedState === null || + isCheckoutStateId(value.expectedState)))) + ); +} + +export function isCheckoutObservation( + value: unknown +): value is CheckoutObservation { + return ( + isRecord(value) && + (value.ownership === "owned" || + value.ownership === "borrowed" || + value.ownership === "external" || + value.ownership === "none") && + (value.ownership === "owned" || value.ownership === "borrowed" + ? isOpaqueId(value.owner) + : value.owner === null) && + Array.isArray(value.borrowers) && + value.borrowers.every(isOpaqueId) && + (value.checkout === null || + (isRecord(value.checkout) && + isCheckoutPath(value.checkout.path) && + (value.checkout.branch === null || + typeof value.checkout.branch === "string") && + isCheckoutStateId(value.checkout.stateId) && + typeof value.checkout.unmerged === "boolean" && + [value.checkout.changedFiles, value.checkout.uncommittedFiles].every( + (files) => + Array.isArray(files) && + files.every((file) => typeof file === "string") + ))) + ); +} diff --git a/packages/runner-protocol/src/connection.ts b/packages/runner-protocol/src/connection.ts index 3240ad74b..f3d74f316 100644 --- a/packages/runner-protocol/src/connection.ts +++ b/packages/runner-protocol/src/connection.ts @@ -89,6 +89,7 @@ export class RunnerConnection { // Repository fetches and engine package installs can run for minutes. const timeoutMs = command.kind === "sessionCheckout" || + command.kind === "checkoutRelease" || command.kind === "inspectCheckout" || command.kind === "viewCheckout" || command.kind === "engine" || diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index be5d9dba0..ee06496fa 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,6 +1,8 @@ import { isCheckoutView, type CheckoutView } from "./checkout-view.js"; import { isCheckoutQuery, + isCheckoutRelease, + type CheckoutRelease, isCheckoutPath, validBranch, type CheckoutQuery, @@ -69,6 +71,7 @@ export type SessionOperation = kind: "sessionCheckout"; operation: { kind: "describe" } | { kind: "select"; path: string | null }; } + | { agentId: string; kind: "checkoutRelease"; operation: CheckoutRelease } | { agentId: string; kind: "repo" }; export type RunnerOperation = @@ -97,6 +100,7 @@ export type ReadyFrame = { sharedWorktree?: true; workspacePreparation?: true; sessionCheckout?: true; + checkoutRelease?: true; }; /** Accept v1 extension fields and enable optional features only when explicitly true. */ @@ -122,6 +126,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.checkoutViews === true && { checkoutViews: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), + ...(frame.checkoutRelease === true && { checkoutRelease: true }), ...(frame.sessionCheckout === true && { sessionCheckout: true }), ...(frame.workspacePreparation === true && { workspacePreparation: true }), ...(frame.health === true && { health: true }), @@ -301,6 +306,8 @@ function isCommand(value: unknown): value is Command { (value.launch.useWorktreeOf === undefined || value.agentId === value.launch.agentId) ); + case "checkoutRelease": + return isCheckoutRelease(value.operation); case "sessionCheckout": return ( isRecord(value.operation) && From 1df09262b4827dc3a3dfd658fedeff0b8ea67889 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:21:09 -0700 Subject: [PATCH 135/642] Route native archive cleanup through the built-in runner --- apps/server/src/agents/archive-checkout.ts | 78 ++++++------ apps/server/src/agents/archive.ts | 115 +++++------------- .../src/agents/local-runner-checkout.ts | 90 ++++++++++++++ apps/server/src/agents/local-runner.ts | 2 + apps/server/src/agents/manager.ts | 9 +- apps/server/src/shared/git/worktree.ts | 11 +- apps/server/test/agent-archive.test.ts | 36 +++++- apps/server/test/checkout-inspection.test.ts | 60 +++++++++ .../db/agent-archive-branch-cleanup.test.ts | 11 ++ e2e/worktree.spec.ts | 14 ++- 10 files changed, 299 insertions(+), 127 deletions(-) create mode 100644 apps/server/src/agents/local-runner-checkout.ts diff --git a/apps/server/src/agents/archive-checkout.ts b/apps/server/src/agents/archive-checkout.ts index 222bda8bc..a806e8273 100644 --- a/apps/server/src/agents/archive-checkout.ts +++ b/apps/server/src/agents/archive-checkout.ts @@ -1,4 +1,3 @@ -import { realpath } from "node:fs/promises"; import { isCheckoutObservation, remotePlacement, @@ -6,8 +5,7 @@ import { type CheckoutReleaseResult, } from "@dispatch/runner-protocol"; import type { Pool } from "pg"; -import { normalizePath } from "../shared/git/git-context.js"; -import { observeGitCheckout } from "./checkout-inspection.js"; +import type { createLocalRunner } from "./local-runner.js"; import { AgentError } from "./errors.js"; import type { RemoteRunnerService } from "./remote/service.js"; import type { AgentRecord, WorktreeCleanupMode } from "./types.js"; @@ -17,19 +15,25 @@ export type ArchiveCheckoutAgent = Pick< "id" | "cwd" | "worktreePath" | "baseBranch" | "worktreeBranch" >; -export async function nativeBorrowers(pool: Pool, agent: ArchiveCheckoutAgent) { +export type LocalArchiveRunner = Pick< + ReturnType, + "checkoutRelease" +>; + +export async function nativeBorrowers( + pool: Pool, + agent: ArchiveCheckoutAgent, + canonicalPath: string +) { const path = agent.worktreePath; if (!path) return []; - const canonical = await realpath(path) - .then(normalizePath) - .catch(() => path); const { rows } = await pool.query<{ id: string }>( `SELECT id FROM agents WHERE deleted_at IS NULL AND id <> $1 AND (worktree_path = ANY($2::text[]) OR workspace_path = ANY($2::text[]) OR cwd = ANY($2::text[])) ORDER BY id`, - [agent.id, [...new Set([path, canonical])]] + [agent.id, [...new Set([path, canonicalPath])]] ); return rows.map(({ id }) => id); } @@ -37,38 +41,40 @@ export async function nativeBorrowers(pool: Pool, agent: ArchiveCheckoutAgent) { export async function observeArchiveCheckout( pool: Pool, agent: ArchiveCheckoutAgent, + localRunner: LocalArchiveRunner, remote?: RemoteRunnerService ): Promise { const placement = remotePlacement(agent.cwd); if (placement) { if (!remote) throw new AgentError("The session runner is unavailable.", 503); - const { value } = await remote.requestSession(placement, { - kind: "checkoutRelease", - agentId: agent.id, - operation: { kind: "observe" }, - }); - const observation: unknown = - typeof value === "string" ? JSON.parse(value) : null; - if (!isCheckoutObservation(observation)) - throw new AgentError( - "Invalid checkout observation from the runner.", - 502 - ); - return observation; + return observeRemoteCheckout(agent, remote, placement); } - if (!agent.worktreePath) - return { - ownership: "external", - owner: null, - borrowers: [], - checkout: null, - }; - const [checkout, borrowers] = await Promise.all([ - observeGitCheckout(agent.worktreePath, agent.baseBranch), - nativeBorrowers(pool, agent), - ]); - return { ownership: "owned", owner: agent.id, borrowers, checkout }; + const observed = await localRunner.checkoutRelease(agent, { + kind: "observe", + }); + if (observed.ownership !== "owned" || !observed.checkout) return observed; + return { + ...observed, + borrowers: await nativeBorrowers(pool, agent, observed.checkout.path), + }; +} + +async function observeRemoteCheckout( + agent: ArchiveCheckoutAgent, + remote: RemoteRunnerService, + placement: NonNullable> +): Promise { + const { value } = await remote.requestSession(placement, { + kind: "checkoutRelease", + agentId: agent.id, + operation: { kind: "observe" }, + }); + const observation: unknown = + typeof value === "string" ? JSON.parse(value) : null; + if (!isCheckoutObservation(observation)) + throw new AgentError("Invalid checkout observation from the runner.", 502); + return observation; } export async function archiveCheckoutState(pool: Pool, id: string) { @@ -101,10 +107,10 @@ export async function releaseRemoteCheckout( let expectedState = mode === "keep" ? null : await archiveCheckoutState(pool, agent.id); if (mode === "auto") { - const { checkout, ownership } = await observeArchiveCheckout( - pool, + const { checkout, ownership } = await observeRemoteCheckout( agent, - remote + remote, + placement ); if ( ownership === "owned" && diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index 024981d80..933b6da73 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -2,8 +2,6 @@ import type { FastifyBaseLogger } from "fastify"; import type { Pool } from "pg"; import { MANAGED_WORKSPACE, remotePlacement } from "@dispatch/runner-protocol"; -import { cleanupGitWorktree } from "../shared/git/worktree.js"; -import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; import { archiveCheckoutState, nativeBorrowers, @@ -11,6 +9,7 @@ import { releaseRemoteCheckout, rememberArchiveCheckoutState, type ArchiveCheckoutAgent, + type LocalArchiveRunner, } from "./archive-checkout.js"; import type { RemoteRunnerService } from "./remote/service.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; @@ -27,6 +26,7 @@ export type ArchiveDeps = { pool: Pool; logger: FastifyBaseLogger; runtime: AgentRuntime; + localRunner: LocalArchiveRunner; remote?: RemoteRunnerService; diffStatsRefresher: { clear(agentId: string): void } | null; getAgent: (id: string) => Promise; @@ -70,35 +70,11 @@ async function getChildAgentIds( return result.rows.map((row) => row.id); } -/** - * git blocks indefinitely on a held index lock, and the cascade is sequential — - * one hang would strand every sibling behind it. - */ -const WORKTREE_CLEANUP_TIMEOUT_MS = 60_000; - -/** Rejects if `work` outruns `ms`, always clearing its own timer. */ -async function withTimeout( - work: Promise, - ms: number, - message: string -): Promise { - let timer: ReturnType | undefined; - try { - return await Promise.race([ - work, - new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error(message)), ms); - }), - ]); - } finally { - if (timer) clearTimeout(timer); - } -} - /** Returns whether cleanup should be retried after archive. */ export async function cleanupAgentWorktree( pool: Pool, logger: FastifyBaseLogger, + localRunner: LocalArchiveRunner, agent: ArchiveCheckoutAgent, mode: WorktreeCleanupMode, durations: Record, @@ -107,73 +83,39 @@ export async function cleanupAgentWorktree( const { id, worktreePath } = agent; if (!worktreePath || remotePlacement(agent.cwd) || mode === "keep") return false; - const run = async () => { + try { const started = Date.now(); - let expectedState = await archiveCheckoutState(pool, id); - const borrowers = await nativeBorrowers(pool, agent); - // Preserve legacy explicit force requests, which predate observation IDs. - if (mode === "auto" || expectedState !== null || borrowers.length) { - const { checkout } = await observeArchiveCheckout(pool, agent); - if ( - !checkout || - (expectedState !== null && expectedState !== checkout.stateId) || - (mode === "auto" && - (checkout.unmerged || checkout.uncommittedFiles.length)) - ) - return false; - expectedState = checkout.stateId; - if (borrowers.length) { - await rememberArchiveCheckoutState(pool, id, expectedState); - return true; - } - } + const expectedState = await archiveCheckoutState(pool, id); + const { checkout, borrowers } = await observeArchiveCheckout( + pool, + agent, + localRunner + ); + if ( + !checkout || + (expectedState !== null && checkout.stateId !== expectedState) || + (mode === "auto" && + (checkout.unmerged || checkout.uncommittedFiles.length)) + ) + return false; durations.outstandingChangesCheck = Date.now() - started; - await onCleanupStart?.(); - if ((await nativeBorrowers(pool, agent)).length) { - if (expectedState === null) return false; - await rememberArchiveCheckoutState(pool, id, expectedState); + if (borrowers.length) { + await rememberArchiveCheckoutState(pool, id, checkout.stateId); return true; } - // Re-read after publishing the phase, including any file edited since the - // confirmation. Git is run by the built-in runner on this machine. - if (mode === "auto" || expectedState !== null) { - const { checkout } = await observeArchiveCheckout(pool, agent); - if ( - !checkout || - (expectedState !== null && checkout.stateId !== expectedState) || - (mode === "auto" && - (checkout.unmerged || checkout.uncommittedFiles.length)) - ) - return false; + await onCleanupStart?.(); + if ((await nativeBorrowers(pool, agent, checkout.path)).length) { + await rememberArchiveCheckoutState(pool, id, checkout.stateId); + return true; } - // A timed-out observation must never start removal in the background. - if (Date.now() - started >= WORKTREE_CLEANUP_TIMEOUT_MS) return false; - const boundedGit: CommandRunner = (command, args, options) => - runCommand(command, args, { - ...options, - timeoutMs: options?.timeoutMs ?? WORKTREE_CLEANUP_TIMEOUT_MS, - }); + const cleanupStarted = Date.now(); - await cleanupGitWorktree( - { - cwd: worktreePath, - deleteBranch: - !!agent.worktreeBranch && - (!agent.baseBranch || agent.worktreeBranch !== agent.baseBranch), - force: true, - originalBranch: agent.worktreeBranch, - }, - boundedGit - ); + await localRunner.checkoutRelease(agent, { + kind: "release", + expectedState: checkout.stateId, + }); durations.worktreeCleanup = Date.now() - cleanupStarted; return false; - }; - try { - return await withTimeout( - run(), - WORKTREE_CLEANUP_TIMEOUT_MS, - "Worktree cleanup timed out" - ); } catch (err) { logger.warn( { err, agentId: id, worktreePath }, @@ -202,6 +144,7 @@ async function finishCheckout( return cleanupAgentWorktree( deps.pool, deps.logger, + deps.localRunner, agent, mode, durations, diff --git a/apps/server/src/agents/local-runner-checkout.ts b/apps/server/src/agents/local-runner-checkout.ts new file mode 100644 index 000000000..606798b8f --- /dev/null +++ b/apps/server/src/agents/local-runner-checkout.ts @@ -0,0 +1,90 @@ +import { lstat } from "node:fs/promises"; +import type { + CheckoutObservation, + CheckoutRelease, + CheckoutReleaseResult, +} from "@dispatch/runner-protocol"; +import { cleanupGitWorktree } from "../shared/git/worktree.js"; +import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; +import { observeGitCheckout } from "./checkout-inspection.js"; + +/** Trusted native binding from the host. The selected workspace can move independently. */ +type LocalCheckoutBinding = { + id: string; + worktreePath: string | null; + worktreeBranch: string | null; + baseBranch: string | null; +}; + +const boundedGit: CommandRunner = (command, args, options) => + runCommand(command, args, { + ...options, + timeoutMs: options?.timeoutMs ?? 60_000, + }); + +class CheckoutChanged extends Error {} + +export function localCheckoutRelease( + binding: LocalCheckoutBinding, + operation: Extract +): Promise; +export function localCheckoutRelease( + binding: LocalCheckoutBinding, + operation: Extract +): Promise; +export async function localCheckoutRelease( + binding: LocalCheckoutBinding, + operation: CheckoutRelease +): Promise { + const { id, worktreePath, worktreeBranch, baseBranch } = binding; + if (operation.kind === "observe") { + const checkout = worktreePath + ? await observeGitCheckout(worktreePath, baseBranch).catch(() => null) + : null; + return { + ownership: worktreePath ? "owned" : "external", + owner: worktreePath ? id : null, + borrowers: [], + checkout, + }; + } + + if (!worktreePath) return "released"; + if (operation.expectedState === null) return "retained"; + const entry = await lstat(worktreePath).catch( + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return null; + throw error; + } + ); + if (!entry) return "released"; + const ownedBranch = + worktreeBranch && worktreeBranch !== baseBranch + ? worktreeBranch + : undefined; + + try { + await cleanupGitWorktree( + { + cwd: worktreePath, + deleteBranch: ownedBranch !== undefined, + deleteBranchOnlyIf: ownedBranch, + originalBranch: ownedBranch, + force: true, + async verifyBeforeRemove(resolvedWorktreePath) { + const checkout = await observeGitCheckout( + resolvedWorktreePath, + baseBranch + ).catch(() => null); + if (checkout?.stateId !== operation.expectedState) + throw new CheckoutChanged(); + }, + }, + boundedGit + ); + return "released"; + } catch (err) { + if (err instanceof CheckoutChanged) return "retained"; + throw err; + } +} diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index 0a04c248b..abc7fb8bb 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -32,6 +32,7 @@ import { } from "./workspace.js"; import { resolveWorkspace } from "./workspace-target.js"; import { resolveProjectRoot } from "../projects/resolve-root.js"; +import { localCheckoutRelease } from "./local-runner-checkout.js"; import { inferRepositoryUrl } from "./remote/repository.js"; export type LocalLaunchSettings = Pick< @@ -251,6 +252,7 @@ export function createLocalRunner( } return { requestSession, + checkoutRelease: localCheckoutRelease, resolveLaunchDirectory, canonicalPath: (directory: string) => realpath(directory).catch(() => null), resolveWorkspace, diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 4952a8c84..b6c70774e 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -2737,7 +2737,12 @@ export class AgentManager { let observation; try { - observation = await observeArchiveCheckout(this.pool, agent, this.remote); + observation = await observeArchiveCheckout( + this.pool, + agent, + this.localRunner, + this.remote + ); } catch { throw new AgentError( "Checkout status is unavailable on the owning runner.", @@ -2828,6 +2833,7 @@ export class AgentManager { await cleanupAgentWorktree( this.pool, this.logger, + this.localRunner, agent, mode ?? "auto", {} @@ -3022,6 +3028,7 @@ export class AgentManager { pool: this.pool, logger: this.logger, runtime: this.runtime, + localRunner: this.localRunner, remote: this.remote, diffStatsRefresher: this.diffStatsRefresher, getAgent: (id) => this.getAgent(id), diff --git a/apps/server/src/shared/git/worktree.ts b/apps/server/src/shared/git/worktree.ts index 7c7e4003f..b1511ab73 100644 --- a/apps/server/src/shared/git/worktree.ts +++ b/apps/server/src/shared/git/worktree.ts @@ -61,6 +61,9 @@ export type CleanupGitWorktreeInput = { baseBranch?: string; updateBaseBranch?: boolean; deleteBranch?: boolean; + /** When supplied, only this ref can be deleted as the current branch. */ + deleteBranchOnlyIf?: string; + verifyBeforeRemove?: (resolvedWorktreePath: string) => Promise; force?: boolean; /** The branch originally created for this worktree (from DB). If the agent * switched branches, this may differ from the current HEAD branch. When set @@ -290,10 +293,16 @@ export async function cleanupGitWorktree( worktreeRemoveArgs.push("--force"); } worktreeRemoveArgs.push(worktreePath); + await input.verifyBeforeRemove?.(worktreePath); await commandRunner("git", worktreeRemoveArgs); let deletedBranch = false; - if ((input.deleteBranch ?? false) && branchName) { + if ( + input.deleteBranch && + branchName && + (input.deleteBranchOnlyIf === undefined || + input.deleteBranchOnlyIf === branchName) + ) { await ensureBranchExists(repoRoot, branchName, commandRunner); await commandRunner("git", [ "-C", diff --git a/apps/server/test/agent-archive.test.ts b/apps/server/test/agent-archive.test.ts index 9785e9793..bb96fabef 100644 --- a/apps/server/test/agent-archive.test.ts +++ b/apps/server/test/agent-archive.test.ts @@ -17,6 +17,17 @@ import type { WorktreeCleanupMode, } from "../src/agents/types.js"; +vi.mock("node:fs/promises", async (importOriginal) => { + const fs = await importOriginal(); + return { + ...fs, + lstat: (path: string, ...options: []) => + path.startsWith("/tmp/wt") + ? Promise.resolve({}) + : fs.lstat(path, ...options), + }; +}); + vi.mock("../src/agents/lifecycle-hooks.js", () => ({ runLifecycleHook: vi.fn().mockResolvedValue(undefined), })); @@ -32,6 +43,7 @@ vi.mock("../src/agents/checkout-inspection.js", () => ({ import { runLifecycleHook } from "../src/agents/lifecycle-hooks.js"; import { cleanupGitWorktree } from "../src/shared/git/worktree.js"; import { observeGitCheckout } from "../src/agents/checkout-inspection.js"; +import { createLocalRunner } from "../src/agents/local-runner.js"; const cleanCheckout = { path: "/tmp/wt", @@ -125,6 +137,10 @@ const makeDeps = (overrides: Partial = {}): ArchiveDeps => { pool: pool as never, logger: noopLogger, runtime: makeRuntime(), + localRunner: createLocalRunner( + "/tmp/dispatch-unused-archive-hosts", + noopLogger + ), diffStatsRefresher: { clear: vi.fn() }, getAgent: vi.fn().mockResolvedValue(null), getRequiredAgent: vi.fn(), @@ -373,7 +389,7 @@ describe("executeArchive", () => { }); describe("worktree cleanup decision — force mode", () => { - it("always cleans up when mode is force, even with outstanding changes", async () => { + it("authorizes the observed checkout in force mode even with outstanding changes", async () => { vi.mocked(observeGitCheckout).mockResolvedValue({ ...cleanCheckout, unmerged: true, @@ -394,8 +410,24 @@ describe("executeArchive", () => { await executeArchive(deps, "a1", makeCallbacks()); expect(cleanupGitWorktree).toHaveBeenCalled(); - expect(observeGitCheckout).not.toHaveBeenCalled(); + expect(observeGitCheckout).toHaveBeenCalledWith("/tmp/wt", null); + }); + }); + + it("preserves a checkout when the built-in runner cannot observe it, even in force mode", async () => { + vi.mocked(observeGitCheckout).mockRejectedValueOnce( + new Error("Git status unavailable") + ); + const deps = makeDeps({ + getRequiredAgent: vi.fn().mockResolvedValue( + makeAgent("a1", { + worktreePath: "/tmp/wt", + archiveCleanupMode: "force", + }) + ), }); + await executeArchive(deps, "a1", makeCallbacks()); + expect(cleanupGitWorktree).not.toHaveBeenCalled(); }); describe("worktree cleanup decision — keep mode", () => { diff --git a/apps/server/test/checkout-inspection.test.ts b/apps/server/test/checkout-inspection.test.ts index 1aa63eca7..2ebc23f90 100644 --- a/apps/server/test/checkout-inspection.test.ts +++ b/apps/server/test/checkout-inspection.test.ts @@ -1,5 +1,6 @@ import { execFileSync, spawnSync } from "node:child_process"; import { + existsSync, mkdirSync, mkdtempSync, rmSync, @@ -22,6 +23,8 @@ import { } from "vitest"; import { inspectCheckout } from "../src/agents/checkout-inspection.js"; +import { createLocalRunner } from "../src/agents/local-runner.js"; +import type { FastifyBaseLogger } from "fastify"; let scratch: string; let cli: string; @@ -361,3 +364,60 @@ it("rejects malformed and oversized stdin with stderr and no reply", () => { expect(result.stderr).toMatch(diagnostic); } }); + +describe("native runner checkout release", () => { + function adapter() { + const binding = { + id: "agent/fixture", + worktreePath: checkout, + worktreeBranch: "feature", + baseBranch: "main", + }; + const runner = createLocalRunner( + path.join(fixture, "hosts"), + {} as FastifyBaseLogger + ); + return { + observe: () => runner.checkoutRelease(binding, { kind: "observe" }), + release: (expectedState: string) => + runner.checkoutRelease(binding, { kind: "release", expectedState }), + }; + } + + it("removes a clean switched worktree without deleting the separately owned ref", async () => { + git(repo, "branch", "user-owned", "main"); + const userTip = git(repo, "rev-parse", "refs/heads/user-owned"); + git(checkout, "switch", "user-owned"); + const runner = adapter(); + const { checkout: observed } = await runner.observe(); + expect(observed).toMatchObject({ + branch: "user-owned", + unmerged: false, + uncommittedFiles: [], + }); + expect(await runner.release(observed!.stateId)).toBe("released"); + expect(existsSync(checkout)).toBe(false); + expect(git(repo, "rev-parse", "refs/heads/user-owned")).toBe(userTip); + expect(await runner.release(observed!.stateId)).toBe("released"); + }); + + it("removes the owned branch when it is still checked out", async () => { + const runner = adapter(); + const { checkout: observed } = await runner.observe(); + expect(observed?.branch).toBe("feature"); + expect(await runner.release(observed!.stateId)).toBe("released"); + expect(existsSync(checkout)).toBe(false); + expect(git(repo, "branch", "--list", "feature")).toBe(""); + }); + + it("preserves a checkout edited after the runner observed it", async () => { + put(checkout, "draft.txt", "first version"); + const runner = adapter(); + const { checkout: observed } = await runner.observe(); + expect(observed?.uncommittedFiles).toEqual(["draft.txt"]); + put(checkout, "draft.txt", "second version"); + expect(await runner.release(observed!.stateId)).toBe("retained"); + expect(existsSync(path.join(checkout, "draft.txt"))).toBe(true); + expect(git(repo, "branch", "--list", "feature")).toContain("feature"); + }); +}); diff --git a/apps/server/test/db/agent-archive-branch-cleanup.test.ts b/apps/server/test/db/agent-archive-branch-cleanup.test.ts index 101f45b7d..5ab0e73cc 100644 --- a/apps/server/test/db/agent-archive-branch-cleanup.test.ts +++ b/apps/server/test/db/agent-archive-branch-cleanup.test.ts @@ -27,6 +27,17 @@ vi.mock("../../src/shared/lib/run-command.js", () => ({ runCommand: vi.fn(async () => ({ exitCode: 0, stdout: "", stderr: "" })), })); +vi.mock("../../src/agents/checkout-inspection.js", () => ({ + observeGitCheckout: vi.fn(async (path: string) => ({ + path, + branch: null, + stateId: "a".repeat(64), + unmerged: false, + changedFiles: [], + uncommittedFiles: [], + })), +})); + // Stub the worktree helpers so we can (a) skip real git work during archive // and (b) observe what AgentManager asks us to do. let fixtureRoot: string; diff --git a/e2e/worktree.spec.ts b/e2e/worktree.spec.ts index 68a7e57cd..fc718b1db 100644 --- a/e2e/worktree.spec.ts +++ b/e2e/worktree.spec.ts @@ -179,7 +179,7 @@ test.describe("Safe worktree archive", () => { }); }); - test("removes an unchanged clean checkout through Archive", async ({ + test("removes a clean switched checkout and preserves the existing branch through Archive", async ({ page, request, }, testInfo) => { @@ -188,6 +188,15 @@ test.describe("Safe worktree archive", () => { cwd: repoPath, useWorktree: true, }); + execSync("git branch user-owned main", { cwd: repoPath }); + const originalTip = execSync("git rev-parse user-owned", { + cwd: repoPath, + encoding: "utf8", + }); + execSync("git switch user-owned", { + cwd: agent.worktreePath!, + stdio: "ignore", + }); await loadApp(page); await page.getByTestId(`agent-expand-toggle-${agent.id}`).click(); await page.getByTestId(`agent-archive-${agent.id}`).click(); @@ -200,6 +209,9 @@ test.describe("Safe worktree archive", () => { await dialog.getByTestId("delete-agent-confirm").click(); await expect(page.getByTestId(`agent-card-${agent.id}`)).toHaveCount(0); expect(existsSync(agent.worktreePath!)).toBe(false); + expect( + execSync("git rev-parse user-owned", { cwd: repoPath, encoding: "utf8" }) + ).toBe(originalTip); }); test("keeps a dirty checkout changed between confirmation and removal", async ({ From 6d5e31ebe1c9c742d9552080043ea0e0b947eb4c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:33:19 -0700 Subject: [PATCH 136/642] Transfer prompt files and collect runner attachments --- apps/server/src/agents/acp/prompt-source.ts | 6 +- apps/server/src/agents/acp/runtime.ts | 17 ++- apps/server/src/agents/launch-guidance.ts | 9 +- apps/server/src/agents/manager.ts | 118 +++++++++++++++- apps/server/src/agents/remote/runner.ts | 41 ++++++ apps/server/src/agents/remote/service.ts | 26 ++++ .../server/src/agents/remote/session-files.ts | 100 +++++++++++++ .../src/agents/remote/session-supervisor.ts | 53 +++++++ apps/server/src/agents/runtime.ts | 1 + apps/server/src/chat/service.ts | 51 +++++-- apps/server/src/main.ts | 4 + apps/server/src/server/mcp-handlers.ts | 4 +- .../server/test/helpers/remote-acp-fixture.ts | 12 ++ .../test/remote-runner-supervisor.test.ts | 73 +++++++++- .../test/runner-protocol-consumer.test.ts | 129 ++++++++++++++++- docs/design/runner-capability-inventory.md | 4 +- docs/file-attachments.md | 16 +++ e2e/fixtures/fake-acp-agent.mjs | 19 +++ e2e/fixtures/runner-file-transfer.mjs | 52 +++++++ e2e/remote-runner/file-transfer.spec.ts | 132 ++++++++++++++++++ e2e/remote-runner/setup.mjs | 1 + packages/runner-protocol/README.md | 26 ++++ packages/runner-protocol/src/execution.ts | 9 ++ packages/runner-protocol/src/index.ts | 1 + packages/runner-protocol/src/session-files.ts | 59 ++++++++ 25 files changed, 934 insertions(+), 29 deletions(-) create mode 100644 apps/server/src/agents/remote/session-files.ts create mode 100644 e2e/fixtures/runner-file-transfer.mjs create mode 100644 e2e/remote-runner/file-transfer.spec.ts create mode 100644 packages/runner-protocol/src/session-files.ts diff --git a/apps/server/src/agents/acp/prompt-source.ts b/apps/server/src/agents/acp/prompt-source.ts index 7da7da1cf..5d0ae9308 100644 --- a/apps/server/src/agents/acp/prompt-source.ts +++ b/apps/server/src/agents/acp/prompt-source.ts @@ -1,5 +1,7 @@ -import type { PromptImage } from "@dispatch/runner-protocol"; -export type { PromptImage } from "@dispatch/runner-protocol"; +import type { PromptImage as WirePromptImage } from "@dispatch/runner-protocol"; + +/** Host-side attachment reference. A runner name marks an input to stage before ACP submission. */ +export type PromptImage = WirePromptImage & { runnerName?: string }; /** * What a prompt sent to the harness was, for the prompt a turn entry diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 51099efdb..5c838ba90 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -247,6 +247,10 @@ function sourceBlockIds(source?: PromptSource): string[] { } export type AcpRuntimeDeps = { + preparePromptFiles?: ( + agentId: string, + images: PromptImage[] + ) => Promise; remote?: Pick; remoteInbox?: Pick; recoverRemoteEvent?: (agentId: string) => Promise; @@ -455,6 +459,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const id = crypto.randomUUID(); let ended = false; let accepted = false; + let submitted = false; const onSettle = () => { ended = true; if (accepted) for (const w of batch) w.resolveSettled(); @@ -530,6 +535,14 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { : "default" ); } else { + const inputs = batch.flatMap((item) => item.images ?? []); + const images = inputs.some( + (input) => input.runnerName !== undefined + ) + ? await deps.preparePromptFiles?.(agentId, inputs) + : inputs; + if (!images) + throw new Error("Runner prompt file delivery is unavailable."); if (entry.remote) { const dir = stateDir(agentId); await mkdir(dir, { recursive: true, mode: 0o700 }); @@ -544,10 +557,10 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { ); } // Set this before submitting: ack and settle can arrive together. + submitted = true; entry.turnOpen = true; entry.turnBlockIds = new Set(sourceBlockIds(source)); entry.conversation = source?.conversation; - const images = batch.flatMap((item) => item.images ?? []); const outcome = await entry.client.prompt( id, text, @@ -576,7 +589,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { (w) => w !== onSettle ); for (const w of batch) finishDecision(w, "failed"); - if (!steering) entry.turnOpen = false; + if (submitted) entry.turnOpen = false; for (const w of batch) { w.rejectAccepted( error instanceof Error ? error : new Error(String(error)) diff --git a/apps/server/src/agents/launch-guidance.ts b/apps/server/src/agents/launch-guidance.ts index 632126657..565f49126 100644 --- a/apps/server/src/agents/launch-guidance.ts +++ b/apps/server/src/agents/launch-guidance.ts @@ -7,6 +7,7 @@ export type StartupFile = { displayName: string; source: string; description: string | null; + runnerPath?: string; }; /** @@ -85,7 +86,9 @@ export function buildStartupPrompt( const sections = [ "Startup context is attached to this session.", - "Inspect the provided links and shared files before acting. Use Dispatch shared-file tools to access attached files; do not try to locate them by searching the filesystem by name.", + initialFiles.some((file) => file.runnerPath) + ? "Inspect the provided links and shared files before acting. Resolve file paths using the session's DISPATCH_FILES_DIR." + : "Inspect the provided links and shared files before acting. Use Dispatch shared-file tools to access attached files; do not try to locate them by searching the filesystem by name.", ]; if (trimmedPrompt) { @@ -105,7 +108,9 @@ export function buildStartupPrompt( ...initialFiles.map((file) => { const detail = file.description?.trim(); const suffix = detail ? ` — ${detail}` : ""; - return `- ${file.displayName}${suffix} (available via dispatch shared files)`; + const location = + file.runnerPath ?? "available via dispatch shared files"; + return `- ${file.displayName}${suffix} (${location})`; }), ].join("\n") ); diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index b6c70774e..a072b9bfc 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,3 +1,4 @@ +import { readSessionFile } from "./remote/session-files.js"; import { readAgentView } from "./checkout-runner.js"; import type { CheckoutView } from "@dispatch/runner-protocol"; import { AttentionHistory } from "../notifications/attention-history.js"; @@ -9,7 +10,7 @@ import { } from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; import { randomUUID } from "node:crypto"; -import { mkdir, readFile, rm, unlink } from "node:fs/promises"; +import { mkdir, readFile, realpath, rm, unlink } from "node:fs/promises"; import path from "node:path"; import type { FastifyBaseLogger } from "fastify"; @@ -91,6 +92,8 @@ import { isSessionCheckout, validBranch, remotePlacement, + isSessionFileData, + isSessionFilePath, type RunnerRepository, type LaunchProgress, type CheckoutQuery, @@ -432,6 +435,7 @@ export class AgentManager { classifySteering: options.classifySteering, remote: this.remote, remoteInbox, + preparePromptFiles: (id, images) => this.preparePromptFiles(id, images), recoverRemoteEvent: (agentId) => remoteInbox.recover(agentId, (event) => this.handleRuntimeEvent(agentId, event, 0, true) @@ -716,6 +720,66 @@ export class AgentManager { this.cancelSchedules = cancel; } + async collectRunnerFile( + agent: AgentRecord, + filePath: string + ): Promise { + const placement = remotePlacement(agent.cwd); + if (!placement || !this.remote || !isSessionFilePath(filePath)) + throw new AgentError("Invalid runner session file path.", 400); + const { value } = await this.remote.requestSession(placement, { + agentId: agent.id, + kind: "sessionFile", + operation: { kind: "collect", path: filePath }, + }); + if (!isSessionFileData(value)) + throw new Error("Invalid runner file response."); + return Buffer.from(value, "base64"); + } + + private async preparePromptFiles( + id: string, + images: PromptImage[] + ): Promise { + if (!images.some((image) => image.runnerName !== undefined)) return images; + const agent = await this.getRequiredAgent(id); + const placement = remotePlacement(agent.cwd); + if (!placement || !this.remote) + throw new Error("Runner session is unavailable."); + const prepared: PromptImage[] = []; + const delivered = new Map(); + for (const { path: source, mimeType, runnerName } of images) { + if (runnerName === undefined) continue; + let destination = delivered.get(runnerName); + if (destination === undefined) { + const bytes = await readSessionFile( + await realpath(path.dirname(source)), + path.basename(source) + ); + const { value } = await this.remote.requestSession(placement, { + agentId: id, + kind: "sessionFile", + operation: { + kind: "deliver", + name: runnerName, + data: bytes.toString("base64"), + }, + }); + if (!isSessionFilePath(value) || !path.posix.isAbsolute(value)) + throw new Error("Invalid runner input file location."); + destination = value; + delivered.set(runnerName, destination); + } + if ( + ["image/png", "image/jpeg", "image/webp", "image/gif"].includes( + mimeType + ) + ) + prepared.push({ path: destination, mimeType }); + } + return prepared; + } + /** Queue one turn; see AgentRuntime.prompt. */ promptAgent( id: string, @@ -1583,14 +1647,21 @@ export class AgentManager { !useWorktreeOf && !options.taskPersonaBody && !input.templateId && - !input.jobRunId) || - input.initialFiles?.length + !input.jobRunId) ) { throw new AgentError( "Runner launches require a standalone agent and runner-managed storage.", 400 ); } + if ( + input.initialFiles?.length && + !this.remote.supportsSessionFiles(placement) + ) + throw new AgentError( + "Update the runner to launch with startup files.", + 409 + ); if (useWorktreeOf && !this.remote.supportsSharedWorktree(placement)) throw new AgentError( "Update the runner to launch an agent in an existing checkout.", @@ -2158,6 +2229,36 @@ export class AgentManager { jobRunId: opts.jobRunId, recordWorkspaceProgress: true, }); + const remote = remotePlacement(agent.cwd); + let images = chatLaunchPost?.images; + try { + if (remote) { + const filesDir = resolveFilesDir( + id, + agent.filesDir, + this.config.filesRoot + ); + images = await this.preparePromptFiles( + id, + images ?? + opts.initialFiles.map((file) => ({ + path: path.join(filesDir, file.fileName), + runnerName: file.fileName, + mimeType: "application/octet-stream", + })) + ); + } + } catch (error) { + await this.runtime + .stop(id, true) + .catch((err: unknown) => + this.logger.warn( + { err, agentId: id }, + "Runner host cleanup after file delivery failure" + ) + ); + throw error; + } await this.pool.query( `UPDATE agents SET status = 'running', cli_session_id = $2, setup_phase = NULL, updated_at = NOW() WHERE id = $1`, [id, sessionId] @@ -2173,7 +2274,12 @@ export class AgentManager { const firstTurn = buildStartupTurn( { initialPrompt: opts.initialPrompt, - initialFiles: opts.initialFiles, + initialFiles: remote + ? opts.initialFiles.map((file) => ({ + ...file, + runnerPath: `$DISPATCH_FILES_DIR/${file.fileName}`, + })) + : opts.initialFiles, chatLaunchPost, }, { jobRunId: opts.jobRunId } @@ -2183,9 +2289,7 @@ export class AgentManager { id, firstTurn, "first turn", - chatLaunchPost?.images?.length - ? { images: chatLaunchPost.images } - : undefined, + images?.length ? { images } : undefined, chatLaunchPost ? { source: "chat", chatMessageId: chatLaunchPost.messageId } : undefined diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index a156d0707..9b3cc46d5 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -23,6 +23,7 @@ import { parseServiceFrame, runnerRequestId, type Command, + MAX_SESSION_FILE_BASE64, type RunnerFrame, type RunnerEngine, } from "./protocol.js"; @@ -460,6 +461,45 @@ export async function runRemoteRunner(filename: string) { } if (socket.destroyed) return; switch (command.kind) { + case "sessionFile": + result( + await supervisor.sessionFile( + agentId, + workspace, + command.operation, + async (kind, root, name, data) => { + const child = execute( + setpriv, + [ + ...childArgs, + ...selfCommand("runner-session-file"), + kind, + root, + name, + ], + { + env, + timeout: 15_000, + signal: connection.signal, + maxBuffer: MAX_SESSION_FILE_BASE64 + 1024, + } + ); + child.child.stdin?.on("error", () => {}); + child.child.stdin?.end(data); + try { + return (await child).stdout; + } catch (error) { + throw new Error( + (error as { stderr?: string }).stderr + ?.trim() + .slice(0, 256) || "Runner file transfer failed." + ); + } + }, + target?.cwd + ) + ); + break; case "checkoutRelease": { const observation = await supervisor.checkoutRelease( agentId, @@ -688,6 +728,7 @@ export async function runRemoteRunner(filename: string) { workspacePreparation: true, sessionCheckout: true, checkoutRelease: true, + sessionFiles: true, checkoutViews: true, sharedWorktree: true, }); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 3a11ce088..08ada9b86 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -163,6 +163,8 @@ type Peer = { checkoutInspection: boolean; sessionCheckout: boolean; checkoutRelease: boolean; + sessionFiles: boolean; + sessionFileTail?: Promise; checkoutViews: boolean; sharedWorktree: boolean; workspacePreparation: boolean; @@ -692,6 +694,7 @@ export class RemoteRunnerService { checkoutViews: ready.checkoutViews === true, sessionCheckout: ready.sessionCheckout === true, checkoutRelease: ready.checkoutRelease === true, + sessionFiles: ready.sessionFiles === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, workspacePreparation: ready.workspacePreparation === true, @@ -1486,6 +1489,13 @@ export class RemoteRunnerService { ); } + supportsSessionFiles(placement: Placement) { + return ( + this.available(placement) && + this.peers.get(placement.runner)?.sessionFiles === true + ); + } + supportsSessionCheckout(placement: Placement) { return ( this.available(placement) && @@ -1553,6 +1563,10 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to use these checkout options." ); + if (command.kind === "sessionFile" && !peer.sessionFiles) + throw new RunnerCapabilityUnavailable( + "Update the runner to transfer session files." + ); if (command.kind === "checkoutRelease" && !peer.checkoutRelease) throw new RunnerCapabilityUnavailable( "Update the runner to inspect and release a session checkout." @@ -1582,6 +1596,18 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to prepare session workspaces." ); + if (command.kind === "sessionFile") { + // A single file can occupy most of the transport's write buffer. + const transfer = (peer.sessionFileTail ?? Promise.resolve()) + .catch(() => {}) + .then(() => peer.connection.request(command)); + peer.sessionFileTail = transfer; + try { + return await transfer; + } finally { + if (peer.sessionFileTail === transfer) peer.sessionFileTail = undefined; + } + } return peer.connection.request(command, { openChannel: open, onProgress }); } diff --git a/apps/server/src/agents/remote/session-files.ts b/apps/server/src/agents/remote/session-files.ts new file mode 100644 index 000000000..5a5fc93f5 --- /dev/null +++ b/apps/server/src/agents/remote/session-files.ts @@ -0,0 +1,100 @@ +import { randomUUID } from "node:crypto"; +import { rename, unlink, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import { + isSessionFileData, + isSessionFileName, + isSessionFilePath, + MAX_SESSION_FILE_BASE64, + MAX_SESSION_FILE_BYTES, +} from "@dispatch/runner-protocol"; +import { + openLinuxDirectory, + openRegularFile, +} from "../../files/open-workspace-file.js"; + +export async function readSessionFile(root: string, relative: string) { + if (!isSessionFilePath(relative) || path.isAbsolute(relative)) + throw new Error("Invalid relative session file path."); + const file = await openRegularFile(root, relative.split("/")); + try { + const stat = await file.stat(); + if (stat.nlink !== 1) + throw new Error("Hard-linked files cannot be collected."); + if (stat.size > MAX_SESSION_FILE_BYTES) + throw new Error("Session files are limited to 20 MiB."); + const bytes = Buffer.allocUnsafe(stat.size + 1); + let size = 0; + while (size < bytes.length) { + const { bytesRead } = await file.read( + bytes, + size, + bytes.length - size, + size + ); + if (!bytesRead) break; + size += bytesRead; + } + if (size !== stat.size || (await file.stat()).mtimeMs !== stat.mtimeMs) + throw new Error( + "Session file changed during transfer. Retry when it is stable." + ); + return bytes.subarray(0, size); + } finally { + await file.close(); + } +} + +async function deliverSessionFile(root: string, name: string, data: string) { + if (!isSessionFileName(name) || !isSessionFileData(data)) + throw new Error("Invalid session input file."); + const dir = await openLinuxDirectory(root); + const destination = `/proc/self/fd/${dir.fd}`; + const temp = path.join(destination, `.incoming-${randomUUID()}`); + try { + await writeFile(temp, Buffer.from(data, "base64"), { + flag: "wx", + mode: 0o600, + }); + await rename(temp, path.join(destination, name)); + } finally { + try { + await unlink(temp).catch(() => {}); + } finally { + await dir.close(); + } + } +} + +/** The supervisor supplies the root, and this process runs as the workload UID. */ +export async function runSessionFileCli( + kind: string, + root: string, + name: string +) { + try { + if (kind === "collect") { + process.stdout.write( + (await readSessionFile(root, name)).toString("base64") + ); + return; + } + let data = ""; + process.stdin.setEncoding("ascii"); + for await (const chunk of process.stdin) { + data += chunk; + if (data.length > MAX_SESSION_FILE_BASE64) + throw new Error("Session files are limited to 20 MiB."); + } + if (kind !== "deliver") throw new Error("Unknown session file operation."); + await deliverSessionFile(root, name, data); + } catch (error) { + const message = + error instanceof Error && !("code" in error) + ? error.message + : "Session file is unavailable."; + process.stderr.write(message); + process.exitCode = 1; + } +} diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 3cdfa62ee..4f9e82d90 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -21,6 +21,8 @@ import { MANAGED_WORKSPACE, isOpaqueId, isCheckoutPath, + isSessionFileOperation, + type SessionFileOperation, type SessionCheckout, type CheckoutObservation, type CheckoutRelease, @@ -874,6 +876,57 @@ export async function createSessionSupervisor( return launch(command, cwd, key, owner, progress); }); }, + sessionFile( + agentId: string, + workspace: string, + operation: SessionFileOperation, + transfer: ( + kind: SessionFileOperation["kind"], + root: string, + name: string, + data?: string + ) => Promise, + configuredCwd?: string + ) { + const key = runnerStorageKey(agentId); + return serialize(key, async () => { + if ( + !isSessionFileOperation(operation) || + !(await bound(key, workspace)) + ) + throw new Error("Invalid or unbound session file operation."); + const files = path.join(hostRoot, key, "files"); + if (operation.kind === "deliver") { + await transfer("deliver", files, operation.name, operation.data); + return path.join(files, operation.name); + } + const source = path.isAbsolute(operation.path) + ? path.normalize(operation.path) + : null; + if (source && containsDirectory(files, source)) + return transfer("collect", files, path.relative(files, source)); + const checkout = await selectedDirectory( + key, + workspace, + await initialDirectory(key, workspace, configuredCwd) + ); + const requested = source ?? path.join(checkout, operation.path); + const owner = checkoutOwner(await readBinding(key)) ?? key; + if ( + !containsDirectory(checkout, requested) || + (containsDirectory(storage, requested) && + !containsDirectory(path.join(sessions, owner), requested)) + ) + throw new Error( + "File path is outside this session's files and checkout." + ); + return transfer( + "collect", + checkout, + path.relative(checkout, requested) + ); + }); + }, async checkoutRelease( agentId: string, workspace: string, diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index 1335db1ad..ad5079efa 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -146,6 +146,7 @@ export function createAgentRuntime( AcpRuntimeDeps, | "hostSeq" | "syncJournal" + | "preparePromptFiles" | "remoteInbox" | "recoverRemoteEvent" | "classifySteering" diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index 673f29952..c45a5742e 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import { riskNotice } from "../agents/pull-request-risk-notice.js"; import { parseVisualization, @@ -235,7 +236,8 @@ export type StreamDeliveryAdapter = { export type StreamAgent = Pick< AgentRecord, "id" | "name" | "filesDir" | "status" ->; +> & + Partial>; export type StreamServiceDeps = { routingShadow?: { @@ -3607,7 +3609,11 @@ export class StreamService { return { id, attachmentLines, - images: await this.promptImages(attachments, input.agentId), + images: await this.promptImages( + attachments, + input.agentId, + input.agentId + ), postText, record: async () => { const block = await this.store.writeLaunchBriefing({ @@ -4368,7 +4374,6 @@ export class StreamService { ): Promise<{ held: boolean }> { const finding = await this.findingOf(block); const task = await this.taskRoot(block.streamId); - const images = await this.promptImages(block.attachments, block.streamId); const outcomes = new Map(); // A post to several agents keeps each outcome of its own, so one // recipient that never took it can be seen, and sent again, without @@ -4405,6 +4410,9 @@ export class StreamService { let held = false; for (const agentId of recipients) { const own = perRecipient(agentId); + const images = own.rawPrompt + ? [] + : await this.promptImages(block.attachments, block.streamId, agentId); // A cancellation closes the ask the same way an answer does: it // resumes the work the ask came from rather than opening a thread. const closes = own.answers ?? own.cancels; @@ -5245,16 +5253,23 @@ export class StreamService { /** Native image references come only from resolved attachment metadata. */ private async promptImages( attachments: ChatAttachment[], - fallbackOwnerId: string + fallbackOwnerId: string, + recipientId: string ): Promise { + const recipient = attachments.some( + (attachment) => attachment.type === "file" + ) + ? await this.deps.getAgent(recipientId) + : null; + const remote = remotePlacement(recipient?.cwd ?? ""); const images: PromptImage[] = []; for (const attachment of attachments) { if ( attachment.type !== "file" || - !attachment.mimeType || - !["image/png", "image/jpeg", "image/webp", "image/gif"].includes( - attachment.mimeType - ) + (!remote && + !["image/png", "image/jpeg", "image/webp", "image/gif"].includes( + attachment.mimeType ?? "" + )) ) continue; // Attachment metadata was resolved against the file registry on posting. @@ -5268,12 +5283,25 @@ export class StreamService { resolveFilesDir(owner.id, owner.filesDir, this.deps.filesRoot), attachment.fileName ), - mimeType: attachment.mimeType, + mimeType: attachment.mimeType ?? "application/octet-stream", + ...(remote && { + runnerName: this.runnerInputName(attachment, owner, recipientId), + }), }); } return images; } + private runnerInputName( + attachment: Extract, + owner: StreamAgent, + recipientId: string + ): string { + return owner.id === recipientId + ? attachment.fileName + : `attachment-${attachment.fileId}${path.extname(attachment.fileName).slice(0, 32)}`; + } + /** Keep file-tool fallback paths aligned with the actual attachment owner. */ private async describeAttachments( agent: StreamAgent, @@ -5292,9 +5320,12 @@ export class StreamService { owner.filesDir, this.deps.filesRoot ); + const filePath = remotePlacement(agent.cwd ?? "") + ? `$DISPATCH_FILES_DIR/${this.runnerInputName(attachment, owner, agent.id)}` + : path.join(filesDir, attachment.fileName); const mime = attachment.mimeType ?? "application/octet-stream"; lines.push( - `- file: ${path.join(filesDir, attachment.fileName)} (${mime}, ${formatAttachmentSize(attachment.sizeBytes)})${attachment.caption ? ` caption: ${JSON.stringify(attachment.caption)}` : ""}` + `- file: ${filePath} (${mime}, ${formatAttachmentSize(attachment.sizeBytes)})${attachment.caption ? ` caption: ${JSON.stringify(attachment.caption)}` : ""}` ); break; } diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index f66e856ca..7816278fc 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -54,6 +54,10 @@ if (process.argv[2]?.startsWith("recovery-")) { warn() {}, }); if (!installed) process.exitCode = 1; +} else if (process.argv[2] === "runner-session-file") { + const { runSessionFileCli } = + await import("./agents/remote/session-files.js"); + await runSessionFileCli(process.argv[3]!, process.argv[4]!, process.argv[5]!); } else if (process.argv[2] === "runner-view-checkout") { const { runCheckoutViewCli } = await import("./agents/checkout-view-cli.js"); await runCheckoutViewCli(process.argv[3]!, process.argv[4] === "--managed"); diff --git a/apps/server/src/server/mcp-handlers.ts b/apps/server/src/server/mcp-handlers.ts index 2a230379f..aa59fd3fc 100644 --- a/apps/server/src/server/mcp-handlers.ts +++ b/apps/server/src/server/mcp-handlers.ts @@ -682,7 +682,9 @@ async function handleShareFile( if (!agent) throw new Error("Agent not found."); if (opts.update) assertValidStoredFileName(opts.update); - const buffer = await readFile(opts.filePath); + const buffer = remotePlacement(agent.cwd) + ? await deps.agentManager.collectRunnerFile(agent, opts.filePath) + : await readFile(opts.filePath); // Typed against the name it will be stored and shown under. const type = detectFileType( buffer, diff --git a/apps/server/test/helpers/remote-acp-fixture.ts b/apps/server/test/helpers/remote-acp-fixture.ts index 1d58a6f59..bdb37ab9c 100644 --- a/apps/server/test/helpers/remote-acp-fixture.ts +++ b/apps/server/test/helpers/remote-acp-fixture.ts @@ -1,3 +1,4 @@ +import { proveFileTransfer } from "../../../../e2e/fixtures/runner-file-transfer.mjs"; // A standalone deterministic ACP provider for the isolated runner proof. import { appendFile, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -6,9 +7,20 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/ import { createFakeAcpAgent } from "./fake-acp-agent.js"; const fake = createFakeAcpAgent({ + supportsImages: true, async turn(prompt, emit, ask) { const session = fake.seen.newSession.at(-1) ?? fake.seen.resumeSession.at(-1)!; + if (prompt.includes("proof-file-transfer")) { + await proveFileTransfer( + prompt, + fake.seen.promptBlocks.at(-1), + session, + Client, + StreamableHTTPClientTransport + ); + return "end_turn"; + } const report = (text: string) => emit({ sessionUpdate: "agent_message_chunk", diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index 40cf528ba..6e6579588 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -1,6 +1,7 @@ import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import { + link, mkdir, mkdtemp, open, @@ -14,13 +15,17 @@ import { import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MANAGED_WORKSPACE } from "../src/agents/remote/protocol.js"; +import { + MANAGED_WORKSPACE, + MAX_SESSION_FILE_BYTES, +} from "../src/agents/remote/protocol.js"; import { parseProcessStat, runnerStateLockError, type SessionIdentity, type SessionProcesses, } from "../src/agents/remote/session-processes.js"; +import { readSessionFile } from "../src/agents/remote/session-files.js"; import { createSessionSupervisor } from "../src/agents/remote/session-supervisor.js"; import { @@ -253,6 +258,72 @@ describe("runner session supervision", () => { expect(processes.stop).toHaveBeenCalledExactlyOnceWith(identity, false); }); + it("bounds collection and rejects symlinks and hard links on disk", async () => { + const dir = await realpath(root); + const original = path.join(dir, "original.txt"); + await writeFile(original, "complete"); + expect(await readSessionFile(dir, "original.txt")).toEqual( + Buffer.from("complete") + ); + await symlink(original, path.join(dir, "symlink.txt")); + await expect(readSessionFile(dir, "symlink.txt")).rejects.toThrow(); + await link(original, path.join(dir, "hardlink.txt")); + await expect(readSessionFile(dir, "hardlink.txt")).rejects.toThrow( + "Hard-linked" + ); + const large = await open(path.join(dir, "large.txt"), "w"); + try { + await large.truncate(MAX_SESSION_FILE_BYTES + 1); + } finally { + await large.close(); + } + await expect(readSessionFile(dir, "large.txt")).rejects.toThrow("20 MiB"); + }); + + it("collects only from the bound session, including when the configured checkout contains runner state", async () => { + const runner = await start(["configured"]); + const cwd = await realpath(root); + const transfer = vi.fn(async () => "YWJj"); + const first = launch("configured"); + await runner.launch(first, cwd); + kernelHost = undefined; + const other = "agt_other"; + record = path.join(state, "bindings", other + ".host"); + await runner.launch({ ...first, agentId: other }, cwd); + const own = path.join(state, "hosts", agentId, "files", "input.txt"); + const foreign = path.join(state, "hosts", other, "files", "input.txt"); + const collect = (id: string, file: string, workspace = first.workspace) => + runner.sessionFile( + id, + workspace, + { kind: "collect", path: file }, + transfer, + cwd + ); + expect(await collect(agentId, own)).toBe("YWJj"); + expect(await collect(agentId, "generated/report.txt")).toBe("YWJj"); + expect(transfer).toHaveBeenNthCalledWith( + 1, + "collect", + path.dirname(own), + "input.txt" + ); + expect(transfer).toHaveBeenNthCalledWith( + 2, + "collect", + cwd, + "generated/report.txt" + ); + for (const [id, file] of [ + [agentId, foreign], + [other, own], + [agentId, "../input.txt"], + ["unbound/session", own], + ] as const) + await expect(collect(id, file)).rejects.toThrow(); + expect(transfer).toHaveBeenCalledTimes(2); + }); + it("treats a recycled PID as stale and leaves an unrelated host running", async () => { const running = await start(["configured"]); await running.launch(launch("configured"), root); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 20c2b3aec..6bcb5ad01 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -17,6 +17,8 @@ import { runnerRequestId, sessionCommandId, isOpaqueId, + isSessionFileData, + MAX_SESSION_FILE_BYTES, isCheckoutReply, isSessionCheckout, isCheckoutObservation, @@ -740,6 +742,7 @@ function fixtureRunner(current: boolean) { pullRequestWatch: true, sessionCheckout: true, checkoutRelease: true, + sessionFiles: true, }), }; const sample = { @@ -772,12 +775,17 @@ function fixtureRunner(current: boolean) { let selectedCheckout = "/workload/launch"; const stateId = "b".repeat(64); let released = false; + const files = new Map(); - function connect() { + function connect(cut?: "partial-frame" | "lost-ack") { const service = new Duplex({ read() {}, write(chunk, _encoding, done) { - runner.push(chunk); + if (cut === "partial-frame") { + runner.push(chunk.subarray(0, Math.floor(chunk.length / 2))); + service.destroy(); + runner.destroy(); + } else runner.push(chunk); done(); }, }); @@ -873,6 +881,21 @@ function fixtureRunner(current: boolean) { command.agentId !== agentId ) { reply({ type: "result", id, error: "Unknown session binding" }); + } else if (command.kind === "sessionFile" && current && running) { + const operation = command.operation; + const root = "/workload/files/"; + if (operation.kind === "deliver") { + files.set(root + operation.name, operation.data); + if (cut === "lost-ack") { + service.destroy(); + runner.destroy(); + } else result(root + operation.name); + } else { + const bytes = files.get(operation.path); + if (bytes === undefined) + reply({ type: "result", id, error: "File unavailable" }); + else result(bytes); + } } else if (command.kind === "checkoutRelease" && current) { if (command.operation.kind === "observe") { result( @@ -1359,3 +1382,105 @@ it.each([true, false])( } } ); + +it.each([true, false])( + "independent service negotiates and retries a complete session file: %s", + async (current) => { + const runner = fixtureRunner(current); + const peer = runner.connect(); + const data = Buffer.from([0, 255, 128]).toString("base64"); + const deliver = { + ...runner.session, + kind: "sessionFile", + operation: { kind: "deliver", name: "sample.bin", data }, + } as const; + const collect = { + ...runner.session, + kind: "sessionFile", + operation: { kind: "collect", path: "/workload/files/sample.bin" }, + } as const; + try { + await vi.waitFor(() => expect(peer.reports[0]).toBeDefined()); + expect(parseReadyFrame(peer.reports[0])?.sessionFiles).toBe( + current ? true : undefined + ); + if (!current) { + expect(runner.requests).toHaveLength(0); + return; + } + await peer.connection.request({ + ...runner.session, + kind: "launch", + launch: { + agentId: runner.session.agentId, + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + }, + }); + for (const [cut, written] of [ + ["partial-frame", false], + ["lost-ack", true], + ] as const) { + const interrupted = runner.connect(cut); + try { + await expect( + interrupted.connection.request(deliver) + ).rejects.toBeInstanceOf(RunnerUnavailable); + if (written) + expect((await peer.connection.request(collect)).value).toBe(data); + else + await expect(peer.connection.request(collect)).rejects.toThrow( + "File unavailable" + ); + } finally { + interrupted.close(); + } + } + expect((await peer.connection.request(deliver)).value).toBe( + collect.operation.path + ); + const collected = (await peer.connection.request(collect)).value; + expect(isSessionFileData(collected)).toBe(true); + expect(collected).toBe(data); + await expect( + peer.connection.request({ ...collect, agentId: "other/session" }) + ).rejects.toThrow("Unknown session binding"); + } finally { + peer.close(); + } + } +); + +it("bounds decoded session files and rejects unsafe paths at the wire boundary", () => { + expect( + isSessionFileData(Buffer.alloc(MAX_SESSION_FILE_BYTES).toString("base64")) + ).toBe(true); + expect( + isSessionFileData( + Buffer.alloc(MAX_SESSION_FILE_BYTES + 1).toString("base64") + ) + ).toBe(false); + expect(isSessionFileData("a=a=")).toBe(false); + expect(isSessionFileData("")).toBe(true); + for (const operation of [ + { kind: "deliver", name: "../file", data: "" }, + { kind: "deliver", name: "slash/file", data: "" }, + { kind: "collect", path: "/root/../other/file" }, + { kind: "collect", path: "path\0name" }, + ]) { + expect( + parseServiceFrame({ + type: "request", + id: "file/42", + command: { + workspace: "my/space", + agentId: "my/session", + kind: "sessionFile", + operation, + }, + }) + ).toBeNull(); + } +}); diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 6cd2f664b..88a2b864a 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -64,9 +64,9 @@ A native host can complete an accepted turn while its controller is down. A repl - Expand a directory and open a file in the runner checkout. A path escaping the workspace is refused there. [Workspace routes](../../apps/server/src/routes/agents/workspace-routes.ts) · [File explorer](../file-explorer.md) -**Move attachments across the boundary.** **Partial.** Dispatch stores and serves user-visible attachments. Initial files, images supplied to a prompt, and files a runner agent posts by path require explicit delivery or collection. A runner-local file path in a chat post is insufficient. +**Move attachments across the boundary.** **Present.** Dispatch keeps the durable copies and attachment records. The optional runner capability delivers startup files and prompt attachments into the receiving session and collects files posted from its files directory or checkout. -- Upload an image, deliver it to one runner agent, then have it post a generated file that opens after its session is archived. [File routes](../../apps/server/src/routes/files.ts) · [Prompt images](../../apps/server/src/agents/acp/prompt-images.ts) · [Attachment behavior](../file-attachments.md) +- Playwright sends a startup image and a composer image to both native and Linux runner sessions, compares the agent's local bytes with the ACP image block, and opens the posted copy after archive. The independent consumer covers interrupted requests, retries, size limits, and capability negotiation. The runner supervisor tests cover isolation between session file directories. [Playwright workflow](../../e2e/remote-runner/file-transfer.spec.ts) · [Protocol](../../packages/runner-protocol/README.md#session-files) · [Attachment behavior](../file-attachments.md) ### Repository automation and cleanup diff --git a/docs/file-attachments.md b/docs/file-attachments.md index 00368ee3b..e8d408d6f 100644 --- a/docs/file-attachments.md +++ b/docs/file-attachments.md @@ -26,3 +26,19 @@ shorten the name; names are never truncated. File-ID and name attachments continue to resolve through the existing registry and allowed-owner query. Validation does not change which owners a caller may attach from, or the owner-independent authenticated file-ID metadata lookup. + +## Runner sessions + +Dispatch keeps the authoritative bytes and attachment records on the host. +Local sessions continue to read the shared directory directly. On runners +that advertise session file transfer, startup files and prompt attachments are +copied into the receiving workload's `DISPATCH_FILES_DIR`. Input paths in +remote prompts refer to that directory. Image attachments also become native +ACP image blocks on adapters that accept them, subject to the existing +native-image limits. + +When an agent posts an attachment by path, Dispatch collects a complete +copy before registering the file. Remote paths can point into the session +files directory or its effective checkout. Relative paths resolve inside +the checkout. Remote transfers support regular files up to 20 MiB. Browser +URLs still resolve to the Dispatch copy after the runner session is archived. diff --git a/e2e/fixtures/fake-acp-agent.mjs b/e2e/fixtures/fake-acp-agent.mjs index cfe54839f..3123cb56f 100755 --- a/e2e/fixtures/fake-acp-agent.mjs +++ b/e2e/fixtures/fake-acp-agent.mjs @@ -6,6 +6,7 @@ // three that publish one, nested tool calls for Claude, a permission ask // for OpenCode, and honors set_mode for Gemini. It never calls a model and // only reads a workspace marker when the runner review fixture requests it. +import { proveFileTransfer } from "./runner-file-transfer.mjs"; import { existsSync, readFileSync } from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; @@ -68,6 +69,7 @@ if (!PROFILE) { let conn; const cwdBySession = new Map(); +const mcpBySession = new Map(); const modelBySession = new Map(); const SLEEP = /sleep:(\d+)/; const RUN = /run:(\d+)/; @@ -100,6 +102,7 @@ const agent = { agentInfo: { name: `fake-${ENGINE}`, version: "0.0.0" }, agentCapabilities: { mcpCapabilities: { http: true }, + promptCapabilities: { image: true }, sessionCapabilities: { close: {}, resume: {} }, }, authMethods: [], @@ -119,6 +122,7 @@ const agent = { async newSession(params) { const sessionId = `fake_${ENGINE}_${Date.now()}`; cwdBySession.set(sessionId, params.cwd); + mcpBySession.set(sessionId, params.mcpServers); setTimeout(() => { void conn.sessionUpdate({ sessionId, @@ -143,6 +147,7 @@ const agent = { }, async resumeSession(params) { cwdBySession.set(params.sessionId, params.cwd); + mcpBySession.set(params.sessionId, params.mcpServers); return { configOptions: configOptions(params.sessionId) }; }, async setSessionMode() { @@ -204,6 +209,20 @@ const agent = { const text = params.prompt .map((b) => (b.type === "text" ? b.text : "")) .join(""); + if (text.includes("proof-file-transfer")) { + const { Client } = require("@modelcontextprotocol/sdk/client/index.js"); + const { + StreamableHTTPClientTransport, + } = require("@modelcontextprotocol/sdk/client/streamableHttp.js"); + await proveFileTransfer( + text, + params.prompt, + { mcpServers: mcpBySession.get(params.sessionId) }, + Client, + StreamableHTTPClientTransport + ); + return { stopReason: "end_turn" }; + } if (text.includes("background-preview-fixture")) { for (const update of [ { diff --git a/e2e/fixtures/runner-file-transfer.mjs b/e2e/fixtures/runner-file-transfer.mjs new file mode 100644 index 000000000..22c4f228e --- /dev/null +++ b/e2e/fixtures/runner-file-transfer.mjs @@ -0,0 +1,52 @@ +import { readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export async function proveFileTransfer( + text, + blocks, + session, + Client, + Transport +) { + const image = blocks.find((block) => block.type === "image"); + const reference = /- file: (.+) \(image\/png,/.exec(text)?.[1]; + if (!reference || !image) + throw new Error("Missing prompt image or file reference"); + const output = path.join( + process.env.DISPATCH_FILES_DIR, + "transfer-output.png" + ); + const input = await readFile( + reference.replace("$DISPATCH_FILES_DIR", process.env.DISPATCH_FILES_DIR) + ); + if (!input.equals(Buffer.from(image.data, "base64"))) + throw new Error("Image and on-machine file differ"); + await writeFile(output, input); + + const endpoint = session.mcpServers.find( + (entry) => "url" in entry && "headers" in entry + ); + if (!endpoint) throw new Error("Missing Dispatch MCP endpoint"); + const client = new Client({ name: "file-transfer-fixture", version: "1" }); + await client.connect( + new Transport(new URL(endpoint.url), { + requestInit: { + headers: Object.fromEntries( + endpoint.headers.map(({ name, value }) => [name, value]) + ), + }, + }) + ); + try { + const post = await client.callTool({ + name: "post", + arguments: { + text: "Read the uploaded image and posted the result.", + attachments: [{ type: "file", path: output }], + }, + }); + if (post.isError) throw new Error(JSON.stringify(post.content)); + } finally { + await client.close(); + } +} diff --git a/e2e/remote-runner/file-transfer.spec.ts b/e2e/remote-runner/file-transfer.spec.ts new file mode 100644 index 000000000..ffeea6aae --- /dev/null +++ b/e2e/remote-runner/file-transfer.spec.ts @@ -0,0 +1,132 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { expect, test } from "@playwright/test"; +import { authHeaders, cleanupE2EAgents, trackAgent } from "../helpers"; +import { chat, enrollViaUi, state } from "./harness"; + +const png = readFileSync( + new URL("../../apps/web/public/icons/teal/pwa-192.png", import.meta.url) +); +const image = { + name: "transfer-input.png", + mimeType: "image/png", + buffer: png, +}; + +test.afterAll(async ({ request }) => cleanupE2EAgents(request)); + +test("file transfer keeps local and remote posted bytes after archive", async ({ + browser, + page, + request, +}, testInfo) => { + const runnerId = await enrollViaUi(page, request, "alpha"); + for (const [lane, cwd, viewport] of [ + ["local", "/tmp", { width: 1440, height: 900 }], + [ + "remote", + `runner://${runnerId}/${state.workspace}`, + { width: 390, height: 844 }, + ], + ] as const) { + const context = await browser.newContext({ + viewport, + deviceScaleFactor: 2, + }); + try { + const session = await context.newPage(); + const launch = await request.post("/api/v1/agents", { + headers: authHeaders(), + multipart: { + name: `e2e-transfer-${lane}`, + cwd, + type: "codex", + useWorktree: "false", + initialPrompt: "proof-file-transfer startup", + startupFiles: image, + }, + }); + expect(launch.status(), await launch.text()).toBe(201); + const { + agent: { id }, + } = await launch.json(); + trackAgent(id); + const filesUrl = `/api/v1/agents/${id}/files`; + const posted = async () => { + const response = await request.get(filesUrl, { + headers: authHeaders(), + }); + return (await response.json()).files.filter((file: { name: string }) => + file.name.startsWith("transfer-output-") + ); + }; + const turnMessage = "Read the uploaded image and posted the result."; + await session.goto(`/agents/${id}`, { waitUntil: "domcontentloaded" }); + await expect(session.getByText(turnMessage, { exact: true })).toHaveCount( + 1, + { timeout: 45_000 } + ); + await expect.poll(async () => (await posted()).length).toBe(1); + + const fileInput = session.getByTestId("chat-composer-file-input"); + await expect(session.getByTestId("chat-composer-input")).toBeEnabled(); + await fileInput.setInputFiles(image); + await expect( + session.getByTestId("chat-composer-attachments") + ).toBeVisible(); + await chat(session, "proof-file-transfer follow-up"); + await expect(session.getByText(turnMessage, { exact: true })).toHaveCount( + 2, + { timeout: 45_000 } + ); + const copies = await posted(); + expect(copies).toHaveLength(2); + const retained = copies[0].url; + + const shot = (phase: string) => { + const name = `runner-transfer-${lane}-${phase}.png`; + const directory = process.env.RUNNER_TRANSFER_EVIDENCE; + return session + .screenshot({ + path: directory + ? path.join(directory, name) + : testInfo.outputPath(name), + }) + .then((body) => + testInfo.attach(name, { body, contentType: "image/png" }) + ); + }; + await shot("posted"); + const archive = await request.delete(`/api/v1/agents/${id}`, { + headers: authHeaders(), + }); + expect(archive.status(), await archive.text()).toBe(202); + await expect + .poll( + async () => + ( + await request.get(`/api/v1/agents/${id}`, { + headers: authHeaders(), + }) + ).status(), + { timeout: 45_000 } + ) + .toBe(404); + const opened = await session.goto(retained, { + waitUntil: "domcontentloaded", + }); + expect(opened?.ok()).toBe(true); + expect(await opened!.body()).toEqual(png); + await expect + .poll(() => + session + .locator("img") + .evaluate((image: HTMLImageElement) => image.naturalWidth) + ) + .toBe(192); + await shot("retained"); + } finally { + await context.close(); + } + } +}); diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs index 09eafcd3a..65fc38884 100644 --- a/e2e/remote-runner/setup.mjs +++ b/e2e/remote-runner/setup.mjs @@ -48,6 +48,7 @@ function artifacts(arch) { const inputs = [ "apps/server/src", "apps/server/test/helpers", + "e2e/fixtures/runner-file-transfer.mjs", "packages/runner-protocol", "pnpm-lock.yaml", ]; diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 76b436711..419d63c83 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -443,3 +443,29 @@ released and its owned checkout was kept, and `inUse` means live borrower bindings still hold the checkout. Retry a deferred release using the same authorization. Repeating a release is safe, including after a lost reply. The legacy `discard` command keeps its original behavior for clients using it. + +## Session files + +A runner advertises `sessionFiles: true` in `ready` to enable the +`sessionFile` command. Send it with the same opaque `agentId` and +`workspace` used to launch the session. Peers that omit the flag continue +to use the existing lifecycle and prompt protocol. + +- `operation: { kind: "deliver", name, data }` writes a complete file to the + session's input directory. `name` is a single filename. `data` is padded + standard base64. The result value is the absolute runner path for the + workload to read, including as an ACP prompt image path. +- `operation: { kind: "collect", path }` reads a regular file from the session + files directory or the effective checkout. Absolute paths must belong to one + of those roots. Relative paths are relative to the effective checkout. + The result value is padded standard base64. Traversal, symlinks, hard links, + and paths outside the bound session's roots are rejected. A deliberately + shared checkout grants access to its shared files. + +Each file holds at most 20 MiB of decoded bytes, including zero-byte files. +Send one transfer at a time per connection. There is no transfer cursor. +An interrupted frame creates no visible file. If a delivery completed but +the acknowledgement was lost, repeat the whole request with the same name +and bytes. Delivery replaces the named file atomically. Collection is +read-only and retries re-read the current file. Commit each successful +collection to service-owned storage before publishing a reference to it. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index ee06496fa..ff5816f31 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,3 +1,7 @@ +import { + isSessionFileOperation, + type SessionFileOperation, +} from "./session-files.js"; import { isCheckoutView, type CheckoutView } from "./checkout-view.js"; import { isCheckoutQuery, @@ -63,6 +67,7 @@ export type SessionLifecycleOperation = { agentId: string } & ( export type SessionOperation = | SessionLifecycleOperation + | { agentId: string; kind: "sessionFile"; operation: SessionFileOperation } | { agentId: string; kind: "watchCheckout" } | { agentId: string; kind: "viewCheckout"; query: CheckoutView } | { agentId: string; kind: "inspectCheckout"; query: CheckoutQuery } @@ -101,6 +106,7 @@ export type ReadyFrame = { workspacePreparation?: true; sessionCheckout?: true; checkoutRelease?: true; + sessionFiles?: true; }; /** Accept v1 extension fields and enable optional features only when explicitly true. */ @@ -126,6 +132,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.checkoutViews === true && { checkoutViews: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), + ...(frame.sessionFiles === true && { sessionFiles: true }), ...(frame.checkoutRelease === true && { checkoutRelease: true }), ...(frame.sessionCheckout === true && { sessionCheckout: true }), ...(frame.workspacePreparation === true && { workspacePreparation: true }), @@ -306,6 +313,8 @@ function isCommand(value: unknown): value is Command { (value.launch.useWorktreeOf === undefined || value.agentId === value.launch.agentId) ); + case "sessionFile": + return isSessionFileOperation(value.operation); case "checkoutRelease": return isCheckoutRelease(value.operation); case "sessionCheckout": diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index 285173c49..cca55243b 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -6,3 +6,4 @@ export * from "./health.js"; export * from "./checkout.js"; export * from "./github.js"; export * from "./checkout-view.js"; +export * from "./session-files.js"; diff --git a/packages/runner-protocol/src/session-files.ts b/packages/runner-protocol/src/session-files.ts new file mode 100644 index 000000000..99937a388 --- /dev/null +++ b/packages/runner-protocol/src/session-files.ts @@ -0,0 +1,59 @@ +import { isRecord } from "./validation.js"; + +/** A complete file fits within one v1 frame, including base64 overhead. */ +export const MAX_SESSION_FILE_BYTES = 20 * 1024 * 1024; +export const MAX_SESSION_FILE_BASE64 = + Math.ceil(MAX_SESSION_FILE_BYTES / 3) * 4; + +export type SessionFileOperation = + | { kind: "deliver"; name: string; data: string } + | { kind: "collect"; path: string }; + +export function isSessionFileData(value: unknown): value is string { + if ( + typeof value !== "string" || + value.length > MAX_SESSION_FILE_BASE64 || + value.length % 4 !== 0 + ) + return false; + const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0; + return ( + (value.length / 4) * 3 - padding <= MAX_SESSION_FILE_BYTES && + !/[^A-Za-z0-9+/]/u.test(value.slice(0, value.length - padding)) + ); +} + +export function isSessionFileName(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= 255 && + value !== "." && + value !== ".." && + !/[^A-Za-z0-9 ._()-]/u.test(value) + ); +} + +export function isSessionFilePath(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= 4096 && + !/[\\\x00-\x1f\x7f]/u.test(value) && + !value.split("/").includes("..") + ); +} + +export function isSessionFileOperation( + value: unknown +): value is SessionFileOperation { + if (!isRecord(value)) return false; + switch (value.kind) { + case "deliver": + return isSessionFileName(value.name) && isSessionFileData(value.data); + case "collect": + return isSessionFilePath(value.path); + default: + return false; + } +} From d5317794965258a9d45669a3432bdcc1f06faf30 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:39:47 -0700 Subject: [PATCH 137/642] Route native attachments through the built-in runner --- apps/server/src/agents/local-runner.ts | 89 +++++++++++++- apps/server/src/agents/manager.ts | 111 ++++++++++++------ .../server/src/agents/remote/session-files.ts | 40 +------ apps/server/src/chat/service.ts | 4 +- apps/server/src/files/session-file.ts | 48 ++++++++ apps/server/src/server/mcp-handlers.ts | 9 +- apps/server/test/file-routes.test.ts | 106 ++++++++++++++++- apps/server/test/mcp-handlers.test.ts | 26 ++-- .../test/remote-runner-supervisor.test.ts | 2 +- apps/server/test/stream-service.test.ts | 6 +- docs/design/runner-capability-inventory.md | 2 +- docs/file-attachments.md | 19 +-- e2e/fixtures/fake-acp-agent.mjs | 3 +- e2e/fixtures/runner-file-transfer.mjs | 21 ++-- 14 files changed, 374 insertions(+), 112 deletions(-) create mode 100644 apps/server/src/files/session-file.ts diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index abc7fb8bb..2c3f88f13 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -13,7 +13,15 @@ import net from "node:net"; import path from "node:path"; import type { Duplex } from "node:stream"; import type { FastifyBaseLogger } from "fastify"; -import type { SessionLifecycleOperation } from "@dispatch/runner-protocol"; +import { + isSessionFileName, + isSessionFilePath, + type SessionLifecycleOperation, +} from "@dispatch/runner-protocol"; +import { + openBoundedSessionFile, + readSessionFile, +} from "../files/session-file.js"; import { killOwnedProcesses, ownedEnvironment, @@ -81,6 +89,26 @@ function signalGroup(pid: number, signal: NodeJS.Signals): void { } } +function containsPath(directory: string, file: string) { + const compare = (value: string) => + process.platform === "darwin" + ? value.normalize("NFC").toLowerCase() + : value; + const relative = path.relative(compare(directory), compare(file)); + return ( + relative !== ".." && + !relative.startsWith(".." + path.sep) && + !path.isAbsolute(relative) + ); +} + +function realpathIfPresent(directory: string) { + return realpath(directory).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "ENOENT") throw error; + return null; + }); +} + /** In-process implementation of runner lifecycle operations for native agent hosts. * The native workload and the host service share an OS account. State * paths and host sockets must stay compatible with hosts from earlier versions. @@ -99,6 +127,63 @@ export function createLocalRunner( throw new Error("Invalid agent state directory"); return path.join(agentStateRoot, agentId); } + async function deliverSessionFile(agentId: string, source: string) { + stateDir(agentId); + // The service resolved this registered attachment for the receiving + // session. The existing host file is already visible to the workload. + const name = path.basename(source); + if (!isSessionFileName(name)) + throw new Error("Invalid session input file."); + const { file } = await openBoundedSessionFile( + await realpath(path.dirname(source)), + name + ); + await file.close(); + return source; + } + + async function collectSessionFile( + agentId: string, + source: string, + files: { root: string; ownDir: string; otherDirs: string[] } + ) { + stateDir(agentId); + if (!isSessionFilePath(source)) + throw new Error("Invalid session output file path."); + // Follow native aliases such as macOS /tmp, then open the resolved path + // without following any links that appear after authorization. + const requested = path.resolve(source); + const [target, root, state] = await Promise.all([ + realpath(requested), + realpathIfPresent(files.root), + realpathIfPresent(agentStateRoot), + ]); + // Derive the permitted canonical child from the root. Resolving ownDir + // separately would let a symlink to a different session claim its files. + const ownRelative = path.relative(files.root, files.ownDir); + const ownInRoot = containsPath(files.root, files.ownDir); + if ( + containsPath(agentStateRoot, requested) || + (state && containsPath(state, target)) || + (containsPath(files.root, requested) && + !containsPath(files.ownDir, requested)) || + (root && + containsPath(root, target) && + (!ownInRoot || !containsPath(path.join(root, ownRelative), target))) + ) { + throw new Error("File path is outside the session's permitted files."); + } + for (const other of files.otherDirs) { + const canonical = await realpathIfPresent(other); + if ( + containsPath(other, requested) || + (canonical && containsPath(canonical, target)) + ) + throw new Error("File path is outside the session's permitted files."); + } + return readSessionFile(path.dirname(target), path.basename(target)); + } + const workspace = createWorkspacePreparation(logger); async function launch(input: HostLaunch) { const dir = stateDir(input.agentId); @@ -252,6 +337,8 @@ export function createLocalRunner( } return { requestSession, + deliverSessionFile, + collectSessionFile, checkoutRelease: localCheckoutRelease, resolveLaunchDirectory, canonicalPath: (directory: string) => realpath(directory).catch(() => null), diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index a072b9bfc..29f6fce6e 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,4 +1,4 @@ -import { readSessionFile } from "./remote/session-files.js"; +import { readSessionFile } from "../files/session-file.js"; import { readAgentView } from "./checkout-runner.js"; import type { CheckoutView } from "@dispatch/runner-protocol"; import { AttentionHistory } from "../notifications/attention-history.js"; @@ -720,12 +720,31 @@ export class AgentManager { this.cancelSchedules = cancel; } - async collectRunnerFile( + async collectSessionFile( agent: AgentRecord, filePath: string ): Promise { const placement = remotePlacement(agent.cwd); - if (!placement || !this.remote || !isSessionFilePath(filePath)) + if (!placement) { + const { rows } = await this.pool.query<{ id: string; files_dir: string }>( + `SELECT id, files_dir FROM agents + WHERE id <> $1 AND files_dir IS NOT NULL + AND files_dir <> ($2 || '/' || id)`, + [agent.id, this.config.filesRoot] + ); + return this.localRunner.collectSessionFile(agent.id, filePath, { + root: this.config.filesRoot, + ownDir: resolveFilesDir( + agent.id, + agent.filesDir, + this.config.filesRoot + ), + otherDirs: rows.map((row) => + resolveFilesDir(row.id, row.files_dir, this.config.filesRoot) + ), + }); + } + if (!this.remote || !isSessionFilePath(filePath)) throw new AgentError("Invalid runner session file path.", 400); const { value } = await this.remote.requestSession(placement, { agentId: agent.id, @@ -737,38 +756,60 @@ export class AgentManager { return Buffer.from(value, "base64"); } + private async deliverSessionFile( + agent: AgentRecord, + source: string, + name: string + ) { + const placement = remotePlacement(agent.cwd); + if (!placement) + return this.localRunner.deliverSessionFile(agent.id, source); + if (!this.remote) throw new Error("Runner session is unavailable."); + const bytes = await readSessionFile( + await realpath(path.dirname(source)), + path.basename(source) + ); + const { value } = await this.remote.requestSession(placement, { + agentId: agent.id, + kind: "sessionFile", + operation: { kind: "deliver", name, data: bytes.toString("base64") }, + }); + if (!isSessionFilePath(value) || !path.posix.isAbsolute(value)) + throw new Error("Invalid runner input file location."); + return value; + } + private async preparePromptFiles( id: string, images: PromptImage[] ): Promise { if (!images.some((image) => image.runnerName !== undefined)) return images; const agent = await this.getRequiredAgent(id); - const placement = remotePlacement(agent.cwd); - if (!placement || !this.remote) - throw new Error("Runner session is unavailable."); const prepared: PromptImage[] = []; const delivered = new Map(); for (const { path: source, mimeType, runnerName } of images) { - if (runnerName === undefined) continue; - let destination = delivered.get(runnerName); + if (runnerName === undefined) { + prepared.push({ path: source, mimeType }); + continue; + } + let destination = delivered.get(source); if (destination === undefined) { - const bytes = await readSessionFile( - await realpath(path.dirname(source)), - path.basename(source) - ); - const { value } = await this.remote.requestSession(placement, { - agentId: id, - kind: "sessionFile", - operation: { - kind: "deliver", - name: runnerName, - data: bytes.toString("base64"), - }, - }); - if (!isSessionFilePath(value) || !path.posix.isAbsolute(value)) - throw new Error("Invalid runner input file location."); - destination = value; - delivered.set(runnerName, destination); + try { + destination = await this.deliverSessionFile( + agent, + source, + runnerName + ); + } catch (error) { + // Native prompts historically retain a reference if an image is gone. + if (remotePlacement(agent.cwd)) throw error; + this.logger.warn( + { err: error, agentId: id }, + "Native prompt file is unavailable" + ); + continue; + } + delivered.set(source, destination); } if ( ["image/png", "image/jpeg", "image/webp", "image/gif"].includes( @@ -2232,21 +2273,21 @@ export class AgentManager { const remote = remotePlacement(agent.cwd); let images = chatLaunchPost?.images; try { - if (remote) { + if (opts.initialFiles.length || images?.length) { const filesDir = resolveFilesDir( id, agent.filesDir, this.config.filesRoot ); - images = await this.preparePromptFiles( - id, - images ?? - opts.initialFiles.map((file) => ({ - path: path.join(filesDir, file.fileName), - runnerName: file.fileName, - mimeType: "application/octet-stream", - })) - ); + const inputs = [...(images ?? [])]; + const sources = new Set(inputs.map((image) => image.path)); + for (const file of opts.initialFiles) { + const source = path.join(filesDir, file.fileName); + if (!sources.has(source)) { + await this.deliverSessionFile(agent, source, file.fileName); + } + } + images = await this.preparePromptFiles(id, inputs); } } catch (error) { await this.runtime diff --git a/apps/server/src/agents/remote/session-files.ts b/apps/server/src/agents/remote/session-files.ts index 5a5fc93f5..428e341a6 100644 --- a/apps/server/src/agents/remote/session-files.ts +++ b/apps/server/src/agents/remote/session-files.ts @@ -5,46 +5,10 @@ import path from "node:path"; import { isSessionFileData, isSessionFileName, - isSessionFilePath, MAX_SESSION_FILE_BASE64, - MAX_SESSION_FILE_BYTES, } from "@dispatch/runner-protocol"; -import { - openLinuxDirectory, - openRegularFile, -} from "../../files/open-workspace-file.js"; - -export async function readSessionFile(root: string, relative: string) { - if (!isSessionFilePath(relative) || path.isAbsolute(relative)) - throw new Error("Invalid relative session file path."); - const file = await openRegularFile(root, relative.split("/")); - try { - const stat = await file.stat(); - if (stat.nlink !== 1) - throw new Error("Hard-linked files cannot be collected."); - if (stat.size > MAX_SESSION_FILE_BYTES) - throw new Error("Session files are limited to 20 MiB."); - const bytes = Buffer.allocUnsafe(stat.size + 1); - let size = 0; - while (size < bytes.length) { - const { bytesRead } = await file.read( - bytes, - size, - bytes.length - size, - size - ); - if (!bytesRead) break; - size += bytesRead; - } - if (size !== stat.size || (await file.stat()).mtimeMs !== stat.mtimeMs) - throw new Error( - "Session file changed during transfer. Retry when it is stable." - ); - return bytes.subarray(0, size); - } finally { - await file.close(); - } -} +import { openLinuxDirectory } from "../../files/open-workspace-file.js"; +import { readSessionFile } from "../../files/session-file.js"; async function deliverSessionFile(root: string, name: string, data: string) { if (!isSessionFileName(name) || !isSessionFileData(data)) diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index c45a5742e..9d7183491 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -5284,9 +5284,7 @@ export class StreamService { attachment.fileName ), mimeType: attachment.mimeType ?? "application/octet-stream", - ...(remote && { - runnerName: this.runnerInputName(attachment, owner, recipientId), - }), + runnerName: this.runnerInputName(attachment, owner, recipientId), }); } return images; diff --git a/apps/server/src/files/session-file.ts b/apps/server/src/files/session-file.ts new file mode 100644 index 000000000..f3fda017f --- /dev/null +++ b/apps/server/src/files/session-file.ts @@ -0,0 +1,48 @@ +import path from "node:path"; +import { + isSessionFilePath, + MAX_SESSION_FILE_BYTES, +} from "@dispatch/runner-protocol"; +import { openRegularFile } from "./open-workspace-file.js"; + +export async function openBoundedSessionFile(root: string, relative: string) { + if (!isSessionFilePath(relative) || path.isAbsolute(relative)) + throw new Error("Invalid relative session file path."); + const file = await openRegularFile(root, relative.split("/")); + try { + const stat = await file.stat(); + if (stat.nlink !== 1) + throw new Error("Hard-linked files cannot be collected."); + if (stat.size > MAX_SESSION_FILE_BYTES) + throw new Error("Session files are limited to 20 MiB."); + return { file, stat }; + } catch (error) { + await file.close(); + throw error; + } +} + +export async function readSessionFile(root: string, relative: string) { + const { file, stat } = await openBoundedSessionFile(root, relative); + try { + const bytes = Buffer.allocUnsafe(stat.size + 1); + let size = 0; + while (size < bytes.length) { + const { bytesRead } = await file.read( + bytes, + size, + bytes.length - size, + size + ); + if (!bytesRead) break; + size += bytesRead; + } + if (size !== stat.size || (await file.stat()).mtimeMs !== stat.mtimeMs) + throw new Error( + "Session file changed during transfer. Retry when it is stable." + ); + return bytes.subarray(0, size); + } finally { + await file.close(); + } +} diff --git a/apps/server/src/server/mcp-handlers.ts b/apps/server/src/server/mcp-handlers.ts index aa59fd3fc..585836808 100644 --- a/apps/server/src/server/mcp-handlers.ts +++ b/apps/server/src/server/mcp-handlers.ts @@ -1,6 +1,6 @@ import { validateAgentEffort } from "../shared/agent-effort.js"; import path from "node:path"; -import { mkdir, readFile, unlink, writeFile } from "node:fs/promises"; +import { mkdir, unlink, writeFile } from "node:fs/promises"; import type { FastifyBaseLogger } from "fastify"; import type { Pool } from "pg"; @@ -682,9 +682,10 @@ async function handleShareFile( if (!agent) throw new Error("Agent not found."); if (opts.update) assertValidStoredFileName(opts.update); - const buffer = remotePlacement(agent.cwd) - ? await deps.agentManager.collectRunnerFile(agent, opts.filePath) - : await readFile(opts.filePath); + const buffer = await deps.agentManager.collectSessionFile( + agent, + opts.filePath + ); // Typed against the name it will be stored and shown under. const type = detectFileType( buffer, diff --git a/apps/server/test/file-routes.test.ts b/apps/server/test/file-routes.test.ts index 370e87a6d..2b753533b 100644 --- a/apps/server/test/file-routes.test.ts +++ b/apps/server/test/file-routes.test.ts @@ -1,4 +1,13 @@ -import { mkdir, writeFile, rm, readdir } from "node:fs/promises"; +import { MAX_SESSION_FILE_BYTES } from "@dispatch/runner-protocol"; +import { + mkdir, + mkdtemp, + writeFile, + rm, + readdir, + symlink, + truncate, +} from "node:fs/promises"; import path from "node:path"; import os from "node:os"; import jpeg from "jpeg-js"; @@ -15,7 +24,10 @@ afterAll(async () => { }); const ctx = useInjectApp({ - env: { DISPATCH_FILES_ROOT: filesRoot }, + env: { + DISPATCH_FILES_ROOT: filesRoot, + DISPATCH_AGENT_STATE_ROOT: path.join(filesRoot, ".session-state"), + }, }); async function authedInject( @@ -109,6 +121,96 @@ beforeEach(async () => { agentId = agent.id; }); +describe("native MCP path attachments", () => { + it("collects files from the session and /tmp, and refuses private paths and oversized outputs", async () => { + const foreign = await createAgent("files-test-foreign"); + const own = path.join(filesRoot, agentId, "own.txt"); + const foreignPath = path.join(filesRoot, foreign.id, "foreign.txt"); + await writeFile(own, "own session output"); + await writeFile(foreignPath, "foreign session output"); + const scratch = await mkdtemp("/tmp/dispatch-native-file-test-"); + const { + rows: [{ value: token }], + } = await ctx.pool.query<{ value: string }>( + "SELECT value FROM settings WHERE key = 'auth_token'" + ); + const post = async (file: string) => { + const response = await ctx.app.inject({ + method: "POST", + url: `/api/mcp/${agentId}`, + headers: { + authorization: `Bearer ${ctx.auth.createAgentMcpToken(token, agentId)}`, + accept: "application/json, text/event-stream", + "content-type": "application/json", + }, + payload: { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { + name: "post", + arguments: { + text: "File result", + attachments: [{ type: "file", path: file }], + }, + }, + }, + }); + expect(response.statusCode).toBe(200); + const data = response.body + .split("\n") + .find((line) => line.startsWith("data: ")); + return JSON.parse(data!.slice(6)).result as { + isError?: boolean; + content: Array<{ text: string }>; + }; + }; + try { + const temporary = path.join(scratch, "temporary.txt"); + const large = path.join(scratch, "large.txt"); + const alias = path.join(scratch, "alias.txt"); + const custom = path.join(scratch, "legacy-files"); + const legacy = path.join(custom, "legacy.txt"); + const stateDir = path.join(filesRoot, ".session-state", agentId); + const stateFile = path.join(stateDir, "state.txt"); + await mkdir(stateDir, { recursive: true }); + await writeFile(stateFile, "session state"); + await writeFile(temporary, "temporary output"); + await writeFile(large, ""); + await truncate(large, MAX_SESSION_FILE_BYTES + 1); + await symlink(foreignPath, alias); + await mkdir(custom); + await writeFile(legacy, "foreign legacy output"); + await ctx.pool.query("UPDATE agents SET files_dir = $2 WHERE id = $1", [ + foreign.id, + custom, + ]); + for (const output of [own, temporary]) { + expect((await post(output)).isError).not.toBe(true); + } + for (const output of [ + foreignPath, + alias, + legacy, + stateFile, + large, + `${scratch}/../${path.basename(scratch)}/temporary.txt`, + ]) { + const result = await post(output); + expect(result.isError, output).toBe(true); + if (output === large) + expect(result.content[0]?.text).toContain("20 MiB"); + } + expect( + (await authedInject("GET", `/api/v1/agents/${agentId}/files`)).json() + .files + ).toHaveLength(2); + } finally { + await rm(scratch, { recursive: true, force: true }); + } + }); +}); + // --------------------------------------------------------------------------- // GET /api/v1/agents/:id/files (list) // --------------------------------------------------------------------------- diff --git a/apps/server/test/mcp-handlers.test.ts b/apps/server/test/mcp-handlers.test.ts index 8cfda8963..10d89ed6f 100644 --- a/apps/server/test/mcp-handlers.test.ts +++ b/apps/server/test/mcp-handlers.test.ts @@ -65,7 +65,6 @@ vi.mock("../src/shared/files.js", async (importOriginal) => ({ })); vi.mock("node:fs/promises", () => ({ - readFile: vi.fn(async () => Buffer.from("file-content")), writeFile: vi.fn(async () => {}), mkdir: vi.fn(async () => {}), unlink: vi.fn(async () => {}), @@ -83,7 +82,7 @@ import { import { GENERIC_REVIEW_PERSONA_SLUG } from "../src/personas/built-in.js"; import { getEnabledAgentTypes } from "../src/agent-type-settings.js"; import { resolveFilesDir } from "../src/shared/files.js"; -import { readFile, writeFile } from "node:fs/promises"; +import { writeFile } from "node:fs/promises"; import { BINARY_BYTES, PNG_BYTES } from "./helpers/file-bytes.js"; function templateRecord(overrides: Record = {}) { @@ -111,6 +110,9 @@ function createMockDeps() { pool: { query: vi.fn(async () => ({ rows: [] })) } as any, filesRoot: "/tmp/files", agentManager: { + collectSessionFile: vi.fn(async (_agent, _source) => + Buffer.from("file-content") + ), getAgent: vi.fn(async () => ({ id: "agt_test1", name: "test-agent", @@ -2456,7 +2458,7 @@ describe("createMcpHandlers", () => { it.each([230, 231])( "imports a %i-byte name with a bounded timestamp suffix", async (length) => { - vi.mocked(readFile).mockResolvedValueOnce(PNG_BYTES); + deps.agentManager.collectSessionFile.mockResolvedValueOnce(PNG_BYTES); const result = await handlers.shareFile("agt_test1", { filePath: "/tmp/source.png", name: `${"a".repeat(length - 4)}.png`, @@ -2472,7 +2474,7 @@ describe("createMcpHandlers", () => { ); it("rejects an oversized import before writing or registering", async () => { - vi.mocked(readFile).mockResolvedValueOnce(PNG_BYTES); + deps.agentManager.collectSessionFile.mockResolvedValueOnce(PNG_BYTES); await expect( handlers.shareFile("agt_test1", { filePath: "/tmp/source.png", @@ -2500,7 +2502,7 @@ describe("createMcpHandlers", () => { ); it("rejects contents that are no type Dispatch stores", async () => { - vi.mocked(readFile).mockResolvedValueOnce(BINARY_BYTES); + deps.agentManager.collectSessionFile.mockResolvedValueOnce(BINARY_BYTES); await expect( handlers.shareFile("agt_test1", { filePath: "/tmp/file.exe", @@ -2520,7 +2522,9 @@ describe("createMcpHandlers", () => { }); it("rejects a name that promises a type its contents are not", async () => { - vi.mocked(readFile).mockResolvedValueOnce(Buffer.from("not an image")); + deps.agentManager.collectSessionFile.mockResolvedValueOnce( + Buffer.from("not an image") + ); await expect( handlers.shareFile("agt_test1", { filePath: "/tmp/shot.png", @@ -2530,7 +2534,7 @@ describe("createMcpHandlers", () => { }); it("creates new file entry, typed from its bytes, and publishes event", async () => { - vi.mocked(readFile).mockResolvedValueOnce(PNG_BYTES); + deps.agentManager.collectSessionFile.mockResolvedValueOnce(PNG_BYTES); const result = await handlers.shareFile("agt_test1", { filePath: "/tmp/shot.png", description: "a screenshot", @@ -2549,7 +2553,9 @@ describe("createMcpHandlers", () => { }); it("uses text source for text files", async () => { - vi.mocked(readFile).mockResolvedValueOnce(Buffer.from("# Notes")); + deps.agentManager.collectSessionFile.mockResolvedValueOnce( + Buffer.from("# Notes") + ); const result = await handlers.shareFile("agt_test1", { filePath: "/tmp/notes.md", description: "notes", @@ -2558,7 +2564,7 @@ describe("createMcpHandlers", () => { }); it("updates existing file when update option is provided", async () => { - vi.mocked(readFile).mockResolvedValueOnce(PNG_BYTES); + deps.agentManager.collectSessionFile.mockResolvedValueOnce(PNG_BYTES); deps.pool.query.mockResolvedValueOnce({ rows: [{ file_name: "existing.png" }], }); @@ -2575,7 +2581,7 @@ describe("createMcpHandlers", () => { }); it("throws when update target not found", async () => { - vi.mocked(readFile).mockResolvedValueOnce(PNG_BYTES); + deps.agentManager.collectSessionFile.mockResolvedValueOnce(PNG_BYTES); deps.pool.query.mockResolvedValueOnce({ rows: [] }); await expect( handlers.shareFile("agt_test1", { diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index 6e6579588..c18252b64 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -25,7 +25,7 @@ import { type SessionIdentity, type SessionProcesses, } from "../src/agents/remote/session-processes.js"; -import { readSessionFile } from "../src/agents/remote/session-files.js"; +import { readSessionFile } from "../src/files/session-file.js"; import { createSessionSupervisor } from "../src/agents/remote/session-supervisor.js"; import { diff --git a/apps/server/test/stream-service.test.ts b/apps/server/test/stream-service.test.ts index 568b7c326..0620367fa 100644 --- a/apps/server/test/stream-service.test.ts +++ b/apps/server/test/stream-service.test.ts @@ -226,7 +226,11 @@ describe("StreamService.recordLaunchContext", () => { files: [{ fileId }], }); expect(prepared?.images).toEqual([ - { path: `/files-root/${A}/native.png`, mimeType: "image/png" }, + { + path: `/files-root/${A}/native.png`, + mimeType: "image/png", + runnerName: "native.png", + }, ]); }); diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 88a2b864a..b91aa9d7f 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -64,7 +64,7 @@ A native host can complete an accepted turn while its controller is down. A repl - Expand a directory and open a file in the runner checkout. A path escaping the workspace is refused there. [Workspace routes](../../apps/server/src/routes/agents/workspace-routes.ts) · [File explorer](../file-explorer.md) -**Move attachments across the boundary.** **Present.** Dispatch keeps the durable copies and attachment records. The optional runner capability delivers startup files and prompt attachments into the receiving session and collects files posted from its files directory or checkout. +**Move attachments across the boundary.** **Present.** Dispatch keeps the durable copies and attachment records. The built-in runner reuses registered input paths and collects native files from permitted host paths. The optional remote runner capability delivers files to the receiving session and collects outputs from its files directory or checkout. - Playwright sends a startup image and a composer image to both native and Linux runner sessions, compares the agent's local bytes with the ACP image block, and opens the posted copy after archive. The independent consumer covers interrupted requests, retries, size limits, and capability negotiation. The runner supervisor tests cover isolation between session file directories. [Playwright workflow](../../e2e/remote-runner/file-transfer.spec.ts) · [Protocol](../../packages/runner-protocol/README.md#session-files) · [Attachment behavior](../file-attachments.md) diff --git a/docs/file-attachments.md b/docs/file-attachments.md index e8d408d6f..7931538dc 100644 --- a/docs/file-attachments.md +++ b/docs/file-attachments.md @@ -30,15 +30,18 @@ attach from, or the owner-independent authenticated file-ID metadata lookup. ## Runner sessions Dispatch keeps the authoritative bytes and attachment records on the host. -Local sessions continue to read the shared directory directly. On runners -that advertise session file transfer, startup files and prompt attachments are -copied into the receiving workload's `DISPATCH_FILES_DIR`. Input paths in -remote prompts refer to that directory. Image attachments also become native -ACP image blocks on adapters that accept them, subject to the existing -native-image limits. +The built-in runner delivers startup files and prompt images by reusing their +registered host paths. On remote runners that advertise session file transfer, +startup files and prompt attachments are copied into the receiving workload's +`DISPATCH_FILES_DIR`. Input paths in remote prompts refer to that directory. +Image attachments also become native ACP image blocks on adapters that accept +them, subject to the existing native-image limits. When an agent posts an attachment by path, Dispatch collects a complete copy before registering the file. Remote paths can point into the session -files directory or its effective checkout. Relative paths resolve inside -the checkout. Remote transfers support regular files up to 20 MiB. Browser +files directory or its effective checkout. Relative remote paths resolve +inside the checkout. Local paths can also point to ordinary files such as +screenshots in `/tmp`. The built-in runner refuses paths into another +session's private files or Dispatch's agent state directory, including aliases +that resolve there. Both runners collect regular files up to 20 MiB. Browser URLs still resolve to the Dispatch copy after the runner session is archived. diff --git a/e2e/fixtures/fake-acp-agent.mjs b/e2e/fixtures/fake-acp-agent.mjs index 3123cb56f..f73f2316f 100755 --- a/e2e/fixtures/fake-acp-agent.mjs +++ b/e2e/fixtures/fake-acp-agent.mjs @@ -219,7 +219,8 @@ const agent = { params.prompt, { mcpServers: mcpBySession.get(params.sessionId) }, Client, - StreamableHTTPClientTransport + StreamableHTTPClientTransport, + "/tmp" ); return { stopReason: "end_turn" }; } diff --git a/e2e/fixtures/runner-file-transfer.mjs b/e2e/fixtures/runner-file-transfer.mjs index 22c4f228e..e5a559765 100644 --- a/e2e/fixtures/runner-file-transfer.mjs +++ b/e2e/fixtures/runner-file-transfer.mjs @@ -1,4 +1,4 @@ -import { readFile, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; export async function proveFileTransfer( @@ -6,22 +6,18 @@ export async function proveFileTransfer( blocks, session, Client, - Transport + Transport, + nativeTempRoot ) { const image = blocks.find((block) => block.type === "image"); const reference = /- file: (.+) \(image\/png,/.exec(text)?.[1]; if (!reference || !image) throw new Error("Missing prompt image or file reference"); - const output = path.join( - process.env.DISPATCH_FILES_DIR, - "transfer-output.png" - ); const input = await readFile( reference.replace("$DISPATCH_FILES_DIR", process.env.DISPATCH_FILES_DIR) ); if (!input.equals(Buffer.from(image.data, "base64"))) throw new Error("Image and on-machine file differ"); - await writeFile(output, input); const endpoint = session.mcpServers.find( (entry) => "url" in entry && "headers" in entry @@ -37,7 +33,17 @@ export async function proveFileTransfer( }, }) ); + let temporary; try { + if (nativeTempRoot) + temporary = await mkdtemp( + path.join(nativeTempRoot, "dispatch-transfer-output-") + ); + const output = path.join( + temporary ?? process.env.DISPATCH_FILES_DIR, + "transfer-output.png" + ); + await writeFile(output, input); const post = await client.callTool({ name: "post", arguments: { @@ -48,5 +54,6 @@ export async function proveFileTransfer( if (post.isError) throw new Error(JSON.stringify(post.content)); } finally { await client.close(); + if (temporary) await rm(temporary, { recursive: true, force: true }); } } From 9761d80ca63af1e2e3aa536da6248b314332fc34 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:43:36 -0700 Subject: [PATCH 138/642] Deliver native composer text attachments through the runner --- apps/server/src/agents/acp/prompt-images.ts | 11 ++--- apps/server/src/agents/acp/prompt-source.ts | 6 +++ apps/server/src/agents/acp/runtime.ts | 35 ++++++++------ apps/server/src/agents/manager.ts | 7 +-- apps/server/src/chat/service.ts | 33 ++++--------- apps/server/test/acp-runtime-queue.test.ts | 51 ++++++++++++++++++++- apps/server/test/db/agent-manager.test.ts | 50 ++++++++++++++++++++ docs/file-attachments.md | 2 +- e2e/fixtures/fake-acp-agent.mjs | 18 ++++++++ e2e/remote-runner/file-transfer.spec.ts | 20 +++++++- 10 files changed, 179 insertions(+), 54 deletions(-) diff --git a/apps/server/src/agents/acp/prompt-images.ts b/apps/server/src/agents/acp/prompt-images.ts index 3275012e6..fbd01394c 100644 --- a/apps/server/src/agents/acp/prompt-images.ts +++ b/apps/server/src/agents/acp/prompt-images.ts @@ -1,17 +1,11 @@ import { open } from "node:fs/promises"; import type { ImageContent } from "@agentclientprotocol/sdk"; -import type { PromptImage } from "./prompt-source.js"; +import { isPromptImageMimeType, type PromptImage } from "./prompt-source.js"; // Bound both memory and the ACP request. File references remain in the envelope // when an image is too large or unavailable, so the agent can use its file tools. const MAX_IMAGE_BYTES = 10 * 1024 * 1024; const MAX_PROMPT_IMAGE_BYTES = 20 * 1024 * 1024; -const MIME_TYPES = new Set([ - "image/png", - "image/jpeg", - "image/webp", - "image/gif", -]); export async function readPromptImages( images: PromptImage[], @@ -21,7 +15,8 @@ export async function readPromptImages( let remaining = MAX_PROMPT_IMAGE_BYTES; const seen = new Set(); for (const image of images) { - if (!MIME_TYPES.has(image.mimeType) || seen.has(image.path)) continue; + if (!isPromptImageMimeType(image.mimeType) || seen.has(image.path)) + continue; seen.add(image.path); try { const file = await open(image.path, "r"); diff --git a/apps/server/src/agents/acp/prompt-source.ts b/apps/server/src/agents/acp/prompt-source.ts index 5d0ae9308..c1afb78c1 100644 --- a/apps/server/src/agents/acp/prompt-source.ts +++ b/apps/server/src/agents/acp/prompt-source.ts @@ -3,6 +3,12 @@ import type { PromptImage as WirePromptImage } from "@dispatch/runner-protocol"; /** Host-side attachment reference. A runner name marks an input to stage before ACP submission. */ export type PromptImage = WirePromptImage & { runnerName?: string }; +export function isPromptImageMimeType(mimeType: string): boolean { + return ["image/png", "image/jpeg", "image/webp", "image/gif"].includes( + mimeType + ); +} + /** * What a prompt sent to the harness was, for the prompt a turn entry * renders. The wire text is an envelope Dispatch built; the feed wants the diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 5c838ba90..49686c5e1 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -1,3 +1,4 @@ +import { isPromptImageMimeType } from "./prompt-source.js"; import type { RuntimeLaunch } from "../runtime.js"; import { sameConversation, type PromptConversation } from "@dispatch/shared"; import { appendFile, mkdir, rm } from "node:fs/promises"; @@ -70,6 +71,7 @@ type Waiting = { onDeferred?: () => Promise; signal?: AbortSignal; images?: PromptImage[]; + requiresPrompt: boolean; source?: PromptSource; /** Not to be combined with others: an interrupting post, a job's nudge. */ alone: boolean; @@ -435,7 +437,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const index = entry.waiting.findIndex( (w) => w.delivery === "auto" && - !w.images?.length && + !w.requiresPrompt && !w.steering?.pending && !( isUserPost(w) && @@ -517,6 +519,12 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { } continue; } + const inputs = batch.flatMap((item) => item.images ?? []); + const images = inputs.some((input) => input.runnerName !== undefined) + ? await deps.preparePromptFiles?.(agentId, inputs) + : inputs; + if (!images) + throw new Error("Runner prompt file delivery is unavailable."); if (steering) { const outcome = await entry.client.steer(id, text, source); if (outcome === "promptRequired") { @@ -535,14 +543,6 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { : "default" ); } else { - const inputs = batch.flatMap((item) => item.images ?? []); - const images = inputs.some( - (input) => input.runnerName !== undefined - ) - ? await deps.preparePromptFiles?.(agentId, inputs) - : inputs; - if (!images) - throw new Error("Runner prompt file delivery is unavailable."); if (entry.remote) { const dir = stateDir(agentId); await mkdir(dir, { recursive: true, mode: 0o700 }); @@ -858,7 +858,15 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }).finally(() => { entry.pending -= 1; }); + const requiresPrompt = + opts?.images?.some( + (input) => + entry.remote || + input.runnerName === undefined || + isPromptImageMimeType(input.mimeType) + ) ?? false; const own: Waiting = { + requiresPrompt, text, ...(opts?.beforeSubmit ? { beforeSubmit: opts.beforeSubmit } : {}), ...(opts?.onDeferred ? { onDeferred: opts.onDeferred } : {}), @@ -869,11 +877,12 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { opts?.delivery === "interrupt" || opts?.alone === true || source?.source !== "chat", - // Steering accepts text only. Keep images for the next ordinary turn. + // Remote inputs can require transfer, and native images need an ACP prompt. + // A native text attachment can still steer with its shared file path. delivery: opts?.delivery === "interrupt" ? "interrupt" - : opts?.images?.length + : requiresPrompt ? "queue" : (opts?.delivery ?? "queue"), taken: false, @@ -921,7 +930,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { !own.source?.steeringExcluded && !own.source?.awaited && !own.source?.scheduleId && - !own.images?.length && + !own.requiresPrompt && entry.turnOpen && entry.turnSeq !== undefined && entry.conversation && @@ -1185,7 +1194,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { return act === "send-now" ? entry.turnOpen && (prompt.delivery === "interrupt" || - !!prompt.images?.length || + prompt.requiresPrompt || (!steers(prompt, entry) && !entry.client.welcome?.steeringSupported)) : // An interrupt already asked for is not asked for twice, and a diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 29f6fce6e..57fe4865d 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,3 +1,4 @@ +import { isPromptImageMimeType } from "./acp/prompt-source.js"; import { readSessionFile } from "../files/session-file.js"; import { readAgentView } from "./checkout-runner.js"; import type { CheckoutView } from "@dispatch/runner-protocol"; @@ -811,11 +812,7 @@ export class AgentManager { } delivered.set(source, destination); } - if ( - ["image/png", "image/jpeg", "image/webp", "image/gif"].includes( - mimeType - ) - ) + if (isPromptImageMimeType(mimeType)) prepared.push({ path: destination, mimeType }); } return prepared; diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index 9d7183491..158386f48 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -3609,11 +3609,7 @@ export class StreamService { return { id, attachmentLines, - images: await this.promptImages( - attachments, - input.agentId, - input.agentId - ), + images: await this.promptFiles(attachments, input.agentId, input.agentId), postText, record: async () => { const block = await this.store.writeLaunchBriefing({ @@ -4412,7 +4408,7 @@ export class StreamService { const own = perRecipient(agentId); const images = own.rawPrompt ? [] - : await this.promptImages(block.attachments, block.streamId, agentId); + : await this.promptFiles(block.attachments, block.streamId, agentId); // A cancellation closes the ask the same way an answer does: it // resumes the work the ask came from rather than opening a thread. const closes = own.answers ?? own.cancels; @@ -5250,35 +5246,22 @@ export class StreamService { return out; } - /** Native image references come only from resolved attachment metadata. */ - private async promptImages( + /** Resolve input paths from registered attachments for the receiving session. */ + private async promptFiles( attachments: ChatAttachment[], fallbackOwnerId: string, recipientId: string ): Promise { - const recipient = attachments.some( - (attachment) => attachment.type === "file" - ) - ? await this.deps.getAgent(recipientId) - : null; - const remote = remotePlacement(recipient?.cwd ?? ""); - const images: PromptImage[] = []; + const files: PromptImage[] = []; for (const attachment of attachments) { - if ( - attachment.type !== "file" || - (!remote && - !["image/png", "image/jpeg", "image/webp", "image/gif"].includes( - attachment.mimeType ?? "" - )) - ) - continue; + if (attachment.type !== "file") continue; // Attachment metadata was resolved against the file registry on posting. // Use its owner, even when the post is addressed to another agent. if (path.basename(attachment.fileName) !== attachment.fileName) continue; const owner = await this.requireAgent( attachment.ownerAgentId ?? fallbackOwnerId ); - images.push({ + files.push({ path: path.join( resolveFilesDir(owner.id, owner.filesDir, this.deps.filesRoot), attachment.fileName @@ -5287,7 +5270,7 @@ export class StreamService { runnerName: this.runnerInputName(attachment, owner, recipientId), }); } - return images; + return files; } private runnerInputName( diff --git a/apps/server/test/acp-runtime-queue.test.ts b/apps/server/test/acp-runtime-queue.test.ts index ede1682f5..153d967c8 100644 --- a/apps/server/test/acp-runtime-queue.test.ts +++ b/apps/server/test/acp-runtime-queue.test.ts @@ -3,6 +3,7 @@ * where the test decides how the host's messages are framed on the wire. */ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createLocalRunner } from "../src/agents/local-runner.js"; import net from "node:net"; import os from "node:os"; import path from "node:path"; @@ -682,10 +683,14 @@ function withinSeconds( async function attached( stateRoot: string, - classifySteering?: Parameters[0]["classifySteering"] + classifySteering?: Parameters[0]["classifySteering"], + preparePromptFiles?: Parameters< + typeof createAcpRuntime + >[0]["preparePromptFiles"] ) { const runtime = createAcpRuntime({ classifySteering, + preparePromptFiles, config: { agentStateRoot: stateRoot, agentRuntime: "acp", @@ -1324,6 +1329,50 @@ describe("AcpRuntime delivery during a turn", () => { await Promise.all([work.settled, next.settled]); }); + it.each(["auto", "queue"] as const)( + "delivers a native composer text attachment through the runner with %s routing", + async (delivery) => { + const host = await heldTurnHost("injected"); + const local = createLocalRunner(host.stateRoot, logger); + const deliver = vi.spyOn(local, "deliverSessionFile"); + const runtime = await attached( + host.stateRoot, + undefined, + async (id, inputs) => { + for (const input of inputs) + await local.deliverSessionFile(id, input.path); + return []; + } + ); + const file = path.join(host.stateRoot, "composer.txt"); + writeFileSync(file, "text from composer"); + const work = runtime.prompt(agentId, "work", post(0)); + await work.accepted; + const text = envelope(1, `- file: ${file} (text/plain, 18 B)`); + const attachedText = runtime.prompt(agentId, text, post(1), { + delivery, + images: [ + { path: file, mimeType: "text/plain", runnerName: "composer.txt" }, + ], + }); + if (delivery === "queue") { + expect(deliver).not.toHaveBeenCalled(); + expect(host.steers).toEqual([]); + host.settle(); + } + await withinSeconds(attachedText.accepted, "native text attachment"); + expect(deliver).toHaveBeenCalledExactlyOnceWith(agentId, file); + if (delivery === "auto") { + expect(host.steers).toEqual([text]); + expect(host.prompts).toHaveLength(1); + } else { + expect(host.prompts[1]).toEqual({ text, source: post(1) }); + } + host.settle(); + await Promise.all([work.settled, attachedText.settled]); + } + ); + it("steers consecutive messages while explicit queue waits, without canceling", async () => { const host = await heldTurnHost("injected"); const runtime = await attached(host.stateRoot); diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index b215c22bf..7b59af356 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -245,6 +245,56 @@ beforeEach(async () => { }); describe("AgentManager", () => { + it("delivers a registered native composer text file through the built-in runner", async () => { + const agent = await manager.createAgent({ + cwd: "/tmp", + useWorktree: false, + }); + const file = path.join(agent.filesDir!, "composer.txt"); + const deliver = vi.spyOn(manager["localRunner"], "deliverSessionFile"); + const submitted = vi.fn(); + const chat = new StreamService({ + pool, + publishUiEvent: () => {}, + getAgent: (id) => manager.getAgent(id), + filesRoot: testConfig.filesRoot, + delivery: { + access: async () => ({ mode: "live" }), + held: () => false, + activeTurn: () => false, + cancel: async () => {}, + inject: async (id, text, opts) => { + submitted( + text, + await manager["preparePromptFiles"](id, opts?.images ?? []) + ); + }, + }, + }); + try { + await writeFile(file, "composer text"); + const { + rows: [attachment], + } = await pool.query<{ id: number }>( + `INSERT INTO files (agent_id, file_name, source, size_bytes, mime_type) + VALUES ($1, 'composer.txt', 'user', 13, 'text/plain') RETURNING id`, + [agent.id] + ); + await chat.post(agent.id, { + text: "Read the attachment", + attachments: [{ type: "file", fileId: attachment.id }], + }); + await chat.waitForInFlightDeliveries(2_000); + expect(deliver).toHaveBeenCalledExactlyOnceWith(agent.id, file); + expect(submitted).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining(`- file: ${file} (text/plain,`), + [] + ); + } finally { + await rm(file, { force: true }); + } + }); + describe("createAgent", () => { it("persists managed placement across restart and retries archive when the original runner returns", async () => { const available = vi.fn(() => true); diff --git a/docs/file-attachments.md b/docs/file-attachments.md index 7931538dc..e730a4c8e 100644 --- a/docs/file-attachments.md +++ b/docs/file-attachments.md @@ -30,7 +30,7 @@ attach from, or the owner-independent authenticated file-ID metadata lookup. ## Runner sessions Dispatch keeps the authoritative bytes and attachment records on the host. -The built-in runner delivers startup files and prompt images by reusing their +The built-in runner delivers startup files and prompt attachments by reusing their registered host paths. On remote runners that advertise session file transfer, startup files and prompt attachments are copied into the receiving workload's `DISPATCH_FILES_DIR`. Input paths in remote prompts refer to that directory. diff --git a/e2e/fixtures/fake-acp-agent.mjs b/e2e/fixtures/fake-acp-agent.mjs index f73f2316f..e4d6b39f8 100755 --- a/e2e/fixtures/fake-acp-agent.mjs +++ b/e2e/fixtures/fake-acp-agent.mjs @@ -259,6 +259,24 @@ const agent = { const cwd = cwdBySession.get(params.sessionId) ?? process.cwd(); const emit = (update) => conn.sessionUpdate({ sessionId: params.sessionId, update }); + if (text.includes("proof-text-transfer")) { + const reference = /^- file: (.+) \(text\/plain,/m.exec(text)?.[1]; + if (!reference || params.prompt.some((block) => block.type === "image")) + throw new Error( + "Expected a plain-text attachment path without an ACP image" + ); + const contents = readFileSync(reference, "utf8"); + if (contents !== "native composer text") + throw new Error("Unexpected text attachment contents"); + await emit({ + sessionUpdate: "agent_message_chunk", + content: { + type: "text", + text: "Read the native composer text file.", + }, + }); + return { stopReason: "end_turn" }; + } if (text.includes("proof-reviewed-checkout")) { const marker = readFileSync( path.join(cwd, "review-marker.txt"), diff --git a/e2e/remote-runner/file-transfer.spec.ts b/e2e/remote-runner/file-transfer.spec.ts index ffeea6aae..3a1cac088 100644 --- a/e2e/remote-runner/file-transfer.spec.ts +++ b/e2e/remote-runner/file-transfer.spec.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { expect, test } from "@playwright/test"; import { authHeaders, cleanupE2EAgents, trackAgent } from "../helpers"; -import { chat, enrollViaUi, state } from "./harness"; +import { chat, enrollViaUi, settledTurns, state } from "./harness"; const png = readFileSync( new URL("../../apps/web/public/icons/teal/pwa-192.png", import.meta.url) @@ -97,6 +97,24 @@ test("file transfer keeps local and remote posted bytes after archive", async ({ ); }; await shot("posted"); + if (lane === "local") { + await expect(settledTurns(session)).toHaveCount(2, { timeout: 30_000 }); + await fileInput.setInputFiles({ + name: "transfer-notes.txt", + mimeType: "text/plain", + buffer: Buffer.from("native composer text"), + }); + await expect( + session.getByTestId("chat-composer-attachments") + ).toBeVisible(); + await chat(session, "proof-text-transfer"); + await expect( + session.getByText("Read the native composer text file.", { + exact: true, + }) + ).toBeVisible({ timeout: 30_000 }); + await shot("composer-text"); + } const archive = await request.delete(`/api/v1/agents/${id}`, { headers: authHeaders(), }); From 2dec8fa02593cedaaa8a8e0ba07b975550798384 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:43:36 -0700 Subject: [PATCH 139/642] Deliver native composer text attachments through the runner --- apps/server/src/agents/acp/prompt-images.ts | 11 ++--- apps/server/src/agents/acp/prompt-source.ts | 6 +++ apps/server/src/agents/acp/runtime.ts | 35 ++++++++------ apps/server/src/agents/manager.ts | 7 +-- apps/server/src/chat/service.ts | 33 ++++--------- apps/server/test/acp-runtime-queue.test.ts | 51 ++++++++++++++++++++- apps/server/test/db/agent-manager.test.ts | 50 ++++++++++++++++++++ docs/file-attachments.md | 2 +- e2e/fixtures/fake-acp-agent.mjs | 18 ++++++++ e2e/remote-runner/file-transfer.spec.ts | 24 +++++++++- 10 files changed, 183 insertions(+), 54 deletions(-) diff --git a/apps/server/src/agents/acp/prompt-images.ts b/apps/server/src/agents/acp/prompt-images.ts index 3275012e6..fbd01394c 100644 --- a/apps/server/src/agents/acp/prompt-images.ts +++ b/apps/server/src/agents/acp/prompt-images.ts @@ -1,17 +1,11 @@ import { open } from "node:fs/promises"; import type { ImageContent } from "@agentclientprotocol/sdk"; -import type { PromptImage } from "./prompt-source.js"; +import { isPromptImageMimeType, type PromptImage } from "./prompt-source.js"; // Bound both memory and the ACP request. File references remain in the envelope // when an image is too large or unavailable, so the agent can use its file tools. const MAX_IMAGE_BYTES = 10 * 1024 * 1024; const MAX_PROMPT_IMAGE_BYTES = 20 * 1024 * 1024; -const MIME_TYPES = new Set([ - "image/png", - "image/jpeg", - "image/webp", - "image/gif", -]); export async function readPromptImages( images: PromptImage[], @@ -21,7 +15,8 @@ export async function readPromptImages( let remaining = MAX_PROMPT_IMAGE_BYTES; const seen = new Set(); for (const image of images) { - if (!MIME_TYPES.has(image.mimeType) || seen.has(image.path)) continue; + if (!isPromptImageMimeType(image.mimeType) || seen.has(image.path)) + continue; seen.add(image.path); try { const file = await open(image.path, "r"); diff --git a/apps/server/src/agents/acp/prompt-source.ts b/apps/server/src/agents/acp/prompt-source.ts index 5d0ae9308..c1afb78c1 100644 --- a/apps/server/src/agents/acp/prompt-source.ts +++ b/apps/server/src/agents/acp/prompt-source.ts @@ -3,6 +3,12 @@ import type { PromptImage as WirePromptImage } from "@dispatch/runner-protocol"; /** Host-side attachment reference. A runner name marks an input to stage before ACP submission. */ export type PromptImage = WirePromptImage & { runnerName?: string }; +export function isPromptImageMimeType(mimeType: string): boolean { + return ["image/png", "image/jpeg", "image/webp", "image/gif"].includes( + mimeType + ); +} + /** * What a prompt sent to the harness was, for the prompt a turn entry * renders. The wire text is an envelope Dispatch built; the feed wants the diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 5c838ba90..49686c5e1 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -1,3 +1,4 @@ +import { isPromptImageMimeType } from "./prompt-source.js"; import type { RuntimeLaunch } from "../runtime.js"; import { sameConversation, type PromptConversation } from "@dispatch/shared"; import { appendFile, mkdir, rm } from "node:fs/promises"; @@ -70,6 +71,7 @@ type Waiting = { onDeferred?: () => Promise; signal?: AbortSignal; images?: PromptImage[]; + requiresPrompt: boolean; source?: PromptSource; /** Not to be combined with others: an interrupting post, a job's nudge. */ alone: boolean; @@ -435,7 +437,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const index = entry.waiting.findIndex( (w) => w.delivery === "auto" && - !w.images?.length && + !w.requiresPrompt && !w.steering?.pending && !( isUserPost(w) && @@ -517,6 +519,12 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { } continue; } + const inputs = batch.flatMap((item) => item.images ?? []); + const images = inputs.some((input) => input.runnerName !== undefined) + ? await deps.preparePromptFiles?.(agentId, inputs) + : inputs; + if (!images) + throw new Error("Runner prompt file delivery is unavailable."); if (steering) { const outcome = await entry.client.steer(id, text, source); if (outcome === "promptRequired") { @@ -535,14 +543,6 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { : "default" ); } else { - const inputs = batch.flatMap((item) => item.images ?? []); - const images = inputs.some( - (input) => input.runnerName !== undefined - ) - ? await deps.preparePromptFiles?.(agentId, inputs) - : inputs; - if (!images) - throw new Error("Runner prompt file delivery is unavailable."); if (entry.remote) { const dir = stateDir(agentId); await mkdir(dir, { recursive: true, mode: 0o700 }); @@ -858,7 +858,15 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { }).finally(() => { entry.pending -= 1; }); + const requiresPrompt = + opts?.images?.some( + (input) => + entry.remote || + input.runnerName === undefined || + isPromptImageMimeType(input.mimeType) + ) ?? false; const own: Waiting = { + requiresPrompt, text, ...(opts?.beforeSubmit ? { beforeSubmit: opts.beforeSubmit } : {}), ...(opts?.onDeferred ? { onDeferred: opts.onDeferred } : {}), @@ -869,11 +877,12 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { opts?.delivery === "interrupt" || opts?.alone === true || source?.source !== "chat", - // Steering accepts text only. Keep images for the next ordinary turn. + // Remote inputs can require transfer, and native images need an ACP prompt. + // A native text attachment can still steer with its shared file path. delivery: opts?.delivery === "interrupt" ? "interrupt" - : opts?.images?.length + : requiresPrompt ? "queue" : (opts?.delivery ?? "queue"), taken: false, @@ -921,7 +930,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { !own.source?.steeringExcluded && !own.source?.awaited && !own.source?.scheduleId && - !own.images?.length && + !own.requiresPrompt && entry.turnOpen && entry.turnSeq !== undefined && entry.conversation && @@ -1185,7 +1194,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { return act === "send-now" ? entry.turnOpen && (prompt.delivery === "interrupt" || - !!prompt.images?.length || + prompt.requiresPrompt || (!steers(prompt, entry) && !entry.client.welcome?.steeringSupported)) : // An interrupt already asked for is not asked for twice, and a diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 29f6fce6e..57fe4865d 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,3 +1,4 @@ +import { isPromptImageMimeType } from "./acp/prompt-source.js"; import { readSessionFile } from "../files/session-file.js"; import { readAgentView } from "./checkout-runner.js"; import type { CheckoutView } from "@dispatch/runner-protocol"; @@ -811,11 +812,7 @@ export class AgentManager { } delivered.set(source, destination); } - if ( - ["image/png", "image/jpeg", "image/webp", "image/gif"].includes( - mimeType - ) - ) + if (isPromptImageMimeType(mimeType)) prepared.push({ path: destination, mimeType }); } return prepared; diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index 9d7183491..158386f48 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -3609,11 +3609,7 @@ export class StreamService { return { id, attachmentLines, - images: await this.promptImages( - attachments, - input.agentId, - input.agentId - ), + images: await this.promptFiles(attachments, input.agentId, input.agentId), postText, record: async () => { const block = await this.store.writeLaunchBriefing({ @@ -4412,7 +4408,7 @@ export class StreamService { const own = perRecipient(agentId); const images = own.rawPrompt ? [] - : await this.promptImages(block.attachments, block.streamId, agentId); + : await this.promptFiles(block.attachments, block.streamId, agentId); // A cancellation closes the ask the same way an answer does: it // resumes the work the ask came from rather than opening a thread. const closes = own.answers ?? own.cancels; @@ -5250,35 +5246,22 @@ export class StreamService { return out; } - /** Native image references come only from resolved attachment metadata. */ - private async promptImages( + /** Resolve input paths from registered attachments for the receiving session. */ + private async promptFiles( attachments: ChatAttachment[], fallbackOwnerId: string, recipientId: string ): Promise { - const recipient = attachments.some( - (attachment) => attachment.type === "file" - ) - ? await this.deps.getAgent(recipientId) - : null; - const remote = remotePlacement(recipient?.cwd ?? ""); - const images: PromptImage[] = []; + const files: PromptImage[] = []; for (const attachment of attachments) { - if ( - attachment.type !== "file" || - (!remote && - !["image/png", "image/jpeg", "image/webp", "image/gif"].includes( - attachment.mimeType ?? "" - )) - ) - continue; + if (attachment.type !== "file") continue; // Attachment metadata was resolved against the file registry on posting. // Use its owner, even when the post is addressed to another agent. if (path.basename(attachment.fileName) !== attachment.fileName) continue; const owner = await this.requireAgent( attachment.ownerAgentId ?? fallbackOwnerId ); - images.push({ + files.push({ path: path.join( resolveFilesDir(owner.id, owner.filesDir, this.deps.filesRoot), attachment.fileName @@ -5287,7 +5270,7 @@ export class StreamService { runnerName: this.runnerInputName(attachment, owner, recipientId), }); } - return images; + return files; } private runnerInputName( diff --git a/apps/server/test/acp-runtime-queue.test.ts b/apps/server/test/acp-runtime-queue.test.ts index ede1682f5..153d967c8 100644 --- a/apps/server/test/acp-runtime-queue.test.ts +++ b/apps/server/test/acp-runtime-queue.test.ts @@ -3,6 +3,7 @@ * where the test decides how the host's messages are framed on the wire. */ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createLocalRunner } from "../src/agents/local-runner.js"; import net from "node:net"; import os from "node:os"; import path from "node:path"; @@ -682,10 +683,14 @@ function withinSeconds( async function attached( stateRoot: string, - classifySteering?: Parameters[0]["classifySteering"] + classifySteering?: Parameters[0]["classifySteering"], + preparePromptFiles?: Parameters< + typeof createAcpRuntime + >[0]["preparePromptFiles"] ) { const runtime = createAcpRuntime({ classifySteering, + preparePromptFiles, config: { agentStateRoot: stateRoot, agentRuntime: "acp", @@ -1324,6 +1329,50 @@ describe("AcpRuntime delivery during a turn", () => { await Promise.all([work.settled, next.settled]); }); + it.each(["auto", "queue"] as const)( + "delivers a native composer text attachment through the runner with %s routing", + async (delivery) => { + const host = await heldTurnHost("injected"); + const local = createLocalRunner(host.stateRoot, logger); + const deliver = vi.spyOn(local, "deliverSessionFile"); + const runtime = await attached( + host.stateRoot, + undefined, + async (id, inputs) => { + for (const input of inputs) + await local.deliverSessionFile(id, input.path); + return []; + } + ); + const file = path.join(host.stateRoot, "composer.txt"); + writeFileSync(file, "text from composer"); + const work = runtime.prompt(agentId, "work", post(0)); + await work.accepted; + const text = envelope(1, `- file: ${file} (text/plain, 18 B)`); + const attachedText = runtime.prompt(agentId, text, post(1), { + delivery, + images: [ + { path: file, mimeType: "text/plain", runnerName: "composer.txt" }, + ], + }); + if (delivery === "queue") { + expect(deliver).not.toHaveBeenCalled(); + expect(host.steers).toEqual([]); + host.settle(); + } + await withinSeconds(attachedText.accepted, "native text attachment"); + expect(deliver).toHaveBeenCalledExactlyOnceWith(agentId, file); + if (delivery === "auto") { + expect(host.steers).toEqual([text]); + expect(host.prompts).toHaveLength(1); + } else { + expect(host.prompts[1]).toEqual({ text, source: post(1) }); + } + host.settle(); + await Promise.all([work.settled, attachedText.settled]); + } + ); + it("steers consecutive messages while explicit queue waits, without canceling", async () => { const host = await heldTurnHost("injected"); const runtime = await attached(host.stateRoot); diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index b215c22bf..38203a52e 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -245,6 +245,56 @@ beforeEach(async () => { }); describe("AgentManager", () => { + it("delivers a registered native composer text file through the built-in runner", async () => { + const agent = await manager.createAgent({ + cwd: "/tmp", + useWorktree: false, + }); + const file = path.join(agent.filesDir!, "composer.txt"); + const deliver = vi.spyOn(manager["localRunner"], "deliverSessionFile"); + const submitted = vi.fn(); + const chat = new StreamService({ + pool, + publishUiEvent: () => {}, + getAgent: (id) => manager.getAgent(id), + filesRoot: testConfig.filesRoot, + delivery: { + access: async () => ({ mode: "live" }), + held: () => false, + activeTurn: () => false, + cancel: async () => {}, + inject: async (id, text, opts) => { + submitted( + text, + await manager["preparePromptFiles"](id, opts?.images ?? []) + ); + }, + }, + }); + try { + await writeFile(file, "composer text"); + const { + rows: [attachment], + } = await pool.query<{ id: number }>( + `INSERT INTO files (agent_id, file_name, source, size_bytes, mime_type) + VALUES ($1, 'composer.txt', 'user', 13, 'text/plain') RETURNING id`, + [agent.id] + ); + await chat.sendUserPost(agent.id, { + text: "Read the attachment", + attachments: [{ type: "file", fileId: attachment.id }], + }); + await chat.waitForInFlightDeliveries(2_000); + expect(deliver).toHaveBeenCalledExactlyOnceWith(agent.id, file); + expect(submitted).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining(`- file: ${file} (text/plain,`), + [] + ); + } finally { + await rm(file, { force: true }); + } + }); + describe("createAgent", () => { it("persists managed placement across restart and retries archive when the original runner returns", async () => { const available = vi.fn(() => true); diff --git a/docs/file-attachments.md b/docs/file-attachments.md index 7931538dc..e730a4c8e 100644 --- a/docs/file-attachments.md +++ b/docs/file-attachments.md @@ -30,7 +30,7 @@ attach from, or the owner-independent authenticated file-ID metadata lookup. ## Runner sessions Dispatch keeps the authoritative bytes and attachment records on the host. -The built-in runner delivers startup files and prompt images by reusing their +The built-in runner delivers startup files and prompt attachments by reusing their registered host paths. On remote runners that advertise session file transfer, startup files and prompt attachments are copied into the receiving workload's `DISPATCH_FILES_DIR`. Input paths in remote prompts refer to that directory. diff --git a/e2e/fixtures/fake-acp-agent.mjs b/e2e/fixtures/fake-acp-agent.mjs index f73f2316f..e4d6b39f8 100755 --- a/e2e/fixtures/fake-acp-agent.mjs +++ b/e2e/fixtures/fake-acp-agent.mjs @@ -259,6 +259,24 @@ const agent = { const cwd = cwdBySession.get(params.sessionId) ?? process.cwd(); const emit = (update) => conn.sessionUpdate({ sessionId: params.sessionId, update }); + if (text.includes("proof-text-transfer")) { + const reference = /^- file: (.+) \(text\/plain,/m.exec(text)?.[1]; + if (!reference || params.prompt.some((block) => block.type === "image")) + throw new Error( + "Expected a plain-text attachment path without an ACP image" + ); + const contents = readFileSync(reference, "utf8"); + if (contents !== "native composer text") + throw new Error("Unexpected text attachment contents"); + await emit({ + sessionUpdate: "agent_message_chunk", + content: { + type: "text", + text: "Read the native composer text file.", + }, + }); + return { stopReason: "end_turn" }; + } if (text.includes("proof-reviewed-checkout")) { const marker = readFileSync( path.join(cwd, "review-marker.txt"), diff --git a/e2e/remote-runner/file-transfer.spec.ts b/e2e/remote-runner/file-transfer.spec.ts index ffeea6aae..3d7542d0a 100644 --- a/e2e/remote-runner/file-transfer.spec.ts +++ b/e2e/remote-runner/file-transfer.spec.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { expect, test } from "@playwright/test"; import { authHeaders, cleanupE2EAgents, trackAgent } from "../helpers"; -import { chat, enrollViaUi, state } from "./harness"; +import { agentInfo, chat, enrollViaUi, state } from "./harness"; const png = readFileSync( new URL("../../apps/web/public/icons/teal/pwa-192.png", import.meta.url) @@ -97,6 +97,28 @@ test("file transfer keeps local and remote posted bytes after archive", async ({ ); }; await shot("posted"); + if (lane === "local") { + await expect + .poll(async () => (await agentInfo(request, id)).activity, { + timeout: 30_000, + }) + .toBe("idle"); + await fileInput.setInputFiles({ + name: "transfer-notes.txt", + mimeType: "text/plain", + buffer: Buffer.from("native composer text"), + }); + await expect( + session.getByTestId("chat-composer-attachments") + ).toBeVisible(); + await chat(session, "proof-text-transfer"); + await expect( + session.getByText("Read the native composer text file.", { + exact: true, + }) + ).toBeVisible({ timeout: 30_000 }); + await shot("composer-text"); + } const archive = await request.delete(`/api/v1/agents/${id}`, { headers: authHeaders(), }); From 9a8a5a3eddba8448a718ebbdcd4bfd007f5e67de Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 16:59:49 -0700 Subject: [PATCH 140/642] Resolve repository discovery in the session checkout --- apps/server/src/agents/checkout-inspection.ts | 84 +++++++- apps/server/src/agents/manager.ts | 22 +++ apps/server/src/agents/remote/runner.ts | 31 +++ apps/server/src/agents/remote/service.ts | 16 ++ apps/server/src/main.ts | 5 +- apps/server/src/personas/catalog.ts | 20 +- apps/server/src/personas/loader.ts | 44 ++++- apps/server/src/personas/resolve.ts | 13 +- apps/server/src/routes/mcp.ts | 101 +++++++--- apps/server/src/routes/personas.ts | 47 ++++- apps/server/src/server/mcp-checkout.ts | 69 +++++++ apps/server/src/server/mcp-handlers.ts | 9 +- .../server/src/server/mcp-persona-handlers.ts | 96 ++++++--- .../shared/mcp/persona-interaction-tools.ts | 3 +- apps/server/src/shared/mcp/repo-tools.ts | 52 ++++- apps/server/src/shared/mcp/server.ts | 24 ++- apps/server/src/tasks/agent-scope.ts | 3 +- apps/server/test/checkout-inspection.test.ts | 78 ++++++-- apps/server/test/mcp-handlers.test.ts | 24 ++- apps/server/test/mcp-routes.test.ts | 81 +++++++- apps/server/test/persona-catalog.test.ts | 17 +- .../test/runner-protocol-consumer.test.ts | 18 ++ .../src/components/app/persona-launcher.tsx | 7 +- e2e/remote-runner/owner-review.spec.ts | 187 +++++++++++++++++- packages/runner-protocol/README.md | 29 +++ packages/runner-protocol/src/checkout.ts | 63 +++++- packages/runner-protocol/src/execution.ts | 13 ++ 27 files changed, 1024 insertions(+), 132 deletions(-) create mode 100644 apps/server/src/server/mcp-checkout.ts diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index 2aa31ba9a..08235c99c 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -5,11 +5,14 @@ import { openRegularFile, openLinuxDirectory, } from "../files/open-workspace-file.js"; +import { openWorkspaceDirectory } from "../files/workspace-directory.js"; +import { resolveRepoRoot } from "../shared/git/git-context.js"; import { constants } from "node:fs"; import { lstat, open, readdir, readlink, realpath } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { + isCheckoutArgv, isCheckoutQuery, type CheckoutQuery, type CheckoutReply, @@ -79,7 +82,11 @@ const run: CommandRunner = async (command, args, options = {}) => { }; function parseQuery(input: unknown): CheckoutQuery { - if (isCheckoutQuery(input) && Object.keys(input).length === 2) return input; + if ( + isCheckoutQuery(input) && + Object.keys(input).length === (input.kind === "roots" ? 1 : 2) + ) + return input; throw new Error("Invalid checkout inspection query"); } @@ -482,7 +489,7 @@ export async function inspectCheckout( const probe = await run("git", ["rev-parse", "--show-toplevel"], { cwd, trimOutput: false, - allowedExitCodes: validated.kind === "readFile" ? [0, 128] : [0], + allowedExitCodes: validated.kind === "changes" ? [0] : [0, 128], }); if (probe.exitCode && !probe.stderr.startsWith("fatal: not a git repository")) throw new Error( @@ -493,6 +500,45 @@ export async function inspectCheckout( : probe.stdout.replace(/\n$/, ""); if (!path.isAbsolute(root)) throw new Error("Could not resolve checkout root"); + if (validated.kind === "roots") + return { + kind: "roots", + checkoutRoot: root, + repositoryRoot: probe.exitCode ? null : await resolveRepoRoot(root), + }; + if (validated.kind === "listFiles") { + const canonicalRoot = await realpath(root); + const directoryPath = path.join( + canonicalRoot, + ...validateFilePath(validated.path) + ); + try { + const { directory, verify } = await openWorkspaceDirectory( + canonicalRoot, + directoryPath + ); + const names: string[] = []; + let scanned = 0; + for await (const entry of directory) { + if (++scanned > 1024) + throw new Error("Checkout directory contains too many entries"); + if ( + entry.isFile() && + !entry.name.includes("\\") && + entry.name.toLowerCase() !== ".git" + ) + names.push(entry.name); + } + await verify(); + const reply = { kind: "listFiles" as const, names: names.sort() }; + encodeReply(reply); + return reply; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") + return { kind: "listFiles", names: [] }; + throw error; + } + } const reply: CheckoutReply = validated.kind === "changes" ? await inspectChanges(root, validated.baseBranch) @@ -507,7 +553,10 @@ export async function inspectCheckout( return reply; } -export async function runCheckoutInspectionCli(cwd: string): Promise { +export async function runCheckoutInspectionCli( + cwd: string, + expectedRoot?: string +): Promise { try { const chunks: Buffer[] = []; let size = 0; @@ -518,9 +567,32 @@ export async function runCheckoutInspectionCli(cwd: string): Promise { throw new Error("Checkout inspection query is too large"); chunks.push(bytes); } - const query = parseQuery( - JSON.parse(Buffer.concat(chunks).toString("utf8")) - ); + const input: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (expectedRoot !== undefined) { + const roots = await inspectCheckout(cwd, { kind: "roots" }); + if (roots.kind !== "roots" || roots.checkoutRoot !== expectedRoot) + throw new Error("The session checkout changed."); + if (!isCheckoutArgv(input)) throw new Error("Invalid command arguments."); + const output = await execFileAsync(input[0], input.slice(1), { + cwd: roots.checkoutRoot, + timeout: 15_000, + killSignal: "SIGKILL", + maxBuffer: 256 * 1024, + }).then( + (result) => ({ ...result, exitCode: 0 }), + (error) => { + if (typeof error.code !== "number") throw error; + return { + stdout: error.stdout, + stderr: error.stderr, + exitCode: error.code, + }; + } + ); + process.stdout.write(JSON.stringify(output)); + return; + } + const query = parseQuery(input); const reply = await inspectCheckout(cwd, query); await new Promise((resolve, reject) => { process.stdout.write(encodeReply(reply), (error) => diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 57fe4865d..52b33d792 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,3 +1,4 @@ +import { isCheckoutCommandResult } from "@dispatch/runner-protocol"; import { isPromptImageMimeType } from "./acp/prompt-source.js"; import { readSessionFile } from "../files/session-file.js"; import { readAgentView } from "./checkout-runner.js"; @@ -3005,6 +3006,27 @@ export class AgentManager { return this.remote?.permitsAgentMcp(placement) ?? false; } + async runCheckoutCommand( + agent: AgentRecord, + expectedRoot: string, + argv: string[] + ) { + const placement = remotePlacement(agent.cwd); + if (!placement || !this.remote || !agent.fullAccess) + throw new AgentError("Checkout command is unavailable.", 403); + const { value } = await this.remote.requestSession(placement, { + kind: "runCheckout", + agentId: agent.id, + expectedRoot, + argv, + }); + const output: unknown = + typeof value === "string" ? JSON.parse(value) : null; + if (!isCheckoutCommandResult(output)) + throw new AgentError("Invalid runner command response.", 502); + return output; + } + remoteRepoOperation(agent: AgentRecord): (() => Promise) | undefined { const placement = remotePlacement(agent.cwd); if (!placement || !this.remote?.repoToolFor(placement)) return undefined; diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 9b3cc46d5..58d47a74f 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -644,6 +644,35 @@ export async function runRemoteRunner(filename: string) { case "log": result(await supervisor.log(agentId, workspace)); break; + case "runCheckout": { + const cwd = await supervisor.checkoutDirectory( + agentId, + workspace, + target?.cwd + ); + const child = execute( + setpriv, + [ + ...childArgs, + ...selfCommand("runner-inspect-checkout"), + cwd, + "--run-command", + command.expectedRoot, + ], + { env, timeout: 20_000, maxBuffer: 1024 * 1024 } + ); + child.child.stdin?.on("error", () => {}); + child.child.stdin?.end(JSON.stringify(command.argv)); + try { + const { stdout } = await child; + result(stdout); + } catch { + throw new Error( + "The runner could not execute the checkout command." + ); + } + break; + } case "repo": { if (!(await supervisor.isBound(agentId, workspace))) throw new Error("Agent is not bound to this workspace"); @@ -725,6 +754,8 @@ export async function runRemoteRunner(filename: string) { pullRequestWatch: true, pullRequestEvidence: true, checkoutInspection: true, + checkoutMetadata: true, + checkoutCommands: true, workspacePreparation: true, sessionCheckout: true, checkoutRelease: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 08ada9b86..3f6fe37c9 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -161,6 +161,8 @@ type Peer = { pullRequestWatch: boolean; pullRequestEvidence: boolean; checkoutInspection: boolean; + checkoutMetadata: boolean; + checkoutCommands: boolean; sessionCheckout: boolean; checkoutRelease: boolean; sessionFiles: boolean; @@ -695,6 +697,8 @@ export class RemoteRunnerService { sessionCheckout: ready.sessionCheckout === true, checkoutRelease: ready.checkoutRelease === true, sessionFiles: ready.sessionFiles === true, + checkoutCommands: ready.checkoutCommands === true, + checkoutMetadata: ready.checkoutMetadata === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, workspacePreparation: ready.workspacePreparation === true, @@ -1571,6 +1575,18 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to inspect and release a session checkout." ); + if (command.kind === "runCheckout" && !peer.checkoutCommands) + throw new RunnerCapabilityUnavailable( + "Update the runner to run checkout commands." + ); + if ( + command.kind === "inspectCheckout" && + (command.query.kind === "roots" || command.query.kind === "listFiles") && + !peer.checkoutMetadata + ) + throw new RunnerCapabilityUnavailable( + "Update the runner to discover checkout metadata." + ); if (command.kind === "inspectCheckout" && !peer.checkoutInspection) throw new RunnerCapabilityUnavailable( "Update the runner to inspect a session checkout." diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 7816278fc..9a9826615 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -76,7 +76,10 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "runner-inspect-checkout") { const { runCheckoutInspectionCli } = await import("./agents/checkout-inspection.js"); - await runCheckoutInspectionCli(process.argv[3]!); + await runCheckoutInspectionCli( + process.argv[3]!, + process.argv[4] === "--run-command" ? process.argv[5] : undefined + ); } else if (process.argv[2] === "remote-runner") { const { runRemoteRunner } = await import("./agents/remote/runner.js"); await runRemoteRunner(process.argv[3]!); diff --git a/apps/server/src/personas/catalog.ts b/apps/server/src/personas/catalog.ts index 7d4643b62..7bd2e53b0 100644 --- a/apps/server/src/personas/catalog.ts +++ b/apps/server/src/personas/catalog.ts @@ -216,7 +216,11 @@ export class PersonaCatalogCache { } } - async get(cwd: string, waitForRefresh = false): Promise { + async get( + cwd: string, + waitForRefresh = false, + includeFallback = true + ): Promise { const common = await this.git(cwd, [ "rev-parse", "--path-format=absolute", @@ -232,12 +236,14 @@ export class PersonaCatalogCache { if (!common || !remote) { const warnings: string[] = []; return { - personas: await loadPersonas( - common && path.basename(common) === ".git" - ? path.dirname(common) - : cwd, - warnings - ), + personas: includeFallback + ? await loadPersonas( + common && path.basename(common) === ".git" + ? path.dirname(common) + : cwd, + warnings + ) + : [], warnings, refreshing: false, updatedAt: null, diff --git a/apps/server/src/personas/loader.ts b/apps/server/src/personas/loader.ts index 144a2e422..696d242b6 100644 --- a/apps/server/src/personas/loader.ts +++ b/apps/server/src/personas/loader.ts @@ -76,30 +76,54 @@ export function parseFrontmatter(content: string): { export async function loadPersonas( repoRoot: string, warnings: string[] = [] +): Promise { + return loadCheckoutPersonas( + (dir) => readdir(path.join(repoRoot, dir)), + (file) => readFile(path.join(repoRoot, file), "utf8"), + warnings + ); +} + +export async function loadCheckoutPersonas( + listFiles: (dir: string) => Promise, + readFile: (file: string) => Promise, + warnings: string[] ): Promise { const personas: PersonaDefinition[] = []; const seen = new Set(); + let bytes = 0; - for (const personasDir of PERSONA_DIRS) { - const dir = path.join(repoRoot, personasDir); + for (const directory of PERSONA_DIRS) { let entries: string[]; try { - entries = await readdir(dir); - } catch { + entries = await listFiles(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") + warnings.push( + `Could not list personas in ${directory}: ${errorMessage(error)}` + ); continue; } - const mdFiles = entries.filter((f) => f.endsWith(".md")).sort(); - for (const file of mdFiles) { - const slug = file.replace(/\.md$/, ""); + for (const file of entries.filter((name) => name.endsWith(".md")).sort()) { + const slug = file.slice(0, -3); if (seen.has(slug)) continue; + if (seen.size >= 100) { + warnings.push("Persona catalog exceeds the 100-file or 4 MiB limit."); + return personas; + } seen.add(slug); try { - const content = await readFile(path.join(dir, file), "utf-8"); - personas.push(toPersonaDefinition(slug, content)); + const content = await readFile(`${directory}/${file}`); + bytes += Buffer.byteLength(content ?? ""); + if (bytes > 4 * 1024 * 1024) { + warnings.push("Persona catalog exceeds the 100-file or 4 MiB limit."); + return personas; + } + if (content !== null) personas.push(toPersonaDefinition(slug, content)); } catch (error) { warnings.push( - `Could not load persona ${path.join(personasDir, file)}: ${errorMessage(error)}` + `Could not load persona ${directory}/${file}: ${errorMessage(error)}` ); } } diff --git a/apps/server/src/personas/resolve.ts b/apps/server/src/personas/resolve.ts index c8338abef..d642a72eb 100644 --- a/apps/server/src/personas/resolve.ts +++ b/apps/server/src/personas/resolve.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import { loadPersonaBySlug, loadPersonas, @@ -18,6 +19,13 @@ export async function discoverPersonas( source: "catalog" | "workspace" = "workspace", waitForRefresh = false ) { + if (remotePlacement(cwd)) + return { + personas: [...BUILT_IN_PERSONAS], + warnings: [], + refreshing: false, + updatedAt: null, + }; const root = await resolveWorktreeRoot(cwd).catch(() => cwd); const catalog = await personaCatalog.get(root, waitForRefresh); const warnings = [...catalog.warnings]; @@ -44,7 +52,10 @@ export async function resolveLaunchPersona( ): Promise { if (slug.includes("/") || slug.includes("\\") || slug.includes("..")) throw new Error("Invalid persona slug."); - const root = cwd && (await resolveWorktreeRoot(cwd).catch(() => cwd)); + const root = + cwd && + !remotePlacement(cwd) && + (await resolveWorktreeRoot(cwd).catch(() => cwd)); // A malformed local override must fail explicitly, not fall back to a remote copy. let persona = root && source === "workspace" ? await loadPersonaBySlug(root, slug) : null; diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index 309e229a1..1cec70f9d 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -2,7 +2,6 @@ import { createRiskReader } from "../shared/mcp/pull-request-risk-tools.js"; import type { PullRequestRefresher } from "../agents/pull-request-refresher.js"; import type { RedeemCodexReset } from "../agents/codex-reset.js"; import type { ScheduledMessageService } from "../scheduled-messages/service.js"; -import path from "node:path"; import type { FastifyInstance } from "fastify"; import { isJSONRPCRequest } from "@modelcontextprotocol/sdk/types.js"; @@ -14,7 +13,10 @@ import { createProviderPlansReporter } from "../agents/provider-plans.js"; import type { UsageCallbacks } from "../shared/mcp/usage-tools.js"; import type { AgentManager } from "../agents/manager.js"; import { remotePlacement } from "../agents/remote/protocol.js"; -import { agentWorkspaceDir } from "../agents/workspace-target.js"; +import { + agentWorkspaceDir, + resolveLaunchLocation, +} from "../agents/workspace-target.js"; import * as telemetry from "../agents/telemetry.js"; import type { LoginLinkStore } from "../auth.js"; import type { BrainStore } from "../brain/store.js"; @@ -22,10 +24,7 @@ import type { AddJobInput, JobService } from "../jobs/service.js"; import type { UpdateJobInput } from "../jobs/store.js"; import type { TemplateService } from "../templates/service.js"; import type { AddTemplateInput } from "../templates/store.js"; -import { - resolveRepoRoot, - resolveWorktreeRoot, -} from "../shared/git/git-context.js"; +import { discoverRepoTools, mcpCheckoutRoots } from "../server/mcp-checkout.js"; import type { CrudToolCallbacks } from "../shared/mcp/crud-tools.js"; import { handleMcpRequest } from "../shared/mcp/server.js"; import type { StreamService } from "../chat/service.js"; @@ -60,6 +59,50 @@ function isOwnerReviewRequest(body: unknown): boolean { ); } +async function checkoutContext( + deps: McpRouteDeps, + agent: NonNullable>>, + body: unknown, + authorized: boolean +) { + const placement = remotePlacement(agent.cwd); + const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; + const ownerOnly = isOwnerReviewRequest(body); + const roots = ownerOnly + ? null + : await mcpCheckoutRoots(deps.agentManager, agent); + const repoRoot = placement ? null : (roots?.repositoryRoot ?? null); + const worktreeRoot = placement ? null : (roots?.checkoutRoot ?? null); + // The runner's machine-local paths never become host paths or Brain keys. + const brainRepoRoot = + placement && agent.projectId && roots?.repositoryRoot + ? (( + await deps.pool.query( + "SELECT repo_root FROM projects WHERE id = $1", + [agent.projectId] + ) + ).rows[0]?.repo_root ?? null) + : repoRoot; + return { + workspaceDir, + repoRoot, + context: { + worktreeRoot, + brainRepoRoot, + toolsRoot: placement ? workspaceDir : (worktreeRoot ?? undefined), + discoverRepoTools: ownerOnly + ? async () => [] + : () => + discoverRepoTools( + deps.agentManager, + agent, + authorized, + roots?.checkoutRoot ?? null + ), + }, + }; +} + type McpRouteDeps = { pullRequests?: Pick; riskEnabled?: () => Promise; @@ -130,7 +173,7 @@ function buildCrudCallbacks( listJobs: async (directory) => { const jobs = await deps.jobService.listJobs(); if (!directory) return jobs; - const resolved = path.resolve(directory); + const resolved = resolveLaunchLocation(directory); return jobs.filter((j) => j.directory === resolved); }, getJobById: (jobId) => deps.jobService.getJobById(jobId), @@ -150,7 +193,7 @@ function buildCrudCallbacks( listTemplates: async (directory) => { const templates = await deps.templateService.listTemplates(); if (!directory) return templates; - const resolved = path.resolve(directory); + const resolved = resolveLaunchLocation(directory); return templates.filter((t) => t.directory === resolved); }, getTemplateById: (templateId) => @@ -224,18 +267,13 @@ export async function registerMcpRoutes( .send({ error: "Token does not match the active job run." }); } - let repoRoot: string | null = null; - let worktreeRoot: string | null = null; - // Repo tools, brain and job defaults follow a moved workspace. - const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; - try { - // Owner review gets checkout facts through the runner. Keep the usual - // scope for other requests, including batches with repo-dependent tools. - if (!remotePlacement(agent.cwd) && !isOwnerReviewRequest(request.body)) { - repoRoot = await resolveRepoRoot(workspaceDir); - worktreeRoot = await resolveWorktreeRoot(workspaceDir); - } - } catch {} + const checkout = await checkoutContext( + deps, + agent, + request.body, + Boolean(bearerToken) + ); + const { workspaceDir, repoRoot } = checkout; const jobTools = run ? { @@ -294,7 +332,7 @@ export async function registerMcpRoutes( fullAccess: agent.fullAccess === true, }, repoRoot, - worktreeRoot, + ...checkout.context, sendNotify: deps.mcpSendNotify, renameSession: deps.mcpRenameSession, setWorkspace: deps.mcpSetWorkspace, @@ -302,6 +340,7 @@ export async function registerMcpRoutes( listFiles: deps.mcpListFiles, deleteFile: deps.mcpDeleteFile, listPersonas: deps.mcpListPersonas, + listSessionPersonas: true, launchOwnerReviews: deps.mcpLaunchOwnerReviews, listPersonalities: deps.mcpListPersonalities, createPersonality: deps.mcpCreatePersonality, @@ -360,16 +399,13 @@ export async function registerMcpRoutes( .send({ error: "Job agents must use the job-scoped MCP route." }); } - let repoRoot: string | null = null; - let worktreeRoot: string | null = null; - // Repo tools, brain and job defaults follow a moved workspace. - const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; - try { - if (!remotePlacement(agent.cwd) && !isOwnerReviewRequest(request.body)) { - repoRoot = await resolveRepoRoot(workspaceDir); - worktreeRoot = await resolveWorktreeRoot(workspaceDir); - } - } catch {} + const checkout = await checkoutContext( + deps, + agent, + request.body, + Boolean(bearerToken) + ); + const { workspaceDir, repoRoot } = checkout; reply.hijack(); // Captured before the transport writes anything, so an archive that stops @@ -406,7 +442,7 @@ export async function registerMcpRoutes( fullAccess: agent.fullAccess === true, }, repoRoot, - worktreeRoot, + ...checkout.context, remoteRepoOperation: bearerToken && remotePlacement(agent.cwd) ? deps.agentManager.remoteRepoOperation(agent) @@ -418,6 +454,7 @@ export async function registerMcpRoutes( listFiles: deps.mcpListFiles, deleteFile: deps.mcpDeleteFile, listPersonas: deps.mcpListPersonas, + listSessionPersonas: true, launchOwnerReviews: deps.mcpLaunchOwnerReviews, listPersonalities: deps.mcpListPersonalities, createPersonality: deps.mcpCreatePersonality, diff --git a/apps/server/src/routes/personas.ts b/apps/server/src/routes/personas.ts index fee4290f8..75eddf856 100644 --- a/apps/server/src/routes/personas.ts +++ b/apps/server/src/routes/personas.ts @@ -1,3 +1,4 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; import type { Effort } from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; import { discoverPersonas } from "../personas/resolve.js"; @@ -8,6 +9,10 @@ import type { AgentManager } from "../agents/manager.js"; import { StreamServiceError, type StreamService } from "../chat/service.js"; import { CLI_AGENT_TYPES } from "../agent-type-settings.js"; import { validateAgentModel } from "../shared/agent-models.js"; +import { + discoverSessionPersonas, + readSessionOwnerRules, +} from "../server/mcp-persona-handlers.js"; import { hasCodeowners } from "../personas/codeowners.js"; import { supportsPersonaType } from "../personas/loader.js"; import { resolveWorktreeRoot } from "../shared/git/git-context.js"; @@ -105,15 +110,41 @@ export async function registerPersonaRoutes( deps: PersonaRouteDeps ): Promise { app.get("/api/v1/personas", async (request, reply) => { - const query = request.query as { cwd?: unknown; type?: unknown }; - if (typeof query.cwd !== "string") { - return reply - .code(400) - .send({ error: "cwd query parameter is required." }); - } + const query = request.query as { + agentId?: unknown; + cwd?: unknown; + type?: unknown; + }; + const type = query.type === "task" ? "task" : "review"; try { - const worktreeRoot = await resolveOptionalWorktreeRoot(query.cwd); - const type = query.type === "task" ? "task" : "review"; + if (typeof query.agentId === "string") { + const agent = await deps.agentManager.getAgent(query.agentId); + if (!agent) return reply.code(404).send({ error: "Agent not found." }); + const [catalog, owners] = await Promise.all([ + discoverSessionPersonas(deps.agentManager, agent), + readSessionOwnerRules(deps.agentManager, agent).catch(() => null), + ]); + return { + ...catalog, + personas: catalog.personas + .filter((p) => supportsPersonaType(p, type)) + .map(({ slug, name, description, type }) => ({ + slug, + name, + description, + type, + })), + codeowners: owners !== null, + }; + } + if (typeof query.cwd !== "string") { + return reply + .code(400) + .send({ error: "cwd query parameter is required." }); + } + const worktreeRoot = remotePlacement(query.cwd) + ? null + : await resolveOptionalWorktreeRoot(query.cwd); const { personas, warnings, refreshing, updatedAt } = await discoverPersonas( query.cwd, diff --git a/apps/server/src/server/mcp-checkout.ts b/apps/server/src/server/mcp-checkout.ts new file mode 100644 index 000000000..c19b37c5a --- /dev/null +++ b/apps/server/src/server/mcp-checkout.ts @@ -0,0 +1,69 @@ +import { remotePlacement } from "@dispatch/runner-protocol"; +import type { AgentManager, AgentRecord } from "../agents/manager.js"; +import { + parseRepoToolFile, + parseRepoTools, + REPO_TOOL_MANIFEST_PATH, +} from "../shared/mcp/repo-tools.js"; + +export async function readAgentCheckoutFile( + manager: AgentManager, + agent: AgentRecord, + path: string +) { + const reply = await manager.inspectCheckout(agent, { + kind: "readFile", + path, + }); + if (reply.kind !== "readFile") + throw new Error("Runner did not return the checkout file."); + return reply.content; +} + +export async function mcpCheckoutRoots( + manager: AgentManager, + agent: AgentRecord +) { + try { + const reply = await manager.inspectCheckout(agent, { kind: "roots" }); + if (reply.kind === "roots") return reply; + } catch { + // Built-in MCP tools remain usable when the checkout is unavailable. + } + return { checkoutRoot: null, repositoryRoot: null }; +} + +export async function discoverRepoTools( + manager: AgentManager, + agent: AgentRecord, + authorized: boolean, + checkoutRoot: string | null +) { + let content: string | null; + try { + content = await readAgentCheckoutFile( + manager, + agent, + REPO_TOOL_MANIFEST_PATH + ); + } catch { + return []; + } + const remote = remotePlacement(agent.cwd); + return parseRepoTools( + parseRepoToolFile(content), + remote + ? (command) => { + if (!authorized || !agent.fullAccess || !checkoutRoot) + throw new Error( + "Repository commands require a full-access runner session and its scoped MCP token." + ); + return manager.runCheckoutCommand(agent, checkoutRoot, [ + "env", + `DISPATCH_AGENT_ID=${agent.id}`, + ...command, + ]); + } + : undefined + ); +} diff --git a/apps/server/src/server/mcp-handlers.ts b/apps/server/src/server/mcp-handlers.ts index 585836808..4d26d9c01 100644 --- a/apps/server/src/server/mcp-handlers.ts +++ b/apps/server/src/server/mcp-handlers.ts @@ -167,6 +167,7 @@ async function addressableAgents< workspacePath?: string | null; parentAgentId?: string | null; launchedByAgentId?: string | null; + projectId?: string | null; }, >( all: T[], @@ -197,6 +198,10 @@ async function addressableAgents< result.push(a); continue; } + if (remotePlacement(a.cwd) || (sender && remotePlacement(sender.cwd))) { + if (sender?.projectId && sender.projectId === a.projectId) result.push(a); + continue; + } try { const aRoot = await resolveRepoRoot(a.workspacePath ?? a.cwd); if (aRoot === senderRepoRoot) result.push(a); @@ -384,7 +389,9 @@ async function handleLaunchAgent( input.persona || (runnerParent && persona) ? runnerParent ? await resolveRunnerPersona(deps.agentManager, parent, persona!) - : await resolveLaunchPersona(cwd, persona!) + : cwd === parentCwd + ? await resolveRunnerPersona(deps.agentManager, parent, persona!) + : await resolveLaunchPersona(cwd, persona!) : null; if (selectedPersona && (selectedPersona.type ?? "review") === "review") { if (template) diff --git a/apps/server/src/server/mcp-persona-handlers.ts b/apps/server/src/server/mcp-persona-handlers.ts index a8e9697f3..698b1dbc2 100644 --- a/apps/server/src/server/mcp-persona-handlers.ts +++ b/apps/server/src/server/mcp-persona-handlers.ts @@ -1,7 +1,7 @@ import { remotePlacement } from "@dispatch/runner-protocol"; import type { Effort } from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; -import { discoverPersonas, resolveLaunchPersona } from "../personas/resolve.js"; +import { resolveLaunchPersona } from "../personas/resolve.js"; import type { Pool } from "pg"; import type { AgentManager, AgentRecord } from "../agents/manager.js"; @@ -11,13 +11,19 @@ import { getEnabledAgentTypes, isCliAgentType, } from "../agent-type-settings.js"; -import { getBuiltInPersona } from "../personas/built-in.js"; +import { + appendBuiltInPersonas, + BUILT_IN_PERSONAS, + getBuiltInPersona, +} from "../personas/built-in.js"; import { supportsPersonaType, assemblePersonaPrompt, buildStandardFeedbackGuidance, MAX_PERSONA_PROMPT_BYTES, loadPersonaFromCheckout, + loadCheckoutPersonas, + mergePersonasWithWorktreePrecedence, type PersonaDefinition, } from "../personas/loader.js"; import { @@ -30,6 +36,8 @@ import { LEGACY_OWNERS_PATH, OWNERS_PATH } from "../personas/paths.js"; import { validateAgentModel } from "../shared/agent-models.js"; import type { PublishUiEvent } from "./mcp-handler-types.js"; +import { personaCatalog } from "../personas/catalog.js"; +import { mcpCheckoutRoots, readAgentCheckoutFile } from "./mcp-checkout.js"; import { PERSONA_CONTEXT_ARG } from "../agents/acp/persona-context.js"; const CODEX_FULL_ACCESS_ARG = "--dangerously-bypass-approvals-and-sandbox"; @@ -42,18 +50,53 @@ export type CreatePersonaHandlersDeps = { withStreamFlag: (agent: AgentRecord) => AgentRecord & { hasStream: boolean }; }; -async function readAgentCheckoutFile( +export async function discoverSessionPersonas( manager: AgentManager, - agent: AgentRecord, - path: string + agent: AgentRecord +) { + const warnings: string[] = []; + const local = await loadCheckoutPersonas( + async (path) => { + const reply = await manager.inspectCheckout(agent, { + kind: "listFiles", + path, + }); + if (reply.kind !== "listFiles") + throw new Error("Runner did not return a file list."); + return reply.names; + }, + (path) => readAgentCheckoutFile(manager, agent, path), + warnings + ); + const root = remotePlacement(agent.cwd) + ? null + : (await mcpCheckoutRoots(manager, agent)).checkoutRoot; + const catalog = root ? await personaCatalog.get(root, false, false) : null; + warnings.push(...(catalog?.warnings ?? [])); + const personas = appendBuiltInPersonas( + mergePersonasWithWorktreePrecedence({ + worktreePersonas: local, + repoPersonas: catalog?.personas ?? [], + }), + BUILT_IN_PERSONAS + ); + return { + personas, + warnings, + refreshing: catalog?.refreshing ?? false, + updatedAt: catalog?.updatedAt ?? null, + }; +} + +export async function readSessionOwnerRules( + manager: AgentManager, + agent: AgentRecord ) { - const reply = await manager.inspectCheckout(agent, { - kind: "readFile", - path, - }); - if (reply.kind !== "readFile") - throw new Error("Runner did not return the checkout file."); - return reply.content; + for (const path of [OWNERS_PATH, LEGACY_OWNERS_PATH]) { + const content = await readAgentCheckoutFile(manager, agent, path); + if (content !== null) return { path, content }; + } + return null; } export async function resolveRunnerPersona( @@ -64,7 +107,15 @@ export async function resolveRunnerPersona( const persona = (await loadPersonaFromCheckout(slug, (path) => readAgentCheckoutFile(manager, agent, path) - )) ?? getBuiltInPersona(slug); + )) ?? + (remotePlacement(agent.cwd) + ? getBuiltInPersona(slug) + : await resolveLaunchPersona( + agentWorkspaceDir(agent), + slug, + undefined, + "catalog" + )); if (!persona) throw new Error( `Persona "${slug}" not found in this checkout or built-ins.` @@ -121,7 +172,7 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { parent.fullAccess, () => opts.resolvedPersona ?? - resolveLaunchPersona(cwd, opts.persona, "review") + resolveRunnerPersona(agentManager, parent, opts.persona) ); } @@ -306,17 +357,12 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { const reviewedState = { head: changes.head, stateId: changes.stateId }; const readCheckoutFile = (path: string) => readAgentCheckoutFile(agentManager, parent, path); - let ownersPath = OWNERS_PATH; - let content = await readCheckoutFile(ownersPath); - if (content === null) { - ownersPath = LEGACY_OWNERS_PATH; - content = await readCheckoutFile(ownersPath); - } - if (content === null) + const owners = await readSessionOwnerRules(agentManager, parent); + if (!owners) throw new Error( `No ${OWNERS_PATH} found in this workspace. Add ownership rules before launching owner reviews.` ); - const config = parseCodeowners(content, ownersPath); + const config = parseCodeowners(owners.content, owners.path); const resolvedPlan = resolveCodeowners( config, changes.files, @@ -432,12 +478,14 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { return reply; } - async function listPersonas(agentCwd: string) { + async function listPersonas(agentId: string) { + const agent = await agentManager.getAgent(agentId); + if (!agent) throw new Error("Agent not found."); const { personas: loaded, warnings, refreshing, - } = await discoverPersonas(agentCwd, "workspace"); + } = await discoverSessionPersonas(agentManager, agent); if (refreshing) warnings.push( "Default-branch persona catalog is refreshing in the background. This list contains currently available definitions; list again shortly for newly merged personas." diff --git a/apps/server/src/shared/mcp/persona-interaction-tools.ts b/apps/server/src/shared/mcp/persona-interaction-tools.ts index e90258902..b285e584b 100644 --- a/apps/server/src/shared/mcp/persona-interaction-tools.ts +++ b/apps/server/src/shared/mcp/persona-interaction-tools.ts @@ -30,6 +30,7 @@ export type PersonaInteractionCallbacks = { parentAgentId?: string | null; worktreeRoot?: string | null; repoRoot?: string | null; + listSessionPersonas?: boolean; listPersonas?: McpRequestContext["listPersonas"]; launchOwnerReviews?: McpRequestContext["launchOwnerReviews"]; }; @@ -218,7 +219,7 @@ export function registerPersonaInteractionTools( const warnings: string[] = []; const available = await resolvePersonaList( listPersonas, - worktreeRoot, + callbacks.listSessionPersonas ? agentId : worktreeRoot, repoRoot, warnings ); diff --git a/apps/server/src/shared/mcp/repo-tools.ts b/apps/server/src/shared/mcp/repo-tools.ts index 63b49a63b..0b5ffa22d 100644 --- a/apps/server/src/shared/mcp/repo-tools.ts +++ b/apps/server/src/shared/mcp/repo-tools.ts @@ -4,7 +4,7 @@ import { readFile, stat } from "node:fs/promises"; import { repoCommandEnvironment } from "../lib/tool-environment.js"; import { runCommand } from "../lib/run-command.js"; -const REPO_TOOL_MANIFEST_PATH = path.join(".dispatch", "tools.json"); +export const REPO_TOOL_MANIFEST_PATH = path.join(".dispatch", "tools.json"); // Cache parsed hooks keyed by manifest path, invalidated by mtime. const hooksCache = new Map(); @@ -79,6 +79,21 @@ export async function loadRepoTools( const config = await readRepoToolFile( path.join(repoRoot, REPO_TOOL_MANIFEST_PATH) ); + return parseRepoTools(config); +} + +export function parseRepoTools( + config: RepoToolFile | null, + execute: ( + command: string[], + cwd: string, + agentId: string + ) => Promise<{ + exitCode: number; + stdout: string; + stderr: string; + }> = runLocalRepoCommand +): RepoToolDefinition[] { const rawTools = Array.isArray(config?.tools) ? config.tools : []; return rawTools.map((rawTool, index) => { @@ -109,13 +124,11 @@ export async function loadRepoTools( } } - const result = await runCommand(command, args, { - cwd: currentRepoRoot, - env: repoCommandEnvironment(agentId), - // Allow all exit codes — the agent decides how to handle failures. - // Throwing on non-zero hides useful diagnostic output (stderr, partial stdout). - allowedExitCodes: Array.from({ length: 256 }, (_, i) => i), - }); + const result = await execute( + [command, ...args], + currentRepoRoot, + agentId + ); return { agentId, @@ -132,11 +145,32 @@ export async function loadRepoTools( }); } +function runLocalRepoCommand( + [command, ...args]: string[], + cwd: string, + agentId: string +) { + return runCommand(command, args, { + cwd, + env: repoCommandEnvironment(agentId), + // Return output and exit status even on failure. + allowedExitCodes: Array.from({ length: 256 }, (_, i) => i), + }); +} + +export function parseRepoToolFile(content: string | null): RepoToolFile | null { + try { + return content === null ? null : JSON.parse(content); + } catch { + return null; + } +} + async function readRepoToolFile( filePath: string ): Promise { try { - return JSON.parse(await readFile(filePath, "utf8")) as RepoToolFile; + return parseRepoToolFile(await readFile(filePath, "utf8")); } catch { return null; } diff --git a/apps/server/src/shared/mcp/server.ts b/apps/server/src/shared/mcp/server.ts index 1de2ba56e..dafcd81b9 100644 --- a/apps/server/src/shared/mcp/server.ts +++ b/apps/server/src/shared/mcp/server.ts @@ -38,7 +38,11 @@ import { registerPersonaInteractionTools, type LaunchPersonaAgentType, } from "./persona-interaction-tools.js"; -import { loadRepoTools, type RepoToolParam } from "./repo-tools.js"; +import { + loadRepoTools, + type RepoToolDefinition, + type RepoToolParam, +} from "./repo-tools.js"; import { jsonText } from "./response.js"; import { toToolError } from "./tool-error.js"; import { registerStreamTools } from "./stream-tools.js"; @@ -276,6 +280,9 @@ export type McpRequestContext = UsageCallbacks & { scheduledMessages?: ScheduledMessageService; agent: McpAgent | null; repoRoot: string | null; + discoverRepoTools?: () => Promise; + toolsRoot?: string; + brainRepoRoot?: string | null; remoteRepoOperation?: () => Promise; worktreeRoot: string | null; /** @@ -320,6 +327,7 @@ export type McpRequestContext = UsageCallbacks & { personas?: string[]; } ) => Promise; + listSessionPersonas?: boolean; listPersonas?: (agentCwd: string) => Promise< | Array<{ slug: string; name: string; description: string }> | { @@ -523,6 +531,7 @@ export async function createDispatchMcpServer( worktreeRoot: context.worktreeRoot, repoRoot: context.repoRoot, listPersonas: context.listPersonas, + listSessionPersonas: context.listSessionPersonas, launchOwnerReviews: context.launchOwnerReviews, }); } @@ -572,8 +581,11 @@ export async function createDispatchMcpServer( } // ── Brain tools (shared memory for agents) ──────────────────────── - if (context.agent && context.repoRoot && context.brainStore) { - const brainRepoRoot = context.repoRoot; + const brainRepoRoot = + context.brainRepoRoot === undefined + ? context.repoRoot + : context.brainRepoRoot; + if (context.agent && brainRepoRoot && context.brainStore) { registerBrainTools(server, allowed, { repoRoot: brainRepoRoot, agentId: context.agent.id, @@ -642,9 +654,11 @@ export async function createDispatchMcpServer( } ); } - const toolsRoot = context.worktreeRoot ?? context.repoRoot; + const toolsRoot = + context.toolsRoot ?? context.worktreeRoot ?? context.repoRoot; if (context.agent && toolsRoot) { - const allRepoTools = await loadRepoTools(toolsRoot); + const allRepoTools = await (context.discoverRepoTools?.() ?? + loadRepoTools(toolsRoot)); const scope = context.toolScope ?? "agent"; const repoTools = allRepoTools.filter( (tool) => !tool.scope || tool.scope.includes(scope) diff --git a/apps/server/src/tasks/agent-scope.ts b/apps/server/src/tasks/agent-scope.ts index d5a73ede4..ba509e201 100644 --- a/apps/server/src/tasks/agent-scope.ts +++ b/apps/server/src/tasks/agent-scope.ts @@ -2,6 +2,7 @@ import { agentWorkspaceDir, type WorkspaceTargetAgent, } from "../agents/workspace-target.js"; +import { remotePlacement } from "@dispatch/runner-protocol"; import { resolveRepoRoot } from "../shared/git/git-context.js"; type ScopedAgent = WorkspaceTargetAgent & { projectId?: string | null }; @@ -34,7 +35,7 @@ export async function agentTaskProject( // Probed live, as the MCP routes do, never from cached git context. const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; let repoRoot: string | null = null; - if (workspaceDir) { + if (workspaceDir && !remotePlacement(workspaceDir)) { try { repoRoot = await resolveRepoRoot(workspaceDir); } catch {} diff --git a/apps/server/test/checkout-inspection.test.ts b/apps/server/test/checkout-inspection.test.ts index 2ebc23f90..ac18ee021 100644 --- a/apps/server/test/checkout-inspection.test.ts +++ b/apps/server/test/checkout-inspection.test.ts @@ -2,6 +2,7 @@ import { execFileSync, spawnSync } from "node:child_process"; import { existsSync, mkdirSync, + realpathSync, mkdtempSync, rmSync, symlinkSync, @@ -47,14 +48,18 @@ function put(root: string, file: string, content: string): void { writeFileSync(target, content); } -function runCli(cwd: string, input: string) { - const result = spawnSync(process.execPath, [cli], { - cwd, - input, - encoding: "utf8", - timeout: 10_000, - maxBuffer: 5 * 1024 * 1024, - }); +function runCli(cwd: string, input: string, expectedRoot?: string) { + const result = spawnSync( + process.execPath, + expectedRoot ? [cli, expectedRoot] : [cli], + { + cwd, + input, + encoding: "utf8", + timeout: 10_000, + maxBuffer: 5 * 1024 * 1024, + } + ); if (result.error) throw result.error; return result; } @@ -73,8 +78,8 @@ function subprocess(cwd: string, query: CheckoutQuery): Promise { } beforeAll(() => { - scratch = mkdtempSync( - path.join(os.tmpdir(), "dispatch-checkout-inspection-") + scratch = realpathSync( + mkdtempSync(path.join(os.tmpdir(), "dispatch-checkout-inspection-")) ); cli = path.join(scratch, "inspect.mjs"); const entry = path.join(scratch, "entry.ts"); @@ -83,7 +88,7 @@ beforeAll(() => { ); writeFileSync( entry, - `import { runCheckoutInspectionCli } from ${JSON.stringify(implementation)};\nawait runCheckoutInspectionCli(process.cwd());\n` + `import { runCheckoutInspectionCli } from ${JSON.stringify(implementation)};\nawait runCheckoutInspectionCli(process.cwd(), process.argv[2]);\n` ); execFileSync("bun", ["build", "--target=node", "--outfile", cli, entry], { stdio: "pipe", @@ -125,10 +130,61 @@ afterEach(() => { rmSync(fixture, { recursive: true, force: true }); }); +it("executes argv in the observed checkout and rejects a checkout mismatch", () => { + const command = JSON.stringify([ + "sh", + "-c", + "pwd; printf diagnostic >&2; exit 7", + ]); + const result = runCli(checkout, command, checkout); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + stdout: checkout + "\n", + stderr: "diagnostic", + exitCode: 7, + }); + const moved = runCli(checkout, command, repo); + expect(moved.status).toBe(1); + expect(moved.stdout).toBe(""); + expect(moved.stderr).toContain("The session checkout changed"); +}); + describe.each([ ["in process", inspectCheckout], ["CLI", subprocess], ] as const)("checkout inspection %s", (_name, inspect) => { + it("discovers ignored configuration and handles non-Git folders", async () => { + put(checkout, ".gitignore", ".config/\n"); + put(checkout, ".config/profile.txt", "checkout profile"); + git(checkout, "check-ignore", ".config/profile.txt"); + expect(await inspect(checkout, { kind: "roots" })).toEqual({ + kind: "roots", + checkoutRoot: checkout, + repositoryRoot: repo, + }); + expect( + await inspect(checkout, { kind: "listFiles", path: ".config" }) + ).toEqual({ + kind: "listFiles", + names: ["profile.txt"], + }); + expect( + await inspect(checkout, { kind: "readFile", path: ".config/missing.txt" }) + ).toEqual({ + kind: "readFile", + content: null, + }); + expect(await inspect(bin, { kind: "roots" })).toEqual({ + kind: "roots", + checkoutRoot: bin, + repositoryRoot: null, + }); + expect(await inspect(bin, { kind: "listFiles", path: "missing" })).toEqual({ + kind: "listFiles", + names: [], + }); + }); + it("refreshes a base and reports committed, staged, unstaged, deleted, renamed and untracked paths", async () => { put(checkout, "committed.txt", "committed"); git(checkout, "add", "committed.txt"); diff --git a/apps/server/test/mcp-handlers.test.ts b/apps/server/test/mcp-handlers.test.ts index 10d89ed6f..a7a9882b1 100644 --- a/apps/server/test/mcp-handlers.test.ts +++ b/apps/server/test/mcp-handlers.test.ts @@ -127,6 +127,28 @@ function createMockDeps() { reviewAgentType: null, filesDir: null, })), + inspectCheckout: vi.fn(async (_agent, query) => { + if (query.kind === "roots") + return { + kind: "roots", + checkoutRoot: "/repo", + repositoryRoot: "/repo", + }; + if (query.kind === "listFiles") + return { + kind: "listFiles", + names: query.path === ".agents/personas" ? ["security.md"] : [], + }; + const persona = query.path.endsWith("/security.md") + ? await loadPersonaBySlug("/repo", "security") + : null; + return { + kind: "readFile", + content: persona + ? `---\ntype: ${persona.type ?? "review"}\nname: ${persona.name}\ndescription: ${persona.description ?? "Security review"}\n---\n${persona.body}` + : null, + }; + }), listAgents: vi.fn(async () => []), createAgent: vi.fn(async (opts: any) => ({ id: "agt_new1", @@ -442,7 +464,7 @@ describe("createMcpHandlers", () => { describe("listPersonas", () => { it("returns personas mapped to slug/name/description", async () => { - const result = await handlers.listPersonas("/repo"); + const result = await handlers.listPersonas("agt_test1"); expect(result).toEqual({ warnings: [], personas: [ diff --git a/apps/server/test/mcp-routes.test.ts b/apps/server/test/mcp-routes.test.ts index 222895914..91ff9f5ac 100644 --- a/apps/server/test/mcp-routes.test.ts +++ b/apps/server/test/mcp-routes.test.ts @@ -46,6 +46,17 @@ function createMockDeps() { // Only the chat-surface flag reads it from these routes. pool: { query: vi.fn(async () => ({ rows: [] })) } as never, agentManager: { + inspectCheckout: vi.fn( + async ( + _record: { cwd: string }, + _query: { kind: string } + ): Promise => ({ + kind: "roots", + checkoutRoot: "/repo", + repositoryRoot: "/repo", + }) + ), + remoteRepoOperation: vi.fn(), permitsRemoteAgentMcp: vi.fn(() => false), getAgent: vi.fn(async () => ({ id: "agt_test1", @@ -131,6 +142,12 @@ afterAll(async () => { beforeEach(() => { vi.clearAllMocks(); + deps.agentManager.permitsRemoteAgentMcp.mockReturnValue(false); + deps.agentManager.inspectCheckout.mockResolvedValue({ + kind: "roots", + checkoutRoot: "/repo", + repositoryRoot: "/repo", + }); deps.agentManager.getAgent.mockResolvedValue({ id: "agt_test1", cwd: "/tmp/test", @@ -321,6 +338,62 @@ describe("usage callback wiring", () => { ); }); +describe("runner-scoped manifests", () => { + it("keeps identical remote paths separate and reads edits on the next request", async () => { + deps.agentManager.permitsRemoteAgentMcp.mockReturnValue(true); + const agent = await deps.agentManager.getAgent(); + const manifests = new Map([ + ["runner://rnr_alpha/proof", "alpha"], + ["runner://rnr_beta/proof", "beta"], + ]); + deps.agentManager.inspectCheckout.mockImplementation( + async (record, query) => { + if (query.kind === "roots") + return { + kind: "roots", + checkoutRoot: "/work/repo", + repositoryRoot: "/work/repo", + }; + const description = manifests.get(record.cwd); + return { + kind: "readFile", + content: description + ? JSON.stringify({ + tools: [{ name: "proof", command: ["true"], description }], + }) + : null, + }; + } + ); + const list = async (cwd: string) => { + deps.agentManager.getAgent.mockResolvedValue({ ...agent, cwd }); + const res = await app.inject({ + method: "POST", + url: "/api/mcp/agt_test1", + payload: {}, + }); + expect(res.statusCode).toBe(200); + const context = vi.mocked(handleMcpRequest).mock.calls.at(-1)?.[3]; + expect(context).toMatchObject({ repoRoot: null, worktreeRoot: null }); + return context?.discoverRepoTools?.(); + }; + await expect(list("runner://rnr_alpha/proof")).resolves.toMatchObject([ + { name: "repo_proof", description: "alpha" }, + ]); + await expect(list("runner://rnr_beta/proof")).resolves.toMatchObject([ + { name: "repo_proof", description: "beta" }, + ]); + manifests.set("runner://rnr_beta/proof", "updated"); + await expect(list("runner://rnr_beta/proof")).resolves.toMatchObject([ + { name: "repo_proof", description: "updated" }, + ]); + manifests.delete("runner://rnr_beta/proof"); + await expect(list("runner://rnr_beta/proof")).resolves.toEqual([]); + expect(resolveRepoRoot).not.toHaveBeenCalled(); + expect(resolveWorktreeRoot).not.toHaveBeenCalled(); + }); +}); + describe("owner review checkout boundary", () => { it.each(["/api/mcp/agt_test1", "/api/mcp/jobs/run_1/agt_test1"])( "skips host checkout discovery for owner calls on %s", @@ -352,8 +425,12 @@ describe("owner review checkout boundary", () => { payload: [call, { ...call, id: 2, params: { name: "list_personas" } }], }); expect(res.statusCode).toBe(200); - expect(resolveRepoRoot).toHaveBeenCalledWith("/tmp/test"); - expect(resolveWorktreeRoot).toHaveBeenCalledWith("/tmp/test"); + expect(deps.agentManager.inspectCheckout).toHaveBeenCalledWith( + expect.objectContaining({ cwd: "/tmp/test" }), + { kind: "roots" } + ); + expect(resolveRepoRoot).not.toHaveBeenCalled(); + expect(resolveWorktreeRoot).not.toHaveBeenCalled(); } ); }); diff --git a/apps/server/test/persona-catalog.test.ts b/apps/server/test/persona-catalog.test.ts index 8ea41de1f..30eae0c1d 100644 --- a/apps/server/test/persona-catalog.test.ts +++ b/apps/server/test/persona-catalog.test.ts @@ -1,3 +1,4 @@ +import { inspectCheckout } from "../src/agents/checkout-inspection.js"; import { createPersonaHandlers } from "../src/server/mcp-persona-handlers.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; @@ -147,10 +148,20 @@ describe("shared remote persona catalog", () => { const cache = new PersonaCatalogCache(delayed); const spy = vi .spyOn(personaCatalog, "get") - .mockImplementation((cwd, wait) => cache.get(cwd, wait)); - const handlers = createPersonaHandlers({} as never); + .mockImplementation((cwd, wait, fallback) => + cache.get(cwd, wait, fallback) + ); + const handlers = createPersonaHandlers({ + agentManager: { + getAgent: async () => ({ cwd: checkout }), + inspectCheckout: ( + _agent: unknown, + query: Parameters[1] + ) => inspectCheckout(checkout, query), + }, + } as never); try { - const result = await handlers.listPersonas(checkout); + const result = await handlers.listPersonas("author"); expect(result.warnings.join()).toContain("refreshing in the background"); expect(fetches).toBe(0); } finally { diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 6bcb5ad01..86edc812a 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -332,6 +332,24 @@ it("validates checkout queries, results and borrowed launches", () => { expect(parse({ ...request, query: { ...read, path } })).toBeNull(); expect(isCheckoutReply({ kind: "changes", files: [] }, read)).toBe(false); expect(isCheckoutReply({ kind: "readFile", content: null }, read)).toBe(true); + const metadata = { kind: "listFiles", path: ".config/profiles" } as const; + expect(parse({ ...request, query: metadata })).not.toBeNull(); + expect(parse({ ...request, query: { kind: "roots" } })).not.toBeNull(); + expect( + isCheckoutReply({ kind: "listFiles", names: ["profile.txt"] }, metadata) + ).toBe(true); + expect( + isCheckoutReply({ kind: "listFiles", names: ["../profile.txt"] }, metadata) + ).toBe(false); + const execute = { + ...request, + kind: "runCheckout", + expectedRoot: "/work/checkout", + argv: ["printf", "%s", "hello"], + }; + expect(parse(execute)).not.toBeNull(); + expect(parse({ ...execute, argv: [] })).toBeNull(); + expect(parse({ ...execute, expectedRoot: "../other" })).toBeNull(); const command = { kind: "launch", workspace: "@session", diff --git a/apps/web/src/components/app/persona-launcher.tsx b/apps/web/src/components/app/persona-launcher.tsx index 0b5e32126..2607f6940 100644 --- a/apps/web/src/components/app/persona-launcher.tsx +++ b/apps/web/src/components/app/persona-launcher.tsx @@ -78,20 +78,20 @@ export function PersonaLauncher({ useAgentModelCatalog(selectedAgentType); const showModelSelect = modelCatalogLoading || modelOptions.length > 0; - const { data: personaCatalog } = useQuery<{ + const { data: personaCatalog, refetch: refreshPersonas } = useQuery<{ personas: PersonaSummary[]; /** The checkout has a .agents/owners.json to route reviewers by. */ codeowners: boolean; refreshing: boolean; }>({ - queryKey: ["personas", cwd], + queryKey: ["personas", agent.id, cwd], refetchInterval: (query) => (query.state.data?.refreshing ? 2000 : false), queryFn: async () => { const result = await api<{ personas: PersonaSummary[]; codeowners?: boolean; refreshing?: boolean; - }>(`/api/v1/personas?cwd=${encodeURIComponent(cwd)}`); + }>(`/api/v1/personas?agentId=${encodeURIComponent(agent.id)}`); return { personas: result.personas, codeowners: result.codeowners === true, @@ -169,6 +169,7 @@ export function PersonaLauncher({ setNote(""); launchMutation.reset(); setTypeDropdownOpen(false); + void refreshPersonas(); setDialogOpen(true); }; diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts index 6cf05aa79..fd4d1afbd 100644 --- a/e2e/remote-runner/owner-review.spec.ts +++ b/e2e/remote-runner/owner-review.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from "@playwright/test"; +import { expect, test, type APIRequestContext } from "@playwright/test"; import { execFileSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -7,6 +7,7 @@ import path from "node:path"; import { authHeaders, callMcpToolViaAPI, deleteAgentViaAPI } from "../helpers"; import { enrollViaUi, + guest, lane, newSettledTurn, runnerRow, @@ -37,7 +38,28 @@ function seed(directory: string, marker: string) { rules: [{ paths: ["*.txt"], personas: ["code-review"] }], }) ); - writeFileSync(path.join(directory, ".gitignore"), "provider-invocations\n"); + writeFileSync( + path.join(directory, ".gitignore"), + "provider-invocations\n.dispatch/\n.agents/personas/ignored-review.md\n" + ); + mkdirSync(path.join(directory, ".dispatch"), { recursive: true }); + writeFileSync( + path.join(directory, ".dispatch/tools.json"), + JSON.stringify({ + tools: [ + { + name: "fixture", + description: marker, + command: ["printf", "%s", marker], + }, + ], + }) + ); + writeFileSync( + path.join(directory, ".agents/personas/ignored-review.md"), + "---\nname: Ignored Review\n---\nReview the effective checkout." + ); + git("add", "."); git("commit", "-m", "base"); git("switch", "-c", "unpublished"); @@ -47,6 +69,17 @@ function seed(directory: string, marker: string) { writeFileSync(path.join(directory, "review-marker.txt"), marker); } +async function listTools(request: APIRequestContext, id: string) { + const res = await request.post("/api/mcp/" + id, { + headers: { Accept: "application/json, text/event-stream" }, + data: { jsonrpc: "2.0", id: 1, method: "tools/list" }, + }); + const text = await res.text(); + const line = text.split("\n").find((line) => line.startsWith("data: ")); + expect(line, text).toBeDefined(); + return JSON.parse(line!.slice(6)).result.tools; +} + for (const placement of ["This Mac", "Linux runner"] as const) { test(`owner reviews share committed and uncommitted work on ${placement}`, async ({ page, @@ -93,6 +126,76 @@ for (const placement of ["This Mac", "Linux runner"] as const) { directory, ]); } + await expect + .poll(() => listTools(request, author)) + .toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "repo_fixture", + description: marker, + }), + ]) + ); + const catalog = await callMcpToolViaAPI( + request, + author, + "list_personas", + {} + ); + expect(catalog.result).toMatchObject({ + structuredContent: { + personas: expect.arrayContaining([ + expect.objectContaining({ slug: "ignored-review" }), + ]), + }, + }); + const pickerCatalog = await request.get( + "/api/v1/personas?agentId=" + author, + { + headers: authHeaders(), + } + ); + expect(pickerCatalog.ok(), await pickerCatalog.text()).toBe(true); + expect(await pickerCatalog.json()).toMatchObject({ + codeowners: true, + personas: expect.arrayContaining([ + expect.objectContaining({ slug: "ignored-review" }), + ]), + }); + if (!remote) { + const desktopViewport = page.viewportSize()!; + for (const [label, width] of [ + ["desktop", desktopViewport.width], + ["mobile", 390], + ] as const) { + await page.setViewportSize({ width, height: desktopViewport.height }); + await page.goto(`/agents/${author}/changes`, { + waitUntil: "domcontentloaded", + }); + await page + .getByTestId("changes-toolbar") + .getByTestId("launch-reviewer-button") + .click({ timeout: 15_000 }); + const dialog = page + .getByRole("dialog") + .filter({ has: page.getByTestId("launch-reviewer-codeowners") }); + await expect( + dialog.getByText("Ignored Review", { exact: true }) + ).toBeVisible(); + await expect( + dialog.getByTestId("launch-reviewer-codeowners") + ).toBeEnabled(); + const path = testInfo.outputPath(`persona-picker-${label}.png`); + await page.screenshot({ path }); + await testInfo.attach(`persona picker ${label}`, { + path, + contentType: "image/png", + }); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + } + await page.setViewportSize(desktopViewport); + } // Leave both views mounted. Mutate outside the agent so ACP turn events // and a navigation-triggered refetch cannot account for the update. const files = await page.context().newPage(); @@ -221,6 +324,33 @@ for (const placement of ["This Mac", "Linux runner"] as const) { path: screenshot, contentType: "image/png", }); + const nested = await callMcpToolViaAPI( + request, + reviewer, + "launch_agent", + { + persona: "ignored-review", + name: "Nested checkout reviewer", + type: "claude", + prompt: "Review the same checkout.", + } + ); + const nestedId = ( + nested.result as { structuredContent: { agentId: string } } + ).structuredContent.agentId; + agents.push(nestedId); + await page.goto("/agents/" + nestedId, { waitUntil: "domcontentloaded" }); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + expect(await listTools(request, nestedId)).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "repo_fixture", + description: marker, + }), + ]) + ); + await deleteAgentViaAPI(request, nestedId); + agents.pop(); await deleteAgentViaAPI(request, reviewer); agents.pop(); await page.goto("/agents/" + author, { waitUntil: "domcontentloaded" }); @@ -263,3 +393,56 @@ for (const placement of ["This Mac", "Linux runner"] as const) { } }); } + +test("identical runner paths yield separate tool catalogs", async ({ + page, + request, +}) => { + const agents: string[] = []; + try { + expect(state.runners.alpha.workspaceDir).toBe( + state.runners.beta.workspaceDir + ); + for (const name of ["alpha", "beta"] as const) { + const runner = + (await runnerRow(request, name))?.id ?? + (await enrollViaUi(page, request, name)); + const directory = state.runners[name].workspaceDir; + const writeManifest = (description: string) => { + const json = JSON.stringify({ + tools: [{ name: "same_path", description, command: ["true"] }], + }); + guest( + name, + `mkdir -p "${directory}/.dispatch" && printf '%s' '${json}' > "${directory}/.dispatch/tools.json"` + ); + }; + writeManifest(name); + const res = await request.post("/api/v1/agents", { + headers: authHeaders(), + data: { + name: `Catalog ${name}`, + type: "claude", + useWorktree: false, + cwd: `runner://${runner}/${state.workspace}`, + initialPrompt: "ready", + }, + }); + expect(res.ok(), await res.text()).toBe(true); + const id = (await res.json()).agent.id as string; + agents.push(id); + const listed = () => listTools(request, id); + const matching = (description: string) => + expect.arrayContaining([ + expect.objectContaining({ name: "repo_same_path", description }), + ]); + await expect.poll(listed).toEqual(matching(name)); + writeManifest(`${name} edited`); + await expect.poll(listed).toEqual(matching(`${name} edited`)); + guest(name, `rm "${directory}/.dispatch/tools.json"`); + await expect.poll(listed).not.toEqual(matching(`${name} edited`)); + } + } finally { + for (const id of agents) await deleteAgentViaAPI(request, id); + } +}); diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index 419d63c83..dc50211d3 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -469,3 +469,32 @@ the acknowledgement was lost, repeat the whole request with the same name and bytes. Delivery replaces the named file atomically. Collection is read-only and retries re-read the current file. Commit each successful collection to service-owned storage before publishing a reference to it. + +### Checkout metadata and commands + +With both `checkoutInspection: true` and `checkoutMetadata: true`, the v1 +`inspectCheckout` request supports two additional queries: + +- `{kind: "roots"}` returns the effective checkout root and the common + repository root. A non-Git directory has a null repository root. Both + paths are meaningful only on the runner. +- `{kind: "listFiles", path}` lists immediate regular filenames in the + checkout-relative directory, including ignored files. An absent directory + returns an empty list. The runner bounds enumeration and rejects traversal. + Read the selected filenames with the existing bounded `readFile` query. + +Share a checkout using the existing session handle. Moves update the +effective binding. A host should reacquire metadata for each discovery +instead of treating equal paths as equal checkouts across machines. Older +v1 peers still accept the original inspection queries. + +With `checkoutCommands: true`, the host may send `runCheckout` with the +bound session and workspace handles, the previously observed +`expectedRoot`, and a bounded `argv` array. The runner uses the bound checkout +and rejects a root mismatch. It executes the argument vector as the workload +user with a timeout and bounded output. A successful protocol result contains +a JSON string with `exitCode`, `stdout` and `stderr`, including ordinary +nonzero process exits. Host services decide who can invoke commands and +interpret any repository-specific formats. Dispatch requires a full-access +session's scoped MCP token for manifest commands on enrolled runners. +The original workspace-approved `repo` operation remains available. diff --git a/packages/runner-protocol/src/checkout.ts b/packages/runner-protocol/src/checkout.ts index 0f43eec36..f5081408f 100644 --- a/packages/runner-protocol/src/checkout.ts +++ b/packages/runner-protocol/src/checkout.ts @@ -4,7 +4,8 @@ import { isRecord } from "./validation.js"; /** Operations are relative to the bound session checkout. Paths never name host files. */ export type CheckoutQuery = | { kind: "changes"; baseBranch: string | null } - | { kind: "readFile"; path: string }; + | { kind: "readFile" | "listFiles"; path: string } + | { kind: "roots" }; export type CheckoutReply = | { @@ -14,7 +15,44 @@ export type CheckoutReply = stateId: string; files: string[]; } - | { kind: "readFile"; content: string | null }; + | { kind: "readFile"; content: string | null } + | { kind: "listFiles"; names: string[] } + | { kind: "roots"; checkoutRoot: string; repositoryRoot: string | null }; + +export type CheckoutCommandResult = { + exitCode: number; + stdout: string; + stderr: string; +}; + +export function isCheckoutCommandResult( + value: unknown +): value is CheckoutCommandResult { + return ( + isRecord(value) && + typeof value.exitCode === "number" && + Number.isInteger(value.exitCode) && + value.exitCode >= 0 && + value.exitCode < 256 && + typeof value.stdout === "string" && + typeof value.stderr === "string" + ); +} + +export function isCheckoutArgv(value: unknown): value is string[] { + return ( + Array.isArray(value) && + value.length > 0 && + value.length <= 256 && + typeof value[0] === "string" && + value[0].length > 0 && + value.every( + (arg) => + typeof arg === "string" && arg.length <= 4096 && !arg.includes("\0") + ) && + new TextEncoder().encode(JSON.stringify(value)).length <= 16 * 1024 + ); +} /** A full branch name, never a revision expression, option, or raw ref. */ export function validBranch(value: unknown): value is string { @@ -45,7 +83,9 @@ function relativePath(value: unknown): value is string { export function isCheckoutQuery(value: unknown): value is CheckoutQuery { if (!isRecord(value)) return false; - if (value.kind === "readFile") return relativePath(value.path); + if (value.kind === "roots") return true; + if (value.kind === "readFile" || value.kind === "listFiles") + return relativePath(value.path); return ( value.kind === "changes" && (value.baseBranch === null || validBranch(value.baseBranch)) @@ -58,7 +98,22 @@ export function isCheckoutReply( ): value is CheckoutReply { if (!isRecord(value) || value.kind !== query.kind) return false; if (value.kind === "readFile") - return value.content === null || typeof value.content === "string"; + return ( + value.content === null || + (typeof value.content === "string" && + new TextEncoder().encode(value.content).length <= 256 * 1024) + ); + if (value.kind === "roots") + return ( + isCheckoutPath(value.checkoutRoot) && + (value.repositoryRoot === null || isCheckoutPath(value.repositoryRoot)) + ); + if (value.kind === "listFiles") + return ( + Array.isArray(value.names) && + value.names.length <= 1024 && + value.names.every((name) => relativePath(name) && !/[\\/]/.test(name)) + ); return ( typeof value.baseRef === "string" && value.baseRef.length > 0 && diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index ff5816f31..f3622a5a3 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -4,6 +4,7 @@ import { } from "./session-files.js"; import { isCheckoutView, type CheckoutView } from "./checkout-view.js"; import { + isCheckoutArgv, isCheckoutQuery, isCheckoutRelease, type CheckoutRelease, @@ -77,6 +78,12 @@ export type SessionOperation = operation: { kind: "describe" } | { kind: "select"; path: string | null }; } | { agentId: string; kind: "checkoutRelease"; operation: CheckoutRelease } + | { + agentId: string; + kind: "runCheckout"; + expectedRoot: string; + argv: string[]; + } | { agentId: string; kind: "repo" }; export type RunnerOperation = @@ -101,6 +108,8 @@ export type ReadyFrame = { pullRequestWatch?: true; pullRequestEvidence?: true; checkoutInspection?: true; + checkoutMetadata?: true; + checkoutCommands?: true; checkoutViews?: true; sharedWorktree?: true; workspacePreparation?: true; @@ -130,6 +139,8 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { version: RUNNER_WIRE_VERSION, workspaces: frame.workspaces, ...(frame.checkoutViews === true && { checkoutViews: true }), + ...(frame.checkoutCommands === true && { checkoutCommands: true }), + ...(frame.checkoutMetadata === true && { checkoutMetadata: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), ...(frame.sessionFiles === true && { sessionFiles: true }), @@ -329,6 +340,8 @@ function isCommand(value: unknown): value is Command { return true; case "viewCheckout": return isCheckoutView(value.query); + case "runCheckout": + return isCheckoutPath(value.expectedRoot) && isCheckoutArgv(value.argv); case "inspectCheckout": return isCheckoutQuery(value.query); case "attach": From 4d413a057514cc24f9d790c972d0f802afb7ba69 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 17:07:34 -0700 Subject: [PATCH 141/642] Resolve default-branch persona files on the owning runner --- apps/server/src/agents/checkout-inspection.ts | 46 +-- .../server/src/agents/default-branch-files.ts | 303 ++++++++++++++++ apps/server/src/agents/manager.ts | 22 -- apps/server/src/agents/remote/runner.ts | 56 ++- apps/server/src/agents/remote/service.ts | 12 +- apps/server/src/main.ts | 5 +- apps/server/src/personas/catalog.ts | 337 +++--------------- apps/server/src/routes/mcp.ts | 25 +- apps/server/src/server/mcp-checkout.ts | 18 +- .../server/src/server/mcp-persona-handlers.ts | 84 +++-- apps/server/test/checkout-inspection.test.ts | 41 +-- apps/server/test/mcp-handlers.test.ts | 10 + .../test/mcp-persona-codeowners.test.ts | 120 ++++--- apps/server/test/persona-catalog.test.ts | 132 ++++++- .../test/remote-runner-enrollment.test.ts | 38 ++ .../test/runner-protocol-consumer.test.ts | 42 ++- e2e/remote-runner/owner-review.spec.ts | 155 +++++++- packages/runner-protocol/README.md | 20 +- packages/runner-protocol/src/checkout.ts | 107 ++++-- packages/runner-protocol/src/execution.ts | 13 +- 20 files changed, 970 insertions(+), 616 deletions(-) create mode 100644 apps/server/src/agents/default-branch-files.ts diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index 08235c99c..29fe17ab2 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -1,3 +1,4 @@ +import { DefaultBranchFiles } from "./default-branch-files.js"; import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { @@ -12,7 +13,6 @@ import { lstat, open, readdir, readlink, realpath } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { - isCheckoutArgv, isCheckoutQuery, type CheckoutQuery, type CheckoutReply, @@ -48,6 +48,7 @@ const run: CommandRunner = async (command, args, options = {}) => { LC_ALL: "C", GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1", + ...options.env, }, maxBuffer: MAX_REPLY_BYTES, timeout: options.timeoutMs ?? 5_000, @@ -81,10 +82,13 @@ const run: CommandRunner = async (command, args, options = {}) => { }; }; +export const defaultBranchFiles = new DefaultBranchFiles(run); + function parseQuery(input: unknown): CheckoutQuery { if ( isCheckoutQuery(input) && - Object.keys(input).length === (input.kind === "roots" ? 1 : 2) + Object.keys(input).length === + (input.kind === "roots" ? 1 : input.kind === "defaultBranchFiles" ? 3 : 2) ) return input; throw new Error("Invalid checkout inspection query"); @@ -485,6 +489,15 @@ export async function inspectCheckout( query: CheckoutQuery ): Promise { const validated = parseQuery(query); + if (validated.kind === "defaultBranchFiles") { + const reply = await defaultBranchFiles.get( + cwd, + validated.directories, + validated.waitForRefresh + ); + encodeReply(reply); + return reply; + } // Preserve whitespace in the root, removing only Git's terminating newline. const probe = await run("git", ["rev-parse", "--show-toplevel"], { cwd, @@ -553,10 +566,7 @@ export async function inspectCheckout( return reply; } -export async function runCheckoutInspectionCli( - cwd: string, - expectedRoot?: string -): Promise { +export async function runCheckoutInspectionCli(cwd: string): Promise { try { const chunks: Buffer[] = []; let size = 0; @@ -568,30 +578,6 @@ export async function runCheckoutInspectionCli( chunks.push(bytes); } const input: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); - if (expectedRoot !== undefined) { - const roots = await inspectCheckout(cwd, { kind: "roots" }); - if (roots.kind !== "roots" || roots.checkoutRoot !== expectedRoot) - throw new Error("The session checkout changed."); - if (!isCheckoutArgv(input)) throw new Error("Invalid command arguments."); - const output = await execFileAsync(input[0], input.slice(1), { - cwd: roots.checkoutRoot, - timeout: 15_000, - killSignal: "SIGKILL", - maxBuffer: 256 * 1024, - }).then( - (result) => ({ ...result, exitCode: 0 }), - (error) => { - if (typeof error.code !== "number") throw error; - return { - stdout: error.stdout, - stderr: error.stderr, - exitCode: error.code, - }; - } - ); - process.stdout.write(JSON.stringify(output)); - return; - } const query = parseQuery(input); const reply = await inspectCheckout(cwd, query); await new Promise((resolve, reject) => { diff --git a/apps/server/src/agents/default-branch-files.ts b/apps/server/src/agents/default-branch-files.ts new file mode 100644 index 000000000..f6037ec91 --- /dev/null +++ b/apps/server/src/agents/default-branch-files.ts @@ -0,0 +1,303 @@ +import { createHash, randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; +import type { DefaultBranchFilesReply } from "@dispatch/runner-protocol"; +import { + DEFAULT_BRANCH_FILE_LIMIT, + DEFAULT_BRANCH_REPLY_BYTES, +} from "@dispatch/runner-protocol"; + +export const DEFAULT_BRANCH_REFRESH_MS = 5 * 60_000; +const MAX_BACKOFF_MS = 60 * 60_000; +const LOCK_TTL_MS = 5 * 60_000; +const cacheSchema = z.object({ + version: z.literal(1), + nextRefreshAt: z.number(), + failures: z.number(), + updatedAt: z.number().nullable(), + commit: z + .string() + .regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/) + .nullable(), + warning: z.string().optional(), +}); +type Cache = z.infer; +/** One default-branch snapshot per Git common directory + origin identity, shared by all worktrees. + * Fetch only remote HEAD into a private ref: no checkout, branch, index or + * FETCH_HEAD changes. No GitHub API, remote polling timer, or force-refresh bypass. + */ +export class DefaultBranchFiles { + private pending = new Map>(); + private unavailable = new Set(); + constructor( + private run: CommandRunner = runCommand, + private now = Date.now + ) {} + + private async git(cwd: string, args: string[]) { + return ( + await this.run("git", ["-C", cwd, ...args], { + timeoutMs: 20_000, + trimOutput: false, + env: { GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" }, + }) + ).stdout; + } + + private async read(file: string): Promise { + try { + if ((await stat(file)).size > 32 * 1024 * 1024) return null; + return cacheSchema.parse(JSON.parse(await readFile(file, "utf8"))); + } catch { + return null; + } + } + + private async write(file: string, cache: Cache) { + const temporary = `${file}.${randomUUID()}.tmp`; + try { + await writeFile(temporary, JSON.stringify(cache), { mode: 0o600 }); + await rename(temporary, file); + } finally { + await rm(temporary, { force: true }); + } + } + + private async readFiles(cwd: string, commit: string, directories: string[]) { + const files: DefaultBranchFilesReply["files"] = []; + let truncated = false; + let bytes = 1024; // Envelope and metadata. + for (const directory of directories) { + // A tree lookup treats the supplied directory as a literal path. + const tree = await this.git(cwd, [ + "rev-parse", + "--verify", + `${commit}:${directory}`, + ]).catch(() => null); + const object = tree?.trim(); + if ( + !object || + !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(object) || + (await this.git(cwd, ["cat-file", "-t", object])).trim() !== "tree" + ) + continue; + const entries = await this.git(cwd, ["ls-tree", "-z", "-l", object]); + for (const entry of entries.split("\0")) { + const tab = entry.indexOf("\t"); + if (tab === -1) continue; + const name = entry.slice(tab + 1); + const [mode, kind, blob, size] = entry + .slice(0, tab) + .trim() + .split(/\s+/); + if ( + kind !== "blob" || + !["100644", "100755"].includes(mode) || + !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(blob) || + !name || + name.includes("\\") || + name.toLowerCase() === ".git" + ) + continue; + const filePath = `${directory}/${name}`; + if (filePath.length > 4096) continue; + if (Number(size) > 256 * 1024) { + truncated = true; + continue; + } + if (files.length >= DEFAULT_BRANCH_FILE_LIMIT) + return { files, truncated: true }; + const content = await this.git(cwd, ["cat-file", "blob", blob]); + if (Buffer.byteLength(content) > 256 * 1024) { + truncated = true; + continue; + } + const file = { path: filePath, content }; + bytes += Buffer.byteLength(JSON.stringify(file)) + 1; + if (bytes > DEFAULT_BRANCH_REPLY_BYTES) + return { files, truncated: true }; + files.push(file); + } + } + return { files, truncated }; + } + + private async refresh( + cwd: string, + file: string, + ref: string, + legacyFile: string + ) { + const lock = `${file}.lock`; + await mkdir(path.dirname(file), { recursive: true, mode: 0o700 }); + try { + await mkdir(lock); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + // Crash recovery. Normal refreshes have a bounded network timeout. + if (this.now() - (await stat(lock)).mtimeMs > LOCK_TTL_MS) + await rm(lock, { recursive: true, force: true }); + return; + } + try { + let cached = (await this.read(file)) ?? (await this.read(legacyFile)); + if (cached && cached.nextRefreshAt > this.now()) return; + if (!cached) { + cached = { + version: 1, + commit: null, + updatedAt: null, + failures: 0, + nextRefreshAt: 0, + }; + } + // Persist the attempt BEFORE contacting the remote, including across process restarts. + cached.nextRefreshAt = + this.now() + + Math.min( + MAX_BACKOFF_MS, + DEFAULT_BRANCH_REFRESH_MS * 2 ** Math.min(cached.failures, 4) + ); + await this.write(file, cached); + try { + await this.git(cwd, [ + "-c", + "credential.interactive=false", + "fetch", + "--no-tags", + "--no-write-fetch-head", + "--no-recurse-submodules", + "origin", + `+HEAD:${ref}`, + ]); + const commit = ( + await this.git(cwd, ["rev-parse", "--verify", `${ref}^{commit}`]) + ).trim(); + await this.write(file, { + version: 1, + commit, + updatedAt: this.now(), + failures: 0, + nextRefreshAt: this.now() + DEFAULT_BRANCH_REFRESH_MS, + }); + } catch { + cached.failures += 1; + cached.nextRefreshAt = + this.now() + + Math.min( + MAX_BACKOFF_MS, + DEFAULT_BRANCH_REFRESH_MS * 2 ** Math.min(cached.failures, 4) + ); + cached.warning = + "Could not refresh the default branch from origin. Using cached files; retry is delayed automatically."; + await this.write(file, cached); + } + } finally { + await rm(lock, { recursive: true, force: true }); + } + } + + async get( + cwd: string, + directories: string[], + waitForRefresh: boolean + ): Promise { + const common = await this.git(cwd, [ + "rev-parse", + "--path-format=absolute", + "--git-common-dir", + ]) + .then((s) => s.trim()) + .catch(() => null); + const remote = common + ? await this.git(cwd, ["remote", "get-url", "origin"]) + .then((s) => s.trim()) + .catch(() => null) + : null; + if (!common || !remote) + return { + kind: "defaultBranchFiles", + hasOrigin: false, + files: [], + warnings: [], + refreshing: false, + updatedAt: null, + truncated: false, + }; + const identity = createHash("sha256").update(remote).digest("hex"); + const file = path.join( + common, + "dispatch", + "default-branch", + `${identity}.json` + ); + // Reuse the fetched commit and cooldown from the old format, without + // depending on its parsed contents. Keep the legacy ref as the GC root. + const legacyFile = path.join( + common, + "dispatch", + "persona-catalog", + `${identity}.json` + ); + let cached = (await this.read(file)) ?? (await this.read(legacyFile)); + if ( + (!cached || cached.nextRefreshAt <= this.now()) && + !this.pending.has(file) + ) { + const work = this.refresh( + cwd, + file, + `refs/dispatch/persona-catalog/${identity}`, + legacyFile + ) + .then(() => { + this.unavailable.delete(file); + }) + .catch(() => { + this.unavailable.add(file); + }) + .finally(() => this.pending.delete(file)); + this.pending.set(file, work); + } + if (waitForRefresh) { + await this.pending.get(file); + cached = (await this.read(file)) ?? (await this.read(legacyFile)); + // Another server may own the cold refresh. A launch can wait briefly for + // that publication, while UI requests always remain non-blocking. + for (let attempt = 0; !cached?.updatedAt && attempt < 250; attempt++) { + const held = await stat(`${file}.lock`) + .then((s) => this.now() - s.mtimeMs < LOCK_TTL_MS) + .catch(() => false); + if (!held) break; + await new Promise((resolve) => setTimeout(resolve, 100)); + cached = (await this.read(file)) ?? (await this.read(legacyFile)); + } + } + const locked = await stat(`${file}.lock`) + .then((s) => this.now() - s.mtimeMs < LOCK_TTL_MS) + .catch(() => false); + const refreshing = this.pending.has(file) || locked; + return { + kind: "defaultBranchFiles", + hasOrigin: true, + ...(cached?.commit + ? await this.readFiles(cwd, cached.commit, directories).catch(() => ({ + files: [], + truncated: true, + })) + : { files: [], truncated: false }), + warnings: [ + ...(this.unavailable.has(file) + ? [ + "Could not store default branch metadata. Check repository cache permissions.", + ] + : []), + ...(cached?.warning ? [cached.warning] : []), + ], + refreshing, + updatedAt: cached?.updatedAt ?? null, + }; + } +} diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 52b33d792..57fe4865d 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,4 +1,3 @@ -import { isCheckoutCommandResult } from "@dispatch/runner-protocol"; import { isPromptImageMimeType } from "./acp/prompt-source.js"; import { readSessionFile } from "../files/session-file.js"; import { readAgentView } from "./checkout-runner.js"; @@ -3006,27 +3005,6 @@ export class AgentManager { return this.remote?.permitsAgentMcp(placement) ?? false; } - async runCheckoutCommand( - agent: AgentRecord, - expectedRoot: string, - argv: string[] - ) { - const placement = remotePlacement(agent.cwd); - if (!placement || !this.remote || !agent.fullAccess) - throw new AgentError("Checkout command is unavailable.", 403); - const { value } = await this.remote.requestSession(placement, { - kind: "runCheckout", - agentId: agent.id, - expectedRoot, - argv, - }); - const output: unknown = - typeof value === "string" ? JSON.parse(value) : null; - if (!isCheckoutCommandResult(output)) - throw new AgentError("Invalid runner command response.", 502); - return output; - } - remoteRepoOperation(agent: AgentRecord): (() => Promise) | undefined { const placement = remotePlacement(agent.cwd); if (!placement || !this.remote?.repoToolFor(placement)) return undefined; diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 58d47a74f..5373c41b9 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -581,11 +581,34 @@ export async function runRemoteRunner(filename: string) { } ); child.child.stdin?.on("error", () => {}); // execFile reports early child failure. + // The worker can publish a cached reply while it finishes a + // bounded background refresh under the workload identity. + let sent = false; + if ( + command.kind === "inspectCheckout" && + command.query.kind === "defaultBranchFiles" && + !command.query.waitForRefresh + ) { + const chunks: Buffer[] = []; + let bytes = 0; + child.child.stdout?.on("data", (data: string | Buffer) => { + if (sent) return; + const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data); + bytes += chunk.length; + if (bytes > 4 * 1024 * 1024) return; + chunks.push(chunk); + if (chunk[chunk.length - 1] === 10) { + sent = true; + result(Buffer.concat(chunks).toString("utf8").trimEnd()); + } + }); + } child.child.stdin?.end(JSON.stringify(command.query)); try { const { stdout } = await child; - result(stdout.trimEnd()); + if (!sent) result(stdout.trimEnd()); } catch (error) { + if (sent) break; // execFile's default message includes the command and machine-local paths. const detail = (error as { stderr?: string }).stderr ?.trim() @@ -644,35 +667,6 @@ export async function runRemoteRunner(filename: string) { case "log": result(await supervisor.log(agentId, workspace)); break; - case "runCheckout": { - const cwd = await supervisor.checkoutDirectory( - agentId, - workspace, - target?.cwd - ); - const child = execute( - setpriv, - [ - ...childArgs, - ...selfCommand("runner-inspect-checkout"), - cwd, - "--run-command", - command.expectedRoot, - ], - { env, timeout: 20_000, maxBuffer: 1024 * 1024 } - ); - child.child.stdin?.on("error", () => {}); - child.child.stdin?.end(JSON.stringify(command.argv)); - try { - const { stdout } = await child; - result(stdout); - } catch { - throw new Error( - "The runner could not execute the checkout command." - ); - } - break; - } case "repo": { if (!(await supervisor.isBound(agentId, workspace))) throw new Error("Agent is not bound to this workspace"); @@ -755,7 +749,7 @@ export async function runRemoteRunner(filename: string) { pullRequestEvidence: true, checkoutInspection: true, checkoutMetadata: true, - checkoutCommands: true, + defaultBranchFiles: true, workspacePreparation: true, sessionCheckout: true, checkoutRelease: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 3f6fe37c9..2d25a8849 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -162,7 +162,7 @@ type Peer = { pullRequestEvidence: boolean; checkoutInspection: boolean; checkoutMetadata: boolean; - checkoutCommands: boolean; + defaultBranchFiles: boolean; sessionCheckout: boolean; checkoutRelease: boolean; sessionFiles: boolean; @@ -697,7 +697,7 @@ export class RemoteRunnerService { sessionCheckout: ready.sessionCheckout === true, checkoutRelease: ready.checkoutRelease === true, sessionFiles: ready.sessionFiles === true, - checkoutCommands: ready.checkoutCommands === true, + defaultBranchFiles: ready.defaultBranchFiles === true, checkoutMetadata: ready.checkoutMetadata === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, @@ -1575,9 +1575,13 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to inspect and release a session checkout." ); - if (command.kind === "runCheckout" && !peer.checkoutCommands) + if ( + command.kind === "inspectCheckout" && + command.query.kind === "defaultBranchFiles" && + !peer.defaultBranchFiles + ) throw new RunnerCapabilityUnavailable( - "Update the runner to run checkout commands." + "Update the runner to read default-branch files." ); if ( command.kind === "inspectCheckout" && diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 9a9826615..7816278fc 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -76,10 +76,7 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "runner-inspect-checkout") { const { runCheckoutInspectionCli } = await import("./agents/checkout-inspection.js"); - await runCheckoutInspectionCli( - process.argv[3]!, - process.argv[4] === "--run-command" ? process.argv[5] : undefined - ); + await runCheckoutInspectionCli(process.argv[3]!); } else if (process.argv[2] === "remote-runner") { const { runRemoteRunner } = await import("./agents/remote/runner.js"); await runRemoteRunner(process.argv[3]!); diff --git a/apps/server/src/personas/catalog.ts b/apps/server/src/personas/catalog.ts index 7bd2e53b0..6eb08b6a2 100644 --- a/apps/server/src/personas/catalog.ts +++ b/apps/server/src/personas/catalog.ts @@ -1,37 +1,19 @@ -import { createHash, randomUUID } from "node:crypto"; -import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; -import path from "node:path"; -import { z } from "zod"; -import { runCommand, type CommandRunner } from "../shared/lib/run-command.js"; +import type { DefaultBranchFilesReply } from "@dispatch/runner-protocol"; import { + DefaultBranchFiles, + DEFAULT_BRANCH_REFRESH_MS, +} from "../agents/default-branch-files.js"; +import { resolveRepoRoot } from "../shared/git/git-context.js"; +import type { CommandRunner } from "../shared/lib/run-command.js"; +import { + loadCheckoutPersonas, loadPersonas, - toPersonaDefinition, type PersonaDefinition, } from "./loader.js"; import { PERSONA_DIRS } from "./paths.js"; -export const PERSONA_REFRESH_MS = 5 * 60_000; -const MAX_BACKOFF_MS = 60 * 60_000; -const LOCK_TTL_MS = 5 * 60_000; -const cacheSchema = z.object({ - version: z.literal(1), - nextRefreshAt: z.number(), - failures: z.number(), - updatedAt: z.number().nullable(), - commit: z.string().nullable(), - warning: z.string().optional(), - warnings: z.array(z.string()), - personas: z.array( - z.object({ - slug: z.string(), - name: z.string(), - description: z.string(), - body: z.string(), - type: z.enum(["task", "review"]).optional(), - }) - ), -}); -type Cache = z.infer; +export const PERSONA_REFRESH_MS = DEFAULT_BRANCH_REFRESH_MS; + export type PersonaCatalog = { personas: PersonaDefinition[]; warnings: string[]; @@ -39,272 +21,51 @@ export type PersonaCatalog = { updatedAt: number | null; }; -/** One catalog per Git common directory + origin identity, shared by all worktrees. - * Fetch only remote HEAD into a private ref: no checkout, branch, index or - * FETCH_HEAD changes. No GitHub API, remote polling timer, or force-refresh bypass. - */ -export class PersonaCatalogCache { - private pending = new Map>(); - private unavailable = new Set(); - constructor( - private run: CommandRunner = runCommand, - private now = Date.now - ) {} - - private async git(cwd: string, args: string[]) { - return ( - await this.run("git", ["-C", cwd, ...args], { - timeoutMs: 20_000, - trimOutput: false, - env: { GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" }, - }) - ).stdout; - } +export async function parseDefaultBranchPersonas( + reply: DefaultBranchFilesReply +): Promise { + const warnings = [...reply.warnings]; + if (reply.truncated) + warnings.push("The default-branch file listing was incomplete."); + const files = new Map( + reply.files.map(({ path, content }) => [path, content]) + ); + const personas = await loadCheckoutPersonas( + async (directory) => + reply.files + .filter( + ({ path }) => path.slice(0, path.lastIndexOf("/")) === directory + ) + .map(({ path }) => path.slice(directory.length + 1)), + async (path) => files.get(path) ?? null, + warnings + ); + return { + personas, + warnings, + refreshing: reply.refreshing, + updatedAt: reply.updatedAt, + }; +} - private async read(file: string): Promise { - try { - if ((await stat(file)).size > 32 * 1024 * 1024) return null; - return cacheSchema.parse(JSON.parse(await readFile(file, "utf8"))); - } catch { - return null; - } - } +/** Catalog for launch configuration before a session exists. */ +export class PersonaCatalogCache { + private files: DefaultBranchFiles; - private async write(file: string, cache: Cache) { - const temporary = `${file}.${randomUUID()}.tmp`; - try { - await writeFile(temporary, JSON.stringify(cache), { mode: 0o600 }); - await rename(temporary, file); - } finally { - await rm(temporary, { force: true }); - } + constructor(run?: CommandRunner, now?: () => number) { + this.files = new DefaultBranchFiles(run, now); } - private async readRef(cwd: string, ref: string) { - const commit = ( - await this.git(cwd, ["rev-parse", "--verify", `${ref}^{commit}`]) - ).trim(); - const entries = ( - await this.git(cwd, [ - "ls-tree", - "-r", - "-z", - "-l", - commit, - "--", - ...PERSONA_DIRS, - ]) - ) - .split("\0") - .filter(Boolean); - const personas: PersonaDefinition[] = []; + async get(cwd: string, waitForRefresh = false): Promise { + const reply = await this.files.get(cwd, [...PERSONA_DIRS], waitForRefresh); + if (reply.hasOrigin) return parseDefaultBranchPersonas(reply); const warnings: string[] = []; - const seen = new Set(); - let bytes = 0; - for (const directory of PERSONA_DIRS) { - for (const entry of entries) { - const [metadata, name] = entry.split("\t"); - if ( - !name?.startsWith(`${directory}/`) || - !name.endsWith(".md") || - name.slice(directory.length + 1).includes("/") - ) - continue; - const slug = path.basename(name, ".md"); - if (seen.has(slug)) continue; - seen.add(slug); - const [mode, kind, object, size] = metadata.trim().split(/\s+/); - bytes += Number(size) || 0; - if (seen.size > 100 || bytes > 4 * 1024 * 1024) { - warnings.push("Persona catalog exceeds the 100-file or 4 MiB limit."); - return { personas, warnings, commit }; - } - if ( - kind !== "blob" || - !["100644", "100755"].includes(mode) || - Number(size) > 256 * 1024 - ) { - warnings.push( - `Could not load persona ${name}: unsupported file or larger than 256 KiB.` - ); - continue; - } - try { - personas.push( - toPersonaDefinition( - slug, - await this.git(cwd, ["cat-file", "blob", object]) - ) - ); - } catch { - warnings.push( - `Could not load persona ${name}: invalid persona definition.` - ); - } - } - } - return { personas, warnings, commit }; - } - - private async refresh(cwd: string, file: string, ref: string) { - const lock = `${file}.lock`; - await mkdir(path.dirname(file), { recursive: true, mode: 0o700 }); - try { - await mkdir(lock); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; - // Crash recovery. Normal refreshes have a bounded network timeout. - if (this.now() - (await stat(lock)).mtimeMs > LOCK_TTL_MS) - await rm(lock, { recursive: true, force: true }); - return; - } - try { - let cached = await this.read(file); - if (cached && cached.nextRefreshAt > this.now()) return; - if (!cached) { - cached = { - version: 1, - personas: [], - warnings: [], - commit: null, - updatedAt: null, - failures: 0, - nextRefreshAt: 0, - }; - } - // Persist the attempt BEFORE contacting the remote, including across process restarts. - cached.nextRefreshAt = - this.now() + - Math.min( - MAX_BACKOFF_MS, - PERSONA_REFRESH_MS * 2 ** Math.min(cached.failures, 4) - ); - await this.write(file, cached); - try { - await this.git(cwd, [ - "-c", - "credential.interactive=false", - "fetch", - "--no-tags", - "--no-write-fetch-head", - "--no-recurse-submodules", - "origin", - `+HEAD:${ref}`, - ]); - const result = await this.readRef(cwd, ref); - await this.write(file, { - version: 1, - ...result, - updatedAt: this.now(), - failures: 0, - nextRefreshAt: this.now() + PERSONA_REFRESH_MS, - }); - } catch { - cached.failures += 1; - cached.nextRefreshAt = - this.now() + - Math.min( - MAX_BACKOFF_MS, - PERSONA_REFRESH_MS * 2 ** Math.min(cached.failures, 4) - ); - cached.warning = - "Could not refresh personas from origin. Using cached definitions; retry is delayed automatically."; - await this.write(file, cached); - } - } finally { - await rm(lock, { recursive: true, force: true }); - } - } - - async get( - cwd: string, - waitForRefresh = false, - includeFallback = true - ): Promise { - const common = await this.git(cwd, [ - "rev-parse", - "--path-format=absolute", - "--git-common-dir", - ]) - .then((s) => s.trim()) - .catch(() => null); - const remote = common - ? await this.git(cwd, ["remote", "get-url", "origin"]) - .then((s) => s.trim()) - .catch(() => null) - : null; - if (!common || !remote) { - const warnings: string[] = []; - return { - personas: includeFallback - ? await loadPersonas( - common && path.basename(common) === ".git" - ? path.dirname(common) - : cwd, - warnings - ) - : [], - warnings, - refreshing: false, - updatedAt: null, - }; - } - const identity = createHash("sha256").update(remote).digest("hex"); - const file = path.join( - common, - "dispatch", - "persona-catalog", - `${identity}.json` - ); - let cached = await this.read(file); - if ( - (!cached || cached.nextRefreshAt <= this.now()) && - !this.pending.has(file) - ) { - const work = this.refresh( - cwd, - file, - `refs/dispatch/persona-catalog/${identity}` - ) - .then(() => { - this.unavailable.delete(file); - }) - .catch(() => { - this.unavailable.add(file); - }) - .finally(() => this.pending.delete(file)); - this.pending.set(file, work); - } - if (waitForRefresh) { - await this.pending.get(file); - cached = await this.read(file); - // Another server may own the cold refresh. A launch can wait briefly for - // that publication, while UI requests always remain non-blocking. - for (let attempt = 0; !cached?.updatedAt && attempt < 250; attempt++) { - const held = await stat(`${file}.lock`) - .then((s) => this.now() - s.mtimeMs < LOCK_TTL_MS) - .catch(() => false); - if (!held) break; - await new Promise((resolve) => setTimeout(resolve, 100)); - cached = await this.read(file); - } - } - const locked = await stat(`${file}.lock`) - .then((s) => this.now() - s.mtimeMs < LOCK_TTL_MS) - .catch(() => false); + const root = await resolveRepoRoot(cwd).catch(() => cwd); return { - personas: cached?.personas ?? [], - warnings: [ - ...(this.unavailable.has(file) - ? [ - "Could not store the persona catalog. Check repository cache permissions.", - ] - : []), - ...(cached?.warnings ?? []), - ...(cached?.warning ? [cached.warning] : []), - ], - refreshing: this.pending.has(file) || locked, - updatedAt: cached?.updatedAt ?? null, + personas: await loadPersonas(root, warnings), + warnings, + refreshing: false, + updatedAt: null, }; } } diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index 1cec70f9d..11f253164 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -62,8 +62,7 @@ function isOwnerReviewRequest(body: unknown): boolean { async function checkoutContext( deps: McpRouteDeps, agent: NonNullable>>, - body: unknown, - authorized: boolean + body: unknown ) { const placement = remotePlacement(agent.cwd); const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; @@ -92,13 +91,7 @@ async function checkoutContext( toolsRoot: placement ? workspaceDir : (worktreeRoot ?? undefined), discoverRepoTools: ownerOnly ? async () => [] - : () => - discoverRepoTools( - deps.agentManager, - agent, - authorized, - roots?.checkoutRoot ?? null - ), + : () => discoverRepoTools(deps.agentManager, agent), }, }; } @@ -267,12 +260,7 @@ export async function registerMcpRoutes( .send({ error: "Token does not match the active job run." }); } - const checkout = await checkoutContext( - deps, - agent, - request.body, - Boolean(bearerToken) - ); + const checkout = await checkoutContext(deps, agent, request.body); const { workspaceDir, repoRoot } = checkout; const jobTools = run @@ -399,12 +387,7 @@ export async function registerMcpRoutes( .send({ error: "Job agents must use the job-scoped MCP route." }); } - const checkout = await checkoutContext( - deps, - agent, - request.body, - Boolean(bearerToken) - ); + const checkout = await checkoutContext(deps, agent, request.body); const { workspaceDir, repoRoot } = checkout; reply.hijack(); diff --git a/apps/server/src/server/mcp-checkout.ts b/apps/server/src/server/mcp-checkout.ts index c19b37c5a..e09aee154 100644 --- a/apps/server/src/server/mcp-checkout.ts +++ b/apps/server/src/server/mcp-checkout.ts @@ -35,9 +35,7 @@ export async function mcpCheckoutRoots( export async function discoverRepoTools( manager: AgentManager, - agent: AgentRecord, - authorized: boolean, - checkoutRoot: string | null + agent: AgentRecord ) { let content: string | null; try { @@ -53,16 +51,10 @@ export async function discoverRepoTools( return parseRepoTools( parseRepoToolFile(content), remote - ? (command) => { - if (!authorized || !agent.fullAccess || !checkoutRoot) - throw new Error( - "Repository commands require a full-access runner session and its scoped MCP token." - ); - return manager.runCheckoutCommand(agent, checkoutRoot, [ - "env", - `DISPATCH_AGENT_ID=${agent.id}`, - ...command, - ]); + ? async () => { + throw new Error( + "Checkout manifest commands are unavailable on enrolled runners." + ); } : undefined ); diff --git a/apps/server/src/server/mcp-persona-handlers.ts b/apps/server/src/server/mcp-persona-handlers.ts index 698b1dbc2..92f071e3b 100644 --- a/apps/server/src/server/mcp-persona-handlers.ts +++ b/apps/server/src/server/mcp-persona-handlers.ts @@ -1,7 +1,6 @@ import { remotePlacement } from "@dispatch/runner-protocol"; import type { Effort } from "@dispatch/shared"; import { validateAgentEffort } from "../shared/agent-effort.js"; -import { resolveLaunchPersona } from "../personas/resolve.js"; import type { Pool } from "pg"; import type { AgentManager, AgentRecord } from "../agents/manager.js"; @@ -32,12 +31,17 @@ import { resolveCodeowners, type OwnerReviewResult, } from "../personas/codeowners.js"; -import { LEGACY_OWNERS_PATH, OWNERS_PATH } from "../personas/paths.js"; +import { + LEGACY_OWNERS_PATH, + OWNERS_PATH, + PERSONA_DIRS, +} from "../personas/paths.js"; import { validateAgentModel } from "../shared/agent-models.js"; import type { PublishUiEvent } from "./mcp-handler-types.js"; -import { personaCatalog } from "../personas/catalog.js"; -import { mcpCheckoutRoots, readAgentCheckoutFile } from "./mcp-checkout.js"; +import { parseDefaultBranchPersonas } from "../personas/catalog.js"; +import { RunnerCapabilityUnavailable } from "../agents/remote/service.js"; +import { readAgentCheckoutFile } from "./mcp-checkout.js"; import { PERSONA_CONTEXT_ARG } from "../agents/acp/persona-context.js"; const CODEX_FULL_ACCESS_ARG = "--dangerously-bypass-approvals-and-sandbox"; @@ -50,6 +54,31 @@ export type CreatePersonaHandlersDeps = { withStreamFlag: (agent: AgentRecord) => AgentRecord & { hasStream: boolean }; }; +async function sessionDefaultBranchPersonas( + manager: AgentManager, + agent: AgentRecord, + waitForRefresh: boolean +) { + try { + const reply = await manager.inspectCheckout(agent, { + kind: "defaultBranchFiles", + directories: [...PERSONA_DIRS], + waitForRefresh, + }); + if (reply.kind !== "defaultBranchFiles") + throw new Error("Runner did not return default-branch files."); + return parseDefaultBranchPersonas(reply); + } catch (error) { + if (!(error instanceof RunnerCapabilityUnavailable)) throw error; + return { + personas: [], + warnings: [error.message], + refreshing: false, + updatedAt: null, + }; + } +} + export async function discoverSessionPersonas( manager: AgentManager, agent: AgentRecord @@ -68,23 +97,29 @@ export async function discoverSessionPersonas( (path) => readAgentCheckoutFile(manager, agent, path), warnings ); - const root = remotePlacement(agent.cwd) - ? null - : (await mcpCheckoutRoots(manager, agent)).checkoutRoot; - const catalog = root ? await personaCatalog.get(root, false, false) : null; - warnings.push(...(catalog?.warnings ?? [])); + const catalog = await sessionDefaultBranchPersonas( + manager, + agent, + false + ).catch(() => ({ + personas: [], + warnings: ["Could not read default-branch files from the runner."], + refreshing: false, + updatedAt: null, + })); + warnings.push(...catalog.warnings); const personas = appendBuiltInPersonas( mergePersonasWithWorktreePrecedence({ worktreePersonas: local, - repoPersonas: catalog?.personas ?? [], + repoPersonas: catalog.personas, }), BUILT_IN_PERSONAS ); return { personas, warnings, - refreshing: catalog?.refreshing ?? false, - updatedAt: catalog?.updatedAt ?? null, + refreshing: catalog.refreshing, + updatedAt: catalog.updatedAt, }; } @@ -104,18 +139,19 @@ export async function resolveRunnerPersona( agent: AgentRecord, slug: string ) { - const persona = - (await loadPersonaFromCheckout(slug, (path) => - readAgentCheckoutFile(manager, agent, path) - )) ?? - (remotePlacement(agent.cwd) - ? getBuiltInPersona(slug) - : await resolveLaunchPersona( - agentWorkspaceDir(agent), - slug, - undefined, - "catalog" - )); + let persona = await loadPersonaFromCheckout(slug, (path) => + readAgentCheckoutFile(manager, agent, path) + ); + if (!persona) { + const catalog = await sessionDefaultBranchPersonas(manager, agent, true); + persona = + catalog.personas.find((candidate) => candidate.slug === slug) ?? + getBuiltInPersona(slug); + if (!persona && catalog.refreshing) + throw new Error( + "Persona catalog is still refreshing. Try again shortly." + ); + } if (!persona) throw new Error( `Persona "${slug}" not found in this checkout or built-ins.` diff --git a/apps/server/test/checkout-inspection.test.ts b/apps/server/test/checkout-inspection.test.ts index ac18ee021..1d8c10b61 100644 --- a/apps/server/test/checkout-inspection.test.ts +++ b/apps/server/test/checkout-inspection.test.ts @@ -48,18 +48,14 @@ function put(root: string, file: string, content: string): void { writeFileSync(target, content); } -function runCli(cwd: string, input: string, expectedRoot?: string) { - const result = spawnSync( - process.execPath, - expectedRoot ? [cli, expectedRoot] : [cli], - { - cwd, - input, - encoding: "utf8", - timeout: 10_000, - maxBuffer: 5 * 1024 * 1024, - } - ); +function runCli(cwd: string, input: string) { + const result = spawnSync(process.execPath, [cli], { + cwd, + input, + encoding: "utf8", + timeout: 10_000, + maxBuffer: 5 * 1024 * 1024, + }); if (result.error) throw result.error; return result; } @@ -88,7 +84,7 @@ beforeAll(() => { ); writeFileSync( entry, - `import { runCheckoutInspectionCli } from ${JSON.stringify(implementation)};\nawait runCheckoutInspectionCli(process.cwd(), process.argv[2]);\n` + `import { runCheckoutInspectionCli } from ${JSON.stringify(implementation)};\nawait runCheckoutInspectionCli(process.cwd());\n` ); execFileSync("bun", ["build", "--target=node", "--outfile", cli, entry], { stdio: "pipe", @@ -130,25 +126,6 @@ afterEach(() => { rmSync(fixture, { recursive: true, force: true }); }); -it("executes argv in the observed checkout and rejects a checkout mismatch", () => { - const command = JSON.stringify([ - "sh", - "-c", - "pwd; printf diagnostic >&2; exit 7", - ]); - const result = runCli(checkout, command, checkout); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout)).toEqual({ - stdout: checkout + "\n", - stderr: "diagnostic", - exitCode: 7, - }); - const moved = runCli(checkout, command, repo); - expect(moved.status).toBe(1); - expect(moved.stdout).toBe(""); - expect(moved.stderr).toContain("The session checkout changed"); -}); - describe.each([ ["in process", inspectCheckout], ["CLI", subprocess], diff --git a/apps/server/test/mcp-handlers.test.ts b/apps/server/test/mcp-handlers.test.ts index a7a9882b1..c7acafb3c 100644 --- a/apps/server/test/mcp-handlers.test.ts +++ b/apps/server/test/mcp-handlers.test.ts @@ -128,6 +128,16 @@ function createMockDeps() { filesDir: null, })), inspectCheckout: vi.fn(async (_agent, query) => { + if (query.kind === "defaultBranchFiles") + return { + kind: "defaultBranchFiles", + hasOrigin: false, + files: [], + warnings: [], + refreshing: false, + updatedAt: null, + truncated: false, + }; if (query.kind === "roots") return { kind: "roots", diff --git a/apps/server/test/mcp-persona-codeowners.test.ts b/apps/server/test/mcp-persona-codeowners.test.ts index 7919941f7..53b5ec009 100644 --- a/apps/server/test/mcp-persona-codeowners.test.ts +++ b/apps/server/test/mcp-persona-codeowners.test.ts @@ -1,6 +1,5 @@ import { access, readFile, readdir } from "node:fs/promises"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { personaCatalog } from "../src/personas/catalog.js"; import { createPersonaHandlers } from "../src/server/mcp-persona-handlers.js"; import { resolveRepoRoot, @@ -74,6 +73,7 @@ function setup(parentChanges: Record = {}) { baseRef: "origin/acp-runtime", head: "a".repeat(40), stateId: "1".repeat(64), + defaultFiles: [] as { path: string; content: string }[], content: new Map([ [modernOwnersPath, ownersMap("owner-one", "owner-two")], [personaFile("owner-one"), "Verify subsystem contracts"], @@ -82,20 +82,32 @@ function setup(parentChanges: Record = {}) { }; const agentManager = { getAgent: vi.fn(async (_id?: string) => parent), - inspectCheckout: vi.fn(async (_agent: typeof parent, query: Query) => - query.kind === "changes" - ? { - kind: "changes" as const, - baseRef: checkout.baseRef, - head: checkout.head, - stateId: checkout.stateId, - files: checkout.files, - } - : { - kind: "readFile" as const, - content: checkout.content.get(query.path) ?? null, - } - ), + inspectCheckout: vi.fn(async (_agent: typeof parent, query: Query) => { + if (query.kind === "changes") + return { + kind: "changes" as const, + baseRef: checkout.baseRef, + head: checkout.head, + stateId: checkout.stateId, + files: checkout.files, + }; + if (query.kind === "defaultBranchFiles") + return { + kind: "defaultBranchFiles" as const, + hasOrigin: true, + files: checkout.defaultFiles, + warnings: [], + refreshing: false, + updatedAt: null, + truncated: false, + }; + if (query.kind !== "readFile") + throw new Error("Unexpected checkout query"); + return { + kind: "readFile" as const, + content: checkout.content.get(query.path) ?? null, + }; + }), createAgent: vi.fn(async (input: { name: string }) => ({ id: `agent-${input.name}`, name: input.name, @@ -440,51 +452,41 @@ describe("code owner launches through the checkout boundary", () => { }); checkout.content.set(modernOwnersPath, ownersMap("code-review")); const builtin = getBuiltInPersona("code-review")!; - const override = { - ...builtin, - body: "Conflicting main checkout instructions", - }; - const catalog = vi.spyOn(personaCatalog, "get").mockResolvedValueOnce({ - personas: [override], - warnings: [], - refreshing: false, - updatedAt: null, + const instructions = "Conflicting default-branch instructions"; + checkout.defaultFiles.push({ + path: personaFile("code-review"), + content: instructions, }); - try { - await handlers.launchOwnerReviews("parent", { context: "Review" }); - expect(catalog).not.toHaveBeenCalled(); - expect(agentManager.createAgent).toHaveBeenCalledWith( - expect.objectContaining({ - fullAccess: false, - agentArgs: expect.arrayContaining([ - expect.stringContaining(builtin.body.trimEnd()), - ]), - }), - { detachLaunch: true, useWorktreeOf: "parent" } - ); - const absent = Object.assign(new Error("Persona file absent"), { - code: "ENOENT", - }); - vi.mocked(readFile) - .mockRejectedValueOnce(absent) - .mockRejectedValueOnce(absent); - await handlers.launchPersonaAgent(parent.id, { - persona: "code-review", - context: "Manual review", - }); - expect(agentManager.createAgent).toHaveBeenLastCalledWith( - expect.objectContaining({ - fullAccess: true, - agentArgs: expect.arrayContaining([ - "--dangerously-bypass-approvals-and-sandbox", - expect.stringContaining(override.body), - ]), - }), - { detachLaunch: true } - ); - } finally { - catalog.mockRestore(); - } + await handlers.launchOwnerReviews("parent", { context: "Review" }); + expect(agentManager.inspectCheckout).not.toHaveBeenCalledWith( + parent, + expect.objectContaining({ kind: "defaultBranchFiles" }) + ); + expect(agentManager.createAgent).toHaveBeenCalledWith( + expect.objectContaining({ + fullAccess: false, + agentArgs: expect.arrayContaining([ + expect.stringContaining(builtin.body.trimEnd()), + ]), + }), + { detachLaunch: true, useWorktreeOf: "parent" } + ); + await handlers.launchPersonaAgent(parent.id, { + persona: "code-review", + context: "Manual review", + }); + expect(agentManager.createAgent).toHaveBeenLastCalledWith( + expect.objectContaining({ + fullAccess: true, + agentArgs: expect.arrayContaining([ + "--dangerously-bypass-approvals-and-sandbox", + expect.stringContaining(instructions), + ]), + }), + { detachLaunch: true } + ); + expect(readFile).not.toHaveBeenCalled(); + expect(runCommand).not.toHaveBeenCalled(); }); it("reports a partial launch without hiding successful agents", async () => { diff --git a/apps/server/test/persona-catalog.test.ts b/apps/server/test/persona-catalog.test.ts index 30eae0c1d..13987d59e 100644 --- a/apps/server/test/persona-catalog.test.ts +++ b/apps/server/test/persona-catalog.test.ts @@ -1,13 +1,27 @@ -import { inspectCheckout } from "../src/agents/checkout-inspection.js"; -import { createPersonaHandlers } from "../src/server/mcp-persona-handlers.js"; +import { + defaultBranchFiles, + inspectCheckout, +} from "../src/agents/checkout-inspection.js"; +import { + createPersonaHandlers, + resolveRunnerPersona, +} from "../src/server/mcp-persona-handlers.js"; +import { DefaultBranchFiles } from "../src/agents/default-branch-files.js"; +import { RunnerCapabilityUnavailable } from "../src/agents/remote/service.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { + mkdtemp, + mkdir, + readdir, + readFile, + rm, + writeFile, +} from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { PersonaCatalogCache, PERSONA_REFRESH_MS, - personaCatalog, } from "../src/personas/catalog.js"; import { runCommand, @@ -145,11 +159,11 @@ describe("shared remote persona catalog", () => { if (args.includes("fetch")) await held; return runner(command, args, options); }; - const cache = new PersonaCatalogCache(delayed); + const cache = new DefaultBranchFiles(delayed); const spy = vi - .spyOn(personaCatalog, "get") - .mockImplementation((cwd, wait, fallback) => - cache.get(cwd, wait, fallback) + .spyOn(defaultBranchFiles, "get") + .mockImplementation((cwd, directories, wait) => + cache.get(cwd, directories, wait) ); const handlers = createPersonaHandlers({ agentManager: { @@ -166,10 +180,78 @@ describe("shared remote persona catalog", () => { expect(fetches).toBe(0); } finally { release(); - await cache.get(checkout, true); + await cache.get(checkout, [".agents/personas"], true); spy.mockRestore(); } }); + it("lists and resolves a session's default-branch persona with checkout precedence", async () => { + await publish("default instructions"); + const agent = { id: "author", cwd: worktree } as never; + const manager = { + getAgent: async () => agent, + inspectCheckout: ( + _agent: unknown, + query: Parameters[1] + ) => inspectCheckout(worktree, query), + } as never; + const handlers = createPersonaHandlers({ agentManager: manager } as never); + expect((await resolveRunnerPersona(manager, agent, "builder")).body).toBe( + "default instructions" + ); + expect((await handlers.listPersonas("author")).personas).toContainEqual( + expect.objectContaining({ slug: "builder", name: "builder" }) + ); + await mkdir(path.join(worktree, ".agents/personas"), { recursive: true }); + await writeFile( + path.join(worktree, ".agents/personas/builder.md"), + "---\ntype: task\nname: Local Builder\n---\ncheckout instructions" + ); + expect((await handlers.listPersonas("author")).personas).toContainEqual( + expect.objectContaining({ slug: "builder", name: "Local Builder" }) + ); + expect((await resolveRunnerPersona(manager, agent, "builder")).body).toBe( + "checkout instructions" + ); + }); + + it("keeps checkout personas and built-ins available to an older runner", async () => { + const agent = { id: "author", cwd: "runner://rnr_old/proof" } as never; + const manager = { + getAgent: async () => agent, + inspectCheckout: async ( + _agent: unknown, + query: { kind: string; path?: string } + ) => { + if (query.kind === "defaultBranchFiles") + throw new RunnerCapabilityUnavailable( + "Update the runner to read default-branch files." + ); + if (query.kind === "listFiles") + return { + kind: "listFiles", + names: query.path === ".agents/personas" ? ["local.md"] : [], + }; + return { + kind: "readFile", + content: + query.path === ".agents/personas/local.md" + ? "Checkout instructions" + : null, + }; + }, + } as never; + const handlers = createPersonaHandlers({ agentManager: manager } as never); + const list = await handlers.listPersonas("author"); + expect(list.personas.map(({ slug }) => slug)).toEqual([ + "local", + "code-review", + ]); + expect(list.warnings.join()).toContain("Update the runner"); + expect( + (await resolveRunnerPersona(manager, agent, "code-review")).slug + ).toBe("code-review"); + }); + it("does not reuse definitions after origin changes", async () => { await publish("first origin"); const cache = new PersonaCatalogCache(runner, () => now); @@ -201,6 +283,38 @@ describe("shared remote persona catalog", () => { await new PersonaCatalogCache(runner, () => now).get(checkout, true); expect(fetches).toBe(3); }); + it("reuses a pinned snapshot from the legacy cache while offline", async () => { + await publish("retained from legacy cache"); + const initial = new PersonaCatalogCache(runner, () => now); + await initial.get(checkout, true); + const base = path.join(checkout, ".git/dispatch"); + const snapshotDir = path.join(base, "default-branch"); + const legacyDir = path.join(base, "persona-catalog"); + const [file] = await readdir(snapshotDir); + const metadata = JSON.parse( + await readFile(path.join(snapshotDir, file), "utf8") + ); + await mkdir(legacyDir); + await writeFile( + path.join(legacyDir, file), + JSON.stringify({ + ...metadata, + personas: [], + warnings: [], + }) + ); + await rm(snapshotDir, { recursive: true }); + rejectFetch = true; + now += PERSONA_REFRESH_MS + 1; + const restarted = await new PersonaCatalogCache(runner, () => now).get( + worktree, + true + ); + expect(restarted.personas[0].body).toBe("retained from legacy cache"); + expect(restarted.warnings.join()).toContain("Could not refresh"); + expect(fetches).toBe(2); + }); + it("drops deleted definitions after a successful refresh and retains other valid files", async () => { await publish("one"); const cache = new PersonaCatalogCache(runner, () => now); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index e6690a46e..00b8d648c 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -60,6 +60,7 @@ function dialRunner(input: { managedWorkspace?: true; sharedWorktree?: true; checkoutInspection?: true; + defaultBranchFiles?: true; githubManagement?: true; pullRequestStatus?: true; }): Promise { @@ -92,6 +93,7 @@ function dialRunner(input: { managedWorkspace: input.managedWorkspace, sharedWorktree: input.sharedWorktree, checkoutInspection: input.checkoutInspection, + defaultBranchFiles: input.defaultBranchFiles, githubManagement: input.githubManagement, pullRequestStatus: input.pullRequestStatus, }); @@ -606,6 +608,14 @@ describe("runner enrollment service", () => { agentId: "author", query: { kind: "changes", baseBranch: null }, } as const; + const defaultFiles = { + ...query, + query: { + kind: "defaultBranchFiles" as const, + directories: [".config"], + waitForRefresh: false, + }, + }; const launch = { kind: "launch", agentId: "reviewer", @@ -639,6 +649,12 @@ describe("runner enrollment service", () => { }); try { await waitFor(() => service.supportsSharedWorktree(placement)); + await expect( + service.requestSession(placement, defaultFiles) + ).rejects.toThrow("Update the runner to read default-branch files"); + expect( + current.requests.filter((frame) => frame.type === "request") + ).toEqual([]); expect((await service.requestSession(placement, query)).value).toBe( "current" ); @@ -648,6 +664,28 @@ describe("runner enrollment service", () => { } finally { current.socket.destroy(); } + await waitFor(() => !service.available(placement)); + const extended = await dialRunner({ + ...a, + label: "with default files", + workspaces: ["@session"], + checkoutInspection: true, + defaultBranchFiles: true, + }); + try { + await waitFor(() => service.available(placement)); + expect( + (await service.requestSession(placement, defaultFiles)).value + ).toBe("with default files"); + expect(extended.requests).toContainEqual( + expect.objectContaining({ + type: "request", + command: { ...defaultFiles, workspace: "@session" }, + }) + ); + } finally { + extended.socket.destroy(); + } }); it("distinguishes a configured @session handle from managed mode and retains the mode offline", async () => { diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 86edc812a..0bd0055e1 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -341,15 +341,41 @@ it("validates checkout queries, results and borrowed launches", () => { expect( isCheckoutReply({ kind: "listFiles", names: ["../profile.txt"] }, metadata) ).toBe(false); - const execute = { - ...request, - kind: "runCheckout", - expectedRoot: "/work/checkout", - argv: ["printf", "%s", "hello"], + const defaultFiles = { + kind: "defaultBranchFiles", + directories: [".config/profiles"], + waitForRefresh: false, + } as const; + expect(parse({ ...request, query: defaultFiles })).not.toBeNull(); + for (const directories of [ + ["../profiles"], + [".git/config"], + ["/etc"], + ["a", "a"], + ]) + expect( + parse({ ...request, query: { ...defaultFiles, directories } }) + ).toBeNull(); + const reply = { + kind: "defaultBranchFiles", + hasOrigin: true, + files: [{ path: ".config/profiles/settings.txt", content: "profile" }], + warnings: [], + refreshing: false, + updatedAt: null, + truncated: false, }; - expect(parse(execute)).not.toBeNull(); - expect(parse({ ...execute, argv: [] })).toBeNull(); - expect(parse({ ...execute, expectedRoot: "../other" })).toBeNull(); + const query = { ...defaultFiles, directories: [...defaultFiles.directories] }; + expect(isCheckoutReply(reply, query)).toBe(true); + expect( + isCheckoutReply( + { + ...reply, + files: [{ path: ".config/other/settings.txt", content: "other" }], + }, + query + ) + ).toBe(false); const command = { kind: "launch", workspace: "@session", diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts index fd4d1afbd..5e7a0b9ea 100644 --- a/e2e/remote-runner/owner-review.spec.ts +++ b/e2e/remote-runner/owner-review.spec.ts @@ -69,6 +69,36 @@ function seed(directory: string, marker: string) { writeFileSync(path.join(directory, "review-marker.txt"), marker); } +function seedDefaultBranch(directory: string) { + const git = (...args: string[]) => + execFileSync("git", ["-C", directory, ...args], { stdio: "pipe" }); + git("init", "--bare", "--initial-branch=trunk", ".git/fixture-origin.git"); + git("remote", "add", "origin", ".git/fixture-origin.git"); + git("switch", "-c", "trunk", "main"); + writeFileSync( + path.join(directory, ".agents/personas/default-review.md"), + "---\nname: Trunk Review\n---\nReview using instructions from the default branch." + ); + git("add", ".agents/personas/default-review.md"); + git("commit", "-m", "Default-branch reviewer"); + git("push", "origin", "trunk"); + git("switch", "unpublished"); +} + +function copyCheckoutToRunner(directory: string, agentId: string) { + const container = state.runners.scratch.container; + const target = "/var/lib/runner/sessions/" + agentId; + execFileSync("docker", ["cp", directory + "/.", container + ":" + target]); + execFileSync("docker", [ + "exec", + container, + "chown", + "-R", + "1500:1500", + target, + ]); +} + async function listTools(request: APIRequestContext, id: string) { const res = await request.post("/api/mcp/" + id, { headers: { Accept: "application/json, text/event-stream" }, @@ -113,19 +143,7 @@ for (const placement of ["This Mac", "Linux runner"] as const) { agents.push(author); await page.goto("/agents/" + author, { waitUntil: "domcontentloaded" }); await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); - if (remote) { - const container = state.runners.scratch.container; - const directory = "/var/lib/runner/sessions/" + author; - execFileSync("docker", ["cp", tmp + "/.", container + ":" + directory]); - execFileSync("docker", [ - "exec", - container, - "chown", - "-R", - "1500:1500", - directory, - ]); - } + if (remote) copyCheckoutToRunner(tmp, author); await expect .poll(() => listTools(request, author)) .toEqual( @@ -394,6 +412,117 @@ for (const placement of ["This Mac", "Linux runner"] as const) { }); } +for (const placement of ["This Mac", "Linux runner"] as const) { + test(`lists and launches a trunk-only persona and checkout override on ${placement}`, async ({ + page, + request, + }) => { + const tmp = mkdtempSync(path.join(os.tmpdir(), "dispatch-default-review-")); + const agents: string[] = []; + try { + seed(tmp, randomUUID()); + seedDefaultBranch(tmp); + const remote = placement === "Linux runner"; + const cwd = remote + ? `runner://${(await runnerRow(request, "scratch"))?.id ?? (await enrollViaUi(page, request, "scratch"))}/@session` + : tmp; + const created = await request.post("/api/v1/agents", { + headers: authHeaders(), + data: { + name: "Default-branch persona author", + type: "claude", + cwd, + useWorktree: false, + initialPrompt: "ready", + }, + }); + expect(created.ok(), await created.text()).toBe(true); + const author = (await created.json()).agent.id as string; + agents.push(author); + await page.goto("/agents/" + author, { waitUntil: "domcontentloaded" }); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + if (remote) copyCheckoutToRunner(tmp, author); + const personaNames = async (id: string) => { + const result = await callMcpToolViaAPI( + request, + id, + "list_personas", + {} + ); + const { personas } = ( + result.result as { + structuredContent: { personas: { slug: string; name: string }[] }; + } + ).structuredContent; + return personas; + }; + await expect + .poll(() => personaNames(author)) + .toContainEqual( + expect.objectContaining({ + slug: "default-review", + name: "Trunk Review", + }) + ); + const launchDefaultReviewer = async (id: string, name: string) => { + const result = await callMcpToolViaAPI(request, id, "launch_agent", { + persona: "default-review", + name, + type: "claude", + prompt: "Review the effective checkout.", + }); + const reviewer = ( + result.result as { structuredContent: { agentId: string } } + ).structuredContent.agentId; + agents.push(reviewer); + await page.goto("/agents/" + reviewer, { + waitUntil: "domcontentloaded", + }); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + await page.goto("/agents/" + id, { waitUntil: "domcontentloaded" }); + await deleteAgentViaAPI(request, reviewer); + agents.pop(); + }; + await launchDefaultReviewer(author, "Trunk reviewer"); + const override = + "---\nname: Checkout Review\n---\nUse the checkout's instructions."; + if (remote) { + execFileSync( + "docker", + [ + "exec", + "-i", + "-u", + "1500:1500", + state.runners.scratch.container, + "tee", + "/var/lib/runner/sessions/" + + author + + "/.agents/personas/default-review.md", + ], + { input: override, stdio: ["pipe", "ignore", "pipe"] } + ); + } else + writeFileSync( + path.join(tmp, ".agents/personas/default-review.md"), + override + ); + await expect + .poll(() => personaNames(author)) + .toContainEqual( + expect.objectContaining({ + slug: "default-review", + name: "Checkout Review", + }) + ); + await launchDefaultReviewer(author, "Checkout override reviewer"); + } finally { + for (const id of agents.reverse()) await deleteAgentViaAPI(request, id); + rmSync(tmp, { recursive: true, force: true }); + } + }); +} + test("identical runner paths yield separate tool catalogs", async ({ page, request, diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index dc50211d3..acd377099 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -470,7 +470,7 @@ and bytes. Delivery replaces the named file atomically. Collection is read-only and retries re-read the current file. Commit each successful collection to service-owned storage before publishing a reference to it. -### Checkout metadata and commands +### Checkout metadata and default-branch files With both `checkoutInspection: true` and `checkoutMetadata: true`, the v1 `inspectCheckout` request supports two additional queries: @@ -488,13 +488,11 @@ effective binding. A host should reacquire metadata for each discovery instead of treating equal paths as equal checkouts across machines. Older v1 peers still accept the original inspection queries. -With `checkoutCommands: true`, the host may send `runCheckout` with the -bound session and workspace handles, the previously observed -`expectedRoot`, and a bounded `argv` array. The runner uses the bound checkout -and rejects a root mismatch. It executes the argument vector as the workload -user with a timeout and bounded output. A successful protocol result contains -a JSON string with `exitCode`, `stdout` and `stderr`, including ordinary -nonzero process exits. Host services decide who can invoke commands and -interpret any repository-specific formats. Dispatch requires a full-access -session's scoped MCP token for manifest commands on enrolled runners. -The original workspace-approved `repo` operation remains available. +With both `checkoutInspection: true` and `defaultBranchFiles: true`, send +`{kind: "defaultBranchFiles", directories, waitForRefresh}` for a bounded +set of immediate regular files in selected checkout-relative directories. +The runner observes the origin's default branch in a private Git ref, without +changing the checkout. The reply includes raw UTF-8 files and refresh status. +A caller can list cached files during refresh or wait for a cold snapshot. +A checkout without an origin returns `hasOrigin: false`. Older peers continue +to serve original queries and the workspace-approved `repo` operation. diff --git a/packages/runner-protocol/src/checkout.ts b/packages/runner-protocol/src/checkout.ts index f5081408f..d34e7923d 100644 --- a/packages/runner-protocol/src/checkout.ts +++ b/packages/runner-protocol/src/checkout.ts @@ -5,7 +5,12 @@ import { isRecord } from "./validation.js"; export type CheckoutQuery = | { kind: "changes"; baseBranch: string | null } | { kind: "readFile" | "listFiles"; path: string } - | { kind: "roots" }; + | { kind: "roots" } + | { + kind: "defaultBranchFiles"; + directories: string[]; + waitForRefresh: boolean; + }; export type CheckoutReply = | { @@ -17,43 +22,22 @@ export type CheckoutReply = } | { kind: "readFile"; content: string | null } | { kind: "listFiles"; names: string[] } - | { kind: "roots"; checkoutRoot: string; repositoryRoot: string | null }; - -export type CheckoutCommandResult = { - exitCode: number; - stdout: string; - stderr: string; + | { kind: "roots"; checkoutRoot: string; repositoryRoot: string | null } + | DefaultBranchFilesReply; + +export const DEFAULT_BRANCH_FILE_LIMIT = 100; +export const DEFAULT_BRANCH_REPLY_BYTES = 4 * 1024 * 1024; + +export type DefaultBranchFilesReply = { + kind: "defaultBranchFiles"; + hasOrigin: boolean; + files: { path: string; content: string }[]; + warnings: string[]; + refreshing: boolean; + updatedAt: number | null; + truncated: boolean; }; -export function isCheckoutCommandResult( - value: unknown -): value is CheckoutCommandResult { - return ( - isRecord(value) && - typeof value.exitCode === "number" && - Number.isInteger(value.exitCode) && - value.exitCode >= 0 && - value.exitCode < 256 && - typeof value.stdout === "string" && - typeof value.stderr === "string" - ); -} - -export function isCheckoutArgv(value: unknown): value is string[] { - return ( - Array.isArray(value) && - value.length > 0 && - value.length <= 256 && - typeof value[0] === "string" && - value[0].length > 0 && - value.every( - (arg) => - typeof arg === "string" && arg.length <= 4096 && !arg.includes("\0") - ) && - new TextEncoder().encode(JSON.stringify(value)).length <= 16 * 1024 - ); -} - /** A full branch name, never a revision expression, option, or raw ref. */ export function validBranch(value: unknown): value is string { return ( @@ -81,9 +65,30 @@ function relativePath(value: unknown): value is string { ); } +function safeCheckoutPath(value: unknown): value is string { + return ( + relativePath(value) && + !value.includes("\\") && + !/^[a-z]:/i.test(value) && + !value.split("/").some((part) => part.toLowerCase() === ".git") + ); +} + export function isCheckoutQuery(value: unknown): value is CheckoutQuery { if (!isRecord(value)) return false; if (value.kind === "roots") return true; + if (value.kind === "defaultBranchFiles") { + return ( + Array.isArray(value.directories) && + value.directories.length > 0 && + value.directories.length <= 8 && + new Set(value.directories).size === value.directories.length && + value.directories.every( + (dir) => safeCheckoutPath(dir) && dir.length <= 512 + ) && + typeof value.waitForRefresh === "boolean" + ); + } if (value.kind === "readFile" || value.kind === "listFiles") return relativePath(value.path); return ( @@ -97,6 +102,36 @@ export function isCheckoutReply( query: CheckoutQuery ): value is CheckoutReply { if (!isRecord(value) || value.kind !== query.kind) return false; + if (value.kind === "defaultBranchFiles" && query.kind === value.kind) { + return ( + typeof value.hasOrigin === "boolean" && + typeof value.refreshing === "boolean" && + typeof value.truncated === "boolean" && + (value.updatedAt === null || + (typeof value.updatedAt === "number" && + Number.isFinite(value.updatedAt) && + value.updatedAt >= 0)) && + Array.isArray(value.warnings) && + value.warnings.length <= 8 && + value.warnings.every( + (warning) => typeof warning === "string" && warning.length <= 512 + ) && + Array.isArray(value.files) && + value.files.length <= DEFAULT_BRANCH_FILE_LIMIT && + value.files.every( + (file) => + isRecord(file) && + safeCheckoutPath(file.path) && + query.directories.includes( + file.path.slice(0, file.path.lastIndexOf("/")) + ) && + typeof file.content === "string" && + new TextEncoder().encode(file.content).length <= 256 * 1024 + ) && + new TextEncoder().encode(JSON.stringify(value)).length <= + DEFAULT_BRANCH_REPLY_BYTES + ); + } if (value.kind === "readFile") return ( value.content === null || diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index f3622a5a3..61044ea7b 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -4,7 +4,6 @@ import { } from "./session-files.js"; import { isCheckoutView, type CheckoutView } from "./checkout-view.js"; import { - isCheckoutArgv, isCheckoutQuery, isCheckoutRelease, type CheckoutRelease, @@ -78,12 +77,6 @@ export type SessionOperation = operation: { kind: "describe" } | { kind: "select"; path: string | null }; } | { agentId: string; kind: "checkoutRelease"; operation: CheckoutRelease } - | { - agentId: string; - kind: "runCheckout"; - expectedRoot: string; - argv: string[]; - } | { agentId: string; kind: "repo" }; export type RunnerOperation = @@ -109,7 +102,7 @@ export type ReadyFrame = { pullRequestEvidence?: true; checkoutInspection?: true; checkoutMetadata?: true; - checkoutCommands?: true; + defaultBranchFiles?: true; checkoutViews?: true; sharedWorktree?: true; workspacePreparation?: true; @@ -139,7 +132,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { version: RUNNER_WIRE_VERSION, workspaces: frame.workspaces, ...(frame.checkoutViews === true && { checkoutViews: true }), - ...(frame.checkoutCommands === true && { checkoutCommands: true }), + ...(frame.defaultBranchFiles === true && { defaultBranchFiles: true }), ...(frame.checkoutMetadata === true && { checkoutMetadata: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), @@ -340,8 +333,6 @@ function isCommand(value: unknown): value is Command { return true; case "viewCheckout": return isCheckoutView(value.query); - case "runCheckout": - return isCheckoutPath(value.expectedRoot) && isCheckoutArgv(value.argv); case "inspectCheckout": return isCheckoutQuery(value.query); case "attach": From 59ebb24108cf15c761463e962901a4dde7911156 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 17:20:47 -0700 Subject: [PATCH 142/642] Run authorized commands in bound runner checkouts --- .agents/owners.json | 2 + apps/server/src/agents/archive.ts | 4 +- apps/server/src/agents/checkout-commands.ts | 49 +++ apps/server/src/agents/checkout-inspection.ts | 59 +++- apps/server/src/agents/lifecycle-hooks.ts | 52 ++- apps/server/src/agents/manager.ts | 41 ++- .../src/agents/remote/checkout-command.ts | 126 ++++++++ apps/server/src/agents/remote/runner.ts | 100 ++++++ apps/server/src/agents/remote/service.ts | 21 +- .../src/agents/remote/session-supervisor.ts | 28 ++ apps/server/src/main.ts | 8 + apps/server/src/routes/mcp.ts | 20 +- apps/server/src/server/mcp-checkout.ts | 33 +- apps/server/src/shared/mcp/repo-tools.ts | 36 ++- apps/server/src/shared/mcp/server.ts | 8 +- apps/server/test/agent-archive.test.ts | 3 +- apps/server/test/lifecycle-hooks.test.ts | 55 +++- apps/server/test/mcp-routes.test.ts | 6 + .../test/remote-runner-enrollment.test.ts | 31 ++ .../test/runner-protocol-consumer.test.ts | 128 ++++++++ docs/04-agent-lifecycle.md | 9 + docs/design/remote-runner-prototype.md | 30 ++ e2e/remote-runner/checkout-command.spec.ts | 296 ++++++++++++++++++ .../runner-protocol/src/checkout-command.ts | 86 +++++ packages/runner-protocol/src/connection.ts | 34 +- packages/runner-protocol/src/execution.ts | 8 + packages/runner-protocol/src/index.ts | 1 + 27 files changed, 1214 insertions(+), 60 deletions(-) create mode 100644 apps/server/src/agents/checkout-commands.ts create mode 100644 apps/server/src/agents/remote/checkout-command.ts create mode 100644 e2e/remote-runner/checkout-command.spec.ts create mode 100644 packages/runner-protocol/src/checkout-command.ts diff --git a/.agents/owners.json b/.agents/owners.json index 1f31c8723..ba1586fcd 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -27,10 +27,12 @@ "apps/server/src/routes/runner-*.ts", "apps/server/test/remote-*.test.ts", "apps/server/test/checkout-inspection.test.ts", + "apps/server/test/lifecycle-hooks.test.ts", "apps/server/test/runner-*.test.ts", "apps/server/test/github-pull-request-watches.test.ts", "apps/server/test/helpers/remote-acp-fixture.ts", "packages/runner-protocol/**", + "docs/04-agent-lifecycle.md", "docs/design/remote-runner-handoff.md", "docs/design/runner-capability-inventory.md", "docs/design/runner-parity-rollout.md", diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index 933b6da73..1669a1363 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -215,7 +215,7 @@ export async function executeArchive( // Phase: stopping — tear down session without changing agent status const t = Date.now(); try { - await runLifecycleHook("stop", agent, logger).catch((err) => + await runLifecycleHook("stop", agent, logger, deps.remote).catch((err) => logger.warn( { err, agentId: id }, "Stop hook failed during archive; continuing" @@ -355,7 +355,7 @@ export async function deleteAgentDirect( // Not stopAgent: it writes `stopping`/`stopped`, releasing the claim above // and letting a fresh archive take this agent mid-teardown. try { - await runLifecycleHook("stop", agent, logger).catch((err) => + await runLifecycleHook("stop", agent, logger, deps.remote).catch((err) => logger.warn( { err, agentId: id }, "Stop hook failed during delete; continuing" diff --git a/apps/server/src/agents/checkout-commands.ts b/apps/server/src/agents/checkout-commands.ts new file mode 100644 index 000000000..e23235255 --- /dev/null +++ b/apps/server/src/agents/checkout-commands.ts @@ -0,0 +1,49 @@ +import { + isCheckoutCommandFile, + isCheckoutCommandResult, + remotePlacement, + type CheckoutCommand, + type CheckoutCommandFile, + type CheckoutCommandResult, +} from "@dispatch/runner-protocol"; +import type { RemoteRunnerService } from "./remote/service.js"; +import type { AgentRecord } from "./types.js"; + +export async function requestCheckoutCommand( + remote: RemoteRunnerService | undefined, + agent: AgentRecord, + operation: Extract, + signal?: AbortSignal +): Promise; +export async function requestCheckoutCommand( + remote: RemoteRunnerService | undefined, + agent: AgentRecord, + operation: Extract, + signal?: AbortSignal +): Promise; +export async function requestCheckoutCommand( + remote: RemoteRunnerService | undefined, + agent: AgentRecord, + operation: CheckoutCommand, + signal?: AbortSignal +) { + const placement = remotePlacement(agent.cwd); + if (!remote || !placement) + throw new Error("The session runner is unavailable."); + const { value } = await remote.requestSession( + placement, + { kind: "checkoutCommand", agentId: agent.id, operation }, + undefined, + signal + ); + let result: unknown; + try { + if (typeof value === "string") result = JSON.parse(value); + } catch { + // Invalid replies are reported below. + } + if (operation.kind === "read" && isCheckoutCommandFile(result)) return result; + if (operation.kind === "run" && isCheckoutCommandResult(result)) + return result; + throw new Error("Invalid runner checkout command response."); +} diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index 29fe17ab2..ca1d77110 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -484,6 +484,46 @@ function encodeReply(reply: CheckoutReply): string { return encoded; } +async function inspectionRoot(cwd: string, requireGit: boolean) { + // Preserve whitespace in the root, removing only Git's terminating newline. + const probe = await run("git", ["rev-parse", "--show-toplevel"], { + cwd, + trimOutput: false, + allowedExitCodes: requireGit ? [0] : [0, 128], + }); + if (probe.exitCode && !probe.stderr.startsWith("fatal: not a git repository")) + throw new Error( + `Could not resolve checkout root: ${probe.stderr.slice(0, MAX_ERROR_BYTES)}` + ); + const root = probe.exitCode + ? await realpath(cwd) + : probe.stdout.replace(/\n$/, ""); + if (!path.isAbsolute(root)) + throw new Error("Could not resolve checkout root"); + return { root, hasGit: probe.exitCode === 0 }; +} + +export async function readCheckoutCommandFile( + cwd: string, + file: string, + configuredRoot?: string +) { + const { root } = await inspectionRoot(cwd, false); + if (configuredRoot) { + const relative = path.relative(configuredRoot, root); + if ( + relative === ".." || + relative.startsWith(".." + path.sep) || + path.isAbsolute(relative) + ) + throw new Error( + "Repository root is outside the configured runner checkout." + ); + } + const content = await readWorktreeFile(root, validateFilePath(file)); + return { root, content }; +} + export async function inspectCheckout( cwd: string, query: CheckoutQuery @@ -498,26 +538,15 @@ export async function inspectCheckout( encodeReply(reply); return reply; } - // Preserve whitespace in the root, removing only Git's terminating newline. - const probe = await run("git", ["rev-parse", "--show-toplevel"], { + const { root, hasGit } = await inspectionRoot( cwd, - trimOutput: false, - allowedExitCodes: validated.kind === "changes" ? [0] : [0, 128], - }); - if (probe.exitCode && !probe.stderr.startsWith("fatal: not a git repository")) - throw new Error( - `Could not resolve checkout root: ${probe.stderr.slice(0, MAX_ERROR_BYTES)}` - ); - const root = probe.exitCode - ? await realpath(cwd) - : probe.stdout.replace(/\n$/, ""); - if (!path.isAbsolute(root)) - throw new Error("Could not resolve checkout root"); + validated.kind === "changes" + ); if (validated.kind === "roots") return { kind: "roots", checkoutRoot: root, - repositoryRoot: probe.exitCode ? null : await resolveRepoRoot(root), + repositoryRoot: hasGit ? await resolveRepoRoot(root) : null, }; if (validated.kind === "listFiles") { const canonicalRoot = await realpath(root); diff --git a/apps/server/src/agents/lifecycle-hooks.ts b/apps/server/src/agents/lifecycle-hooks.ts index 97ba4f8e2..9fc9fd626 100644 --- a/apps/server/src/agents/lifecycle-hooks.ts +++ b/apps/server/src/agents/lifecycle-hooks.ts @@ -3,7 +3,14 @@ import type { FastifyBaseLogger } from "fastify"; import { repoCommandEnvironment } from "../shared/lib/tool-environment.js"; import { runCommand } from "../shared/lib/run-command.js"; -import { loadRepoHooks } from "../shared/mcp/repo-tools.js"; +import { requestCheckoutCommand } from "./checkout-commands.js"; +import type { RemoteRunnerService } from "./remote/service.js"; +import { + loadRepoHooks, + parseRepoHooks, + parseRepoToolFile, + REPO_TOOL_MANIFEST_PATH, +} from "../shared/mcp/repo-tools.js"; import type { AgentRecord } from "./types.js"; @@ -35,9 +42,48 @@ export type LifecycleHookName = "stop"; export async function runLifecycleHook( hookName: LifecycleHookName, agent: AgentRecord, - logger: FastifyBaseLogger + logger: FastifyBaseLogger, + remote?: RemoteRunnerService ): Promise { - if (remotePlacement(agent.cwd)) return; + if (remotePlacement(agent.cwd)) { + for (const checkout of ["launch", "moved"] as const) { + try { + const target = { checkout, path: REPO_TOOL_MANIFEST_PATH }; + const file = await requestCheckoutCommand(remote, agent, { + ...target, + kind: "read", + }); + const hook = + file && parseRepoHooks(parseRepoToolFile(file.content))[hookName]; + if (!hook) continue; + const result = await requestCheckoutCommand(remote, agent, { + ...target, + kind: "run", + state: file.state, + argv: hook.command, + }); + if (result.exitCode !== 0) { + logger.warn( + { + agentId: agent.id, + hook: hookName, + checkout, + exitCode: result.exitCode, + stderr: result.stderr, + truncated: result.truncated, + }, + "Lifecycle hook exited with non-zero code" + ); + } + } catch (err) { + logger.warn( + { err, agentId: agent.id, hook: hookName, checkout }, + "Runner lifecycle hook failed; continuing shutdown" + ); + } + } + return; + } // An agent that moved runs the hook in both places: what it started in // the launch checkout and what it started in its workspace (a dev stack, // say) each belong to that checkout's own hook. diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 57fe4865d..0c32e2542 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1,3 +1,5 @@ +import { requestCheckoutCommand } from "./checkout-commands.js"; +import { REPO_TOOL_MANIFEST_PATH } from "../shared/mcp/repo-tools.js"; import { isPromptImageMimeType } from "./acp/prompt-source.js"; import { readSessionFile } from "../files/session-file.js"; import { readAgentView } from "./checkout-runner.js"; @@ -2815,11 +2817,12 @@ export class AgentManager { await this.setAgentStatus(id, "stopping", null); // Run repo-defined stop hook (best-effort, non-blocking) - await runLifecycleHook("stop", agent, this.logger).catch((err) => - this.logger.warn( - { err, agentId: id }, - "Stop hook failed; continuing shutdown" - ) + await runLifecycleHook("stop", agent, this.logger, this.remote).catch( + (err) => + this.logger.warn( + { err, agentId: id }, + "Stop hook failed; continuing shutdown" + ) ); try { @@ -3019,6 +3022,34 @@ export class AgentManager { ); } + readRemoteRepoManifest(agent: AgentRecord) { + return requestCheckoutCommand(this.remote, agent, { + kind: "read", + checkout: "effective", + path: REPO_TOOL_MANIFEST_PATH, + }); + } + + runRemoteRepoCommand( + agent: AgentRecord, + state: string, + argv: string[], + signal?: AbortSignal + ) { + return requestCheckoutCommand( + this.remote, + agent, + { + kind: "run", + checkout: "effective", + path: REPO_TOOL_MANIFEST_PATH, + state, + argv, + }, + signal + ); + } + /** The agent's working directory: the worktree when it has one. */ async resolveRuntimeCwd(agent: AgentRecord): Promise { return agent.cwd; diff --git a/apps/server/src/agents/remote/checkout-command.ts b/apps/server/src/agents/remote/checkout-command.ts new file mode 100644 index 000000000..230af86b4 --- /dev/null +++ b/apps/server/src/agents/remote/checkout-command.ts @@ -0,0 +1,126 @@ +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { constants } from "node:os"; +import { + isCheckoutCommand, + MAX_CHECKOUT_COMMAND_OUTPUT_BYTES, + type CheckoutCommand, + type CheckoutCommandFile, + type CheckoutCommandResult, +} from "@dispatch/runner-protocol"; +import type { Readable } from "node:stream"; +import { repoCommandEnvironment } from "../../shared/lib/tool-environment.js"; +import { readCheckoutCommandFile } from "../checkout-inspection.js"; + +function capture(stream: Readable) { + const limit = MAX_CHECKOUT_COMMAND_OUTPUT_BYTES; + const buffer = Buffer.alloc(limit); + let used = 0; + let truncated = false; + stream.on("data", (chunk: Buffer) => { + const size = chunk.copy(buffer, used); + used += size; + if (size < chunk.length) truncated = true; + }); + return () => { + const decoded = buffer.toString("utf8", 0, used).trim(); + const encoded = Buffer.from(decoded); + return { + text: new TextDecoder().decode(encoded.subarray(0, limit), { + stream: true, + }), + truncated: truncated || encoded.length > limit, + }; + }; +} + +export async function executeCheckoutCommand( + cwd: string, + session: string, + operation: CheckoutCommand, + configuredRoot?: string +): Promise { + const { root, content } = await readCheckoutCommandFile( + cwd, + operation.path, + configuredRoot + ); + const state = createHash("sha256") + .update( + JSON.stringify([ + session, + operation.checkout, + cwd, + root, + operation.path, + content, + ]) + ) + .digest("hex"); + if (operation.kind === "read") + return content === null ? null : { content, state }; + if (content === null || operation.state !== state) + throw new Error( + "Checkout command authorization is stale. Read the checkout file again." + ); + + const [command, ...args] = operation.argv; + const child = spawn(command!, args, { + cwd: root, + env: repoCommandEnvironment(session), + stdio: ["ignore", "pipe", "pipe"], + }); + const stdout = capture(child.stdout); + const stderr = capture(child.stderr); + return new Promise((resolve, reject) => { + child.once("error", () => + reject(new Error("Could not start checkout command.")) + ); + child.once("close", (code, signal) => { + const output = stdout(); + const errors = stderr(); + resolve({ + exitCode: code ?? (signal ? 128 + constants.signals[signal] : 1), + stdout: output.text, + stderr: errors.text, + truncated: output.truncated || errors.truncated, + }); + }); + }); +} + +export async function runCheckoutCommandCli( + cwd: string, + session: string, + configuredRoot?: string +) { + try { + const chunks: Buffer[] = []; + let size = 0; + for await (const input of process.stdin) { + const chunk = Buffer.from(input); + size += chunk.length; + if (size > 96 * 1024) + throw new Error("Checkout command request is too large."); + chunks.push(chunk); + } + const operation: unknown = JSON.parse( + Buffer.concat(chunks).toString("utf8") + ); + if (!isCheckoutCommand(operation)) + throw new Error("Invalid checkout command."); + process.stdout.write( + JSON.stringify( + await executeCheckoutCommand(cwd, session, operation, configuredRoot) + ) + ); + } catch (error) { + process.stderr.write( + (error instanceof Error + ? error.message + : "Checkout command failed." + ).slice(0, 1024) + ); + process.exitCode = 1; + } +} diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 5373c41b9..73f1fea2b 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -19,6 +19,8 @@ import { MANAGED_WORKSPACE, RUNNER_WIRE_VERSION, MAX_CHECKOUT_VIEW_BYTES, + CHECKOUT_COMMAND_TIMEOUT_MS, + MAX_CHECKOUT_COMMAND_REPLY_BYTES, wireFrames, parseServiceFrame, runnerRequestId, @@ -108,6 +110,53 @@ function executionArgs(uid: number, gid: number) { ]; } +function runCheckoutWorker( + args: string[], + env: NodeJS.ProcessEnv, + input: string, + signal: AbortSignal +): Promise { + signal.throwIfAborted(); + const child = spawn(setpriv, args, { detached: true, env }); + const kill = () => { + if (!child.pid) return; + try { + process.kill(-child.pid, "SIGKILL"); + } catch { + // The process group may already have exited. + } + }; + return new Promise((resolve, reject) => { + const stdout: Buffer[] = []; + let bytes = 0; + let stderr = ""; + signal.addEventListener("abort", kill, { once: true }); + child.stdout.on("data", (chunk: Buffer) => { + bytes += chunk.length; + if (bytes > MAX_CHECKOUT_COMMAND_REPLY_BYTES) kill(); + else stdout.push(chunk); + }); + child.stderr.on("data", (chunk: Buffer) => { + if (stderr.length < 1024) + stderr = (stderr + chunk.toString()).slice(0, 1024); + }); + child.stdin.on("error", () => {}); + child.stdin.end(input); + child.once("error", () => + reject(new Error("Could not start checkout worker.")) + ); + child.once("close", (code) => { + signal.removeEventListener("abort", kill); + if (signal.aborted) reject(signal.reason); + else if (bytes > MAX_CHECKOUT_COMMAND_REPLY_BYTES) + reject(new Error("Checkout command reply exceeded its output limit.")); + else if (code !== 0) + reject(new Error(stderr || "Checkout worker failed.")); + else resolve(Buffer.concat(stdout).toString("utf8")); + }); + }); +} + async function verifyExecutionIdentity( uid: number, gid: number, @@ -321,6 +370,7 @@ export async function runRemoteRunner(filename: string) { samplingEngines = false; } }; + const checkoutCommands = new Map(); const watches = new Map void>(); const sharedWatches = new SharedCheckoutWatches((cwd, changed, closed) => childWatch( @@ -461,6 +511,51 @@ export async function runRemoteRunner(filename: string) { } if (socket.destroyed) return; switch (command.kind) { + case "checkoutCommand": { + if (checkoutCommands.has(id) || checkoutCommands.size >= 32) + throw new Error( + "Too many checkout commands or duplicate request ID." + ); + const controller = new AbortController(); + checkoutCommands.set(id, controller); + const deadline = setTimeout( + () => controller.abort(new Error("Checkout command timed out.")), + CHECKOUT_COMMAND_TIMEOUT_MS + ); + const signal = AbortSignal.any([ + connection.signal, + controller.signal, + ]); + try { + const value = await supervisor.withCommandCheckout( + agentId, + workspace, + command.operation.checkout, + target?.cwd, + signal, + (cwd, configuredRoot) => + runCheckoutWorker( + [ + ...childArgs, + ...selfCommand("runner-checkout-command"), + cwd, + agentId, + ...(configuredRoot ? [configuredRoot] : []), + ], + env, + JSON.stringify(command.operation), + signal + ) + ); + if (value === null && command.operation.kind === "run") + throw new Error("The moved checkout is no longer selected."); + result(value ?? "null"); + } finally { + clearTimeout(deadline); + checkoutCommands.delete(id); + } + break; + } case "sessionFile": result( await supervisor.sessionFile( @@ -720,6 +815,10 @@ export async function runRemoteRunner(filename: string) { : "Runner command failed", }) ); + } else if (frame.type === "cancel_checkout_command") { + checkoutCommands + .get(frame.id) + ?.abort(new Error("Checkout command cancelled.")); } else if (frame.type === "data") { const channel = channels.get(frame.id); if (channel && channel.writableLength > 32 * 1024 * 1024) @@ -749,6 +848,7 @@ export async function runRemoteRunner(filename: string) { pullRequestEvidence: true, checkoutInspection: true, checkoutMetadata: true, + checkoutCommands: true, defaultBranchFiles: true, workspacePreparation: true, sessionCheckout: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 2d25a8849..1966ed1d2 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -162,6 +162,7 @@ type Peer = { pullRequestEvidence: boolean; checkoutInspection: boolean; checkoutMetadata: boolean; + checkoutCommands: boolean; defaultBranchFiles: boolean; sessionCheckout: boolean; checkoutRelease: boolean; @@ -699,6 +700,7 @@ export class RemoteRunnerService { sessionFiles: ready.sessionFiles === true, defaultBranchFiles: ready.defaultBranchFiles === true, checkoutMetadata: ready.checkoutMetadata === true, + checkoutCommands: ready.checkoutCommands === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, workspacePreparation: ready.workspacePreparation === true, @@ -1238,13 +1240,15 @@ export class RemoteRunnerService { requestSession( placement: Placement, operation: SessionOperation, - onProgress?: (progress: LaunchProgress) => void + onProgress?: (progress: LaunchProgress) => void, + signal?: AbortSignal ) { return this.request( placement, { ...operation, workspace: placement.workspace }, operation.kind === "attach" || operation.kind === "watchCheckout", - onProgress + onProgress, + signal ); } @@ -1528,7 +1532,8 @@ export class RemoteRunnerService { placement: Placement, command: Command, open = false, - onProgress?: (progress: LaunchProgress) => void + onProgress?: (progress: LaunchProgress) => void, + signal?: AbortSignal ) { const peer = this.peers.get(placement.runner); if ( @@ -1567,6 +1572,10 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to use these checkout options." ); + if (command.kind === "checkoutCommand" && !peer.checkoutCommands) + throw new RunnerCapabilityUnavailable( + "Update the runner to execute checkout commands." + ); if (command.kind === "sessionFile" && !peer.sessionFiles) throw new RunnerCapabilityUnavailable( "Update the runner to transfer session files." @@ -1628,7 +1637,11 @@ export class RemoteRunnerService { if (peer.sessionFileTail === transfer) peer.sessionFileTail = undefined; } } - return peer.connection.request(command, { openChannel: open, onProgress }); + return peer.connection.request(command, { + openChannel: open, + onProgress, + signal, + }); } close() { diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index 4f9e82d90..e42bcfbb2 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -1,3 +1,4 @@ +import type { CheckoutCommand } from "@dispatch/runner-protocol"; import { createHash, randomUUID } from "node:crypto"; import { closeSync, constants, fstatSync, openSync, type Stats } from "node:fs"; import { @@ -942,6 +943,33 @@ export async function createSessionSupervisor( : releaseCheckout(key, workspace, operation.expectedState); }); }, + async withCommandCheckout( + agentId: string, + workspace: string, + checkout: CheckoutCommand["checkout"], + configuredCwd: string | undefined, + signal: AbortSignal, + run: (cwd: string, configuredRoot?: string) => Promise + ): Promise { + const key = runnerStorageKey(agentId); + const owner = checkoutOwner(await readBinding(key)) ?? key; + return withLaunchLocks([key, owner], async () => { + signal.throwIfAborted(); + if ((checkoutOwner(await readBinding(key)) ?? key) !== owner) + throw new Error("The checkout binding changed; retry the request."); + const initial = await initialDirectory(key, workspace, configuredCwd); + const cwd = + checkout === "launch" + ? initial + : await selectedDirectory(key, workspace, initial); + signal.throwIfAborted(); + if (checkout === "moved" && cwd === initial) return null; + const configuredRoot = managedTarget(workspace) + ? undefined + : await configuredDirectory(key, configuredCwd); + return run(cwd, configuredRoot); + }); + }, checkoutDirectory( agentId: string, workspace: string, diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 7816278fc..7ccfe4753 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -73,6 +73,14 @@ if (process.argv[2]?.startsWith("recovery-")) { } catch { process.exitCode = 1; } +} else if (process.argv[2] === "runner-checkout-command") { + const { runCheckoutCommandCli } = + await import("./agents/remote/checkout-command.js"); + await runCheckoutCommandCli( + process.argv[3]!, + process.argv[4]!, + process.argv[5] + ); } else if (process.argv[2] === "runner-inspect-checkout") { const { runCheckoutInspectionCli } = await import("./agents/checkout-inspection.js"); diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index 11f253164..cb37aa911 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -62,7 +62,8 @@ function isOwnerReviewRequest(body: unknown): boolean { async function checkoutContext( deps: McpRouteDeps, agent: NonNullable>>, - body: unknown + body: unknown, + allowRemoteCommands: boolean ) { const placement = remotePlacement(agent.cwd); const workspaceDir = agentWorkspaceDir(agent) ?? agent.cwd; @@ -91,7 +92,8 @@ async function checkoutContext( toolsRoot: placement ? workspaceDir : (worktreeRoot ?? undefined), discoverRepoTools: ownerOnly ? async () => [] - : () => discoverRepoTools(deps.agentManager, agent), + : () => + discoverRepoTools(deps.agentManager, agent, allowRemoteCommands), }, }; } @@ -260,7 +262,12 @@ export async function registerMcpRoutes( .send({ error: "Token does not match the active job run." }); } - const checkout = await checkoutContext(deps, agent, request.body); + const checkout = await checkoutContext( + deps, + agent, + request.body, + Boolean(bearerToken && run) + ); const { workspaceDir, repoRoot } = checkout; const jobTools = run @@ -387,7 +394,12 @@ export async function registerMcpRoutes( .send({ error: "Job agents must use the job-scoped MCP route." }); } - const checkout = await checkoutContext(deps, agent, request.body); + const checkout = await checkoutContext( + deps, + agent, + request.body, + Boolean(bearerToken) + ); const { workspaceDir, repoRoot } = checkout; reply.hijack(); diff --git a/apps/server/src/server/mcp-checkout.ts b/apps/server/src/server/mcp-checkout.ts index e09aee154..daa9549b9 100644 --- a/apps/server/src/server/mcp-checkout.ts +++ b/apps/server/src/server/mcp-checkout.ts @@ -1,4 +1,5 @@ import { remotePlacement } from "@dispatch/runner-protocol"; +import { RunnerCapabilityUnavailable } from "../agents/remote/service.js"; import type { AgentManager, AgentRecord } from "../agents/manager.js"; import { parseRepoToolFile, @@ -35,8 +36,30 @@ export async function mcpCheckoutRoots( export async function discoverRepoTools( manager: AgentManager, - agent: AgentRecord + agent: AgentRecord, + allowRemoteCommands: boolean ) { + const remote = remotePlacement(agent.cwd); + let unavailable: RunnerCapabilityUnavailable | undefined; + if (remote && allowRemoteCommands) { + let file; + try { + file = await manager.readRemoteRepoManifest(agent); + } catch (error) { + if (!(error instanceof RunnerCapabilityUnavailable)) return []; + // Keep discovery on older peers and surface their capability error on call. + unavailable = error; + } + if (file) { + return parseRepoTools( + parseRepoToolFile(file.content), + (argv, _cwd, _id, signal) => + manager.runRemoteRepoCommand(agent, file.state, argv, signal) + ); + } + if (!unavailable) return []; + } + let content: string | null; try { content = await readAgentCheckoutFile( @@ -47,13 +70,15 @@ export async function discoverRepoTools( } catch { return []; } - const remote = remotePlacement(agent.cwd); return parseRepoTools( parseRepoToolFile(content), remote ? async () => { - throw new Error( - "Checkout manifest commands are unavailable on enrolled runners." + throw ( + unavailable ?? + new Error( + "Checkout commands require the selected session's MCP credential." + ) ); } : undefined diff --git a/apps/server/src/shared/mcp/repo-tools.ts b/apps/server/src/shared/mcp/repo-tools.ts index 0b5ffa22d..7b7ce00c2 100644 --- a/apps/server/src/shared/mcp/repo-tools.ts +++ b/apps/server/src/shared/mcp/repo-tools.ts @@ -56,6 +56,7 @@ export type RepoToolResult = { repoRoot: string; command: string[]; exitCode: number; + truncated?: boolean; stdout: string; stderr: string; message: string; @@ -70,6 +71,7 @@ export type RepoToolDefinition = { agentId: string; repoRoot: string; params?: Record; + signal?: AbortSignal; }) => Promise; }; @@ -87,9 +89,11 @@ export function parseRepoTools( execute: ( command: string[], cwd: string, - agentId: string + agentId: string, + signal?: AbortSignal ) => Promise<{ exitCode: number; + truncated?: boolean; stdout: string; stderr: string; }> = runLocalRepoCommand @@ -104,7 +108,7 @@ export function parseRepoTools( description: tool.description, params: tool.params, scope: tool.scope, - run: async ({ agentId, repoRoot: currentRepoRoot, params }) => { + run: async ({ agentId, repoRoot: currentRepoRoot, params, signal }) => { const [command, ...args] = tool.command; // Append CLI flags from params @@ -127,7 +131,8 @@ export function parseRepoTools( const result = await execute( [command, ...args], currentRepoRoot, - agentId + agentId, + signal ); return { @@ -135,6 +140,9 @@ export function parseRepoTools( repoRoot: currentRepoRoot, command: tool.command, exitCode: result.exitCode, + ...(result.truncated !== undefined && { + truncated: result.truncated, + }), stdout: result.stdout, stderr: result.stderr, message: @@ -234,25 +242,21 @@ export async function loadRepoHooks(repoRoot: string): Promise { } const config = await readRepoToolFile(manifestPath); + const hooks = parseRepoHooks(config); + hooksCache.set(manifestPath, { mtime, hooks }); + return hooks; +} + +export function parseRepoHooks(config: RepoToolFile | null): RepoHooks { if ( !config?.hooks || typeof config.hooks !== "object" || Array.isArray(config.hooks) - ) { - const empty = {}; - hooksCache.set(manifestPath, { mtime, hooks: empty }); - return empty; - } + ) + return {}; - const hooks: RepoHooks = {}; const raw = config.hooks as Record; - - if (raw.stop) { - hooks.stop = parseHookDefinition(raw.stop, "stop"); - } - - hooksCache.set(manifestPath, { mtime, hooks }); - return hooks; + return raw.stop ? { stop: parseHookDefinition(raw.stop, "stop") } : {}; } function parseHookDefinition(value: unknown, name: string): RepoHookDefinition { diff --git a/apps/server/src/shared/mcp/server.ts b/apps/server/src/shared/mcp/server.ts index dafcd81b9..d81a26cd9 100644 --- a/apps/server/src/shared/mcp/server.ts +++ b/apps/server/src/shared/mcp/server.ts @@ -661,7 +661,10 @@ export async function createDispatchMcpServer( loadRepoTools(toolsRoot)); const scope = context.toolScope ?? "agent"; const repoTools = allRepoTools.filter( - (tool) => !tool.scope || tool.scope.includes(scope) + (tool) => + (tool.name !== "repo_runner_workspace" || + !context.remoteRepoOperation) && + (!tool.scope || tool.scope.includes(scope)) ); for (const tool of repoTools) { const inputSchema = buildParamSchema(tool.params); @@ -671,12 +674,13 @@ export async function createDispatchMcpServer( description: tool.description, inputSchema, }, - async (args) => { + async (args, { signal }) => { try { const result = await tool.run({ agentId: context.agent!.id, repoRoot: toolsRoot, params: args as Record, + signal, }); // `message` is the command's stdout, which is already the text // content — carrying it in the structured payload too sent every diff --git a/apps/server/test/agent-archive.test.ts b/apps/server/test/agent-archive.test.ts index bb96fabef..53fad094c 100644 --- a/apps/server/test/agent-archive.test.ts +++ b/apps/server/test/agent-archive.test.ts @@ -613,7 +613,8 @@ describe("executeArchive", () => { expect(runLifecycleHook).toHaveBeenCalledWith( "stop", agent, - expect.anything() + expect.anything(), + undefined ); }); diff --git a/apps/server/test/lifecycle-hooks.test.ts b/apps/server/test/lifecycle-hooks.test.ts index 91dbe30d5..f27afd9bf 100644 --- a/apps/server/test/lifecycle-hooks.test.ts +++ b/apps/server/test/lifecycle-hooks.test.ts @@ -2,9 +2,10 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { runLifecycleHook } from "../src/agents/lifecycle-hooks.js"; +import type { RemoteRunnerService } from "../src/agents/remote/service.js"; import type { AgentRecord } from "../src/agents/types.js"; const logger = { @@ -86,3 +87,55 @@ describe("runLifecycleHook", () => { ); }); }); + +it("reports a runner hook failure and still runs the moved checkout on each teardown attempt", async () => { + const warn = vi.fn(); + const call = vi.fn(async (_placement, { operation }) => { + const content = JSON.stringify({ + hooks: { stop: { command: ["cleanup", operation.checkout] } }, + }); + return { + value: JSON.stringify( + operation.kind === "read" + ? { content, state: "a".repeat(64) } + : { + exitCode: operation.checkout === "launch" ? 23 : 0, + stderr: "cleanup failed", + stdout: "", + truncated: false, + } + ), + }; + }); + const remote = { requestSession: call } as unknown as RemoteRunnerService; + const agent = { id: "session", cwd: "runner://machine/work" } as AgentRecord; + for (let attempt = 0; attempt < 2; attempt++) { + await expect( + runLifecycleHook("stop", agent, { ...logger, warn }, remote) + ).resolves.toBeUndefined(); + } + expect( + call.mock.calls.map(([, { operation }]) => [ + operation.checkout, + operation.kind, + ]) + ).toEqual([ + ["launch", "read"], + ["launch", "run"], + ["moved", "read"], + ["moved", "run"], + ["launch", "read"], + ["launch", "run"], + ["moved", "read"], + ["moved", "run"], + ]); + expect(warn).toHaveBeenCalledTimes(2); + expect(warn).toHaveBeenCalledWith( + expect.objectContaining({ + checkout: "launch", + exitCode: 23, + stderr: "cleanup failed", + }), + expect.any(String) + ); +}); diff --git a/apps/server/test/mcp-routes.test.ts b/apps/server/test/mcp-routes.test.ts index 91ff9f5ac..560f00bbb 100644 --- a/apps/server/test/mcp-routes.test.ts +++ b/apps/server/test/mcp-routes.test.ts @@ -9,6 +9,7 @@ import { } from "vitest"; import Fastify, { type FastifyInstance } from "fastify"; +import { RunnerCapabilityUnavailable } from "../src/agents/remote/service.js"; import { registerMcpRoutes } from "../src/routes/mcp.js"; import { handleMcpRequest } from "../src/shared/mcp/server.js"; import { @@ -56,6 +57,11 @@ function createMockDeps() { repositoryRoot: "/repo", }) ), + readRemoteRepoManifest: vi.fn(async () => { + throw new RunnerCapabilityUnavailable( + "Update the runner to execute checkout commands." + ); + }), remoteRepoOperation: vi.fn(), permitsRemoteAgentMcp: vi.fn(() => false), getAgent: vi.fn(async () => ({ diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 00b8d648c..e254d40d8 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -248,6 +248,37 @@ describe("runner enrollment service", () => { ).toHaveLength(1); }); + it("rejects checkout commands on an older peer while preserving the workspace operation", async () => { + const service = makeService(true); + const enrolled = await enroll(service, "legacy-checkout"); + const placement = { runner: enrolled.created.id, workspace: "work" }; + const peer = await dialRunner({ + ...enrolled, + workspaces: ["work"], + label: "approved", + }); + runners.push(peer); + await waitFor(() => service.available(placement)); + + await expect( + service.requestSession(placement, { + kind: "checkoutCommand", + agentId: "session", + operation: { kind: "read", checkout: "effective", path: "tools.json" }, + }) + ).rejects.toThrow(/update.*checkout commands/i); + expect(service.repoToolFor(placement)).toBe(true); + await expect( + service.requestSession(placement, { + kind: "repo", + agentId: "session", + }) + ).resolves.toMatchObject({ value: "approved" }); + expect( + peer.requests.filter((frame) => frame.type === "request") + ).toHaveLength(1); + }); + it("pairs with a one-time code over a pinned CA and lists the runner", async () => { const service = makeService(); const created = await service.createRegistration("alpha"); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 0bd0055e1..501cedaf4 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -26,6 +26,8 @@ import { isGitHubPullRequestDetails, isGitHubPullRequestDiff, isCheckoutViewData, + isCheckoutCommandFile, + isCheckoutCommandResult, remotePlacement, workspaceLocator, } from "@dispatch/runner-protocol"; @@ -786,6 +788,7 @@ function fixtureRunner(current: boolean) { pullRequestWatch: true, sessionCheckout: true, checkoutRelease: true, + checkoutCommands: true, sessionFiles: true, }), }; @@ -872,6 +875,8 @@ function fixtureRunner(current: boolean) { case "close": channels.get(frame.id)?.destroy(); break; + case "cancel_checkout_command": + break; case "request": { const { command, id } = frame; const result = (value: boolean | string) => @@ -925,6 +930,27 @@ function fixtureRunner(current: boolean) { command.agentId !== agentId ) { reply({ type: "result", id, error: "Unknown session binding" }); + } else if (command.kind === "checkoutCommand" && current && running) { + const operation = command.operation; + if (operation.kind === "read") { + result( + JSON.stringify({ + content: "independent policy data", + state: stateId, + }) + ); + } else if (operation.state !== stateId) { + reply({ type: "result", id, error: "Stale command state" }); + } else if (operation.argv[0] !== "wait") { + result( + JSON.stringify({ + exitCode: 0, + stdout: operation.argv[1], + stderr: "", + truncated: false, + }) + ); + } } else if (command.kind === "sessionFile" && current && running) { const operation = command.operation; const root = "/workload/files/"; @@ -1528,3 +1554,105 @@ it("bounds decoded session files and rejects unsafe paths at the wire boundary", ).toBeNull(); } }); + +it.each([true, false])( + "independent host negotiates checkout execution and cancels by request ID: %s", + async (current) => { + const runner = fixtureRunner(current); + const peer = runner.connect(); + try { + await vi.waitFor(() => expect(peer.reports[0]).toBeDefined()); + const ready = parseReadyFrame(peer.reports[0]); + expect(ready?.checkoutCommands).toBe(current ? true : undefined); + if (!ready?.checkoutCommands) { + expect(runner.requests).toHaveLength(0); + return; + } + await peer.connection.request({ + ...runner.session, + kind: "launch", + launch: { + agentId: runner.session.agentId, + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + }, + }); + const route = { ...runner.session, kind: "checkoutCommand" } as const; + const file = { checkout: "effective", path: "config/commands" } as const; + const read = await peer.connection.request({ + ...route, + operation: { ...file, kind: "read" }, + }); + const observed: unknown = JSON.parse(String(read.value)); + if (!isCheckoutCommandFile(observed) || !observed) + throw new Error("Expected checkout file"); + expect(observed.content).toBe("independent policy data"); + const operation = { + ...file, + kind: "run" as const, + state: observed.state, + argv: ["printf", "one literal argument"], + }; + const wire = (overrides: Record) => + parseServiceFrame({ + type: "request", + id: "id", + command: { ...route, operation: { ...operation, ...overrides } }, + }); + expect(wire({})).not.toBeNull(); + for (const invalid of [ + { path: "../commands" }, + { argv: [] }, + { argv: ["bad\0arg"] }, + { argv: ["x".repeat(16 * 1024 + 1)] }, + { checkout: "/workload" }, + { state: "x" }, + ]) + expect(wire(invalid)).toBeNull(); + const reply = await peer.connection.request({ ...route, operation }); + const value = JSON.parse(String(reply.value)); + expect(isCheckoutCommandResult(value)).toBe(true); + expect(value.stdout).toBe(operation.argv[1]); + expect( + isCheckoutCommandResult({ ...value, stdout: "x".repeat(65537) }) + ).toBe(false); + await expect( + peer.connection.request({ + ...route, + operation: { ...operation, state: "a".repeat(64) }, + }) + ).rejects.toThrow("Stale"); + await expect( + peer.connection.request({ + ...route, + agentId: "foreign/session", + operation, + }) + ).rejects.toThrow("Unknown session binding"); + + const abort = new AbortController(); + const waiting = peer.connection.request( + { ...route, operation: { ...operation, argv: ["wait"] } }, + { signal: abort.signal } + ); + await vi.waitFor(() => + expect(runner.requests.at(-1)).toMatchObject({ + command: { operation: { argv: ["wait"] } }, + }) + ); + const id = requestId(runner.requests.at(-1)); + abort.abort(); + await expect(waiting).rejects.toThrow(/cancelled/i); + await vi.waitFor(() => + expect(runner.requests.at(-1)).toEqual({ + type: "cancel_checkout_command", + id, + }) + ); + } finally { + peer.close(); + } + } +); diff --git a/docs/04-agent-lifecycle.md b/docs/04-agent-lifecycle.md index 6dd5c2fad..23d282a24 100644 --- a/docs/04-agent-lifecycle.md +++ b/docs/04-agent-lifecycle.md @@ -169,6 +169,15 @@ Force stop (`force: true` on `POST /agents/:id/stop`) skips the graceful ACP clo The repo's `stop` lifecycle hook (configured under `.dispatch/tools.json`) runs best-effort before the teardown. +For an enrolled runner with checkout command support, Dispatch reads the +`stop` hook from the launch checkout, then from the selected workspace if it +differs. The runner invokes each command under its workload identity before +teardown. Dispatch logs nonzero exits and execution errors and continues +stopping the session. Selecting a workspace only changes the checkout +selection, so retrying the selection cannot invoke a hook. A retry after +failed teardown can invoke both hooks again. Stop on an already stopped +session skips the hooks. Keep cleanup idempotent. + ## Idempotency Rules - `start` on a `running` agent is a no-op (returns the agent at `running` with HTTP 200). The handler reattaches to a live host if one is found instead of spawning a new one. diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index bfb16260c..b2ea554c7 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -243,6 +243,36 @@ With `sharedWorktree: true`, a launch can specify `useWorktreeOf`, an existing a The service checks advertised capabilities on each connection before sending a dependent command. A peer without the extension can continue its existing sessions. Callers receive an actionable unsupported error if they request checkout inspection or sharing. A failed remote inspection must never resolve the runner locator as a local path. +### Executing commands in a bound checkout + +V1 peers advertising `checkoutCommands: true` accept the session-scoped +`checkoutCommand` request. It uses the usual opaque workspace and session +handles. The operation includes a checkout selector (`effective`, `launch` +or `moved`) and a relative file path. `read` returns a JSON string containing +`{content,state}`, or JSON null for an absent file or a missing moved +selection. The returned state is opaque to consumers and binds the read to +the directory and text observed by the runner. `run` takes that state and the +authorized argv. A changed file or checkout produces an error before spawn. +The service decides what the file means and which argv to authorize. A +companion command can change independently of the read file, so the consumer +must trust commands in the selected checkout. + +The runner executes argv directly in the checkout as the workload user and +exports the opaque session ID in `DISPATCH_AGENT_ID`. It returns a JSON string +containing `{exitCode,stdout,stderr,truncated}`, with at most 64 KiB of UTF-8 +per stream. A signal exit uses 128 plus the signal number. Each operation has +a 15-second runner deadline. The service may send +`{type:"cancel_checkout_command",id}` on the same connection. Cancellation, +deadline and disconnect terminate the worker process group. Commands that +deliberately leave the process group own their own cleanup. A lost reply can +leave side effects, so consumers should reconcile them before retrying. Older +peers keep the existing inspection and configured workspace operations. + +Dispatch interprets the repository manifest and applies its MCP tool scope and +argument rules. Executing a remote manifest tool requires the credential for the +selected session or its active job run. Dispatch checks the runner registration +before routing the request. + ## Observed traces The initial fake-agent turn ran as `agt_4643ddec746a`. The UI showed diff --git a/e2e/remote-runner/checkout-command.spec.ts b/e2e/remote-runner/checkout-command.spec.ts new file mode 100644 index 000000000..75d4fa72e --- /dev/null +++ b/e2e/remote-runner/checkout-command.spec.ts @@ -0,0 +1,296 @@ +import { expect, test, type APIRequestContext } from "@playwright/test"; +import { + mkdtempSync, + mkdirSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { authHeaders, deleteAgentViaAPI } from "../helpers"; +import { + enrollViaUi, + guest, + guestDiagnostics, + RUNNERS_API, + state, +} from "./harness"; + +function manifest(marker: string, hookCode = 0) { + return JSON.stringify({ + tools: [ + { + name: "fixture", + description: marker, + command: [ + "sh", + "-c", + 'printf "%s|%s|%s|%s|%s" "$1" "$PWD" "$(id -u):$(id -g)" "$DISPATCH_AGENT_ID" "$3"', + "fixture", + marker, + ], + params: [ + { + name: "value", + type: "string", + flag: "--value", + description: "Fixture value", + }, + ], + }, + { + name: "bounded", + description: "Return more output than the runner retains.", + command: ["sh", "-c", "yes x | head -c 70000; exit 17"], + }, + { + name: "deadline", + description: "Start a child and wait for the runner deadline.", + command: ["sh", "-c", 'sleep 60 & echo "$!" > deadline.pid; wait'], + }, + ], + hooks: { + stop: { + command: [ + "sh", + "-c", + 'printf "%s|%s|%s\\n" "$PWD" "$(id -u):$(id -g)" "$DISPATCH_AGENT_ID" >> hook.log; exit "$1"', + "hook", + String(hookCode), + ], + }, + }, + }); +} + +function seedGuest( + name: "alpha" | "scratch", + directory: string, + marker: string, + hookCode = 0 +) { + guest( + name, + `mkdir -p '${directory}/.dispatch' && cat > '${directory}/.dispatch/tools.json' <<'MANIFEST'\n${manifest(marker, hookCode)}\nMANIFEST\nchown -R 1500:1500 '${directory}'` + ); +} + +async function mcp( + request: APIRequestContext, + id: string, + token: string | undefined, + method: string, + params?: unknown +) { + return request.post("/api/mcp/" + id, { + headers: { + Accept: "application/json, text/event-stream", + ...(token && { Authorization: "Bearer " + token }), + }, + data: { jsonrpc: "2.0", id: 1, method, params }, + }); +} + +async function result(response: Awaited>) { + const body = await response.text(); + expect(response.ok(), body).toBe(true); + const line = body.split("\n").find((line) => line.startsWith("data: ")); + expect(line, body).toBeDefined(); + return JSON.parse(line!.slice(6)).result; +} + +test("dispatches authenticated repo tools and stop hooks to the bound checkout", async ({ + page, + request, +}, testInfo) => { + const native = realpathSync( + mkdtempSync(path.join(os.tmpdir(), "dispatch-checkout-command-")) + ); + const agents: string[] = []; + const start = async (cwd: string) => { + const res = await request.post("/api/v1/agents", { + headers: authHeaders(), + data: { + name: "Checkout command fixture", + type: "claude", + cwd, + useWorktree: false, + }, + }); + expect(res.ok(), await res.text()).toBe(true); + const { + agent: { id }, + } = await res.json(); + agents.push(id); + await expect + .poll( + async () => { + const response = await request.get("/api/v1/agents/" + id, { + headers: authHeaders(), + }); + return (await response.json()).agent?.status; + }, + { timeout: 30_000 } + ) + .toBe("running"); + return id as string; + }; + const stop = async (id: string) => { + const res = await request.post("/api/v1/agents/" + id + "/stop", { + headers: authHeaders(), + }); + expect(res.ok(), await res.text()).toBe(true); + expect((await res.json()).agent.status).toBe("stopped"); + }; + const token = (runner: "alpha" | "scratch", id: string): string => + JSON.parse(guest(runner, `cat /var/lib/runner/hosts/${id}/launch.json`)).mcp + .token; + const call = { + name: "repo_fixture", + arguments: { value: "literal ; $HOME" }, + }; + const verify = async ( + id: string, + key: string | undefined, + marker: string, + cwd: string, + identity: string + ) => { + const catalog = await result(await mcp(request, id, key, "tools/list")); + expect(catalog.tools).toContainEqual( + expect.objectContaining({ name: "repo_fixture", description: marker }) + ); + const invoked = await result( + await mcp(request, id, key, "tools/call", call) + ); + expect(invoked.structuredContent).toMatchObject({ + exitCode: 0, + stdout: [marker, cwd, identity, id, call.arguments.value].join("|"), + }); + await testInfo.attach(marker, { + body: invoked.structuredContent.stdout, + contentType: "text/plain", + }); + }; + + try { + const alpha = await enrollViaUi(page, request, "alpha"); + const configured = state.runners.alpha.workspaceDir; + seedGuest("alpha", configured, "configured"); + const configuredId = await start(`runner://${alpha}/${state.workspace}`); + const configuredToken = token("alpha", configuredId); + await verify( + configuredId, + configuredToken, + "configured", + configured, + "1500:1500" + ); + + const approved = await result( + await mcp(request, configuredId, configuredToken, "tools/call", { + name: "repo_runner_workspace", + arguments: {}, + }) + ); + expect(approved.isError).toBeUndefined(); + expect(guest("alpha", `cat '${configured}/repo-op'`).trim()).toBe("ran"); + + const scratch = await enrollViaUi(page, request, "scratch"); + const managedId = await start(`runner://${scratch}/@session`); + const managed = `/var/lib/runner/sessions/${managedId}`; + seedGuest("scratch", managed, "managed", 23); + const managedToken = token("scratch", managedId); + await verify(managedId, managedToken, "managed", managed, "1500:1500"); + expect( + ( + await mcp(request, managedId, configuredToken, "tools/call", call) + ).status() + ).toBe(403); + expect( + await result(await mcp(request, managedId, undefined, "tools/call", call)) + ).toMatchObject({ isError: true }); + + const moved = "/tmp/checkout-command-moved"; + seedGuest("scratch", moved, "moved"); + for (let repeat = 0; repeat < 2; repeat++) { + const res = await request.patch(`/api/v1/agents/${managedId}/workspace`, { + headers: authHeaders(), + data: { path: moved }, + }); + expect(res.ok(), await res.text()).toBe(true); + expect((await res.json()).agent.workspacePath).toBe(moved); + } + await verify(managedId, managedToken, "moved", moved, "1500:1500"); + const invokeMoved = (name: string) => + mcp(request, managedId, managedToken, "tools/call", { + name, + arguments: {}, + }).then(result); + const bounded = await invokeMoved("repo_bounded"); + expect(bounded.structuredContent).toMatchObject({ + exitCode: 17, + truncated: true, + }); + expect( + Buffer.byteLength(bounded.structuredContent.stdout) + ).toBeLessThanOrEqual(64 * 1024); + const timedOut = await invokeMoved("repo_deadline"); + expect(timedOut).toMatchObject({ + isError: true, + content: [{ text: expect.stringMatching(/timed out/i) }], + }); + const processState = guest( + "scratch", + `ps -o stat= -p "$(cat '${moved}/deadline.pid')" || true` + ).trim(); + expect(processState).toMatch(/^(?:Z.*)?$/); + await stop(managedId); + await stop(managedId); + for (const dir of [managed, moved]) { + expect(guest("scratch", `cat '${dir}/hook.log'`).trim()).toBe( + `${dir}|1500:1500|${managedId}` + ); + } + await stop(configuredId); + expect(guest("alpha", `cat '${configured}/hook.log'`).trim()).toBe( + `${configured}|1500:1500|${configuredId}` + ); + + mkdirSync(path.join(native, ".dispatch")); + writeFileSync( + path.join(native, ".dispatch/tools.json"), + manifest("native") + ); + const localId = await start(native); + await verify( + localId, + undefined, + "native", + native, + `${process.getuid!()}:${process.getgid!()}` + ); + + const revoked = await request.delete(`${RUNNERS_API}/${alpha}`, { + headers: authHeaders(), + }); + expect(revoked.ok(), await revoked.text()).toBe(true); + expect( + ( + await mcp(request, configuredId, configuredToken, "tools/call", call) + ).status() + ).toBe(403); + } catch (error) { + for (const name of ["alpha", "scratch"] as const) { + await testInfo.attach(name + " runner diagnostics", { + body: guestDiagnostics(name), + contentType: "text/plain", + }); + } + throw error; + } finally { + for (const id of agents.reverse()) await deleteAgentViaAPI(request, id); + rmSync(native, { recursive: true, force: true }); + } +}); diff --git a/packages/runner-protocol/src/checkout-command.ts b/packages/runner-protocol/src/checkout-command.ts new file mode 100644 index 000000000..54640ccdf --- /dev/null +++ b/packages/runner-protocol/src/checkout-command.ts @@ -0,0 +1,86 @@ +import { isCheckoutQuery } from "./checkout.js"; +import { isRecord } from "./validation.js"; + +export const CHECKOUT_COMMAND_TIMEOUT_MS = 15_000; +export const MAX_CHECKOUT_COMMAND_OUTPUT_BYTES = 64 * 1024; +export const MAX_CHECKOUT_COMMAND_FILE_BYTES = 256 * 1024; +export const MAX_CHECKOUT_COMMAND_REPLY_BYTES = 4 * 1024 * 1024; + +export type CheckoutCommand = { + checkout: "effective" | "launch" | "moved"; + path: string; +} & ({ kind: "read" } | { kind: "run"; state: string; argv: string[] }); + +export type CheckoutCommandFile = { content: string; state: string }; +export type CheckoutCommandResult = { + exitCode: number; + stdout: string; + stderr: string; + truncated: boolean; +}; + +const utf8 = new TextEncoder(); +const fits = (value: string, limit: number) => + value.length <= limit && utf8.encode(value).length <= limit; + +const digest = (value: unknown) => + typeof value === "string" && /^[a-f0-9]{64}$/.test(value); + +export function isCheckoutCommand(value: unknown): value is CheckoutCommand { + if ( + !isRecord(value) || + !isCheckoutQuery({ + kind: "readFile", + path: value.path, + }) || + (value.checkout !== "effective" && + value.checkout !== "launch" && + value.checkout !== "moved") + ) + return false; + if (value.kind === "read") return Object.keys(value).length === 3; + return ( + value.kind === "run" && + Object.keys(value).length === 5 && + digest(value.state) && + Array.isArray(value.argv) && + value.argv.length > 0 && + value.argv.length <= 256 && + Boolean(value.argv[0]) && + value.argv.every( + (arg) => + typeof arg === "string" && !arg.includes("\0") && fits(arg, 16 * 1024) + ) && + fits(JSON.stringify(value.argv), 64 * 1024) + ); +} + +export function isCheckoutCommandFile( + value: unknown +): value is CheckoutCommandFile | null { + return ( + value === null || + (isRecord(value) && + typeof value.content === "string" && + fits(value.content, MAX_CHECKOUT_COMMAND_FILE_BYTES) && + digest(value.state)) + ); +} + +export function isCheckoutCommandResult( + value: unknown +): value is CheckoutCommandResult { + return ( + isRecord(value) && + typeof value.exitCode === "number" && + Number.isInteger(value.exitCode) && + value.exitCode >= 0 && + value.exitCode <= 255 && + [value.stdout, value.stderr].every( + (output) => + typeof output === "string" && + fits(output, MAX_CHECKOUT_COMMAND_OUTPUT_BYTES) + ) && + typeof value.truncated === "boolean" + ); +} diff --git a/packages/runner-protocol/src/connection.ts b/packages/runner-protocol/src/connection.ts index f3d74f316..a0e6200cb 100644 --- a/packages/runner-protocol/src/connection.ts +++ b/packages/runner-protocol/src/connection.ts @@ -53,13 +53,16 @@ export class RunnerConnection { { openChannel = false, onProgress, + signal, }: { openChannel?: boolean; + signal?: AbortSignal; onProgress?: (progress: LaunchProgress) => void; } = {} ) { if (this.closed) throw new RunnerUnavailable("The runner connection is closed."); + if (command.kind === "checkoutCommand") signal?.throwIfAborted(); const id = crypto.randomUUID(); const channel = openChannel ? hostChannel(id, this.send, () => this.channels.delete(id)) @@ -74,7 +77,11 @@ export class RunnerConnection { ) this.progress.set(id, onProgress); try { - const value = await this.sendRequest(id, command); + const value = await this.sendRequest( + id, + command, + command.kind === "checkoutCommand" ? signal : undefined + ); return { value, channel }; } catch (error) { channel?.destroy(); @@ -84,7 +91,8 @@ export class RunnerConnection { private sendRequest( id: string, - command: Command + command: Command, + signal?: AbortSignal ): Promise { // Repository fetches and engine package installs can run for minutes. const timeoutMs = @@ -100,6 +108,7 @@ export class RunnerConnection { return new Promise((resolve, reject) => { const finish = (frame?: ResultFrame) => { clearTimeout(timer); + signal?.removeEventListener("abort", cancel); this.pending.delete(id); this.progress.delete(id); if (!frame) @@ -113,7 +122,26 @@ export class RunnerConnection { else if (frame.error) reject(new Error(frame.error)); else resolve(frame.value); }; - const timer = setTimeout(finish, timeoutMs); + const requestCancel = () => { + try { + this.send({ type: "cancel_checkout_command", id }); + } catch { + // The connection may already have failed. + } + }; + const cancel = () => { + requestCancel(); + finish({ + type: "result", + id, + error: "Checkout command cancelled.", + }); + }; + const timer = setTimeout(() => { + if (command.kind === "checkoutCommand") requestCancel(); + finish(); + }, timeoutMs); + signal?.addEventListener("abort", cancel, { once: true }); this.pending.set(id, finish); try { this.send({ type: "request", id, command }); diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 61044ea7b..4447bc660 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -1,3 +1,4 @@ +import { isCheckoutCommand, type CheckoutCommand } from "./checkout-command.js"; import { isSessionFileOperation, type SessionFileOperation, @@ -76,6 +77,7 @@ export type SessionOperation = kind: "sessionCheckout"; operation: { kind: "describe" } | { kind: "select"; path: string | null }; } + | { agentId: string; kind: "checkoutCommand"; operation: CheckoutCommand } | { agentId: string; kind: "checkoutRelease"; operation: CheckoutRelease } | { agentId: string; kind: "repo" }; @@ -102,6 +104,7 @@ export type ReadyFrame = { pullRequestEvidence?: true; checkoutInspection?: true; checkoutMetadata?: true; + checkoutCommands?: true; defaultBranchFiles?: true; checkoutViews?: true; sharedWorktree?: true; @@ -133,6 +136,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { workspaces: frame.workspaces, ...(frame.checkoutViews === true && { checkoutViews: true }), ...(frame.defaultBranchFiles === true && { defaultBranchFiles: true }), + ...(frame.checkoutCommands === true && { checkoutCommands: true }), ...(frame.checkoutMetadata === true && { checkoutMetadata: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), @@ -157,6 +161,7 @@ export type ChannelFrame = export type ServiceFrame = | { type: "accept_health"; engineInventory?: true } | { type: "request"; id: string; command: Command } + | { type: "cancel_checkout_command"; id: string } | ChannelFrame; export type ResultFrame = { @@ -319,6 +324,8 @@ function isCommand(value: unknown): value is Command { ); case "sessionFile": return isSessionFileOperation(value.operation); + case "checkoutCommand": + return isCheckoutCommand(value.operation); case "checkoutRelease": return isCheckoutRelease(value.operation); case "sessionCheckout": @@ -378,6 +385,7 @@ function isServiceFrame(value: unknown): value is ServiceFrame { ); case "request": return isOpaqueId(value.id) && isCommand(value.command); + case "cancel_checkout_command": case "close": return isOpaqueId(value.id); case "data": diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index cca55243b..532414b5c 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -7,3 +7,4 @@ export * from "./checkout.js"; export * from "./github.js"; export * from "./checkout-view.js"; export * from "./session-files.js"; +export * from "./checkout-command.js"; From a48474988d70bdb14a77ce916db842a85d2c4a40 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 17:29:55 -0700 Subject: [PATCH 143/642] Route native repository commands through the built-in runner --- .agents/owners.json | 1 + apps/server/src/agents/archive.ts | 13 +- .../src/agents/checkout-command-executor.ts | 102 ++++++++++++++ apps/server/src/agents/checkout-commands.ts | 28 ++-- apps/server/src/agents/checkout-inspection.ts | 9 +- apps/server/src/agents/lifecycle-hooks.ts | 133 ++++++------------ apps/server/src/agents/local-runner.ts | 75 +++++++++- apps/server/src/agents/manager.ts | 34 +++-- .../src/agents/remote/checkout-command.ts | 95 +------------ apps/server/src/server/mcp-checkout.ts | 36 +++-- apps/server/src/shared/mcp/server.ts | 11 +- apps/server/test/agent-archive.test.ts | 2 +- apps/server/test/lifecycle-hooks.test.ts | 14 +- apps/server/test/mcp-routes.test.ts | 2 +- apps/server/test/mcp-tool-invoked.test.ts | 100 ++++++++++++- .../server/test/repo-tool-environment.test.ts | 9 +- docs/04-agent-lifecycle.md | 8 +- docs/design/remote-runner-prototype.md | 8 +- e2e/remote-runner/checkout-command.spec.ts | 58 +++++++- plugins/dispatch/skills/repo-tools/SKILL.md | 4 +- 20 files changed, 483 insertions(+), 259 deletions(-) create mode 100644 apps/server/src/agents/checkout-command-executor.ts diff --git a/.agents/owners.json b/.agents/owners.json index ba1586fcd..4043f8252 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -205,6 +205,7 @@ "apps/server/src/server.ts", "plugins/dispatch/**", "apps/server/test/*mcp*", + "apps/server/test/repo-tool-environment.test.ts", "apps/server/test/tasks-service.test.ts", "packages/shared/src/mcp-inventory-types.ts", "apps/server/src/agents/acp/mcp-inventory.ts" diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index 1669a1363..e667e1593 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -12,6 +12,7 @@ import { type LocalArchiveRunner, } from "./archive-checkout.js"; import type { RemoteRunnerService } from "./remote/service.js"; +import type { CheckoutCommandRunners } from "./checkout-commands.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; import { AgentError } from "./errors.js"; import type { AgentRuntime } from "./runtime.js"; @@ -26,7 +27,7 @@ export type ArchiveDeps = { pool: Pool; logger: FastifyBaseLogger; runtime: AgentRuntime; - localRunner: LocalArchiveRunner; + localRunner: LocalArchiveRunner & CheckoutCommandRunners["local"]; remote?: RemoteRunnerService; diffStatsRefresher: { clear(agentId: string): void } | null; getAgent: (id: string) => Promise; @@ -215,7 +216,10 @@ export async function executeArchive( // Phase: stopping — tear down session without changing agent status const t = Date.now(); try { - await runLifecycleHook("stop", agent, logger, deps.remote).catch((err) => + await runLifecycleHook("stop", agent, logger, { + local: deps.localRunner, + remote: deps.remote, + }).catch((err) => logger.warn( { err, agentId: id }, "Stop hook failed during archive; continuing" @@ -355,7 +359,10 @@ export async function deleteAgentDirect( // Not stopAgent: it writes `stopping`/`stopped`, releasing the claim above // and letting a fresh archive take this agent mid-teardown. try { - await runLifecycleHook("stop", agent, logger, deps.remote).catch((err) => + await runLifecycleHook("stop", agent, logger, { + local: deps.localRunner, + remote: deps.remote, + }).catch((err) => logger.warn( { err, agentId: id }, "Stop hook failed during delete; continuing" diff --git a/apps/server/src/agents/checkout-command-executor.ts b/apps/server/src/agents/checkout-command-executor.ts new file mode 100644 index 000000000..d89857d63 --- /dev/null +++ b/apps/server/src/agents/checkout-command-executor.ts @@ -0,0 +1,102 @@ +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { constants } from "node:os"; +import { + MAX_CHECKOUT_COMMAND_OUTPUT_BYTES, + type CheckoutCommand, + type CheckoutCommandFile, + type CheckoutCommandResult, +} from "@dispatch/runner-protocol"; +import type { Readable } from "node:stream"; +import { repoCommandEnvironment } from "../shared/lib/tool-environment.js"; + +function capture(stream: Readable) { + const limit = MAX_CHECKOUT_COMMAND_OUTPUT_BYTES; + const buffer = Buffer.alloc(limit); + let used = 0; + let truncated = false; + stream.on("data", (chunk: Buffer) => { + const size = chunk.copy(buffer, used); + used += size; + if (size < chunk.length) truncated = true; + }); + return () => { + const decoded = buffer.toString("utf8", 0, used).trim(); + const encoded = Buffer.from(decoded); + return { + text: new TextDecoder().decode(encoded.subarray(0, limit), { + stream: true, + }), + truncated: truncated || encoded.length > limit, + }; + }; +} + +export async function executeCheckoutCommand( + cwd: string, + session: string, + operation: CheckoutCommand, + read: (path: string) => Promise<{ root: string; content: string | null }>, + cancellation?: AbortSignal +): Promise { + cancellation?.throwIfAborted(); + const { root, content } = await read(operation.path); + cancellation?.throwIfAborted(); + const state = createHash("sha256") + .update( + JSON.stringify([ + session, + operation.checkout, + cwd, + root, + operation.path, + content, + ]) + ) + .digest("hex"); + if (operation.kind === "read") + return content === null ? null : { content, state }; + if (content === null || operation.state !== state) + throw new Error( + "Checkout command authorization is stale. Read the checkout file again." + ); + + const [command, ...args] = operation.argv; + const child = spawn(command!, args, { + cwd: root, + detached: cancellation !== undefined, + env: repoCommandEnvironment(session), + stdio: ["ignore", "pipe", "pipe"], + }); + const stdout = capture(child.stdout); + const stderr = capture(child.stderr); + return new Promise((resolve, reject) => { + const cancel = () => { + if (!child.pid) return; + try { + process.kill(-child.pid, "SIGKILL"); + } catch { + // The process group may already have exited. + } + }; + cancellation?.addEventListener("abort", cancel, { once: true }); + child.once("error", () => + reject(new Error("Could not start checkout command.")) + ); + child.once("close", (code, signal) => { + cancellation?.removeEventListener("abort", cancel); + if (cancellation?.aborted) { + reject(cancellation.reason); + return; + } + const output = stdout(); + const errors = stderr(); + resolve({ + exitCode: code ?? (signal ? 128 + constants.signals[signal] : 1), + stdout: output.text, + stderr: errors.text, + truncated: output.truncated || errors.truncated, + }); + }); + }); +} diff --git a/apps/server/src/agents/checkout-commands.ts b/apps/server/src/agents/checkout-commands.ts index e23235255..3bd952b3a 100644 --- a/apps/server/src/agents/checkout-commands.ts +++ b/apps/server/src/agents/checkout-commands.ts @@ -7,35 +7,43 @@ import { type CheckoutCommandResult, } from "@dispatch/runner-protocol"; import type { RemoteRunnerService } from "./remote/service.js"; +import type { createLocalRunner } from "./local-runner.js"; import type { AgentRecord } from "./types.js"; +export type CheckoutCommandRunners = { + local: Pick, "requestSession">; + remote?: RemoteRunnerService; +}; + export async function requestCheckoutCommand( - remote: RemoteRunnerService | undefined, + runners: CheckoutCommandRunners, agent: AgentRecord, operation: Extract, signal?: AbortSignal ): Promise; export async function requestCheckoutCommand( - remote: RemoteRunnerService | undefined, + runners: CheckoutCommandRunners, agent: AgentRecord, operation: Extract, signal?: AbortSignal ): Promise; export async function requestCheckoutCommand( - remote: RemoteRunnerService | undefined, + runners: CheckoutCommandRunners, agent: AgentRecord, operation: CheckoutCommand, signal?: AbortSignal ) { const placement = remotePlacement(agent.cwd); - if (!remote || !placement) + const request = { + kind: "checkoutCommand", + agentId: agent.id, + operation, + } as const; + if (placement && !runners.remote) throw new Error("The session runner is unavailable."); - const { value } = await remote.requestSession( - placement, - { kind: "checkoutCommand", agentId: agent.id, operation }, - undefined, - signal - ); + const { value } = await (placement + ? runners.remote!.requestSession(placement, request, undefined, signal) + : runners.local.requestSession(request, { checkout: agent, signal })); let result: unknown; try { if (typeof value === "string") result = JSON.parse(value); diff --git a/apps/server/src/agents/checkout-inspection.ts b/apps/server/src/agents/checkout-inspection.ts index ca1d77110..a706b876c 100644 --- a/apps/server/src/agents/checkout-inspection.ts +++ b/apps/server/src/agents/checkout-inspection.ts @@ -506,9 +506,14 @@ async function inspectionRoot(cwd: string, requireGit: boolean) { export async function readCheckoutCommandFile( cwd: string, file: string, - configuredRoot?: string + { + configuredRoot, + exact = false, + }: { configuredRoot?: string; exact?: boolean } = {} ) { - const { root } = await inspectionRoot(cwd, false); + const root = exact + ? await realpath(cwd) + : (await inspectionRoot(cwd, false)).root; if (configuredRoot) { const relative = path.relative(configuredRoot, root); if ( diff --git a/apps/server/src/agents/lifecycle-hooks.ts b/apps/server/src/agents/lifecycle-hooks.ts index 9fc9fd626..b1ae1f34b 100644 --- a/apps/server/src/agents/lifecycle-hooks.ts +++ b/apps/server/src/agents/lifecycle-hooks.ts @@ -1,12 +1,10 @@ -import { remotePlacement } from "./remote/protocol.js"; import type { FastifyBaseLogger } from "fastify"; -import { repoCommandEnvironment } from "../shared/lib/tool-environment.js"; -import { runCommand } from "../shared/lib/run-command.js"; -import { requestCheckoutCommand } from "./checkout-commands.js"; -import type { RemoteRunnerService } from "./remote/service.js"; import { - loadRepoHooks, + requestCheckoutCommand, + type CheckoutCommandRunners, +} from "./checkout-commands.js"; +import { parseRepoHooks, parseRepoToolFile, REPO_TOOL_MANIFEST_PATH, @@ -33,102 +31,51 @@ export type LifecycleHookName = "stop"; * * Runs with `DISPATCH_AGENT_ID` exported in env so the hook can * disambiguate which agent triggered it. 15-second hard timeout. - * - * Lives outside the manager because the operation isn't manager-state- - * coupled — it just shells out to a repo-defined command, given an - * agent record. Keeping it standalone makes it the natural home for - * additional hook names without growing the manager class. */ export async function runLifecycleHook( hookName: LifecycleHookName, agent: AgentRecord, logger: FastifyBaseLogger, - remote?: RemoteRunnerService + runners: CheckoutCommandRunners ): Promise { - if (remotePlacement(agent.cwd)) { - for (const checkout of ["launch", "moved"] as const) { - try { - const target = { checkout, path: REPO_TOOL_MANIFEST_PATH }; - const file = await requestCheckoutCommand(remote, agent, { - ...target, - kind: "read", - }); - const hook = - file && parseRepoHooks(parseRepoToolFile(file.content))[hookName]; - if (!hook) continue; - const result = await requestCheckoutCommand(remote, agent, { - ...target, - kind: "run", - state: file.state, - argv: hook.command, - }); - if (result.exitCode !== 0) { - logger.warn( - { - agentId: agent.id, - hook: hookName, - checkout, - exitCode: result.exitCode, - stderr: result.stderr, - truncated: result.truncated, - }, - "Lifecycle hook exited with non-zero code" - ); - } - } catch (err) { + for (const checkout of ["launch", "moved"] as const) { + try { + const target = { checkout, path: REPO_TOOL_MANIFEST_PATH }; + const file = await requestCheckoutCommand(runners, agent, { + ...target, + kind: "read", + }); + const hook = + file && parseRepoHooks(parseRepoToolFile(file.content))[hookName]; + if (!hook) continue; + logger.info( + { agentId: agent.id, hook: hookName, checkout }, + "Running lifecycle hook" + ); + const result = await requestCheckoutCommand(runners, agent, { + ...target, + kind: "run", + state: file.state, + argv: hook.command, + }); + if (result.exitCode !== 0) { logger.warn( - { err, agentId: agent.id, hook: hookName, checkout }, - "Runner lifecycle hook failed; continuing shutdown" + { + agentId: agent.id, + hook: hookName, + checkout, + exitCode: result.exitCode, + stderr: result.stderr, + truncated: result.truncated, + }, + "Lifecycle hook exited with non-zero code" ); } + } catch (err) { + logger.warn( + { err, agentId: agent.id, hook: hookName, checkout }, + "Runner lifecycle hook failed; continuing shutdown" + ); } - return; - } - // An agent that moved runs the hook in both places: what it started in - // the launch checkout and what it started in its workspace (a dev stack, - // say) each belong to that checkout's own hook. - const roots = new Set( - [agent.worktreePath ?? agent.cwd, agent.workspacePath].filter( - (root): root is string => Boolean(root) - ) - ); - for (const root of roots) { - await runLifecycleHookIn(hookName, agent, root, logger); - } -} - -async function runLifecycleHookIn( - hookName: LifecycleHookName, - agent: AgentRecord, - repoRoot: string, - logger: FastifyBaseLogger -): Promise { - const hooks = await loadRepoHooks(repoRoot); - const hook = hooks[hookName]; - if (!hook) return; - - const [command, ...args] = hook.command; - logger.info( - { agentId: agent.id, hook: hookName, command: hook.command, repoRoot }, - "Running lifecycle hook" - ); - - const result = await runCommand(command, args, { - cwd: repoRoot, - env: repoCommandEnvironment(agent.id), - timeoutMs: 15_000, - }); - - if (result.exitCode !== 0) { - logger.warn( - { - agentId: agent.id, - hook: hookName, - repoRoot, - exitCode: result.exitCode, - stderr: result.stderr, - }, - "Lifecycle hook exited with non-zero code" - ); } } diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index 2c3f88f13..47e984771 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -14,6 +14,10 @@ import path from "node:path"; import type { Duplex } from "node:stream"; import type { FastifyBaseLogger } from "fastify"; import { + CHECKOUT_COMMAND_TIMEOUT_MS, + isCheckoutCommand, + remotePlacement, + type SessionOperation, isSessionFileName, isSessionFilePath, type SessionLifecycleOperation, @@ -41,18 +45,32 @@ import { import { resolveWorkspace } from "./workspace-target.js"; import { resolveProjectRoot } from "../projects/resolve-root.js"; import { localCheckoutRelease } from "./local-runner-checkout.js"; +import { executeCheckoutCommand } from "./checkout-command-executor.js"; +import { readCheckoutCommandFile } from "./checkout-inspection.js"; +import type { AgentRecord } from "./types.js"; import { inferRepositoryUrl } from "./remote/repository.js"; export type LocalLaunchSettings = Pick< HostLaunch, "cwd" | "env" | "bins" | "pathPrefix" >; +type CheckoutCommandOperation = Extract< + SessionOperation, + { kind: "checkoutCommand" } +>; +type LocalCheckoutSettings = { + checkout: Pick; + signal?: AbortSignal; +}; + export type SessionResult = { value?: string | boolean; channel?: Duplex; launchExited?: () => boolean; }; +// Native tools can start or rebuild project services before returning. +const NATIVE_REPO_TOOL_TIMEOUT_MS = 5 * 60_000; const STOP_GRACE_MS = 8_000; const KILL_GRACE_MS = 2_000; const LOG_TAIL_LINES = 20; @@ -293,16 +311,67 @@ export function createLocalRunner( } async function requestSession( - operation: SessionLifecycleOperation, - settings?: LocalLaunchSettings + operation: SessionLifecycleOperation | CheckoutCommandOperation, + settings?: LocalLaunchSettings | LocalCheckoutSettings ): Promise { const { agentId } = operation; const dir = stateDir(agentId); switch (operation.kind) { case "launch": - if (!settings || operation.launch.agentId !== agentId) + if ( + !settings || + !("cwd" in settings) || + operation.launch.agentId !== agentId + ) throw new Error("Missing or mismatched native launch settings"); return launch({ ...operation.launch, ...settings }); + case "checkoutCommand": { + if ( + !settings || + !("checkout" in settings) || + settings.checkout.id !== agentId || + remotePlacement(settings.checkout.cwd) || + !isCheckoutCommand(operation.operation) + ) + throw new Error("Invalid native checkout command binding."); + const { checkout, signal } = settings; + const { operation: command } = operation; + const launch = checkout.worktreePath ?? checkout.cwd; + const moved = checkout.workspacePath; + const cwd = command.checkout === "launch" ? launch : (moved ?? launch); + if (command.checkout === "moved" && (!moved || moved === launch)) { + if (command.kind === "run") + throw new Error("The moved checkout is no longer selected."); + return { value: "null" }; + } + const deadline = new AbortController(); + const timer = setTimeout( + () => deadline.abort(new Error("Checkout command timed out.")), + command.checkout === "effective" + ? NATIVE_REPO_TOOL_TIMEOUT_MS + : CHECKOUT_COMMAND_TIMEOUT_MS + ); + try { + return { + value: JSON.stringify( + await executeCheckoutCommand( + cwd, + agentId, + command, + (file) => + readCheckoutCommandFile(cwd, file, { + exact: command.checkout !== "effective", + }), + signal + ? AbortSignal.any([signal, deadline.signal]) + : deadline.signal + ) + ), + }; + } finally { + clearTimeout(timer); + } + } case "attach": { const channel = await new Promise((resolve, reject) => { const socket = net.createConnection(hostFile(dir, "socket")); diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 0c32e2542..fa37d0ef7 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -2817,12 +2817,14 @@ export class AgentManager { await this.setAgentStatus(id, "stopping", null); // Run repo-defined stop hook (best-effort, non-blocking) - await runLifecycleHook("stop", agent, this.logger, this.remote).catch( - (err) => - this.logger.warn( - { err, agentId: id }, - "Stop hook failed; continuing shutdown" - ) + await runLifecycleHook("stop", agent, this.logger, { + local: this.localRunner, + remote: this.remote, + }).catch((err) => + this.logger.warn( + { err, agentId: id }, + "Stop hook failed; continuing shutdown" + ) ); try { @@ -3022,22 +3024,26 @@ export class AgentManager { ); } - readRemoteRepoManifest(agent: AgentRecord) { - return requestCheckoutCommand(this.remote, agent, { - kind: "read", - checkout: "effective", - path: REPO_TOOL_MANIFEST_PATH, - }); + readRepoManifest(agent: AgentRecord) { + return requestCheckoutCommand( + { local: this.localRunner, remote: this.remote }, + agent, + { + kind: "read", + checkout: "effective", + path: REPO_TOOL_MANIFEST_PATH, + } + ); } - runRemoteRepoCommand( + runRepoCommand( agent: AgentRecord, state: string, argv: string[], signal?: AbortSignal ) { return requestCheckoutCommand( - this.remote, + { local: this.localRunner, remote: this.remote }, agent, { kind: "run", diff --git a/apps/server/src/agents/remote/checkout-command.ts b/apps/server/src/agents/remote/checkout-command.ts index 230af86b4..4aa563c2e 100644 --- a/apps/server/src/agents/remote/checkout-command.ts +++ b/apps/server/src/agents/remote/checkout-command.ts @@ -1,94 +1,7 @@ -import { spawn } from "node:child_process"; -import { createHash } from "node:crypto"; -import { constants } from "node:os"; -import { - isCheckoutCommand, - MAX_CHECKOUT_COMMAND_OUTPUT_BYTES, - type CheckoutCommand, - type CheckoutCommandFile, - type CheckoutCommandResult, -} from "@dispatch/runner-protocol"; -import type { Readable } from "node:stream"; -import { repoCommandEnvironment } from "../../shared/lib/tool-environment.js"; +import { isCheckoutCommand } from "@dispatch/runner-protocol"; +import { executeCheckoutCommand } from "../checkout-command-executor.js"; import { readCheckoutCommandFile } from "../checkout-inspection.js"; -function capture(stream: Readable) { - const limit = MAX_CHECKOUT_COMMAND_OUTPUT_BYTES; - const buffer = Buffer.alloc(limit); - let used = 0; - let truncated = false; - stream.on("data", (chunk: Buffer) => { - const size = chunk.copy(buffer, used); - used += size; - if (size < chunk.length) truncated = true; - }); - return () => { - const decoded = buffer.toString("utf8", 0, used).trim(); - const encoded = Buffer.from(decoded); - return { - text: new TextDecoder().decode(encoded.subarray(0, limit), { - stream: true, - }), - truncated: truncated || encoded.length > limit, - }; - }; -} - -export async function executeCheckoutCommand( - cwd: string, - session: string, - operation: CheckoutCommand, - configuredRoot?: string -): Promise { - const { root, content } = await readCheckoutCommandFile( - cwd, - operation.path, - configuredRoot - ); - const state = createHash("sha256") - .update( - JSON.stringify([ - session, - operation.checkout, - cwd, - root, - operation.path, - content, - ]) - ) - .digest("hex"); - if (operation.kind === "read") - return content === null ? null : { content, state }; - if (content === null || operation.state !== state) - throw new Error( - "Checkout command authorization is stale. Read the checkout file again." - ); - - const [command, ...args] = operation.argv; - const child = spawn(command!, args, { - cwd: root, - env: repoCommandEnvironment(session), - stdio: ["ignore", "pipe", "pipe"], - }); - const stdout = capture(child.stdout); - const stderr = capture(child.stderr); - return new Promise((resolve, reject) => { - child.once("error", () => - reject(new Error("Could not start checkout command.")) - ); - child.once("close", (code, signal) => { - const output = stdout(); - const errors = stderr(); - resolve({ - exitCode: code ?? (signal ? 128 + constants.signals[signal] : 1), - stdout: output.text, - stderr: errors.text, - truncated: output.truncated || errors.truncated, - }); - }); - }); -} - export async function runCheckoutCommandCli( cwd: string, session: string, @@ -111,7 +24,9 @@ export async function runCheckoutCommandCli( throw new Error("Invalid checkout command."); process.stdout.write( JSON.stringify( - await executeCheckoutCommand(cwd, session, operation, configuredRoot) + await executeCheckoutCommand(cwd, session, operation, (file) => + readCheckoutCommandFile(cwd, file, { configuredRoot }) + ) ) ); } catch (error) { diff --git a/apps/server/src/server/mcp-checkout.ts b/apps/server/src/server/mcp-checkout.ts index daa9549b9..d2aaed699 100644 --- a/apps/server/src/server/mcp-checkout.ts +++ b/apps/server/src/server/mcp-checkout.ts @@ -8,7 +8,7 @@ import { } from "../shared/mcp/repo-tools.js"; export async function readAgentCheckoutFile( - manager: AgentManager, + manager: Pick, agent: AgentRecord, path: string ) { @@ -35,18 +35,21 @@ export async function mcpCheckoutRoots( } export async function discoverRepoTools( - manager: AgentManager, + manager: Pick< + AgentManager, + "inspectCheckout" | "readRepoManifest" | "runRepoCommand" + >, agent: AgentRecord, allowRemoteCommands: boolean ) { const remote = remotePlacement(agent.cwd); let unavailable: RunnerCapabilityUnavailable | undefined; - if (remote && allowRemoteCommands) { + if (!remote || allowRemoteCommands) { let file; try { - file = await manager.readRemoteRepoManifest(agent); + file = await manager.readRepoManifest(agent); } catch (error) { - if (!(error instanceof RunnerCapabilityUnavailable)) return []; + if (!remote || !(error instanceof RunnerCapabilityUnavailable)) return []; // Keep discovery on older peers and surface their capability error on call. unavailable = error; } @@ -54,7 +57,7 @@ export async function discoverRepoTools( return parseRepoTools( parseRepoToolFile(file.content), (argv, _cwd, _id, signal) => - manager.runRemoteRepoCommand(agent, file.state, argv, signal) + manager.runRepoCommand(agent, file.state, argv, signal) ); } if (!unavailable) return []; @@ -70,17 +73,12 @@ export async function discoverRepoTools( } catch { return []; } - return parseRepoTools( - parseRepoToolFile(content), - remote - ? async () => { - throw ( - unavailable ?? - new Error( - "Checkout commands require the selected session's MCP credential." - ) - ); - } - : undefined - ); + return parseRepoTools(parseRepoToolFile(content), async () => { + throw ( + unavailable ?? + new Error( + "Checkout commands require the selected session's MCP credential." + ) + ); + }); } diff --git a/apps/server/src/shared/mcp/server.ts b/apps/server/src/shared/mcp/server.ts index d81a26cd9..8e6aa26d2 100644 --- a/apps/server/src/shared/mcp/server.ts +++ b/apps/server/src/shared/mcp/server.ts @@ -38,11 +38,7 @@ import { registerPersonaInteractionTools, type LaunchPersonaAgentType, } from "./persona-interaction-tools.js"; -import { - loadRepoTools, - type RepoToolDefinition, - type RepoToolParam, -} from "./repo-tools.js"; +import { type RepoToolDefinition, type RepoToolParam } from "./repo-tools.js"; import { jsonText } from "./response.js"; import { toToolError } from "./tool-error.js"; import { registerStreamTools } from "./stream-tools.js"; @@ -656,9 +652,8 @@ export async function createDispatchMcpServer( } const toolsRoot = context.toolsRoot ?? context.worktreeRoot ?? context.repoRoot; - if (context.agent && toolsRoot) { - const allRepoTools = await (context.discoverRepoTools?.() ?? - loadRepoTools(toolsRoot)); + if (context.agent && toolsRoot && context.discoverRepoTools) { + const allRepoTools = await context.discoverRepoTools(); const scope = context.toolScope ?? "agent"; const repoTools = allRepoTools.filter( (tool) => diff --git a/apps/server/test/agent-archive.test.ts b/apps/server/test/agent-archive.test.ts index 53fad094c..a793286af 100644 --- a/apps/server/test/agent-archive.test.ts +++ b/apps/server/test/agent-archive.test.ts @@ -614,7 +614,7 @@ describe("executeArchive", () => { "stop", agent, expect.anything(), - undefined + { local: deps.localRunner, remote: undefined } ); }); diff --git a/apps/server/test/lifecycle-hooks.test.ts b/apps/server/test/lifecycle-hooks.test.ts index f27afd9bf..a2398ace2 100644 --- a/apps/server/test/lifecycle-hooks.test.ts +++ b/apps/server/test/lifecycle-hooks.test.ts @@ -4,6 +4,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createLocalRunner } from "../src/agents/local-runner.js"; import { runLifecycleHook } from "../src/agents/lifecycle-hooks.js"; import type { RemoteRunnerService } from "../src/agents/remote/service.js"; import type { AgentRecord } from "../src/agents/types.js"; @@ -50,7 +51,8 @@ describe("runLifecycleHook", () => { worktreePath: launch, workspacePath: moved, } as AgentRecord, - logger + logger, + { local: createLocalRunner(root, logger) } ); await expect(readFile(path.join(launch, "stopped"), "utf8")).resolves.toBe( @@ -79,7 +81,8 @@ describe("runLifecycleHook", () => { worktreePath: null, workspacePath: null, } as AgentRecord, - logger + logger, + { local: createLocalRunner(root, logger) } ); await expect(readFile(path.join(launch, "stopped"), "utf8")).resolves.toBe( @@ -111,7 +114,12 @@ it("reports a runner hook failure and still runs the moved checkout on each tear const agent = { id: "session", cwd: "runner://machine/work" } as AgentRecord; for (let attempt = 0; attempt < 2; attempt++) { await expect( - runLifecycleHook("stop", agent, { ...logger, warn }, remote) + runLifecycleHook( + "stop", + agent, + { ...logger, warn }, + { local: createLocalRunner("/tmp/runner-hooks-unused", logger), remote } + ) ).resolves.toBeUndefined(); } expect( diff --git a/apps/server/test/mcp-routes.test.ts b/apps/server/test/mcp-routes.test.ts index 560f00bbb..0774d3066 100644 --- a/apps/server/test/mcp-routes.test.ts +++ b/apps/server/test/mcp-routes.test.ts @@ -57,7 +57,7 @@ function createMockDeps() { repositoryRoot: "/repo", }) ), - readRemoteRepoManifest: vi.fn(async () => { + readRepoManifest: vi.fn(async () => { throw new RunnerCapabilityUnavailable( "Update the runner to execute checkout commands." ); diff --git a/apps/server/test/mcp-tool-invoked.test.ts b/apps/server/test/mcp-tool-invoked.test.ts index 81fceee04..433add170 100644 --- a/apps/server/test/mcp-tool-invoked.test.ts +++ b/apps/server/test/mcp-tool-invoked.test.ts @@ -1,4 +1,5 @@ -import { mkdtemp, mkdir, writeFile } from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -15,6 +16,43 @@ import { type McpRequestContext, } from "../src/shared/mcp/server.js"; +import type { FastifyBaseLogger } from "fastify"; +import { requestCheckoutCommand } from "../src/agents/checkout-commands.js"; +import { createLocalRunner } from "../src/agents/local-runner.js"; +import type { AgentRecord } from "../src/agents/types.js"; +import { discoverRepoTools } from "../src/server/mcp-checkout.js"; + +function nativeCatalog(root: string) { + const agent = { + ...AGENT, + cwd: root, + worktreePath: null, + workspacePath: null, + } as AgentRecord; + const runners = { local: createLocalRunner(root, {} as FastifyBaseLogger) }; + const selector = { + checkout: "effective", + path: ".dispatch/tools.json", + } as const; + return () => + discoverRepoTools( + { + inspectCheckout: vi.fn(), + readRepoManifest: () => + requestCheckoutCommand(runners, agent, { ...selector, kind: "read" }), + runRepoCommand: (_, state, argv, signal) => + requestCheckoutCommand( + runners, + agent, + { ...selector, kind: "run", state, argv }, + signal + ), + }, + agent, + false + ); +} + const AGENT = { id: "agt_tool_blip", cwd: "/tmp", @@ -90,7 +128,11 @@ describe("agent.tool_invoked", () => { }) ); const publishUiEvent = vi.fn(); - const client = await connect({ publishUiEvent, repoRoot }); + const client = await connect({ + publishUiEvent, + repoRoot, + discoverRepoTools: nativeCatalog(repoRoot), + }); const result = await client.callTool({ name: "repo_echo", @@ -134,3 +176,57 @@ describe("agent.tool_invoked", () => { expect(result.isError).toBeFalsy(); }); }); + +it("cancels a native checkout command through the MCP client", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "mcp-repo-cancel-")); + const abort = new AbortController(); + try { + await mkdir(path.join(root, ".dispatch")); + await writeFile( + path.join(root, ".dispatch/tools.json"), + JSON.stringify({ + tools: [ + { + name: "wait", + description: "Start a subprocess and wait for cancellation.", + command: ["sh", "-c", 'sleep 60 & echo "$!" > child.pid; wait'], + }, + ], + }) + ); + const client = await connect({ + repoRoot: root, + discoverRepoTools: nativeCatalog(root), + }); + expect((await client.listTools()).tools).toContainEqual( + expect.objectContaining({ name: "repo_wait" }) + ); + const result = client + .callTool({ name: "repo_wait", arguments: {} }, undefined, { + signal: abort.signal, + }) + .catch((error: unknown) => error); + const childFile = path.join(root, "child.pid"); + let pid = ""; + await vi.waitFor(async () => { + pid = (await readFile(childFile, "utf8")).trim(); + expect(pid).toMatch(/^\d+$/); + }); + abort.abort(); + expect(await result).toBeInstanceOf(Error); + await vi.waitFor(() => { + let status = ""; + try { + status = execFileSync("ps", ["-o", "stat=", "-p", pid], { + encoding: "utf8", + }).trim(); + } catch { + // No matching process. + } + expect(status).toMatch(/^(?:Z.*)?$/); + }); + } finally { + abort.abort(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/apps/server/test/repo-tool-environment.test.ts b/apps/server/test/repo-tool-environment.test.ts index 3da34714c..73c40709e 100644 --- a/apps/server/test/repo-tool-environment.test.ts +++ b/apps/server/test/repo-tool-environment.test.ts @@ -11,6 +11,7 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createLocalRunner } from "../src/agents/local-runner.js"; import { runLifecycleHook } from "../src/agents/lifecycle-hooks.js"; import type { AgentRecord } from "../src/agents/types.js"; import { repoCommandEnvironment } from "../src/shared/lib/tool-environment.js"; @@ -155,7 +156,10 @@ describe("repo command environment", () => { it("gives the stop hook the same discovery environment", async () => { const { root } = await fixture(); - const logger = { info: vi.fn(), warn: vi.fn() }; + const logger = { + info: vi.fn(), + warn: vi.fn(), + } as unknown as import("fastify").FastifyBaseLogger; await expect( runLifecycleHook( "stop", @@ -165,7 +169,8 @@ describe("repo command environment", () => { worktreePath: null, workspacePath: null, } as AgentRecord, - logger as unknown as import("fastify").FastifyBaseLogger + logger, + { local: createLocalRunner(root, logger) } ) ).resolves.toBeUndefined(); expect(logger.info).toHaveBeenCalled(); diff --git a/docs/04-agent-lifecycle.md b/docs/04-agent-lifecycle.md index 23d282a24..5298f5a15 100644 --- a/docs/04-agent-lifecycle.md +++ b/docs/04-agent-lifecycle.md @@ -169,10 +169,10 @@ Force stop (`force: true` on `POST /agents/:id/stop`) skips the graceful ACP clo The repo's `stop` lifecycle hook (configured under `.dispatch/tools.json`) runs best-effort before the teardown. -For an enrolled runner with checkout command support, Dispatch reads the -`stop` hook from the launch checkout, then from the selected workspace if it -differs. The runner invokes each command under its workload identity before -teardown. Dispatch logs nonzero exits and execution errors and continues +For the built-in runner and enrolled runners with checkout command support, +Dispatch reads the `stop` hook from the launch checkout, then from the selected +workspace if it differs. The session runner invokes each command under its +workload identity before teardown. Dispatch logs nonzero exits and execution errors and continues stopping the session. Selecting a workspace only changes the checkout selection, so retrying the selection cannot invoke a hook. A retry after failed teardown can invoke both hooks again. Stop on an already stopped diff --git a/docs/design/remote-runner-prototype.md b/docs/design/remote-runner-prototype.md index b2ea554c7..098472476 100644 --- a/docs/design/remote-runner-prototype.md +++ b/docs/design/remote-runner-prototype.md @@ -271,7 +271,13 @@ peers keep the existing inspection and configured workspace operations. Dispatch interprets the repository manifest and applies its MCP tool scope and argument rules. Executing a remote manifest tool requires the credential for the selected session or its active job run. Dispatch checks the runner registration -before routing the request. +before routing the request. Native manifest reads and execution use the same +session operation in the built-in runner. Local tool calls retain the native +command environment and honor cancellation delivered by the MCP transport. +Bun’s Node HTTP compatibility layer may leave a disconnected streaming request +running until the runner deadline if it does not report the disconnect. +Native manifest tool calls have a five-minute deadline to accommodate project +setup commands. Native stop hooks keep their 15-second deadline. ## Observed traces diff --git a/e2e/remote-runner/checkout-command.spec.ts b/e2e/remote-runner/checkout-command.spec.ts index 75d4fa72e..4da91e32b 100644 --- a/e2e/remote-runner/checkout-command.spec.ts +++ b/e2e/remote-runner/checkout-command.spec.ts @@ -1,6 +1,7 @@ import { expect, test, type APIRequestContext } from "@playwright/test"; import { mkdtempSync, + readFileSync, mkdirSync, realpathSync, rmSync, @@ -261,7 +262,7 @@ test("dispatches authenticated repo tools and stop hooks to the bound checkout", mkdirSync(path.join(native, ".dispatch")); writeFileSync( path.join(native, ".dispatch/tools.json"), - manifest("native") + manifest("native", 23) ); const localId = await start(native); await verify( @@ -272,6 +273,61 @@ test("dispatches authenticated repo tools and stop hooks to the bound checkout", `${process.getuid!()}:${process.getgid!()}` ); + const nativeMoved = path.join(native, "moved"); + mkdirSync(path.join(nativeMoved, ".dispatch"), { recursive: true }); + writeFileSync( + path.join(nativeMoved, ".dispatch/tools.json"), + manifest("native moved") + ); + const selected = await request.patch( + `/api/v1/agents/${localId}/workspace`, + { + headers: authHeaders(), + data: { path: nativeMoved }, + } + ); + expect(selected.ok(), await selected.text()).toBe(true); + const nativeIdentity = `${process.getuid!()}:${process.getgid!()}`; + await verify( + localId, + undefined, + "native moved", + nativeMoved, + nativeIdentity + ); + + const nativeHook = (dir: string) => `${dir}|${nativeIdentity}|${localId}\n`; + await stop(localId); + await stop(localId); + for (const dir of [native, nativeMoved]) + expect(readFileSync(path.join(dir, "hook.log"), "utf8")).toBe( + nativeHook(dir) + ); + + const restarted = await request.post(`/api/v1/agents/${localId}/start`, { + headers: authHeaders(), + }); + expect(restarted.ok(), await restarted.text()).toBe(true); + const archive = await request.delete( + `/api/v1/agents/${localId}?force=true&cleanupWorktree=keep`, + { headers: authHeaders() } + ); + expect(archive.ok(), await archive.text()).toBe(true); + await expect + .poll(async () => + ( + await request.get(`/api/v1/agents/${localId}`, { + headers: authHeaders(), + }) + ).status() + ) + .toBe(404); + agents.splice(agents.indexOf(localId), 1); + for (const dir of [native, nativeMoved]) + expect(readFileSync(path.join(dir, "hook.log"), "utf8")).toBe( + nativeHook(dir).repeat(2) + ); + const revoked = await request.delete(`${RUNNERS_API}/${alpha}`, { headers: authHeaders(), }); diff --git a/plugins/dispatch/skills/repo-tools/SKILL.md b/plugins/dispatch/skills/repo-tools/SKILL.md index 7861c0bc4..531bd7288 100644 --- a/plugins/dispatch/skills/repo-tools/SKILL.md +++ b/plugins/dispatch/skills/repo-tools/SKILL.md @@ -106,8 +106,8 @@ logged and never blocks the stop. The tools manifest is re-read from disk on **every** MCP request — there is no caching — so an edited command, description, or param takes effect on the next -tool listing with no server restart. (The mtime cache in Dispatch applies only to -`hooks`, not to `tools`.) +tool listing with no server restart. Dispatch reads each checkout’s stop hook +when it tears down the session. The catch is on the client side: an agent's CLI fetches its tool list once at session start and holds it. So an edit to an **existing** tool is picked up by From 356967b12b83758fcec40b6f87c520006349d8cb Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 17:43:40 -0700 Subject: [PATCH 144/642] Apply runner MCP trust before the engine starts --- apps/server/src/agents/acp/host-env.ts | 2 +- .../src/agents/remote/session-supervisor.ts | 20 +- apps/server/test/acp-host-env.test.ts | 4 + apps/server/test/acp-host.test.ts | 4 +- .../test/remote-runner-supervisor.test.ts | 227 +++++++++++++++++- .../test/runner-protocol-consumer.test.ts | 30 +++ docs/design/runner-parity-rollout.md | 15 ++ 7 files changed, 295 insertions(+), 7 deletions(-) diff --git a/apps/server/src/agents/acp/host-env.ts b/apps/server/src/agents/acp/host-env.ts index 08b7111c8..ce31458ed 100644 --- a/apps/server/src/agents/acp/host-env.ts +++ b/apps/server/src/agents/acp/host-env.ts @@ -24,7 +24,7 @@ export function buildHostEnv( // or tool must never replace another agent's or tool's trust configuration. env.NODE_EXTRA_CA_CERTS = localAgentCaBundle( ca, - env.NODE_EXTRA_CA_CERTS, + env.NODE_EXTRA_CA_CERTS || env.SSL_CERT_FILE, path.join(stateDir, "node-ca.pem") ); if (launch.engine === "codex") { diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index e42bcfbb2..eeea98d7d 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -696,6 +696,10 @@ export async function createSessionSupervisor( progress?.({ phase: "ready" }); const dir = path.join(hostRoot, key); const files = path.join(dir, "files"); + const mcpCaPath = path.join(dir, "service-mcp-ca.pem"); + // The enrollment CA may live under a root-only directory. Publish just + // the certificate into the private workload state before starting the host. + const mcpCa = mcp ? await readFile(config.ca) : undefined; const { repository: _repository, useWorktreeOf: _owner, @@ -710,8 +714,12 @@ export async function createSessionSupervisor( env: { DISPATCH_AGENT_ID: agentId, DISPATCH_FILES_DIR: files, - ...(mcpUrl ? { DISPATCH_API_URL: mcpUrl.origin } : {}), - NODE_EXTRA_CA_CERTS: config.ca, + ...(mcpUrl + ? { + DISPATCH_API_URL: mcpUrl.origin, + DISPATCH_LOCAL_CA_CERTIFICATE: mcpCaPath, + } + : { NODE_EXTRA_CA_CERTS: config.ca }), }, pathPrefix: [], reportTurnActivity: true, @@ -722,6 +730,10 @@ export async function createSessionSupervisor( await mkdir(dir, { mode: 0o700 }); await mkdir(files, { mode: 0o700 }); await chown(files, config.uid, config.gid); + if (mcpCa) { + await writeFile(mcpCaPath, mcpCa, { mode: 0o600 }); + await chown(mcpCaPath, config.uid, config.gid); + } await writeFile(hostFile(dir, "launch"), JSON.stringify(launch), { mode: 0o600, }); @@ -735,7 +747,9 @@ export async function createSessionSupervisor( await processes.spawn( [...host, "--state", dir], cwd, - env, + mcpCa && env.NODE_EXTRA_CA_CERTS === config.ca + ? { ...env, NODE_EXTRA_CA_CERTS: undefined } + : env, log, (identity) => writePrivateState(identityFile(key), JSON.stringify(identity)), diff --git a/apps/server/test/acp-host-env.test.ts b/apps/server/test/acp-host-env.test.ts index ffb008f60..3984ef3a0 100644 --- a/apps/server/test/acp-host-env.test.ts +++ b/apps/server/test/acp-host-env.test.ts @@ -90,6 +90,7 @@ it("merges shell-provided trust after ~/.dispatch/env and isolates agents and co ...shellEnv, CODEX_CA_CERTIFICATE: undefined, CURL_CA_BUNDLE: undefined, + NODE_EXTRA_CA_CERTS: undefined, }); expect(readFileSync(fallback.CODEX_CA_CERTIFICATE!, "utf8")).toContain( `${agent} SSL_CERT_FILE corporate root` @@ -97,6 +98,9 @@ it("merges shell-provided trust after ~/.dispatch/env and isolates agents and co expect(readFileSync(fallback.CURL_CA_BUNDLE!, "utf8")).toContain( `${agent} SSL_CERT_FILE corporate root` ); + expect(readFileSync(fallback.NODE_EXTRA_CA_CERTS!, "utf8")).toContain( + `${agent} SSL_CERT_FILE corporate root` + ); } expect(results[0].CODEX_CA_CERTIFICATE).not.toBe( results[1].CODEX_CA_CERTIFICATE diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index 84bc3b7de..cd703d357 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -687,7 +687,8 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); const id = "agt_host_receipt"; const { runtime } = runtimeWith(stateRoot, () => 0); const launch = launchFor(id, cwd); - delete launch.mcp; + const token = "reauthentication-is-not-required-on-attach"; + launch.mcp = { url: "https://127.0.0.1:1/service", token }; launch.bins.adapter = { bin: "bun", args: [path.join(here, "helpers/remote-acp-fixture.ts")], @@ -778,6 +779,7 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); : [] ); expect(turns).toEqual(["started", "settled"]); + expect(JSON.stringify(second.messages)).not.toContain(token); } finally { second.socket.destroy(); await runtime.stop(id, true); diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index c18252b64..658f6c9c4 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -1,4 +1,4 @@ -import { execFileSync } from "node:child_process"; +import { execFile, execFileSync, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { link, @@ -14,6 +14,15 @@ import { } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { createInterface } from "node:readline"; +import { promisify } from "node:util"; +import Fastify from "fastify"; +import { buildHostEnv } from "../src/agents/acp/host-env.js"; +import type { HostLaunch } from "../src/agents/acp/host-protocol.js"; +import { issueAuthority, issueServer } from "../src/agents/remote/x509.js"; +import { createAgentMcpToken, validateAgentMcpToken } from "../src/auth.js"; +import { registerMcpRoutes } from "../src/routes/mcp.js"; +import { assertAccessCeiling } from "../src/shared/access-ceiling.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { MANAGED_WORKSPACE, @@ -64,6 +73,73 @@ it("explains lock contention while retaining diagnostics for other flock failure ); }); +// Drive the actual CLI's MCP client directly, with no provider account or model turn. +async function callCodexMcp( + bin: string, + env: NodeJS.ProcessEnv, + launch: HostLaunch +): Promise { + const child = spawn(bin, ["app-server", "--listen", "stdio://"], { + cwd: launch.cwd, + env, + stdio: ["pipe", "pipe", "ignore"], + }); + const responses = createInterface({ input: child.stdout })[ + Symbol.asyncIterator + ](); + let id = 0; + async function request(method: string, params: object) { + const requestId = ++id; + child.stdin.write( + JSON.stringify({ jsonrpc: "2.0", id: requestId, method, params }) + "\n" + ); + while (true) { + const line = await responses.next(); + if (line.done) throw new Error(method + " closed without a response"); + const message = JSON.parse(line.value); + if (message.id !== requestId) continue; + if (message.error) + throw new Error(method + " failed: " + message.error.code); + return message.result; + } + } + const timeout = setTimeout(() => child.kill(), 15_000); + try { + const mcp = launch.mcp!; + await request("initialize", { + clientInfo: { name: "dispatch-first-launch", version: "1" }, + capabilities: { experimentalApi: true }, + }); + child.stdin.write('{"jsonrpc":"2.0","method":"initialized"}\n'); + const { thread } = await request("thread/start", { + cwd: launch.cwd, + ephemeral: true, + sandbox: "read-only", + approvalPolicy: "never", + config: { + mcp_servers: { + [mcp.name!]: { + url: mcp.url, + http_headers: { Authorization: "Bearer " + mcp.token }, + }, + }, + }, + }); + return JSON.stringify( + await request("mcpServer/tool/call", { + threadId: thread.id, + server: mcp.name, + tool: "create_template", + arguments: { name: "first launch", fullAccess: false }, + }) + ); + } finally { + clearTimeout(timeout); + child.stdin.end(); + child.kill(); + } +} + describe("runner session supervision", () => { let root: string; let state: string; @@ -113,7 +189,7 @@ describe("runner session supervision", () => { state, uid: process.getuid!(), gid: process.getgid!(), - ca: "ca", + ca: path.join(state, "runner-ca.pem"), bins: { claudeBin: "", codexBin: "" }, env: {}, workspaces: new Set(workspaces), @@ -411,6 +487,149 @@ describe("runner session supervision", () => { await expect(stat(record)).rejects.toMatchObject({ code: "ENOENT" }); }); + async function proveServiceMcp(codex?: string) { + const running = await start([]); + const ca = issueAuthority("First launch fixture"); + const leaf = issueServer(ca, ["127.0.0.1"]); + await writeFile(path.join(state, "runner-ca.pem"), ca.cert); + const app = Fastify({ https: { cert: leaf.cert, key: leaf.key } }); + const secret = "isolated first launch fixture"; + const token = createAgentMcpToken(secret, reviewerId); + let active = true; + const addTemplate = vi.fn( + async ( + input: { name: string; fullAccess: boolean }, + callerFullAccess: boolean + ) => { + assertAccessCeiling(input.fullAccess, callerFullAccess); + return { id: "fixture-template", name: input.name }; + } + ); + await registerMcpRoutes(app, { + config: { authToken: secret }, + providerPlans: async () => ({}), + getBearerToken: (request) => + /^Bearer (.+)$/.exec(request.headers.authorization ?? "")?.[1] ?? null, + validateAgentMcpToken, + agentManager: { + getAgent: async (id: string) => ({ + id, + cwd: "runner://fixture/proof", + parentAgentId: agentId, + fullAccess: false, + }), + permitsRemoteAgentMcp: () => active, + remoteRepoOperation: () => undefined, + }, + jobService: { getActiveRunForAgent: async () => null }, + templateService: { addTemplate }, + mcpMethodNotAllowed: () => ({}), + } as Parameters[1]); + const origin = await app.listen({ host: "127.0.0.1", port: 0 }); + try { + // The author starts with MCP omitted. The restricted child gets its own + // endpoint and credential even though it borrows the author's checkout. + await running.launch(launch(MANAGED_WORKSPACE), undefined); + processes.spawn.mockImplementationOnce( + async (_cmd, _cwd, _env, _log, save) => { + kernelReviewer = { ...identity, pid: 101 }; + await save(kernelReviewer); + } + ); + const child = sharedLaunch(); + const mcp = { + name: "service", + url: origin + "/api/mcp/" + reviewerId, + token, + }; + await running.launch( + { + ...child, + launch: { ...child.launch, mcp, fullAccess: false }, + }, + undefined + ); + const dir = path.join(state, "hosts", reviewerId); + const payload: HostLaunch = JSON.parse( + await readFile(path.join(dir, "launch.json"), "utf8") + ); + expect(payload.mcp).toEqual(mcp); + expect(payload.fullAccess).toBe(false); + expect(payload.env.DISPATCH_API_URL).toBe(origin); + const caPath = payload.env.DISPATCH_LOCAL_CA_CERTIFICATE!; + expect(await readFile(caPath, "utf8")).toBe(ca.cert); + expect((await stat(caPath)).mode & 0o777).toBe(0o600); + const env = buildHostEnv(payload, dir, { + HOME: root, + CODEX_HOME: root, + PATH: process.env.PATH, + }); + if (codex) { + const output = await callCodexMcp(codex, env, payload); + expect(output).toContain("fixture-template"); + expect(output).not.toContain(token); + } else { + const request = async (url: string, fullAccess: boolean) => { + const { stdout } = await promisify(execFile)( + process.execPath, + [ + "--input-type=module", + "-e", + ` + const [url, fullAccess] = process.argv.slice(1); + const response = await fetch(url, { + method: "POST", + headers: { + authorization: "Bearer " + process.env.FIXTURE_TOKEN, + accept: "application/json, text/event-stream", + "content-type": "application/json", + }, + body: JSON.stringify({ + jsonrpc: "2.0", id: 1, method: "tools/call", + params: { name: "create_template", arguments: { + name: "first launch", fullAccess: fullAccess === "true" + }}, + }), + }); + console.log(response.status, await response.text()); + `, + url, + String(fullAccess), + ], + { env: { ...env, FIXTURE_TOKEN: token }, timeout: 5000 } + ); + expect(stdout).not.toContain(token); + return stdout; + }; + expect(await request(mcp.url, false)).toContain("fixture-template"); + expect(await request(mcp.url, true)).toContain("restricted agent"); + expect(await request(origin + "/api/mcp/" + agentId, false)).toMatch( + /^403 / + ); + active = false; + expect(await request(mcp.url, false)).toMatch(/^403 /); + } + expect(addTemplate).toHaveBeenCalledWith( + expect.objectContaining({ name: "first launch", fullAccess: false }), + false + ); + } finally { + await app.close(); + } + } + + it("uses workload trust for a session-bound TLS tool and denies escalation and revocation", async () => { + await proveServiceMcp(); + }, 15_000); + + it.runIf(Boolean(process.env.DISPATCH_TEST_CODEX_BIN))( + "calls the TLS tool on a fresh real Codex app-server thread", + async () => { + await proveServiceMcp(process.env.DISPATCH_TEST_CODEX_BIN); + }, + 25_000 + ); + it("starts the reviewer in the author's checkout with independent state", async () => { const running = await start([]); const author = path.join(state, "sessions", agentId); @@ -443,6 +662,10 @@ describe("runner session supervision", () => { env: { DISPATCH_FILES_DIR: path.join(reviewerHost, "files") }, }); expect(payload).not.toHaveProperty("useWorktreeOf"); + expect(payload).not.toHaveProperty("mcp"); + await expect( + stat(path.join(reviewerHost, "service-mcp-ca.pem")) + ).rejects.toMatchObject({ code: "ENOENT" }); await expect( stat(path.join(state, "sessions", reviewerId)) ).rejects.toMatchObject({ code: "ENOENT" }); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 501cedaf4..6c5cfd9f1 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -488,6 +488,36 @@ it("disconnect settles only its own requests and a missing host has a distinct r await expect(pending).rejects.toBeInstanceOf(RunnerHostGone); }); +it("reattaches by opaque session handle after losing an MCP launch acknowledgement", async () => { + const first = peer(); + const token = "one-session-fixture-bearer"; + const launch = first.connection.request({ + ...attach, + kind: "launch", + launch: { + agentId: attach.agentId, + engine: "codex", + model: null, + systemPrompt: null, + resumeSessionId: null, + mcp: { name: "tool-service", url: "https://service.example/mcp", token }, + }, + }); + const lost = expect(launch).rejects.toThrow(/acknowledgement was lost/); + first.connection.close(); + await lost; + + const reconnected = peer(); + const attached = reconnected.connection.request(attach, { + openChannel: true, + }); + const id = requestId(reconnected.sent[0]); + reconnected.connection.receive({ type: "result", id, value: true }); + (await attached).channel!.destroy(); + expect(reconnected.sent[0]).toEqual({ type: "request", id, command: attach }); + expect(JSON.stringify(reconnected.sent)).not.toContain(token); +}); + it("a timed-out request has an unknown outcome even if its receipt arrives late", async () => { vi.useFakeTimers(); try { diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index 974515f04..89edd1b74 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -45,6 +45,21 @@ Each observation needs an owning machine/account, freshness, a bounded payload, Ship each capability through its normal local and remote entry points, test older peers, and update the inventory with evidence. Keep release/update policy changes separate until the restart and mixed-version tests establish what can safely coexist. +A launch with service MCP uses the HTTPS URL as seen from the workload. +The runner stages its enrollment CA in the private host directory and the +host adds it to the engine's TLS bundles before spawning the adapter. For +an endpoint on a separate private CA, the runner operator can configure +`trustBundle` with the additional roots. The v1 launch shape and optional +`mcp` field are unchanged. An attach after disconnect uses the opaque +session handle and reuses the running host without resending its bearer. +The service validates the bearer against the intended session and owns +revocation and child access policy. + +The supervisor regression exercises the host's TLS bundles against the +Dispatch MCP route with a loopback client. To repeat the offline tool call +with a real Codex app-server on a fresh thread, run +`DISPATCH_TEST_CODEX_BIN="$(command -v codex)" pnpm --filter @dispatch/server exec vitest run test/remote-runner-supervisor.test.ts -t 'fresh real Codex'`. + Session checkout selection now runs on the owning runner. Dispatch preserves the machine binding and project membership and records the selected path after runner acknowledgement. Borrowers retain the effective directory From b356403d2090c5a1b9bf09b0b4b3d72819253a55 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 17:51:10 -0700 Subject: [PATCH 145/642] Exercise first-launch MCP through the real Codex adapter --- apps/server/test/helpers/codex-mcp-probe.mjs | 73 ++++++++ .../test/remote-runner-supervisor.test.ts | 171 +++++++++--------- docs/design/runner-parity-rollout.md | 10 +- 3 files changed, 168 insertions(+), 86 deletions(-) create mode 100644 apps/server/test/helpers/codex-mcp-probe.mjs diff --git a/apps/server/test/helpers/codex-mcp-probe.mjs b/apps/server/test/helpers/codex-mcp-probe.mjs new file mode 100644 index 000000000..e4ebc196e --- /dev/null +++ b/apps/server/test/helpers/codex-mcp-probe.mjs @@ -0,0 +1,73 @@ +// Forward the production adapter's app-server traffic unchanged. After its +// first thread/start, ask the real engine to call the service tool without a +// model turn. No MCP configuration or bearer is supplied by this probe. +import { spawn } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; + +const args = process.argv.slice(2); +const appServer = args[0] === "app-server"; +const codex = spawn(process.env.FIXTURE_CODEX_BIN, args, { + stdio: appServer ? ["pipe", "pipe", "inherit"] : "inherit", +}); +codex.on("exit", (code) => process.exit(code ?? 1)); +for (const signal of ["SIGINT", "SIGTERM"]) + process.on(signal, () => codex.kill(signal)); + +if (appServer) { + const probeId = "dispatch-first-launch-probe"; + let threadStartId; + let probed = false; + const input = createInterface({ input: process.stdin }); + input.on("line", (line) => { + const request = JSON.parse(line); + if (threadStartId === undefined && request.method === "thread/start") + threadStartId = request.id; + codex.stdin.write(line + "\n"); + }); + input.on("close", () => codex.stdin.end()); + const output = createInterface({ input: codex.stdout }); + output.on("line", (line) => { + const response = JSON.parse(line); + if (response.id === probeId && !response.method) { + const succeeded = + !response.error && + !response.result?.isError && + JSON.stringify(response.result?.content ?? []).includes( + "fixture-template" + ); + writeFileSync( + process.env.FIXTURE_PROBE_RESULT, + succeeded ? "ok" : "tool failed" + ); + return; + } + process.stdout.write(line + "\n"); + if ( + probed || + threadStartId === undefined || + response.id !== threadStartId || + response.method + ) + return; + probed = true; + const threadId = response.result?.thread?.id; + if (!threadId) { + writeFileSync(process.env.FIXTURE_PROBE_RESULT, "thread failed"); + return; + } + codex.stdin.write( + JSON.stringify({ + jsonrpc: "2.0", + id: probeId, + method: "mcpServer/tool/call", + params: { + threadId, + server: "service", + tool: "create_template", + arguments: { name: "first launch", fullAccess: false }, + }, + }) + "\n" + ); + }); +} diff --git a/apps/server/test/remote-runner-supervisor.test.ts b/apps/server/test/remote-runner-supervisor.test.ts index 658f6c9c4..83cbd2c1c 100644 --- a/apps/server/test/remote-runner-supervisor.test.ts +++ b/apps/server/test/remote-runner-supervisor.test.ts @@ -1,5 +1,6 @@ import { execFile, execFileSync, spawn } from "node:child_process"; import { createHash } from "node:crypto"; +import { once } from "node:events"; import { link, mkdir, @@ -12,9 +13,8 @@ import { symlink, writeFile, } from "node:fs/promises"; -import os from "node:os"; import path from "node:path"; -import { createInterface } from "node:readline"; +import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import Fastify from "fastify"; import { buildHostEnv } from "../src/agents/acp/host-env.js"; @@ -73,73 +73,6 @@ it("explains lock contention while retaining diagnostics for other flock failure ); }); -// Drive the actual CLI's MCP client directly, with no provider account or model turn. -async function callCodexMcp( - bin: string, - env: NodeJS.ProcessEnv, - launch: HostLaunch -): Promise { - const child = spawn(bin, ["app-server", "--listen", "stdio://"], { - cwd: launch.cwd, - env, - stdio: ["pipe", "pipe", "ignore"], - }); - const responses = createInterface({ input: child.stdout })[ - Symbol.asyncIterator - ](); - let id = 0; - async function request(method: string, params: object) { - const requestId = ++id; - child.stdin.write( - JSON.stringify({ jsonrpc: "2.0", id: requestId, method, params }) + "\n" - ); - while (true) { - const line = await responses.next(); - if (line.done) throw new Error(method + " closed without a response"); - const message = JSON.parse(line.value); - if (message.id !== requestId) continue; - if (message.error) - throw new Error(method + " failed: " + message.error.code); - return message.result; - } - } - const timeout = setTimeout(() => child.kill(), 15_000); - try { - const mcp = launch.mcp!; - await request("initialize", { - clientInfo: { name: "dispatch-first-launch", version: "1" }, - capabilities: { experimentalApi: true }, - }); - child.stdin.write('{"jsonrpc":"2.0","method":"initialized"}\n'); - const { thread } = await request("thread/start", { - cwd: launch.cwd, - ephemeral: true, - sandbox: "read-only", - approvalPolicy: "never", - config: { - mcp_servers: { - [mcp.name!]: { - url: mcp.url, - http_headers: { Authorization: "Bearer " + mcp.token }, - }, - }, - }, - }); - return JSON.stringify( - await request("mcpServer/tool/call", { - threadId: thread.id, - server: mcp.name, - tool: "create_template", - arguments: { name: "first launch", fullAccess: false }, - }) - ); - } finally { - clearTimeout(timeout); - child.stdin.end(); - child.kill(); - } -} - describe("runner session supervision", () => { let root: string; let state: string; @@ -182,7 +115,11 @@ describe("runner session supervision", () => { asWorkload: Parameters< typeof createSessionSupervisor >[0]["asWorkload"] = vi.fn(), - prepareDependencies?: (cwd: string) => Promise + prepareDependencies?: (cwd: string) => Promise, + workload?: Pick< + Parameters[0], + "env" | "bins" | "hostCommand" + > ) { supervisor = await createSessionSupervisor( { @@ -198,6 +135,7 @@ describe("runner session supervision", () => { observeCheckout: (dir, scratch) => scratch ? observeScratchCheckout(dir) : observeGitCheckout(dir), prepareDependencies, + ...workload, }, processes ); @@ -217,7 +155,7 @@ describe("runner session supervision", () => { kernelHost = undefined; kernelReviewer = undefined; locked = false; - root = await mkdtemp(path.join(os.tmpdir(), "runner-supervisor-")); + root = await mkdtemp("/tmp/runner-supervisor-"); state = path.join(await realpath(root), "state"); record = path.join(state, "bindings", agentId + ".host"); }); @@ -488,7 +426,40 @@ describe("runner session supervision", () => { }); async function proveServiceMcp(codex?: string) { - const running = await start([]); + const probeResult = path.join(root, "codex-probe-result"); + let workload: Parameters[3]; + if (codex) { + const probe = path.join(root, "codex-mcp-probe.mjs"); + const fixture = await readFile( + new URL("./helpers/codex-mcp-probe.mjs", import.meta.url), + "utf8" + ); + await writeFile(probe, "#!/usr/bin/env node\n" + fixture, { + mode: 0o700, + }); + // Let the adapter initialize offline without an OpenAI login. The + // probe only issues an app-server tool call, so no model turn is sent. + await writeFile( + path.join(root, "config.toml"), + 'model_provider = "fixture"\n' + + "[model_providers.fixture]\n" + + 'name = "Offline fixture"\n' + + 'base_url = "http://127.0.0.1:1/v1"\n' + ); + const main = fileURLToPath(new URL("../src/main.ts", import.meta.url)); + workload = { + bins: { claudeBin: "", codexBin: probe }, + hostCommand: () => ["bun", main, "agent-host"], + env: { + HOME: root, + CODEX_HOME: root, + PATH: process.env.PATH, + FIXTURE_CODEX_BIN: codex, + FIXTURE_PROBE_RESULT: probeResult, + }, + }; + } + const running = await start([], undefined, undefined, workload); const ca = issueAuthority("First launch fixture"); const leaf = issueServer(ca, ["127.0.0.1"]); await writeFile(path.join(state, "runner-ca.pem"), ca.cert); @@ -526,13 +497,22 @@ describe("runner session supervision", () => { mcpMethodNotAllowed: () => ({}), } as Parameters[1]); const origin = await app.listen({ host: "127.0.0.1", port: 0 }); + let host: ReturnType | undefined; try { // The author starts with MCP omitted. The restricted child gets its own // endpoint and credential even though it borrows the author's checkout. await running.launch(launch(MANAGED_WORKSPACE), undefined); processes.spawn.mockImplementationOnce( - async (_cmd, _cwd, _env, _log, save) => { - kernelReviewer = { ...identity, pid: 101 }; + async ([bin, ...args], cwd, env, log, save) => { + if (codex) { + host = spawn(bin!, args, { + cwd, + env, + stdio: ["ignore", log, log], + }); + await once(host, "spawn"); + } + kernelReviewer = { ...identity, pid: host?.pid ?? 101 }; await save(kernelReviewer); } ); @@ -559,16 +539,31 @@ describe("runner session supervision", () => { const caPath = payload.env.DISPATCH_LOCAL_CA_CERTIFICATE!; expect(await readFile(caPath, "utf8")).toBe(ca.cert); expect((await stat(caPath)).mode & 0o777).toBe(0o600); - const env = buildHostEnv(payload, dir, { - HOME: root, - CODEX_HOME: root, - PATH: process.env.PATH, - }); if (codex) { - const output = await callCodexMcp(codex, env, payload); - expect(output).toContain("fixture-template"); - expect(output).not.toContain(token); + // Check that the tool returned and the real host completed its + // session/new handoff with the adapter. + await vi + .waitFor( + async () => { + expect(await readFile(probeResult, "utf8")).toBe("ok"); + const session = JSON.parse( + await readFile(path.join(dir, "session.json"), "utf8") + ); + expect(session.sessionId).toEqual(expect.any(String)); + }, + { timeout: 15_000, interval: 50 } + ) + .catch(async (error) => { + const log = await running.log(reviewerId, MANAGED_WORKSPACE); + throw new Error(log.replaceAll(token, "[fixture bearer]"), { + cause: error, + }); + }); } else { + const env = buildHostEnv(payload, dir, { + HOME: root, + PATH: process.env.PATH, + }); const request = async (url: string, fullAccess: boolean) => { const { stdout } = await promisify(execFile)( process.execPath, @@ -614,6 +609,16 @@ describe("runner session supervision", () => { false ); } finally { + if (host?.pid && host.exitCode === null && host.signalCode === null) { + const exited = once(host, "exit"); + const force = setTimeout(() => host?.kill("SIGKILL"), 3_000); + host.kill("SIGTERM"); + try { + await exited; + } finally { + clearTimeout(force); + } + } await app.close(); } } @@ -623,7 +628,7 @@ describe("runner session supervision", () => { }, 15_000); it.runIf(Boolean(process.env.DISPATCH_TEST_CODEX_BIN))( - "calls the TLS tool on a fresh real Codex app-server thread", + "calls the TLS tool on first launch through the production Codex adapter", async () => { await proveServiceMcp(process.env.DISPATCH_TEST_CODEX_BIN); }, diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index 89edd1b74..7b6bce8ae 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -56,9 +56,13 @@ The service validates the bearer against the intended session and owns revocation and child access policy. The supervisor regression exercises the host's TLS bundles against the -Dispatch MCP route with a loopback client. To repeat the offline tool call -with a real Codex app-server on a fresh thread, run -`DISPATCH_TEST_CODEX_BIN="$(command -v codex)" pnpm --filter @dispatch/server exec vitest run test/remote-runner-supervisor.test.ts -t 'fresh real Codex'`. +Dispatch MCP route with a loopback client. The opt-in Codex test launches +the real agent host and bundled ACP adapter from a fresh supervisor +session. A stdio probe forwards the adapter's configuration unchanged and +asks the real Codex app-server to call the tool once its thread starts. +This runs offline with a temporary Codex home and the test user's UID. +To repeat it, run +`DISPATCH_TEST_CODEX_BIN="$(command -v codex)" pnpm --filter @dispatch/server exec vitest run test/remote-runner-supervisor.test.ts -t 'production Codex adapter'`. Session checkout selection now runs on the owning runner. Dispatch preserves the machine binding and project membership and records the selected path From d4dcbf632d937e5276a37747e8c8bfafba98d41c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 17:52:05 -0700 Subject: [PATCH 146/642] Assign first-launch Codex probe to the runtime owner --- .agents/owners.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.agents/owners.json b/.agents/owners.json index 4043f8252..09b19b5aa 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -31,6 +31,7 @@ "apps/server/test/runner-*.test.ts", "apps/server/test/github-pull-request-watches.test.ts", "apps/server/test/helpers/remote-acp-fixture.ts", + "apps/server/test/helpers/codex-mcp-probe.mjs", "packages/runner-protocol/**", "docs/04-agent-lifecycle.md", "docs/design/remote-runner-handoff.md", From 6e86dc929e89d566ddaba7e81c4feca218cf0904 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 18:04:09 -0700 Subject: [PATCH 147/642] Read engine capabilities from the selected runner workload --- apps/server/src/agents/engine-models.ts | 47 ++-- apps/server/src/agents/manager.ts | 10 +- apps/server/src/agents/provider-plans.ts | 97 ++++++- .../agents/remote/engine-capability-result.ts | 119 +++++++++ .../agents/remote/engine-capability-worker.ts | 247 ++++++++++++++++++ .../src/agents/remote/engine-manager.ts | 14 +- .../agents/remote/engine-runner-executor.ts | 8 + .../src/agents/remote/engine-transport.ts | 49 +++- apps/server/src/agents/remote/runner.ts | 70 +++++ apps/server/src/agents/remote/service.ts | 28 +- apps/server/src/main.ts | 4 + apps/server/src/routes/agents/crud-routes.ts | 16 +- apps/server/src/routes/engine-management.ts | 18 ++ apps/server/src/routes/mcp.ts | 57 +++- apps/server/src/server.ts | 3 + apps/server/src/server/mcp-handlers.ts | 6 +- apps/server/src/shared/agent-effort.ts | 4 +- apps/server/src/shared/agent-models.ts | 7 +- apps/server/src/shared/mcp/usage-tools.ts | 79 +++--- .../test/engine-capability-worker.test.ts | 150 +++++++++++ apps/server/test/engine-models.test.ts | 27 +- apps/server/test/provider-plans.test.ts | 74 ++++++ .../test/remote-runner-enrollment.test.ts | 77 ++++++ .../test/runner-protocol-consumer.test.ts | 48 +++- .../app/agent-effort-select.test.tsx | 18 +- .../components/app/agent-effort-select.tsx | 7 +- .../components/app/agent-engine-fields.tsx | 6 +- .../src/components/app/chat/composer-meta.tsx | 23 +- .../components/app/create-agent-dialog.tsx | 7 + .../src/components/app/runner-settings.tsx | 19 +- .../components/app/use-create-agent-form.ts | 53 +++- .../runner-engines/runner-engines.tsx | 19 +- .../runner-engines/runner-plugin.tsx | 85 ++++++ .../runner-engines/runner-provider-usage.tsx | 164 ++++++++++++ apps/web/src/hooks/use-agent-model-catalog.ts | 14 +- apps/web/src/hooks/use-engines.ts | 3 +- apps/web/src/hooks/use-runner-engines.ts | 63 +++++ apps/web/src/hooks/use-runners.ts | 1 + docs/design/runner-capability-inventory.md | 29 +- packages/runner-protocol/README.md | 34 +++ .../runner-protocol/src/engine-management.ts | 106 +++++++- packages/runner-protocol/src/execution.ts | 2 + 42 files changed, 1801 insertions(+), 111 deletions(-) create mode 100644 apps/server/src/agents/remote/engine-capability-result.ts create mode 100644 apps/server/src/agents/remote/engine-capability-worker.ts create mode 100644 apps/server/test/engine-capability-worker.test.ts create mode 100644 apps/web/src/components/runner-engines/runner-plugin.tsx create mode 100644 apps/web/src/components/runner-engines/runner-provider-usage.tsx diff --git a/apps/server/src/agents/engine-models.ts b/apps/server/src/agents/engine-models.ts index 96f4e6228..a35bc9e01 100644 --- a/apps/server/src/agents/engine-models.ts +++ b/apps/server/src/agents/engine-models.ts @@ -11,8 +11,8 @@ import { } from "../shared/agent-models.js"; import { AGENT_TYPES, type AgentType } from "../shared/agent-types.js"; -/** The settings key an engine's learned list lives under. */ -const settingKey = (agentType: AgentType) => `agent_models:${agentType}`; +/** Old catalog keys could contain enrolled observations without provenance. */ +const settingKey = (agentType: AgentType) => `agent_models:local:${agentType}`; type StoredEngineModels = { models: AgentModelOption[]; @@ -100,28 +100,13 @@ export async function loadLearnedAgentModels(pool: Pool): Promise { export async function recordEngineModels( deps: { pool: Pool; logger: FastifyBaseLogger }, agent: { id: string; type: AgentType; model: string | null }, - options: readonly SessionConfigOption[] + options: readonly SessionConfigOption[], + { learn = true } = {} ): Promise<{ modelChanged: boolean; modelsChanged: boolean }> { const report = modelOptionOf(options); if (!report) return { modelChanged: false, modelsChanged: false }; const previous = getAgentModelOptions(agent.type); - const effortOption = options.find( - (o) => - o.type === "select" && - (o.category === "thought_level" || - /effort|reasoning|thinking/i.test(o.id)) - ); - const effort = - effortOption?.type === "select" - ? effortOption.options - .flatMap((entry) => ("options" in entry ? entry.options : [entry])) - .filter((choice) => choice.value !== "default") - .map((choice) => ({ - value: choice.value, - name: choice.name, - ...(choice.description ? { description: choice.description } : {}), - })) - : []; + const effort = engineEffortOption(options); report.choices = report.choices.map((choice) => { const known = choice.id === report.current @@ -132,10 +117,11 @@ export async function recordEngineModels( const defaultModel = agent.model === null ? report.current : agentModelDefaults()[agent.type]; const modelsChanged = + learn && report.choices.length > 0 && (!sameModels(previous, report.choices) || defaultModel !== agentModelDefaults()[agent.type]); - if (report.choices.length > 0) { + if (learn && report.choices.length > 0) { setLearnedAgentModels(agent.type, report.choices, defaultModel); const stored: StoredEngineModels = { models: report.choices, @@ -172,6 +158,25 @@ function sameModels( ); } +export function engineEffortOption(options: readonly SessionConfigOption[]) { + const effortOption = options.find( + (o) => + o.type === "select" && + (o.category === "thought_level" || + /effort|reasoning|thinking/i.test(o.id)) + ); + return effortOption?.type === "select" + ? effortOption.options + .flatMap((entry) => ("options" in entry ? entry.options : [entry])) + .filter((choice) => choice.value !== "default") + .map((choice) => ({ + value: choice.value, + name: choice.name, + ...(choice.description ? { description: choice.description } : {}), + })) + : []; +} + /** Persist the live session's effort, including removal when a model has no option. */ export async function recordEngineEffort( pool: Pool, diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index fa37d0ef7..f16c1a96f 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -617,7 +617,8 @@ export class AgentManager { const { modelChanged, modelsChanged } = await recordEngineModels( { pool: this.pool, logger: this.logger }, { id: agent.id, type: agent.type, model: agent.model ?? null }, - options + options, + { learn: !remotePlacement(agent.cwd) } ); const effortChanged = await recordEngineEffort(this.pool, agent, options); if (modelChanged || effortChanged) @@ -2110,7 +2111,12 @@ export class AgentManager { if (!placement) await getDirectoryIconPath(this.pool, originalCwd); const id = this.newAgentId(); const type: AgentType = input.type ?? "claude"; - const effort = validateAgentEffort(type, input.effort, input.model); + const effort = validateAgentEffort( + type, + input.effort, + input.model, + Boolean(placement) + ); const role: AgentRole = input.role ?? "standard"; const fullAccess = type === "opencode" || (input.fullAccess ?? false); const fullAccessArg = diff --git a/apps/server/src/agents/provider-plans.ts b/apps/server/src/agents/provider-plans.ts index dcbf63677..894c686fd 100644 --- a/apps/server/src/agents/provider-plans.ts +++ b/apps/server/src/agents/provider-plans.ts @@ -1,5 +1,5 @@ import { execFile } from "node:child_process"; -import { randomUUID } from "node:crypto"; +import { createHmac, randomUUID, timingSafeEqual } from "node:crypto"; import { open, readdir, readFile, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -30,6 +30,9 @@ type JsonObject = Record; export type ProviderPlanOptions = { now?: Date; + /** Workload reads require a live account-bound report. CLI caches have no + * reliable account attribution across sign-ins. */ + liveOnly?: boolean; homeDir?: string; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform; @@ -397,6 +400,7 @@ const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"; const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials"; type RefreshFailureReason = + | "account_changed" | "not_signed_in" | "login_expired" | "login_rejected" @@ -411,6 +415,8 @@ const RENEW_LOGIN = "Claude Code's login on this machine has expired, so plan usage cannot be refreshed. It renews the next time Claude Code runs."; const REFRESH_FAILURE_TEXT: Record = { + account_changed: + "The provider account changed. Refresh usage before trying again.", not_signed_in: "Claude Code is not signed in with a subscription on this machine.", login_expired: RENEW_LOGIN, @@ -597,10 +603,17 @@ async function loadCodexLivePlan( options: ProviderPlanOptions, env: NodeJS.ProcessEnv, homeDir: string, - now: Date + now: Date, + loginOverride?: CodexLogin | null ): Promise { - const fallback = () => loadCodexPlan(options, env, homeDir); - const login = await readCodexLogin(options, env, homeDir); + const fallback = () => + options.liveOnly + ? Promise.resolve(parseCodexRollout("")) + : loadCodexPlan(options, env, homeDir); + const login = + loginOverride === undefined + ? await readCodexLogin(options, env, homeDir) + : loginOverride; if (!login) return fallback(); try { if (codexTokenExpired(login.token, now)) @@ -658,6 +671,8 @@ export class CodexResetError extends Error { } const CODEX_RESET_FAILURE_TEXT: Record = { + account_changed: + "The Codex account changed. Refresh usage before trying again.", not_signed_in: "Codex is not signed in with a ChatGPT plan on this machine, so no reset can be used.", login_expired: CODEX_RENEW_LOGIN, @@ -681,12 +696,29 @@ const CODEX_RESET_FAILURE_TEXT: Record = { * second spend. Called only for an explicit UI or authenticated agent action. */ export async function consumeCodexLimitReset( - options: ProviderPlanOptions & { requestId?: string } = {} + options: ProviderPlanOptions & { + requestId?: string; + account?: { handle: string; secret: string }; + } = {} ): Promise { const now = options.now ?? new Date(); const env = options.env ?? process.env; const homeDir = options.homeDir ?? os.homedir(); const login = await readCodexLogin(options, env, homeDir); + if (options.account) { + const actual = login && codexAccountHandle(login, options.account.secret); + const expected = options.account.handle; + if ( + !actual || + actual.length !== expected.length || + !timingSafeEqual(Buffer.from(actual), Buffer.from(expected)) + ) { + throw new CodexResetError( + "account_changed", + CODEX_RESET_FAILURE_TEXT.account_changed + ); + } + } if (!login) { throw new CodexResetError( "not_signed_in", @@ -810,7 +842,9 @@ async function loadClaudePlan( const read = options.read ?? ((file: string) => readFile(file, "utf8")); let claude: ProviderPlan; try { - claude = parseClaudeCache(await read(claudeConfigPath(homeDir, env))); + claude = parseClaudeCache( + options.liveOnly ? "" : await read(claudeConfigPath(homeDir, env)) + ); } catch { claude = parseClaudeCache(""); } @@ -854,6 +888,13 @@ async function loadClaudePlan( if (!live.windows.length && !live.spend) { throw new RefreshFailure("no_usage_reported"); } + if (options.liveOnly) { + const current = await readClaudeLogin(options, read, homeDir, env).catch( + () => null + ); + if (login.token !== current?.token) + throw new RefreshFailure("account_changed"); + } return live; } catch (error) { const failure = @@ -874,6 +915,50 @@ async function loadClaudePlan( } } +function codexAccountHandle(login: CodexLogin, secret: string): string { + return createHmac("sha256", secret) + .update(JSON.stringify([login.accountId, login.token])) + .digest("base64url"); +} + +export async function loadWorkloadProviderPlans( + secret: string, + options: ProviderPlanOptions = {} +): Promise { + const scoped = { ...options, liveOnly: true }; + const now = scoped.now ?? new Date(); + const env = scoped.env ?? process.env; + const home = scoped.homeDir ?? os.homedir(); + const login = await readCodexLogin(scoped, env, home); + const [claude, codex] = await Promise.all([ + loadClaudePlan(scoped, env, home, now), + loadCodexLivePlan(scoped, env, home, now, login), + ]); + const current = await readCodexLogin(scoped, env, home); + if ( + login?.token !== current?.token || + login?.accountId !== current?.accountId + ) { + return { + checkedAt: now.toISOString(), + providers: [ + claude, + { + ...parseCodexRollout(""), + unavailableReason: CODEX_RESET_FAILURE_TEXT.account_changed, + }, + ], + }; + } + return { + checkedAt: now.toISOString(), + providers: [claude, codex], + ...(login && codex.source === "live" && codex.limitResets + ? { codexResetAccount: codexAccountHandle(login, secret) } + : {}), + }; +} + export async function loadProviderPlans( options: ProviderPlanOptions = {} ): Promise { diff --git a/apps/server/src/agents/remote/engine-capability-result.ts b/apps/server/src/agents/remote/engine-capability-result.ts new file mode 100644 index 000000000..0e2d34224 --- /dev/null +++ b/apps/server/src/agents/remote/engine-capability-result.ts @@ -0,0 +1,119 @@ +import * as z from "zod/v4"; + +import type { + EngineCapabilityOperation, + EngineCapabilityResult, +} from "@dispatch/runner-protocol/engine-management"; + +const label = z + .string() + .min(1) + .max(120) + .regex(/^[\p{L}\p{N} ._'():+&\[\]-]+$/u); +const id = z.string().regex(/^[\w./:@+\[\]-]{1,160}$/); +const version = z + .string() + .regex(/^\d[\w.+-]{0,39}$/) + .nullable(); +const timestamp = z.iso.datetime({ offset: true }); +const count = z.number().int().nonnegative(); +const account = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/); + +const catalog = z.object({ + defaultModel: id.nullable(), + models: z + .array( + z.object({ + id, + label, + effort: z + .array(z.object({ value: id, name: label })) + .max(32) + .optional(), + }) + ) + .max(256), +}); + +const usage = z.object({ + checkedAt: timestamp, + codexResetAccount: account.optional(), + providers: z + .array( + z.object({ + engine: z.enum(["claude", "codex"]), + plan: label.nullable().catch(null), + observedAt: timestamp.nullable(), + source: z.enum(["live", "local"]).optional(), + windows: z + .array( + z.object({ + id: label, + label, + usedPercent: z.number().min(0).max(100), + resetsAt: timestamp.nullable().catch(null), + }) + ) + .max(32), + spend: z + .object({ + used: z.number().nonnegative(), + limit: z.number().nonnegative(), + currency: z.string().regex(/^[A-Z]{3}$/), + enabled: z.boolean().optional(), + }) + .optional() + .catch(undefined), + credits: z + .object({ + balance: z.number().nullable(), + unlimited: z.boolean(), + }) + .optional(), + limitResets: z + .object({ available: count, applicable: count }) + .optional(), + limitReached: z.boolean().optional(), + unavailableReason: z + .string() + .max(200) + .regex(/^[\p{L}\p{N} .'’_-]+$/u) + .optional() + .catch(undefined), + }) + ) + .max(2), +}); + +const resultSchema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("model_catalog"), catalog }), + z.object({ type: z.literal("provider_usage"), usage }), + z.object({ + type: z.literal("codex_reset"), + code: z.enum(["ok", "nothing_to_reset", "no_credit", "unknown"]), + windowsReset: count, + }), + z.object({ + type: z.literal("plugin_status"), + status: z.object({ + installed: z.boolean(), + enabled: z.boolean(), + currentVersion: version.catch(null), + latestVersion: version.catch(null), + updateAvailable: z.boolean(), + actions: z.array(z.enum(["install", "update"])).max(2), + }), + }), +]); + +/** Pick only the published fields before data leaves the workload or reaches Dispatch. */ +export function parseEngineCapabilityResult( + operation: EngineCapabilityOperation, + input: unknown +): EngineCapabilityResult | null { + const result = resultSchema.safeParse(input); + const expected = operation.type.startsWith("plugin_") + ? "plugin_status" + : operation.type; + return result.success && result.data.type === expected ? result.data : null; +} diff --git a/apps/server/src/agents/remote/engine-capability-worker.ts b/apps/server/src/agents/remote/engine-capability-worker.ts new file mode 100644 index 000000000..a400d47f2 --- /dev/null +++ b/apps/server/src/agents/remote/engine-capability-worker.ts @@ -0,0 +1,247 @@ +import { spawn } from "node:child_process"; +import { Readable, Writable } from "node:stream"; + +import type { RunnerEngine } from "@dispatch/runner-protocol"; +import * as acp from "@agentclientprotocol/sdk"; +import { + isEngineCapabilityOperation, + isEngineOperation, + type EngineCapabilityOperation, + type EngineModelCatalog, + type EngineOperationAck, +} from "@dispatch/runner-protocol/engine-management"; + +import { withEngineBinDir } from "../acp/engine-bin-dir.js"; +import { engineSpecFor, type EngineBins } from "../acp/engine-spec.js"; +import { modelOptionOf, engineEffortOption } from "../engine-models.js"; +import { + CodexResetError, + consumeCodexLimitReset, + loadWorkloadProviderPlans, +} from "../provider-plans.js"; +import { + applyPluginUpdate, + checkPluginStatus, +} from "../../shared/plugin-status.js"; +import { parseEngineCapabilityResult } from "./engine-capability-result.js"; + +async function readCatalog( + engine: RunnerEngine, + bins: EngineBins, + model?: string +): Promise { + const spec = engineSpecFor(engine, bins, false); + const bin = { + claude: bins.claudeBin, + codex: bins.codexBin, + opencode: bins.opencodeBin, + }[engine]; + const cwd = process.env.HOME!; + const child = spawn(spec.bin, spec.args, { + cwd, + env: { + ...spec.envDefaults, + ...process.env, + ...spec.env, + PATH: bin ? withEngineBinDir(process.env.PATH, bin) : process.env.PATH, + }, + stdio: ["pipe", "pipe", "ignore"], + }); + let deadline: ReturnType | undefined; + try { + const conn = new acp.ClientSideConnection( + () => ({ + async sessionUpdate() {}, + async requestPermission() { + return { outcome: { outcome: "cancelled" } }; + }, + }), + acp.ndJsonStream( + Writable.toWeb(child.stdin), + Readable.toWeb(child.stdout) + ) + ); + const read = async () => { + await conn.initialize({ protocolVersion: acp.PROTOCOL_VERSION }); + const session = await conn.newSession({ cwd, mcpServers: [] }); + const options = session.configOptions ?? []; + const report = modelOptionOf(options); + const modelOption = options.find( + (option) => + option.type === "select" && + (option.category === "model" || option.id === "model") + ); + const defaultModel = + report?.current === "default" ? null : (report?.current ?? null); + let selected = report?.current; + let reportedOptions = options; + if (model && model !== selected) { + if ( + !modelOption || + !report?.choices.some((choice) => choice.id === model) + ) { + throw new Error("Model unavailable"); + } + ({ configOptions: reportedOptions } = await conn.setSessionConfigOption( + { + sessionId: session.sessionId, + configId: modelOption.id, + value: model, + } + )); + selected = modelOptionOf(reportedOptions)?.current; + } + const effort = engineEffortOption(reportedOptions); + return { + defaultModel, + models: (report?.choices ?? []).map(({ id, label }) => ({ + id, + label, + ...(id === selected ? { effort } : {}), + })), + }; + }; + const stop = new Promise((_, reject) => { + deadline = setTimeout( + () => reject(new Error("Catalog timed out")), + 15_000 + ); + child.once("error", reject); + child.once("exit", () => reject(new Error("Adapter exited"))); + }); + return await Promise.race([read(), stop]); + } finally { + clearTimeout(deadline); + child.kill("SIGKILL"); + } +} + +async function handle( + operation: EngineCapabilityOperation, + bins: EngineBins, + secret: string +): Promise { + switch (operation.type) { + case "model_catalog": + return { + ok: true, + capability: { + type: operation.type, + catalog: await readCatalog(operation.engine, bins, operation.model), + }, + }; + case "provider_usage": + return { + ok: true, + capability: { + type: operation.type, + usage: await loadWorkloadProviderPlans(secret), + }, + }; + case "codex_reset": { + try { + const { code, windowsReset } = await consumeCodexLimitReset({ + requestId: operation.requestId, + account: { handle: operation.account, secret }, + }); + return { + ok: true, + capability: { + type: operation.type, + code: ["ok", "nothing_to_reset", "no_credit"].includes(code) + ? code + : "unknown", + windowsReset, + }, + }; + } catch (error) { + if ( + error instanceof CodexResetError && + error.reason === "account_changed" + ) { + return { + ok: false, + reason: "account_changed", + error: + "The Codex account changed. Refresh usage before trying again.", + }; + } + return { + ok: false, + error: + "Codex did not confirm the reset. Refresh usage before trying again.", + }; + } + } + case "plugin_status": + case "plugin_install": + case "plugin_update": { + const bin = + operation.engine === "claude" ? bins.claudeBin : bins.codexBin; + // The wire accepts an identifier. The implementation supplies the + // marketplace source itself and only manages its provisioned plugin. + if (operation.plugin !== "dispatch@dispatch" || !bin) { + return { + ok: false, + unsupported: true, + error: "Plugin management is unavailable on this runner.", + }; + } + const change = operation.type !== "plugin_status"; + const result = change + ? await applyPluginUpdate( + operation.engine, + bin, + undefined, + undefined, + operation.type === "plugin_install" ? "install" : "update" + ) + : null; + if (result?.error) return { ok: false, error: result.error }; + const status = + result?.status ?? (await checkPluginStatus(operation.engine, bin)); + if (status.detectionError) + return { + ok: false, + error: "Could not read plugin status on this runner.", + }; + return { + ok: true, + capability: { + type: "plugin_status", + status: { + ...status, + actions: status.installed ? ["update"] : ["install"], + }, + }, + }; + } + } +} + +export async function runEngineCapabilityWorker(): Promise { + let ack: EngineOperationAck = { + ok: false, + error: "Engine capability is unavailable on this runner.", + }; + try { + const { operation, bins, secret } = await Bun.stdin.json(); + if ( + isEngineOperation(operation) && + isEngineCapabilityOperation(operation) + ) { + const result = await handle(operation, bins, secret); + if (!result.ok) ack = result; + else { + const capability = parseEngineCapabilityResult( + operation, + result.capability + ); + if (capability) ack = { ok: true, capability }; + } + } + } catch { + // Adapter stderr, local paths and provider bodies stay on the workload. + } + process.stdout.write(JSON.stringify(ack)); +} diff --git a/apps/server/src/agents/remote/engine-manager.ts b/apps/server/src/agents/remote/engine-manager.ts index 7e9b267d9..abbe19957 100644 --- a/apps/server/src/agents/remote/engine-manager.ts +++ b/apps/server/src/agents/remote/engine-manager.ts @@ -4,6 +4,7 @@ import type { RunnerEngine } from "@dispatch/runner-protocol"; import { RUNNER_ENGINES, engineScopeKey, + isEngineCapabilityOperation, type EngineInventoryEntry, type EngineOperation, type EngineOperationAck, @@ -121,7 +122,11 @@ export class EngineManager { // own pushed-cache update can lag its ack by a round trip, so force a // live read here rather than risk handing back what the cache held // before the operation ran. - if (operation.type !== "status" && operation.type !== "login_status") { + if ( + !isEngineCapabilityOperation(operation) && + operation.type !== "status" && + operation.type !== "login_status" + ) { const entries = scope.kind === "local" ? await this.localInventory().catch(() => null) @@ -201,6 +206,13 @@ export class EngineManager { operation: EngineOperation ): Promise { const { logins, updates, overrides } = this.deps.local; + if (isEngineCapabilityOperation(operation)) { + return { + ok: false, + unsupported: true, + error: "Use this machine’s engine settings.", + }; + } switch (operation.type) { case "status": return { ok: true }; diff --git a/apps/server/src/agents/remote/engine-runner-executor.ts b/apps/server/src/agents/remote/engine-runner-executor.ts index 854c6c251..a3f88a4bd 100644 --- a/apps/server/src/agents/remote/engine-runner-executor.ts +++ b/apps/server/src/agents/remote/engine-runner-executor.ts @@ -7,6 +7,7 @@ import path from "node:path"; import type { RunnerEngine } from "@dispatch/runner-protocol"; import { RUNNER_ENGINES, + isEngineCapabilityOperation, type EngineInventoryEntry, type EngineLoginView, type EngineOperation, @@ -254,6 +255,13 @@ export class EngineRunnerExecutor { operation: EngineOperation, onEvent?: (event: EngineOperationEvent) => void ): Promise { + if (isEngineCapabilityOperation(operation)) { + return { + ok: false, + unsupported: true, + error: "Engine capabilities require a workload worker.", + }; + } switch (operation.type) { case "status": { const entries = await this.inventory(); diff --git a/apps/server/src/agents/remote/engine-transport.ts b/apps/server/src/agents/remote/engine-transport.ts index 45353ac92..ed19888f3 100644 --- a/apps/server/src/agents/remote/engine-transport.ts +++ b/apps/server/src/agents/remote/engine-transport.ts @@ -1,6 +1,9 @@ +import { isEngineCapabilityOperation } from "@dispatch/runner-protocol/engine-management"; +import { parseEngineCapabilityResult } from "./engine-capability-result.js"; import type { EngineOperationAck, EngineOperationEvent } from "./protocol.js"; import { RunnerCapabilityUnavailable, + RunnerUnavailable, type RemoteRunnerService, } from "./service.js"; import type { RunnerEngineTransport } from "./engine-manager.js"; @@ -13,6 +16,7 @@ export function remoteEngineTransport( return service.engineInventorySnapshot(runnerId); }, async send(runnerId, operation, onEvent) { + const scoped = isEngineCapabilityOperation(operation); try { const { value, channel } = await service.requestRunner(runnerId, { kind: "engine", @@ -49,7 +53,41 @@ export function remoteEngineTransport( return { ok: false, error: "No response from the runner." }; } try { - return JSON.parse(value) as EngineOperationAck; + const ack = JSON.parse(value) as EngineOperationAck; + if (!scoped) return ack; + if (ack.ok === true) { + const capability = parseEngineCapabilityResult( + operation, + ack.capability + ); + if (capability) return { ok: true, capability }; + } + if (ack.ok === false && ack.unsupported === true) { + return { + ok: false, + unsupported: true, + error: "This engine action is unavailable on the runner.", + }; + } + if (operation.type === "codex_reset") { + if (ack.ok === false && ack.reason === "account_changed") { + return { + ok: false, + reason: "account_changed", + error: + "The Codex account changed. Refresh usage before trying again.", + }; + } + return { + ok: false, + error: + "The runner did not confirm the reset. Refresh usage before trying again.", + }; + } + return { + ok: false, + error: "Could not complete the engine request on this runner.", + }; } catch { return { ok: false, error: "Malformed response from the runner." }; } @@ -57,6 +95,15 @@ export function remoteEngineTransport( if (error instanceof RunnerCapabilityUnavailable) { return { ok: false, error: error.message, unsupported: true }; } + if (scoped) { + return { + ok: false, + error: + error instanceof RunnerUnavailable + ? "The runner is disconnected or unavailable." + : "Could not complete the engine request on this runner.", + }; + } return { ok: false, error: diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 73f1fea2b..12d919a23 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -1,6 +1,7 @@ import { runnerHealthSampler } from "./health.js"; import { SharedCheckoutWatches, childWatch } from "../checkout-watch.js"; import { execFile, spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; import { readFileSync } from "node:fs"; import { createConnection, isIP } from "node:net"; import path from "node:path"; @@ -14,6 +15,9 @@ export { runnerStorageKey } from "./session-supervisor.js"; import { hostCommand, selfCommand } from "../acp/host-command.js"; import { isOpaqueId, + isEngineCapabilityOperation, + type EngineCapabilityOperation, + type EngineOperationAck, isGitHubPullRequestObservation, MAX_PULL_REQUEST_WATCH_EVENT_BYTES, MANAGED_WORKSPACE, @@ -270,6 +274,56 @@ export async function runRemoteRunner(filename: string) { }, }, }); + const engineAccountSecret = randomBytes(32).toString("base64url"); + const capabilityRequests = new Set(); + async function engineCapability( + operation: EngineCapabilityOperation, + signal: AbortSignal + ): Promise { + const key = + operation.type.startsWith("plugin_") && "engine" in operation + ? `plugin:${operation.engine}` + : JSON.stringify( + operation.type === "codex_reset" ? operation.type : operation + ); + if (capabilityRequests.has(key) || capabilityRequests.size >= 8) { + return { + ok: false, + error: + "An engine capability request is already in progress. Try again shortly.", + }; + } + capabilityRequests.add(key); + try { + const child = execute( + setpriv, + [...childArgs, ...selfCommand("runner-engine-capability")], + { + env, + cwd: config.home, + timeout: operation.type.startsWith("plugin_") ? 160_000 : 20_000, + maxBuffer: 192 * 1024, + signal, + } + ); + child.child.stdin?.on("error", () => {}); + child.child.stdin?.end( + JSON.stringify({ + operation, + bins: config.bins, + secret: engineAccountSecret, + }) + ); + return JSON.parse((await child).stdout); + } catch { + return { + ok: false, + error: "Engine capability is unavailable on this runner.", + }; + } finally { + capabilityRequests.delete(key); + } + } const asWorkload: WorkloadCommand = async (bin, args, opts) => { const { stdout } = await execute( setpriv, @@ -413,6 +467,21 @@ export async function runRemoteRunner(filename: string) { if (!isOpaqueId(id)) throw new Error("Invalid runner request ID"); if (socket.destroyed) return; if (command.kind === "engine") { + if (isEngineCapabilityOperation(command.operation)) { + if ( + !(managedWorkspace + ? command.workspace === MANAGED_WORKSPACE + : configuredHandles.includes(command.workspace)) + ) { + throw new Error("Unknown runner workspace."); + } + const ack = await engineCapability( + command.operation, + connection.signal + ); + safeSend({ type: "result", id, value: JSON.stringify(ack) }); + return; + } const ack = await engineExecutor.handle( command.operation, (event) => { @@ -842,6 +911,7 @@ export async function runRemoteRunner(filename: string) { : configuredHandles, ...(managedWorkspace ? { managedWorkspace: true } : {}), engineManagement: true, + engineCapabilities: true, githubManagement: true, pullRequestStatus: true, pullRequestWatch: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 1966ed1d2..0014dd070 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1,3 +1,4 @@ +import { isEngineCapabilityOperation } from "@dispatch/runner-protocol/engine-management"; import { githubPullRequestUrl, githubPullRequestTarget, @@ -112,6 +113,7 @@ export type RunnerSummary = { healthReceivedAt?: string; /** Whether this (online) peer advertised support for engine management. */ engineManagement: boolean; + engineCapabilities?: true; githubManagement: boolean; /** Last pushed snapshot while online; absent offline or before the first push. */ engines?: EngineInventoryEntry[]; @@ -154,6 +156,7 @@ type Peer = { gate: Gate; health?: { sample: RunnerHealth; receivedAt: Date }; reportsHealth?: boolean; + engineCapabilities: boolean; /** Advertised in `ready`; whether this peer answers the `"engine"` command. */ engineManagement: boolean; githubManagement: boolean; @@ -690,6 +693,7 @@ export class RemoteRunnerService { socket, reportsHealth: ready.health === true, engineManagement: ready.engineManagement === true, + engineCapabilities: ready.engineCapabilities === true, pullRequestStatus: ready.pullRequestStatus === true, pullRequestWatch: ready.pullRequestWatch === true, pullRequestEvidence: ready.pullRequestEvidence === true, @@ -935,6 +939,8 @@ export class RemoteRunnerService { name: this.legacy.id, engineManagement: peer?.gate.approved() === true && peer.engineManagement, + ...(peer?.gate.approved() && + peer.engineCapabilities && { engineCapabilities: true as const }), githubManagement: peer?.gate.approved() === true && peer.githubManagement, ...(peer?.engines ? { engines: peer.engines } : {}), @@ -973,6 +979,8 @@ export class RemoteRunnerService { ? "online" : "offline", engineManagement: online && peer.engineManagement, + ...(online && + peer.engineCapabilities && { engineCapabilities: true as const }), githubManagement: online && peer.githubManagement, ...(online && peer.engines ? { engines: peer.engines } : {}), ...(online && peer.health @@ -1299,15 +1307,31 @@ export class RemoteRunnerService { "Runner does not support PR watches." ); + if ( + operation.kind === "engine" && + isEngineCapabilityOperation(operation.operation) && + !peer.engineCapabilities + ) { + throw new RunnerCapabilityUnavailable( + "Update the runner to read engine capabilities." + ); + } + // V1 requires a routable workspace and an id even for a runner-wide operation. for (const workspace of peer.workspaces) { - if (peer.gate.allows(workspace)) - return this.request( + if (peer.gate.allows(workspace)) { + const result = await this.request( { runner: runnerId, workspace }, { ...operation, agentId: `@${operation.kind}`, workspace }, operation.kind === "engine" || operation.operation.type === "watchPullRequests" ); + if (this.peers.get(runnerId) !== peer || !peer.gate.approved()) { + result.channel?.destroy(); + throw new RunnerUnavailable("The runner connection changed."); + } + return result; + } } throw new RunnerUnavailable("The runner has no available workspace."); } diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 7ccfe4753..fc378d6a9 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -85,6 +85,10 @@ if (process.argv[2]?.startsWith("recovery-")) { const { runCheckoutInspectionCli } = await import("./agents/checkout-inspection.js"); await runCheckoutInspectionCli(process.argv[3]!); +} else if (process.argv[2] === "runner-engine-capability") { + const { runEngineCapabilityWorker } = + await import("./agents/remote/engine-capability-worker.js"); + await runEngineCapabilityWorker(); } else if (process.argv[2] === "remote-runner") { const { runRemoteRunner } = await import("./agents/remote/runner.js"); await runRemoteRunner(process.argv[3]!); diff --git a/apps/server/src/routes/agents/crud-routes.ts b/apps/server/src/routes/agents/crud-routes.ts index 273f6dc28..9522d31ef 100644 --- a/apps/server/src/routes/agents/crud-routes.ts +++ b/apps/server/src/routes/agents/crud-routes.ts @@ -221,9 +221,9 @@ export async function registerAgentCrudRoutes( (typeof body.projectId !== "string" || !body.projectId) ) return reply.code(400).send({ error: "Invalid project." }); - const managed = - typeof body.cwd === "string" && - remotePlacement(body.cwd)?.workspace === MANAGED_WORKSPACE; + const placement = + typeof body.cwd === "string" ? remotePlacement(body.cwd) : null; + const managed = placement?.workspace === MANAGED_WORKSPACE; // Created for a task: briefed on it in its prompt, placed in its // project unless a location was chosen, and assigned once it exists. let taskBriefing: { projectId: string; text: string; name: string } | null = @@ -376,9 +376,15 @@ export async function registerAgentCrudRoutes( try { model = validateAgentModel( agentType, - typeof body.model === "string" ? body.model : undefined + typeof body.model === "string" ? body.model : undefined, + Boolean(placement) + ); + effort = validateAgentEffort( + agentType, + body.effort, + model, + Boolean(placement) ); - effort = validateAgentEffort(agentType, body.effort, model); } catch (error) { return reply.code(400).send({ error: errorMessage(error) }); } diff --git a/apps/server/src/routes/engine-management.ts b/apps/server/src/routes/engine-management.ts index aeceea96b..db9696756 100644 --- a/apps/server/src/routes/engine-management.ts +++ b/apps/server/src/routes/engine-management.ts @@ -1,3 +1,7 @@ +import { + isEngineCapabilityOperation, + isEngineOperation, +} from "@dispatch/runner-protocol/engine-management"; import type { FastifyInstance } from "fastify"; import * as z from "zod/v4"; @@ -78,6 +82,20 @@ export async function registerEngineManagementRoutes( }); app.post("/api/v1/engine-management/operations", async (request, reply) => { + const candidate = (request.body ?? {}) as Record; + const operation = candidate.operation; + if ( + isEngineOperation(operation) && + isEngineCapabilityOperation(operation) + ) { + const scope = scopeSchema.safeParse(candidate.scope); + if (!scope.success || scope.data.kind !== "runner") { + return reply + .code(400) + .send({ error: "Choose a runner for this operation." }); + } + return { ack: await manager.rpc(scope.data, operation) }; + } const body = operationBodySchema.safeParse(request.body); if (!body.success) { return reply.code(400).send({ error: "Invalid scope or operation." }); diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index cb37aa911..58ef06680 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -1,3 +1,4 @@ +import type { RunnerEngineTransport } from "../agents/remote/engine-manager.js"; import { createRiskReader } from "../shared/mcp/pull-request-risk-tools.js"; import type { PullRequestRefresher } from "../agents/pull-request-refresher.js"; import type { RedeemCodexReset } from "../agents/codex-reset.js"; @@ -104,6 +105,7 @@ type McpRouteDeps = { redeemCodexReset?: RedeemCodexReset; usageWatches?: UsageCallbacks["usageWatches"]; providerPlans?: ReturnType; + runnerEngines?: RunnerEngineTransport; config: { authToken: string; }; @@ -217,6 +219,41 @@ export async function registerMcpRoutes( ): Promise { const providerPlans = deps.providerPlans ?? createProviderPlansReporter({ log: app.log }); + + function usageForRunner(runnerId: string): UsageCallbacks { + return { + providerPlans: async () => { + const ack = await deps.runnerEngines?.send(runnerId, { + type: "provider_usage", + }); + if (ack?.ok && ack.capability?.type === "provider_usage") { + const { checkedAt, providers } = ack.capability.usage; + return { checkedAt, providers }; + } + return { + checkedAt: new Date().toISOString(), + providers: (["claude", "codex"] as const).map((engine) => ({ + engine, + plan: null, + observedAt: null, + windows: [], + unavailableReason: + ack?.ok === false ? ack.error : "Runner usage is unavailable.", + })), + }; + }, + modelOptions: async (engine) => { + const ack = await deps.runnerEngines?.send(runnerId, { + type: "model_catalog", + engine, + }); + return ack?.ok && ack.capability?.type === "model_catalog" + ? ack.capability.catalog.models + : []; + }, + }; + } + const enabledAgentTypes = () => getEnabledAgentTypes(deps.pool); app.post("/api/mcp", async (request, reply) => { @@ -310,9 +347,13 @@ export async function registerMcpRoutes( inventory: deps.pullRequests, enabled: deps.riskEnabled, }), - providerPlans, - usageWatches: deps.usageWatches, - redeemCodexReset: bearerToken ? deps.redeemCodexReset : undefined, + ...(placement + ? usageForRunner(placement.runner) + : { + providerPlans, + usageWatches: deps.usageWatches, + redeemCodexReset: bearerToken ? deps.redeemCodexReset : undefined, + }), enabledAgentTypes, whenResponseFinished: () => responseFinished, agent: { @@ -420,9 +461,13 @@ export async function registerMcpRoutes( inventory: deps.pullRequests, enabled: deps.riskEnabled, }), - providerPlans, - usageWatches: deps.usageWatches, - redeemCodexReset: bearerToken ? deps.redeemCodexReset : undefined, + ...(placement + ? usageForRunner(placement.runner) + : { + providerPlans, + usageWatches: deps.usageWatches, + redeemCodexReset: bearerToken ? deps.redeemCodexReset : undefined, + }), enabledAgentTypes, whenResponseFinished: () => responseFinished, agent: { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 52f33ea40..f0ebcf46c 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1092,6 +1092,9 @@ async function registerRoutes() { usageWatches.dispose(); }); await registerMcpRoutes(app, { + runnerEngines: remoteRunner + ? remoteEngineTransport(remoteRunner) + : undefined, usageWatches, providerPlans, redeemCodexReset, diff --git a/apps/server/src/server/mcp-handlers.ts b/apps/server/src/server/mcp-handlers.ts index 4d26d9c01..9529c010b 100644 --- a/apps/server/src/server/mcp-handlers.ts +++ b/apps/server/src/server/mcp-handlers.ts @@ -506,7 +506,8 @@ async function handleLaunchAgent( ? input.model : template?.agentType === agentType ? template.model - : undefined) ?? undefined + : undefined) ?? undefined, + Boolean(runnerParent) ); const effort = validateAgentEffort( agentType as (typeof CLI_AGENT_TYPES)[number], @@ -516,7 +517,8 @@ async function handleLaunchAgent( (template.model ?? undefined) === model ? template.effort : null, - model + model, + Boolean(runnerParent) ); // Launching a template is a request for the template's own instructions — diff --git a/apps/server/src/shared/agent-effort.ts b/apps/server/src/shared/agent-effort.ts index 87887d387..6a03341a2 100644 --- a/apps/server/src/shared/agent-effort.ts +++ b/apps/server/src/shared/agent-effort.ts @@ -5,7 +5,8 @@ import { getAgentModelOptions, agentModelDefaults } from "./agent-models.js"; export function validateAgentEffort( type: AgentType, effort: unknown, - model?: string | null + model?: string | null, + workload = false ): Effort | null { if (effort == null) return null; if (typeof effort !== "string" || !effort.trim() || effort.length > 128) { @@ -13,6 +14,7 @@ export function validateAgentEffort( "Invalid effort. Choose an engine-reported level or null to inherit." ); } + if (workload) return effort; model ??= agentModelDefaults()[type]; const choices = model ? getAgentModelOptions(type).find((option) => option.id === model)?.effort diff --git a/apps/server/src/shared/agent-models.ts b/apps/server/src/shared/agent-models.ts index 9e9c8453f..303b231be 100644 --- a/apps/server/src/shared/agent-models.ts +++ b/apps/server/src/shared/agent-models.ts @@ -154,11 +154,16 @@ export function describeAgentModelCatalog( export function validateAgentModel( agentType: AgentType, - model: string | undefined + model: string | undefined, + workload = false ): string | undefined { const normalizedModel = model?.trim() || undefined; if (normalizedModel === undefined) return undefined; + // An enrolled engine owns its catalog and validates the override in ACP. + if (workload && /^[\w./:@+\[\]-]{1,160}$/.test(normalizedModel)) + return normalizedModel; if ( + !workload && getAgentModelOptions(agentType).some( (option) => option.id === normalizedModel ) diff --git a/apps/server/src/shared/mcp/usage-tools.ts b/apps/server/src/shared/mcp/usage-tools.ts index ec24897ab..428a139dc 100644 --- a/apps/server/src/shared/mcp/usage-tools.ts +++ b/apps/server/src/shared/mcp/usage-tools.ts @@ -1,3 +1,4 @@ +import type { RunnerEngine } from "@dispatch/runner-protocol"; import type { RedeemCodexReset } from "../../agents/codex-reset.js"; import type { ProviderPlan, ProviderPlansResponse } from "@dispatch/shared"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; @@ -27,6 +28,9 @@ function agentPlan(plan: ProviderPlan) { export type UsageCallbacks = { redeemCodexReset?: RedeemCodexReset; + modelOptions?: ( + engine: RunnerEngine + ) => Promise>; providerPlans?: (request?: { force?: boolean; }) => Promise; @@ -259,40 +263,47 @@ export function registerUsageTools( providerPlans({ force }), callbacks.enabledAgentTypes?.() ?? CLI_AGENT_TYPES, ]); - const providers = CLI_AGENT_TYPES.filter( - (engine) => !type || type === engine - ).map((engine) => { - const plan = report.providers.find( - (provider) => provider.engine === engine - ); - const windows = withRemaining(plan?.windows ?? []); - return { - ...(plan - ? agentPlan(plan) - : { - engine, - plan: null, - observedAt: null, - unavailableReason: - engine === "opencode" - ? "OpenCode ACP reports session usage, but does not expose provider subscription limits." - : "No usage report available.", - }), - type: engine, - enabled: enabled.includes(engine), - ...verdict(plan, windows), - models: getAgentModelOptions(engine), - windows, - ...(plan?.spend - ? { - spend: { - ...plan.spend, - remaining: Math.max(0, plan.spend.limit - plan.spend.used), - }, - } - : {}), - }; - }); + const providers = await Promise.all( + CLI_AGENT_TYPES.filter((engine) => !type || type === engine).map( + async (engine) => { + const plan = report.providers.find( + (provider) => provider.engine === engine + ); + const windows = withRemaining(plan?.windows ?? []); + return { + ...(plan + ? agentPlan(plan) + : { + engine, + plan: null, + observedAt: null, + unavailableReason: + engine === "opencode" + ? "OpenCode ACP reports session usage, but does not expose provider subscription limits." + : "No usage report available.", + }), + type: engine, + enabled: enabled.includes(engine), + ...verdict(plan, windows), + models: callbacks.modelOptions + ? await callbacks.modelOptions(engine) + : getAgentModelOptions(engine), + windows, + ...(plan?.spend + ? { + spend: { + ...plan.spend, + remaining: Math.max( + 0, + plan.spend.limit - plan.spend.used + ), + }, + } + : {}), + }; + } + ) + ); const result = { checkedAt: report.checkedAt, ...summarizeUsage(providers, report.checkedAt), diff --git a/apps/server/test/engine-capability-worker.test.ts b/apps/server/test/engine-capability-worker.test.ts new file mode 100644 index 000000000..102538b2d --- /dev/null +++ b/apps/server/test/engine-capability-worker.test.ts @@ -0,0 +1,150 @@ +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; + +import type { EngineCapabilityOperation } from "@dispatch/runner-protocol/engine-management"; +import { expect, it } from "vitest"; + +const execute = promisify(execFile); +const main = fileURLToPath(new URL("../src/main.ts", import.meta.url)); + +it("discovers models, effort and installed plugins from two workload homes", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "runner-capability-")); + try { + const adapter = path.join(root, "adapter.mjs"); + const cli = path.join(root, "cli.mjs"); + const homes = [path.join(root, "first"), path.join(root, "second")]; + await Promise.all(homes.map((home) => mkdir(home))); + await writeFile(path.join(homes[0]!, "installed"), "1.2.3"); + await writeFile( + adapter, + ` +import { basename } from "node:path"; +import { createInterface } from "node:readline"; +const home = basename(process.env.HOME); +let model = home + "/default"; +for await (const line of createInterface({ input: process.stdin })) { + const { id, method, params } = JSON.parse(line); + if (id === undefined) continue; + if (method === "session/set_config_option") model = params.value; + const result = method === "initialize" ? { protocolVersion: 1 } : { + sessionId: "fixture", + configOptions: [ + { id: "model", name: "Model", category: "model", type: "select", + currentValue: model, options: [ + { value: home + "/default", name: home + " default" }, + { value: home + "/alternate", name: home + " alternate" }, + ] }, + { id: "effort", name: "Effort", category: "thought_level", type: "select", + currentValue: home, options: [{ value: home, name: home }] }, + ], + }; + console.log(JSON.stringify({ jsonrpc: "2.0", id, result })); +} +` + ); + await writeFile( + cli, + `#!/usr/bin/env node +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +const marker = join(process.env.HOME, "installed"); +const args = process.argv.slice(2).join(" "); +if (args === "plugin list --json") { + const installed = existsSync(marker) ? [{ + pluginId: "dispatch@dispatch", version: readFileSync(marker, "utf8"), enabled: true + }] : []; + console.log(JSON.stringify({ installed })); +} else if (args === "plugin marketplace list --json") { + console.log(JSON.stringify({ marketplaces: [{ name: "dispatch", root: process.env.HOME }] })); +} else if (args.startsWith("plugin add ")) { + writeFileSync(marker, "2.0.0"); +} +`, + { mode: 0o755 } + ); + async function worker(home: string, operation: EngineCapabilityOperation) { + const child = execute("bun", [main, "runner-engine-capability"], { + cwd: home, + env: { + HOME: home, + PATH: process.env.PATH, + DISPATCH_ACP_ADAPTER_COMMAND: JSON.stringify([ + process.execPath, + adapter, + ]), + }, + timeout: 20_000, + }); + child.child.stdin!.end( + JSON.stringify({ + operation, + bins: { claudeBin: cli, codexBin: cli, opencodeBin: cli }, + secret: "fixture-secret", + }) + ); + return JSON.parse((await child).stdout); + } + const plugin = { engine: "codex", plugin: "dispatch@dispatch" } as const; + const [first, second, installed, absent] = await Promise.all([ + worker(homes[0]!, { type: "model_catalog", engine: "codex" }), + worker(homes[1]!, { + type: "model_catalog", + engine: "opencode", + model: "second/alternate", + }), + worker(homes[0]!, { type: "plugin_status", ...plugin }), + worker(homes[1]!, { type: "plugin_status", ...plugin }), + ]); + expect(first).toMatchObject({ + ok: true, + capability: { + catalog: { + defaultModel: "first/default", + models: [ + { id: "first/default", effort: [{ value: "first" }] }, + { id: "first/alternate" }, + ], + }, + }, + }); + expect(second).toMatchObject({ + ok: true, + capability: { + catalog: { + defaultModel: "second/default", + models: [ + { id: "second/default" }, + { id: "second/alternate", effort: [{ value: "second" }] }, + ], + }, + }, + }); + expect(installed).toMatchObject({ + ok: true, + capability: { status: { currentVersion: "1.2.3", installed: true } }, + }); + expect(absent).toMatchObject({ + ok: true, + capability: { status: { installed: false, actions: ["install"] } }, + }); + expect( + await worker(homes[1]!, { type: "plugin_install", ...plugin }) + ).toMatchObject({ + ok: true, + capability: { status: { currentVersion: "2.0.0", installed: true } }, + }); + expect( + await worker(homes[1]!, { + type: "plugin_status", + ...plugin, + plugin: "other@marketplace", + }) + ).toMatchObject({ ok: false, unsupported: true }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}, 30_000); diff --git a/apps/server/test/engine-models.test.ts b/apps/server/test/engine-models.test.ts index e91c6b5e0..889cafcc2 100644 --- a/apps/server/test/engine-models.test.ts +++ b/apps/server/test/engine-models.test.ts @@ -170,10 +170,32 @@ describe("recordEngineModels", () => { const stored = p.query.mock.calls.find((c) => String(c[0]).includes("INSERT INTO settings") )?.[1] as [string, string]; - expect(stored[0]).toBe("agent_models:claude"); + expect(stored[0]).toBe("agent_models:local:claude"); expect(JSON.parse(stored[1]).models).toHaveLength(2); }); + it("records a workload session model without learning it as a native option", async () => { + const p = pool(); + const before = getAgentModelOptions("claude"); + const result = await recordEngineModels( + { pool: p as never, logger }, + { id: "agt_remote", type: "claude", model: null }, + [ + modelOption("runner/model", [ + { value: "runner/model", name: "Runner model" }, + ]), + ], + { learn: false } + ); + expect(result).toEqual({ modelChanged: true, modelsChanged: false }); + expect(getAgentModelOptions("claude")).toEqual(before); + expect(p.query).toHaveBeenCalledTimes(1); + expect(p.query).toHaveBeenCalledWith( + expect.stringContaining("UPDATE agents"), + ["agt_remote", "runner/model"] + ); + }); + it("leaves the agent alone when the engine runs what it already says", async () => { const p = pool(); const result = await recordEngineModels( @@ -269,7 +291,8 @@ describe("recordEngineModels", () => { const reload = { query: vi.fn().mockImplementation((_sql, args) => Promise.resolve({ - rows: args[0] === "agent_models:codex" ? [{ value: stored }] : [], + rows: + args[0] === "agent_models:local:codex" ? [{ value: stored }] : [], }) ), }; diff --git a/apps/server/test/provider-plans.test.ts b/apps/server/test/provider-plans.test.ts index 414908dca..491fbb4ac 100644 --- a/apps/server/test/provider-plans.test.ts +++ b/apps/server/test/provider-plans.test.ts @@ -8,6 +8,7 @@ import { consumeCodexLimitReset, createProviderPlansReporter, loadProviderPlans, + loadWorkloadProviderPlans, parseClaudeCache, parseClaudeUtilization, parseCodexRollout, @@ -571,6 +572,79 @@ describe("loadProviderPlans", () => { return new Response(JSON.stringify(claudeUtilization)); }); + it("reads each workload login and rejects reset after account replacement", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "workload-usage-")); + try { + const homes = [path.join(root, "first"), path.join(root, "second")]; + const writeLogin = async (home: string, account: string) => { + await mkdir(path.join(home, ".codex"), { recursive: true }); + await writeFile( + path.join(home, ".codex/auth.json"), + JSON.stringify({ + tokens: { access_token: `fixture-${account}`, account_id: account }, + }) + ); + }; + await Promise.all( + homes.map((home, index) => writeLogin(home, `account-${index}`)) + ); + const fetchUsage = vi.fn(async (url: string, init?: RequestInit) => { + if (url.endsWith("/consume")) + return Response.json({ code: "ok", windows_reset: 1 }); + const account = new Headers(init?.headers).get("ChatGPT-Account-Id"); + if (url.endsWith("/usage")) + return Response.json({ + ...codexUsage, + plan_type: account === "account-0" ? "pro" : "plus", + }); + return Response.json(codexResets); + }); + const scoped = (homeDir: string) => ({ + homeDir, + env: {}, + platform: "linux" as const, + fetchUsage: fetchUsage as unknown as typeof fetch, + }); + const [first, second] = await Promise.all( + homes.map((home) => + loadWorkloadProviderPlans("fixture-secret", scoped(home)) + ) + ); + expect(first.providers[1]?.plan).toBe("Pro"); + expect(second.providers[1]?.plan).toBe("Plus"); + expect(first.codexResetAccount).toBeDefined(); + expect(second.codexResetAccount).toBeDefined(); + expect(first.codexResetAccount).not.toBe(second.codexResetAccount); + const account = { + secret: "fixture-secret", + handle: first.codexResetAccount!, + }; + await writeLogin(homes[0]!, "replacement"); + await expect( + consumeCodexLimitReset({ ...scoped(homes[0]!), account }) + ).rejects.toMatchObject({ reason: "account_changed" }); + expect( + fetchUsage.mock.calls.some(([url]) => url.endsWith("/consume")) + ).toBe(false); + const readRollouts = vi.fn(async () => ["/old-account"]); + const offline = await loadWorkloadProviderPlans("fixture-secret", { + ...scoped(homes[0]!), + codexFiles: readRollouts, + fetchUsage: async () => { + throw new Error("offline"); + }, + }); + expect(offline.codexResetAccount).toBeUndefined(); + expect(offline.providers[1]).toMatchObject({ + windows: [], + observedAt: null, + }); + expect(readRollouts).not.toHaveBeenCalled(); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + it("lists the account's resets, oldest first, beside the live report", async () => { const fetchUsage = codexFetch(); const report = await loadProviderPlans({ diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index e254d40d8..e35d76169 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -12,6 +12,7 @@ import { type EnrollmentRequest, type EnrollmentReply, } from "../src/agents/remote/protocol.js"; +import { remoteEngineTransport } from "../src/agents/remote/engine-transport.js"; import { RunnerRegistry } from "../src/agents/remote/registry.js"; import { advertisedHost, @@ -62,6 +63,8 @@ function dialRunner(input: { checkoutInspection?: true; defaultBranchFiles?: true; githubManagement?: true; + engineManagement?: true; + engineCapabilities?: true; pullRequestStatus?: true; }): Promise { const url = new URL(input.endpoint); @@ -95,6 +98,8 @@ function dialRunner(input: { checkoutInspection: input.checkoutInspection, defaultBranchFiles: input.defaultBranchFiles, githubManagement: input.githubManagement, + engineManagement: input.engineManagement, + engineCapabilities: input.engineCapabilities, pullRequestStatus: input.pullRequestStatus, }); resolve({ socket, closed, requests }); @@ -248,6 +253,78 @@ describe("runner enrollment service", () => { ).toHaveLength(1); }); + it("negotiates workload capabilities per enrolled peer and fails closed offline", async () => { + const service = makeService(); + const current = await enroll(service, "current-engine"); + const older = await enroll(service, "older-engine"); + const currentPeer = await dialRunner({ + ...current, + workspaces: ["work"], + engineManagement: true, + engineCapabilities: true, + label: JSON.stringify({ + ok: true, + capability: { + type: "model_catalog", + catalog: { + defaultModel: "runner/model", + models: [ + { + id: "runner/model", + label: "Runner model", + hostPath: "/private/home", + }, + ], + }, + }, + }), + }); + const olderPeer = await dialRunner({ + ...older, + workspaces: ["work"], + engineManagement: true, + label: JSON.stringify({ ok: true }), + }); + runners.push(currentPeer, olderPeer); + const currentId = current.created.id; + const olderId = older.created.id; + await waitFor(() => + [currentId, olderId].every((runner) => + service.available({ runner, workspace: "work" }) + ) + ); + const transport = remoteEngineTransport(service); + const operation = { type: "model_catalog", engine: "codex" } as const; + await expect(transport.send(currentId, operation)).resolves.toEqual({ + ok: true, + capability: { + type: "model_catalog", + catalog: { + defaultModel: "runner/model", + models: [{ id: "runner/model", label: "Runner model" }], + }, + }, + }); + await expect(transport.send(olderId, operation)).resolves.toMatchObject({ + ok: false, + unsupported: true, + }); + expect( + olderPeer.requests.filter((frame) => frame.type === "request") + ).toHaveLength(0); + await expect(transport.send(olderId, { type: "status" })).resolves.toEqual({ + ok: true, + }); + + currentPeer.socket.destroy(); + await waitFor( + () => !service.available({ runner: currentId, workspace: "work" }) + ); + await expect(transport.send(currentId, operation)).resolves.toMatchObject({ + ok: false, + }); + }); + it("rejects checkout commands on an older peer while preserving the workspace operation", async () => { const service = makeService(true); const enrolled = await enroll(service, "legacy-checkout"); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index 6c5cfd9f1..ff9401842 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -813,6 +813,7 @@ function fixtureRunner(current: boolean) { managedWorkspace: true, health: true, engineManagement: true, + engineCapabilities: true, githubManagement: true, pullRequestEvidence: true, pullRequestWatch: true, @@ -919,6 +920,29 @@ function fixtureRunner(current: boolean) { ) { const ack: EngineOperationAck = { ok: true }; result(JSON.stringify(ack)); + } else if ( + current && + command.kind === "engine" && + command.workspace === workspace && + command.operation.type === "model_catalog" + ) { + const ack: EngineOperationAck = { + ok: true, + capability: { + type: "model_catalog", + catalog: { + defaultModel: "workload/model", + models: [ + { + id: "workload/model", + label: "Workload model", + effort: [{ value: "high", name: "High" }], + }, + ], + }, + }, + }; + result(JSON.stringify(ack)); } else if ( current && command.kind === "github" && @@ -1322,6 +1346,28 @@ it.each([true, false])( : { unavailable: true } ); + if (ready?.engineManagement && ready.engineCapabilities) { + const { value } = await peer.connection.request({ + kind: "engine", + workspace: runner.session.workspace, + agentId: "collector/catalog", + operation: { type: "model_catalog", engine: "codex" }, + }); + const ack: EngineOperationAck = JSON.parse(String(value)); + expect(ack).toMatchObject({ + ok: true, + capability: { + type: "model_catalog", + catalog: { + defaultModel: "workload/model", + models: [{ id: "workload/model", effort: [{ value: "high" }] }], + }, + }, + }); + } else { + expect(ready?.engineCapabilities).toBeUndefined(); + } + if (ready?.githubManagement && ready.pullRequestWatch) { const { value, channel } = await peer.connection.request( { @@ -1476,7 +1522,7 @@ it.each([true, false])( runner.requests.filter( (frame) => frame.type === "request" && frame.command.kind === "engine" ) - ).toHaveLength(current ? 1 : 0); + ).toHaveLength(current ? 2 : 0); } finally { peer.close(); } diff --git a/apps/web/src/components/app/agent-effort-select.test.tsx b/apps/web/src/components/app/agent-effort-select.test.tsx index e8c0a8405..986cf554d 100644 --- a/apps/web/src/components/app/agent-effort-select.test.tsx +++ b/apps/web/src/components/app/agent-effort-select.test.tsx @@ -30,7 +30,7 @@ describe("AgentEffortSelect", () => { model="new-model" /> ); - expect(choices).toHaveBeenCalledWith("codex", "new-model"); + expect(choices).toHaveBeenCalledWith("codex", "new-model", true); fireEvent.click(screen.getByRole("button", { name: /^Effort:/ })); fireEvent.click(screen.getByRole("radio", { name: "Deliberate" })); expect(onChange).toHaveBeenCalledWith("future"); @@ -44,6 +44,22 @@ describe("AgentEffortSelect", () => { fireEvent.click(screen.getByRole("radio", { name: "Default" })); expect(onChange).toHaveBeenLastCalledWith(null); }); + it("shows workload choices without enabling the native catalog query", () => { + choices.mockReturnValue([{ value: "native", name: "Native effort" }]); + render( + + ); + expect(choices).toHaveBeenLastCalledWith("codex", null, false); + fireEvent.click(screen.getByRole("button", { name: /^Effort:/ })); + expect(screen.getByRole("radio", { name: "Workload effort" })).toBeTruthy(); + expect(screen.queryByRole("radio", { name: "Native effort" })).toBeNull(); + }); it.each([undefined, []])( "does not fabricate options when capabilities are %s", (value) => { diff --git a/apps/web/src/components/app/agent-effort-select.tsx b/apps/web/src/components/app/agent-effort-select.tsx index 3fe2a5d2e..4f4bd16f5 100644 --- a/apps/web/src/components/app/agent-effort-select.tsx +++ b/apps/web/src/components/app/agent-effort-select.tsx @@ -10,6 +10,8 @@ export function AgentEffortSelect({ model = null, id = "create-agent-effort", inheritLabel = "Default", + workload = false, + workloadChoices, }: { value: Effort | null; onChange: (value: Effort | null) => void; @@ -17,8 +19,11 @@ export function AgentEffortSelect({ model?: string | null; id?: string; inheritLabel?: string; + workload?: boolean; + workloadChoices?: import("@dispatch/shared").AgentConfigChoice[]; }): JSX.Element { - const choices = useAgentEffortChoices(agentType, model); + const nativeChoices = useAgentEffortChoices(agentType, model, !workload); + const choices = workload ? workloadChoices : nativeChoices; return (
    + {capabilities && + scope.kind === "runner" && + entry.installed && + entry.id !== "opencode" && ( + + )} + {entry.issue === "install-unavailable" && (

    Install isn't available on this runner — its install command couldn't diff --git a/apps/web/src/components/runner-engines/runner-plugin.tsx b/apps/web/src/components/runner-engines/runner-plugin.tsx new file mode 100644 index 000000000..4c22d1295 --- /dev/null +++ b/apps/web/src/components/runner-engines/runner-plugin.tsx @@ -0,0 +1,85 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +import { Button } from "@/components/ui/button"; +import { runnerEngineCapability } from "@/hooks/use-runner-engines"; + +export function RunnerPlugin({ + runnerId, + engine, +}: { + runnerId: string; + engine: "codex" | "claude"; +}) { + const client = useQueryClient(); + const queryKey = ["runner-plugin", runnerId, engine]; + const plugin = "dispatch@dispatch"; + const status = useQuery({ + queryKey, + retry: false, + queryFn: async () => + ( + await runnerEngineCapability( + runnerId, + { type: "plugin_status", engine, plugin }, + "plugin_status" + ) + ).status, + }); + const change = useMutation({ + mutationFn: async (action: "install" | "update") => + ( + await runnerEngineCapability( + runnerId, + { + type: action === "install" ? "plugin_install" : "plugin_update", + engine, + plugin, + }, + "plugin_status" + ) + ).status, + onSuccess: (data) => client.setQueryData(queryKey, data), + onError: () => client.invalidateQueries({ queryKey }), + }); + const current = status.data; + const action = current?.installed ? "update" : "install"; + const offered = + current?.actions.includes(action) && + (action === "install" || current.updateAvailable); + + return ( +

    + + Dispatch plugin ·{" "} + {status.isError + ? status.error.message + : current + ? current.installed + ? [ + current.currentVersion ?? "installed", + current.enabled ? null : "disabled", + ] + .filter(Boolean) + .join(" · ") + : "not installed" + : "checking…"} + + {offered && !status.isError && ( + + )} + {status.isError && ( + + )} + {change.isError && {change.error.message}} +
    + ); +} diff --git a/apps/web/src/components/runner-engines/runner-provider-usage.tsx b/apps/web/src/components/runner-engines/runner-provider-usage.tsx new file mode 100644 index 000000000..46b2d59e7 --- /dev/null +++ b/apps/web/src/components/runner-engines/runner-provider-usage.tsx @@ -0,0 +1,164 @@ +import { useMutation } from "@tanstack/react-query"; +import { useState } from "react"; + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { createClientId } from "@/lib/client-id"; +import { Button } from "@/components/ui/button"; +import { + runnerEngineCapability, + useRunnerProviderUsage, +} from "@/hooks/use-runner-engines"; + +export function RunnerProviderUsage({ + runnerId, + allowReset = false, +}: { + runnerId: string; + allowReset?: boolean; +}) { + const usage = useRunnerProviderUsage(runnerId, true); + const [confirmation, setConfirmation] = useState(null); + const redeem = useMutation({ + mutationFn: (account: string) => + runnerEngineCapability( + runnerId, + { type: "codex_reset", account, requestId: createClientId() }, + "codex_reset" + ), + onSettled: () => usage.refetch(), + }); + const report = usage.data; + const account = report?.codexResetAccount; + const resetCount = + report?.providers.find((plan) => plan.engine === "codex")?.limitResets + ?.available ?? 0; + const canRedeem = + allowReset && + account && + resetCount > 0 && + !usage.isFetching && + !usage.isError && + !redeem.isPending; + + return ( +
    +
    +

    Plan limits

    + +
    + {usage.isPending &&

    Reading runner usage…

    } + {usage.isError && ( +

    + {report + ? "Showing the last report. Refresh failed." + : usage.error.message} +

    + )} + {report?.providers.map((plan) => ( +
    +

    + {plan.engine === "codex" ? "Codex" : "Claude"} + {plan.plan && ` · ${plan.plan}`} +

    + {plan.unavailableReason && ( +

    {plan.unavailableReason}

    + )} + {plan.windows.map((window) => ( +

    + {window.label} · {Math.round(100 - window.usedPercent)}% remaining + {window.resetsAt && + ` · resets ${new Date(window.resetsAt).toLocaleString()}`} +

    + ))} + {plan.spend && ( +

    + {plan.spend.used} of {plan.spend.limit} {plan.spend.currency} used +

    + )} + {plan.credits && ( +

    + {plan.credits.unlimited + ? "Unlimited credits" + : `Credit balance ${plan.credits.balance ?? "unknown"}`} +

    + )} + {plan.observedAt && ( +

    + Observed {new Date(plan.observedAt).toLocaleString()} +

    + )} +
    + ))} + {resetCount > 0 && ( +

    + {resetCount} Codex reset {resetCount === 1 ? "credit" : "credits"}{" "} + available +

    + )} + {allowReset && ( + + setConfirmation(open ? (account ?? null) : null) + } + > + + + + + Use a Codex reset credit? + + This spends one credit on the Codex account shown for this runner + if its limits can be reset. + +
    + Cancel + confirmation && redeem.mutate(confirmation)} + > + Use reset credit + +
    +
    +
    + )} + {redeem.isError &&

    {redeem.error.message}

    } + {redeem.data && ( +

    + {redeem.data.code === "ok" + ? "Codex reset applied." + : redeem.data.code === "nothing_to_reset" + ? "Codex has no windows to reset." + : redeem.data.code === "no_credit" + ? "Codex has no reset credit available." + : "Codex did not confirm the reset. Check usage before trying again."} +

    + )} +
    + ); +} diff --git a/apps/web/src/hooks/use-agent-model-catalog.ts b/apps/web/src/hooks/use-agent-model-catalog.ts index d5bf0dc73..0d60de03b 100644 --- a/apps/web/src/hooks/use-agent-model-catalog.ts +++ b/apps/web/src/hooks/use-agent-model-catalog.ts @@ -23,7 +23,10 @@ export type AgentModelCatalog = Partial>; * the cache. A list an engine publishes later reaches an open picker through * the `agent_models.changed` event, which invalidates this key (use-sse.ts). */ -export function useAgentModelCatalog(agentType: AgentType): { +export function useAgentModelCatalog( + agentType: AgentType, + enabled = true +): { options: AgentModelOption[]; loading: boolean; /** True only once a catalog has actually arrived — a failed fetch stays @@ -40,6 +43,7 @@ export function useAgentModelCatalog(agentType: AgentType): { } { const { data, isLoading } = useQuery({ queryKey: ["agent-models"], + enabled, queryFn: () => api("/api/v1/agent-models"), staleTime: 5 * 60 * 1000, gcTime: Infinity, @@ -88,9 +92,10 @@ export function useAgentModelCatalogData(): AgentModelCatalog | undefined { } /** Shares the model catalog cache: no separate hardcoded effort list. */ -export function useAgentEffortCatalog() { +export function useAgentEffortCatalog(enabled = true) { const { data } = useQuery({ queryKey: ["agent-models"], + enabled, queryFn: () => api("/api/v1/agent-models"), staleTime: 5 * 60 * 1000, gcTime: Infinity, @@ -104,7 +109,8 @@ export function useAgentEffortCatalog() { export function useAgentEffortChoices( agentType: AgentType, - model: string | null + model: string | null, + enabled = true ) { - return useAgentEffortCatalog()(agentType, model); + return useAgentEffortCatalog(enabled)(agentType, model); } diff --git a/apps/web/src/hooks/use-engines.ts b/apps/web/src/hooks/use-engines.ts index df66ae9ca..a0ffea9f2 100644 --- a/apps/web/src/hooks/use-engines.ts +++ b/apps/web/src/hooks/use-engines.ts @@ -44,13 +44,14 @@ export type EngineStatus = { }; }; -export function useEngines(): { +export function useEngines(enabled = true): { engines: EngineStatus[]; /** Absent while the check is in flight, so nothing reads as missing yet. */ loaded: boolean; } { const { data } = useQuery<{ engines: EngineStatus[] }>({ queryKey: ["system-engines"], + enabled, queryFn: () => api("/api/v1/system/engines"), staleTime: 60_000, }); diff --git a/apps/web/src/hooks/use-runner-engines.ts b/apps/web/src/hooks/use-runner-engines.ts index 1e58d51d2..f528a4c10 100644 --- a/apps/web/src/hooks/use-runner-engines.ts +++ b/apps/web/src/hooks/use-runner-engines.ts @@ -1,8 +1,11 @@ +import type { RunnerEngine } from "@dispatch/runner-protocol"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { engineScopeKey, type EngineInventoryEntry, + type EngineCapabilityOperation, + type EngineCapabilityResult, type EngineLoginView, type EngineOperation, type EngineOperationAck, @@ -108,3 +111,63 @@ export function useRunnerEngineLoginStatus( }, }); } + +export async function runnerEngineCapability< + T extends EngineCapabilityResult["type"], +>( + runnerId: string, + operation: EngineCapabilityOperation, + type: T +): Promise> { + const { ack } = await api<{ ack: EngineOperationAck }>( + "/api/v1/engine-management/operations", + { + method: "POST", + body: JSON.stringify({ scope: { kind: "runner", runnerId }, operation }), + } + ); + if (!ack.ok) throw new Error(ack.error); + if (ack.capability?.type !== type) + throw new Error("The runner did not return the requested engine data."); + return ack.capability as Extract; +} + +export function useRunnerModelCatalog( + runnerId: string | null, + engine: RunnerEngine, + online: boolean, + model?: string +) { + return useQuery({ + queryKey: ["runner-engine-catalog", runnerId, engine, model], + enabled: Boolean(runnerId && online), + retry: false, + queryFn: async () => + ( + await runnerEngineCapability( + runnerId!, + { type: "model_catalog", engine, ...(model ? { model } : {}) }, + "model_catalog" + ) + ).catalog, + }); +} + +export function useRunnerProviderUsage( + runnerId: string | null, + enabled: boolean +) { + return useQuery({ + queryKey: ["runner-provider-usage", runnerId], + enabled: Boolean(runnerId && enabled), + retry: false, + queryFn: async () => + ( + await runnerEngineCapability( + runnerId!, + { type: "provider_usage" }, + "provider_usage" + ) + ).usage, + }); +} diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index b148916f0..063adaa12 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -12,6 +12,7 @@ export type Runner = { workspaces: string[]; managedWorkspace?: true; engineManagement?: true; + engineCapabilities?: true; githubManagement?: boolean; health?: RunnerHealth; healthReceivedAt?: string; diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index b91aa9d7f..47d48cdd5 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -80,9 +80,32 @@ A native host can complete an accepted turn while its controller is down. A repl ### Machine capabilities and integrations -**Manage engines and credentials.** **Partial.** Inventory, versions, supported actions, install/update, and Codex/Claude login are runner-scoped. Model and effort catalogs, plugin install/status, provider usage, account reset and quota probes also need explicit machine/account scope. Dispatch can aggregate sanitized results. - -- Compare two runners signed into different accounts. Verify first login, cancel, async completion, update, unavailable actions, selected model/effort and version-compatible OpenCode resume. [Engine operations](../../packages/runner-protocol/src/engine-management.ts) · [Model discovery](../../apps/server/src/agents/engine-models.ts) · [Provider plans](../../apps/server/src/agents/provider-plans.ts) · [Plugin routes](../../apps/server/src/routes/plugin.ts) +**Manage engines and credentials.** Inventory, versions, install/update and +Codex/Claude login are runner-scoped. The optional v1 +`engineCapabilities` flag adds model and effort catalogs, plugin status and +actions, provider subscription usage, and account-checked Codex reset +redemption. The runner performs these reads and actions as the workload +identity. Create Agent reads the selected runner's catalog. Runner settings +and the session usage popover read that runner's plan limits. Enrolled ACP +reports still update their own sessions without changing the native catalog. +Native picks use the shipped catalog until a local session republishes its +options if the only saved catalog was from an earlier build without scope. + +- Runner-side provider reads discard CLI cache snapshots whose account cannot + be established. Dispatch can show its last report for that same runner with + its observation time when a refresh fails. Reset is disabled for a failed + read and bound to the original credential if it changes before redemption. +- Native settings and MCP usage watches retain their local scope. Enrolled + sessions' `get_usage` reads their runner. Enrolled usage watches and + agent-initiated redemption are unavailable. An operator can redeem from + runner settings. +- The model probe opens an ACP session in the workload home without prompting + or enabling tools. Repository-specific settings can still affect launch. + OpenCode does not provide subscription limits through this integration. +- Fixture coverage compares distinct workload homes and exercises account + replacement, provider failure, plugin installation, and a public protocol + client. Live provider sign-ins and paid account actions require separate + acceptance evidence. **Human terminals and desktop integrations.** **Decision per capability.** A human PTY opened in the agent checkout needs machine-local process, resize, input, detach/resume and close. Desktop IDE, clipboard, browser and computer-use actions need an explicit target and OS permissions. Some belong to the operator’s desktop, even when the agent runs elsewhere. diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index acd377099..fbe626c52 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -496,3 +496,37 @@ changing the checkout. The reply includes raw UTF-8 files and refresh status. A caller can list cached files during refresh or wait for a cold snapshot. A checkout without an origin returns `hasOrigin: false`. Older peers continue to serve original queries and the workspace-approved `repo` operation. + +### Workload model, usage and plugin operations + +A peer that advertises both `engineManagement: true` and +`engineCapabilities: true` in its v1 `ready` accepts the following optional +`engine` operations. They use the existing runner-wide routing convention +with a permitted workspace and an opaque caller-supplied request owner. +Clients send these operations only when both flags are present. Existing +inventory, install, update and login clients continue using `engineManagement` +alone. Replies use the existing JSON-encoded ack with a typed `capability` +on success. There is no progress stream for these operations. + +- `model_catalog` reads the engine's model choices in the workload's home. + The optional `model` asks for the effort choices for that model. Other + models may omit effort, which indicates no observation for those models. +- `provider_usage` returns bounded subscription windows and observation + times. A provider that could not be read can report empty windows and + an unavailable reason. The built-in runner uses a fresh read because + on-disk usage snapshots lack reliable account attribution after sign-in. +- `codex_reset` requires a UUID request ID and the opaque + `codexResetAccount` from the usage reply. The runner checks it against + the credential it will use for redemption. A missing handle means the + action is unavailable. Handles can change when credentials rotate or + the runner restarts. Reuse the UUID for a retry of the same operation + and refresh usage after an uncertain result. +- `plugin_status`, `plugin_install` and `plugin_update` refer to a configured + `name@marketplace` identifier. A runner chooses which plugins and actions + it supports and how to resolve them. The built-in runner supports its + Dispatch plugin and rejects other identifiers. Plugin replies publish + status, versions and available actions without plugin paths or CLI output. + +Scope any host-side cache to the runner. A disconnected or older peer gives +an unavailable result. Never substitute another runner's data or the host's +own credentials, catalog or plugin state. diff --git a/packages/runner-protocol/src/engine-management.ts b/packages/runner-protocol/src/engine-management.ts index 96ab0dda9..584f9ae1f 100644 --- a/packages/runner-protocol/src/engine-management.ts +++ b/packages/runner-protocol/src/engine-management.ts @@ -56,7 +56,82 @@ export type EngineLoginView = { finishedAt?: string; }; +/** Optional runner-wide operations negotiated with engineCapabilities. */ +export type EngineCapabilityOperation = + | { type: "model_catalog"; engine: RunnerEngine; model?: string } + | { type: "provider_usage" } + | { type: "codex_reset"; account: string; requestId: string } + | { + type: "plugin_status" | "plugin_install" | "plugin_update"; + engine: "claude" | "codex"; + /** An operator-provisioned plugin identifier. */ + plugin: string; + }; + +export type EngineChoice = { value: string; name: string }; +export type EngineModelCatalog = { + defaultModel: string | null; + models: Array<{ id: string; label: string; effort?: EngineChoice[] }>; +}; + +export type EngineProviderUsage = { + checkedAt: string; + providers: Array<{ + engine: "claude" | "codex"; + plan: string | null; + observedAt: string | null; + source?: "live" | "local"; + windows: Array<{ + id: string; + label: string; + usedPercent: number; + resetsAt: string | null; + }>; + limitReached?: boolean; + spend?: { + used: number; + limit: number; + currency: string; + enabled?: boolean; + }; + credits?: { balance: number | null; unlimited: boolean }; + limitResets?: { available: number; applicable: number }; + unavailableReason?: string; + }>; + /** Opaque precondition for redeeming against the reported Codex login. */ + codexResetAccount?: string; +}; + +export type EnginePluginStatus = { + installed: boolean; + enabled: boolean; + currentVersion: string | null; + latestVersion: string | null; + updateAvailable: boolean; + actions: Array<"install" | "update">; +}; + +export type EngineCapabilityResult = + | { type: "model_catalog"; catalog: EngineModelCatalog } + | { type: "provider_usage"; usage: EngineProviderUsage } + | { type: "codex_reset"; code: string; windowsReset: number } + | { type: "plugin_status"; status: EnginePluginStatus }; + +export function isEngineCapabilityOperation( + operation: EngineOperation +): operation is EngineCapabilityOperation { + return ( + operation.type === "model_catalog" || + operation.type === "provider_usage" || + operation.type === "codex_reset" || + operation.type === "plugin_status" || + operation.type === "plugin_install" || + operation.type === "plugin_update" + ); +} + export type EngineOperation = + | EngineCapabilityOperation | { type: "status" } | { type: "install"; engine: RunnerEngine } | { type: "update"; engine: RunnerEngine } @@ -100,11 +175,17 @@ export type EngineOperationAck = | { ok: true; operationId?: string; + capability?: EngineCapabilityResult; login?: EngineLoginView; /** e.g. "Already up to date (version 1.2.3)." — never raw CLI output. */ message?: string; } - | { ok: false; error: string; unsupported?: boolean }; + | { + ok: false; + error: string; + unsupported?: boolean; + reason?: "account_changed"; + }; export const RUNNER_ENGINES: readonly RunnerEngine[] = [ "claude", @@ -134,7 +215,30 @@ export function isEngineOperation(value: unknown): value is EngineOperation { if (!isRecord(value)) return false; switch (value.type) { case "status": + case "provider_usage": return true; + case "model_catalog": + return ( + isRunnerEngine(value.engine) && + (value.model === undefined || + (typeof value.model === "string" && + /^[\w./:@+\[\]-]{1,160}$/.test(value.model))) + ); + case "codex_reset": + return ( + typeof value.account === "string" && + /^[A-Za-z0-9_-]{1,128}$/.test(value.account) && + typeof value.requestId === "string" && + /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value.requestId) + ); + case "plugin_status": + case "plugin_install": + case "plugin_update": + return ( + (value.engine === "claude" || value.engine === "codex") && + typeof value.plugin === "string" && + /^[\w-]{1,48}@[\w-]{1,48}$/.test(value.plugin) + ); case "install": case "update": return isRunnerEngine(value.engine); diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index 4447bc660..ba36fee50 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -98,6 +98,7 @@ export type ReadyFrame = { managedWorkspace?: true; /** Advertises support for the `"engine"` command and inventory push. */ engineManagement?: true; + engineCapabilities?: true; githubManagement?: true; pullRequestStatus?: true; pullRequestWatch?: true; @@ -146,6 +147,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.workspacePreparation === true && { workspacePreparation: true }), ...(frame.health === true && { health: true }), ...(frame.engineManagement === true && { engineManagement: true }), + ...(frame.engineCapabilities === true && { engineCapabilities: true }), ...(frame.pullRequestEvidence === true && { pullRequestEvidence: true }), ...(frame.pullRequestWatch === true && { pullRequestWatch: true }), ...(frame.pullRequestStatus === true && { pullRequestStatus: true }), From 732e153b70f2519deb0eaf05b763aec0b962ec49 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 18:11:02 -0700 Subject: [PATCH 148/642] Route native engine capabilities through the built-in runner --- .agents/owners.json | 2 + apps/server/src/agents/local-runner-engine.ts | 156 ++++++++++++++++ apps/server/src/agents/provider-plans.ts | 7 +- .../src/agents/remote/engine-manager.ts | 23 ++- apps/server/src/routes/agents/shared.ts | 5 + apps/server/src/routes/agents/usage-routes.ts | 19 +- apps/server/src/routes/mcp.ts | 18 +- apps/server/src/routes/plugin.ts | 23 +-- apps/server/src/routes/system.ts | 12 +- apps/server/src/server.ts | 19 +- apps/server/test/mcp-codex-reset.test.ts | 167 +++++++++++++++++- apps/server/test/plugin-routes.test.ts | 11 +- .../app/use-create-agent-form.test.tsx | 16 ++ .../components/app/use-create-agent-form.ts | 2 +- docs/design/runner-capability-inventory.md | 8 +- 15 files changed, 424 insertions(+), 64 deletions(-) create mode 100644 apps/server/src/agents/local-runner-engine.ts diff --git a/.agents/owners.json b/.agents/owners.json index 09b19b5aa..e8f696db0 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -57,6 +57,8 @@ "packages/shared/src/pull-requests.ts", "apps/server/test/codex-reset.test.ts", "apps/server/test/provider-plans.test.ts", + "apps/server/src/routes/plugin.ts", + "apps/server/test/plugin-routes.test.ts", "apps/server/test/usage-watches.test.ts", "apps/server/test/lifecycle-routes.test.ts", "apps/server/test/*worktree*", diff --git a/apps/server/src/agents/local-runner-engine.ts b/apps/server/src/agents/local-runner-engine.ts new file mode 100644 index 000000000..5a3f60382 --- /dev/null +++ b/apps/server/src/agents/local-runner-engine.ts @@ -0,0 +1,156 @@ +import { randomBytes } from "node:crypto"; + +import type { + EngineCapabilityOperation, + EngineCapabilityResult, + EngineOperationAck, +} from "@dispatch/runner-protocol/engine-management"; + +import { + agentModelCatalog, + agentModelDefaults, + getAgentModelOptions, +} from "../shared/agent-models.js"; +import { + createPluginStatusChecker, + type PluginStatusLogger, +} from "../shared/plugin-status.js"; +import { findEngineBin } from "./engine-availability.js"; +import { + CodexResetError, + consumeCodexLimitReset, + loadProviderPlans, + loadWorkloadProviderPlans, + type ProviderPlanOptions, +} from "./provider-plans.js"; +import { parseEngineCapabilityResult } from "./remote/engine-capability-result.js"; + +/** + * Native runner-wide operations. Like native checkout operations, this + * runner shares the service's OS identity. The CLI, credential and catalog + * reads belong here so host presentation and policy have one owner boundary. + */ +export function createLocalEngineRunner( + options: { + bins?: { claude: string; codex: string }; + logger?: PluginStatusLogger; + providerOptions?: ProviderPlanOptions; + } = {} +) { + const { bins = { claude: "claude", codex: "codex" }, logger } = options; + const providerOptions = { log: logger, ...options.providerOptions }; + const secret = randomBytes(32).toString("base64url"); + const plugins = createPluginStatusChecker({ + binFor: async (engine) => + (await findEngineBin(bins[engine])) ?? bins[engine], + logger, + }); + + async function handle( + operation: EngineCapabilityOperation + ): Promise { + let result: EngineCapabilityResult; + try { + switch (operation.type) { + case "model_catalog": + // Native ACP hosts already publish their model and effort choices + // during launch. Serve that observation without starting a session + // merely to open the picker. The existing shipped catalog is the fallback. + result = { + type: operation.type, + catalog: { + defaultModel: agentModelDefaults()[operation.engine] ?? null, + models: [...getAgentModelOptions(operation.engine)], + }, + }; + break; + case "provider_usage": + result = { + type: operation.type, + usage: await loadWorkloadProviderPlans(secret, providerOptions), + }; + break; + case "codex_reset": { + const { code, windowsReset } = await consumeCodexLimitReset({ + ...providerOptions, + requestId: operation.requestId, + account: { secret, handle: operation.account }, + }); + result = { + type: operation.type, + code: ["ok", "no_credit", "nothing_to_reset"].includes(code) + ? code + : "unknown", + windowsReset, + }; + break; + } + case "plugin_status": + case "plugin_install": + case "plugin_update": { + if (operation.plugin !== "dispatch@dispatch") { + return { + ok: false, + unsupported: true, + error: "This plugin is unavailable on the native runner.", + }; + } + const change = + operation.type === "plugin_install" + ? await plugins.install(operation.engine) + : operation.type === "plugin_update" + ? await plugins.update(operation.engine) + : null; + if (change?.error) return { ok: false, error: change.error }; + const status = + change?.status ?? (await plugins.getStatus(operation.engine)); + if (status.detectionError) + return { ok: false, error: status.detectionError }; + result = { + type: "plugin_status", + status: { + ...status, + actions: status.installed ? ["update"] : ["install"], + }, + }; + break; + } + } + const capability = parseEngineCapabilityResult(operation, result); + if (capability) return { ok: true, capability }; + } catch (error) { + if (error instanceof CodexResetError) { + return { + ok: false, + ...(error.reason === "account_changed" && { + reason: "account_changed" as const, + }), + error: error.message, + }; + } + } + return { + ok: false, + error: "Engine capability is unavailable on the native runner.", + }; + } + + return { + handle, + plugins, + readModelCatalog: () => ({ + models: agentModelCatalog(), + defaults: agentModelDefaults(), + }), + readModelOptions: async ( + engine: Parameters[0] + ) => getAgentModelOptions(engine), + // The existing native surfaces retain the richer legacy presentation + // and local snapshots. The optional protocol above has a bounded reply. + readProviderPlans: () => loadProviderPlans(providerOptions), + consumeCodexReset: (requestId: string) => + consumeCodexLimitReset({ ...providerOptions, requestId }), + }; +} + +export type LocalEngineRunner = ReturnType; diff --git a/apps/server/src/agents/provider-plans.ts b/apps/server/src/agents/provider-plans.ts index 894c686fd..a169b7413 100644 --- a/apps/server/src/agents/provider-plans.ts +++ b/apps/server/src/agents/provider-plans.ts @@ -996,9 +996,12 @@ export type ProviderPlansReporter = ((request?: { }; export function createProviderPlansReporter( - options: Omit = {}, + options: Omit & { + load?: () => Promise; + } = {}, cacheMs = 60_000 ): ProviderPlansReporter { + const read = options.load ?? (() => loadProviderPlans(options)); let cached: { loadedAt: number; report: ProviderPlansResponse } | null = null; let pending: Promise | null = null; // Bumped by invalidate(): a load begun before it may still finish, but it @@ -1016,7 +1019,7 @@ export function createProviderPlansReporter( } if (pending) return pending; const started = generation; - const load = loadProviderPlans(options) + const load = read() .then((report) => { if (started !== generation) return report; report.providers = report.providers.map((plan) => { diff --git a/apps/server/src/agents/remote/engine-manager.ts b/apps/server/src/agents/remote/engine-manager.ts index abbe19957..381ebd25f 100644 --- a/apps/server/src/agents/remote/engine-manager.ts +++ b/apps/server/src/agents/remote/engine-manager.ts @@ -1,3 +1,7 @@ +import { + createLocalEngineRunner, + type LocalEngineRunner, +} from "../local-runner-engine.js"; import { EventEmitter } from "node:events"; import type { RunnerEngine } from "@dispatch/runner-protocol"; @@ -59,6 +63,7 @@ export interface RunnerEngineTransport { export type LocalEngineDeps = { logins: EngineLogins; updates: EngineUpdateOperations; + capabilities?: Pick; overrides?: Partial>; }; @@ -74,13 +79,23 @@ export type EngineManagerChangeListener = ( export class EngineManager { private readonly events = new EventEmitter(); + private readonly localCapabilities: Pick; constructor( private readonly deps: { local: LocalEngineDeps; remote: RunnerEngineTransport; } - ) {} + ) { + this.localCapabilities = + deps.local.capabilities ?? + createLocalEngineRunner({ + bins: { + claude: deps.local.overrides?.claude ?? "claude", + codex: deps.local.overrides?.codex ?? "codex", + }, + }); + } /** Subscribe to inventory changes for one scope; call the returned function to stop. */ onChanged( @@ -207,11 +222,7 @@ export class EngineManager { ): Promise { const { logins, updates, overrides } = this.deps.local; if (isEngineCapabilityOperation(operation)) { - return { - ok: false, - unsupported: true, - error: "Use this machine’s engine settings.", - }; + return this.localCapabilities.handle(operation); } switch (operation.type) { case "status": diff --git a/apps/server/src/routes/agents/shared.ts b/apps/server/src/routes/agents/shared.ts index a7eea0d46..a8f18ddbb 100644 --- a/apps/server/src/routes/agents/shared.ts +++ b/apps/server/src/routes/agents/shared.ts @@ -1,3 +1,4 @@ +import type { LocalEngineRunner } from "../../agents/local-runner-engine.js"; import type { RedeemCodexReset } from "../../agents/codex-reset.js"; import type { ProviderPlansResponse } from "@dispatch/shared"; import type { FastifyBaseLogger, FastifyReply } from "fastify"; @@ -60,6 +61,10 @@ export type AgentRouteDeps = { * message; see `routes/agents/prompt-routes.ts`. */ chat: StreamService; + localEngines?: Pick< + LocalEngineRunner, + "readProviderPlans" | "consumeCodexReset" + >; /** Subscription plan usage; tests inject one so nothing reads a real login. */ providerPlans?: ((request?: { force?: boolean; diff --git a/apps/server/src/routes/agents/usage-routes.ts b/apps/server/src/routes/agents/usage-routes.ts index 3187aea1c..9e9388f5a 100644 --- a/apps/server/src/routes/agents/usage-routes.ts +++ b/apps/server/src/routes/agents/usage-routes.ts @@ -1,3 +1,4 @@ +import { createLocalEngineRunner } from "../../agents/local-runner-engine.js"; import { createCodexResetCoordinator } from "../../agents/codex-reset.js"; import * as z from "zod/v4"; import type { @@ -6,10 +7,7 @@ import type { } from "@dispatch/shared"; import type { FastifyInstance } from "fastify"; -import { - consumeCodexLimitReset, - createProviderPlansReporter, -} from "../../agents/provider-plans.js"; +import { createProviderPlansReporter } from "../../agents/provider-plans.js"; import { loadAgentUsage, toAgentConfigOptions, @@ -26,8 +24,14 @@ export async function registerAgentUsageRoutes( app: FastifyInstance, deps: AgentRouteDeps ): Promise { + const localEngines = + deps.localEngines ?? createLocalEngineRunner({ logger: deps.appLog }); const providerPlans = - deps.providerPlans ?? createProviderPlansReporter({ log: deps.appLog }); + deps.providerPlans ?? + createProviderPlansReporter({ + load: localEngines.readProviderPlans, + log: deps.appLog, + }); app.get("/api/v1/agents/:id/config", async (request, reply) => { const id = (request.params as { id?: string }).id ?? ""; @@ -85,10 +89,7 @@ export async function registerAgentUsageRoutes( const redeem = deps.redeemCodexReset ?? createCodexResetCoordinator({ - consume: - deps.consumeCodexReset ?? - ((requestId) => - consumeCodexLimitReset({ log: deps.appLog, requestId })), + consume: deps.consumeCodexReset ?? localEngines.consumeCodexReset, providerPlans, }); app.post("/api/v1/usage/codex/resets/consume", async (request, reply) => { diff --git a/apps/server/src/routes/mcp.ts b/apps/server/src/routes/mcp.ts index 58ef06680..cc7824cbf 100644 --- a/apps/server/src/routes/mcp.ts +++ b/apps/server/src/routes/mcp.ts @@ -1,3 +1,7 @@ +import { + createLocalEngineRunner, + type LocalEngineRunner, +} from "../agents/local-runner-engine.js"; import type { RunnerEngineTransport } from "../agents/remote/engine-manager.js"; import { createRiskReader } from "../shared/mcp/pull-request-risk-tools.js"; import type { PullRequestRefresher } from "../agents/pull-request-refresher.js"; @@ -106,6 +110,10 @@ type McpRouteDeps = { usageWatches?: UsageCallbacks["usageWatches"]; providerPlans?: ReturnType; runnerEngines?: RunnerEngineTransport; + localEngines?: Pick< + LocalEngineRunner, + "readProviderPlans" | "readModelOptions" + >; config: { authToken: string; }; @@ -217,8 +225,14 @@ export async function registerMcpRoutes( app: FastifyInstance, deps: McpRouteDeps ): Promise { + const localEngines = + deps.localEngines ?? createLocalEngineRunner({ logger: app.log }); const providerPlans = - deps.providerPlans ?? createProviderPlansReporter({ log: app.log }); + deps.providerPlans ?? + createProviderPlansReporter({ + load: localEngines.readProviderPlans, + log: app.log, + }); function usageForRunner(runnerId: string): UsageCallbacks { return { @@ -351,6 +365,7 @@ export async function registerMcpRoutes( ? usageForRunner(placement.runner) : { providerPlans, + modelOptions: localEngines.readModelOptions, usageWatches: deps.usageWatches, redeemCodexReset: bearerToken ? deps.redeemCodexReset : undefined, }), @@ -465,6 +480,7 @@ export async function registerMcpRoutes( ? usageForRunner(placement.runner) : { providerPlans, + modelOptions: localEngines.readModelOptions, usageWatches: deps.usageWatches, redeemCodexReset: bearerToken ? deps.redeemCodexReset : undefined, }), diff --git a/apps/server/src/routes/plugin.ts b/apps/server/src/routes/plugin.ts index 970733687..f16e04d82 100644 --- a/apps/server/src/routes/plugin.ts +++ b/apps/server/src/routes/plugin.ts @@ -1,11 +1,8 @@ -import type { FastifyBaseLogger, FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import type { Pool } from "pg"; import { getEnabledAgentTypes } from "../agent-type-settings.js"; -import { findEngineBin } from "../agents/engine-availability.js"; -import type { AppConfig } from "../config.js"; import { - createPluginStatusChecker, isPluginAgentType, PLUGIN_AGENT_TYPES, type PluginStatusChecker, @@ -13,25 +10,13 @@ import { type PluginRouteDeps = { pool: Pool; - config: AppConfig; - appLog: FastifyBaseLogger; + plugins: PluginStatusChecker; }; export async function registerPluginRoutes( app: FastifyInstance, deps: PluginRouteDeps ): Promise { - const checker: PluginStatusChecker = createPluginStatusChecker({ - // Find the CLI the way agent launches do: a service's PATH (the Mac - // app's especially) rarely has ~/.local/bin, where claude installs. - binFor: async (agentType) => { - const configured = - agentType === "claude" ? deps.config.claudeBin : deps.config.codexBin; - return (await findEngineBin(configured)) ?? configured; - }, - logger: deps.appLog, - }); - app.get("/api/v1/plugin/status", async (request) => { const query = request.query as { refresh?: unknown }; const forceRefresh = query?.refresh === "true" || query?.refresh === "1"; @@ -43,7 +28,7 @@ export async function registerPluginRoutes( const statuses = await Promise.all( applicableTypes.map((agentType) => - checker.getStatus(agentType, { forceRefresh }) + deps.plugins.getStatus(agentType, { forceRefresh }) ) ); @@ -67,7 +52,7 @@ export async function registerPluginRoutes( .send({ error: `${agentType} is not an enabled agent type.` }); } - const result = await checker[action](agentType); + const result = await deps.plugins[action](agentType); if (result.error) { // ranCommands are subcommands only (no bin path, no absolute paths) — diff --git a/apps/server/src/routes/system.ts b/apps/server/src/routes/system.ts index c9183077a..9da6c2f7b 100644 --- a/apps/server/src/routes/system.ts +++ b/apps/server/src/routes/system.ts @@ -29,9 +29,9 @@ import { IDE_TYPES, getEnabledIdes, setEnabledIdes } from "../ide-settings.js"; import { SlackNotifier, slackDelayError } from "../notifications/slack.js"; import { resolveTilde } from "../shared/lib/resolve-tilde.js"; import { - agentModelCatalog, - agentModelDefaults, -} from "../shared/agent-models.js"; + createLocalEngineRunner, + type LocalEngineRunner, +} from "../agents/local-runner-engine.js"; import { engineStatuses, withEngineVersions, @@ -58,6 +58,7 @@ import { ACP_ENGINE_IDS, type AcpEngineId } from "../agents/acp/engine-spec.js"; const INSTANCE_NAME_KEY = "instance_name"; type SystemRouteDeps = { + localEngines?: Pick; runnerWorkspaceAvailable?: (placement: Placement) => boolean; notificationLinkOrigins?: () => Promise; slackAnswers?: Pick< @@ -188,9 +189,8 @@ export async function registerSystemRoutes( } }); - app.get("/api/v1/agent-models", async () => { - return { models: agentModelCatalog(), defaults: agentModelDefaults() }; - }); + const localEngines = deps.localEngines ?? createLocalEngineRunner(); + app.get("/api/v1/agent-models", async () => localEngines.readModelCatalog()); app.get("/api/v1/system/path-info", async (request, reply) => { const query = request.query as { path?: unknown }; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index f0ebcf46c..c339e7ee3 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -19,7 +19,7 @@ import { } from "./routes/portfolio.js"; import { installRequestLifecycle } from "./server/request-lifecycle.js"; import { createCodexResetCoordinator } from "./agents/codex-reset.js"; -import { consumeCodexLimitReset } from "./agents/provider-plans.js"; +import { createLocalEngineRunner } from "./agents/local-runner-engine.js"; import { TaskWatchNotifier } from "./tasks/watch-notifier.js"; import { UsageWatchService } from "./agents/usage-watches.js"; import { registerHumanTerminalRoutes } from "./routes/human-terminals.js"; @@ -1058,10 +1058,17 @@ async function registerRoutes() { withStreamFlag, }); - const providerPlans = createProviderPlansReporter({ log: app.log }); + const localEngines = createLocalEngineRunner({ + bins: { claude: config.claudeBin, codex: config.codexBin }, + logger: app.log, + }); + const providerPlans = createProviderPlansReporter({ + load: localEngines.readProviderPlans, + log: app.log, + }); const redeemCodexReset = createCodexResetCoordinator({ providerPlans, - consume: (requestId) => consumeCodexLimitReset({ log: app.log, requestId }), + consume: localEngines.consumeCodexReset, }); // One evaluator for every agent's usage watches, fed by every refresh of // the shared reporter plus its own bounded tick while live watches exist. @@ -1092,6 +1099,7 @@ async function registerRoutes() { usageWatches.dispose(); }); await registerMcpRoutes(app, { + localEngines, runnerEngines: remoteRunner ? remoteEngineTransport(remoteRunner) : undefined, @@ -1161,6 +1169,7 @@ async function registerRoutes() { app.log.error({ err: error }, "Engine update persistence failed"), }); await registerSystemRoutes(app, { + localEngines, engineUpdates, runnerWorkspaceAvailable: (placement) => remoteRunner?.available(placement) ?? false, @@ -1201,6 +1210,7 @@ async function registerRoutes() { new EngineManager({ local: { logins: engineLogins, + capabilities: localEngines, updates: engineUpdates, overrides: { claude: config.claudeBin, @@ -1264,7 +1274,7 @@ async function registerRoutes() { clearInterval(shadowRetention); }); - await registerPluginRoutes(app, { pool, config, appLog: app.log }); + await registerPluginRoutes(app, { pool, plugins: localEngines.plugins }); await registerBrainRoutes(app, { brainStore, @@ -1344,6 +1354,7 @@ async function registerRoutes() { }); await registerAgentRoutes(app, { + localEngines, providerPlans, redeemCodexReset, tasks: { diff --git a/apps/server/test/mcp-codex-reset.test.ts b/apps/server/test/mcp-codex-reset.test.ts index 6b9c9713a..3b8eac1d9 100644 --- a/apps/server/test/mcp-codex-reset.test.ts +++ b/apps/server/test/mcp-codex-reset.test.ts @@ -1,4 +1,6 @@ -import { writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import Fastify from "fastify"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; @@ -11,6 +13,10 @@ import { validateAgentMcpToken, validateJobMcpToken, } from "../src/auth.js"; +import { createLocalEngineRunner } from "../src/agents/local-runner-engine.js"; +import { createProviderPlansReporter } from "../src/agents/provider-plans.js"; +import { registerPluginRoutes } from "../src/routes/plugin.js"; +import { registerSystemRoutes } from "../src/routes/system.js"; import { createCodexResetCoordinator } from "../src/agents/codex-reset.js"; import { registerMcpRoutes } from "../src/routes/mcp.js"; import { registerAgentUsageRoutes } from "../src/routes/agents/usage-routes.js"; @@ -137,13 +143,91 @@ describe("authenticated Codex reset MCP HTTP transport (mock provider only)", () it("lists/calls through real scoped-token HTTP, shares UI replay, denies wrong scopes and public access", async () => { const app = Fastify(); - const consume = vi.fn(async (_requestId: string) => outcome); - const providerPlans = Object.assign( - vi.fn(async () => report), - { invalidate: vi.fn() } + const home = await mkdtemp( + path.join(os.tmpdir(), "native-engine-boundary-") ); + const codexBin = path.join(home, "codex"); + await mkdir(path.join(home, ".codex")); + await writeFile( + path.join(home, ".codex", "auth.json"), + JSON.stringify({ + tokens: { + account_id: "native-fixture-account", + access_token: "native-fixture-token", + }, + }) + ); + await writeFile( + codexBin, + `#!/bin/sh +cd "$(dirname "$0")" +case "$*" in + "plugin list --json") + if test -f installed; then + echo '{"installed":[{"pluginId":"dispatch@dispatch","version":"1.2.3","enabled":true}]}' + else + echo '{"installed":[]}' + fi ;; + "plugin marketplace list --json") + printf '{"marketplaces":[{"name":"dispatch","root":"%s"}]}\n' "$PWD" ;; + "plugin marketplace upgrade dispatch --json") ;; + "plugin add dispatch@dispatch") touch installed ;; + *) exit 2 ;; +esac +`, + { mode: 0o755 } + ); + const consume = vi.fn(); + const fetchUsage = vi.fn( + async (url: string | URL | Request, init?: RequestInit) => { + const headers = new Headers(init?.headers); + expect(headers.get("Authorization")).toBe( + "Bearer native-fixture-token" + ); + expect(headers.get("ChatGPT-Account-Id")).toBe( + "native-fixture-account" + ); + if (String(url).endsWith("/consume")) { + consume(JSON.parse(String(init?.body)).redeem_request_id); + return Response.json({ + code: outcome.code, + windows_reset: outcome.windowsReset, + credit: { id: outcome.credit.id, title: outcome.credit.title }, + }); + } + if (String(url).endsWith("/usage")) { + return Response.json({ + plan_type: "plus", + rate_limit: { + primary_window: { + used_percent: 25, + limit_window_seconds: 604800, + }, + }, + }); + } + return Response.json({ + available_count: 3, + applicable_available_count: 0, + }); + } + ); + const localEngines = createLocalEngineRunner({ + bins: { codex: codexBin, claude: codexBin }, + providerOptions: { + homeDir: home, + env: {}, + platform: "linux", + fetchUsage, + }, + }); + const readModels = vi.spyOn(localEngines, "readModelCatalog"); + const readChoices = vi.spyOn(localEngines, "readModelOptions"); + const providerPlans = createProviderPlansReporter({ + load: localEngines.readProviderPlans, + }); const redeemCodexReset = createCodexResetCoordinator({ - consume, + consume: localEngines.consumeCodexReset, providerPlans, }); const agentManager = { @@ -155,6 +239,7 @@ describe("authenticated Codex reset MCP HTTP transport (mock provider only)", () listAgents: async () => [], }; const deps = { + localEngines, config: { authToken: secret }, providerPlans, redeemCodexReset, @@ -176,14 +261,55 @@ describe("authenticated Codex reset MCP HTTP transport (mock provider only)", () }; await registerMcpRoutes(app, deps as never); await registerAgentUsageRoutes(app, { ...deps, appLog: app.log } as never); + await registerPluginRoutes(app, { + pool: deps.pool as never, + plugins: localEngines.plugins, + }); + await registerSystemRoutes(app, { pool: deps.pool, localEngines } as never); const address = await app.listen({ host: "127.0.0.1", port: 0 }); const transcript: unknown[] = [ { safety: - "Ephemeral loopback Fastify, real MCP HTTP transport and HMAC token validation; reset provider and usage mocked, no real account credentials or provider calls.", + "Loopback HTTP with scoped MCP tokens and the native runner. A real temporary home supplies fixture credentials, a real CLI subprocess implements plugin changes, and provider HTTP is stubbed.", }, ]; try { + const models = await app.inject({ + method: "GET", + url: "/api/v1/agent-models", + }); + expect(models.json()).toHaveProperty("models.codex"); + expect(readModels).toHaveBeenCalledOnce(); + const plan = await app.inject({ + method: "GET", + url: "/api/v1/usage/plans", + }); + expect(plan.json()).toMatchObject({ + providers: expect.arrayContaining([ + expect.objectContaining({ + engine: "codex", + plan: "Plus", + source: "live", + }), + ]), + }); + const pluginBefore = await app.inject({ + method: "GET", + url: "/api/v1/plugin/status", + }); + expect(pluginBefore.json()).toMatchObject({ + statuses: expect.arrayContaining([ + expect.objectContaining({ agentType: "codex", installed: false }), + ]), + }); + const plugin = await app.inject({ + method: "POST", + url: "/api/v1/plugin/install", + payload: { agentType: "codex" }, + }); + expect(plugin.json()).toMatchObject({ + status: { installed: true, currentVersion: "1.2.3" }, + }); for (const [route, token] of [ ["/api/mcp/agent-test", createAgentMcpToken(secret, "agent-test")], [ @@ -212,6 +338,20 @@ describe("authenticated Codex reset MCP HTTP transport (mock provider only)", () tools.find((tool) => tool.name === "get_usage")?.annotations ?.readOnlyHint ).toBe(true); + const usage = await client.callTool({ + name: "get_usage", + arguments: { type: "codex" }, + }); + expect(usage.structuredContent).toMatchObject({ + providers: [ + { + engine: "codex", + plan: "Plus", + models: expect.any(Array), + }, + ], + }); + expect(readChoices).toHaveBeenCalledWith("codex"); const invalid = await client.callTool({ name: "redeem_codex_reset", arguments: { idempotencyKey: "not-a-uuid" }, @@ -221,12 +361,20 @@ describe("authenticated Codex reset MCP HTTP transport (mock provider only)", () name: "redeem_codex_reset", arguments: { idempotencyKey: key }, }); - expect(result.structuredContent).toEqual({ + expect(result.structuredContent).toMatchObject({ outcome, error: null, - usage: agentReport, + usage: { + providers: expect.arrayContaining([ + expect.objectContaining({ + engine: "codex", + limitResets: expect.objectContaining({ available: 3 }), + }), + ]), + }, refreshError: null, }); + expect(JSON.stringify(result)).not.toContain('"applicable"'); transcript.push({ route, listedTool: reset, @@ -321,6 +469,7 @@ describe("authenticated Codex reset MCP HTTP transport (mock provider only)", () ); } finally { await app.close(); + await rm(home, { recursive: true, force: true }); } }); }); diff --git a/apps/server/test/plugin-routes.test.ts b/apps/server/test/plugin-routes.test.ts index 0b131bcae..0f23bfc63 100644 --- a/apps/server/test/plugin-routes.test.ts +++ b/apps/server/test/plugin-routes.test.ts @@ -1,7 +1,7 @@ import Fastify from "fastify"; import type { Pool } from "pg"; import { afterEach, describe, expect, it, vi } from "vitest"; -import type { AppConfig } from "../src/config.js"; +import { createLocalEngineRunner } from "../src/agents/local-runner-engine.js"; import { registerPluginRoutes } from "../src/routes/plugin.js"; const mocks = vi.hoisted(() => ({ @@ -37,8 +37,7 @@ async function request(body: unknown) { try { await registerPluginRoutes(app, { pool: {} as Pool, - config: {} as AppConfig, - appLog: app.log, + plugins: createLocalEngineRunner({ logger: app.log }).plugins, }); return await app.inject({ method: "POST", @@ -98,8 +97,10 @@ describe("plugin CLI resolution", () => { const app = Fastify(); await registerPluginRoutes(app, { pool: {} as Pool, - config: { claudeBin: "claude", codexBin: "codex" } as AppConfig, - appLog: app.log, + plugins: createLocalEngineRunner({ + bins: { claude: "claude", codex: "codex" }, + logger: app.log, + }).plugins, }); await app.close(); mocks.findEngineBin.mockImplementation(async (bin: string) => diff --git a/apps/web/src/components/app/use-create-agent-form.test.tsx b/apps/web/src/components/app/use-create-agent-form.test.tsx index 3bf0ad3f5..27fef08fa 100644 --- a/apps/web/src/components/app/use-create-agent-form.test.tsx +++ b/apps/web/src/components/app/use-create-agent-form.test.tsx @@ -787,6 +787,22 @@ describe("handleSubmit", () => { expect(agentsPostJson().model).toBeUndefined(); }); + it("retains the stored model through an empty catalog and restores it when it returns", async () => { + const pref = createAgentModelPrefAtom("claude:/repo/app"); + jotaiStore.set(pref, "saved-model"); + queryClient.setQueryData(["agent-models"], { models: { claude: [] } }); + const { result } = await setup({ initialAgentType: "claude" }); + expect(jotaiStore.get(pref)).toBe("saved-model"); + act(() => { + queryClient.setQueryData(["agent-models"], { + models: { claude: [{ id: "saved-model", label: "Saved model" }] }, + }); + }); + await waitFor(() => expect(result.current.modelOptions).toHaveLength(1)); + await act(async () => result.current.handleSubmit(submitEvent())); + expect(agentsPostJson().model).toBe("saved-model"); + }); + it("records last-used values and hands the created agent to onCreated", async () => { const { result, onCreated } = await setup({ initialAgentType: "codex", diff --git a/apps/web/src/components/app/use-create-agent-form.ts b/apps/web/src/components/app/use-create-agent-form.ts index a2b71704b..cde04b14d 100644 --- a/apps/web/src/components/app/use-create-agent-form.ts +++ b/apps/web/src/components/app/use-create-agent-form.ts @@ -279,7 +279,7 @@ export function useCreateAgentForm({ )?.effort; useEffect(() => { - if (!modelCatalogLoaded) return; + if (!modelCatalogLoaded || modelOptions.length === 0) return; // Anything stored that the catalog no longer offers (a retired id, or an // empty string persisted by an older build) resets to the CLI default. if ( diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 47d48cdd5..509c9e62c 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -88,8 +88,12 @@ redemption. The runner performs these reads and actions as the workload identity. Create Agent reads the selected runner's catalog. Runner settings and the session usage popover read that runner's plan limits. Enrolled ACP reports still update their own sessions without changing the native catalog. -Native picks use the shipped catalog until a local session republishes its -options if the only saved catalog was from an earlier build without scope. +The built-in runner serves native model observations, provider usage and +reset execution, and plugin reads and actions in process under the native OS +identity. Native picks use the shipped catalog until a local session +republishes its options if the only saved catalog was from an earlier build +without scope. The service keeps the original native settings responses and +shares its reset coordinator across HTTP and MCP. - Runner-side provider reads discard CLI cache snapshots whose account cannot be established. Dispatch can show its last report for that same runner with From 08a881f9ca8e05db3b06e09add8599437ce643ba Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 18:30:02 -0700 Subject: [PATCH 149/642] Route session terminals and desktop actions by machine --- apps/server/src/agents/remote/runner.ts | 101 +++++++- apps/server/src/agents/remote/service.ts | 10 +- apps/server/src/main.ts | 3 + .../src/routes/agents/streaming-routes.ts | 6 + apps/server/src/routes/files.ts | 17 +- apps/server/src/routes/human-terminals.ts | 39 ++- apps/server/src/server.ts | 1 + apps/server/src/terminal/manager.ts | 234 +++++++++--------- apps/server/src/terminal/pty.ts | 84 +++++++ apps/server/src/terminal/remote.ts | 66 +++++ apps/server/src/terminal/runner-worker.ts | 104 ++++++++ apps/server/test/human-terminals.test.ts | 8 +- .../test/remote-runner-enrollment.test.ts | 8 +- .../test/runner-protocol-consumer.test.ts | 95 +++++++ .../src/components/app/agent-card-details.tsx | 8 +- .../src/components/app/ide-launch-button.tsx | 24 +- docs/design/runner-capability-inventory.md | 2 +- docs/macos-app.md | 17 ++ e2e/remote-runner/playwright.config.ts | 2 + e2e/remote-runner/terminal.spec.ts | 209 ++++++++++++++++ packages/runner-protocol/README.md | 33 +++ packages/runner-protocol/src/execution.ts | 21 +- packages/runner-protocol/src/index.ts | 1 + packages/runner-protocol/src/node.ts | 7 +- packages/runner-protocol/src/terminal.ts | 72 ++++++ packages/runner-protocol/src/validation.ts | 10 + scripts/smoke-human-terminal.ts | 2 +- 27 files changed, 1000 insertions(+), 184 deletions(-) create mode 100644 apps/server/src/terminal/pty.ts create mode 100644 apps/server/src/terminal/remote.ts create mode 100644 apps/server/src/terminal/runner-worker.ts create mode 100644 e2e/remote-runner/terminal.spec.ts create mode 100644 packages/runner-protocol/src/terminal.ts diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 12d919a23..b747bb9c3 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -7,6 +7,8 @@ import { createConnection, isIP } from "node:net"; import path from "node:path"; import process from "node:process"; import { connect } from "node:tls"; +import { Duplex } from "node:stream"; +import { terminalEnvironment } from "../../terminal/pty.js"; import { promisify } from "node:util"; import type { HostLaunch } from "../acp/host-protocol.js"; import type { WorkloadCommand } from "./session-storage.js"; @@ -15,6 +17,9 @@ export { runnerStorageKey } from "./session-supervisor.js"; import { hostCommand, selfCommand } from "../acp/host-command.js"; import { isOpaqueId, + isTerminalEvent, + isTerminalInfo, + MAX_TERMINAL_FRAME_LENGTH, isEngineCapabilityOperation, type EngineCapabilityOperation, type EngineOperationAck, @@ -437,7 +442,8 @@ export async function runRemoteRunner(filename: string) { closed ) ); - const channels = new Map>(); + const channels = new Map(); + const terminals = new Map(); const timeout = setTimeout(() => socket.destroy(), 5000); socket.on("error", (error: Error) => console.error("Runner transport:", error.message) @@ -448,6 +454,7 @@ export async function runRemoteRunner(filename: string) { watches.clear(); clearTimeout(timeout); clearInterval(healthInterval); + terminals.clear(); for (const channel of channels.values()) channel.destroy(); finished( connectedAt === undefined ? 0 : performance.now() - connectedAt @@ -689,6 +696,82 @@ export async function runRemoteRunner(filename: string) { ) ); break; + case "openTerminal": { + if (terminals.size >= 16 || terminals.has(id) || channels.has(id)) + throw new Error( + "Runner terminal limit reached or duplicate channel." + ); + const reservation = Symbol(); + terminals.set(id, reservation); + try { + const cwd = await supervisor.checkoutDirectory( + agentId, + workspace, + target?.cwd + ); + if (terminals.get(id) !== reservation || socket.destroyed) return; + const child = spawn( + setpriv, + [...childArgs, ...selfCommand("runner-terminal"), cwd], + { + env: terminalEnvironment(env), + stdio: ["pipe", "pipe", "ignore"], + } + ); + child.on("error", () => channel.destroy()); + const channel = Duplex.from({ + readable: child.stdout, + writable: child.stdin, + }); + channels.set(id, channel); + let ready = false; + channel.on("error", () => channel.destroy()); + channel.once("close", () => { + child.kill(); + terminals.delete(id); + channels.delete(id); + if (!ready) + safeSend({ + type: "result", + id, + error: + "The runner could not start a terminal in this checkout.", + }); + safeSend({ type: "close", id }); + }); + wireFrames( + channel, + (event) => { + if ( + !ready && + event && + typeof event === "object" && + "type" in event && + event.type === "ready" && + "info" in event && + isTerminalInfo(event.info) + ) { + ready = true; + result(JSON.stringify(event.info)); + } else if (ready && isTerminalEvent(event)) { + safeSend({ + type: "data", + id, + data: Buffer.from(JSON.stringify(event) + "\n").toString( + "base64" + ), + }); + } else channel.destroy(); + }, + MAX_TERMINAL_FRAME_LENGTH + ); + } catch (error) { + if (terminals.get(id) !== reservation) return; + terminals.delete(id); + throw error; + } + break; + } case "watchCheckout": { const cwd = await supervisor.checkoutDirectory( agentId, @@ -890,13 +973,22 @@ export async function runRemoteRunner(filename: string) { ?.abort(new Error("Checkout command cancelled.")); } else if (frame.type === "data") { const channel = channels.get(frame.id); - if (channel && channel.writableLength > 32 * 1024 * 1024) + if ( + channel && + terminals.has(frame.id) && + (channel.writableLength > 128 * 1024 || + frame.data.length > 256 * 1024) + ) + channel.destroy(); + else if (channel && channel.writableLength > 32 * 1024 * 1024) channel.destroy(); else channel?.write(Buffer.from(frame.data, "base64")); } else if (frame.type === "close") { watches.get(frame.id)?.(); watches.delete(frame.id); - channels.get(frame.id)?.destroy(); + const channel = channels.get(frame.id); + if (channel) channel.destroy(); + else terminals.delete(frame.id); } else socket.destroy(); }); socket.once("secureConnect", () => { @@ -919,6 +1011,9 @@ export async function runRemoteRunner(filename: string) { checkoutInspection: true, checkoutMetadata: true, checkoutCommands: true, + ...(typeof Bun !== "undefined" && typeof Bun.Terminal === "function" + ? { terminals: true } + : {}), defaultBranchFiles: true, workspacePreparation: true, sessionCheckout: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 0014dd070..9fd40f12c 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -166,6 +166,7 @@ type Peer = { checkoutInspection: boolean; checkoutMetadata: boolean; checkoutCommands: boolean; + terminals: boolean; defaultBranchFiles: boolean; sessionCheckout: boolean; checkoutRelease: boolean; @@ -705,6 +706,7 @@ export class RemoteRunnerService { defaultBranchFiles: ready.defaultBranchFiles === true, checkoutMetadata: ready.checkoutMetadata === true, checkoutCommands: ready.checkoutCommands === true, + terminals: ready.terminals === true, checkoutInspection: ready.checkoutInspection === true, sharedWorktree: ready.sharedWorktree === true, workspacePreparation: ready.workspacePreparation === true, @@ -1254,7 +1256,9 @@ export class RemoteRunnerService { return this.request( placement, { ...operation, workspace: placement.workspace }, - operation.kind === "attach" || operation.kind === "watchCheckout", + operation.kind === "attach" || + operation.kind === "watchCheckout" || + operation.kind === "openTerminal", onProgress, signal ); @@ -1596,6 +1600,10 @@ export class RemoteRunnerService { throw new RunnerCapabilityUnavailable( "Update the runner to use these checkout options." ); + if (command.kind === "openTerminal" && !peer.terminals) + throw new RunnerCapabilityUnavailable( + "Update this runner to open a terminal." + ); if (command.kind === "checkoutCommand" && !peer.checkoutCommands) throw new RunnerCapabilityUnavailable( "Update the runner to execute checkout commands." diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index fc378d6a9..9a3b213df 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -43,6 +43,9 @@ if (process.argv[2]?.startsWith("recovery-")) { } else if (process.argv[2] === "connect") { const { runRunnerConnect } = await import("./agents/remote/enrollment.js"); await runRunnerConnect(process.argv.slice(3)); +} else if (process.argv[2] === "runner-terminal") { + const { runTerminalWorker } = await import("./terminal/runner-worker.js"); + await runTerminalWorker(process.argv[3]!); } else if (process.argv[2] === "runner-watch-checkout") { const { runCheckoutWatchCli } = await import("./agents/checkout-watch.js"); runCheckoutWatchCli(process.argv[3]!); diff --git a/apps/server/src/routes/agents/streaming-routes.ts b/apps/server/src/routes/agents/streaming-routes.ts index 42de9ab55..d0b6a63b9 100644 --- a/apps/server/src/routes/agents/streaming-routes.ts +++ b/apps/server/src/routes/agents/streaming-routes.ts @@ -28,6 +28,12 @@ export async function registerAgentStreamingRoutes( } if (body?.type === "playwright") { + // The screencast opens a CDP port on this machine's loopback interface. + if (agent.cwd.startsWith("runner://")) { + return reply.code(409).send({ + error: "Playwright screencasts are unavailable for runner sessions.", + }); + } if ( typeof body.port !== "number" || !Number.isFinite(body.port) || diff --git a/apps/server/src/routes/files.ts b/apps/server/src/routes/files.ts index 5e30339e1..1d9356bf7 100644 --- a/apps/server/src/routes/files.ts +++ b/apps/server/src/routes/files.ts @@ -27,21 +27,8 @@ import { sanitizeUploadedFileName, toFileKey, } from "../shared/files.js"; -import { hostClipboardImageCapable } from "../shared/lib/clipboard-capability.js"; -import { writeImageToClipboard } from "../shared/lib/clipboard-write.js"; -import { runCommand } from "../shared/lib/run-command.js"; import type { PublishUiEvent } from "../server/ui-events.js"; -// Per-agent [File #N] sequence counter for terminal injection. In-memory, -// resets on server restart — N is a cosmetic prompt label, not a stable ID. -const fileSeqByAgent = new Map(); - -function nextFileSeq(agentId: string): number { - const seq = (fileSeqByAgent.get(agentId) ?? 0) + 1; - fileSeqByAgent.set(agentId, seq); - return seq; -} - function fileContentUrl(agentId: string, fileName: string): string { return `/api/v1/agents/${agentId}/files/${encodeURIComponent(fileName)}`; } @@ -254,8 +241,8 @@ export async function registerFileRoutes( deps.publishUiEvent({ type: "files.changed", agentId: id }); - // Uploads no longer type into a pane; the agent reads shared files - // through its tools, and Chat attachments carry the reference. + // Uploads store bytes for the session. Clipboard access belongs to the + // operator's browser and never runs as a side effect of an upload. const delivery: "none" = "none"; return reply.code(201).send({ diff --git a/apps/server/src/routes/human-terminals.ts b/apps/server/src/routes/human-terminals.ts index ecca0e478..7eb3b8ef0 100644 --- a/apps/server/src/routes/human-terminals.ts +++ b/apps/server/src/routes/human-terminals.ts @@ -2,6 +2,9 @@ import type { FastifyInstance, FastifyRequest } from "fastify"; import type { Pool } from "pg"; import { realpath, stat } from "node:fs/promises"; import { randomUUID } from "node:crypto"; +import { remotePlacement } from "@dispatch/runner-protocol"; +import { remoteTerminal } from "../terminal/remote.js"; +import type { RemoteRunnerService } from "../agents/remote/service.js"; import { isPasswordSet, validateSession } from "../auth.js"; import { HumanTerminalManager, terminalOwner } from "../terminal/manager.js"; @@ -31,9 +34,12 @@ export function terminalOriginAllowed( type Deps = { pool: Pool; sessionCookie: string; - getAgent: ( - id: string - ) => Promise<{ cwd: string; worktreePath: string | null } | null>; + getAgent: (id: string) => Promise<{ + cwd: string; + worktreePath: string | null; + workspacePath?: string | null; + } | null>; + runner?: Pick | null; manager?: HumanTerminalManager; }; @@ -151,17 +157,28 @@ export async function registerHumanTerminalRoutes( if (!agent) return reply.code(404).send({ error: "Workspace not found." }); try { - const cwd = await realpath(agent.worktreePath || agent.cwd); + const { agentId, clientId } = request.body; + const placement = remotePlacement(agent.cwd); + const unencrypted = request.protocol !== "https"; + if (placement) { + if (!deps.runner) + throw new Error("The session runner is unavailable."); + const backend = remoteTerminal(deps.runner, placement, agentId); + return { + ...(await manager.openRemote(owner, clientId, agentId, backend)), + unencrypted, + }; + } + if (agent.cwd.startsWith("runner://")) + throw new Error("The session runner location is invalid."); + const cwd = await realpath( + agent.workspacePath ?? agent.worktreePath ?? agent.cwd + ); if (!(await stat(cwd)).isDirectory()) throw new Error("Workspace directory is unavailable."); return { - ...manager.open( - owners.get(request)!.owner, - request.body.clientId, - request.body.agentId, - cwd - ), - unencrypted: request.protocol !== "https", + ...manager.open(owner, clientId, agentId, cwd), + unencrypted, }; } catch (error) { return reply.code(409).send({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index c339e7ee3..4b3860e8e 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1030,6 +1030,7 @@ async function registerRoutes() { await registerHumanTerminalRoutes(app, { pool, sessionCookie: SESSION_COOKIE, + runner: remoteRunner, getAgent: (id) => agentManager.getAgent(id), }); diff --git a/apps/server/src/terminal/manager.ts b/apps/server/src/terminal/manager.ts index f6285107c..589814bb5 100644 --- a/apps/server/src/terminal/manager.ts +++ b/apps/server/src/terminal/manager.ts @@ -1,105 +1,37 @@ import { createHash, randomUUID } from "node:crypto"; import { hostname, userInfo } from "node:os"; -import { captureTerminalSession } from "./process-session.js"; +import { spawnTerminal, type PtyProcess, type SpawnTerminal } from "./pty.js"; import type { WebSocket } from "ws"; +import { + isTerminalControl, + MAX_TERMINAL_INPUT_BYTES, + TERMINAL_REPLAY_BYTES, + type TerminalInfo, +} from "@dispatch/runner-protocol"; -export const REPLAY_BYTES = 256 * 1024; +export const REPLAY_BYTES = TERMINAL_REPLAY_BYTES; export const DISCONNECT_GRACE_MS = 60_000; -const MAX_INPUT_BYTES = 16 * 1024; export function terminalOwner(session: string): string { return createHash("sha256").update(session).digest("hex"); } -/** Start from a small allowlist: never inherit Dispatch/agent tokens or hooks. */ -export function terminalEnvironment( - source = process.env -): Record { - const env: Record = { - TERM: "xterm-256color", - COLORTERM: "truecolor", - }; - for (const key of [ - "HOME", - "USER", - "LOGNAME", - "SHELL", - "PATH", - "LANG", - "LC_ALL", - "LC_CTYPE", - "TZ", - "TMPDIR", - ]) { - if (source[key]) env[key] = source[key]!; - } - return env; -} - -export type PtyProcess = { - pid: number; - terminal: { - write(data: string): number; - resize(cols: number, rows: number): void; - close(): void; - }; - exited: Promise; +type TerminalProcess = TerminalInfo & { + terminal: PtyProcess["terminal"] & { detach?(): void; resume?(): void }; + exited: Promise; kill(): void; }; -export type SpawnTerminal = ( - cwd: string, - output: (data: Uint8Array) => void -) => PtyProcess; -export const spawnTerminal: SpawnTerminal = (cwd, output) => { - if ( - typeof Bun === "undefined" || - typeof Bun.Terminal !== "function" || - process.platform === "win32" - ) { - throw new Error( - "Human terminals require Bun 1.3.13 or newer on macOS or Linux." - ); - } - if (process.getuid?.() === 0) - throw new Error( - "Human terminals require Dispatch to run as an ordinary OS user." - ); - const shell = userInfo().shell || "/bin/sh"; - const proc = Bun.spawn([shell, "-l"], { - cwd, - env: terminalEnvironment(), - terminal: { cols: 80, rows: 24, data: (_terminal, data) => output(data) }, - }); - let cleanup: () => void; - try { - cleanup = captureTerminalSession(proc.pid); - } catch (error) { - proc.terminal?.close(); - proc.kill("SIGKILL"); - throw error; - } - return { - pid: proc.pid, - terminal: proc.terminal!, - exited: proc.exited, - kill() { - try { - cleanup(); - } finally { - proc.terminal?.close(); - } - }, - }; -}; +export type TerminalBackend = ( + output: (data: Uint8Array) => void +) => Promise; type TerminalSession = { id: string; owner: string; clientId: string; agentId: string; - cwd: string; - process: PtyProcess; + process: TerminalProcess; replay: Buffer; socket?: WebSocket; expiry?: ReturnType; @@ -112,31 +44,39 @@ export class HumanTerminalManager { private graceMs = DISCONNECT_GRACE_MS ) {} - open(owner: string, clientId: string, agentId: string, cwd: string) { - const existing = [...this.sessions.values()].find( + private pending = new Map< + string, + { + owner: string; + opened: Promise>; + } + >(); + + private existing(owner: string, clientId: string, agentId: string) { + return [...this.sessions.values()].find( (s) => s.owner === owner && s.clientId === clientId && s.agentId === agentId ); - if (existing) return this.describe(existing); + } + + private reserve(owner: string, clientId: string, agentId: string) { + const active = [...this.sessions.values(), ...this.pending.values()]; if ( - this.sessions.size >= 16 || - [...this.sessions.values()].filter((s) => s.owner === owner).length >= 4 - ) { + active.length >= 16 || + active.filter((s) => s.owner === owner).length >= 4 + ) throw new Error( "Terminal limit reached. End an existing terminal first." ); - } - const id = randomUUID(); const session: TerminalSession = { - id, + id: randomUUID(), owner, clientId, agentId, - cwd, - process: undefined as unknown as PtyProcess, + process: undefined as unknown as TerminalProcess, replay: Buffer.alloc(0), }; - session.process = this.spawn(cwd, (data) => { + const output = (data: Uint8Array) => { const bytes = Buffer.from(data); session.replay = Buffer.concat([session.replay, bytes]).subarray( -REPLAY_BYTES @@ -147,25 +87,70 @@ export class HumanTerminalManager { socket.close(1013, "Terminal output overflow; reconnect to resume."); else socket.send(bytes); } + }; + return { session, output }; + } + + open(owner: string, clientId: string, agentId: string, cwd: string) { + const existing = this.existing(owner, clientId, agentId); + if (existing) return this.describe(existing); + const { session, output } = this.reserve(owner, clientId, agentId); + return this.activate(session, { + ...this.spawn(cwd, output), + cwd, + host: hostname(), + user: userInfo().username, }); + } + + async openRemote( + owner: string, + clientId: string, + agentId: string, + open: TerminalBackend + ) { + const existing = this.existing(owner, clientId, agentId); + if (existing) return this.describe(existing); + const key = JSON.stringify([owner, clientId, agentId]); + const pending = this.pending.get(key); + if (pending) return pending.opened; + const { session, output } = this.reserve(owner, clientId, agentId); + const opened = open(output) + .then((process) => { + if (this.pending.get(key)?.opened !== opened) { + process.kill(); + throw new Error("Terminal was closed before it could open."); + } + return this.activate(session, process); + }) + .finally(() => { + if (this.pending.get(key)?.opened === opened) this.pending.delete(key); + }); + this.pending.set(key, { owner, opened }); + return opened; + } + + private activate(session: TerminalSession, process: TerminalProcess) { + const { id, owner } = session; + session.process = process; this.sessions.set(id, session); this.expire(session); - void session.process.exited.then((code) => { + void process.exited.then((code) => { if (this.sessions.get(id) !== session) return; - session.socket?.send(JSON.stringify({ type: "exit", code })); - this.end(id, owner); + if (code === null) { + this.end(id, owner, "Runner terminal connection ended."); + } else { + if (session.socket?.readyState === 1) + session.socket.send(JSON.stringify({ type: "exit", code })); + this.end(id, owner); + } }); return this.describe(session); } private describe(s: TerminalSession) { - return { - id: s.id, - agentId: s.agentId, - cwd: s.cwd, - host: hostname(), - user: userInfo().username, - }; + const { cwd, host, user } = s.process; + return { id: s.id, agentId: s.agentId, cwd, host, user }; } resume(id: string, owner: string, clientId: string, agentId: string) { const s = this.sessions.get(id); @@ -192,6 +177,12 @@ export class HumanTerminalManager { s.socket = socket; socket.send(JSON.stringify({ type: "connected" })); if (s.replay.length) socket.send(s.replay); + try { + s.process.terminal.resume?.(); + } catch { + this.end(id, owner, "Runner terminal connection ended."); + return true; + } let budget = 64 * 1024; let last = Date.now(); socket.on("message", (data, binary) => { @@ -204,26 +195,22 @@ export class HumanTerminalManager { last = Date.now(); } budget -= size; - if (binary || size > MAX_INPUT_BYTES || budget < 0) { + if (binary || size > MAX_TERMINAL_INPUT_BYTES || budget < 0) { socket.close(1008, "Terminal input limit exceeded."); return; } try { const message = JSON.parse(data.toString()); - if (message.type === "input" && typeof message.data === "string") { + if (!isTerminalControl(message)) { + socket.close(1008, "Invalid terminal message."); + return; + } + if (message.type === "input") { const written = s.process.terminal.write(message.data); // Bun's write returns accepted bytes; don't silently lose keystrokes. if (written < Buffer.byteLength(message.data)) socket.close(1013, "Terminal input buffer full."); - } else if ( - message.type === "resize" && - Number.isInteger(message.cols) && - Number.isInteger(message.rows) && - message.cols >= 2 && - message.cols <= 500 && - message.rows >= 1 && - message.rows <= 200 - ) { + } else if (message.type === "resize") { s.process.terminal.resize(message.cols, message.rows); } else socket.close(1008, "Invalid terminal message."); } catch { @@ -233,20 +220,26 @@ export class HumanTerminalManager { socket.on("close", () => { if (s.socket === socket) { s.socket = undefined; - this.expire(s); + try { + s.process.terminal.detach?.(); + this.expire(s); + } catch { + this.end(id, owner); + } } }); socket.on("error", () => socket.close()); return true; } - end(id: string, owner: string): boolean { + end(id: string, owner: string, reason = "Terminal ended."): boolean { const s = this.sessions.get(id); if (!s || s.owner !== owner) return false; this.sessions.delete(id); clearTimeout(s.expiry); - s.socket?.close(1000, "Terminal ended."); - // The adapter retains the kernel session identity even after shell exit. + const socket = s.socket; + s.socket = undefined; + socket?.close(1000, reason); try { s.process.kill(); } catch { @@ -261,6 +254,7 @@ export class HumanTerminalManager { return true; } shutdown() { + this.pending.clear(); for (const s of this.sessions.values()) this.end(s.id, s.owner); } } diff --git a/apps/server/src/terminal/pty.ts b/apps/server/src/terminal/pty.ts new file mode 100644 index 000000000..9097fcc9e --- /dev/null +++ b/apps/server/src/terminal/pty.ts @@ -0,0 +1,84 @@ +import { userInfo } from "node:os"; +import { captureTerminalSession } from "./process-session.js"; + +/** Start from a small allowlist: never inherit Dispatch/agent tokens or hooks. */ +export function terminalEnvironment( + source = process.env +): Record { + const env: Record = { + TERM: "xterm-256color", + COLORTERM: "truecolor", + }; + for (const key of [ + "HOME", + "USER", + "LOGNAME", + "SHELL", + "PATH", + "LANG", + "LC_ALL", + "LC_CTYPE", + "TZ", + "TMPDIR", + ]) { + if (source[key]) env[key] = source[key]!; + } + return env; +} + +export type PtyProcess = { + pid: number; + terminal: { + write(data: string): number; + resize(cols: number, rows: number): void; + close(): void; + }; + exited: Promise; + kill(): void; +}; +export type SpawnTerminal = ( + cwd: string, + output: (data: Uint8Array) => void +) => PtyProcess; + +export const spawnTerminal: SpawnTerminal = (cwd, output) => { + if ( + typeof Bun === "undefined" || + typeof Bun.Terminal !== "function" || + process.platform === "win32" + ) { + throw new Error( + "Human terminals require Bun 1.3.13 or newer on macOS or Linux." + ); + } + if (process.getuid?.() === 0) + throw new Error( + "Human terminals require Dispatch to run as an ordinary OS user." + ); + const shell = userInfo().shell || "/bin/sh"; + const proc = Bun.spawn([shell, "-l"], { + cwd, + env: terminalEnvironment(), + terminal: { cols: 80, rows: 24, data: (_terminal, data) => output(data) }, + }); + let cleanup: () => void; + try { + cleanup = captureTerminalSession(proc.pid); + } catch (error) { + proc.terminal?.close(); + proc.kill("SIGKILL"); + throw error; + } + return { + pid: proc.pid, + terminal: proc.terminal!, + exited: proc.exited, + kill() { + try { + cleanup(); + } finally { + proc.terminal?.close(); + } + }, + }; +}; diff --git a/apps/server/src/terminal/remote.ts b/apps/server/src/terminal/remote.ts new file mode 100644 index 000000000..e24a6445e --- /dev/null +++ b/apps/server/src/terminal/remote.ts @@ -0,0 +1,66 @@ +import { + isTerminalEvent, + isTerminalInfo, + MAX_TERMINAL_FRAME_LENGTH, + type Placement, + type TerminalControl, +} from "@dispatch/runner-protocol"; +import { wireFrames } from "@dispatch/runner-protocol/node"; +import type { RemoteRunnerService } from "../agents/remote/service.js"; +import type { TerminalBackend } from "./manager.js"; + +export function remoteTerminal( + runner: Pick, + placement: Placement, + agentId: string +): TerminalBackend { + return async (output) => { + const { value, channel } = await runner.requestSession(placement, { + kind: "openTerminal", + agentId, + }); + try { + const info: unknown = + typeof value === "string" ? JSON.parse(value) : null; + if (!channel || !isTerminalInfo(info)) + throw new Error("Invalid runner terminal response."); + let finish!: (code: number | null) => void; + const exited = new Promise((resolve) => { + finish = resolve; + }); + channel.once("close", () => finish(null)); + channel.once("end", () => finish(null)); + const send = wireFrames( + channel, + (event) => { + if (!isTerminalEvent(event)) return channel.destroy(); + if (event.type === "output") + output(Buffer.from(event.data, "base64")); + else { + finish(event.type === "exit" ? event.code : null); + channel.destroy(); + } + }, + MAX_TERMINAL_FRAME_LENGTH + ); + return { + ...info, + exited, + kill: () => channel.destroy(), + terminal: { + write(data) { + send({ type: "input", data }); + return Buffer.byteLength(data); + }, + resize: (cols, rows) => send({ type: "resize", cols, rows }), + close: () => channel.destroy(), + detach: () => send({ type: "detach" }), + resume: () => send({ type: "resume" }), + }, + }; + } catch (error) { + channel?.destroy(); + throw error; + } + }; +} diff --git a/apps/server/src/terminal/runner-worker.ts b/apps/server/src/terminal/runner-worker.ts new file mode 100644 index 000000000..91bbd0077 --- /dev/null +++ b/apps/server/src/terminal/runner-worker.ts @@ -0,0 +1,104 @@ +import { hostname, userInfo } from "node:os"; +import { Duplex } from "node:stream"; +import { + isTerminalControl, + MAX_TERMINAL_FRAME_LENGTH, + TERMINAL_REPLAY_BYTES, + type TerminalEvent, + type TerminalInfo, +} from "@dispatch/runner-protocol"; +import { wireFrames } from "@dispatch/runner-protocol/node"; +import { spawnTerminal, type PtyProcess } from "./pty.js"; + +type TerminalWorkerEvent = + | TerminalEvent + | { type: "ready"; info: TerminalInfo }; + +/** Runs with the configured workload UID, GID and home. */ +export async function runTerminalWorker(cwd: string) { + const io = Duplex.from({ readable: process.stdin, writable: process.stdout }); + let detached = false; + let replay = Buffer.alloc(0); + const { uid, username } = userInfo(); + const info = { + cwd, + host: hostname(), + user: username === "unknown" ? `uid ${uid}` : username, + }; + let pty: PtyProcess | undefined; + const send = wireFrames( + io, + (message) => { + if (!isTerminalControl(message)) + throw new Error("Invalid terminal control."); + if (!pty) throw new Error("Terminal has not started."); + switch (message.type) { + case "input": + if ( + !detached && + pty.terminal.write(message.data) < Buffer.byteLength(message.data) + ) { + send({ type: "error", message: "Terminal input buffer full." }); + io.end(); + } + break; + case "resize": + if (!detached) pty.terminal.resize(message.cols, message.rows); + break; + case "detach": + detached = true; + break; + case "resume": + detached = false; + if (replay.length) + send({ type: "output", data: replay.toString("base64") }); + replay = Buffer.alloc(0); + break; + } + }, + MAX_TERMINAL_FRAME_LENGTH + ); + const close = () => io.destroy(); + const cleanup = () => { + process.off("SIGTERM", close); + process.stdin.destroy(); + try { + pty?.kill(); + } catch { + // The shell may already have exited. + } + }; + process.once("SIGTERM", close); + io.on("error", close); + io.on("finish", close); + io.once("close", cleanup); + try { + pty = spawnTerminal(cwd, (data) => { + const bytes = Buffer.from(data); + if (detached) { + replay = Buffer.concat([replay, bytes]).subarray( + -TERMINAL_REPLAY_BYTES + ); + } else if (!io.destroyed) { + try { + send({ type: "output", data: bytes.toString("base64") }); + } catch { + io.destroy(); + } + } + }); + } catch (error) { + close(); + throw error; + } + send({ type: "ready", info }); + const code = await pty.exited; + if (!io.destroyed && !io.writableEnded) { + try { + send({ type: "exit", code }); + io.end(); + } catch { + io.destroy(); + } + } +} diff --git a/apps/server/test/human-terminals.test.ts b/apps/server/test/human-terminals.test.ts index 3477ee563..b1533ab0f 100644 --- a/apps/server/test/human-terminals.test.ts +++ b/apps/server/test/human-terminals.test.ts @@ -5,12 +5,8 @@ import { EventEmitter } from "node:events"; import { afterEach, describe, expect, it, vi } from "vitest"; import { WebSocket } from "ws"; import type { Pool } from "pg"; -import { - HumanTerminalManager, - REPLAY_BYTES, - terminalEnvironment, - type PtyProcess, -} from "../src/terminal/manager.js"; +import { HumanTerminalManager, REPLAY_BYTES } from "../src/terminal/manager.js"; +import { terminalEnvironment, type PtyProcess } from "../src/terminal/pty.js"; import { registerHumanTerminalRoutes, terminalOriginAllowed, diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index e35d76169..03f018660 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -701,7 +701,7 @@ describe("runner enrollment service", () => { ); }); - it("gates worktree reuse and inspection before sending requests to older peers", async () => { + it("gates worktree reuse, inspection and terminals before sending requests to older peers", async () => { const service = makeService(); const a = await enroll(service, "alpha"); const placement = { runner: a.id, workspace: "@session" }; @@ -743,6 +743,12 @@ describe("runner enrollment service", () => { await expect(service.requestSession(placement, launch)).rejects.toThrow( "Update the runner" ); + await expect( + service.requestSession(placement, { + kind: "openTerminal", + agentId: "author", + }) + ).rejects.toThrow("Update this runner to open a terminal."); expect(legacy.requests.filter((f) => f.type === "request")).toEqual([]); } finally { legacy.socket.destroy(); diff --git a/apps/server/test/runner-protocol-consumer.test.ts b/apps/server/test/runner-protocol-consumer.test.ts index ff9401842..41605817b 100644 --- a/apps/server/test/runner-protocol-consumer.test.ts +++ b/apps/server/test/runner-protocol-consumer.test.ts @@ -1,6 +1,12 @@ import { Duplex } from "node:stream"; import { type Frame, + type TerminalControl, + type TerminalEvent, + MAX_TERMINAL_FRAME_LENGTH, + isTerminalInfo, + isTerminalControl, + isTerminalEvent, type RemoteLaunch, type RunnerFrame, type SessionReply, @@ -1732,3 +1738,92 @@ it.each([true, false])( } } ); + +it.each([true, false])( + "an independent service uses a terminal channel only when negotiated: %s", + async (terminals) => { + const ready = parseReadyFrame({ + type: "ready", + version: 1, + workspaces: ["execution/β"], + ...(terminals && { terminals: true }), + }); + const sent: ServiceFrame[] = []; + const connection = new RunnerConnection((frame) => sent.push(frame)); + const open = () => + ready?.terminals + ? connection.request( + { + kind: "openTerminal", + workspace: "execution/β", + agentId: "service/session-42", + }, + { openChannel: true } + ) + : null; + const opened = open(); + if (!terminals) { + expect(opened).toBeNull(); + expect(sent).toEqual([]); + return; + } + + const request = parseServiceFrame(sent[0]); + expect(request).toMatchObject({ + type: "request", + command: { + kind: "openTerminal", + workspace: "execution/β", + agentId: "service/session-42", + }, + }); + if (request?.type !== "request") + throw new Error("Missing terminal request"); + const { id } = request; + const info = { cwd: "/execution/session", host: "guest", user: "workload" }; + connection.receive({ type: "result", id, value: JSON.stringify(info) }); + const { value, channel } = (await opened)!; + expect(isTerminalInfo(JSON.parse(String(value)))).toBe(true); + expect(JSON.parse(String(value))).toEqual(info); + const events: TerminalEvent[] = []; + const send = wireFrames( + channel!, + (value) => { + if (!isTerminalEvent(value)) throw new Error("Invalid terminal event"); + events.push(value); + }, + MAX_TERMINAL_FRAME_LENGTH + ); + const controls: TerminalControl[] = [ + { type: "resize", cols: 110, rows: 40 }, + { type: "input", data: "cat marker.txt\r" }, + { type: "detach" }, + { type: "resume" }, + ]; + controls.forEach(send); + const decoded = sent.slice(1).map((frame) => { + if (frame.type !== "data" || frame.id !== id) + throw new Error("Wrong channel"); + const value = JSON.parse(Buffer.from(frame.data, "base64").toString()); + expect(isTerminalControl(value)).toBe(true); + return value; + }); + expect(decoded).toEqual(controls); + expect(isTerminalControl({ type: "resize", cols: 501, rows: 10 })).toBe( + false + ); + + const output = { + type: "output", + data: Buffer.from([0, 255]).toString("base64"), + }; + const record = Buffer.from(JSON.stringify(output) + "\n"); + for (const part of [record.subarray(0, 6), record.subarray(6)]) { + connection.receive({ type: "data", id, data: part.toString("base64") }); + } + await vi.waitFor(() => expect(events).toEqual([output])); + channel!.destroy(); + expect(sent.at(-1)).toEqual({ type: "close", id }); + connection.close(); + } +); diff --git a/apps/web/src/components/app/agent-card-details.tsx b/apps/web/src/components/app/agent-card-details.tsx index e28ca2560..4ab703b40 100644 --- a/apps/web/src/components/app/agent-card-details.tsx +++ b/apps/web/src/components/app/agent-card-details.tsx @@ -207,8 +207,12 @@ export function AgentCardDetails({
    - {!remoteLocation && workspaceDir ? ( - + {workspaceDir ? ( + ) : null} {!remoteLocation && } {!remoteLocation && agent.gitContext?.isWorktree && workspaceDir ? ( diff --git a/apps/web/src/components/app/ide-launch-button.tsx b/apps/web/src/components/app/ide-launch-button.tsx index 9eb78ed93..297204ee8 100644 --- a/apps/web/src/components/app/ide-launch-button.tsx +++ b/apps/web/src/components/app/ide-launch-button.tsx @@ -73,9 +73,11 @@ const PILL_BASE = export function IdeLaunchButton({ path, enabledIdes = [], + runnerCheckout = false, }: { path: string; enabledIdes?: IdeType[]; + runnerCheckout?: boolean; }): JSX.Element { const [preferredIde, setPreferredIde] = useAtom(preferredIdeAtom); const onLoopback = isLoopbackHost(); @@ -83,7 +85,7 @@ export function IdeLaunchButton({ // Empty-state CTA: when on loopback with no IDEs enabled, show a discoverable // pill that links into Settings → Workspace so users find the toggle. - if (onLoopback && orderedEnabled.length === 0) { + if (!runnerCheckout && onLoopback && orderedEnabled.length === 0) { return ( @@ -107,10 +109,11 @@ export function IdeLaunchButton({ ); } - // Remote (non-loopback): render a disabled button so the feature is - // discoverable but the URL handler isn't fired against a path that doesn't - // exist on the user's machine. - if (!onLoopback) { + // The browser invokes a URL handler on its own desktop. + if (runnerCheckout || !onLoopback) { + const reason = runnerCheckout + ? "Open in IDE is unavailable for runner checkouts" + : "Open in IDE does not work when accessing Dispatch remotely"; const fallbackIde = orderedEnabled[0] ?? (IDE_TYPES.includes(preferredIde) ? preferredIde : "vscode"); @@ -121,7 +124,11 @@ export function IdeLaunchButton({ variant="ghost" size="sm" disabled - aria-label="Open in IDE (unavailable on remote access)" + aria-label={ + runnerCheckout + ? reason + : "Open in IDE (unavailable on remote access)" + } data-testid="ide-launch-disabled" className={cn( "rounded-full disabled:opacity-50 disabled:pointer-events-auto", @@ -129,11 +136,10 @@ export function IdeLaunchButton({ )} > + {runnerCheckout && IDE unavailable} - - Open in IDE does not work when accessing Dispatch remotely - + {reason} ); } diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 509c9e62c..0ce56cd8e 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -111,7 +111,7 @@ shares its reset coordinator across HTTP and MCP. client. Live provider sign-ins and paid account actions require separate acceptance evidence. -**Human terminals and desktop integrations.** **Decision per capability.** A human PTY opened in the agent checkout needs machine-local process, resize, input, detach/resume and close. Desktop IDE, clipboard, browser and computer-use actions need an explicit target and OS permissions. Some belong to the operator’s desktop, even when the agent runs elsewhere. +**Human terminals and desktop integrations.** The native and enrolled runner paths open the PTY in the selected checkout. Enrolled peers advertise the optional terminal channel. Desktop actions follow the [target and permissions table](../macos-app.md#session-terminals-and-desktop-actions). - Keep native Mac behavior. A remote terminal, if offered, opens in the correct guest with the correct identity. Never interpret a remote path as a request to open a Mac file. [Human terminal manager](../../apps/server/src/terminal/manager.ts) · [Clipboard behavior](../../apps/server/src/routes/files.ts) · [Mac integration](../macos-app.md) diff --git a/docs/macos-app.md b/docs/macos-app.md index 7443e23f1..b024fa903 100644 --- a/docs/macos-app.md +++ b/docs/macos-app.md @@ -233,3 +233,20 @@ database is contacted. The notarized SMAppService proof is documented in [macos-sparkle-service-proof.md](macos-sparkle-service-proof.md); its scripts and results remain for regression investigations. + +### Session terminals and desktop actions + +The Terminal drawer opens the session's effective checkout. The built-in +runner starts the shell under the Dispatch service's ordinary Mac user. +An enrolled runner with terminal support starts it under its own workload user +and reports that machine, user, and checkout in the drawer. A runner that +doesn't advertise terminal support returns an upgrade message. + +| Action | Where it runs | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Open in IDE | The operator browser invokes the desktop's VS Code or Cursor URL handler for a native checkout on loopback. Runner checkouts show an unavailable action, including when the browser is on loopback. | +| Copy or paste files and text | The operator browser owns the clipboard. Uploads transfer file bytes and require no clipboard permission on the runner or service. | +| Open Dispatch, Finder, and Settings links | The menu app opens these on the operator Mac using macOS integration. | +| Browser Feedback | The operator's browser extension captures the tab where it is installed. An enrolled session can receive the resulting evidence. | +| Session Playwright screencast | The Dispatch service reads a browser debug port on its execution machine for native sessions. Enrolled sessions get an unsupported response until there is a runner-side capture transport. | +| Computer-use tools | Dispatch has no session computer-use relay. A separately configured tool acts where its own desktop integration runs and needs that machine's OS permissions. Enrollment grants no desktop permissions. | diff --git a/e2e/remote-runner/playwright.config.ts b/e2e/remote-runner/playwright.config.ts index d7e34fe58..b98322cd0 100644 --- a/e2e/remote-runner/playwright.config.ts +++ b/e2e/remote-runner/playwright.config.ts @@ -20,6 +20,8 @@ export default defineConfig({ env: { ...((base.webServer as { env?: Record }).env ?? {}), DISPATCH_HOST: "127.0.0.1", + // Exercise the browser terminal cookie without changing shared auth. + DISPATCH_DEV_STACK: "1", DISPATCH_RUNNER_HOST: process.env.DISPATCH_RUNNER_HOST ?? "", DISPATCH_RUNNER_REPO_TOOL: process.env.DISPATCH_RUNNER_REPO_TOOL ?? "", DISPATCH_RUNNER_PORT: process.env.DISPATCH_RUNNER_PORT ?? "", diff --git a/e2e/remote-runner/terminal.spec.ts b/e2e/remote-runner/terminal.spec.ts new file mode 100644 index 000000000..72ec09c30 --- /dev/null +++ b/e2e/remote-runner/terminal.spec.ts @@ -0,0 +1,209 @@ +import { test, expect, type Page } from "@playwright/test"; +import { join } from "node:path"; +import { authHeaders, cleanupE2EAgents, createAgentViaAPI } from "../helpers"; +import { + agentInfo, + enrollViaUi, + guest, + guestOk, + marker, + runnerRow, + state, +} from "./harness"; + +test.use({ actionTimeout: 10_000 }); + +test.afterAll(async ({ request }) => cleanupE2EAgents(request)); + +async function openTerminal(page: Page) { + const tab = page.getByTestId("sidebar-tab-terminal"); + await expect(page.getByTestId("chat-pane")).toBeVisible(); + const box = await tab.boundingBox(); + if (!box || box.x >= page.viewportSize()!.width) + await page.getByTestId("toggle-drawer").click(); + await tab.click(); + const panel = page.getByRole("region", { name: "Terminal", exact: true }); + await expect(panel.getByRole("status")).toHaveText("Connected"); + return panel; +} + +for (const lane of ["native", "runner", "managed"] as const) { + const remote = lane !== "native"; + const guestName = lane === "managed" ? "scratch" : "alpha"; + test(`${lane} terminal keeps its shell through a browser reconnect`, async ({ + browser, + page, + request, + }, testInfo) => { + const runner = remote + ? ((await runnerRow(request, guestName))?.id ?? + (await enrollViaUi(page, request, guestName))) + : null; + const ideSettings = "/api/v1/app/settings/ides"; + const headers = authHeaders(); + const previousIdes = await ( + await request.get(ideSettings, { headers }) + ).json(); + const enabled = await request.post(ideSettings, { + headers, + data: { enabledIdes: ["vscode"] }, + }); + expect(enabled.ok()).toBe(true); + const agent = await createAgentViaAPI(request, { + name: `e2e-${lane}-terminal`, + cwd: runner + ? `runner://${runner}/${lane === "managed" ? "@session" : state.workspace}` + : "/tmp", + }); + const context = await browser.newContext({ + viewport: remote + ? { width: 390, height: 844 } + : { width: 1440, height: 900 }, + deviceScaleFactor: 2, + }); + try { + await expect + .poll(async () => (await agentInfo(request, agent.id)).status, { + timeout: 15_000, + }) + .toBe("running"); + let target = state.runners.alpha.workspaceDir; + let expectedMarker = lane === "runner" ? marker("alpha") : ""; + if (lane === "managed") { + target = `/tmp/terminal-checkout-${agent.id}`; + expectedMarker = `managed-marker-${agent.id}`; + guest( + guestName, + `install -d -o 1500 -g 1500 '${target}' && printf '%s\n' '${expectedMarker}' >'${target}/marker.txt'` + ); + const moved = await request.patch( + `/api/v1/agents/${agent.id}/workspace`, + { + headers, + data: { path: target }, + } + ); + expect(moved.ok(), await moved.text()).toBe(true); + } + const session = await context.newPage(); + const screenshot = async (phase: string) => { + const name = `terminal-${lane}-${phase}.png`; + const evidence = process.env.RUNNER_TERMINAL_EVIDENCE; + const path = evidence + ? join(evidence, name) + : testInfo.outputPath(name); + await session.screenshot({ path }); + await testInfo.attach(name, { path, contentType: "image/png" }); + }; + let output = ""; + let resize: { cols: number; rows: number } | undefined; + session.on("websocket", (socket) => { + if (!socket.url().includes("/human-terminals/")) return; + socket.on("framereceived", ({ payload }) => { + if (Buffer.isBuffer(payload)) output += payload.toString("utf8"); + }); + socket.on("framesent", ({ payload }) => { + if (typeof payload !== "string") return; + const message = JSON.parse(payload); + if (message.type === "resize") resize = message; + }); + }); + + await session.goto(`/agents/${agent.id}`, { + waitUntil: "domcontentloaded", + }); + const expand = session.getByTestId(`agent-expand-toggle-${agent.id}`); + await expect(session.getByTestId("chat-pane")).toBeVisible(); + const openSidebar = session.getByTitle("Open sidebar", { exact: true }); + if (await openSidebar.isVisible()) await openSidebar.click(); + await expect(expand).toHaveAttribute("aria-expanded", "true"); + if (remote) { + const action = session.getByRole("button", { + name: "Open in IDE is unavailable for runner checkouts", + }); + await expect(action).toBeDisabled(); + await action.scrollIntoViewIfNeeded(); + await expect(action).toBeInViewport({ ratio: 0.8 }); + await expect(session.locator('a[href^="vscode:"]')).toHaveCount(0); + const stream = await request.post(`/api/v1/agents/${agent.id}/stream`, { + headers, + data: { type: "playwright", port: 9222 }, + }); + expect(stream.status()).toBe(409); + expect((await stream.json()).error).toContain( + "unavailable for runner sessions" + ); + } else { + const action = session.getByTestId("ide-launch-button"); + await action.scrollIntoViewIfNeeded(); + await expect(action).toBeInViewport({ ratio: 0.8 }); + await expect(action).toHaveAttribute( + "href", + /^vscode:\/\/file\/(private\/)?tmp$/ + ); + } + await screenshot("ide"); + if (remote) + await session + .getByTestId("sidebar-shell") + .getByTitle("Close sidebar") + .click(); + + let panel = await openTerminal(session); + const open = await session.evaluate( + (id) => sessionStorage.getItem(`dispatch:human-terminal:${id}`), + agent.id + ); + expect(open).toBeTruthy(); + await expect.poll(() => resize).toBeTruthy(); + const input = session.getByLabel("Host terminal").locator("textarea"); + const type = async (command: string) => { + await input.pressSequentially(command); + await input.press("Enter"); + }; + await type( + remote + ? `cat marker.txt; stty size; printf 'PTY_PID_%s\\n' $$; printf 'PTY_UID_%s\\n' "$(id -u)"` + : "stty size; printf 'PTY_PID_%s\\n' $$" + ); + if (remote) { + await expect(panel.getByText(target, { exact: true })).toBeVisible(); + await expect.poll(() => output).toContain(expectedMarker); + await expect.poll(() => output).toContain("PTY_UID_1500"); + } + const initialSize = resize!; + await expect + .poll(() => output) + .toContain(`${initialSize.rows} ${initialSize.cols}`); + await expect.poll(() => /PTY_PID_(\d+)/.test(output)).toBe(true); + const pid = /PTY_PID_(\d+)/.exec(output)![1]; + await screenshot("connected"); + + output = ""; + await session.reload({ waitUntil: "domcontentloaded" }); + panel = await openTerminal(session); + expect( + await session.evaluate( + (id) => sessionStorage.getItem(`dispatch:human-terminal:${id}`), + agent.id + ) + ).toBe(open); + await expect.poll(() => output).toContain(`PTY_PID_${pid}`); + await type("printf 'RESUMED_%s\\n' $$"); + await expect.poll(() => output).toContain(`RESUMED_${pid}`); + await panel.getByRole("button", { name: "End terminal" }).click(); + await expect( + panel.getByRole("button", { name: "New terminal" }) + ).toBeEnabled(); + if (remote) { + await expect + .poll(() => guestOk(guestName, `test -d /proc/${pid}`)) + .toBe(false); + } + await screenshot("ended"); + } finally { + await context.close(); + await request.post(ideSettings, { headers, data: previousIdes }); + } + }); +} diff --git a/packages/runner-protocol/README.md b/packages/runner-protocol/README.md index fbe626c52..e5bd5048a 100644 --- a/packages/runner-protocol/README.md +++ b/packages/runner-protocol/README.md @@ -530,3 +530,36 @@ on success. There is no progress stream for these operations. Scope any host-side cache to the runner. A disconnected or older peer gives an unavailable result. Never substitute another runner's data or the host's own credentials, catalog or plugin state. + +### Session terminals + +The V1 `ready.terminals: true` flag opts into `openTerminal`. Services must +check it before sending this request. Its absence means the peer cannot open a +terminal. No protocol version change is required. + +Use the existing `request` envelope with a fresh channel ID and +`{ kind: "openTerminal", agentId, workspace }`. The two target fields are +opaque IDs obtained from the session's execution binding. The runner resolves +the current checkout and starts the login shell with its workload identity. +The successful result's string value contains JSON `{ cwd, host, user }` +for display. These fields describe the execution machine. + +Open the channel when issuing the request. After the result, send newline- +terminated JSON `TerminalControl` records on the channel. The runner sends +newline-terminated JSON `TerminalEvent` records back. Channel data uses the +existing base64 framing and records can span frames. An `output` record carries +base64 PTY bytes, preserving binary output and partial UTF-8 sequences. +Send `input` with a UTF-8 string (up to 16 KiB) and `resize` with integer +`cols` (2–500) and `rows` (1–200). + +Send `detach` to suspend delivery and buffer the last 256 KiB of new output. +Keep the runner channel open. Send `resume` on that channel to drain the +buffer and continue live delivery. These controls are idempotent. The detached +PTY ignores input and resize until resumed. Services can retain previously +delivered output separately and control how long their frontend is allowed to +reconnect. A runner transport disconnect ends its terminals. + +Destroy the channel or send a channel `close` to end the terminal and clean up +the shell and its process session. The runner sends `exit` on shell exit or +closes the channel if the worker is lost. Browser authentication, browser +session IDs, tabs, and user interface state belong to the service. diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index ba36fee50..fae14004a 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -22,7 +22,12 @@ import { } from "./engine-management.js"; import { isGitHubOperation, type GitHubOperation } from "./github.js"; import type { RunnerHealth } from "./health.js"; -import { isHttpUrl, isNullableString, isRecord } from "./validation.js"; +import { + isBase64, + isHttpUrl, + isNullableString, + isRecord, +} from "./validation.js"; export const RUNNER_WIRE_VERSION = 1; @@ -70,6 +75,7 @@ export type SessionOperation = | SessionLifecycleOperation | { agentId: string; kind: "sessionFile"; operation: SessionFileOperation } | { agentId: string; kind: "watchCheckout" } + | { agentId: string; kind: "openTerminal" } | { agentId: string; kind: "viewCheckout"; query: CheckoutView } | { agentId: string; kind: "inspectCheckout"; query: CheckoutQuery } | { @@ -106,6 +112,7 @@ export type ReadyFrame = { checkoutInspection?: true; checkoutMetadata?: true; checkoutCommands?: true; + terminals?: true; defaultBranchFiles?: true; checkoutViews?: true; sharedWorktree?: true; @@ -138,6 +145,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.checkoutViews === true && { checkoutViews: true }), ...(frame.defaultBranchFiles === true && { defaultBranchFiles: true }), ...(frame.checkoutCommands === true && { checkoutCommands: true }), + ...(frame.terminals === true && { terminals: true }), ...(frame.checkoutMetadata === true && { checkoutMetadata: true }), ...(frame.checkoutInspection === true && { checkoutInspection: true }), ...(frame.sharedWorktree === true && { sharedWorktree: true }), @@ -338,6 +346,7 @@ function isCommand(value: unknown): value is Command { (value.operation.path === null || isCheckoutPath(value.operation.path)))) ); + case "openTerminal": case "watchCheckout": return true; case "viewCheckout": @@ -368,16 +377,6 @@ export function runnerRequestId(value: unknown): string | undefined { : undefined; } -function isBase64(value: unknown): value is string { - if (typeof value !== "string" || /[^A-Za-z0-9+/=]/u.test(value)) return false; - const paddingStart = value.indexOf("="); - if (paddingStart === -1) return value.length % 4 !== 1; - return ( - value.length % 4 === 0 && - (value.slice(paddingStart) === "=" || value.slice(paddingStart) === "==") - ); -} - function isServiceFrame(value: unknown): value is ServiceFrame { if (!isRecord(value)) return false; switch (value.type) { diff --git a/packages/runner-protocol/src/index.ts b/packages/runner-protocol/src/index.ts index 532414b5c..3c9ca1074 100644 --- a/packages/runner-protocol/src/index.ts +++ b/packages/runner-protocol/src/index.ts @@ -8,3 +8,4 @@ export * from "./github.js"; export * from "./checkout-view.js"; export * from "./session-files.js"; export * from "./checkout-command.js"; +export * from "./terminal.js"; diff --git a/packages/runner-protocol/src/node.ts b/packages/runner-protocol/src/node.ts index d7da3c831..d61bdfb79 100644 --- a/packages/runner-protocol/src/node.ts +++ b/packages/runner-protocol/src/node.ts @@ -6,7 +6,8 @@ type Send = (frame: T) => void; export function wireFrames( socket: Duplex, - receive: (frame: Incoming) => void + receive: (frame: Incoming) => void, + maxLineLength = 32 * 1024 * 1024 ): Send { const decoder = new StringDecoder("utf8"); let pending = ""; @@ -14,7 +15,7 @@ export function wireFrames( pending += decoder.write(chunk); let newline: number; while ((newline = pending.indexOf("\n")) >= 0) { - if (newline > 32 * 1024 * 1024) return socket.destroy(); + if (newline > maxLineLength) return socket.destroy(); const line = pending.slice(0, newline); pending = pending.slice(newline + 1); try { @@ -23,7 +24,7 @@ export function wireFrames( return socket.destroy(); } } - if (pending.length > 32 * 1024 * 1024) socket.destroy(); + if (pending.length > maxLineLength) socket.destroy(); }); return (frame) => { if (socket.destroyed || socket.writableLength > 32 * 1024 * 1024) { diff --git a/packages/runner-protocol/src/terminal.ts b/packages/runner-protocol/src/terminal.ts new file mode 100644 index 000000000..1f06553d6 --- /dev/null +++ b/packages/runner-protocol/src/terminal.ts @@ -0,0 +1,72 @@ +import { isBase64, isRecord } from "./validation.js"; + +export const TERMINAL_REPLAY_BYTES = 256 * 1024; +export const MAX_TERMINAL_INPUT_BYTES = 16 * 1024; +export const MAX_TERMINAL_FRAME_LENGTH = 512 * 1024; + +export type TerminalInfo = { cwd: string; host: string; user: string }; +export type TerminalControl = + | { type: "input"; data: string } + | { type: "resize"; cols: number; rows: number } + | { type: "detach" | "resume" }; +export type TerminalEvent = + | { type: "output"; data: string } + | { type: "exit"; code: number } + | { type: "error"; message: string }; + +const utf8 = new TextEncoder(); + +export function isTerminalControl(value: unknown): value is TerminalControl { + if (!isRecord(value)) return false; + switch (value.type) { + case "input": + return ( + typeof value.data === "string" && + value.data.length <= MAX_TERMINAL_INPUT_BYTES && + utf8.encode(value.data).length <= MAX_TERMINAL_INPUT_BYTES + ); + case "resize": + return ( + typeof value.cols === "number" && + Number.isInteger(value.cols) && + value.cols >= 2 && + value.cols <= 500 && + typeof value.rows === "number" && + Number.isInteger(value.rows) && + value.rows >= 1 && + value.rows <= 200 + ); + case "detach": + case "resume": + return true; + default: + return false; + } +} + +export function isTerminalInfo(value: unknown): value is TerminalInfo { + return ( + isRecord(value) && + [value.cwd, value.host, value.user].every( + (field) => + typeof field === "string" && field.length > 0 && field.length <= 8192 + ) + ); +} + +export function isTerminalEvent(value: unknown): value is TerminalEvent { + if (!isRecord(value)) return false; + switch (value.type) { + case "output": + return ( + isBase64(value.data) && + value.data.length <= Math.ceil(TERMINAL_REPLAY_BYTES / 3) * 4 + ); + case "exit": + return typeof value.code === "number" && Number.isInteger(value.code); + case "error": + return typeof value.message === "string" && value.message.length <= 1024; + default: + return false; + } +} diff --git a/packages/runner-protocol/src/validation.ts b/packages/runner-protocol/src/validation.ts index 684c420b3..595cbc1e5 100644 --- a/packages/runner-protocol/src/validation.ts +++ b/packages/runner-protocol/src/validation.ts @@ -20,3 +20,13 @@ export function isHttpUrl(value: unknown, allowHttp = false): value is string { return false; } } + +export function isBase64(value: unknown): value is string { + if (typeof value !== "string" || /[^A-Za-z0-9+/=]/u.test(value)) return false; + const paddingStart = value.indexOf("="); + if (paddingStart === -1) return value.length % 4 !== 1; + return ( + value.length % 4 === 0 && + (value.slice(paddingStart) === "=" || value.slice(paddingStart) === "==") + ); +} diff --git a/scripts/smoke-human-terminal.ts b/scripts/smoke-human-terminal.ts index ec03f341d..297ce9561 100644 --- a/scripts/smoke-human-terminal.ts +++ b/scripts/smoke-human-terminal.ts @@ -1,6 +1,6 @@ /** Run with Bun: real PTY smoke, never requests sudo or uses real credentials. */ import assert from "node:assert/strict"; -import { spawnTerminal } from "../apps/server/src/terminal/manager.js"; +import { spawnTerminal } from "../apps/server/src/terminal/pty.js"; let output = ""; const decoder = new TextDecoder(); const proc = spawnTerminal("/tmp", (data) => { From 1c4c3cd4d9b3e66aadef8a1678f9a99c63d7cdb5 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 18:34:38 -0700 Subject: [PATCH 150/642] Delegate native terminal sessions to the built-in runner --- .agents/owners.json | 8 ++++ apps/server/src/agents/local-runner.ts | 29 +++++++++++- apps/server/src/agents/manager.ts | 11 +++++ apps/server/src/routes/human-terminals.ts | 45 +++++------------- apps/server/src/server.ts | 3 +- apps/server/src/terminal/manager.ts | 22 ++------- apps/server/test/human-terminals.test.ts | 44 ++++++++++++------ e2e/remote-runner/terminal.spec.ts | 56 +++++++++++++++++------ 8 files changed, 135 insertions(+), 83 deletions(-) diff --git a/.agents/owners.json b/.agents/owners.json index e8f696db0..56e354ed7 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -24,6 +24,11 @@ "apps/server/src/agents/**", "apps/server/src/main.ts", "apps/server/src/routes/runners.ts", + "apps/server/src/routes/human-terminals.ts", + "apps/server/src/terminal/**", + "apps/server/test/human-terminals.test.ts", + "apps/server/test/terminal-process-session.test.ts", + "scripts/smoke-human-terminal.ts", "apps/server/src/routes/runner-*.ts", "apps/server/test/remote-*.test.ts", "apps/server/test/checkout-inspection.test.ts", @@ -279,6 +284,7 @@ "apps/server/src/db/migrations/**", "release-notes/**", "docs/macos-releases.md", + "docs/macos-app.md", "docs/design/remote-runner-prototype.md", "docs/remote-runner-linux.md", "bin/**", @@ -361,6 +367,8 @@ "apps/server/src/agents/remote/registry.ts", "apps/server/src/agents/remote/service.ts", "apps/server/src/routes/runners.ts", + "apps/server/src/routes/human-terminals.ts", + "apps/server/test/human-terminals.test.ts", "apps/server/src/multi-listener.ts", "apps/server/src/server/auth-runtime.ts", "apps/server/src/routes/auth.ts", diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index 47e984771..7072ddf82 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -6,10 +6,12 @@ import { readFile, realpath, rm, + stat, unlink, writeFile, } from "node:fs/promises"; import net from "node:net"; +import { hostname, userInfo } from "node:os"; import path from "node:path"; import type { Duplex } from "node:stream"; import type { FastifyBaseLogger } from "fastify"; @@ -49,6 +51,8 @@ import { executeCheckoutCommand } from "./checkout-command-executor.js"; import { readCheckoutCommandFile } from "./checkout-inspection.js"; import type { AgentRecord } from "./types.js"; import { inferRepositoryUrl } from "./remote/repository.js"; +import type { TerminalBackend } from "../terminal/manager.js"; +import { spawnTerminal, type SpawnTerminal } from "../terminal/pty.js"; export type LocalLaunchSettings = Pick< HostLaunch, @@ -133,7 +137,8 @@ function realpathIfPresent(directory: string) { */ export function createLocalRunner( agentStateRoot: string, - logger: FastifyBaseLogger + logger: FastifyBaseLogger, + spawnPty: SpawnTerminal = spawnTerminal ) { function stateDir(agentId: string) { if ( @@ -145,6 +150,27 @@ export function createLocalRunner( throw new Error("Invalid agent state directory"); return path.join(agentStateRoot, agentId); } + function terminalBackend( + checkout: Pick + ): TerminalBackend { + return async (output) => { + stateDir(checkout.id); + if (checkout.cwd.startsWith("runner://")) + throw new Error("Invalid native terminal binding."); + const cwd = await realpath( + checkout.workspacePath ?? checkout.worktreePath ?? checkout.cwd + ); + if (!(await stat(cwd)).isDirectory()) + throw new Error("Workspace directory is unavailable."); + return { + ...spawnPty(cwd, output), + cwd, + host: hostname(), + user: userInfo().username, + }; + }; + } + async function deliverSessionFile(agentId: string, source: string) { stateDir(agentId); // The service resolved this registered attachment for the receiving @@ -406,6 +432,7 @@ export function createLocalRunner( } return { requestSession, + terminalBackend, deliverSessionFile, collectSessionFile, checkoutRelease: localCheckoutRelease, diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index f16c1a96f..79cd0ae9b 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -72,6 +72,8 @@ import { type ChatLaunchPost, shouldSuggestSessionRename, } from "./launch-guidance.js"; +import type { TerminalBackend } from "../terminal/manager.js"; +import { remoteTerminal } from "../terminal/remote.js"; import { createLocalRunner } from "./local-runner.js"; import type { LaunchDirectory, WorktreeRequest } from "./workspace.js"; import { createAgentMcpToken, createJobMcpToken } from "../auth.js"; @@ -1289,6 +1291,15 @@ export class AgentManager { ); } + async terminalBackend(id: string): Promise { + const agent = await this.getAgent(id); + if (!agent) return null; + const placement = remotePlacement(agent.cwd); + if (!placement) return this.localRunner.terminalBackend(agent); + if (!this.remote) throw new Error("The session runner is unavailable."); + return remoteTerminal(this.remote, placement, agent.id); + } + async getAgent(id: string): Promise { const result = await this.pool.query( `${this.baseAgentSelectSql()} AND id = $1`, diff --git a/apps/server/src/routes/human-terminals.ts b/apps/server/src/routes/human-terminals.ts index 7eb3b8ef0..f15205f9d 100644 --- a/apps/server/src/routes/human-terminals.ts +++ b/apps/server/src/routes/human-terminals.ts @@ -1,12 +1,12 @@ import type { FastifyInstance, FastifyRequest } from "fastify"; import type { Pool } from "pg"; -import { realpath, stat } from "node:fs/promises"; import { randomUUID } from "node:crypto"; -import { remotePlacement } from "@dispatch/runner-protocol"; -import { remoteTerminal } from "../terminal/remote.js"; -import type { RemoteRunnerService } from "../agents/remote/service.js"; import { isPasswordSet, validateSession } from "../auth.js"; -import { HumanTerminalManager, terminalOwner } from "../terminal/manager.js"; +import { + HumanTerminalManager, + terminalOwner, + type TerminalBackend, +} from "../terminal/manager.js"; export function terminalOriginAllowed( origin: string | undefined, @@ -34,12 +34,7 @@ export function terminalOriginAllowed( type Deps = { pool: Pool; sessionCookie: string; - getAgent: (id: string) => Promise<{ - cwd: string; - worktreePath: string | null; - workspacePath?: string | null; - } | null>; - runner?: Pick | null; + getBackend: (id: string) => Promise; manager?: HumanTerminalManager; }; @@ -153,32 +148,14 @@ export async function registerHumanTerminalRoutes( }); return { ...resumed, unencrypted: request.protocol !== "https" }; } - const agent = await deps.getAgent(request.body.agentId); - if (!agent) - return reply.code(404).send({ error: "Workspace not found." }); try { const { agentId, clientId } = request.body; - const placement = remotePlacement(agent.cwd); - const unencrypted = request.protocol !== "https"; - if (placement) { - if (!deps.runner) - throw new Error("The session runner is unavailable."); - const backend = remoteTerminal(deps.runner, placement, agentId); - return { - ...(await manager.openRemote(owner, clientId, agentId, backend)), - unencrypted, - }; - } - if (agent.cwd.startsWith("runner://")) - throw new Error("The session runner location is invalid."); - const cwd = await realpath( - agent.workspacePath ?? agent.worktreePath ?? agent.cwd - ); - if (!(await stat(cwd)).isDirectory()) - throw new Error("Workspace directory is unavailable."); + const backend = await deps.getBackend(agentId); + if (!backend) + return reply.code(404).send({ error: "Workspace not found." }); return { - ...manager.open(owner, clientId, agentId, cwd), - unencrypted, + ...(await manager.open(owner, clientId, agentId, backend)), + unencrypted: request.protocol !== "https", }; } catch (error) { return reply.code(409).send({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 4b3860e8e..600e7b6c0 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1030,8 +1030,7 @@ async function registerRoutes() { await registerHumanTerminalRoutes(app, { pool, sessionCookie: SESSION_COOKIE, - runner: remoteRunner, - getAgent: (id) => agentManager.getAgent(id), + getBackend: (id) => agentManager.terminalBackend(id), }); await registerBrowserExtensionRoutes(app, { diff --git a/apps/server/src/terminal/manager.ts b/apps/server/src/terminal/manager.ts index 589814bb5..dc9b51be5 100644 --- a/apps/server/src/terminal/manager.ts +++ b/apps/server/src/terminal/manager.ts @@ -1,6 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { hostname, userInfo } from "node:os"; -import { spawnTerminal, type PtyProcess, type SpawnTerminal } from "./pty.js"; +import type { PtyProcess } from "./pty.js"; import type { WebSocket } from "ws"; import { isTerminalControl, @@ -39,10 +38,7 @@ type TerminalSession = { export class HumanTerminalManager { private sessions = new Map(); - constructor( - private spawn: SpawnTerminal = spawnTerminal, - private graceMs = DISCONNECT_GRACE_MS - ) {} + constructor(private graceMs = DISCONNECT_GRACE_MS) {} private pending = new Map< string, @@ -91,19 +87,7 @@ export class HumanTerminalManager { return { session, output }; } - open(owner: string, clientId: string, agentId: string, cwd: string) { - const existing = this.existing(owner, clientId, agentId); - if (existing) return this.describe(existing); - const { session, output } = this.reserve(owner, clientId, agentId); - return this.activate(session, { - ...this.spawn(cwd, output), - cwd, - host: hostname(), - user: userInfo().username, - }); - } - - async openRemote( + async open( owner: string, clientId: string, agentId: string, diff --git a/apps/server/test/human-terminals.test.ts b/apps/server/test/human-terminals.test.ts index b1533ab0f..4848f89df 100644 --- a/apps/server/test/human-terminals.test.ts +++ b/apps/server/test/human-terminals.test.ts @@ -1,6 +1,8 @@ import Fastify from "fastify"; import cookie from "@fastify/cookie"; import websocket from "@fastify/websocket"; +import { realpath } from "node:fs/promises"; +import { createLocalRunner } from "../src/agents/local-runner.js"; import { EventEmitter } from "node:events"; import { afterEach, describe, expect, it, vi } from "vitest"; import { WebSocket } from "ws"; @@ -35,9 +37,22 @@ function harness(grace = 60_000) { output = callback; return process; }); - const manager = new HumanTerminalManager(spawn, grace); + const manager = new HumanTerminalManager(grace); + const runner = createLocalRunner( + "/tmp", + Fastify({ logger: false }).log, + spawn + ); + const backend = (workspacePath: string | null = null) => + runner.terminalBackend({ + id: "agent", + cwd: "/tmp", + worktreePath: null, + workspacePath, + }); return { manager, + backend, process, spawn, output: (text: string) => output(Buffer.from(text)), @@ -58,11 +73,13 @@ afterEach(() => { }); describe("human terminal lifecycle", () => { - it("keeps one per owner/tab/workspace, rejects foreign owners, replays bounded bytes and expires disconnected processes", () => { + it("keeps one per owner/tab/workspace, rejects foreign owners, replays bounded bytes and expires disconnected processes", async () => { vi.useFakeTimers(); const h = harness(); - const first = h.manager.open("a", "tab", "agent", "/tmp"); - expect(h.manager.open("a", "tab", "agent", "/other")).toEqual(first); + const first = await h.manager.open("a", "tab", "agent", h.backend()); + expect( + await h.manager.open("a", "tab", "agent", h.backend("/other")) + ).toEqual(first); expect(h.spawn).toHaveBeenCalledTimes(1); expect(h.manager.resume(first.id, "b", "tab", "agent")).toBeNull(); expect(h.manager.resume(first.id, "a", "other", "agent")).toBeNull(); @@ -84,9 +101,9 @@ describe("human terminal lifecycle", () => { expect(h.process.kill).toHaveBeenCalledOnce(); expect(h.manager.owns(first.id, "a")).toBe(false); }); - it("limits input, validates dimensions, ends only for its owner and cleans shutdown", () => { + it("limits input, validates dimensions, ends only for its owner and cleans shutdown", async () => { const h = harness(); - const { id } = h.manager.open("a", "tab", "agent", "/tmp"); + const { id } = await h.manager.open("a", "tab", "agent", h.backend()); const ws = socket(); h.manager.attach(id, "a", ws); ws.emit( @@ -141,7 +158,7 @@ describe("terminal browser security", () => { await registerHumanTerminalRoutes(app, { pool: {} as Pool, sessionCookie: "session", - getAgent: async () => ({ cwd: "/tmp", worktreePath: null }), + getBackend: async () => h.backend(), manager: h.manager, }); await app.ready(); @@ -220,11 +237,12 @@ describe("terminal browser security", () => { secret: name + "-cookie-secret-at-least-32bytes", }); await app.register(websocket); + const h = harness(); await registerHumanTerminalRoutes(app, { pool: {} as Pool, sessionCookie: name, - getAgent: async () => ({ cwd: "/tmp", worktreePath: null }), - manager: harness().manager, + getBackend: async () => h.backend(), + manager: h.manager, }); await app.ready(); } @@ -303,7 +321,7 @@ describe("terminal browser security", () => { ) ).toBe(true); }); - it("rejects first-run, bearer-only, bad cookies and cross-owner REST/WS, uses server cwd", async () => { + it("rejects first-run, bearer-only, bad cookies and cross-owner REST/WS, uses the moved native checkout", async () => { const app = Fastify(); await app.register(cookie, { secret: "terminal-test-cookie-secret-32bytes", @@ -313,8 +331,8 @@ describe("terminal browser security", () => { await registerHumanTerminalRoutes(app, { pool: {} as Pool, sessionCookie: "session", - getAgent: async (id) => - id === "agent" ? { cwd: "/tmp", worktreePath: null } : null, + getBackend: async (id) => + id === "agent" ? h.backend(process.cwd()) : null, manager: h.manager, }); await app.ready(); @@ -367,7 +385,7 @@ describe("terminal browser security", () => { ).statusCode ).toBe(200); // Fastify strips extra fields; never forwards them. expect(h.spawn).toHaveBeenCalledWith( - await import("node:fs/promises").then((fs) => fs.realpath("/tmp")), + await realpath(process.cwd()), expect.any(Function) ); const result = await create({ cookie: signed("browser-a") }); diff --git a/e2e/remote-runner/terminal.spec.ts b/e2e/remote-runner/terminal.spec.ts index 72ec09c30..f169d6919 100644 --- a/e2e/remote-runner/terminal.spec.ts +++ b/e2e/remote-runner/terminal.spec.ts @@ -1,4 +1,6 @@ import { test, expect, type Page } from "@playwright/test"; +import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { authHeaders, cleanupE2EAgents, createAgentViaAPI } from "../helpers"; import { @@ -23,7 +25,10 @@ async function openTerminal(page: Page) { await page.getByTestId("toggle-drawer").click(); await tab.click(); const panel = page.getByRole("region", { name: "Terminal", exact: true }); - await expect(panel.getByRole("status")).toHaveText("Connected"); + // Runner opens can wait for checkout resolution and a worker acknowledgement. + await expect(panel.getByRole("status")).toHaveText("Connected", { + timeout: 25_000, + }); return panel; } @@ -61,6 +66,7 @@ for (const lane of ["native", "runner", "managed"] as const) { : { width: 1440, height: 900 }, deviceScaleFactor: 2, }); + let nativeFixture: string | undefined; try { await expect .poll(async () => (await agentInfo(request, agent.id)).status, { @@ -76,6 +82,15 @@ for (const lane of ["native", "runner", "managed"] as const) { guestName, `install -d -o 1500 -g 1500 '${target}' && printf '%s\n' '${expectedMarker}' >'${target}/marker.txt'` ); + } else if (lane === "native") { + nativeFixture = await mkdtemp( + join(tmpdir(), "dispatch-native-terminal-") + ); + target = await realpath(nativeFixture); + expectedMarker = `native-marker-${agent.id}`; + await writeFile(join(target, "marker.txt"), expectedMarker + "\n"); + } + if (lane !== "runner") { const moved = await request.patch( `/api/v1/agents/${agent.id}/workspace`, { @@ -96,6 +111,7 @@ for (const lane of ["native", "runner", "managed"] as const) { await testInfo.attach(name, { path, contentType: "image/png" }); }; let output = ""; + let submitted = ""; let resize: { cols: number; rows: number } | undefined; session.on("websocket", (socket) => { if (!socket.url().includes("/human-terminals/")) return; @@ -106,6 +122,7 @@ for (const lane of ["native", "runner", "managed"] as const) { if (typeof payload !== "string") return; const message = JSON.parse(payload); if (message.type === "resize") resize = message; + if (message.type === "input") submitted += message.data; }); }); @@ -137,10 +154,7 @@ for (const lane of ["native", "runner", "managed"] as const) { const action = session.getByTestId("ide-launch-button"); await action.scrollIntoViewIfNeeded(); await expect(action).toBeInViewport({ ratio: 0.8 }); - await expect(action).toHaveAttribute( - "href", - /^vscode:\/\/file\/(private\/)?tmp$/ - ); + await expect(action).toHaveAttribute("href", `vscode://file${target}`); } await screenshot("ide"); if (remote) @@ -156,21 +170,33 @@ for (const lane of ["native", "runner", "managed"] as const) { ); expect(open).toBeTruthy(); await expect.poll(() => resize).toBeTruthy(); - const input = session.getByLabel("Host terminal").locator("textarea"); const type = async (command: string) => { - await input.pressSequentially(command); - await input.press("Enter"); + const from = submitted.length; + if (remote) { + await session + .getByRole("button", { name: "Open text input" }) + .click(); + await session + .getByRole("textbox", { name: "Terminal input text" }) + .fill(command); + await session + .getByRole("button", { name: "Submit", exact: true }) + .click(); + } else { + const input = session.getByLabel("Host terminal").locator("textarea"); + await input.pressSequentially(command); + await input.press("Enter"); + } + await expect.poll(() => submitted.slice(from)).toContain(command); }; await type( remote ? `cat marker.txt; stty size; printf 'PTY_PID_%s\\n' $$; printf 'PTY_UID_%s\\n' "$(id -u)"` - : "stty size; printf 'PTY_PID_%s\\n' $$" + : "cat marker.txt; stty size; printf 'PTY_PID_%s\\n' $$" ); - if (remote) { - await expect(panel.getByText(target, { exact: true })).toBeVisible(); - await expect.poll(() => output).toContain(expectedMarker); - await expect.poll(() => output).toContain("PTY_UID_1500"); - } + await expect(panel.getByText(target, { exact: true })).toBeVisible(); + await expect.poll(() => output).toContain(expectedMarker); + if (remote) await expect.poll(() => output).toContain("PTY_UID_1500"); const initialSize = resize!; await expect .poll(() => output) @@ -203,6 +229,8 @@ for (const lane of ["native", "runner", "managed"] as const) { await screenshot("ended"); } finally { await context.close(); + if (nativeFixture) + await rm(nativeFixture, { recursive: true, force: true }); await request.post(ideSettings, { headers, data: previousIdes }); } }); From 02791516fa711a0895e9e79b814aeab636a47824 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 18:42:33 -0700 Subject: [PATCH 151/642] Specify the runner preview reachability boundary --- docs/design/runner-capability-inventory.md | 2 +- docs/design/runner-preview-access.md | 75 ++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 docs/design/runner-preview-access.md diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 0ce56cd8e..88f6b7643 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -115,7 +115,7 @@ shares its reset coordinator across HTTP and MCP. - Keep native Mac behavior. A remote terminal, if offered, opens in the correct guest with the correct identity. Never interpret a remote path as a request to open a Mac file. [Human terminal manager](../../apps/server/src/terminal/manager.ts) · [Clipboard behavior](../../apps/server/src/routes/files.ts) · [Mac integration](../macos-app.md) -**Serve previews.** **Deferred.** An agent can publish a preview link. Reaching a server bound inside a remote execution environment is a separate capability. Dispatch owns the browser-facing URL and access policy. +**Serve previews.** **Deferred.** An agent can publish a preview link. Reaching a server bound inside a remote execution environment is a separate capability. Dispatch owns the browser-facing URL and access policy. See the [preview reachability boundary and proposed negotiation](runner-preview-access.md). - When implemented, two runners can independently serve the same guest port. Access and live reload end for the revoked runner. [Preview acceptance in handoff](remote-runner-handoff.md) diff --git a/docs/design/runner-preview-access.md b/docs/design/runner-preview-access.md new file mode 100644 index 000000000..2ad48b946 --- /dev/null +++ b/docs/design/runner-preview-access.md @@ -0,0 +1,75 @@ +# Runner preview access + +A published preview is an authored URL. Dispatch stores the attachment and +returns the latest explicit preview through the agent preview route. The +browser connects directly to that URL. This works for both built-in and enrolled +sessions without a runner capability. Reachability depends on the browser's +network, DNS and credentials. In particular, loopback in a published link +means the browser's machine. Dispatch never interprets a published URL as a +request to dial the runner. + +A service reachable only from a runner needs a separate connection. Support is +deferred. The connection is optional and will be limited to TCP loopback inside +a network namespace dedicated to the active execution session. Other sessions, +runner control services, arbitrary addresses, LAN services and Unix sockets +are outside that reachability boundary. The existing enrolled launcher switches +workload UID and GID but retains a shared network namespace. An authenticated +session handle and a port number establish neither listener ownership nor +network isolation. Workload credential switching alone cannot enforce this +boundary. Built-in native sessions retain their existing published-link path +and should advertise the new capability only if they meet the same boundary. + +## Proposed runner contract + +Advertise `previewPorts: true` in the authenticated ready frame only when the +runner can enforce session-local loopback access. Treat an absent flag as +unsupported. A host checks the flag on the current connection before sending +any preview operation. This is additive to the existing negotiation. Existing +hosts ignore the extra ready field and continue using supported operations. + +The operations below describe semantics for a future wire revision. Machine +identity comes from the authenticated connection. Session, endpoint and grant +handles are opaque to the host. The protocol needs no project, browser, +attachment, membership or review fields. + +| Operation | Contract | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Register endpoint | Bind an explicitly requested integer port from 1 through 65535 to a live session and return a session-local opaque endpoint handle. The dial destination is fixed loopback in that session's namespace. | +| Grant access | Bind a revocable opaque grant to the connection, active session and endpoint. Grants have a finite lifetime and are invalid on reconnect. | +| Open connection | Validate the grant and open one bidirectional byte stream. Validate the bindings before dialing and again before exposing the stream if the dial completed asynchronously. | +| Revoke access | Invalidate the grant and destroy every active stream for it. Repeating revocation succeeds. | + +Closing a session, losing the authenticated connection or revoking runner +enrollment invalidates its grants and closes affected streams, including +upgraded connections. A new connection requires fresh authorization. Limit +concurrent streams and pending dials per grant and per runner. Disconnects and +revocation must cancel pending opens and release sockets. + +## Dispatch browser boundary + +Dispatch authorizes a viewer against the session before granting access and +owns the browser-facing link, expiry and revocation. Serve untrusted preview +content on a browser origin isolated from Dispatch and from other previews, +with no Dispatch cookies or credentials forwarded upstream. Keep authorization +on HTTP requests and WebSocket upgrades. Preserve same-preview asset paths and +upgrade traffic for live reload. A redirect cannot grant the relay access to +another upstream destination. Closing the preview grant terminates existing +HTTP streams and upgraded sockets as well as denying new requests. + +## Enablement evidence + +Use the existing owner-review fixture as the baseline for normal built-in and +enrolled placement coverage. The published-link route is placement-independent. +The optional terminal path shows the existing connection and channel pattern +through the built-in backend or the enrolled runner service. + +Before advertising the capability, run an independent protocol consumer and +the scoped Hangar proof. Verify old peers with ordinary published links. Enroll +two runners with distinct session-local content on the same port and open both +browser links simultaneously. Change one page and observe a live reload. +Revoke its access and verify that its active upgrade closes, a new request is +denied and the other preview continues serving. Close the remaining session +and verify its active and future connections are denied. Also verify that a +session cannot reach a port belonging to another session or the runner control +plane. Capture the browser states and the lifecycle evidence in the task +conversation. From fba81876d0ef969ef8f8f3d584391f574d30e107 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 18:43:50 -0700 Subject: [PATCH 152/642] Record prerequisites for isolated preview workloads --- docs/design/runner-preview-access.md | 29 ++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/docs/design/runner-preview-access.md b/docs/design/runner-preview-access.md index 2ad48b946..0ca8ef045 100644 --- a/docs/design/runner-preview-access.md +++ b/docs/design/runner-preview-access.md @@ -19,6 +19,23 @@ network isolation. Workload credential switching alone cannot enforce this boundary. Built-in native sessions retain their existing published-link path and should advertise the new capability only if they meet the same boundary. +Current enrollment authenticates a runner and permits it to launch multiple +sessions. Configuring a workspace restricts checkout selection. It does not +reserve the runner for one session or isolate its workload from the runner +control process. The existing Docker acceptance harness isolates runner +containers from one another and still allows multiple sessions inside each +container. A deployable placement needs a provisioner that binds each session +to its own workload network namespace, provides the runner a scoped dial path +into that namespace and releases that path on session close. A deployment can +supply that boundary externally if the runner can verify the binding and +enforce exclusive session assignment. No current enrollment mode does so. + +A local Docker check ran two disposable containers with networking disabled +apart from loopback. They served different bodies on port 4173, and the +second remained reachable from inside its namespace after stopping the first. +This checks the isolation primitive. The enrolled relay, browser origin, +live reload and access revocation remain unverified. + ## Proposed runner contract Advertise `previewPorts: true` in the authenticated ready frame only when the @@ -32,12 +49,12 @@ identity comes from the authenticated connection. Session, endpoint and grant handles are opaque to the host. The protocol needs no project, browser, attachment, membership or review fields. -| Operation | Contract | -| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Register endpoint | Bind an explicitly requested integer port from 1 through 65535 to a live session and return a session-local opaque endpoint handle. The dial destination is fixed loopback in that session's namespace. | -| Grant access | Bind a revocable opaque grant to the connection, active session and endpoint. Grants have a finite lifetime and are invalid on reconnect. | -| Open connection | Validate the grant and open one bidirectional byte stream. Validate the bindings before dialing and again before exposing the stream if the dial completed asynchronously. | -| Revoke access | Invalidate the grant and destroy every active stream for it. Repeating revocation succeeds. | +| Operation | Contract | +| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Register endpoint | Explicitly publish an integer port from 1 through 65535. The runner must approve it for the live session’s verified workload before returning a session-local opaque endpoint handle. The dial destination is fixed loopback in that session's namespace. | +| Grant access | Bind a revocable opaque grant to the connection, active session and endpoint. Grants have a finite lifetime and are invalid on reconnect. | +| Open connection | Validate the grant and open one bidirectional byte stream. Validate the bindings before dialing and again before exposing the stream if the dial completed asynchronously. | +| Revoke access | Invalidate the grant and destroy every active stream for it. Repeating revocation succeeds. | Closing a session, losing the authenticated connection or revoking runner enrollment invalidates its grants and closes affected streams, including From b46514d855ee1a8e747f5ec60f15b4b8c1846677 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 18:45:18 -0700 Subject: [PATCH 153/642] Assign runner preview design to the runtime owner --- .agents/owners.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.agents/owners.json b/.agents/owners.json index 56e354ed7..8fd71c6da 100644 --- a/.agents/owners.json +++ b/.agents/owners.json @@ -41,6 +41,7 @@ "docs/04-agent-lifecycle.md", "docs/design/remote-runner-handoff.md", "docs/design/runner-capability-inventory.md", + "docs/design/runner-preview-access.md", "docs/design/runner-parity-rollout.md", "scripts/e2e-remote-runners.sh", "scripts/remote-runner/codex-offline-preflight.sh", From d972e4e5b926fa118edab751c56c35e860dbb9f9 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 19:30:19 -0700 Subject: [PATCH 154/642] Report native host inventory during runner recovery --- apps/server/src/agents/acp/runtime.ts | 36 ++++++++++ apps/server/src/agents/local-runner.ts | 93 +++++++++++++++++++------- apps/server/src/agents/manager.ts | 14 +++- apps/server/src/agents/runtime.ts | 14 ++++ apps/server/test/acp-host.test.ts | 71 +++++++++++++++++--- docs/design/runner-parity-rollout.md | 31 +++++++++ 6 files changed, 225 insertions(+), 34 deletions(-) diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 49686c5e1..2e8674445 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -1342,6 +1342,42 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { entry?.client.close(); }, + async inspectNativeHost(agentId) { + const process = await local.inspectHost(agentId); + const entry = live.get(agentId); + const welcome = + process.processState === "live" && + entry && + !entry.remote && + entry.client.isConnected() + ? entry.client.welcome + : null; + return { + ...process, + activity: welcome?.running + ? runtime.isBusy(agentId) + ? "busy" + : "idle" + : "unknown", + attached: welcome !== null, + capabilities: welcome + ? { + steering: welcome.steeringSupported === true, + interrupt: welcome.interruptSupported === true, + mcpInventory: welcome.mcpInventorySupported === true, + backgroundWork: welcome.backgroundWorkSupported === true, + } + : null, + cursor: + welcome && entry + ? { + seq: entry.lastSeq, + journalId: entry.journalId, + } + : null, + }; + }, + async listHosted() { return (await local.listHosted()).filter((id) => id.startsWith("agt_")); }, diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index 7072ddf82..b269e6123 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -1,4 +1,4 @@ -import { spawn } from "node:child_process"; +import { execFile, spawn } from "node:child_process"; import { closeSync, openSync } from "node:fs"; import { mkdir, @@ -14,6 +14,7 @@ import net from "node:net"; import { hostname, userInfo } from "node:os"; import path from "node:path"; import type { Duplex } from "node:stream"; +import { promisify } from "node:util"; import type { FastifyBaseLogger } from "fastify"; import { CHECKOUT_COMMAND_TIMEOUT_MS, @@ -80,13 +81,46 @@ const KILL_GRACE_MS = 2_000; const LOG_TAIL_LINES = 20; const CONNECT_TIMEOUT_MS = 5_000; -async function readPid(stateDir: string): Promise { +export type NativeHostProcess = { + sessionHandle: string; + processState: "live" | "gone" | "stale"; +}; + +const processArgs = promisify(execFile); + +async function readHostPid(dir: string): Promise { + const record = await readFile(hostFile(dir, "pid"), "utf8").catch( + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return null; + throw error; + } + ); + return record === null ? null : Number(record.trim()); +} + +async function inspectHostProcess(dir: string): Promise<{ + processState: NativeHostProcess["processState"]; + pid: number | null; +}> { + const pid = await readHostPid(dir); + if (pid === null) return { processState: "gone", pid: null }; + if (!Number.isSafeInteger(pid) || pid <= 0) + return { processState: "stale", pid: null }; + if (!pidAlive(pid)) return { processState: "gone", pid: null }; + if (await hostPidMatches(pid, dir)) return { processState: "live", pid }; + return { processState: "stale", pid: null }; +} + +async function hostPidMatches(pid: number, dir: string): Promise { try { - const text = await readFile(hostFile(stateDir, "pid"), "utf8"); - const pid = Number(text.trim()); - return Number.isInteger(pid) && pid > 0 ? pid : null; + const { stdout } = await processArgs( + "/bin/ps", + ["-p", String(pid), "-o", "args="], + { timeout: 2_000 } + ); + return stdout.trimEnd().endsWith(` agent-host --state ${dir}`); } catch { - return null; + return false; } } @@ -299,19 +333,19 @@ export function createLocalRunner( } async function stop(agentId: string, force: boolean) { const dir = stateDir(agentId); - const pid = await readPid(dir); - if (pid && pidAlive(pid)) { + const { pid } = await inspectHostProcess(dir); + if (pid) { const deadline = Date.now() + (force ? 0 : STOP_GRACE_MS); while (Date.now() < deadline && pidAlive(pid)) { await new Promise((resolve) => setTimeout(resolve, 200)); } - if (pidAlive(pid)) { + if (await hostPidMatches(pid, dir)) { signalGroup(pid, "SIGTERM"); const killAt = Date.now() + KILL_GRACE_MS; while (Date.now() < killAt && pidAlive(pid)) { await new Promise((resolve) => setTimeout(resolve, 200)); } - if (pidAlive(pid)) signalGroup(pid, "SIGKILL"); + if (await hostPidMatches(pid, dir)) signalGroup(pid, "SIGKILL"); } } const marker = await readFile(path.join(dir, "ownership"), "utf8").catch( @@ -417,8 +451,14 @@ export function createLocalRunner( return { channel }; } case "alive": { - const pid = await readPid(dir); - return { value: pid !== null && pidAlive(pid) }; + const pid = await readHostPid(dir); + return { + value: + pid !== null && + Number.isSafeInteger(pid) && + pid > 0 && + pidAlive(pid), + }; } case "stop": await stop(agentId, operation.force); @@ -456,24 +496,31 @@ export function createLocalRunner( agentId: string, progress: Parameters[1] ) => workspace.resume(stateDir(agentId), progress), + async inspectHost(sessionHandle: string): Promise { + const { processState } = await inspectHostProcess( + stateDir(sessionHandle) + ); + return { sessionHandle, processState }; + }, + async listHosted() { - let ids: string[] = []; - try { - ids = await readdir(agentStateRoot); - } catch { - return []; - } + const entries = await readdir(agentStateRoot, { + withFileTypes: true, + }).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return []; + throw error; + }); const hosted: string[] = []; - for (const id of ids) { - const pid = await readPid(stateDir(id)); - if (pid && pidAlive(pid)) hosted.push(id); + for (const entry of entries) { + if (!entry.isDirectory()) continue; + const { processState } = await inspectHostProcess(stateDir(entry.name)); + if (processState === "live") hosted.push(entry.name); } return hosted; }, async hostPid(agentId: string) { - const pid = await readPid(stateDir(agentId)); - return pid && pidAlive(pid) ? pid : null; + return (await inspectHostProcess(stateDir(agentId))).pid; }, }; } diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 79cd0ae9b..b70ddae11 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1137,7 +1137,19 @@ export class AgentManager { row.id, remotePlacement(row.cwd) ? row.cwd : (row.workspacePath ?? row.cwd) ); - if (await this.runtime.attach(row.id)) { + const attachedToHost = await this.runtime.attach(row.id); + if (!remotePlacement(row.cwd) && this.runtime.inspectNativeHost) { + try { + const host = await this.runtime.inspectNativeHost(row.id); + this.logger.info({ host }, "Observed native host during recovery"); + } catch (err) { + this.logger.warn( + { err, agentId: row.id }, + "Native host inspection failed" + ); + } + } + if (attachedToHost) { attached.push(row.id); continue; } diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index ad5079efa..c283037da 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -125,6 +125,20 @@ export type AgentRuntime = { cancel(agentId: string): Promise; /** Shut the host down; `force` skips the graceful ACP close. */ stop(agentId: string, force: boolean): Promise; + /** Local recovery diagnostics. Capabilities are known only after hello. */ + inspectNativeHost?(sessionHandle: string): Promise<{ + sessionHandle: string; + processState: "live" | "gone" | "stale"; + activity: "busy" | "idle" | "unknown"; + attached: boolean; + capabilities: { + steering: boolean; + interrupt: boolean; + mcpInventory: boolean; + backgroundWork: boolean; + } | null; + cursor: { seq: number; journalId: string | null } | null; + }>; /** Agents with a live host, for the reconciler. */ listHosted(): Promise; /** The host's pid when it is alive; the root of the agent's process tree. */ diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index cd703d357..1db01e2f8 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -600,8 +600,10 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); it("reattaches to an active native host after its controller exits", async () => { const id = "agt_native_handoff"; + const parentId = "agt_native_parent"; const folder = mkdtempSync(path.join(cwd, "session-")); const input = launchFor(id, folder); + input.fullAccess = false; input.bins.adapter = { bin: "bun", args: [path.join(here, "helpers/remote-acp-fixture.ts")], @@ -619,16 +621,23 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); hostSeq:async()=>({seq:0,journalId:null}), syncJournal:async()=>{} }); const input = ${JSON.stringify(input)}; + await runtime.launch({...input, agentId: ${JSON.stringify(parentId)}}); const {sessionId}=await runtime.launch(input); const pid=await runtime.hostPid(input.agentId); - runtime.onEvent((_, event, seq)=>{ - if(event.type==="update" && event.update.content?.text==="Guest turn waiting for reconnect.") { - console.log(JSON.stringify({sessionId,pid,seq})); + let cursor = 0; + runtime.onEvent((id, _, seq) => { + if (id === input.agentId) cursor = Math.max(cursor, seq); + }); + const turn = runtime.prompt(input.agentId, "proof-count prove-permission"); + await turn.accepted; + for (;;) { + const [permission] = runtime.getPermissions(input.agentId).requests; + if (permission && cursor > 0) { + console.log(JSON.stringify({sessionId, pid, seq: cursor, permissionId: permission.id})); process.exit(0); } - }); - await runtime.prompt(input.agentId,"proof-delay:2500 proof-count").settled; - throw new Error("Controller never received the in-flight checkpoint"); + await new Promise(resolve => setTimeout(resolve, 10)); + } ` ); const result = execFileSync("bun", [controller], { @@ -646,9 +655,28 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); () => checkpoint.seq, journalId ); + const parent = runtimeWith(stateRoot, () => 0); try { + expect(await runtime.listHosted()).toContain(id); + expect(await runtime.inspectNativeHost!(id)).toMatchObject({ + sessionHandle: id, + processState: "live", + attached: false, + activity: "unknown", + capabilities: null, + }); expect(await runtime.attach(id)).toBe(true); + expect(await runtime.inspectNativeHost!(id)).toMatchObject({ + processState: "live", + attached: true, + activity: "busy", + cursor: { journalId }, + }); expect(await runtime.hostPid(id)).toBe(checkpoint.pid); + expect(runtime.getPermissions(id).requests[0]?.id).toBe( + checkpoint.permissionId + ); + await runtime.answerPermission(id, checkpoint.permissionId, "allow"); await until(() => seen.some( ({ event }) => event.type === "turn" && event.state === "settled" @@ -659,15 +687,25 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); ({ event }) => event.type === "turn" && event.state === "settled" ) ).toHaveLength(1); - expect(seen[0]?.seq).toBe(checkpoint.seq + 1); + expect(seen.find(({ seq }) => seq > 0)?.seq).toBe(checkpoint.seq + 1); expect( readFileSync(path.join(folder, "provider-invocations"), "utf8") ).toBe("called\n"); + expect(await runtime.inspectNativeHost!(id)).toMatchObject({ + processState: "live", + activity: "idle", + capabilities: { steering: expect.any(Boolean) }, + }); writeFileSync(path.join(folder, "review-marker.txt"), "native-handoff"); - await runtime.prompt(id, "proof-reviewed-checkout").settled; + expect(readFileSync(path.join(folder, "protected-action"), "utf8")).toBe( + "allowed\n" + ); + expect(await parent.runtime.attach(parentId)).toBe(true); + await parent.runtime.prompt(parentId, "proof-reviewed-checkout").settled; await until(() => - seen.some( - ({ event }) => + parent.seen.some( + ({ agentId, event }) => + agentId === parentId && event.type === "update" && event.update.sessionUpdate === "agent_message_chunk" && event.update.content.type === "text" && @@ -675,9 +713,22 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); ) ); } finally { + await parent.runtime.stop(parentId, true); + await parent.runtime.discard(parentId); await runtime.stop(id, true); await runtime.discard(id); } + expect(await runtime.inspectNativeHost!(id)).toMatchObject({ + processState: "gone", + attached: false, + }); + mkdirSync(path.join(stateRoot, id)); + writeFileSync(path.join(stateRoot, id, "host.pid"), String(process.pid)); + expect(await runtime.inspectNativeHost!(id)).toMatchObject({ + processState: "stale", + attached: false, + }); + expect(await runtime.listHosted()).not.toContain(id); expect(readFileSync(path.join(folder, "review-marker.txt"), "utf8")).toBe( "native-handoff" ); diff --git a/docs/design/runner-parity-rollout.md b/docs/design/runner-parity-rollout.md index 7b6bce8ae..426292396 100644 --- a/docs/design/runner-parity-rollout.md +++ b/docs/design/runner-parity-rollout.md @@ -81,3 +81,34 @@ ID for retries. The runner checks that state again under its checkout lock and defers removal while another session holds a borrower binding. Older runners keep their legacy protocol, and managed cleanup requested by a newer Dispatch waits for a runner that advertises conditional release. + +### Native recovery evidence + +The built-in runner discovers native processes using the session state +directory and the host command line. Its inventory reports process state, +attachment, observed activity, the capabilities from the existing hello +exchange, and the last observed journal cursor. A live detached host has +unknown activity. An invalid or recycled PID record is stale, and a missing +record or dead process is gone. The Dispatch adapter records these observations +during startup reconciliation. Enrolled runners still use their existing +placement-based session requests and per-connection capability negotiation. + +A compatible controller restart can reattach to a surviving host with the same +journal and an accepted turn. The native process fixture exits its controller +with a permission request pending, reattaches at a saved sequence, answers the +same request and observes one completion and one provider invocation. Two +native sessions in the fixture use the same checkout. This exercises checkout +retention at the host layer. Dispatch parent/child row restoration and mixed +published binaries require separate service-level evidence. + +The installer fixture runs the enrolled runner install/update script with +simulated systemd, including successful start, busy deferral and restoring the +old runtime after a candidate fails to start. The protected server update +coordinator tests exercise the backup, probation and rollback boundaries with +injected dependencies. If probation fails before commit, recovery restores the +previous release and its recovery point. If restore or previous-version +readiness fails, admission stays fenced. Once committed, a later normal startup +failure keeps the committed state. No update admission changes are proposed +here. The controller handoff proof does not establish that an installer can +admit an update with an active host or carry that turn through a database +migration. From 823994e2113adc6951e5fd10edf263f806c12dc6 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 19:38:20 -0700 Subject: [PATCH 155/642] Require native host identity for recovery liveness --- apps/server/src/agents/local-runner.ts | 10 ++----- apps/server/test/acp-runtime-queue.test.ts | 26 ++++++++++++++---- apps/server/test/db/agent-manager.test.ts | 32 ++++++++++++++++++++++ 3 files changed, 55 insertions(+), 13 deletions(-) diff --git a/apps/server/src/agents/local-runner.ts b/apps/server/src/agents/local-runner.ts index b269e6123..711e25fd6 100644 --- a/apps/server/src/agents/local-runner.ts +++ b/apps/server/src/agents/local-runner.ts @@ -451,14 +451,8 @@ export function createLocalRunner( return { channel }; } case "alive": { - const pid = await readHostPid(dir); - return { - value: - pid !== null && - Number.isSafeInteger(pid) && - pid > 0 && - pidAlive(pid), - }; + const { processState } = await inspectHostProcess(dir); + return { value: processState === "live" }; } case "stop": await stop(agentId, operation.force); diff --git a/apps/server/test/acp-runtime-queue.test.ts b/apps/server/test/acp-runtime-queue.test.ts index 153d967c8..12a5f6fa2 100644 --- a/apps/server/test/acp-runtime-queue.test.ts +++ b/apps/server/test/acp-runtime-queue.test.ts @@ -2,6 +2,7 @@ * The runtime's prompt queue against a scripted host on a real socket, * where the test decides how the host's messages are framed on the wire. */ +import { spawn } from "node:child_process"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { createLocalRunner } from "../src/agents/local-runner.js"; import net from "node:net"; @@ -45,6 +46,21 @@ afterEach(() => { for (const run of cleanup.splice(0)) run(); }); +// The scripted socket lives in the test worker. Give it a separate process +// identity so native liveness follows the same path as it does for a real host. +function recordFixtureHostPid(dir: string) { + const host = spawn( + process.execPath, + ["-e", "setTimeout(() => {}, 120000)", "--", "agent-host", "--state", dir], + { detached: true, stdio: "ignore" } + ); + if (!host.pid) throw new Error("Could not spawn the fixture host process"); + cleanup.push(() => { + host.kill(); + }); + writeFileSync(hostFile(dir, "pid"), String(host.pid)); +} + /** * A host that answers every prompt with a turn that fails at once, its * ack and both turn events written to the socket in a single chunk. @@ -56,7 +72,7 @@ async function fastFailingHost(): Promise<{ const stateRoot = mkdtempSync(path.join(os.tmpdir(), "dispatch-queue-")); const dir = path.join(stateRoot, agentId); mkdirSync(dir, { recursive: true }); - writeFileSync(hostFile(dir, "pid"), String(process.pid)); + recordFixtureHostPid(dir); const prompts: string[] = []; let seq = 0; const event = (e: unknown): HostMessage => @@ -194,7 +210,7 @@ describe("AcpRuntime prompt queue", () => { const stateRoot = mkdtempSync(path.join(os.tmpdir(), "dispatch-queue-")); const dir = path.join(stateRoot, agentId); mkdirSync(dir, { recursive: true }); - writeFileSync(hostFile(dir, "pid"), String(process.pid)); + recordFixtureHostPid(dir); let seq = 0; const event = (e: unknown): HostMessage => ({ @@ -299,7 +315,7 @@ describe("AcpRuntime user post priority", () => { const stateRoot = mkdtempSync(path.join(os.tmpdir(), "dispatch-queue-")); const dir = path.join(stateRoot, agentId); mkdirSync(dir, { recursive: true }); - writeFileSync(hostFile(dir, "pid"), String(process.pid)); + recordFixtureHostPid(dir); let seq = 0; const event = (e: unknown): HostMessage => ({ @@ -414,7 +430,7 @@ describe("AcpRuntime legacy host replay", () => { const stateRoot = mkdtempSync(path.join(os.tmpdir(), "dispatch-legacy-")); const dir = path.join(stateRoot, agentId); mkdirSync(dir, { recursive: true }); - writeFileSync(hostFile(dir, "pid"), String(process.pid)); + recordFixtureHostPid(dir); const hellos: number[] = []; const entries: HostMessage[] = [ { @@ -525,7 +541,7 @@ async function heldTurnHost( const stateRoot = mkdtempSync(path.join(os.tmpdir(), "dispatch-queue-")); const dir = path.join(stateRoot, agentId); mkdirSync(dir, { recursive: true }); - writeFileSync(hostFile(dir, "pid"), String(process.pid)); + recordFixtureHostPid(dir); const prompts: Array<{ text: string; source?: PromptSource; diff --git a/apps/server/test/db/agent-manager.test.ts b/apps/server/test/db/agent-manager.test.ts index 38203a52e..6678d9003 100644 --- a/apps/server/test/db/agent-manager.test.ts +++ b/apps/server/test/db/agent-manager.test.ts @@ -3164,6 +3164,38 @@ describe("AgentManager", () => { expect(lost!.lastError).toContain("not running when Dispatch restarted"); }); + it("stops a running row when its native host PID belongs to another process", async () => { + const agent = await manager.createAgent({ + cwd: "/tmp", + useWorktree: false, + }); + const agentStateRoot = await mkdtemp( + path.join(os.tmpdir(), "dispatch-stale-host-") + ); + const dir = path.join(agentStateRoot, agent.id); + try { + await mkdir(dir); + await writeFile(path.join(dir, "host.pid"), String(process.pid)); + const recovering = new AgentManager(pool, noopLogger, { + ...testConfig, + agentStateRoot, + }); + await expect(recovering.restoreRunningAgents()).resolves.toEqual({ + attached: [], + lost: [agent.id], + resumes: [], + }); + expect(await recovering.getAgent(agent.id)).toMatchObject({ + status: "stopped", + lastError: expect.stringContaining( + "not running when Dispatch restarted" + ), + }); + } finally { + await rm(agentStateRoot, { recursive: true, force: true }); + } + }); + it("does not lose, or let boot cleanup kill, a host that is alive but missed its first attach — and recovers once a later attach succeeds", async () => { // Models the real failure this closes: a host busy replaying its // journal (or plain boot contention) doesn't answer `hello` inside From ed26e4d95012454d42d6b42964327f3cd4f14b79 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 19:50:53 -0700 Subject: [PATCH 156/642] Audit runner ownership and exercise task launch parity --- docs/design/runner-capability-inventory.md | 41 ++++++++++++++++++---- e2e/remote-runner/acceptance.spec.ts | 4 ++- e2e/remote-runner/owner-review.spec.ts | 38 ++++++++++++++++---- 3 files changed, 70 insertions(+), 13 deletions(-) diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index 88f6b7643..e864d9cff 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -2,7 +2,7 @@ **Starting point.** Implement owner review through a built-in local runner and a connected Linux runner. Both should accept the same operations on an opaque agent ID. Keep the native Mac execution path underneath the local implementation. The first release can support a different set of capabilities on each machine. Dispatch must be able to tell the user which operations their selected runner supports. -**Evidence baseline.** This inventory traces the feature branch at `598070c197cc`. GitHub’s main branch was at `8eebbe319863` during the audit. Ten main-branch commits were absent from the feature branch. The compatibility cases below include newer OpenCode launch, resume and verified update behavior, ACP adapter updates, and interruption across conversations. This is a source audit plus evidence from the two real runner sessions. Most rows have not been exercised on both placements. [Lifecycle model](../04-agent-lifecycle.md) · [ACP design](acp-runtime.md) · [Runner contract and compatibility](remote-runner-prototype.md) +**Evidence baseline.** The rollout audit starts at integration head `823994e2113adc6951e5fd10edf263f806c12dc6`. The register below distinguishes source coverage, isolated fixture runs and the earlier field observations. ## What exists on the wire @@ -56,7 +56,7 @@ A native host can complete an accepted turn while its controller is down. A repl - Compare an untracked file, rename, image and dirty worktree against the same base. Handle a missing base without probing another machine. [Agent diff](../../apps/server/src/shared/git/agent-diff.ts) · [Agent routes](../../apps/server/src/routes/agents/lifecycle-routes.ts) · [Stats refresher](../../apps/server/src/agents/diff-stats-refresher.ts) -**Discover repositories and interact with GitHub.** **Partial.** Runner Git can provision a checkout. Repository search, PR head lookup and tracked PR status/checks use the selected runner’s GitHub account. Dispatch schedules reads and publishes the results to the UI. Moving merge-risk evidence to the runner and having the runner push PR changes are the next steps in the [parity rollout](runner-parity-rollout.md). A project association alone grants no GitHub access. +**Discover repositories and interact with GitHub.** **Partial.** Runner Git can provision a checkout. Repository search, PR head lookup and tracked PR status/checks use the selected runner’s GitHub account. Dispatch schedules reads and publishes the results to the UI. Merge-risk inputs come from the same runner credential. Push and PR creation remain workload actions using the runner’s Git and GitHub credentials. A project association alone grants no GitHub access. - From a fresh runner account, sign in to GitHub, clone a private test repo, fetch a fork PR, and verify the identity used for push and PR creation. Sign out and verify isolation from other runners. Local-only review must also work with no published branch. [Search](../../apps/server/src/routes/runner-repositories.ts) · [PR reader](../../apps/server/src/agents/pull-request-reader.ts) · [Refresh](../../apps/server/src/agents/pull-request-refresher.ts) · [Risk inputs](../../apps/server/src/agents/merge-risk/github-source.ts) @@ -70,7 +70,7 @@ A native host can complete an accepted turn while its controller is down. A repl ### Repository automation and cleanup -**Discover repo tools, hooks and instructions.** **Partial.** Local sessions load checkout-specific persona files, tool manifests and lifecycle hooks. Local stop hooks skip remote placements today. The proof command on configured workspaces covers only a narrow case. Service policy controls what may run. The execution side resolves the manifest and runs the approved operation in the correct checkout. +**Discover repo tools, hooks and instructions.** **Partial.** Local sessions load checkout-specific persona files, tool manifests and lifecycle hooks. Repo tool manifests and stop hooks use checkout-scoped commands on both placements. Stop hooks resolve the launch and moved checkouts independently. Service policy controls what may run. The execution side resolves the manifest and runs the approved operation in the correct checkout. - A repo dev tool uses the runner’s working directory. Stop hooks run with their documented semantics for the launch and moved checkout. Missing tools are reported explicitly. [Repo tools](../../apps/server/src/shared/mcp/repo-tools.ts) · [Hooks](../../apps/server/src/agents/lifecycle-hooks.ts) · [Persona discovery](../../apps/server/src/personas/catalog.ts) @@ -115,9 +115,7 @@ shares its reset coordinator across HTTP and MCP. - Keep native Mac behavior. A remote terminal, if offered, opens in the correct guest with the correct identity. Never interpret a remote path as a request to open a Mac file. [Human terminal manager](../../apps/server/src/terminal/manager.ts) · [Clipboard behavior](../../apps/server/src/routes/files.ts) · [Mac integration](../macos-app.md) -**Serve previews.** **Deferred.** An agent can publish a preview link. Reaching a server bound inside a remote execution environment is a separate capability. Dispatch owns the browser-facing URL and access policy. See the [preview reachability boundary and proposed negotiation](runner-preview-access.md). - -- When implemented, two runners can independently serve the same guest port. Access and live reload end for the revoked runner. [Preview acceptance in handoff](remote-runner-handoff.md) +**Serve previews.** The native baseline uses a direct IP-and-port link from Dispatch and requires a viewer with a network route to the listening service. Generated URLs, Bonjour and Tailscale validation, and enrolled preview relay are deferred to the remote preview phase. Enrolled previews are unsupported when the viewer can reach only Dispatch. This checkpoint retains the direct LAN behavior and does not add a fresh second-device check. Acceptance in the deferred topology requires a session-bound service, isolated browser origin, HTTP and WebSocket forwarding over the authenticated runner connection, root asset and live reload checks, and access closure. [Preview design](runner-preview-access.md) **Report health and manage the runner.** **Present in part.** Remote registration, pairing, certificates, revocation, periodic health and engine inventory already exist. Keep wire-version negotiation, last-seen time, stale reports, session counts, CPU, memory, diagnostics, safe update and recovery visible. Built-in local execution needs a stable identity and capability set. The app installer can own its lifecycle. @@ -129,6 +127,37 @@ shares its reset coordinator across HTTP and MCP. - Launch the same project via Create Agent, a task, a template and a child. Verify placement and project association across restart. A project may contain a scratch session without a repository. [Jobs](../../apps/server/src/jobs/service.ts) · [Templates](../../apps/server/src/templates/service.ts) · [Repo-keyed brain storage](../../apps/server/src/brain/store.ts) · [Child options](../../apps/server/src/shared/mcp/agent-launch-tools.ts) +## Machine access at the rollout checkpoint + +| Entry point | Execution owner and host responsibility | Verification path | +| ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Create Agent and HTTP workspace selection | Built-in runner resolves native paths and branches. Enrolled runner resolves workspace handles and prepares scratch or repository directories with workload Git and dependency commands. Dispatch resolves project membership and admission. | Multi-runner launch, managed scratch selection and native recovery fixtures. | +| Task, template, scheduled job, MCP child and owner review | Dispatch chooses the launch policy and persists placement. Checkout inspection, persona/config reads and borrower binding run on the owning runner. A borrowed checkout includes unpublished files. An independent checkout uses the origin and a published base. | Owner-review spec exercises the ordinary child, nested persona, review, task-persona and override paths. Scheduled-job placement has service coverage. The same spec launches the author from a board task via its template and the task launch endpoint. Automatic column-trigger placement needs separate browser evidence. | +| HTTP Files and Changes, browser subscriptions and background diff refresh | Checkout reads and watches belong to the owning runner. Dispatch fans out events to browser tabs, refreshes stats and persists comments. Reconnect reconciles open views. | Owner-review spec opens Files and Changes, edits while disconnected and verifies the changed marker after reconnect. | +| PR status, checks, repository search and merge-risk worker | Git/gh and credentials belong to the runner. Dispatch selects tracked PRs and persists observations, review policy and notifications. Older peers fall back to polling if they support reads without watch. | GitHub account fixture covers private checkout, open card updates and account removal. The risk collector and compatibility paths are covered by focused tests. | +| MCP repository tools and lifecycle hooks | Dispatch authorizes the command. The owning runner reads the manifest and executes under the checkout identity. | Checkout-command browser spec and separate catalogs on identical enrolled paths. | +| Session runtime, terminal and account probes | Runner owns ACP, process identity, sockets, PTYs and workload homes. Dispatch owns prompt routing, permissions, durable cursors and presentation. Native accounts, provider usage and engines use the built-in runner. | Disconnect/replay and supervisor restart in the multi-runner spec. Browser terminal reconnect, workload capability workers and independent protocol fixtures. | +| Archive, startup recovery and retention | Runner owns checkout state checks, borrower references, process discovery and release. Dispatch owns cleanup decisions, pending retries, archive records, attachment retention and startup reconciliation. | Owner-review archive order, managed scratch archive, attachment retention and native controller handoff. | +| Attachments | Dispatch owns durable bytes and records. Session input staging and output collection use the receiving runner and session-bound paths. | File-transfer browser spec and independent consumer tests for interruption, retry and negotiation. | + +### Fresh verification at the checkpoint + +- The independent v1 consumer passed all 27 cases, including peers that omit optional capabilities, opaque session handles, and reattach after a lost launch acknowledgement. The combined consumer, native host and supervisor suite passed 76 cases with one opt-in case skipped. The supervisor suite covers owner-first archive, borrower retention and restoration across supervisor restart. +- A native task launched via its project template into an unpublished branch in a temporary directory. Playwright verified Files and Changes, the owner reviewer and nested launcher, and author access after reviewer archive. The ordinary child and both persona types read the same dirty marker. The multi-runner browser fixture also started a native session in the non-repository `/tmp` directory. +- Multi-runner Playwright verified same-named workspace isolation, browser permission routing during disconnect, supervisor restart, a mid-turn replay with one invocation and one completion, and revocation. Other sessions continued during the disconnect. +- The GitHub fixture passed private checkout, live updates in an open PR card, manual refresh at 390 px, and loss of access after signing out on the enrolled runner. It used fixture GitHub services and credentials. +- The artifact fixture passed on both placements with startup and composer inputs and a posted attachment that remained readable after archive. +- The enrolled task started in managed scratch. The fixture copied the unpublished checkout into that session before inspection and review. A serial run passed Files and Changes after reconnect, the nested reviewer, the ordinary child and both persona types, and continued author access after reviewer archive. The scratch container recorded zero OOM kills through that run. +- One earlier Linux attempt reached the task, Files and Changes after reconnect, and owner review. The nested reviewer timed out and the subsequent checkout override case found the runner unavailable. The scratch container recorded four OOM kills and its supervisor process disappeared during overlapping fixture runs on a 2 GiB Docker host. This accounts for the observed runner outage in this attempt. Earlier Linux timeouts need their own resource evidence before attributing them to the same cause. + +### Residual host access and deferred work + +- Task template persona validation still resolves the persona catalog using the template directory on the host. Job and template configuration can resolve an enrolled persona against the native project catalog. Checkout-local MCP persona discovery is runner-scoped. Enrolled-only personas selected before launch need a placement-aware catalog. [Task validation](../../apps/server/src/tasks/service.ts) · [Templates](../../apps/server/src/templates/service.ts) · [Jobs](../../apps/server/src/jobs/service.ts) +- Dispatch directly reads its native setup log when building a failed job diagnostic. Enrolled workspace preparation exposes progress but has no equivalent job diagnostic tail. The task/job launch can still use an enrolled placement. [Job diagnostics](../../apps/server/src/jobs/service.ts) +- Project icons resolve paths in the registered native project root. The per-agent repository icon also resolves a local path from session metadata and has no enrolled checkout read path. [Project icon](../../apps/server/src/routes/projects.ts) · [Agent icon](../../apps/server/src/routes/agents/crud-routes.ts) Native folder selection and host system information are host-scoped. Durable attachments, enrollment material, database state, release artifacts and installer recovery belong to Dispatch. +- Clipboard, Finder, IDE and operator browser actions target the operator desktop and follow the native permissions boundary. Session terminals target the owning runner. +- Enrolled usage watches and agent-initiated reset redemption remain unavailable. Live provider-account verification, published mixed-version upgrades with active sessions, and isolated enrolled previews remain separate acceptance work. + ## First implementation and release gate 1. **Characterize local owner review before moving it.** Use an unpublished feature branch, checkout-local owner rules and a persona, staged and unstaged changes, and an untracked file. Capture the selected base, paths, owners and effective reviewer cwd. Cover the case where the launcher differs from the display parent. [Existing owner tests](../../apps/server/test/mcp-persona-codeowners.test.ts) diff --git a/e2e/remote-runner/acceptance.spec.ts b/e2e/remote-runner/acceptance.spec.ts index 19a660df4..7f4b387ab 100644 --- a/e2e/remote-runner/acceptance.spec.ts +++ b/e2e/remote-runner/acceptance.spec.ts @@ -122,7 +122,9 @@ test("UI launches local, alpha and beta; each answer comes from its own side", a }); await expect(text(pages[r]!)).not.toContainText(marker(other)); expect(invocations(r)).toBe(1); - // The approved repo operation ran in this runner's workspace only. + await expect(answers(pages[r]!, "Approved repo operation:")).toBeVisible({ + timeout: 15_000, + }); expect(guestOk(r, `test -f ${state.runners[r].workspaceDir}/repo-op`)).toBe( true ); diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts index 5e7a0b9ea..3ee2df885 100644 --- a/e2e/remote-runner/owner-review.spec.ts +++ b/e2e/remote-runner/owner-review.spec.ts @@ -118,6 +118,9 @@ for (const placement of ["This Mac", "Linux runner"] as const) { const tmp = mkdtempSync(path.join(os.tmpdir(), "dispatch-review-")); const marker = randomUUID(); const agents: string[] = []; + const headers = authHeaders(); + let projectId: string | undefined; + let templateId: string | undefined; try { seed(tmp, marker); const remote = placement === "Linux runner"; @@ -128,16 +131,35 @@ for (const placement of ["This Mac", "Linux runner"] as const) { row?.id ?? (await enrollViaUi(page, request, "scratch")); cwd = `runner://${runnerId}/@session`; } - const created = await request.post("/api/v1/agents", { - headers: authHeaders(), + const project = await request.post("/api/v1/projects", { + headers, + data: { name: "Runner parity task", repoRoot: tmp, color: "#7c6ee6" }, + }); + expect(project.ok(), await project.text()).toBe(true); + projectId = (await project.json()).id; + const template = await request.post("/api/v1/templates", { + headers, data: { - name: "Field review author", - type: "claude", - cwd, + name: "Runner parity builder", + projectId, + agentType: "claude", + directory: cwd, useWorktree: false, - initialPrompt: "ready", + prompt: "ready", }, }); + expect(template.ok(), await template.text()).toBe(true); + templateId = (await template.json()).id; + const task = await request.post("/api/v1/tasks", { + headers, + data: { projectId, title: "Review an unpublished checkout" }, + }); + expect(task.ok(), await task.text()).toBe(true); + const { id: taskId } = await task.json(); + const created = await request.post(`/api/v1/tasks/${taskId}/launch`, { + headers, + data: { templateId }, + }); expect(created.ok(), await created.text()).toBe(true); const author = (await created.json()).agent.id as string; agents.push(author); @@ -407,6 +429,10 @@ for (const placement of ["This Mac", "Linux runner"] as const) { } } finally { for (const id of agents.reverse()) await deleteAgentViaAPI(request, id); + if (templateId) + await request.delete(`/api/v1/templates/${templateId}`, { headers }); + if (projectId) + await request.delete(`/api/v1/projects/${projectId}`, { headers }); rmSync(tmp, { recursive: true, force: true }); } }); From 1d19ae871fd1c0a5be34782587de734a220a55c4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 19:55:12 -0700 Subject: [PATCH 157/642] Launch project tasks in configured runner workspaces --- apps/server/src/agents/manager.ts | 9 +- .../server/test/helpers/remote-acp-fixture.ts | 8 ++ docs/design/runner-capability-inventory.md | 1 + e2e/remote-runner/owner-review.spec.ts | 98 +++++++++++++++++++ 4 files changed, 112 insertions(+), 4 deletions(-) diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index b70ddae11..7b5c56693 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1703,10 +1703,11 @@ export class AgentManager { if ( (!useWorktreeOf && !independentSource && input.parentAgentId) || (!managed && - (input.projectId || - input.templateId || - input.jobRunId || - input.useWorktree)) || + (input.jobRunId || + input.useWorktree || + // A project template selects an existing configured workspace. + // Project membership is validated below and remains host state. + Boolean(input.projectId) !== Boolean(input.templateId))) || (input.persona && !useWorktreeOf && !options.taskPersonaBody && diff --git a/apps/server/test/helpers/remote-acp-fixture.ts b/apps/server/test/helpers/remote-acp-fixture.ts index bdb37ab9c..e0b416107 100644 --- a/apps/server/test/helpers/remote-acp-fixture.ts +++ b/apps/server/test/helpers/remote-acp-fixture.ts @@ -1,5 +1,6 @@ import { proveFileTransfer } from "../../../../e2e/fixtures/runner-file-transfer.mjs"; // A standalone deterministic ACP provider for the isolated runner proof. +import { execFileSync } from "node:child_process"; import { appendFile, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; @@ -35,6 +36,13 @@ const fake = createFakeAcpAgent({ "called\n" ); } + if (prompt.includes("proof-launch-branch")) { + const branch = execFileSync("git", ["branch", "--show-current"], { + cwd: session.cwd, + encoding: "utf8", + }).trim(); + await report("Launch branch " + branch + "\n"); + } if (prompt.includes("proof-reviewed-checkout")) { const marker = ( await readFile(path.join(session.cwd, "review-marker.txt"), "utf8") diff --git a/docs/design/runner-capability-inventory.md b/docs/design/runner-capability-inventory.md index e864d9cff..49e12240d 100644 --- a/docs/design/runner-capability-inventory.md +++ b/docs/design/runner-capability-inventory.md @@ -147,6 +147,7 @@ shares its reset coordinator across HTTP and MCP. - Multi-runner Playwright verified same-named workspace isolation, browser permission routing during disconnect, supervisor restart, a mid-turn replay with one invocation and one completion, and revocation. Other sessions continued during the disconnect. - The GitHub fixture passed private checkout, live updates in an open PR card, manual refresh at 390 px, and loss of access after signing out on the enrolled runner. It used fixture GitHub services and credentials. - The artifact fixture passed on both placements with startup and composer inputs and a posted attachment that remained readable after archive. +- A separate configured Linux runner fixture seeds an unpublished branch and tracks a dirty marker before task launch. The host project contains neither. The author’s first turn reports the branch name from Git and reads the marker from its launch checkout. - The enrolled task started in managed scratch. The fixture copied the unpublished checkout into that session before inspection and review. A serial run passed Files and Changes after reconnect, the nested reviewer, the ordinary child and both persona types, and continued author access after reviewer archive. The scratch container recorded zero OOM kills through that run. - One earlier Linux attempt reached the task, Files and Changes after reconnect, and owner review. The nested reviewer timed out and the subsequent checkout override case found the runner unavailable. The scratch container recorded four OOM kills and its supervisor process disappeared during overlapping fixture runs on a 2 GiB Docker host. This accounts for the observed runner outage in this attempt. Earlier Linux timeouts need their own resource evidence before attributing them to the same cause. diff --git a/e2e/remote-runner/owner-review.spec.ts b/e2e/remote-runner/owner-review.spec.ts index 3ee2df885..bddb5e8f5 100644 --- a/e2e/remote-runner/owner-review.spec.ts +++ b/e2e/remote-runner/owner-review.spec.ts @@ -601,3 +601,101 @@ test("identical runner paths yield separate tool catalogs", async ({ for (const id of agents) await deleteAgentViaAPI(request, id); } }); + +test("task first turn sees the configured runner's existing unpublished branch", async ({ + page, + request, +}, testInfo) => { + const host = mkdtempSync(path.join(os.tmpdir(), "dispatch-task-host-")); + const headers = authHeaders(); + const marker = randomUUID(); + const branch = "guest-unpublished-" + marker; + const directory = state.runners.alpha.workspaceDir; + let projectId: string | undefined; + let templateId: string | undefined; + let authorId: string | undefined; + let seeded = false; + try { + execFileSync("git", ["init", "-b", "main", host]); + const runner = + (await runnerRow(request, "alpha"))?.id ?? + (await enrollViaUi(page, request, "alpha")); + guest( + "alpha", + `cd "${directory}" && test ! -e .git && test ! -e review-marker.txt` + ); + seeded = true; + execFileSync("docker", [ + "exec", + "-u", + "1500:1500", + state.runners.alpha.container, + "sh", + "-c", + `cd "${directory}" && + git init -b main && + git add marker.txt && + git -c user.name=Fixture -c user.email=fixture@localhost commit -m base && + git switch -c "${branch}" && + printf '%s' baseline > review-marker.txt && + git add review-marker.txt && + git -c user.name=Fixture -c user.email=fixture@localhost commit -m unpublished && + printf '%s' "${marker}" > review-marker.txt`, + ]); + const project = await request.post("/api/v1/projects", { + headers, + data: { + name: "Configured runner task", + repoRoot: host, + color: "#7c6ee6", + }, + }); + expect(project.ok(), await project.text()).toBe(true); + projectId = (await project.json()).id; + const template = await request.post("/api/v1/templates", { + headers, + data: { + name: "Configured runner builder", + projectId, + agentType: "claude", + directory: `runner://${runner}/${state.workspace}`, + useWorktree: false, + prompt: "proof-launch-branch proof-reviewed-checkout", + }, + }); + expect(template.ok(), await template.text()).toBe(true); + templateId = (await template.json()).id; + const task = await request.post("/api/v1/tasks", { + headers, + data: { projectId, title: "Open the unpublished guest branch" }, + }); + expect(task.ok(), await task.text()).toBe(true); + const { id: taskId } = await task.json(); + const launch = await request.post(`/api/v1/tasks/${taskId}/launch`, { + headers, + data: { templateId }, + }); + expect(launch.ok(), await launch.text()).toBe(true); + authorId = (await launch.json()).agent.id; + await page.goto(`/agents/${authorId}`, { waitUntil: "domcontentloaded" }); + await expect(settledTurns(page)).toHaveCount(1, { timeout: 45_000 }); + const firstTurn = settledTurns(page).first().getByTestId("harness-result"); + await expect(firstTurn).toContainText("Launch branch " + branch); + await expect(firstTurn).toContainText("Checkout marker " + marker); + const screenshot = testInfo.outputPath("configured-first-turn.png"); + await page.screenshot({ path: screenshot }); + await testInfo.attach("Configured runner first turn", { + path: screenshot, + contentType: "image/png", + }); + } finally { + if (authorId) await deleteAgentViaAPI(request, authorId, "keep"); + if (templateId) + await request.delete(`/api/v1/templates/${templateId}`, { headers }); + if (projectId) + await request.delete(`/api/v1/projects/${projectId}`, { headers }); + if (seeded) + guest("alpha", `cd "${directory}" && rm -rf .git review-marker.txt`); + rmSync(host, { recursive: true, force: true }); + } +}); From b1cbf9556b69fa7d52af4a27e07596a365caaa86 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 20:39:21 -0700 Subject: [PATCH 158/642] Guide paired runners through account and engine setup --- apps/server/src/agents/provider-plans.ts | 11 +- .../agents/remote/engine-runner-executor.ts | 115 ++++++++++++++++-- .../agents/remote/github-runner-executor.ts | 38 ++++-- apps/server/src/agents/remote/runner.ts | 29 ++++- apps/server/src/agents/remote/service.ts | 3 +- .../src/agents/remote/session-supervisor.ts | 6 +- .../test/engine-runner-executor.test.ts | 110 +++++++++++++++++ .../test/github-runner-executor.test.ts | 36 +++++- .../components/app/runner-github-account.tsx | 7 +- .../src/components/app/runner-onboarding.tsx | 5 +- .../src/components/app/runner-settings.tsx | 8 +- .../runner-engines/runner-engines.tsx | 22 +++- .../runner-engines/runner-provider-usage.tsx | 59 ++++++--- bin/install-dispatch-runner.sh | 15 +++ packages/runner-protocol/src/github.ts | 6 +- 15 files changed, 424 insertions(+), 46 deletions(-) diff --git a/apps/server/src/agents/provider-plans.ts b/apps/server/src/agents/provider-plans.ts index a169b7413..d7a3bb94e 100644 --- a/apps/server/src/agents/provider-plans.ts +++ b/apps/server/src/agents/provider-plans.ts @@ -648,7 +648,11 @@ async function loadCodexLivePlan( failure.reason === "login_expired" || failure.reason === "login_rejected" ? CODEX_RENEW_LOGIN - : CODEX_COULD_NOT_REFRESH, + : options.liveOnly + ? failure.reason === "no_usage_reported" + ? NO_CODEX_REPORT + : "Could not refresh Codex plan usage. Try again." + : CODEX_COULD_NOT_REFRESH, }; } } @@ -910,7 +914,10 @@ async function loadClaudePlan( ); return { ...claude, - unavailableReason: REFRESH_FAILURE_TEXT[failure.reason], + unavailableReason: + options.liveOnly && failure.reason === "no_usage_reported" + ? NO_CLAUDE_REPORT + : REFRESH_FAILURE_TEXT[failure.reason], }; } } diff --git a/apps/server/src/agents/remote/engine-runner-executor.ts b/apps/server/src/agents/remote/engine-runner-executor.ts index a3f88a4bd..3c74e5aaf 100644 --- a/apps/server/src/agents/remote/engine-runner-executor.ts +++ b/apps/server/src/agents/remote/engine-runner-executor.ts @@ -30,6 +30,12 @@ import { EngineLogins, isLoginEngine, loginScript } from "../engine-login.js"; * as the workload identity, never as this (root) process. */ +const MANAGED_PACKAGES: Record = { + claude: "@anthropic-ai/claude-code", + codex: "@openai/codex", + opencode: "opencode-ai", +}; + const LABELS: Record = { claude: "Claude Code", codex: "Codex", @@ -104,13 +110,14 @@ function sanitizeVersion(output: string): string | null { } export class EngineRunnerExecutor { + private nodeSetup?: Promise; private readonly logins: EngineLogins; private readonly wrap: NonNullable; constructor(private readonly config: EngineRunnerExecutorConfig) { this.wrap = config.wrap ?? setprivWrap(config.uid, config.gid); this.logins = new EngineLogins({ - resolveBin: async (engine) => config.engines[engine]?.bin ?? null, + resolveBin: async (engine) => (await this.resolveEngine(engine)).bin, // loginScript's own argv already starts with "/bin/sh"; wrap that // whole command behind the same privilege drop every runner exec uses. command: (bin, args, opts) => { @@ -210,16 +217,68 @@ export class EngineRunnerExecutor { return spawnError === undefined && code === 0; } + private canUseSharedBin(engine: RunnerEngine): boolean { + const cfg = this.config.engines[engine]; + const home = this.config.env.HOME; + return Boolean( + cfg?.install && + home && + cfg.bin === path.join(home, ".local", "bin", engine) + ); + } + + // Only installer defaults can fall back. An operator pin is authoritative. + private async resolveEngine(engine: RunnerEngine) { + const cfg = this.config.engines[engine]; + const bin = cfg?.bin ?? null; + const result = bin + ? await this.probe(bin) + : { installed: false, version: null }; + if (!result.installed && this.canUseSharedBin(engine)) { + for (const dir of new Set(this.config.env.PATH?.split(path.delimiter))) { + if (!path.isAbsolute(dir)) continue; + const shared = path.join(dir, engine); + if (shared === bin) continue; + const probed = await this.probe(shared); + if (probed.installed) return { bin: shared, ...probed }; + } + } + return { bin, ...result }; + } + + async resolveBin(engine: RunnerEngine): Promise { + if (!this.canUseSharedBin(engine)) + return this.config.engines[engine]?.bin ?? null; + return (await this.resolveEngine(engine)).bin; + } + + private ensureManagedNode(prefix: string): Promise { + return (this.nodeSetup ??= (async () => { + const node = await this.probe("node"); + if (Number(node.version?.split(".")[0]) >= 22) return true; + + // Ubuntu may provide a working npm backed by an older Node. Bootstrap + // Node into the same workload-owned prefix used for engine binaries. + const install = await this.run( + "npm", + ["install", "--global", "--prefix", prefix, "node@22"], + this.config.env, + 90_000 + ); + if (install.code !== 0) return false; + const installed = await this.probe("node"); + return Number(installed.version?.split(".")[0]) >= 22; + })().finally(() => { + this.nodeSetup = undefined; + })); + } + /** The scope-aware engine list and supported actions, for a snapshot view. */ async inventory(): Promise { return Promise.all( RUNNER_ENGINES.map(async (engine) => { const cfg = this.config.engines[engine]; - const bin = cfg?.bin ?? null; - const probed = bin - ? await this.probe(bin) - : { installed: false, version: null }; - const { installed, version } = probed; + const { bin, installed, version } = await this.resolveEngine(engine); let signedIn: boolean | null = null; let detail: string | undefined; if (installed && isLoginEngine(engine)) { @@ -231,9 +290,13 @@ export class EngineRunnerExecutor { let issue: string | undefined; if (!installed && cfg?.install) { if (await this.commandUsable(cfg.install)) actions.push("install"); - else issue = "install-unavailable"; + else + issue = + cfg.install.executable === "npm" + ? "node-npm-unavailable" + : "install-unavailable"; } - if (installed && cfg?.update) actions.push("update"); + if (installed && cfg?.update && bin === cfg.bin) actions.push("update"); if (installed && isLoginEngine(engine)) actions.push("login", "login_cancel"); return { @@ -319,6 +382,13 @@ export class EngineRunnerExecutor { error: `No managed ${kind} command is configured for ${LABELS[engine]} on this runner.`, }; } + const current = await this.resolveEngine(engine); + if (current.installed && current.bin !== cfg?.bin) { + return { + ok: false, + error: "This engine is maintained by the runner administrator.", + }; + } const operationId = randomUUID(); onEvent?.({ type: "operation_progress", @@ -327,7 +397,34 @@ export class EngineRunnerExecutor { phase: kind, message: kind === "install" ? "Installing…" : "Updating…", }); - const before = cfg?.bin ? (await this.probe(cfg.bin)).version : null; + const prefix = path.join(this.config.env.HOME ?? "", ".local"); + const defaultInstallArgs = [ + "install", + "--global", + "--prefix", + prefix, + `${MANAGED_PACKAGES[engine]}@latest`, + ]; + if ( + this.canUseSharedBin(engine) && + step.executable === "npm" && + !step.env && + step.args.length === defaultInstallArgs.length && + step.args.every((arg, index) => arg === defaultInstallArgs[index]) && + !(await this.ensureManagedNode(prefix)) + ) { + const message = + "Could not set up Node.js 22 for managed engine installs. Check npm and registry access on this runner."; + onEvent?.({ + type: "operation_complete", + operationId, + engine, + success: false, + message, + }); + return { ok: false, error: message }; + } + const before = current.version; const result = await this.run( step.executable, step.args, diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index bd6f81a99..580f0f7a9 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -7,6 +7,7 @@ import { execFile, spawn, type ChildProcess } from "node:child_process"; import { promisify } from "node:util"; import { githubDeviceUrl, + githubCliMissing, githubPullRequestHead, githubRepositoryResults, validGitHubLogin, @@ -81,14 +82,29 @@ export class GitHubRunnerExecutor { ["config", "get", "user", "--host", host], signal ); - if (!validGitHubLogin(login)) - throw new Error("Invalid configured GitHub user."); - return login; + if (validGitHubLogin(login)) return login; + if (login) throw new Error("Invalid configured GitHub user."); + // Older packaged gh can return success with an empty value. } catch (error) { - const { stderr } = error as { stderr?: string }; + const { code, stderr } = error as { code?: number; stderr?: string }; + if (code !== 1) throw error; if (stderr?.trim() === 'could not find key "user"') return undefined; + } + + try { + await this.run(["auth", "status", ...hostArgs], signal); + } catch (error) { + const { code, stderr } = error as { code?: number; stderr?: string }; + if ( + code === 1 && + /^You are not logged into any GitHub hosts\.(?: To log in, run: gh auth login| Run gh auth login to authenticate\.)?$/.test( + stderr?.trim() ?? "" + ) + ) + return undefined; throw error; } + throw new Error("GitHub CLI did not identify the configured user."); } private async account(signal: AbortSignal): Promise { @@ -336,9 +352,17 @@ export class GitHubRunnerExecutor { try { return await result; } catch (error) { - const { stderr } = error as { stderr?: string }; - if (stderr?.includes("No such file or directory")) - return { status: "unavailable" }; + const { code, stderr } = error as { + code?: string | number; + stderr?: string; + }; + if ( + code === "ENOENT" || + /failed to execute \/usr\/bin\/gh: No such file or directory/.test( + stderr ?? "" + ) + ) + return { status: "unavailable", message: githubCliMissing }; return { status: operation.type === "status" ? "unavailable" : "failed", }; diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index b747bb9c3..7258f136c 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -279,6 +279,29 @@ export async function runRemoteRunner(filename: string) { }, }, }); + async function resolveBins( + engine?: RunnerEngine + ): Promise { + switch (engine) { + case "claude": + return { + ...config.bins, + claudeBin: (await engineExecutor.resolveBin(engine)) ?? "", + }; + case "codex": + return { + ...config.bins, + codexBin: await engineExecutor.resolveBin(engine), + }; + case "opencode": + return { + ...config.bins, + opencodeBin: await engineExecutor.resolveBin(engine), + }; + default: + return config.bins; + } + } const engineAccountSecret = randomBytes(32).toString("base64url"); const capabilityRequests = new Set(); async function engineCapability( @@ -300,6 +323,9 @@ export async function runRemoteRunner(filename: string) { } capabilityRequests.add(key); try { + const bins = await resolveBins( + "engine" in operation ? operation.engine : undefined + ); const child = execute( setpriv, [...childArgs, ...selfCommand("runner-engine-capability")], @@ -315,7 +341,7 @@ export async function runRemoteRunner(filename: string) { child.child.stdin?.end( JSON.stringify({ operation, - bins: config.bins, + bins, secret: engineAccountSecret, }) ); @@ -350,6 +376,7 @@ export async function runRemoteRunner(filename: string) { }; const supervisor = await createSessionSupervisor({ ...config, + resolveBins, env, workspaces: new Set(configuredHandles), asWorkload, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 9fd40f12c..c47dc7eaa 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1373,7 +1373,8 @@ export class RemoteRunnerService { return { ...status, message: - "GitHub is unavailable. Check that GitHub CLI is installed on the runner and it can reach github.com.", + status.message ?? + "Could not verify the GitHub account. Check the runner’s connection to github.com and retry.", }; return status; } catch (error) { diff --git a/apps/server/src/agents/remote/session-supervisor.ts b/apps/server/src/agents/remote/session-supervisor.ts index eeea98d7d..cbbaa8b0e 100644 --- a/apps/server/src/agents/remote/session-supervisor.ts +++ b/apps/server/src/agents/remote/session-supervisor.ts @@ -33,6 +33,7 @@ import { type Command, type LaunchProgress, type RunnerRepository, + type RunnerEngine, } from "./protocol.js"; import { parseRepository, repositoryUrl } from "./repository.js"; import { @@ -71,6 +72,7 @@ type SupervisorOptions = { gid: number; ca: string; bins: HostLaunch["bins"]; + resolveBins?: (engine: RunnerEngine) => Promise; env: NodeJS.ProcessEnv; workspaces: ReadonlySet; hostCommand: () => string[]; @@ -710,7 +712,9 @@ export async function createSessionSupervisor( ...launchOptions, agentId, cwd, - bins: config.bins, + bins: config.resolveBins + ? await config.resolveBins(launchOptions.engine) + : config.bins, env: { DISPATCH_AGENT_ID: agentId, DISPATCH_FILES_DIR: files, diff --git a/apps/server/test/engine-runner-executor.test.ts b/apps/server/test/engine-runner-executor.test.ts index 21d2566f1..1f8080bca 100644 --- a/apps/server/test/engine-runner-executor.test.ts +++ b/apps/server/test/engine-runner-executor.test.ts @@ -57,6 +57,116 @@ if (args === "--version") { afterAll(() => rmSync(dir, { recursive: true, force: true })); afterEach(() => executor?.close()); + it("discovers an executable shared Claude only for the default managed path", async () => { + const managed = path.join(dir, ".local", "bin", "claude"); + const custom = path.join(dir, "custom-claude"); + const shared = "/usr/local/bin/claude"; + let accessible = true; + const install = { executable: "npm", args: [] }; + const config = { + uid: 1000, + gid: 1000, + env: { + ...process.env, + HOME: dir, + PATH: `/usr/local/bin:${process.env.PATH ?? ""}`, + }, + wrap: (bin: string, args: string[]) => { + if (accessible && bin === "/bin/sh") + return { + bin, + args: args.map((arg) => (arg === shared ? fake : arg)), + }; + return { + bin: bin === shared && accessible ? fake : "/nonexistent", + args, + }; + }, + }; + executor = new EngineRunnerExecutor({ + ...config, + engines: { claude: { bin: managed, install, update: install } }, + }); + expect(await executor.resolveBin("claude")).toBe(shared); + expect( + (await executor.inventory()).find((entry) => entry.id === "claude") + ).toMatchObject({ + installed: true, + signedIn: true, + actions: ["login", "login_cancel"], + }); + accessible = false; + expect(await executor.resolveBin("claude")).toBe(managed); + expect( + (await executor.inventory()).find((entry) => entry.id === "claude") + ).toMatchObject({ + installed: false, + issue: "node-npm-unavailable", + }); + accessible = true; + const pinned = new EngineRunnerExecutor({ + ...config, + engines: { claude: { bin: custom, install } }, + }); + expect(await pinned.resolveBin("claude")).toBe(custom); + expect( + (await pinned.inventory()).find((entry) => entry.id === "claude") + ?.installed + ).toBe(false); + }); + + it("bootstraps Node into the workload prefix before running a default npm install", async () => { + const prefix = path.join(dir, ".local"); + const managed = path.join(prefix, "bin", "claude"); + const args = [ + "install", + "--global", + "--prefix", + prefix, + "@anthropic-ai/claude-code@latest", + ]; + const npmPackages: string[] = []; + executor = new EngineRunnerExecutor({ + uid: 1000, + gid: 1000, + env: { ...process.env, HOME: dir }, + engines: { + claude: { bin: managed, install: { executable: "npm", args } }, + }, + wrap(bin, args) { + if (bin === "node") + return { + bin: "/bin/echo", + args: [npmPackages.length ? "v22.0.0" : "v18.0.0"], + }; + if (bin === "npm") { + expect(args.slice(0, 4)).toEqual([ + "install", + "--global", + "--prefix", + prefix, + ]); + npmPackages.push(args[4]!); + return { bin: "/bin/sh", args: ["-c", "exit 0"] }; + } + const installed = npmPackages.includes( + "@anthropic-ai/claude-code@latest" + ); + return { + bin: installed && bin === managed ? fake : "/nonexistent", + args, + }; + }, + }); + await expect( + executor.handle({ type: "install", engine: "claude" }) + ).resolves.toMatchObject({ ok: true }); + expect(npmPackages).toEqual([ + "node@22", + "@anthropic-ai/claude-code@latest", + ]); + }); + it("reports an installed engine's version and sign-in status", async () => { executor = new EngineRunnerExecutor({ uid: 1000, diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts index ee1fefcbb..3556e6750 100644 --- a/apps/server/test/github-runner-executor.test.ts +++ b/apps/server/test/github-runner-executor.test.ts @@ -30,11 +30,19 @@ fi case "$1 $2" in 'config get') test "$*" = 'config get user --host github.com' - if [ -f login ]; then cat login; else + if [ -f login ]; then cat login; elif [ -f legacy ]; then exit 0; else printf 'could not find key "user"\n' >&2 exit 1 fi ;; + 'auth status') + if [ -f network-down ]; then + printf 'dial tcp: network is unreachable\n' >&2 + else + printf 'You are not logged into any GitHub hosts. Run gh auth login to authenticate.\n' >&2 + fi + exit 1 + ;; 'auth login') test "$GH_PROMPT_DISABLED" = '1' test "$*" = 'auth login --hostname github.com --git-protocol https --web' @@ -124,6 +132,32 @@ esac } } +it("offers sign-in for an empty legacy gh account and preserves network failures", async () => { + await fixture(async ({ executor, root }) => { + const { signal } = new AbortController(); + await writeFile(path.join(root, "legacy"), ""); + expect(await executor.handle({ type: "status" }, signal)).toEqual({ + status: "signed-out", + }); + await writeFile(path.join(root, "network-down"), ""); + expect(await executor.handle({ type: "status" }, signal)).toEqual({ + status: "unavailable", + }); + }); +}); + +it("reports a missing CLI separately from a signed-out account", async () => { + await fixture(async ({ executor, gh }) => { + await rm(gh); + expect( + await executor.handle({ type: "status" }, new AbortController().signal) + ).toMatchObject({ + status: "unavailable", + message: "GitHub CLI is missing on this runner.", + }); + }); +}); + it("completes a device login and configures the same credential helper for an agent and managed checkout", async () => { await fixture(async ({ executor, root, env, gh }) => { const connection = new AbortController(); diff --git a/apps/web/src/components/app/runner-github-account.tsx b/apps/web/src/components/app/runner-github-account.tsx index 9ebeeba31..513f2af5a 100644 --- a/apps/web/src/components/app/runner-github-account.tsx +++ b/apps/web/src/components/app/runner-github-account.tsx @@ -46,7 +46,7 @@ function accountSummary(account: GitHubStatus) { case "signed-in": return `Signed in as @${account.login}`; case "signed-out": - return "Signed out"; + return "Signed out · optional for GitHub access"; case "pending": return account.code ? "Waiting for GitHub approval" @@ -54,7 +54,10 @@ function accountSummary(account: GitHubStatus) { case "failed": return "Sign-in did not complete. Try again."; case "unavailable": - return "Couldn’t reach GitHub from this runner. Check its connection and GitHub CLI installation."; + return ( + account.message ?? + "Couldn’t verify the GitHub account from this runner. Check its connection and retry." + ); } } diff --git a/apps/web/src/components/app/runner-onboarding.tsx b/apps/web/src/components/app/runner-onboarding.tsx index d3d168996..0ff4cb971 100644 --- a/apps/web/src/components/app/runner-onboarding.tsx +++ b/apps/web/src/components/app/runner-onboarding.tsx @@ -272,8 +272,9 @@ export function RunnerOnboarding() {

    1. Install on Linux

    - Requires Linux x86-64 or ARM64, systemd, Git, GitHub CLI, and - sudo. + Requires Linux x86-64 or ARM64, systemd, Git, sudo, and a GitHub + CLI with attestation support. Check with{" "} + gh attestation verify --help.

    {installer.isError ? (
    -
    +

    Agent engines

    + {runner.status === "online" && runner.engineCapabilities && ( +

    + Install and sign in to Claude or Codex here to see its plan limits + below. +

    + )} {runner.status !== "online" ? (

    Available when the runner is online. diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index 46692f3be..0e14e6659 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -17,6 +17,9 @@ import { } from "@/hooks/use-runner-engines"; import type { EngineScope } from "@dispatch/runner-protocol/engine-management"; +const ubuntuNodeSetup = + "sudo apt-get update && sudo apt-get install nodejs npm"; + /** * Engine install/update/sign-in for one scope: this machine, or a named * runner workspace. Self-contained — the caller only supplies `scope` @@ -74,6 +77,21 @@ export function RunnerEngines({ No engines reported.

    )} + {entries.some((entry) => entry.issue === "node-npm-unavailable") && ( +
    +

    + Managed engine installs need working Node.js and npm. Run this on + the Ubuntu runner. Install buttons appear once setup is detected. +

    +
    + {ubuntuNodeSetup} + +
    +
    + )} {entries.map((entry) => ( - Install isn't available on this runner — its install command couldn't - run (likely missing npm/node for this engine). + The configured install command could not run. Ask the runner + administrator to check it.

    )} diff --git a/apps/web/src/components/runner-engines/runner-provider-usage.tsx b/apps/web/src/components/runner-engines/runner-provider-usage.tsx index 46b2d59e7..f63efd4a6 100644 --- a/apps/web/src/components/runner-engines/runner-provider-usage.tsx +++ b/apps/web/src/components/runner-engines/runner-provider-usage.tsx @@ -15,6 +15,7 @@ import { Button } from "@/components/ui/button"; import { runnerEngineCapability, useRunnerProviderUsage, + useRunnerEngineInventory, } from "@/hooks/use-runner-engines"; export function RunnerProviderUsage({ @@ -24,7 +25,15 @@ export function RunnerProviderUsage({ runnerId: string; allowReset?: boolean; }) { - const usage = useRunnerProviderUsage(runnerId, true); + const inventory = useRunnerEngineInventory({ kind: "runner", runnerId }); + const accountEntries = inventory.data?.entries.filter( + (entry) => entry.id === "claude" || entry.id === "codex" + ); + const canReadUsage = + accountEntries?.some( + (entry) => entry.installed && entry.signedIn !== false + ) ?? false; + const usage = useRunnerProviderUsage(runnerId, canReadUsage); const [confirmation, setConfirmation] = useState(null); const redeem = useMutation({ mutationFn: (account: string) => @@ -35,10 +44,16 @@ export function RunnerProviderUsage({ ), onSettled: () => usage.refetch(), }); - const report = usage.data; + const report = canReadUsage ? usage.data : undefined; + const providers = report?.providers.filter((plan) => + accountEntries?.some( + (entry) => + entry.id === plan.engine && entry.installed && entry.signedIn !== false + ) + ); const account = report?.codexResetAccount; const resetCount = - report?.providers.find((plan) => plan.engine === "codex")?.limitResets + providers?.find((plan) => plan.engine === "codex")?.limitResets ?.available ?? 0; const canRedeem = allowReset && @@ -52,25 +67,37 @@ export function RunnerProviderUsage({

    Plan limits

    - + {canReadUsage && ( + + )}
    - {usage.isPending &&

    Reading runner usage…

    } - {usage.isError && ( + {accountEntries && !canReadUsage && ( +

    + + Set up Claude or Codex + {" "} + to see usage here. +

    + )} + {canReadUsage && usage.isPending && ( +

    Reading runner usage…

    + )} + {canReadUsage && usage.isError && (

    {report ? "Showing the last report. Refresh failed." : usage.error.message}

    )} - {report?.providers.map((plan) => ( + {providers?.map((plan) => (

    {plan.engine === "codex" ? "Codex" : "Claude"} @@ -111,7 +138,7 @@ export function RunnerProviderUsage({ available

    )} - {allowReset && ( + {allowReset && account && resetCount > 0 && ( setConfirmation(open ? (account ?? null) : null) diff --git a/bin/install-dispatch-runner.sh b/bin/install-dispatch-runner.sh index b618ec16d..76d0187c6 100755 --- a/bin/install-dispatch-runner.sh +++ b/bin/install-dispatch-runner.sh @@ -111,6 +111,20 @@ install_service_unit() { fi } +install_engine_prerequisites() { + if command -v node >/dev/null && command -v npm >/dev/null; then + return + fi + if [[ -r /etc/os-release ]] && ( + . /etc/os-release + [[ "${ID:-}" == ubuntu ]] + ); then + if ! /usr/bin/apt-get update || ! /usr/bin/apt-get install -y nodejs npm; then + printf 'Could not install Node.js and npm. Install them before using managed engine setup.\n' >&2 + fi + fi +} + install_runner() { local account_entry account_home account_shell if [[ -e "$command_path" || -L "$command_path" ]]; then @@ -324,6 +338,7 @@ main() { trap 'exit 143' TERM if [[ "$action" == install ]]; then stage_release + install_engine_prerequisites install_runner else update_runner diff --git a/packages/runner-protocol/src/github.ts b/packages/runner-protocol/src/github.ts index a4fb13380..a15883fc8 100644 --- a/packages/runner-protocol/src/github.ts +++ b/packages/runner-protocol/src/github.ts @@ -182,6 +182,8 @@ export function isGitHubPullRequestObservation( ); } +export const githubCliMissing = "GitHub CLI is missing on this runner."; + export type GitHubStatus = | { status: "signed-in"; login: string } | { status: "pending"; code?: string; verificationUrl?: string } @@ -319,7 +321,9 @@ export function parseGitHubStatus(value: unknown): GitHubStatus { case "signed-out": return { status: "signed-out" }; case "unavailable": - return { status: "unavailable" }; + return value.message === githubCliMissing + ? { status: "unavailable", message: githubCliMissing } + : { status: "unavailable" }; case "failed": return { status: "failed" }; } From 55ff3b63bbf2ad41dba2f5da2b3896df685d5976 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 21:05:39 -0700 Subject: [PATCH 159/642] Identify runner engines with their shared icons --- .../runner-engines/runner-engines.tsx | 62 ++++++++++++------- 1 file changed, 41 insertions(+), 21 deletions(-) diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index 0e14e6659..c678a1f86 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -7,6 +7,8 @@ import type { EngineLoginView, } from "@dispatch/runner-protocol/engine-management"; +import { AgentTypeIcon } from "@/components/app/agent-type-icon"; +import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { CopyButton } from "@/components/ui/copy-button"; import { Input } from "@/components/ui/input"; @@ -17,6 +19,12 @@ import { } from "@/hooks/use-runner-engines"; import type { EngineScope } from "@dispatch/runner-protocol/engine-management"; +const engineIconColors = { + claude: "border-orange-500/25 bg-orange-500/10 text-orange-500", + codex: "border-sky-500/25 bg-sky-500/10 text-sky-500", + opencode: "border-violet-500/25 bg-violet-500/10 text-violet-500", +}; + const ubuntuNodeSetup = "sudo apt-get update && sudo apt-get install nodejs npm"; @@ -104,6 +112,12 @@ export function RunnerEngines({ } /> ))} + {entries.some((entry) => entry.issue === "install-unavailable") && ( +

    + For engines marked “Install unavailable”, check the configured install + command on the runner. +

    + )}
    ); } @@ -179,20 +193,33 @@ function EngineRow({ data-testid={`runner-engine-${entry.id}`} >
    -
    -
    {entry.label}
    -

    - {entry.installed ? ( - <> - {entry.version ? `v${entry.version}` : "Installed"} - {entry.signedIn === true && " · signed in"} - {entry.signedIn === false && " · signed out"} - {entry.detail && entry.signedIn && ` · ${entry.detail}`} - - ) : ( - "Not installed" - )} -

    +
    + +
    +
    {entry.label}
    +

    + {entry.installed ? ( + <> + {entry.version ? `v${entry.version}` : "Installed"} + {entry.signedIn === true && " · signed in"} + {entry.signedIn === false && " · signed out"} + {entry.detail && entry.signedIn && ` · ${entry.detail}`} + + ) : entry.issue === "install-unavailable" ? ( + "Install unavailable" + ) : ( + "Not installed" + )} +

    +
    {canInstall && ( @@ -243,13 +270,6 @@ function EngineRow({ )} - {entry.issue === "install-unavailable" && ( -

    - The configured install command could not run. Ask the runner - administrator to check it. -

    - )} - {operation.isError && (

    {operation.error.message} From 9148e4d3e4bf4990b722d4085aedd6e1312e6290 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 21:17:56 -0700 Subject: [PATCH 160/642] =?UTF-8?q?Install=20managed=20engines=20with=20th?= =?UTF-8?q?e=20runner=E2=80=99s=20bundled=20package=20manager?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../agents/remote/engine-runner-executor.ts | 107 ++++++++++++------ apps/server/src/agents/remote/runner.ts | 1 + .../test/engine-runner-executor.test.ts | 29 +++-- .../components/app/runner-github-account.tsx | 38 +++++-- .../runner-engines/runner-engines.tsx | 36 +----- bin/install-dispatch-runner.sh | 21 +--- docs/remote-runner-linux.md | 7 +- scripts/remote-runner/test-installer.sh | 7 +- 8 files changed, 121 insertions(+), 125 deletions(-) diff --git a/apps/server/src/agents/remote/engine-runner-executor.ts b/apps/server/src/agents/remote/engine-runner-executor.ts index 3c74e5aaf..85b0824b5 100644 --- a/apps/server/src/agents/remote/engine-runner-executor.ts +++ b/apps/server/src/agents/remote/engine-runner-executor.ts @@ -1,4 +1,5 @@ import { spawn } from "node:child_process"; +import { isDeepStrictEqual } from "node:util"; import { randomUUID } from "node:crypto"; import { chown, mkdtemp } from "node:fs/promises"; import os from "node:os"; @@ -64,6 +65,7 @@ export type RunnerEngineConfig = { export type EngineRunnerExecutorConfig = { uid: number; gid: number; + bundledRuntime?: string; /** Merged into every spawned process's environment (HOME, PATH, CA, …). */ env: NodeJS.ProcessEnv; engines: Partial>; @@ -110,7 +112,7 @@ function sanitizeVersion(output: string): string | null { } export class EngineRunnerExecutor { - private nodeSetup?: Promise; + private installingBundledPackage = false; private readonly logins: EngineLogins; private readonly wrap: NonNullable; @@ -252,25 +254,41 @@ export class EngineRunnerExecutor { return (await this.resolveEngine(engine)).bin; } - private ensureManagedNode(prefix: string): Promise { - return (this.nodeSetup ??= (async () => { - const node = await this.probe("node"); - if (Number(node.version?.split(".")[0]) >= 22) return true; + private bundledCommand( + engine: RunnerEngine, + step: ManagedCommand + ): ManagedCommand | null { + const runtime = this.config.bundledRuntime; + if (!runtime || !this.canUseSharedBin(engine)) return null; + const prefix = path.join(this.config.env.HOME!, ".local"); + const pkg = MANAGED_PACKAGES[engine] + "@latest"; + const bundled = { + executable: runtime, + args: ["add", "--global", "--trust", pkg], + env: { BUN_BE_BUN: "1", BUN_INSTALL: prefix }, + }; + // Earlier managed installs wrote npm commands to runner.json. Recognize + // exactly those defaults so existing pairings can use the bundled runtime. + const legacy = { + executable: "npm", + args: ["install", "--global", "--prefix", prefix, pkg], + }; + return isDeepStrictEqual(step, legacy) || isDeepStrictEqual(step, bundled) + ? bundled + : null; + } - // Ubuntu may provide a working npm backed by an older Node. Bootstrap - // Node into the same workload-owned prefix used for engine binaries. - const install = await this.run( - "npm", - ["install", "--global", "--prefix", prefix, "node@22"], - this.config.env, - 90_000 - ); - if (install.code !== 0) return false; - const installed = await this.probe("node"); - return Number(installed.version?.split(".")[0]) >= 22; - })().finally(() => { - this.nodeSetup = undefined; - })); + private async ensureManagedNode(command: ManagedCommand): Promise { + const usable = async () => + Number((await this.probe("node")).version?.split(".")[0]) >= 22; + if (await usable()) return true; + const result = await this.run( + command.executable, + ["add", "--global", `node-linux-${process.arch}@22`], + { ...this.config.env, ...command.env }, + 90_000 + ); + return result.code === 0 && (await usable()); } /** The scope-aware engine list and supported actions, for a snapshot view. */ @@ -289,7 +307,12 @@ export class EngineRunnerExecutor { const actions: EngineSupportedAction[] = []; let issue: string | undefined; if (!installed && cfg?.install) { - if (await this.commandUsable(cfg.install)) actions.push("install"); + if ( + await this.commandUsable( + this.bundledCommand(engine, cfg.install) ?? cfg.install + ) + ) + actions.push("install"); else issue = cfg.install.executable === "npm" @@ -382,6 +405,31 @@ export class EngineRunnerExecutor { error: `No managed ${kind} command is configured for ${LABELS[engine]} on this runner.`, }; } + const bundled = this.bundledCommand(engine, step); + if (!bundled) + return this.executeManaged(engine, kind, step, false, onEvent); + if (this.installingBundledPackage) + return { + ok: false, + error: + "Another engine installation is in progress. Try again when it finishes.", + }; + this.installingBundledPackage = true; + try { + return await this.executeManaged(engine, kind, bundled, true, onEvent); + } finally { + this.installingBundledPackage = false; + } + } + + private async executeManaged( + engine: RunnerEngine, + kind: "install" | "update", + step: ManagedCommand, + bundled: boolean, + onEvent?: (event: EngineOperationEvent) => void + ): Promise { + const cfg = this.config.engines[engine]; const current = await this.resolveEngine(engine); if (current.installed && current.bin !== cfg?.bin) { return { @@ -397,24 +445,9 @@ export class EngineRunnerExecutor { phase: kind, message: kind === "install" ? "Installing…" : "Updating…", }); - const prefix = path.join(this.config.env.HOME ?? "", ".local"); - const defaultInstallArgs = [ - "install", - "--global", - "--prefix", - prefix, - `${MANAGED_PACKAGES[engine]}@latest`, - ]; - if ( - this.canUseSharedBin(engine) && - step.executable === "npm" && - !step.env && - step.args.length === defaultInstallArgs.length && - step.args.every((arg, index) => arg === defaultInstallArgs[index]) && - !(await this.ensureManagedNode(prefix)) - ) { + if (bundled && !(await this.ensureManagedNode(step))) { const message = - "Could not set up Node.js 22 for managed engine installs. Check npm and registry access on this runner."; + "Could not install the engine runtime. Check this runner’s access to the package registry."; onEvent?.({ type: "operation_complete", operationId, diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 7258f136c..e8dc216e8 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -267,6 +267,7 @@ export async function runRemoteRunner(filename: string) { }); github.onLogin = () => pullRequests.reset(); const engineExecutor = new EngineRunnerExecutor({ + bundledRuntime: process.versions.bun ? process.execPath : undefined, uid: config.uid, gid: config.gid, env, diff --git a/apps/server/test/engine-runner-executor.test.ts b/apps/server/test/engine-runner-executor.test.ts index 1f8080bca..9151e3b1c 100644 --- a/apps/server/test/engine-runner-executor.test.ts +++ b/apps/server/test/engine-runner-executor.test.ts @@ -115,7 +115,7 @@ if (args === "--version") { ).toBe(false); }); - it("bootstraps Node into the workload prefix before running a default npm install", async () => { + it("uses the bundled runtime for a legacy managed install with no system npm", async () => { const prefix = path.join(dir, ".local"); const managed = path.join(prefix, "bin", "claude"); const args = [ @@ -125,8 +125,9 @@ if (args === "--version") { prefix, "@anthropic-ai/claude-code@latest", ]; - const npmPackages: string[] = []; + const packages: string[] = []; executor = new EngineRunnerExecutor({ + bundledRuntime: "/opt/dispatch-runner/dispatch", uid: 1000, gid: 1000, env: { ...process.env, HOME: dir }, @@ -137,32 +138,28 @@ if (args === "--version") { if (bin === "node") return { bin: "/bin/echo", - args: [npmPackages.length ? "v22.0.0" : "v18.0.0"], + args: [packages.length ? "v22.0.0" : "v18.0.0"], }; - if (bin === "npm") { - expect(args.slice(0, 4)).toEqual([ - "install", - "--global", - "--prefix", - prefix, - ]); - npmPackages.push(args[4]!); + if (bin === "/opt/dispatch-runner/dispatch") { + if (args[0] === "--version") + return { bin: "/bin/echo", args: ["1.3.13"] }; + expect(args.slice(0, 2)).toEqual(["add", "--global"]); + packages.push(args.at(-1)!); return { bin: "/bin/sh", args: ["-c", "exit 0"] }; } - const installed = npmPackages.includes( - "@anthropic-ai/claude-code@latest" - ); + const installed = packages.includes("@anthropic-ai/claude-code@latest"); return { bin: installed && bin === managed ? fake : "/nonexistent", args, }; }, }); + expect((await executor.inventory())[0]?.actions).toContain("install"); await expect( executor.handle({ type: "install", engine: "claude" }) ).resolves.toMatchObject({ ok: true }); - expect(npmPackages).toEqual([ - "node@22", + expect(packages).toEqual([ + `node-linux-${process.arch}@22`, "@anthropic-ai/claude-code@latest", ]); }); diff --git a/apps/web/src/components/app/runner-github-account.tsx b/apps/web/src/components/app/runner-github-account.tsx index 513f2af5a..f38199d13 100644 --- a/apps/web/src/components/app/runner-github-account.tsx +++ b/apps/web/src/components/app/runner-github-account.tsx @@ -1,4 +1,8 @@ -import { githubDeviceUrl, type GitHubStatus } from "@dispatch/runner-protocol"; +import { + githubCliMissing, + githubDeviceUrl, + type GitHubStatus, +} from "@dispatch/runner-protocol"; import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { ExternalLink, Github } from "lucide-react"; @@ -46,7 +50,7 @@ function accountSummary(account: GitHubStatus) { case "signed-in": return `Signed in as @${account.login}`; case "signed-out": - return "Signed out · optional for GitHub access"; + return "Connect GitHub to use private repositories."; case "pending": return account.code ? "Waiting for GitHub approval" @@ -54,10 +58,9 @@ function accountSummary(account: GitHubStatus) { case "failed": return "Sign-in did not complete. Try again."; case "unavailable": - return ( - account.message ?? - "Couldn’t verify the GitHub account from this runner. Check its connection and retry." - ); + return account.message === githubCliMissing + ? githubCliMissing + : "Connect GitHub to use private repositories."; } } @@ -76,10 +79,20 @@ function ConnectedAccount({ runner }: { runner: Runner }) { }); const action = useMutation({ gcTime: 0, - mutationFn: (op: "login" | "logout" | "cancel") => - api(op === "logout" ? path : path + "/login", { - method: op === "login" ? "POST" : "DELETE", - }), + mutationFn: async (op: "login" | "logout" | "cancel") => { + const result = await api( + op === "logout" ? path : path + "/login", + { + method: op === "login" ? "POST" : "DELETE", + } + ); + if (result.status === "unavailable" || result.status === "failed") { + throw new Error( + result.message ?? "Couldn’t complete the GitHub request." + ); + } + return result; + }, onMutate: () => client.cancelQueries({ queryKey: key }), onSuccess: async (value) => { client.setQueryData(key, value); @@ -93,7 +106,8 @@ function ConnectedAccount({ runner }: { runner: Runner }) { const state = account.data; const pending = state?.status === "pending"; const signedIn = state?.status === "signed-in"; - const unavailable = state?.status === "unavailable"; + const missingCli = + state?.status === "unavailable" && state.message === githubCliMissing; const statusText = account.isError ? "Couldn’t read the account." : state @@ -111,7 +125,7 @@ function ConnectedAccount({ runner }: { runner: Runner }) { {statusText}

    - {account.isError || unavailable ? ( + {account.isError || missingCli ? (
    ); } @@ -197,10 +166,7 @@ function EngineRow({
    diff --git a/bin/install-dispatch-runner.sh b/bin/install-dispatch-runner.sh index 76d0187c6..56263d4f9 100755 --- a/bin/install-dispatch-runner.sh +++ b/bin/install-dispatch-runner.sh @@ -54,11 +54,11 @@ start_enabled_runner() { stable_start } -# npm's global prefix has a bin/ directory that the workload owns and uses for launch. +# The standalone runner doubles as Bun's package installer under the workload UID. engine_commands() { local package="$1" command - printf -v command '{"executable":"npm","args":["install","--global","--prefix","%s","%s@latest"]}' \ - "$state/home/.local" "$package" + printf -v command '{"executable":"%s/dispatch","args":["add","--global","--trust","%s@latest"],"env":{"BUN_BE_BUN":"1","BUN_INSTALL":"%s/home/.local"}}' \ + "$runtime" "$package" "$state" printf '{"install":%s,"update":%s}' "$command" "$command" } @@ -111,20 +111,6 @@ install_service_unit() { fi } -install_engine_prerequisites() { - if command -v node >/dev/null && command -v npm >/dev/null; then - return - fi - if [[ -r /etc/os-release ]] && ( - . /etc/os-release - [[ "${ID:-}" == ubuntu ]] - ); then - if ! /usr/bin/apt-get update || ! /usr/bin/apt-get install -y nodejs npm; then - printf 'Could not install Node.js and npm. Install them before using managed engine setup.\n' >&2 - fi - fi -} - install_runner() { local account_entry account_home account_shell if [[ -e "$command_path" || -L "$command_path" ]]; then @@ -338,7 +324,6 @@ main() { trap 'exit 143' TERM if [[ "$action" == install ]]; then stage_release - install_engine_prerequisites install_runner else update_runner diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index b97c52316..d8968c293 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -26,10 +26,9 @@ For manual source runs, use Bun. Settings. 3. Select the runner in **Settings → Runners**. Under **Agent engines**, choose **Install** for - the engine you want, then **Sign in** for Codex or Claude. The runner uses - Node.js and npm from its workload PATH to install engine binaries under - `/var/lib/dispatch-runner/home/.local/bin`. Install Node.js and npm on - the Linux host to enable managed engine installs and updates. Credentials + the engine you want, then **Sign in** for Codex or Claude. The runner uses its + bundled package manager and installs any required Node runtime under + `/var/lib/dispatch-runner/home/.local`. Credentials belong to that runner's workload account. 4. In **Create Agent**, choose the runner. A Dispatch project can supply the repository. Select a base branch for a new worktree, use an existing branch, diff --git a/scripts/remote-runner/test-installer.sh b/scripts/remote-runner/test-installer.sh index df665901b..4f3e7670b 100755 --- a/scripts/remote-runner/test-installer.sh +++ b/scripts/remote-runner/test-installer.sh @@ -169,7 +169,7 @@ run install v1.0.0 ! grep -Eq '^(start|enable) ' "$root/systemctl" [[ "$(find "$root/settings/runner.json" -perm 0600 -print)" == "$root/settings/runner.json" ]] grep -q '"workspaces": {}' "$root/settings/runner.json" -node - "$root/settings/runner.json" <<'JS' +node - "$root/settings/runner.json" "$root/runtime/dispatch" <<'JS' const assert = require("node:assert/strict"); const fs = require("node:fs"); const config = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); @@ -179,8 +179,9 @@ for (const [engine, pkg] of Object.entries(packages)) { assert.equal(config.bins[engine + "Bin"], prefix + "/bin/" + engine); for (const action of ["install", "update"]) { assert.deepEqual(config.engines[engine][action], { - executable: "npm", - args: ["install", "--global", "--prefix", prefix, pkg + "@latest"] + executable: process.argv[3], + args: ["add", "--global", "--trust", pkg + "@latest"], + env: {BUN_BE_BUN: "1", BUN_INSTALL: prefix} }); } } From 26588435667f9e54f9f2ca7b903f09e0cfb6b0ea Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 21:07:53 -0700 Subject: [PATCH 161/642] Unify managed runner project and repository selection --- .../app/agent-engine-fields.test.tsx | 12 +- .../components/app/agent-engine-fields.tsx | 11 +- .../src/components/app/agent-model-select.tsx | 36 ++- .../components/app/create-agent-dialog.tsx | 119 +++++---- apps/web/src/components/app/runner-picker.tsx | 14 +- .../components/app/runner-project-picker.tsx | 234 ++++++++++++++++++ .../app/runner-repository-fields.tsx | 179 +++----------- .../app/use-create-agent-form.test.tsx | 22 +- .../components/app/use-create-agent-form.ts | 132 +++++++--- apps/web/src/hooks/use-agent-model-catalog.ts | 9 +- apps/web/src/hooks/use-runner-engines.ts | 3 +- e2e/remote-runner/entrypoint.sh | 10 + e2e/remote-runner/harness.ts | 11 +- e2e/remote-runner/setup.mjs | 2 +- 14 files changed, 525 insertions(+), 269 deletions(-) create mode 100644 apps/web/src/components/app/runner-project-picker.tsx diff --git a/apps/web/src/components/app/agent-engine-fields.test.tsx b/apps/web/src/components/app/agent-engine-fields.test.tsx index 4e4d429f6..d91d6802d 100644 --- a/apps/web/src/components/app/agent-engine-fields.test.tsx +++ b/apps/web/src/components/app/agent-engine-fields.test.tsx @@ -27,12 +27,14 @@ vi.mock("./use-create-agent-form", async () => { return { step: "config", createType: createType.value, + agentTypes: enabledAgentTypes, setCreateType: vi.fn(), createModel: null, createEffort: null, setCreateEffort: vi.fn(), setCreateModel: vi.fn(), modelOptions: models.options, + defaultModel: models.defaultModel, modelCatalogLoading: models.loading, createName: "", setCreateName: vi.fn(), @@ -185,9 +187,11 @@ const renderHost = (host: "create" | "trigger") => { * adds a hidden native select only inside a
    , which Create Agent is. */ const engineBlock = () => { - const type = screen.getByRole("combobox", { name: "Type" }); + const type = screen.getByRole("combobox", { name: /^(Agent|Type)$/ }); const block = type.parentElement!.parentElement!.parentElement!; return block.outerHTML + .replace(">Agent", ">Type") + .replaceAll(">Use engine setting<", ">Default<") .replace(/task-trigger-type/g, "agent-type-select") .replace(/task-trigger-(model|engine|effort)/g, "create-agent-$1") .replace(/radix-[^"]*/g, "radix") @@ -250,11 +254,11 @@ it("says what to install for a missing engine in both hosts", async () => { expect(trigger).toBe(create); }); -it("hides the model picker without a catalog in both hosts", async () => { +it("keeps the Model field in Create Agent without a catalog", async () => { createType.value = templateType.value = "opencode"; - const create = await blockIn("create", false); + const create = await blockIn("create", true); const trigger = await blockIn("trigger", false); - expect(trigger).toBe(create); + expect(create).toContain("create-agent-model"); expect(trigger).toContain("grid-cols-[minmax(0,1fr)_4.75rem]"); expect(trigger).toContain("OpenCode · /usr/local/bin/opencode"); }); diff --git a/apps/web/src/components/app/agent-engine-fields.tsx b/apps/web/src/components/app/agent-engine-fields.tsx index 30e0f947e..e7b7de5bd 100644 --- a/apps/web/src/components/app/agent-engine-fields.tsx +++ b/apps/web/src/components/app/agent-engine-fields.tsx @@ -13,12 +13,14 @@ type AgentEngineFieldsProps = { agentType: AgentType; onAgentTypeChange: (type: AgentType) => void; agentTypes: AgentType[]; + agentLabel?: string; effort?: Effort | null; effortDefaultLabel?: string; onEffortChange?: (effort: Effort | null) => void; model: string | null; onModelChange: (model: string | null) => void; modelOptions: readonly AgentModelOption[]; + catalogDefault?: string | null; modelLoading: boolean; onTypeOpenChange?: (open: boolean) => void; /** Overridden by dialogs other than Create Agent so ids stay unique. */ @@ -31,12 +33,13 @@ type AgentEngineFieldsProps = { /** * The type and model pickers side by side, with the engine Dispatch will * drive named underneath. Every dialog that launches an agent shows them the - * same way. The model picker stays hidden for an engine with no catalog. + * same way. Create Agent keeps the model picker visible without a catalog. */ export function AgentEngineFields({ agentType, onAgentTypeChange, agentTypes, + agentLabel, model, effort, effortDefaultLabel, @@ -44,6 +47,7 @@ export function AgentEngineFields({ onModelChange, modelOptions, modelLoading, + catalogDefault, onTypeOpenChange, idPrefix, remote = false, @@ -65,7 +69,8 @@ export function AgentEngineFields({ [engines] ); const engineLine = remote ? null : engineSummary(engines, agentType); - const showModelSelect = modelLoading || modelOptions.length > 0; + const showModelSelect = + catalogDefault !== undefined || modelLoading || modelOptions.length > 0; return (
    @@ -78,6 +83,7 @@ export function AgentEngineFields({ value={agentType} onChange={onAgentTypeChange} agentTypes={agentTypes} + label={agentLabel} onOpenChange={onTypeOpenChange} missing={remote ? undefined : missingEngines} /> @@ -88,6 +94,7 @@ export function AgentEngineFields({ testId={idPrefix ? `${idPrefix}-model` : undefined} value={model} options={modelOptions} + catalogDefault={catalogDefault} onChange={onModelChange} loading={modelLoading} /> diff --git a/apps/web/src/components/app/agent-model-select.tsx b/apps/web/src/components/app/agent-model-select.tsx index 6d2e36e85..328e9b08b 100644 --- a/apps/web/src/components/app/agent-model-select.tsx +++ b/apps/web/src/components/app/agent-model-select.tsx @@ -11,6 +11,7 @@ type AgentModelOption = { id: string; label: string }; type AgentModelSelectProps = { value: string | null; options: readonly AgentModelOption[]; + catalogDefault?: string | null; onChange: (model: string | null) => void; loading?: boolean; /** Overridden by dialogs other than Create Agent so ids stay unique. */ @@ -23,18 +24,15 @@ const DEFAULT_VALUE = "__default__"; export function AgentModelSelect({ value, options, + catalogDefault, onChange, loading = false, id = "create-agent-model", testId = "create-agent-model", }: AgentModelSelectProps): JSX.Element { - // Radix renders an empty trigger whenever the selected value has no matching - // item, so anything unrecognized (a retired model id, a stray empty string) - // falls back to Default — which is what an unset model means anyway. + const fallback = catalogDefault ?? DEFAULT_VALUE; const selectedValue = - value && options.some((option) => option.id === value) - ? value - : DEFAULT_VALUE; + value && options.some((option) => option.id === value) ? value : fallback; return (
    @@ -48,14 +46,30 @@ export function AgentModelSelect({ // onValueChange when its native
    diff --git a/apps/web/src/components/runner-engines/runner-engines.test.tsx b/apps/web/src/components/runner-engines/runner-engines.test.tsx index ef9b4d0a4..f884c902b 100644 --- a/apps/web/src/components/runner-engines/runner-engines.test.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.test.tsx @@ -129,7 +129,9 @@ it("walks a Codex-style device sign-in to the waiting state", async () => { fireEvent.click(screen.getByTestId("runner-engine-claude-sign-in")); await waitFor(() => expect(screen.getByText("ABCD-1234")).toBeTruthy()); - expect(screen.getByText("https://auth.example.com/device")).toBeTruthy(); + expect( + screen.getByDisplayValue("https://auth.example.com/device") + ).toBeTruthy(); }); it("surfaces a failed update instead of silently reporting success", async () => { diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index b58dc0bbe..7ef6f71f2 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -8,7 +8,7 @@ import type { } from "@dispatch/runner-protocol/engine-management"; import { AgentTypeIcon } from "@/components/app/agent-type-icon"; -import { Button } from "@/components/ui/button"; +import { LoadingButton } from "@/components/ui/button"; import { CopyButton } from "@/components/ui/copy-button"; import { Input } from "@/components/ui/input"; import { @@ -53,14 +53,15 @@ export function RunnerEngines({

    Could not load engines.

    - +
    ); } @@ -141,7 +142,7 @@ function EngineRow({ operation.mutate(op, { onSuccess: ({ ack }) => { if (ack.ok && ack.login) onLoginChange(ack.login); - if (op.type === "install" || op.type === "update") { + if (!ack.ok || op.type === "install" || op.type === "update") { setActionResult( ack.ok ? { kind: "success", message: ack.message ?? "Done." } @@ -152,6 +153,9 @@ function EngineRow({ }); }; + const pendingAction = operation.isPending + ? operation.variables?.type + : undefined; const canInstall = entry.actions.includes("install"); const canUpdate = entry.actions.includes("update"); const canLogin = entry.actions.includes("login"); @@ -189,42 +193,45 @@ function EngineRow({
    {canInstall && ( - + {pendingAction === "install" ? "Installing…" : "Install"} + )} {canUpdate && ( - + {pendingAction === "update" ? "Updating…" : "Update"} + )} {canLogin && entry.signedIn !== true && !isLoginActive(activeLogin) && ( - + {pendingAction === "login_start" ? "Starting…" : "Sign in"} + )}
    @@ -278,9 +285,9 @@ function EngineRow({ } onCancel={() => { run({ type: "login_cancel", loginId: activeLogin.id }); - onLoginChange(null); }} - submitting={operation.isPending} + submitting={pendingAction === "login_submit"} + cancelling={pendingAction === "login_cancel"} /> )} @@ -309,6 +316,7 @@ function LoginFlow({ onSubmit, onCancel, submitting, + cancelling, }: { login: EngineLoginView; code: string; @@ -316,6 +324,7 @@ function LoginFlow({ onSubmit: () => void; onCancel: () => void; submitting: boolean; + cancelling: boolean; }): JSX.Element { if (login.status !== "waiting" || !login.url) { return ( @@ -326,26 +335,37 @@ function LoginFlow({ ? "Checking the code…" : "Starting the sign-in…"}

    - +
    ); } return (
    -
    - - {login.url} - - +
    + +
    {login.userCode ? (
    @@ -364,15 +384,17 @@ function LoginFlow({
    ) : ( @@ -380,7 +402,7 @@ function LoginFlow({ className="flex gap-2" onSubmit={(event) => { event.preventDefault(); - if (code.trim()) onSubmit(); + if (code.trim() && !submitting && !cancelling) onSubmit(); }} > - - + )}
    diff --git a/apps/web/src/components/runner-engines/runner-plugin.tsx b/apps/web/src/components/runner-engines/runner-plugin.tsx index 4c22d1295..7cca8274b 100644 --- a/apps/web/src/components/runner-engines/runner-plugin.tsx +++ b/apps/web/src/components/runner-engines/runner-plugin.tsx @@ -1,6 +1,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { Button } from "@/components/ui/button"; +import { LoadingButton } from "@/components/ui/button"; import { runnerEngineCapability } from "@/hooks/use-runner-engines"; export function RunnerPlugin({ @@ -65,19 +65,32 @@ export function RunnerPlugin({ : "checking…"} {offered && !status.isError && ( - + {change.isPending + ? action === "install" + ? "Installing plugin…" + : "Updating plugin…" + : status.isFetching + ? "Checking plugin…" + : action === "install" + ? "Install plugin" + : "Update plugin"} + )} {status.isError && ( - + )} {change.isError && {change.error.message}}
    diff --git a/apps/web/src/components/runner-engines/runner-provider-usage.tsx b/apps/web/src/components/runner-engines/runner-provider-usage.tsx index f63efd4a6..11a226f6f 100644 --- a/apps/web/src/components/runner-engines/runner-provider-usage.tsx +++ b/apps/web/src/components/runner-engines/runner-provider-usage.tsx @@ -11,7 +11,7 @@ import { AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { createClientId } from "@/lib/client-id"; -import { Button } from "@/components/ui/button"; +import { LoadingButton } from "@/components/ui/button"; import { runnerEngineCapability, useRunnerProviderUsage, @@ -68,15 +68,16 @@ export function RunnerProviderUsage({

    Plan limits

    {canReadUsage && ( - + )}
    {accountEntries && !canReadUsage && ( @@ -145,14 +146,15 @@ export function RunnerProviderUsage({ } > - + Use a Codex reset credit? diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx index 95b668855..a6f550484 100644 --- a/apps/web/src/components/ui/button.tsx +++ b/apps/web/src/components/ui/button.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { Loader2 } from "lucide-react"; import { Slot } from "@radix-ui/react-slot"; import { cva, type VariantProps } from "class-variance-authority"; @@ -62,4 +63,27 @@ const Button = React.forwardRef( ); Button.displayName = "Button"; -export { Button }; +function LoadingButton({ + loading, + disabled, + children, + ...props +}: Omit & { loading: boolean }) { + return ( + + ); +} + +export { Button, LoadingButton }; diff --git a/e2e/remote-runner/fixture-gh.sh b/e2e/remote-runner/fixture-gh.sh index 6d409c2f0..3da9b1502 100644 --- a/e2e/remote-runner/fixture-gh.sh +++ b/e2e/remote-runner/fixture-gh.sh @@ -10,6 +10,7 @@ case "$1 ${2:-}" in 'config get') if [ -s "$key" ]; then cat "$key"; else echo 'could not find key "user"' >&2; exit 1; fi ;; + 'config set') test "$*" = 'config set git_protocol https --host github.com' ;; 'auth login') printf '! First copy your one-time code: B123-C456\nOpen this URL to continue in your web browser: https://github.com/login/device\n' >&2 while [ ! -f /tmp/github-fixture-approved ]; do sleep .1; done @@ -41,13 +42,13 @@ case "$1 ${2:-}" in test -s "$key" case " $* " in *'/pulls/'*) printf '{"url":"https://github.com/%s/private.git","branch":"review-topic"}\n' "$login" ;; + *' search/repositories '*) + test -s "$key" + printf '[{"fullName":"%s/private","url":"https://github.com/%s/private"}]\n' "$login" "$login" + ;; *' user '*) printf '%s\n' "$login" ;; *) exit 1 ;; esac ;; - 'search repos') - test -s "$key" - printf '[{"fullName":"%s/private","url":"https://github.com/%s/private"}]\n' "$login" "$login" - ;; *) [ "$1" = --version ] && echo 'gh version 2.86.0 (fixture)' ;; esac From 43cb28b609ed029463512a60a40c6b9ae3e66487 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 22:14:55 -0700 Subject: [PATCH 165/642] Keep remote runner test binaries only for the lifetime of each run --- e2e/remote-runner/setup.mjs | 76 ++++++++++++++--------------------- scripts/e2e-remote-runners.sh | 7 +++- 2 files changed, 35 insertions(+), 48 deletions(-) diff --git a/e2e/remote-runner/setup.mjs b/e2e/remote-runner/setup.mjs index f9f06e817..07514d338 100644 --- a/e2e/remote-runner/setup.mjs +++ b/e2e/remote-runner/setup.mjs @@ -8,12 +8,12 @@ import { execFileSync, spawn } from "node:child_process"; import { chmodSync, copyFileSync, - existsSync, mkdirSync, readFileSync, + rmdirSync, + rmSync, writeFileSync, } from "node:fs"; -import { createHash } from "node:crypto"; import { createServer } from "node:net"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -23,10 +23,6 @@ const root = path.resolve(here, "../.."); const RUNNERS = ["alpha", "beta", "scratch"]; const WORKSPACE = "proof"; // identical handle on every runner, on purpose const WORKSPACE_DIR = "/opt/dispatch-guest-proof"; -// Colima/Docker Desktop share $HOME, not /tmp, with the VM; bind mounts must live here. -export const base = - process.env.REMOTE_E2E_ROOT ?? - path.join(process.env.HOME, ".cache", "dispatch-remote-e2e"); // The supervisor uses procps to reap engine descendants during archive. const IMAGE = process.env.REMOTE_E2E_IMAGE ?? "node:22-bookworm"; const sh = (cmd, args, opts = {}) => @@ -44,49 +40,21 @@ const freePort = () => }); }); -function artifacts(arch) { - const inputs = [ - "apps/server/src", - "apps/server/test/helpers", - "e2e/fixtures/runner-file-transfer.mjs", - "packages/runner-protocol", - "pnpm-lock.yaml", - ]; - const hash = createHash("sha256") - .update(sh("bun", ["--version"])) - .update(sh("git", ["ls-files", "-s", "--", ...inputs], { cwd: root })) - .update(sh("git", ["diff", "HEAD", "--", ...inputs], { cwd: root })) - .digest("hex") - .slice(0, 16); - const dir = path.join(base, `bin-${arch}-${hash}`); +// All three containers share this pair for the lifetime of the run. +function artifacts(arch, run) { + const dir = path.join(run, "compiled-runner"); + mkdirSync(dir, { mode: 0o700 }); const runner = path.join(dir, "dispatch-runner"); const adapter = path.join(dir, "remote-acp-fixture"); - if (!existsSync(runner) || !existsSync(adapter)) { - mkdirSync(dir, { recursive: true }); - sh("bun", ["scripts/generate-server-runtime-assets.mjs"], { cwd: root }); - const target = `bun-linux-${arch === "arm64" ? "arm64" : "x64"}`; + sh("bun", ["scripts/generate-server-runtime-assets.mjs"], { cwd: root }); + const target = `bun-linux-${arch === "arm64" ? "arm64" : "x64"}`; + for (const [entry, outfile] of [ + ["apps/server/src/main.ts", runner], + ["apps/server/test/helpers/remote-acp-fixture.ts", adapter], + ]) { sh( "bun", - [ - "build", - "--compile", - `--target=${target}`, - "apps/server/src/main.ts", - "--outfile", - runner, - ], - { cwd: root } - ); - sh( - "bun", - [ - "build", - "--compile", - `--target=${target}`, - "apps/server/test/helpers/remote-acp-fixture.ts", - "--outfile", - adapter, - ], + ["build", "--compile", `--target=${target}`, entry, "--outfile", outfile], { cwd: root } ); } @@ -111,7 +79,7 @@ async function up(run) { sh("docker", ["version", "--format", "{{.Server.Arch}}"]).trim() === "arm64" ? "arm64" : "x64"; - const bin = artifacts(arch); + const bin = artifacts(arch, run); const runnerPort = await freePort(); // DISPATCH_RUNNER_PORT: the service's enrolled-mode listener const controlPort = await freePort(); const lanes = []; @@ -222,6 +190,7 @@ async function up(run) { function down(run) { const id = path.basename(run); + let containersRemoved = false; try { const ids = sh("docker", [ "ps", @@ -232,6 +201,7 @@ function down(run) { .split(/\s+/) .filter(Boolean); if (ids.length) sh("docker", ["rm", "-f", ...ids]); + containersRemoved = true; } catch (e) { console.error("container cleanup:", e.message); } @@ -242,7 +212,21 @@ function down(run) { try { process.kill(Number(pid), "SIGTERM"); } catch {} + rmSync(path.join(run, "pids"), { force: true }); } catch {} + if (!containersRemoved) { + process.exitCode = 1; + return; + } + const dir = path.join(run, "compiled-runner"); + for (const binary of ["dispatch-runner", "remote-acp-fixture"]) { + rmSync(path.join(dir, binary), { force: true }); + } + try { + rmdirSync(dir); + } catch (error) { + if (error.code !== "ENOENT") throw error; + } } if (process.argv[1] === fileURLToPath(import.meta.url)) { diff --git a/scripts/e2e-remote-runners.sh b/scripts/e2e-remote-runners.sh index 21a1ca167..3e326b4ab 100755 --- a/scripts/e2e-remote-runners.sh +++ b/scripts/e2e-remote-runners.sh @@ -8,11 +8,14 @@ BASE="${REMOTE_E2E_ROOT:-$HOME/.cache/dispatch-remote-e2e}" # must be shared wi mkdir -p "$BASE" RUN_DIR="$BASE/run-$$-$(date +%s)" cleanup() { - node "$ROOT_DIR/e2e/remote-runner/setup.mjs" down "$RUN_DIR" || true - rm -rf "$RUN_DIR" + if ! node "$ROOT_DIR/e2e/remote-runner/setup.mjs" down "$RUN_DIR"; then + echo "Container cleanup failed; retained this run at $RUN_DIR to retry teardown." >&2 + exit 1 + fi # Credentials live only inside the containers; prove none survive. left="$(docker ps -aq --filter "label=dispatch-remote-e2e=$(basename "$RUN_DIR")")" [ -z "$left" ] || { echo "LEAK: runner containers remain: $left" >&2; exit 1; } + rm -rf "$RUN_DIR" } trap cleanup EXIT node "$ROOT_DIR/e2e/remote-runner/setup.mjs" up "$RUN_DIR" From 1f6e1f1f4fd0327ed56cd969ece1640f295dba3a Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 22:35:15 -0700 Subject: [PATCH 166/642] Keep Create Agent steady and browse repositories on the selected runner --- .../agents/remote/github-runner-executor.ts | 78 +++++++++++----- apps/server/src/agents/remote/runner.ts | 1 + apps/server/src/agents/remote/service.ts | 36 ++++++++ apps/server/src/routes/runner-repositories.ts | 21 ++++- apps/server/test/engine-wire.test.ts | 5 +- .../test/github-runner-executor.test.ts | 6 +- apps/server/test/runner-repositories.test.ts | 1 + .../components/app/agent-engine-fields.tsx | 10 ++- apps/web/src/components/app/branch-select.tsx | 88 +++++++++++++++---- .../components/app/create-agent-dialog.tsx | 70 ++++++++++----- .../app/create-agent-worktree-section.tsx | 26 ++++-- apps/web/src/components/app/runner-picker.tsx | 85 +++++++++--------- .../components/app/runner-project-picker.tsx | 15 +++- .../app/runner-repository-fields.tsx | 67 -------------- .../app/use-create-agent-form.test.tsx | 11 ++- .../components/app/use-create-agent-form.ts | 47 +++++----- apps/web/src/hooks/use-runners.ts | 1 + e2e/remote-runner/fixture-gh.sh | 5 +- e2e/remote-runner/harness.ts | 14 +-- packages/runner-protocol/src/execution.ts | 2 + packages/runner-protocol/src/github.ts | 5 ++ 21 files changed, 378 insertions(+), 216 deletions(-) delete mode 100644 apps/web/src/components/app/runner-repository-fields.tsx diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index 09d80466a..d1cfb34cf 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -11,6 +11,7 @@ import { githubPullRequestHead, githubRepositoryResults, validGitHubLogin, + validBranch, type GitHubOperation, type GitHubStatus, } from "./protocol.js"; @@ -312,31 +313,60 @@ export class GitHubRunnerExecutor { signal.throwIfAborted(); switch (operation.type) { case "repositorySearch": { - const rows = await this.run( - [ - "api", - ...hostArgs, - "search/repositories", - "--method", - "GET", - "-f", - `q=${operation.query} in:name`, - "-f", - "per_page=12", - "--jq", - "[.items[] | {fullName: .full_name, url: .html_url}]", - ], - signal - ); - const value: unknown = JSON.parse(rows); - if (!Array.isArray(value)) - throw new Error("Invalid GitHub repository list."); - return githubRepositoryResults( - value.map((row) => ({ - name: row?.fullName, - url: row?.url, - })) + const matches: { name: string; url: string }[] = []; + const query = operation.query.toLowerCase(); + for (let page = 1; matches.length < 12; page++) { + const rows: unknown = JSON.parse( + await this.run( + [ + "api", + ...hostArgs, + "user/repos", + "--method", + "GET", + "-f", + "affiliation=owner,collaborator,organization_member", + "-f", + "per_page=100", + "-f", + `page=${page}`, + "--jq", + "[.[] | {name: .full_name, url: .html_url}]", + ], + signal + ) + ); + if (!Array.isArray(rows)) + throw new Error("Invalid GitHub repository list."); + matches.push( + ...githubRepositoryResults( + rows.filter( + (row) => + typeof row?.name === "string" && + row.name.toLowerCase().includes(query) + ) + ).repositories + ); + if (rows.length < 100) break; + } + return githubRepositoryResults(matches); + } + case "repositoryBranches": { + const rows: unknown = JSON.parse( + await this.run( + [ + "api", + ...hostArgs, + `repos/${operation.owner}/${operation.repo}/branches?per_page=100`, + "--jq", + "[.[].name]", + ], + signal + ) ); + if (!Array.isArray(rows)) + throw new Error("Invalid GitHub branch list."); + return { branches: rows.filter(validBranch) }; } case "pullRequestDetails": return this.evidence.details(operation, signal); diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index e8dc216e8..66bf82d23 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -1033,6 +1033,7 @@ export async function runRemoteRunner(filename: string) { engineManagement: true, engineCapabilities: true, githubManagement: true, + repositoryPicker: true, pullRequestStatus: true, pullRequestWatch: true, pullRequestEvidence: true, diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 572fbb57e..7133c365d 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -47,6 +47,7 @@ import { isGitHubPullRequestDiff, githubPullRequestHead, githubRepositoryResults, + validBranch, type SessionOperation, type LaunchProgress, parseLaunchProgress, @@ -115,6 +116,7 @@ export type RunnerSummary = { engineManagement: boolean; engineCapabilities?: true; githubManagement: boolean; + repositoryPicker?: boolean; /** Last pushed snapshot while online; absent offline or before the first push. */ engines?: EngineInventoryEntry[]; workspaces: string[]; @@ -160,6 +162,7 @@ type Peer = { /** Advertised in `ready`; whether this peer answers the `"engine"` command. */ engineManagement: boolean; githubManagement: boolean; + repositoryPicker?: boolean; pullRequestStatus: boolean; pullRequestWatch: boolean; pullRequestEvidence: boolean; @@ -698,6 +701,7 @@ export class RemoteRunnerService { pullRequestStatus: ready.pullRequestStatus === true, pullRequestWatch: ready.pullRequestWatch === true, pullRequestEvidence: ready.pullRequestEvidence === true, + repositoryPicker: ready.repositoryPicker === true, githubManagement: ready.githubManagement === true, checkoutViews: ready.checkoutViews === true, sessionCheckout: ready.sessionCheckout === true, @@ -943,6 +947,8 @@ export class RemoteRunnerService { peer?.gate.approved() === true && peer.engineManagement, ...(peer?.gate.approved() && peer.engineCapabilities && { engineCapabilities: true as const }), + ...(peer?.gate.approved() && + peer.repositoryPicker && { repositoryPicker: true }), githubManagement: peer?.gate.approved() === true && peer.githubManagement, ...(peer?.engines ? { engines: peer.engines } : {}), @@ -983,6 +989,7 @@ export class RemoteRunnerService { engineManagement: online && peer.engineManagement, ...(online && peer.engineCapabilities && { engineCapabilities: true as const }), + ...(online && peer.repositoryPicker && { repositoryPicker: true }), githubManagement: online && peer.githubManagement, ...(online && peer.engines ? { engines: peer.engines } : {}), ...(online && peer.health @@ -1321,6 +1328,17 @@ export class RemoteRunnerService { ); } + if ( + operation.kind === "github" && + (operation.operation.type === "repositorySearch" || + operation.operation.type === "repositoryBranches") && + !peer.repositoryPicker + ) { + throw new RunnerCapabilityUnavailable( + "Update the runner to browse your repositories." + ); + } + // V1 requires a routable workspace and an id even for a runner-wide operation. for (const workspace of peer.workspaces) { if (peer.gate.allows(workspace)) { @@ -1391,6 +1409,24 @@ export class RemoteRunnerService { } } + async listGitHubBranches(runnerId: string, owner: string, repo: string) { + const response = await this.requestGitHub(runnerId, { + type: "repositoryBranches", + owner, + repo, + }); + if ( + !response || + typeof response !== "object" || + !("branches" in response) || + !Array.isArray(response.branches) || + !response.branches.every(validBranch) + ) { + throw new Error("Invalid GitHub branches reply."); + } + return { branches: response.branches }; + } + async searchGitHubRepositories(runnerId: string, query: string) { const response = await this.requestGitHub(runnerId, { type: "repositorySearch", diff --git a/apps/server/src/routes/runner-repositories.ts b/apps/server/src/routes/runner-repositories.ts index 8f33b6d7d..8fdd31e71 100644 --- a/apps/server/src/routes/runner-repositories.ts +++ b/apps/server/src/routes/runner-repositories.ts @@ -9,7 +9,9 @@ export function registerRunnerRepositorySearch( app: FastifyInstance, runners: Pick< RemoteRunnerService, - "searchGitHubRepositories" | "lookupGitHubPullRequestHead" + | "searchGitHubRepositories" + | "lookupGitHubPullRequestHead" + | "listGitHubBranches" > ) { const options = { config: { validateSuppliedAuthorization: true } } as const; @@ -33,6 +35,23 @@ export function registerRunnerRepositorySearch( } } ); + app.get<{ Params: { id: string; owner: string; repo: string } }>( + "/api/v1/runners/:id/repositories/:owner/:repo/branches", + options, + async (req, reply) => { + reply.header("Cache-Control", "no-store"); + const { id, owner, repo } = req.params; + if (!validGitHubRepoPart(owner) || !validGitHubRepoPart(repo)) + return reply.code(400).send({ error: "Invalid repository." }); + try { + return await runners.listGitHubBranches(id, owner, repo); + } catch { + return reply + .code(503) + .send({ error: "Couldn’t load branches from this runner." }); + } + } + ); app.get<{ Params: { id: string }; Querystring: { url?: string } }>( "/api/v1/runners/:id/pull-request-head", options, diff --git a/apps/server/test/engine-wire.test.ts b/apps/server/test/engine-wire.test.ts index 149d35302..4249f0810 100644 --- a/apps/server/test/engine-wire.test.ts +++ b/apps/server/test/engine-wire.test.ts @@ -84,7 +84,10 @@ function dialEngineRunner(input: { version: 1, health: true, ...(input.engineManagement !== false ? { engineManagement: true } : {}), - ...(input.onGitHub && { githubManagement: true }), + ...(input.onGitHub && { + githubManagement: true, + repositoryPicker: true, + }), workspaces: input.workspaces, }); resolve({ diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts index d3400a55b..2eb73a606 100644 --- a/apps/server/test/github-runner-executor.test.ts +++ b/apps/server/test/github-runner-executor.test.ts @@ -100,11 +100,11 @@ case "$1 $2" in 'api --hostname') test "$3" = 'github.com' case "$4" in - search/repositories) - test "$5 $6 $7 $8 $9" = "--method GET -f q=org/project in:name -f" + user/repos) + test "$5 $6 $7 $8 $9" = "--method GET -f affiliation=owner,collaborator,organization_member -f" test "$GH_HOST" = 'github.com' test -f login - printf '%s' '[{"fullName":"org/project","url":"https://github.com/org/project"},{"fullName":"ignored/secret","url":"https://synthetic-token@github.com/org/project"}]' + printf '%s' '[{"name":"org/project","url":"https://github.com/org/project"},{"name":"unrelated/other","url":"https://github.com/unrelated/other"},{"name":"org/project-secret","url":"https://synthetic-token@github.com/org/project"}]' ;; user) if [ -f revoked ]; then printf '(HTTP 401)\n' >&2; exit 1; fi; cat login ;; repos/org/project/pulls/42) diff --git a/apps/server/test/runner-repositories.test.ts b/apps/server/test/runner-repositories.test.ts index c6b244640..ca2eb8afe 100644 --- a/apps/server/test/runner-repositories.test.ts +++ b/apps/server/test/runner-repositories.test.ts @@ -12,6 +12,7 @@ describe("runner repository selection", () => { }); const search = vi.fn().mockRejectedValue(new Error("secret from upstream")); registerRunnerRepositorySearch(app, { + listGitHubBranches: vi.fn(), lookupGitHubPullRequestHead: lookup, searchGitHubRepositories: search, }); diff --git a/apps/web/src/components/app/agent-engine-fields.tsx b/apps/web/src/components/app/agent-engine-fields.tsx index e7b7de5bd..12c01f3da 100644 --- a/apps/web/src/components/app/agent-engine-fields.tsx +++ b/apps/web/src/components/app/agent-engine-fields.tsx @@ -27,6 +27,7 @@ type AgentEngineFieldsProps = { idPrefix?: string; /** Runs on a remote runner: this machine's CLI install state is irrelevant. */ remote?: boolean; + statusLine?: string; workloadEffort?: import("@dispatch/shared").AgentConfigChoice[]; }; @@ -51,6 +52,7 @@ export function AgentEngineFields({ onTypeOpenChange, idPrefix, remote = false, + statusLine, workloadEffort, }: AgentEngineFieldsProps): JSX.Element { // Engines whose CLI this machine does not have: pickable, but the picker @@ -68,7 +70,7 @@ export function AgentEngineFields({ ), [engines] ); - const engineLine = remote ? null : engineSummary(engines, agentType); + const engineLine = remote ? statusLine : engineSummary(engines, agentType); const showModelSelect = catalogDefault !== undefined || modelLoading || modelOptions.length > 0; @@ -112,10 +114,10 @@ export function AgentEngineFields({ /> ) : null} - {engineLine ? ( + {engineLine || statusLine !== undefined ? (

    {engineLine} diff --git a/apps/web/src/components/app/branch-select.tsx b/apps/web/src/components/app/branch-select.tsx index 807ed1e29..fa0df9336 100644 --- a/apps/web/src/components/app/branch-select.tsx +++ b/apps/web/src/components/app/branch-select.tsx @@ -18,6 +18,8 @@ import { cn } from "@/lib/utils"; export type BranchSelectProps = { cwd: string; + runner?: { id: string; repository: string; browse: boolean }; + allowPullRequest?: boolean; baseBranch: string; /** * Fired when the user picks a branch. The component never overwrites @@ -42,6 +44,8 @@ export type BranchSelectProps = { export function BranchSelect({ cwd, + runner, + allowPullRequest = false, baseBranch, onBaseBranchChange, worktreeBranch, @@ -53,6 +57,19 @@ export function BranchSelect({ showNewBranchInput = true, disabled = false, }: BranchSelectProps): JSX.Element { + const [typed, setTyped] = useState(""); + const githubRepo = + runner?.browse && + /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec( + runner.repository + ); + const endpoint = runner + ? githubRepo + ? `/api/v1/runners/${encodeURIComponent(runner.id)}/repositories/${githubRepo[1]}/${githubRepo[2]}/branches` + : "" + : cwd.trim() + ? `/api/v1/git/branches?cwd=${encodeURIComponent(cwd.trim())}` + : ""; const [dropdownOpen, setDropdownOpen] = useState(false); const [remoteBranches, setRemoteBranches] = useState([]); const [branchesLoading, setBranchesLoading] = useState(false); @@ -66,14 +83,11 @@ export function BranchSelect({ useClickOutside(cmdRef, dropdownOpen, closeDropdown); const fetchBranches = useCallback(async () => { - const trimmed = cwd.trim(); - if (!trimmed || disabled) return; + if (!endpoint || disabled) return; setBranchesLoading(true); setFetchError(null); try { - const result = await api<{ branches: string[] }>( - `/api/v1/git/branches?cwd=${encodeURIComponent(trimmed)}` - ); + const result = await api<{ branches: string[] }>(endpoint); setRemoteBranches(result.branches); } catch (error) { setRemoteBranches([]); @@ -82,31 +96,34 @@ export function BranchSelect({ ); } finally { setBranchesLoading(false); - setFetchedForCwd(trimmed); + setFetchedForCwd(endpoint); } - }, [cwd, disabled]); + }, [endpoint, disabled]); const openDropdown = useCallback(() => { if (disabled) return; + setTyped(""); setDropdownOpen(true); - if (fetchedForCwd !== cwd.trim()) { + if (fetchedForCwd !== endpoint) { void fetchBranches(); } requestAnimationFrame(() => inputRef.current?.focus()); - }, [disabled, fetchBranches, fetchedForCwd, cwd, setDropdownOpen]); + }, [disabled, fetchBranches, fetchedForCwd, endpoint, setDropdownOpen]); // Keep the saved baseBranch selectable even if the fetched list doesn't // include it (branch renamed/deleted upstream). We flag it visually in // the dropdown rather than silently overwrite it. const allBranches = useMemo(() => { - const base = remoteBranches.includes("main") - ? remoteBranches - : ["main", ...remoteBranches]; + const base = + runner || remoteBranches.includes("main") + ? remoteBranches + : ["main", ...remoteBranches]; if (baseBranch && !base.includes(baseBranch)) return [baseBranch, ...base]; return base; - }, [remoteBranches, baseBranch]); + }, [remoteBranches, baseBranch, runner]); const savedBranchMissing = + !runner && !branchesLoading && !!baseBranch && !!fetchedForCwd && @@ -125,6 +142,7 @@ export function BranchSelect({ role="combobox" tabIndex={0} disabled={disabled} + aria-label={baseBranchLabel} aria-expanded={dropdownOpen} data-testid={`${testIdPrefix}-base-branch`} onClick={() => @@ -142,7 +160,12 @@ export function BranchSelect({ disabled && "cursor-not-allowed opacity-60" )} > - {baseBranch} + + {baseBranch || + (allowPullRequest + ? "Choose a branch or PR" + : "Repository default")} + {branchesLoading ? ( ) : ( @@ -167,7 +190,15 @@ export function BranchSelect({ > @@ -181,8 +212,35 @@ export function BranchSelect({ ) : null} No matching branches. + {runner && !allowPullRequest && ( + { + onBaseBranchChange(""); + closeDropdown(); + triggerRef.current?.focus(); + }} + > + Repository default + + )} + {runner && + typed.trim() && + !allBranches.includes(typed.trim()) && ( + { + onBaseBranchChange(typed.trim()); + closeDropdown(); + triggerRef.current?.focus(); + }} + > + Use {typed.trim()} + + )} {allBranches.map((branch) => { const isMissing = + !runner && branch === baseBranch && remoteBranches.length > 0 && !remoteBranches.includes(branch); diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index 6f139bde9..dba430712 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -1,5 +1,4 @@ import { RunnerProjectPicker } from "./runner-project-picker"; -import { RunnerRepositoryFields } from "./runner-repository-fields"; import { taskAgentName } from "@dispatch/shared"; import { ProjectLocation } from "./project-location"; import { useProjectScope, useProjects } from "@/hooks/use-projects"; @@ -13,7 +12,10 @@ import { AgentEngineFields } from "@/components/app/agent-engine-fields"; import { ContextPicker } from "@/components/app/context-picker"; import { CONTEXT_PROMPT_ID } from "@/components/app/create-agent-dialog-utils"; import { WorktreeSection } from "@/components/app/create-agent-worktree-section"; -import { RunnerPicker } from "@/components/app/runner-picker"; +import { + RunnerPicker, + RunnerWorkspacePicker, +} from "@/components/app/runner-picker"; import { PathInput } from "@/components/app/path-input"; import { useCreateAgentForm } from "@/components/app/use-create-agent-form"; import { ActivityBars } from "@/components/ui/activity-bars"; @@ -92,6 +94,7 @@ function CreateAgentDialogContent({ return ( void form.handleSubmit(event)} > -

    +
    - {(form.runnerEngineBlocked || - form.workloadCatalogUnavailable) && ( -

    - {form.runnerEngineBlocked - ? "Install and sign in to this agent on the runner before creating a session." - : "Model choices are unavailable. The agent will use its configured model."} -

    - )} -
    diff --git a/apps/web/src/components/app/runner-picker.tsx b/apps/web/src/components/app/runner-picker.tsx index c9c9351e9..1a4ecd15e 100644 --- a/apps/web/src/components/app/runner-picker.tsx +++ b/apps/web/src/components/app/runner-picker.tsx @@ -16,22 +16,16 @@ export function RunnerPicker({ runners, runnerId, onRunnerChange, - workspace, - onWorkspaceChange, unavailable, }: { runners: Runner[]; runnerId: string | null; onRunnerChange: (id: string | null) => void; - workspace: string | null; - onWorkspaceChange: (workspace: string) => void; unavailable: boolean; }): JSX.Element | null { const runnerLabelId = useId(); - const workspaceLabelId = useId(); const usable = runners.filter((r) => r.status !== "revoked"); if (usable.length === 0 && !runnerId) return null; - const selected = usable.find((r) => r.id === runnerId); return (
    @@ -82,42 +76,51 @@ export function RunnerPicker({ to continue.

    ) : null} - {selected && !unavailable && !selected.managedWorkspace ? ( -
    -
    ); } diff --git a/apps/web/src/components/app/runner-project-picker.tsx b/apps/web/src/components/app/runner-project-picker.tsx index 459939cc8..97fc7d901 100644 --- a/apps/web/src/components/app/runner-project-picker.tsx +++ b/apps/web/src/components/app/runner-project-picker.tsx @@ -19,11 +19,12 @@ import { import { useProjects } from "@/hooks/use-projects"; import { api } from "@/lib/api"; import { ProjectIcon } from "./project-location"; -import { isRepositoryUrl } from "./runner-repository-fields"; +import { parseRunnerRepositoryUrl } from "@dispatch/runner-protocol"; export function RunnerProjectPicker({ runnerId, canSearch, + updateNeeded, projectId, repository, onProject, @@ -31,6 +32,7 @@ export function RunnerProjectPicker({ }: { runnerId: string; canSearch: boolean; + updateNeeded: boolean; projectId: string | null; repository: string; onProject: (id: string | null) => void; @@ -45,7 +47,7 @@ export function RunnerProjectPicker({ const project = projects.find((item) => item.id === projectId); const text = input.trim(); const urlInput = /^(?:\w+:\/\/|git@)/i.test(text); - const validUrl = isRepositoryUrl(text); + const validUrl = Boolean(parseRunnerRepositoryUrl(text)); const searchGitHub = open && canSearch && !urlInput && validRepositorySearch(text); useEffect(() => { @@ -121,12 +123,17 @@ export function RunnerProjectPicker({ aria-label="Search projects or repositories" placeholder={ canSearch - ? "Search projects or GitHub, or paste a URL" + ? "Search projects or your repos, or paste a URL" : "Search projects or paste an HTTPS URL" } value={input} onValueChange={setInput} /> + {updateNeeded && ( +

    + Update this runner to search your GitHub repositories. +

    + )} {projectMatches.length > 0 && ( @@ -146,7 +153,7 @@ export function RunnerProjectPicker({ )} {repositories.length > 0 && ( - + {repositories.map((item) => ( void; - branch: string; - onBranch: (branch: string) => void; -}) { - const id = useId(); - return ( -
    -
    - - -
    - -

    - Archiving removes the session worktree. Commit and push changes you want - to keep. -

    -
    - ); -} diff --git a/apps/web/src/components/app/use-create-agent-form.test.tsx b/apps/web/src/components/app/use-create-agent-form.test.tsx index 62a38b224..53ed9e5be 100644 --- a/apps/web/src/components/app/use-create-agent-form.test.tsx +++ b/apps/web/src/components/app/use-create-agent-form.test.tsx @@ -244,10 +244,19 @@ describe("launch location preference", () => { }, }, }); + apiMock.mockClear(); + act(() => result.current.setRunnerNewBranch("feature/custom")); + await act(async () => result.current.handleSubmit(submitEvent())); + expect(agentsPostJson()).toMatchObject({ + repository: { + checkout: { kind: "new", base: "release", branch: "feature/custom" }, + }, + }); + apiMock.mockClear(); act(() => { result.current.chooseRepo("https://github.com/org/standalone"); - result.current.changeBranchMode("existing"); + result.current.setBranchMode("existing"); result.current.setRunnerBranch("feature"); }); await act(async () => result.current.handleSubmit(submitEvent())); diff --git a/apps/web/src/components/app/use-create-agent-form.ts b/apps/web/src/components/app/use-create-agent-form.ts index e2ddaee6d..1ba745cd1 100644 --- a/apps/web/src/components/app/use-create-agent-form.ts +++ b/apps/web/src/components/app/use-create-agent-form.ts @@ -6,13 +6,12 @@ import { isLocalFolder } from "./path-input-utils"; import { createClientId } from "@/lib/client-id"; import { MANAGED_WORKSPACE, + parseRunnerRepositoryUrl, + validBranch, type GitHubStatus, } from "@dispatch/runner-protocol"; import { useQuery } from "@tanstack/react-query"; -import { - isRepositoryUrl, - type RunnerBranchMode, -} from "./runner-repository-fields"; + import type { Effort } from "@dispatch/shared"; import { useAtom } from "jotai"; import { useProjects } from "@/hooks/use-projects"; @@ -104,6 +103,7 @@ export function useCreateAgentForm({ setCreateEffort(null); setChosenRepo(null); setRunnerProjectId(undefined); + setRunnerNewBranch(""); setRunnerBranch(""); setBranchMode("new"); setRunnerId(id); @@ -145,20 +145,18 @@ export function useCreateAgentForm({ retry: false, }); const [chosenRepo, setChosenRepo] = useState(null); - const [branchMode, setBranchMode] = useState("new"); + const [branchMode, setBranchMode] = useState<"new" | "existing">("new"); + const [runnerNewBranch, setRunnerNewBranch] = useState(""); const [runnerBranch, setRunnerBranch] = useState(""); const repository = chosenRepo ?? projectRepository.data?.url ?? ""; const chooseRepo = (url: string) => { - if (task || !isRepositoryUrl(url)) return; + if (task || !parseRunnerRepositoryUrl(url)) return; setRunnerProjectId(null); setChosenRepo(url); + setRunnerNewBranch(""); setRunnerBranch(""); setBranchMode("new"); }; - const changeBranchMode = (mode: RunnerBranchMode) => { - setBranchMode(mode); - setRunnerBranch(""); - }; const repoStatus = !managedSession || !selectedProjectId ? null @@ -170,18 +168,26 @@ export function useCreateAgentForm({ ? "This project is unavailable." : !repository && task ? null - : !isRepositoryUrl(repository) + : !parseRunnerRepositoryUrl(repository) ? "This project has no supported HTTPS repository linked." : null; const repoReady = !managedSession || (!repoStatus && - (!repository || branchMode === "new" || Boolean(runnerBranch.trim()))); + (!repository || + (branchMode === "new" + ? (!runnerBranch || validBranch(runnerBranch.trim())) && + (!runnerNewBranch.trim() || validBranch(runnerNewBranch.trim())) + : validBranch(runnerBranch.trim()) || + /^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/[1-9]\d*\/?$/.test( + runnerBranch.trim() + )))); const setCreateProjectId = (id: string | null) => { if (managedSession) { setRunnerProjectId(id); setChosenRepo(null); setBranchMode("new"); + setRunnerNewBranch(""); setRunnerBranch(""); return; } @@ -299,15 +305,12 @@ export function useCreateAgentForm({ }); const catalog = useRunnerModelCatalog(runnerId, createType, online); - const currentCatalog = - online && !catalog.isError && !catalog.isFetching - ? catalog.data - : undefined; + const currentCatalog = online && !catalog.isError ? catalog.data : undefined; const modelOptions = useMemo( () => (remote ? (currentCatalog?.models ?? []) : nativeOptions), [remote, currentCatalog, nativeOptions] ); - const modelCatalogLoading = remote ? catalog.isFetching : nativeLoading; + const modelCatalogLoading = remote ? catalog.isLoading : nativeLoading; const reportedDefault = remote ? currentCatalog?.defaultModel : nativeDefault; const defaultModel = modelOptions.some( (option) => option.id === reportedDefault @@ -328,7 +331,7 @@ export function useCreateAgentForm({ ); const effortCatalog = selectedModel && selectedModel !== currentCatalog?.defaultModel - ? !selectedEffortCatalog.isFetching && !selectedEffortCatalog.isError + ? !selectedEffortCatalog.isError ? selectedEffortCatalog.data : undefined : currentCatalog; @@ -480,7 +483,7 @@ export function useCreateAgentForm({ url: repository.trim(), checkout: { kind: "new", - branch: `session/${createClientId()}`, + branch: runnerNewBranch.trim() || `session/${createClientId()}`, base: branch || undefined, }, }; @@ -598,6 +601,7 @@ export function useCreateAgentForm({ repository, branchMode, runnerBranch, + runnerNewBranch, locationReady, runnerEngineBlocked, createCwd, @@ -639,7 +643,10 @@ export function useCreateAgentForm({ repository, chooseRepo, branchMode, - changeBranchMode, + setBranchMode, + runnerNewBranch, + setRunnerNewBranch, + runner, runnerBranch, setRunnerBranch, repoStatus, diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index 063adaa12..b109dad52 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -14,6 +14,7 @@ export type Runner = { engineManagement?: true; engineCapabilities?: true; githubManagement?: boolean; + repositoryPicker?: boolean; health?: RunnerHealth; healthReceivedAt?: string; }; diff --git a/e2e/remote-runner/fixture-gh.sh b/e2e/remote-runner/fixture-gh.sh index 3da9b1502..7ab4c788b 100644 --- a/e2e/remote-runner/fixture-gh.sh +++ b/e2e/remote-runner/fixture-gh.sh @@ -41,10 +41,11 @@ case "$1 ${2:-}" in 'api user'|'api --hostname') test -s "$key" case " $* " in + *'/branches?per_page=100'*) printf '%s' '["main","review-topic"]' ;; *'/pulls/'*) printf '{"url":"https://github.com/%s/private.git","branch":"review-topic"}\n' "$login" ;; - *' search/repositories '*) + *' user/repos '*) test -s "$key" - printf '[{"fullName":"%s/private","url":"https://github.com/%s/private"}]\n' "$login" "$login" + printf '[{"name":"%s/private","url":"https://github.com/%s/private"}]\n' "$login" "$login" ;; *' user '*) printf '%s\n' "$login" ;; *) exit 1 ;; diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index 944332791..c5ada6a9c 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -310,15 +310,17 @@ export async function launchViaUi( .getByRole("option", { name: opts.repository, exact: true }) .click(); if (opts.pullRequest) { + await page.getByTestId("create-agent-new-branch").click(); + await page.getByTestId("create-agent-base-branch").click(); await page - .getByRole("combobox", { name: "Branch", exact: true }) - .click(); + .getByPlaceholder("Branch name or GitHub PR URL") + .fill(opts.pullRequest); await page - .getByRole("option", { name: "Use an existing branch or PR" }) + .getByRole("option", { + name: `Use ${opts.pullRequest}`, + exact: true, + }) .click(); - await page - .getByLabel("Branch or pull request") - .fill(opts.pullRequest); } } } else { diff --git a/packages/runner-protocol/src/execution.ts b/packages/runner-protocol/src/execution.ts index fae14004a..1ee6e918c 100644 --- a/packages/runner-protocol/src/execution.ts +++ b/packages/runner-protocol/src/execution.ts @@ -106,6 +106,7 @@ export type ReadyFrame = { engineManagement?: true; engineCapabilities?: true; githubManagement?: true; + repositoryPicker?: true; pullRequestStatus?: true; pullRequestWatch?: true; pullRequestEvidence?: true; @@ -159,6 +160,7 @@ export function parseReadyFrame(value: unknown): ReadyFrame | null { ...(frame.pullRequestEvidence === true && { pullRequestEvidence: true }), ...(frame.pullRequestWatch === true && { pullRequestWatch: true }), ...(frame.pullRequestStatus === true && { pullRequestStatus: true }), + ...(frame.repositoryPicker === true && { repositoryPicker: true }), ...(frame.githubManagement === true && { githubManagement: true }), ...(frame.managedWorkspace === true && { managedWorkspace: true }), }; diff --git a/packages/runner-protocol/src/github.ts b/packages/runner-protocol/src/github.ts index 9efbe5892..57fd67f41 100644 --- a/packages/runner-protocol/src/github.ts +++ b/packages/runner-protocol/src/github.ts @@ -51,6 +51,7 @@ export type GitHubOperation = | { type: "watchPullRequests"; targets: GitHubPullRequestTarget[] } | { type: "status" | "login" | "cancel" | "logout" } | { type: "repositorySearch"; query: string } + | { type: "repositoryBranches"; owner: string; repo: string } | (GitHubPullRequestTarget & ( | { type: "pullRequestHead" | "pullRequestDetails" } @@ -266,6 +267,10 @@ export function isGitHubOperation(value: unknown): value is GitHubOperation { value.targets.length <= MAX_PULL_REQUEST_WATCH_TARGETS && value.targets.every(isGitHubPullRequestTarget) ); + case "repositoryBranches": + return ( + validGitHubRepoPart(value.owner) && validGitHubRepoPart(value.repo) + ); case "repositorySearch": return validRepositorySearch(value.query); case "pullRequestStatus": From 94c8b3a8b60168ee036142274c598e0bea5c2ff4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 22:39:37 -0700 Subject: [PATCH 167/642] Preserve the compact Create Agent layout for local-only setups --- apps/web/src/components/app/create-agent-dialog.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index dba430712..96e3dc980 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -90,11 +90,16 @@ function CreateAgentDialogContent({ onCreated, }); + const hasRunnerChoice = form.runners.some( + (runner) => runner.status !== "revoked" + ); useRadixPopoverZFix(); return ( From fed8ed46c8f2afa55286c76500949773c1c7e27d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Thu, 19 Nov 2026 22:42:53 -0700 Subject: [PATCH 168/642] Allow touch and wheel scrolling in Create Agent repository results --- apps/web/src/components/app/runner-project-picker.tsx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/app/runner-project-picker.tsx b/apps/web/src/components/app/runner-project-picker.tsx index 97fc7d901..e8485638e 100644 --- a/apps/web/src/components/app/runner-project-picker.tsx +++ b/apps/web/src/components/app/runner-project-picker.tsx @@ -76,6 +76,8 @@ export function RunnerProjectPicker({ setOpen(next); setInput(""); }; + // Keep the results inside the dialog's scroll lock and clipping boundary. + const dialog = trigger.current?.closest('[role="dialog"]'); const hasSelection = Boolean(projectId || repository); return ( @@ -111,13 +113,15 @@ export function RunnerProjectPicker({ )} - + {projectMatches.length > 0 && ( {projectMatches.map((item) => ( From 73a13fe95e9638968bb5da61577f329cbb0137b7 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 08:05:56 -0700 Subject: [PATCH 169/642] Preserve open idle sessions through runner updates and rollback --- bin/install-dispatch-runner.sh | 102 +++++++++++++++++++----- bin/runner-handoff-v1.py | 77 ++++++++++++++++++ docs/remote-runner-linux.md | 28 ++++--- scripts/remote-runner/test-installer.sh | 25 +++++- 4 files changed, 193 insertions(+), 39 deletions(-) create mode 100644 bin/runner-handoff-v1.py diff --git a/bin/install-dispatch-runner.sh b/bin/install-dispatch-runner.sh index e2f646de2..4b392f8ad 100755 --- a/bin/install-dispatch-runner.sh +++ b/bin/install-dispatch-runner.sh @@ -13,7 +13,7 @@ Usage: Run as root on Linux with systemd and unified cgroup v2. Install verifies the release and prepares the runner for the connect command. -Update exits 75 if the runner has workload processes. Retry when idle. +Update preserves idle sessions on compatible runners. Exit 75 means retry after the reported activity finishes. Recover restores the previous binary after an interrupted update. USAGE } @@ -47,6 +47,10 @@ stable_start() { start_enabled_runner() { local enabled + if [[ -f "$runtime/previous" && -f "$runtime/previous-active" ]]; then + stable_start + return + fi enabled=$(systemctl is-enabled "$unit") || { [[ "$enabled" == disabled ]] && return 0 return 1 @@ -170,7 +174,7 @@ install_runner() { } defer() { - printf 'Runner update deferred. Retry when the runner has no active sessions.\n' >&2 + printf 'Runner update deferred: %s.\n' "${1:-could not verify the service is ready for an update}" >&2 exit 75 } @@ -181,17 +185,54 @@ thaw() { fi } +# A verified target opts into the v1 host-binding format by shipping the +# checker. Keep a copy with the rollback record for interrupted maintenance. +preserves_session_processes() { + local mode stop post + mode=$(systemctl show -p KillMode --value "$unit") && + stop=$(systemctl show -p ExecStop --value "$unit") && + post=$(systemctl show -p ExecStopPost --value "$unit") && + [[ "$mode" == process && -z "$stop" && -z "$post" ]] +} + +check_session_handoff() { + local pids=$1 main_pid=$2 + [[ -s "$stage/handoff.py" ]] || defer "target release cannot reattach open sessions" + preserves_session_processes || + defer "the service stop policy cannot preserve open sessions" + command -v python3 >/dev/null || defer "python3 is needed to verify open sessions" + python3 -I "$stage/handoff.py" "$config" "$pids" "$main_pid" || + defer "retry after the reported activity finishes" +} + +record_previous() { + install -m 0600 "$stage/handoff.py" "$runtime/previous-handoff.py" + ln "$runtime/dispatch" "$runtime/previous" + sync -f "$runtime" +} + # Once frozen, the supervisor cannot accept another launch or fork a child # between the process check and delivery of SIGKILL to its main process. -stop_idle_runner() { - local cgroup main_pid process_file contents frozen_line +stop_runner_for_update() { + local before_stop=${1:-:} cgroup main_pid process_file frozen_line if ! systemctl is-active --quiet "$unit"; then + if [[ -f "$runtime/previous" && -s "$runtime/previous-handoff.py" && + "$(systemctl show -p SubState --value "$unit")" == auto-restart* ]] && + preserves_session_processes; then + systemctl stop "$unit" + fi [[ "$(systemctl show -p ActiveState --value "$unit")" =~ ^(inactive|failed)$ ]] || defer cgroup=$(systemctl show -p ControlGroup --value "$unit") if [[ -n "$cgroup" && -d "$cgroup_root$cgroup" ]]; then frozen_line=$(<"$cgroup_root$cgroup/cgroup.events") - [[ $'\n'"$frozen_line"$'\n' == *$'\npopulated 0\n'* ]] || defer + if [[ $'\n'"$frozen_line"$'\n' != *$'\npopulated 0\n'* ]]; then + # KillMode=process leaves the original hosts here when a trial fails. + [[ -f "$runtime/previous" && -s "$stage/handoff.py" ]] || defer + # Already inactive. Leave the processes in place for the restored daemon. + return + fi fi + "$before_stop" systemctl stop "$unit" return fi @@ -204,25 +245,32 @@ stop_idle_runner() { [[ $'\n'"$frozen_line"$'\n' == *$'\nfrozen 1\n'* ]] || defer [[ -r "$cgroup_root$cgroup/cgroup.procs" ]] || defer find "$cgroup_root$cgroup" -name cgroup.procs -print0 > "$stage/process-files" + : > "$stage/service-pids" while IFS= read -r -d '' process_file; do - # cgroup files can report a zero file size despite containing process IDs. - contents=$(<"$process_file") - if [[ "$process_file" == "$cgroup_root$cgroup/cgroup.procs" ]]; then - [[ "$contents" == "$main_pid" ]] || defer - else - [[ -z "$contents" ]] || defer - fi + cat "$process_file" >> "$stage/service-pids" done < "$stage/process-files" - # systemctl stop thaws the unit. Queue the fatal signal before the thaw so - # that the old supervisor gets no chance to dispatch a launch. + grep -Fxq "$main_pid" "$stage/service-pids" || defer + if [[ "$(<"$stage/service-pids")" != "$main_pid" ]]; then + check_session_handoff "$stage/service-pids" "$main_pid" + fi + # Keep the daemon stopped across the thaw. Some systemd releases refuse + # both stop and thaw after a frozen unit's main process has already exited. # Probe the option parser without signaling a unit. Older systemctl uses # --kill-who, and an actual signal failure must abort the update. local target=--kill-whom=main if ! systemctl "$target" --version >/dev/null 2>&1; then target=--kill-who=main fi + if [[ "$before_stop" == record_previous ]]; then + touch "$runtime/previous-active" + fi + "$before_stop" maintenance_step=signal + paused_target=$target + systemctl kill "$target" --signal=SIGSTOP "$unit" + thaw systemctl kill "$target" --signal=SIGKILL "$unit" + paused_target= maintenance_step=stop systemctl stop "$unit" frozen=0 @@ -232,14 +280,19 @@ recover_runner() { # A killed updater may have left its cgroup frozen. systemctl thaw "$unit" 2>/dev/null || true if [[ -f "$runtime/previous" ]]; then - stop_idle_runner + if [[ -s "$runtime/previous-handoff.py" ]]; then + cp "$runtime/previous-handoff.py" "$stage/handoff.py" + fi + stop_runner_for_update # Keep the recovery record until the restored service passes startup. - ln "$runtime/previous" "$stage/restore" - mv -fT "$stage/restore" "$runtime/dispatch" + if [[ ! "$runtime/previous" -ef "$runtime/dispatch" ]]; then + ln "$runtime/previous" "$stage/restore" + mv -fT "$stage/restore" "$runtime/dispatch" + fi sync -f "$runtime" fi start_enabled_runner || error "Runner recovery could not start. See journalctl -u $unit" - rm -f -- "$runtime/previous" + rm -f -- "$runtime/previous" "$runtime/previous-handoff.py" "$runtime/previous-active" sync -f "$runtime" } @@ -258,6 +311,9 @@ update_runner() { fi maintenance_step=stage stage_release + if ! tar -xOzf "$stage/dispatch-server.tar.gz" bin/runner-handoff-v1.py > "$stage/handoff.py" 2>/dev/null; then + : > "$stage/handoff.py" + fi if cmp -s "$stage/dispatch" "$runtime/dispatch"; then maintenance_step=unit install_service_unit @@ -270,10 +326,9 @@ update_runner() { # Create the record only after the idle check, so a deferred update leaves # no transaction to recover. maintenance_step=stop - stop_idle_runner + rm -f -- "$runtime/previous-active" + stop_runner_for_update record_previous maintenance_step=replace - ln "$runtime/dispatch" "$runtime/previous" - sync -f "$runtime" mv -fT "$stage/next" "$runtime/dispatch" sync -f "$runtime" maintenance_step=start @@ -283,7 +338,7 @@ update_runner() { maintenance_step=start error "New runner failed to start. Restored the previous release" fi - rm -f -- "$runtime/previous" + rm -f -- "$runtime/previous" "$runtime/previous-handoff.py" "$runtime/previous-active" sync -f "$runtime" maintenance_step=unit install_service_unit @@ -294,6 +349,9 @@ update_runner() { cleanup() { local status=$? thaw || printf 'Could not thaw %s. Run the recovery command.\n' "$unit" >&2 + if [[ -n "${paused_target:-}" ]]; then + systemctl kill "$paused_target" --signal=SIGCONT "$unit" || : + fi if [[ "${action:-}" == update || "${action:-}" == recover ]]; then if [[ "$status" == 0 ]]; then rm -f -- "$runtime/last-maintenance-failure.json" || : diff --git a/bin/runner-handoff-v1.py b/bin/runner-handoff-v1.py new file mode 100644 index 000000000..7b76dc258 --- /dev/null +++ b/bin/runner-handoff-v1.py @@ -0,0 +1,77 @@ +"""Validate frozen Linux runner processes against the supervisor's v1 bindings.""" +import json +import os +import re +import stat +import sys +from pathlib import Path + + +def require(condition, reason): + if not condition: + raise ValueError(reason) + + +def check(config_file, pid_file, main_pid): + config = json.loads(Path(config_file).read_text()) + state = Path(config["state"]) + bindings = state / "bindings" + for directory in (state, bindings, state / "hosts"): + meta = directory.lstat() + require(stat.S_ISDIR(meta.st_mode) and meta.st_uid == 0 and + not meta.st_mode & 0o022, "untrusted runner state directory") + scope = (Path("/proc/sys/kernel/random/boot_id").read_text().strip() + + ":" + os.readlink("/proc/self/ns/pid")) + processes = {} + for value in Path(pid_file).read_text().split(): + pid = int(value) + if pid == main_pid: + continue + fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() + parent = int(fields[1]) + # The checkout watcher exits on stdin EOF and Dispatch re-subscribes. + if parent == main_pid: + args = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0") + if (len(args) == 4 and args[1] == b"runner-watch-checkout" and + os.path.samefile(f"/proc/{pid}/exe", f"/proc/{main_pid}/exe")): + continue + processes[pid] = (parent, int(fields[3]), fields[19]) + hosts = set() + for record in bindings.glob("*.host"): + if not re.fullmatch(r"(agt_[a-z0-9]+|opaque-[A-Za-z0-9_-]{43})", record.stem): + continue + meta = record.lstat() + require(stat.S_ISREG(meta.st_mode) and meta.st_uid == 0 and + not meta.st_mode & 0o022, "untrusted runner host record") + identity = json.loads(record.read_text()) + pid = identity["pid"] + if pid not in processes: + continue + _, sid, start = processes[pid] + require(sid == pid and start == identity["start"] and identity["scope"] == scope + and re.fullmatch(r"DISPATCH_OWNED_[0-9a-f]{32}=1", identity["marker"]), + "session process identity changed") + host = state / "hosts" / record.stem + require(stat.S_ISDIR(host.lstat().st_mode), "session directory unavailable") + socket = (host / "host.sock").lstat() + require(stat.S_ISSOCK(socket.st_mode) and socket.st_uid == config["uid"], + "session has not finished starting") + require(not os.path.lexists(host / "turn-active"), "an agent is working") + hosts.add(pid) + for pid in processes: + ancestor = pid + while ancestor in processes and ancestor not in hosts: + parent, sid, _ = processes[ancestor] + if sid in hosts: + break + ancestor = parent + else: + require(ancestor in hosts, "a runner operation is still in progress") + print(f"Preserving {len(hosts)} open runner session(s).") + + +if __name__ == "__main__": + try: + check(sys.argv[1], sys.argv[2], int(sys.argv[3])) + except (OSError, KeyError, TypeError, ValueError) as exc: + sys.exit(f"Runner handoff deferred: {exc}") diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index d8968c293..528c51a40 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -112,17 +112,19 @@ sudo /opt/dispatch-runner/install-dispatch-runner.sh update --tag vX.Y.Z ``` The updater stages and verifies the complete archive before it makes service -changes. It briefly freezes the service cgroup to check for workload processes -and exits with status 75 if the runner is busy. Retry after the sessions have -ended. On an idle runner it retains the previous executable, atomically -replaces the live executable, and checks that the replacement service survives -startup. The runner's **Online** status in Settings confirms reconnection. If -startup fails, the updater restores the previous executable and starts it. -Updates preserve the enrollment, settings, configured workspace bindings and -managed checkouts. Host recovery starts with sessions launched by a -restart-aware supervisor. For a manual upgrade from an older runner, stop -its sessions with the old supervisor before replacing it. Updating before -connect keeps the service stopped. +changes. On the managed systemd unit, compatible updates keep open, idle agents +running and restart the supervisor. Dispatch reconnects to the existing host +processes. You can continue the same conversation in its checkout. +The updater briefly freezes the service and checks the recorded Linux process +identities. It uses Python 3 for this check when workload processes are present. +An active turn, an unrelated runner operation, an incompatible release, or a +custom stop policy that could terminate agents defers the update with exit 75. +Retry after the reported activity finishes. + +The updater retains the previous executable through startup and restores it +if the replacement fails to start. Settings shows **Online** after reconnection. +Enrollment, settings, workspace bindings, and managed checkouts are retained. +Updating before connecting keeps the service stopped. If an update was interrupted, run: @@ -130,8 +132,8 @@ If an update was interrupted, run: sudo /opt/dispatch-runner/install-dispatch-runner.sh recover ``` -Recovery can also defer while a workload is active. Once idle, it will restore -the previous executable when a replacement is pending, or start the installed +Recovery can also defer while a turn or runner operation is active. It restores +the previous executable when a replacement is pending, or starts the installed executable otherwise. ## Validate installer changes diff --git a/scripts/remote-runner/test-installer.sh b/scripts/remote-runner/test-installer.sh index 8635234c2..4d75cd0c7 100755 --- a/scripts/remote-runner/test-installer.sh +++ b/scripts/remote-runner/test-installer.sh @@ -64,11 +64,14 @@ systemctl() { fi ;; stop) + [[ ! -e "$root/frozen" ]] || return 1 rm -f "$root/running" printf 'populated 0\nfrozen 0\n' > "$cgroup_root/service/cgroup.events" ;; show) case "$3" in + KillMode) if [[ -e "$root/custom-kill" ]]; then echo control-group; else echo process; fi ;; + ExecStop|ExecStopPost|SubState) : ;; ActiveState) printf 'inactive\n' ;; MainPID) printf '101\n' ;; ControlGroup) printf '/service\n' ;; @@ -76,6 +79,7 @@ systemctl() { esac ;; freeze) + : > "$root/frozen" printf 'populated 1\nfrozen 1\n' > "$cgroup_root/service/cgroup.events" printf '%s\n' 101 > "$cgroup_root/service/cgroup.procs" if [[ -e "$root/busy" ]]; then @@ -83,17 +87,24 @@ systemctl() { printf '%s\n' 102 > "$cgroup_root/service/child/cgroup.procs" fi ;; - thaw) rm -rf "$cgroup_root/service/child" ;; + thaw) rm -f "$root/frozen"; rm -rf "$cgroup_root/service/child" ;; --kill-whom=main) [[ "$2" == --version && ! -e "$root/legacy-systemctl" ]];; kill) local target=--kill-whom=main [[ ! -e "$root/legacy-systemctl" ]] || target=--kill-who=main - [[ "$*" == "kill $target --signal=SIGKILL dispatch-runner.service" ]] + [[ "$*" == "kill $target --signal=SIGKILL dispatch-runner.service" || "$*" == "kill $target --signal=SIGSTOP dispatch-runner.service" ]] ;; daemon-reload) ;; *) return 1 ;; esac } +python3() { + # Process identity checks run against real /proc in the Linux VM. Here the + # fixture models an open, recoverable host to exercise the installer gates. + [[ "$1" == -I && "$2" == "$stage/handoff.py" && "$3" == "$config" && + "$5" == 101 && -f "$root/idle-host" ]] && + cmp -s "$2" bin/runner-handoff-v1.py && grep -Fxq 102 "$4" +} getent() { [[ -e "$root/account" ]] || return 2 printf 'dispatch-runner:x:103:104::%s:/usr/sbin/nologin\n' "$state/home" @@ -132,7 +143,7 @@ HARNESS openssl genrsa -out "$root/private.pem" 2048 2>/dev/null openssl rsa -in "$root/private.pem" -pubout -out "$root/public.pem" 2>/dev/null mkdir -p "$root/archive/dist/bun" "$root/archive/bin" -cp bin/{dispatch-runner,dispatch-runner.service,install-dispatch-runner.sh,pack-release} "$root/archive/bin/" +cp bin/{dispatch-runner,dispatch-runner.service,install-dispatch-runner.sh,runner-handoff-v1.py,pack-release} "$root/archive/bin/" touch "$root/archive/README.md" "$root/archive/.env.example" for version in 1.0.0 1.0.1; do release="$root/releases/v$version" @@ -221,7 +232,11 @@ cmp "$root/original" "$root/runtime/dispatch" [[ ! -e "$root/runtime/previous" ]] ! grep -q '^kill ' "$root/systemctl" grep -q '^thaw ' "$root/systemctl" -rm "$root/busy" +# Even a recoverable host must survive the effective unit's stop policy. +touch "$root/idle-host" "$root/custom-kill" +expect_status 75 update v1.0.1 +[[ ! -e "$root/runtime/previous" && ! -e "$root/frozen" ]] +rm "$root/custom-kill" : > "$root/reject-new" expect_status 1 update v1.0.1 arm64 @@ -242,6 +257,8 @@ diff -r "$root/original-settings" "$root/settings" # A recovery record survives an interrupted swap. cp "$root/original" "$root/runtime/previous" +expect_status 75 recover "" +cp bin/runner-handoff-v1.py "$root/runtime/previous-handoff.py" run recover "" cmp "$root/original" "$root/runtime/dispatch" diff -r "$root/original-settings" "$root/settings" From 3f3374c1af7c41f8daaa1277ee9ee67efe04e459 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 08:28:36 -0700 Subject: [PATCH 170/642] Hand off the runner burn-in and outstanding field feedback --- docs/design/runner-burn-in-handoff.md | 34 +++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/design/runner-burn-in-handoff.md diff --git a/docs/design/runner-burn-in-handoff.md b/docs/design/runner-burn-in-handoff.md new file mode 100644 index 000000000..1e1e4bace --- /dev/null +++ b/docs/design/runner-burn-in-handoff.md @@ -0,0 +1,34 @@ +# Dispatch runner burn-in handoff + +Updated 2026-11-20 at 08:27 Mountain. Brad is using the branch on his LAN and has successfully started an agent on Ubuntu. Continue the burn-in from the existing checkout and session data. + +## Start here + +- The integration branch is `agt_6500d94e4ff5/agent-4e4ff5`. The last implementation commit is `73a13fe9`. Work in `/Users/brad/dev/apps/dispatch/.dispatch/worktrees/agt-6500d94e4ff5-agent-4e4ff5`. Eight tracked web files contain unfinished Create Agent edits. They are visible in `git diff` and need to survive the handoff. +- The web instance Brad is using is `http://192.168.1.246:51839/`. The dev-stack suffix belongs to the outgoing session, `agt_6500d94e4ff5`. The repo stop hook invokes `./bin/dispatch-dev down` for the stopping agent. Retire the outgoing lead only after the burn-in stack has an independent lifecycle or Brad has finished using it. A newly launched agent gets its own suffix by default. +- At handoff the live runner API showed `ubu` (`rnr_891ccc555fc8`) online at `1f6e1f1f4fd0`, advertising `repositoryPicker: true`, with one open session and zero working. That resolves the older-binary warning reported earlier. The controller commit and runner binary revision differ intentionally. +- The original 14 runner tasks are accepted and the serial queue is closed. The hourly reminder is complete and the earlier schedule is cancelled. The account setup and picker follow-ups are also Done. Brad asked to retire their builders. The project-wide Conductor is independent. Keep work local to the integration branch. Brad excluded merging into main. + +## First pending work — Create Agent + +Open Brad’s annotated phone screenshot in message `1d8a3460-2d7b-4270-a63e-8693eb2a5bd1`. His complaint is about losing the familiar launch form. He has already approved the placement and interaction model. + +1. Keep the runner selector compact at the top right beside the title. Preserve the dialog geometry, typed name, focus and common controls when switching machines. Keep the shared Agent, Model and Effort row. The inherited fallback reads **Default**. If the catalog reports a named default, retain that existing behavior. +2. For a managed runner, use one optional project or repository picker. Selecting a project supplies its repository. Selecting **No repository** starts in an empty session directory. Remove the separate clear button. Allow account-scoped GitHub search and a validated pasted HTTPS Git URL. Remote users do not select a host folder. Retain the configured-workspace option and the familiar native project/folder flow. +3. Restore normal spacing between the picker, selected URL and worktree fields. Keep the shared searchable starting-branch control and show the actual repository default, including defaults such as trunk. Preserve explicit branch and PR choices. Show an initial loading state for async engines/models and avoid offering a stale engine for launch. +4. Inspect the uncommitted edits in `apps/web/src/components/app/` first. They cover the header, runner picker, fallback model label, No repository row, spacing and initial engine loading. Type checking ran during the updater work. These edits have **not** passed final UI acceptance. The actual default-branch lookup is still missing. The current runner branch-list operation returns names only, and fallback older peers may lack branch browsing. Avoid guessing main from a sorted list. Any runner binary change needs a verified copyable update command, with instructions grounded in the installed revision. +5. Relevant sources include `branch-select.tsx`, `create-agent-worktree-section.tsx`, `runner-project-picker.tsx`, `use-create-agent-form.ts`, the runner GitHub executor and service in `apps/server/src/agents/remote/`, and `e2e/remote-runner/{harness.ts,fixture-gh.sh,github-account.spec.ts}`. The harness still expects the old empty-picker label. Preserve the in-dialog popover and its touch/wheel scrolling fix from `fed8ed46`. +6. Drive the served form on desktop and phone widths and verify delayed inventory, runner switching, scoped results, clearing to No repository, branch search/default and selecting a branch. Exercise the installed peer as well as controlled fixtures. Follow AGENTS.md for checks and screenshot attachments. Existing temporary Playwright drivers include `/tmp/dispatch-picker-browser.cjs` and `/tmp/dispatch-repo-scroll.cjs`. The former still expects the removed clear button. + +## Second pending work — remote agent dev tools + +Brad’s report is `bc39a69e-3ce6-4b6d-b899-8cf87de8a503`. His Claude session `agt_756e6d3144d6` reported ECONNRESET on repo_dev_up and repo_dev_status, followed by a disconnected Dispatch MCP server. + +A separate session-bound terminal on ubu reached the expected checkout. The read-only dev helper reported “No dev environment found” for this agent’s suffix. Git, Docker CLI and Node were on the workload PATH. pnpm and Bun were missing there and this checkout’s dev helper requires both. Docker daemon access was not established. The terminal was closed after the check. These findings establish prerequisites for starting this particular repo; the cause of the MCP transport reset is still unknown. Diagnose the authenticated normal tool path, preserve the existing user agent, and check status before retrying a launch. An outgoing controller’s local repo_dev_up starts a different stack. + +## Update verification and scope + +- `73a13fe9` fixed idle sessions blocking Linux runner updates. On an isolated Ubuntu VM the actual burn-in upgrade from b20e3b10 to 1f6e1f1f kept the host PID, session, journal and checkout. A new turn ran once after the upgrade. An injected startup failure rolled back with the agent intact. A real active turn deferred with 75. The replacement bootstrap posted for Brad is `458cd30b-06ff-4652-a2d8-a0f51a850eb9`. The VM evidence is attached to `2edbc5a2-c0bc-4463-ba0a-338bc1675a7a`. Type checks and installer fixtures passed. The VM and its disk were deleted. +- The approved preview scope for this burn-in is the existing local LAN IP-and-port flow. Generated Bonjour, HTTPS/Tailscale configuration and enrolled-runner preview relaying are deferred. A future remote preview should be reachable through Dispatch even when the device cannot reach the runner. +- Prior audit evidence lives in `docs/design/runner-capability-inventory.md` and `docs/design/runner-parity-rollout.md`. Brad confirmed engine installs and sign-ins. Keep earlier fixture results distinct from live behavior. The user prefers one active implementer and concrete commands. +- Protect disk space. `43cb28b6` fixed an E2E binary retention issue. The ignored legacy downloads under `apps/web/dist/runner-burnin` and `apps/web/dist/wireframes` can be embedded into generated runtime assets during builds. Move existing legacy directories to one temporary holding directory before generating assets or building, and restore them afterward. The current updater is served separately from `apps/web/runner-burnin/dist`. Reuse existing tests and the live stack where appropriate. Ask before using a new VM under AGENTS.md. From 8115ccc5a9c0d0857d9bf088a0a1f3a3eeb6ea0c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 08:51:39 -0700 Subject: [PATCH 171/642] Restore the familiar Create Agent form on runners and speed up repository search Keep the runner picker compact and fixed-width beside the title, with a machine icon and connection status per option. Agent and Model stay as ordinary controls while their options load. Drop the agent binary line and the reserved gap beneath the engine row. A managed runner offers No repository in the picker instead of a separate clear button. The starting branch control lists the same rows on a runner as locally and names the repository's real default branch, which the runner now reports. Repository search shares one cached listing of the account's repositories instead of re-listing every page for each keystroke. Co-Authored-By: Claude Fable 5.2 --- .../agents/remote/github-runner-executor.ts | 127 ++++++++++++------ apps/server/src/agents/remote/service.ts | 10 +- .../app/agent-engine-fields.test.tsx | 33 +++-- .../components/app/agent-engine-fields.tsx | 14 +- .../app/agent-model-select.test.tsx | 8 +- .../src/components/app/agent-model-select.tsx | 20 +-- .../src/components/app/agent-type-select.tsx | 31 ++++- apps/web/src/components/app/branch-select.tsx | 54 ++++++-- .../components/app/create-agent-dialog.tsx | 41 +++--- .../components/app/jobs-settings-tab.test.tsx | 6 +- apps/web/src/components/app/runner-picker.tsx | 76 ++++++++--- .../components/app/runner-project-picker.tsx | 46 +++---- .../components/app/use-create-agent-form.ts | 11 +- e2e/remote-runner/fixture-gh.sh | 1 + e2e/remote-runner/harness.ts | 2 +- 15 files changed, 318 insertions(+), 162 deletions(-) diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index d1cfb34cf..9b870c583 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -62,6 +62,65 @@ export class GitHubRunnerExecutor { private login?: Login; private failure?: string; private queue = Promise.resolve(); + private repositories?: { + at: number; + rows: Promise<{ name: string; url: string }[]>; + }; + + /** + * Every repository the signed-in account can reach. Listing a large + * account takes several seconds, so searches typed in quick succession + * share one listing and reuse it for a few minutes. + */ + private repositoryList() { + const cached = this.repositories; + if (cached && Date.now() - cached.at < 5 * 60_000) return cached.rows; + const signal = AbortSignal.timeout(60_000); + const rows = (async () => { + const all: { name: string; url: string }[] = []; + for (let page = 1; page <= 50; page++) { + const batch: unknown = JSON.parse( + await this.run( + [ + "api", + ...hostArgs, + "user/repos", + "--method", + "GET", + "-f", + "affiliation=owner,collaborator,organization_member", + "-f", + "sort=pushed", + "-f", + "per_page=100", + "-f", + `page=${page}`, + "--jq", + "[.[] | {name: .full_name, url: .html_url}]", + ], + signal + ) + ); + if (!Array.isArray(batch)) + throw new Error("Invalid GitHub repository list."); + all.push( + ...batch.filter( + (row) => + typeof row?.name === "string" && typeof row?.url === "string" + ) + ); + if (batch.length < 100) break; + } + return all; + })(); + const entry = { at: Date.now(), rows }; + this.repositories = entry; + // A failed listing is retried by the next search. + rows.catch(() => { + if (this.repositories === entry) this.repositories = undefined; + }); + return rows; + } constructor( env: NodeJS.ProcessEnv, @@ -242,6 +301,7 @@ export class GitHubRunnerExecutor { session.child.kill("SIGKILL"); await session.finished; this.failure = undefined; + this.repositories = undefined; } private async logout(login: string, signal: AbortSignal) { @@ -278,6 +338,7 @@ export class GitHubRunnerExecutor { await this.login?.finished; signal.throwIfAborted(); this.failure = undefined; + this.repositories = undefined; const account = await this.account(signal); if (account.status === "signed-out") { this.start(signal); @@ -298,6 +359,7 @@ export class GitHubRunnerExecutor { case "logout": { await this.stopLogin(); this.failure = undefined; + this.repositories = undefined; const login = await this.configuredUser(signal); if (login) await this.logout(login, signal); return this.account(signal); @@ -313,60 +375,41 @@ export class GitHubRunnerExecutor { signal.throwIfAborted(); switch (operation.type) { case "repositorySearch": { - const matches: { name: string; url: string }[] = []; const query = operation.query.toLowerCase(); - for (let page = 1; matches.length < 12; page++) { - const rows: unknown = JSON.parse( - await this.run( - [ - "api", - ...hostArgs, - "user/repos", - "--method", - "GET", - "-f", - "affiliation=owner,collaborator,organization_member", - "-f", - "per_page=100", - "-f", - `page=${page}`, - "--jq", - "[.[] | {name: .full_name, url: .html_url}]", - ], - signal - ) - ); - if (!Array.isArray(rows)) - throw new Error("Invalid GitHub repository list."); - matches.push( - ...githubRepositoryResults( - rows.filter( - (row) => - typeof row?.name === "string" && - row.name.toLowerCase().includes(query) - ) - ).repositories - ); - if (rows.length < 100) break; - } - return githubRepositoryResults(matches); + const rows = await this.repositoryList(); + signal.throwIfAborted(); + return githubRepositoryResults( + rows.filter((row) => row.name.toLowerCase().includes(query)) + ); } case "repositoryBranches": { - const rows: unknown = JSON.parse( - await this.run( + const repository = `repos/${operation.owner}/${operation.repo}`; + // The list is capped and alphabetical, so the default is asked for + // by name. A failed lookup leaves the list usable without it. + const [list, named] = await Promise.all([ + this.run( [ "api", ...hostArgs, - `repos/${operation.owner}/${operation.repo}/branches?per_page=100`, + `${repository}/branches?per_page=100`, "--jq", "[.[].name]", ], signal - ) - ); + ), + this.run( + ["api", ...hostArgs, repository, "--jq", ".default_branch"], + signal + ).catch(() => ""), + ]); + const rows: unknown = JSON.parse(list); if (!Array.isArray(rows)) throw new Error("Invalid GitHub branch list."); - return { branches: rows.filter(validBranch) }; + const defaultBranch = named.trim(); + return { + branches: rows.filter(validBranch), + ...(validBranch(defaultBranch) && { defaultBranch }), + }; } case "pullRequestDetails": return this.evidence.details(operation, signal); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 7133c365d..0a3db409d 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -1424,7 +1424,15 @@ export class RemoteRunnerService { ) { throw new Error("Invalid GitHub branches reply."); } - return { branches: response.branches }; + // Peers older than the default-branch lookup reply with names only. + const named = + "defaultBranch" in response && validBranch(response.defaultBranch) + ? response.defaultBranch + : undefined; + return { + branches: response.branches as string[], + ...(named && { defaultBranch: named }), + }; } async searchGitHubRepositories(runnerId: string, query: string) { diff --git a/apps/web/src/components/app/agent-engine-fields.test.tsx b/apps/web/src/components/app/agent-engine-fields.test.tsx index d91d6802d..18e2267fe 100644 --- a/apps/web/src/components/app/agent-engine-fields.test.tsx +++ b/apps/web/src/components/app/agent-engine-fields.test.tsx @@ -191,7 +191,6 @@ const engineBlock = () => { const block = type.parentElement!.parentElement!.parentElement!; return block.outerHTML .replace(">Agent", ">Type") - .replaceAll(">Use engine setting<", ">Default<") .replace(/task-trigger-type/g, "agent-type-select") .replace(/task-trigger-(model|engine|effort)/g, "create-agent-$1") .replace(/radix-[^"]*/g, "radix") @@ -199,22 +198,22 @@ const engineBlock = () => { .replace(/:r[0-9a-z]+:/g, "id"); }; -const settle = async (expectModel: boolean) => { +const settle = async (expectModel: boolean, missing = false) => { await waitFor(() => { - expect(screen.queryByText(/Loading models/)).toBeNull(); + expect(document.querySelector('[aria-busy="true"]')).toBeNull(); expect(screen.queryAllByText("Model")).toHaveLength(expectModel ? 1 : 0); }); - // Engines arrive on their own query: the summary line or the install hint. - await waitFor(() => - expect( - screen.queryAllByTestId(/-engine$|^agent-type-missing-note$/) - ).not.toHaveLength(0) - ); + // Engines arrive on their own query; only a missing one says anything. + if (missing) await screen.findByTestId("agent-type-missing-note"); }; -const blockIn = async (host: "create" | "trigger", expectModel: boolean) => { +const blockIn = async ( + host: "create" | "trigger", + expectModel: boolean, + missing = false +) => { renderHost(host); - await settle(expectModel); + await settle(expectModel, missing); const html = engineBlock(); cleanup(); return html; @@ -224,7 +223,8 @@ it("renders the installed engine's block the same in both hosts", async () => { createType.value = templateType.value = "codex"; renderHost("trigger"); await settle(true); - await screen.findByText("Codex 0.155.1 · /opt/homebrew/bin/codex"); + // The binary and its path stay out of the form rows. + expect(screen.queryByText(/\/opt\/homebrew\/bin\/codex/)).toBeNull(); expect(screen.getByRole("combobox", { name: "Type" }).textContent).toContain( "Codex" ); @@ -242,15 +242,14 @@ it("renders the installed engine's block the same in both hosts", async () => { it("says what to install for a missing engine in both hosts", async () => { createType.value = templateType.value = "claude"; renderHost("trigger"); - await settle(true); - await screen.findByTestId("agent-type-missing-note"); + await settle(true, true); expect(screen.getByTestId("agent-type-missing-note").textContent).toContain( "npm i -g @anthropic-ai/claude-code" ); cleanup(); - const create = await blockIn("create", true); - const trigger = await blockIn("trigger", true); + const create = await blockIn("create", true, true); + const trigger = await blockIn("trigger", true, true); expect(trigger).toBe(create); }); @@ -260,5 +259,5 @@ it("keeps the Model field in Create Agent without a catalog", async () => { const trigger = await blockIn("trigger", false); expect(create).toContain("create-agent-model"); expect(trigger).toContain("grid-cols-[minmax(0,1fr)_4.75rem]"); - expect(trigger).toContain("OpenCode · /usr/local/bin/opencode"); + expect(trigger).not.toContain("/usr/local/bin/opencode"); }); diff --git a/apps/web/src/components/app/agent-engine-fields.tsx b/apps/web/src/components/app/agent-engine-fields.tsx index 12c01f3da..122636a39 100644 --- a/apps/web/src/components/app/agent-engine-fields.tsx +++ b/apps/web/src/components/app/agent-engine-fields.tsx @@ -6,7 +6,7 @@ import { useMemo } from "react"; import { AgentModelSelect } from "@/components/app/agent-model-select"; import { AgentTypeSelect } from "@/components/app/agent-type-select"; import { type AgentModelOption } from "@/hooks/use-agent-model-catalog"; -import { engineSummary, useEngines } from "@/hooks/use-engines"; +import { useEngines } from "@/hooks/use-engines"; import { type AgentType } from "@/lib/agent-types"; type AgentEngineFieldsProps = { @@ -14,6 +14,7 @@ type AgentEngineFieldsProps = { onAgentTypeChange: (type: AgentType) => void; agentTypes: AgentType[]; agentLabel?: string; + agentLoading?: boolean; effort?: Effort | null; effortDefaultLabel?: string; onEffortChange?: (effort: Effort | null) => void; @@ -41,6 +42,7 @@ export function AgentEngineFields({ onAgentTypeChange, agentTypes, agentLabel, + agentLoading, model, effort, effortDefaultLabel, @@ -70,7 +72,6 @@ export function AgentEngineFields({ ), [engines] ); - const engineLine = remote ? statusLine : engineSummary(engines, agentType); const showModelSelect = catalogDefault !== undefined || modelLoading || modelOptions.length > 0; @@ -86,6 +87,7 @@ export function AgentEngineFields({ onChange={onAgentTypeChange} agentTypes={agentTypes} label={agentLabel} + loading={agentLoading} onOpenChange={onTypeOpenChange} missing={remote ? undefined : missingEngines} /> @@ -114,13 +116,13 @@ export function AgentEngineFields({ /> ) : null} - {engineLine || statusLine !== undefined ? ( + {statusLine ? (

    - {engineLine} + {statusLine}

    ) : null}
    diff --git a/apps/web/src/components/app/agent-model-select.test.tsx b/apps/web/src/components/app/agent-model-select.test.tsx index b1407421a..ef923719b 100644 --- a/apps/web/src/components/app/agent-model-select.test.tsx +++ b/apps/web/src/components/app/agent-model-select.test.tsx @@ -35,12 +35,14 @@ describe("AgentModelSelect", () => { } ); - it("keeps the trigger labelled while the catalog loads", () => { + it("stays a usable, labelled control while the catalog loads", () => { render( ); const trigger = screen.getByTestId("create-agent-model"); - expect(trigger.textContent).toContain("Loading models…"); - expect(trigger).toHaveProperty("disabled", true); + expect(trigger.textContent).toContain("Default"); + expect(trigger.textContent).not.toContain("Loading"); + expect(trigger.getAttribute("aria-busy")).toBe("true"); + expect(trigger).toHaveProperty("disabled", false); }); }); diff --git a/apps/web/src/components/app/agent-model-select.tsx b/apps/web/src/components/app/agent-model-select.tsx index 328e9b08b..3e868e44a 100644 --- a/apps/web/src/components/app/agent-model-select.tsx +++ b/apps/web/src/components/app/agent-model-select.tsx @@ -52,22 +52,22 @@ export function AgentModelSelect({ - {loading - ? "Loading models…" - : options.length === 0 - ? "Default" - : undefined} + {options.some((option) => option.id === selectedValue) + ? undefined + : "Default"} {!catalogDefault && ( - - {catalogDefault === null && options.length > 0 - ? "Use engine setting" - : "Default"} + Default + )} + {loading && ( + + Loading models… )} {options.map((option) => ( diff --git a/apps/web/src/components/app/agent-type-select.tsx b/apps/web/src/components/app/agent-type-select.tsx index 81814b941..d53e8740a 100644 --- a/apps/web/src/components/app/agent-type-select.tsx +++ b/apps/web/src/components/app/agent-type-select.tsx @@ -1,4 +1,5 @@ import { useCallback, useMemo, useRef, useState } from "react"; +import { ActivityBars } from "@/components/ui/activity-bars"; import { Check, ChevronDown } from "lucide-react"; import { @@ -21,6 +22,7 @@ type AgentTypeSelectProps = { agentTypes: AgentType[]; onOpenChange?: (open: boolean) => void; label?: string; + loading?: boolean; /** Override when a page can render more than one of these, so ids stay * unique. */ id?: string; @@ -37,6 +39,7 @@ export function AgentTypeSelect({ agentTypes, onOpenChange, label = "Type", + loading = false, id = "agent-type-select", missing, }: AgentTypeSelectProps): JSX.Element { @@ -68,6 +71,7 @@ export function AgentTypeSelect({ role="combobox" tabIndex={0} aria-expanded={open} + aria-busy={loading || undefined} onClick={() => updateOpen(!open)} onKeyDown={(e) => { if (e.key === "ArrowDown" || e.key === "Enter" || e.key === " ") { @@ -81,12 +85,16 @@ export function AgentTypeSelect({ )} > {AGENT_TYPE_LABELS[value]} - + {loading ? ( + + ) : ( + + )} {open ? (
    @@ -104,8 +112,17 @@ export function AgentTypeSelect({ }} > + {loading ? ( +
    + + Loading agents… +
    + ) : null} - {sortedTypes.map((agentType) => ( + {(loading ? [] : sortedTypes).map((agentType) => ( ([]); + // The runner repository's real default, when its peer reports one. + const [defaultBranch, setDefaultBranch] = useState(""); const [branchesLoading, setBranchesLoading] = useState(false); const [fetchedForCwd, setFetchedForCwd] = useState(null); const [fetchError, setFetchError] = useState(null); @@ -87,10 +89,14 @@ export function BranchSelect({ setBranchesLoading(true); setFetchError(null); try { - const result = await api<{ branches: string[] }>(endpoint); + const result = await api<{ branches: string[]; defaultBranch?: string }>( + endpoint + ); setRemoteBranches(result.branches); + setDefaultBranch(result.defaultBranch ?? ""); } catch (error) { setRemoteBranches([]); + setDefaultBranch(""); setFetchError( error instanceof Error ? error.message : "Couldn't load branches." ); @@ -100,6 +106,13 @@ export function BranchSelect({ } }, [endpoint, disabled]); + // A runner repository names its default up front, so the closed control + // reads as the branch the session will start from. + const runnerEndpoint = runner ? endpoint : ""; + useEffect(() => { + if (runnerEndpoint) void fetchBranches(); + }, [runnerEndpoint, fetchBranches]); + const openDropdown = useCallback(() => { if (disabled) return; setTyped(""); @@ -114,13 +127,19 @@ export function BranchSelect({ // include it (branch renamed/deleted upstream). We flag it visually in // the dropdown rather than silently overwrite it. const allBranches = useMemo(() => { - const base = - runner || remoteBranches.includes("main") + // The default has its own row when starting a new branch; when opening + // an existing branch it leads the list, even past the list's cap. + const others = remoteBranches.filter((branch) => branch !== defaultBranch); + const base = runner + ? allowPullRequest && defaultBranch + ? [defaultBranch, ...others] + : others + : remoteBranches.includes("main") ? remoteBranches : ["main", ...remoteBranches]; if (baseBranch && !base.includes(baseBranch)) return [baseBranch, ...base]; return base; - }, [remoteBranches, baseBranch, runner]); + }, [remoteBranches, baseBranch, runner, defaultBranch, allowPullRequest]); const savedBranchMissing = !runner && @@ -164,7 +183,7 @@ export function BranchSelect({ {baseBranch || (allowPullRequest ? "Choose a branch or PR" - : "Repository default")} + : defaultBranch || "Repository default")} {branchesLoading ? ( @@ -193,10 +212,8 @@ export function BranchSelect({ value={typed} onValueChange={setTyped} placeholder={ - runner - ? allowPullRequest - ? "Branch name or GitHub PR URL" - : "Find or enter a branch" + runner && allowPullRequest + ? "Branch name or GitHub PR URL" : "Search branches..." } className="font-mono text-xs" @@ -214,18 +231,28 @@ export function BranchSelect({ {runner && !allowPullRequest && ( { onBaseBranchChange(""); closeDropdown(); triggerRef.current?.focus(); }} > - Repository default + + {defaultBranch || "Repository default"} )} {runner && typed.trim() && + (allowPullRequest || typed.trim() !== defaultBranch) && !allBranches.includes(typed.trim()) && ( - Use {typed.trim()} + + {typed.trim()} )} {allBranches.map((branch) => { diff --git a/apps/web/src/components/app/create-agent-dialog.tsx b/apps/web/src/components/app/create-agent-dialog.tsx index 96e3dc980..53c326afc 100644 --- a/apps/web/src/components/app/create-agent-dialog.tsx +++ b/apps/web/src/components/app/create-agent-dialog.tsx @@ -117,8 +117,18 @@ function CreateAgentDialogContent({ > {form.step === "config" ? ( <> - - Create Agent + + Create Agent + r.managedWorkspace) + : form.runners + } + runnerId={form.runnerId} + unavailable={form.runnerUnavailable} + onRunnerChange={form.selectRunner} + />
    - r.managedWorkspace) - : form.runners - } - runnerId={form.runnerId} - unavailable={form.runnerUnavailable} - onRunnerChange={form.selectRunner} - /> + {form.runnerUnavailable && ( +

    + This runner is revoked or gone. Choose This computer or + another runner to continue. +

    + )} @@ -182,7 +191,7 @@ function CreateAgentDialogContent({
    {task && } -
    +
    {form.runner && !form.runnerUnavailable && !form.managedSession && ( diff --git a/apps/web/src/components/app/jobs-settings-tab.test.tsx b/apps/web/src/components/app/jobs-settings-tab.test.tsx index 46fe355aa..fb7338bd1 100644 --- a/apps/web/src/components/app/jobs-settings-tab.test.tsx +++ b/apps/web/src/components/app/jobs-settings-tab.test.tsx @@ -237,9 +237,9 @@ describe("save payload", () => { // through untouched, so saving too early would sidestep the behavior // under test. await waitFor(() => - expect(screen.getByTestId("create-agent-model").textContent).toContain( - "Default" - ) + expect( + screen.getByTestId("create-agent-model").getAttribute("aria-busy") + ).toBeNull() ); await clickSave(); diff --git a/apps/web/src/components/app/runner-picker.tsx b/apps/web/src/components/app/runner-picker.tsx index 1a4ecd15e..10c703766 100644 --- a/apps/web/src/components/app/runner-picker.tsx +++ b/apps/web/src/components/app/runner-picker.tsx @@ -1,3 +1,4 @@ +import { Monitor, Server } from "lucide-react"; import { useId } from "react"; import { @@ -8,9 +9,47 @@ import { SelectValue, } from "@/components/ui/select"; import { type Runner } from "@/hooks/use-runners"; +import { cn } from "@/lib/utils"; const THIS_COMPUTER = "__local__"; +/** One machine in the picker: what kind it is, its name, whether it is up. */ +function RunnerOption({ + local = false, + name, + status, +}: { + local?: boolean; + name: string; + status: "online" | "offline" | "pending" | "unavailable"; +}) { + const Icon = local ? Monitor : Server; + return ( + +
    diff --git a/apps/web/src/components/app/use-create-agent-form.ts b/apps/web/src/components/app/use-create-agent-form.ts index 1ba745cd1..79e832f0d 100644 --- a/apps/web/src/components/app/use-create-agent-form.ts +++ b/apps/web/src/components/app/use-create-agent-form.ts @@ -272,6 +272,9 @@ export function useCreateAgentForm({ runnerId ? { kind: "runner", runnerId } : { kind: "local" }, online && runner?.engineManagement === true ); + const runnerEnginesLoading = Boolean( + remote && online && runner?.engineManagement && inventory.isLoading + ); const entries = online && !inventory.isError ? inventory.data?.entries : undefined; const runnableTypes = entries @@ -462,7 +465,8 @@ export function useCreateAgentForm({ async (event: FormEvent) => { event.preventDefault(); const cwd = createCwd.trim(); - if (!cwd || !locationReady || runnerEngineBlocked) return; + if (!cwd || !locationReady || runnerEnginesLoading || runnerEngineBlocked) + return; setCreating(true); try { @@ -604,6 +608,7 @@ export function useCreateAgentForm({ runnerNewBranch, locationReady, runnerEngineBlocked, + runnerEnginesLoading, createCwd, remote, createProjectId, @@ -633,6 +638,7 @@ export function useCreateAgentForm({ agentTypes, runnerEngineBlocked, runnerId, + runnerEnginesLoading, runnerUnavailable, runnerGitHubAvailable: online && @@ -654,7 +660,8 @@ export function useCreateAgentForm({ runnerWorkspace, setRunnerWorkspace, createProjectId, - locationReady: locationReady && !runnerEngineBlocked, + locationReady: + locationReady && !runnerEnginesLoading && !runnerEngineBlocked, lastProjectId: locationPref?.projectId, setCreateProjectId, step, diff --git a/e2e/remote-runner/fixture-gh.sh b/e2e/remote-runner/fixture-gh.sh index 7ab4c788b..fe8684976 100644 --- a/e2e/remote-runner/fixture-gh.sh +++ b/e2e/remote-runner/fixture-gh.sh @@ -42,6 +42,7 @@ case "$1 ${2:-}" in test -s "$key" case " $* " in *'/branches?per_page=100'*) printf '%s' '["main","review-topic"]' ;; + *' .default_branch '*) printf 'trunk\n' ;; *'/pulls/'*) printf '{"url":"https://github.com/%s/private.git","branch":"review-topic"}\n' "$login" ;; *' user/repos '*) test -s "$key" diff --git a/e2e/remote-runner/harness.ts b/e2e/remote-runner/harness.ts index c5ada6a9c..a443d705b 100644 --- a/e2e/remote-runner/harness.ts +++ b/e2e/remote-runner/harness.ts @@ -300,7 +300,7 @@ export async function launchViaUi( page.getByTestId("create-agent-runner-workspace") ).toHaveCount(0); const picker = page.getByTestId("runner-repository"); - await expect(picker).toContainText("Choose a project or repository"); + await expect(picker).toContainText("No repository"); if (opts.repository) { await picker.click(); await page From 50af389565af0568a7a072e0d94f0a556dd71fde Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 09:21:07 -0700 Subject: [PATCH 172/642] List runner repositories in parallel and start when the account is read A cold search waited on every page of a large account in sequence. Fetch pages four at a time and begin the listing when the form asks for the runner's GitHub account, so the first search usually finds it ready. Co-Authored-By: Claude Fable 5.2 --- .../agents/remote/github-runner-executor.ts | 82 +++++++++++-------- 1 file changed, 50 insertions(+), 32 deletions(-) diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index 9b870c583..8e5716b39 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -76,40 +76,52 @@ export class GitHubRunnerExecutor { const cached = this.repositories; if (cached && Date.now() - cached.at < 5 * 60_000) return cached.rows; const signal = AbortSignal.timeout(60_000); + const page = async (number: number) => { + const batch: unknown = JSON.parse( + await this.run( + [ + "api", + ...hostArgs, + "user/repos", + "--method", + "GET", + "-f", + "affiliation=owner,collaborator,organization_member", + "-f", + "sort=pushed", + "-f", + "per_page=100", + "-f", + `page=${number}`, + "--jq", + "[.[] | {name: .full_name, url: .html_url}]", + ], + signal + ) + ); + if (!Array.isArray(batch)) + throw new Error("Invalid GitHub repository list."); + return batch as { name?: unknown; url?: unknown }[]; + }; const rows = (async () => { const all: { name: string; url: string }[] = []; - for (let page = 1; page <= 50; page++) { - const batch: unknown = JSON.parse( - await this.run( - [ - "api", - ...hostArgs, - "user/repos", - "--method", - "GET", - "-f", - "affiliation=owner,collaborator,organization_member", - "-f", - "sort=pushed", - "-f", - "per_page=100", - "-f", - `page=${page}`, - "--jq", - "[.[] | {name: .full_name, url: .html_url}]", - ], - signal - ) - ); - if (!Array.isArray(batch)) - throw new Error("Invalid GitHub repository list."); - all.push( - ...batch.filter( - (row) => - typeof row?.name === "string" && typeof row?.url === "string" - ) + const seen = new Set(); + // Pages are fetched a few at a time; a short page ends the listing. + for (let first = 1; first <= 48; first += 4) { + const batches = await Promise.all( + [0, 1, 2, 3].map((offset) => page(first + offset)) ); - if (batch.length < 100) break; + for (const batch of batches) + for (const row of batch) + if ( + typeof row?.name === "string" && + typeof row?.url === "string" && + !seen.has(row.url) + ) { + seen.add(row.url); + all.push({ name: row.name, url: row.url }); + } + if (batches.some((batch) => batch.length < 100)) break; } return all; })(); @@ -332,7 +344,13 @@ export class GitHubRunnerExecutor { case "status": if (this.login) return this.currentLogin(); if (this.failure) return { status: "failed", message: this.failure }; - return this.account(signal); + return this.account(signal).then((account) => { + // The form asks for the account before anyone searches, so the + // first search finds the listing already under way. + if (account.status === "signed-in") + void this.repositoryList().catch(() => {}); + return account; + }); case "login": { if (this.login?.connection === signal) return this.currentLogin(); await this.login?.finished; From 1bd38c05d75a3f73d34d3d1cf4e2806857346b3f Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 09:43:30 -0700 Subject: [PATCH 173/642] Configure Git author identity for runner accounts Use the signed-in GitHub profile to fill missing Git identity in the workload account, including for existing logins. --- .../agents/remote/github-runner-executor.ts | 58 +++++++++++++++++-- .../test/github-runner-executor.test.ts | 48 ++++++++++++++- e2e/remote-runner/fixture-gh.sh | 1 + 3 files changed, 100 insertions(+), 7 deletions(-) diff --git a/apps/server/src/agents/remote/github-runner-executor.ts b/apps/server/src/agents/remote/github-runner-executor.ts index 8e5716b39..7091bf32a 100644 --- a/apps/server/src/agents/remote/github-runner-executor.ts +++ b/apps/server/src/agents/remote/github-runner-executor.ts @@ -154,8 +154,17 @@ export class GitHubRunnerExecutor { ); } - private async run(args: string[], signal: AbortSignal, token?: string) { - const command = this.wrap(gh, args); + private run(args: string[], signal: AbortSignal, token?: string) { + return this.runCommand(gh, args, signal, token); + } + + private async runCommand( + bin: string, + args: string[], + signal: AbortSignal, + token?: string + ) { + const command = this.wrap(bin, args); const { stdout } = await execute(command.bin, command.args, { env: token ? { ...this.env, GH_TOKEN: token } : this.env, signal, @@ -166,6 +175,26 @@ export class GitHubRunnerExecutor { return stdout.trim(); } + private async configureGitIdentity( + profile: { login: string; id: number; name?: unknown }, + signal: AbortSignal + ) { + const config = (args: string[]) => + this.runCommand("/usr/bin/git", ["config", "--global", ...args], signal); + const name = typeof profile.name === "string" ? profile.name.trim() : ""; + for (const [key, value] of [ + ["user.name", name || profile.login], + ["user.email", `${profile.id}+${profile.login}@users.noreply.github.com`], + ]) { + try { + await config(["--get", key]); + } catch (error) { + if ((error as { code?: number }).code !== 1) throw error; + await config([key, value]); + } + } + } + private async configuredUser(signal: AbortSignal) { try { const login = await this.run( @@ -199,12 +228,14 @@ export class GitHubRunnerExecutor { private async account(signal: AbortSignal): Promise { if (!(await this.configuredUser(signal))) return { status: "signed-out" }; + let profile: { login?: unknown; id?: unknown; name?: unknown } | null; try { - const login = await this.run( - ["api", ...hostArgs, "user", "--jq", ".login"], - signal + profile = JSON.parse( + await this.run( + ["api", ...hostArgs, "user", "--jq", "{login,id,name}"], + signal + ) ); - if (validGitHubLogin(login)) return { status: "signed-in", login }; } catch (error) { const { code, stderr } = error as { code?: number; stderr?: string }; if (code === 4 || /HTTP 401\b/.test(stderr ?? "")) @@ -214,6 +245,18 @@ export class GitHubRunnerExecutor { message: cliIssue(error, githubAccountIssues.verify), }; } + if ( + validGitHubLogin(profile?.login) && + typeof profile.id === "number" && + Number.isSafeInteger(profile.id) && + profile.id > 0 + ) { + await this.configureGitIdentity( + { login: profile.login, id: profile.id, name: profile.name }, + signal + ); + return { status: "signed-in", login: profile.login }; + } return { status: "unavailable", message: githubAccountIssues.verify }; } @@ -289,6 +332,9 @@ export class GitHubRunnerExecutor { ["auth", "setup-git", ...hostArgs], AbortSignal.timeout(7000) ); + const account = await this.account(AbortSignal.timeout(7000)); + if (account.status !== "signed-in") + failure = githubAccountIssues.verify; } catch { failure = githubAccountIssues.helper; } diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts index 2eb73a606..75a00687a 100644 --- a/apps/server/test/github-runner-executor.test.ts +++ b/apps/server/test/github-runner-executor.test.ts @@ -106,7 +106,21 @@ case "$1 $2" in test -f login printf '%s' '[{"name":"org/project","url":"https://github.com/org/project"},{"name":"unrelated/other","url":"https://github.com/unrelated/other"},{"name":"org/project-secret","url":"https://synthetic-token@github.com/org/project"}]' ;; - user) if [ -f revoked ]; then printf '(HTTP 401)\n' >&2; exit 1; fi; cat login ;; + user) + if [ -f revoked ]; then printf '(HTTP 401)\n' >&2; exit 1; fi + test -s login + case "$6" in + .login) cat login ;; + '{login,id,name}') + if [ -f no-profile-name ]; then + printf '{"login":"fixture-user","id":1234,"name":null}' + else + printf '{"login":"fixture-user","id":1234,"name":"Fixture User"}' + fi + ;; + *) exit 1 ;; + esac + ;; repos/org/project/pulls/42) if [ "$6" = '.number' ]; then test "$GH_TOKEN" = 'approved-token' @@ -128,6 +142,7 @@ esac { mode: 0o700 } ); const executor = new GitHubRunnerExecutor(env, (bin, args) => { + if (bin === "/usr/bin/git") return { bin, args }; expect(bin).toBe("/usr/bin/gh"); return { bin: gh, args }; }); @@ -202,6 +217,10 @@ it("completes a device login and configures the same credential helper for an ag }); expect(result).toContain("username=fixture-user"); } + expect(gitConfig(env, "user.name")).toBe("Fixture User"); + expect(gitConfig(env, "user.email")).toBe( + "1234+fixture-user@users.noreply.github.com" + ); expect( await executor.handle( { type: "repositorySearch", query: "org/project" }, @@ -264,6 +283,33 @@ it("completes a device login and configures the same credential helper for an ag }); }); +function gitConfig(env: NodeJS.ProcessEnv, key: string, value?: string) { + return execFileSync( + "git", + ["config", "--global", key, ...(value === undefined ? [] : [value])], + { env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] } + ).trim(); +} + +it("fills missing Git identity for an existing login and preserves custom values", async () => { + await fixture(async ({ executor, root, env }) => { + const signal = new AbortController().signal; + await writeFile(path.join(root, "login"), "fixture-user"); + await writeFile(path.join(root, "no-profile-name"), ""); + gitConfig(env, "user.email", "custom@example.com"); + expect(await executor.handle({ type: "status" }, signal)).toEqual({ + status: "signed-in", + login: "fixture-user", + }); + expect(gitConfig(env, "user.name")).toBe("fixture-user"); + expect(gitConfig(env, "user.email")).toBe("custom@example.com"); + gitConfig(env, "user.name", "Custom Name"); + await executor.handle({ type: "login" }, signal); + expect(gitConfig(env, "user.name")).toBe("Custom Name"); + expect(gitConfig(env, "user.email")).toBe("custom@example.com"); + }); +}); + it("binds bounded PR details and an assessed diff to the workload credential", async () => { await fixture(async ({ executor, root }) => { const target = { owner: "org", repo: "project", number: 42 }; diff --git a/e2e/remote-runner/fixture-gh.sh b/e2e/remote-runner/fixture-gh.sh index fe8684976..c9865715e 100644 --- a/e2e/remote-runner/fixture-gh.sh +++ b/e2e/remote-runner/fixture-gh.sh @@ -48,6 +48,7 @@ case "$1 ${2:-}" in test -s "$key" printf '[{"name":"%s/private","url":"https://github.com/%s/private"}]\n' "$login" "$login" ;; + *' {login,id,name} '*) printf '{"login":"%s","id":1234,"name":null}\n' "$login" ;; *' user '*) printf '%s\n' "$login" ;; *) exit 1 ;; esac From 90919c7a7fa4e9b0589ed9e44f6366dae805edab Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 09:46:15 -0700 Subject: [PATCH 174/642] Free runner handshake slots after HTTP requests arrive Keep pairing and incomplete requests bounded. Close idle proxy connections gracefully while allowing in-flight MCP calls to finish. --- apps/server/src/agents/remote/service.ts | 89 +++++++++++++++---- .../test/remote-runner-enrollment.test.ts | 59 +++++++++++- 2 files changed, 132 insertions(+), 16 deletions(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 0a3db409d..897fa2e46 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -8,7 +8,7 @@ import { X509Certificate } from "node:crypto"; import { readFileSync, watchFile, unwatchFile } from "node:fs"; import http from "node:http"; import https from "node:https"; -import { connect as connectTcp, isIP } from "node:net"; +import { connect as connectTcp, isIP, type Socket } from "node:net"; import os from "node:os"; import { createServer, type Server, type TLSSocket } from "node:tls"; import { @@ -183,6 +183,7 @@ type Peer = { }; const MAX_UNAUTHENTICATED = 64; +const PROXY_KEEP_ALIVE_TIMEOUT = 75_000; function validHost(host: string) { return ( @@ -363,12 +364,23 @@ export class RemoteRunnerService { if (enrollment.endpointHost && !validHost(enrollment.endpointHost)) throw new Error("DISPATCH_RUNNER_ENDPOINT_HOST is not a valid host"); } - this.proxy = http.createServer((request, response) => - this.forward(request, response) + this.proxy = http.createServer( + { + // MCP tool calls may legitimately run for a long time. + requestTimeout: 0, + headersTimeout: 30_000, + // Manage keep-alive below because Bun ignores this option. + keepAliveTimeout: 0, + }, + (request, response) => { + const firstRequest = this.proxyFirstRequests.get( + request.socket.remotePort! + ); + firstRequest?.(); + this.trackProxyRequest(request.socket, response); + this.forward(request, response); + } ); - // MCP tool calls may legitimately run for a long time. - this.proxy.requestTimeout = 0; - this.proxy.headersTimeout = 30_000; } /** Origin for an agent's MCP URL as seen from the runner it is placed on. */ @@ -586,10 +598,14 @@ export class RemoteRunnerService { // Unauthenticated peers may pair once or reach the scoped MCP proxy. if (this.unauthenticated >= MAX_UNAUTHENTICATED) return socket.destroy(); this.unauthenticated++; - socket.once("close", () => this.unauthenticated--); const deadline = setTimeout(() => socket.destroy(), 10_000); - socket.once("data", (chunk: Buffer) => { + const release = () => { + socket.removeListener("close", release); clearTimeout(deadline); + this.unauthenticated--; + }; + socket.once("close", release); + socket.once("data", (chunk: Buffer) => { if (chunk[0] === 0x7b && kind === "enrolled") { socket.pause(); socket.unshift(chunk); @@ -598,7 +614,7 @@ export class RemoteRunnerService { } else if ( /^[A-Z]{3,7} \//.test(chunk.subarray(0, 9).toString("latin1")) ) { - void this.relay(socket, chunk); + void this.relay(socket, chunk, release); } else socket.destroy(); }); } @@ -608,7 +624,7 @@ export class RemoteRunnerService { * request on it. Piping (rather than emitting the TLS socket into an * http.Server) works the same under Node and Bun. */ - private async relay(socket: TLSSocket, head: Buffer) { + private async relay(socket: TLSSocket, head: Buffer, release: () => void) { socket.pause(); try { const port = await this.ensureProxy(); @@ -616,15 +632,55 @@ export class RemoteRunnerService { const upstream = connectTcp(port, "127.0.0.1"); upstream.on("error", () => socket.destroy()); socket.on("close", () => upstream.destroy()); - upstream.on("close", () => socket.destroy()); - upstream.write(head); - socket.pipe(upstream).pipe(socket); - socket.resume(); + upstream.on("close", () => { + if (!upstream.readableEnded) socket.destroy(); + }); + upstream.once("connect", () => { + const relayPort = upstream.localPort!; + this.proxyFirstRequests.set(relayPort, () => { + this.proxyFirstRequests.delete(relayPort); + release(); + }); + upstream.once("close", () => this.proxyFirstRequests.delete(relayPort)); + upstream.write(head); + socket.pipe(upstream).pipe(socket); + socket.resume(); + }); } catch { socket.destroy(); } } + private readonly proxyIdleTimeout = PROXY_KEEP_ALIVE_TIMEOUT; + private readonly proxyFirstRequests = new Map void>(); + private readonly proxyRequests = new WeakMap< + Socket, + { pending: number; idleTimer?: ReturnType } + >(); + + private trackProxyRequest(socket: Socket, response: http.ServerResponse) { + let entry = this.proxyRequests.get(socket); + if (!entry) { + const state: { + pending: number; + idleTimer?: ReturnType; + } = { pending: 0 }; + socket.once("close", () => clearTimeout(state.idleTimer)); + this.proxyRequests.set(socket, state); + entry = state; + } + clearTimeout(entry.idleTimer); + entry.pending++; + const state = entry; + response.once("finish", () => { + if (--state.pending === 0) + state.idleTimer = setTimeout( + () => socket.end(), + this.proxyIdleTimeout + ).unref(); + }); + } + private ensureProxy() { this.proxyPort ??= new Promise((resolve, reject) => { this.proxy.once("error", reject); @@ -919,7 +975,10 @@ export class RemoteRunnerService { rejectUnauthorized: false, }, (reply) => { - response.writeHead(reply.statusCode ?? 502, reply.headers); + const headers = { ...reply.headers }; + delete headers.connection; + delete headers["keep-alive"]; + response.writeHead(reply.statusCode ?? 502, headers); reply.pipe(response); } ); diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 03f018660..852829e5a 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -1,8 +1,9 @@ import { X509Certificate } from "node:crypto"; +import { once } from "node:events"; import http from "node:http"; import https from "node:https"; import type { AddressInfo } from "node:net"; -import { connect, type TLSSocket } from "node:tls"; +import { connect, createServer, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { exchangeCode } from "../src/agents/remote/enrollment.js"; @@ -997,6 +998,62 @@ describe("runner enrollment service", () => { }); }); +it("releases the handshake slot for HTTP and closes the idle relay cleanly", async () => { + const authority = issueAuthority("relay-test"); + const leaf = issueServer(authority, [HOST]); + let requests = 0; + const api = http.createServer((_request, response) => { + const delay = requests++ === 0 ? 0 : 150; + setTimeout(() => response.end("ok"), delay); + }); + api.listen(0, HOST); + await once(api, "listening"); + const service = new RemoteRunnerService(undefined, undefined, { + host: HOST, + port: (api.address() as AddressInfo).port, + tls: false, + }); + const listener = createServer({ cert: leaf.cert, key: leaf.key }, (socket) => + service["accept"](socket, "legacy") + ); + listener.listen(0, HOST); + await once(listener, "listening"); + const agent = new https.Agent({ keepAlive: true, ca: authority.cert }); + try { + expect(service["proxyIdleTimeout"]).toBeGreaterThan(60_000); + Object.defineProperty(service, "proxyIdleTimeout", { value: 100 }); + const ping = () => + new Promise((resolve, reject) => { + const request = https.get( + { + host: HOST, + port: (listener.address() as AddressInfo).port, + path: "/ping", + agent, + }, + (response) => { + const connection = response.socket as TLSSocket; + response.resume(); + response.once("end", () => resolve(connection)); + response.once("error", reject); + } + ); + request.on("error", reject); + }); + const socket = await ping(); + expect(service["unauthenticated"]).toBe(0); + expect(await ping()).toBe(socket); + expect(socket.destroyed).toBe(false); + const [hadError] = await once(socket, "close"); + expect(hadError).toBe(false); + } finally { + agent.destroy(); + service.close(); + listener.close(); + api.close(); + } +}); + describe("legacy runner config", () => { it("keeps its locator and gates MCP on the live approval file", async () => { const { mkdtemp, writeFile } = await import("node:fs/promises"); From 1ba8c865ebd506b0d6ee08b1b335895ee2faab9c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 09:48:37 -0700 Subject: [PATCH 175/642] Use runner model catalogs when launching personas Resolve the parent agent placement so the persona picker offers the same runner models as Create Agent. --- .../components/app/persona-launcher.test.tsx | 57 ++++++++++++++++++- .../src/components/app/persona-launcher.tsx | 32 +++++++++-- 2 files changed, 83 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/app/persona-launcher.test.tsx b/apps/web/src/components/app/persona-launcher.test.tsx index 4b2f89dcc..251e33500 100644 --- a/apps/web/src/components/app/persona-launcher.test.tsx +++ b/apps/web/src/components/app/persona-launcher.test.tsx @@ -58,20 +58,73 @@ function launchRequestBody(): Record { return JSON.parse(call![1].body); } -function renderLauncher() { +function renderLauncher(parent = agent) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); render( - + ); } describe("PersonaLauncher", () => { + it("offers and submits models from the parent agent's runner", async ({ + onTestFinished, + }) => { + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { + value: vi.fn(), + configurable: true, + }); + onTestFinished(() => { + Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView"); + }); + const runnerId = "rnr_test"; + const model = { id: "claude-haiku-5-5", label: "Haiku 5.5" }; + api.mockImplementation(async (path: string, init?: RequestInit) => { + if (path === "/api/runners") + return { runners: [{ id: runnerId, status: "online" }] }; + if (path === "/api/v1/engine-management/operations") { + expect(JSON.parse(String(init?.body))).toEqual({ + scope: { kind: "runner", runnerId }, + operation: { type: "model_catalog", engine: "claude" }, + }); + return { + ack: { + ok: true, + capability: { type: "model_catalog", catalog: { models: [model] } }, + }, + }; + } + if (path.startsWith("/api/v1/personas")) return { personas: PERSONAS }; + if (path.includes("/launch-persona")) + return { ok: true, block: { id: "blk_1" } }; + return { models: { claude: [{ id: "opus", label: "Opus" }] } }; + }); + renderLauncher({ + ...agent, + cwd: `runner://${runnerId}/@session`, + workspacePath: "/remote/repo", + reviewAgentType: "claude", + }); + + fireEvent.click(await screen.findByTestId("launch-reviewer-button")); + fireEvent.keyDown(await screen.findByTestId("launch-reviewer-model"), { + key: "Enter", + }); + const option = await screen.findByRole("option", { name: model.label }); + expect(screen.queryByRole("option", { name: "Opus" })).toBeNull(); + fireEvent.click(option); + fireEvent.click(screen.getByTestId("launch-reviewer-persona-ux-review")); + fireEvent.click(screen.getByTestId("launch-reviewer-submit")); + await vi.waitFor(() => { + expect(launchRequestBody()).toMatchObject({ model: model.id }); + }); + }); + it("holds the launch button disabled while the model catalog loads", async () => { // The catalog never settles: launching now would send model: null and // silently drop the preference the select is about to show. diff --git a/apps/web/src/components/app/persona-launcher.tsx b/apps/web/src/components/app/persona-launcher.tsx index 2607f6940..6d43aacf7 100644 --- a/apps/web/src/components/app/persona-launcher.tsx +++ b/apps/web/src/components/app/persona-launcher.tsx @@ -1,4 +1,5 @@ import { ChevronDown } from "lucide-react"; +import { remotePlacement } from "@dispatch/runner-protocol"; import { useAtom } from "jotai"; import { useCallback, useMemo, useRef, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; @@ -20,6 +21,8 @@ import { } from "@/components/ui/tooltip"; import { useAgentModelCatalog } from "@/hooks/use-agent-model-catalog"; import { useClickOutside } from "@/hooks/use-click-outside"; +import { useRunnerModelCatalog } from "@/hooks/use-runner-engines"; +import { useRunners } from "@/hooks/use-runners"; import { api } from "@/lib/api"; import { AGENT_TYPE_LABELS, @@ -55,6 +58,7 @@ export function PersonaLauncher({ }): JSX.Element { const queryClient = useQueryClient(); const cwd = agent.workspacePath ?? agent.worktreePath ?? agent.cwd; + const runnerId = remotePlacement(agent.cwd)?.runner ?? null; const reviewerTypes = enabledAgentTypes.filter(isCliAgentType); const showReviewAgentTypePicker = reviewerTypes.length > 1; const [dialogOpen, setDialogOpen] = useState(false); @@ -69,13 +73,33 @@ export function PersonaLauncher({ const typeTriggerRef = useRef(null); const modelAtom = useMemo( - () => reviewAgentModelPrefAtom(`${selectedAgentType}:${cwd}`), - [selectedAgentType, cwd] + () => + reviewAgentModelPrefAtom( + runnerId + ? `runner://${encodeURIComponent(runnerId)}:${selectedAgentType}:${cwd}` + : `${selectedAgentType}:${cwd}` + ), + [selectedAgentType, cwd, runnerId] ); const [selectedModel, setSelectedModel] = useAtom(modelAtom); - const { options: modelOptions, loading: modelCatalogLoading } = - useAgentModelCatalog(selectedAgentType); + const localCatalog = useAgentModelCatalog(selectedAgentType, !runnerId); + const runners = useRunners({ enabled: dialogOpen && Boolean(runnerId) }); + const online = + runners.data?.find((runner) => runner.id === runnerId)?.status === "online"; + const runnerCatalog = useRunnerModelCatalog( + runnerId, + selectedAgentType, + dialogOpen && online + ); + const modelOptions = runnerId + ? online && !runnerCatalog.isError + ? (runnerCatalog.data?.models ?? []) + : [] + : localCatalog.options; + const modelCatalogLoading = runnerId + ? runners.isLoading || runnerCatalog.isLoading + : localCatalog.loading; const showModelSelect = modelCatalogLoading || modelOptions.length > 0; const { data: personaCatalog, refetch: refreshPersonas } = useQuery<{ From dad2d9055af1a26d12cd90c522b0d3cb8df3d84c Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 09:52:06 -0700 Subject: [PATCH 176/642] Launch review personas with full access Apply the same unattended review access to direct persona and owner launches on both placements while retaining the ordinary child access ceiling. --- .../server/src/server/mcp-persona-handlers.ts | 64 ++++------------- apps/server/test/mcp-handlers.test.ts | 28 +++++--- .../test/mcp-persona-codeowners.test.ts | 69 +++++++++---------- 3 files changed, 66 insertions(+), 95 deletions(-) diff --git a/apps/server/src/server/mcp-persona-handlers.ts b/apps/server/src/server/mcp-persona-handlers.ts index 92f071e3b..2e6a46897 100644 --- a/apps/server/src/server/mcp-persona-handlers.ts +++ b/apps/server/src/server/mcp-persona-handlers.ts @@ -183,15 +183,11 @@ export type PreparedPersonaLaunch = { effort: Effort | null; cwd: string; agentArgs: string[]; - fullAccess: boolean; }; /** - * A persona is a profile: instructions plus defaults, applied to an ordinary - * launch. This resolves the profile against the requester's worktree (repo - * personas win over built-ins), assembles the briefing, and - * returns everything `createAgent` needs. Nothing here is review-specific: - * a QA persona, a docs persona and a reviewer all take this path. + * Resolve review personas against the requester's worktree and assemble their + * briefing. Task personas use the ordinary agent launch path. */ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { const { pool, agentManager, publishUiEvent, withStreamFlag } = deps; @@ -200,12 +196,13 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { parent: AgentRecord, opts: PersonaLaunchOptions ): Promise { - const cwd = agentWorkspaceDir(parent) ?? parent.cwd; + const cwd = remotePlacement(parent.cwd) + ? parent.cwd + : (agentWorkspaceDir(parent) ?? parent.cwd); return prepareReviewLaunch( parent, opts, cwd, - parent.fullAccess, () => opts.resolvedPersona ?? resolveRunnerPersona(agentManager, parent, opts.persona) @@ -216,7 +213,6 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { parent: AgentRecord, opts: PersonaLaunchOptions, cwd: string, - fullAccess: boolean, resolvePersona: () => PersonaDefinition | Promise ): Promise { const fallbackReviewType = isCliAgentType(parent.reviewAgentType) @@ -230,15 +226,6 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { if (!CLI_AGENT_TYPES.includes(agentType)) { throw new Error(`Unsupported agent type "${agentType}".`); } - if (agentType === "opencode" && !parent.fullAccess) { - throw new Error( - "Permission denied: a restricted agent cannot launch full-access OpenCode agents." - ); - } - if (agentType === "opencode" && !fullAccess) - throw new Error( - "OpenCode requires full access and cannot run a restricted owner review." - ); const enabledAgentTypes = await getEnabledAgentTypes(pool); if (!enabledAgentTypes.includes(agentType)) { throw new Error(`${agentType} agents are disabled in settings.`); @@ -259,15 +246,8 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { PERSONA_CONTEXT_ARG, prompt, ]; - if (fullAccess) { - const fullAccessArg = - agentType === "claude" - ? CLAUDE_FULL_ACCESS_ARG - : agentType === "codex" - ? CODEX_FULL_ACCESS_ARG - : null; - if (fullAccessArg) agentArgs.push(fullAccessArg); - } + if (agentType === "claude") agentArgs.push(CLAUDE_FULL_ACCESS_ARG); + if (agentType === "codex") agentArgs.push(CODEX_FULL_ACCESS_ARG); return { persona, prompt, @@ -276,7 +256,6 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { effort, cwd, agentArgs, - fullAccess, }; } @@ -291,25 +270,11 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { ) { const parent = await agentManager.getAgent(parentId); if (!parent) throw new Error("Parent agent not found."); - if (remotePlacement(parent.cwd)) { - return launchReviewer( - parent, - opts, - () => - prepareReviewLaunch( - parent, - opts, - parent.cwd, - false, - () => - opts.resolvedPersona ?? - resolveRunnerPersona(agentManager, parent, opts.persona) - ), - parent.id - ); - } - return launchReviewer(parent, opts, () => - preparePersonaLaunch(parent, opts) + return launchReviewer( + parent, + opts, + () => preparePersonaLaunch(parent, opts), + remotePlacement(parent.cwd) ? parent.id : undefined ); } @@ -344,7 +309,9 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { model: prepared.model, effort: prepared.effort, agentArgs: prepared.agentArgs, - fullAccess: prepared.fullAccess, + // Reviews must run unattended, including reviews requested by a + // restricted author. Ordinary child launches keep their access ceiling. + fullAccess: true, useWorktree: false, persona: opts.persona, role: "review", @@ -488,7 +455,6 @@ export function createPersonaHandlers(deps: CreatePersonaHandlersDeps) { author, launchOpts, author.cwd, - false, () => selectedPersonas.get(persona)! ), author.id diff --git a/apps/server/test/mcp-handlers.test.ts b/apps/server/test/mcp-handlers.test.ts index c7acafb3c..b9cec7fcc 100644 --- a/apps/server/test/mcp-handlers.test.ts +++ b/apps/server/test/mcp-handlers.test.ts @@ -595,7 +595,7 @@ describe("createMcpHandlers", () => { parentAgentId: "agt_root", launchedByAgentId: "agt_child", cwd: "/repo", - fullAccess: false, + fullAccess: true, initialPrompt: expect.stringContaining('to: "agt_child"'), }), { detachLaunch: true } @@ -752,15 +752,25 @@ describe("createMcpHandlers", () => { ); }); - it("blocks restricted review-persona launches selecting OpenCode", async () => { - await expect( - handlers.launchAgent("agt_test1", { - persona: "code-review", + it("gives an OpenCode review persona full access for a restricted caller", async () => { + vi.mocked(getEnabledAgentTypes).mockResolvedValue([ + "claude", + "codex", + "opencode", + ]); + await handlers.launchAgent("agt_test1", { + persona: "code-review", + type: "opencode", + prompt: "review", + }); + expect(deps.agentManager.createAgent).toHaveBeenCalledWith( + expect.objectContaining({ type: "opencode", - prompt: "review", - }) - ).rejects.toThrow(/restricted agent cannot launch full-access OpenCode/); - expect(deps.agentManager.createAgent).not.toHaveBeenCalled(); + role: "review", + fullAccess: true, + }), + { detachLaunch: true } + ); }); it("prevents restricted callers from escalating through OpenCode normalization", async () => { diff --git a/apps/server/test/mcp-persona-codeowners.test.ts b/apps/server/test/mcp-persona-codeowners.test.ts index 53b5ec009..cf113d1cd 100644 --- a/apps/server/test/mcp-persona-codeowners.test.ts +++ b/apps/server/test/mcp-persona-codeowners.test.ts @@ -202,7 +202,7 @@ describe("code owner launches through the checkout boundary", () => { parentAgentId: "launcher", launchedByAgentId: "parent", useWorktree: false, - fullAccess: false, + fullAccess: true, initialPrompt: expect.stringContaining('to: "parent"'), agentArgs: expect.arrayContaining([ expect.stringContaining("Verify subsystem contracts"), @@ -255,47 +255,42 @@ describe("code owner launches through the checkout boundary", () => { } ); - it.each(["explicit", "saved"])( - "blocks restricted OpenCode owner reviews selected by %s runtime", - async (selection) => { - const { handlers, agentManager } = setup( - selection === "saved" ? { reviewAgentType: "opencode" } : {} - ); + it.each(["/checkout", "runner://linux/@session"])( + "launches Claude reviewers with full access from a restricted author in %s", + async (cwd) => { + const { handlers, agentManager } = setup({ cwd, type: "claude" }); + await handlers.launchPersonaAgent("parent", { + persona: "owner-one", + context: "Review", + }); const result = await handlers.launchOwnerReviews("parent", { - context: "review", - ...(selection === "explicit" ? { agentType: "opencode" as const } : {}), + context: "Review", + personas: ["owner-one"], }); - expect(result.launched).toHaveLength(0); - expect(result.failures.length).toBeGreaterThan(0); - expect( - result.failures.every((f) => - JSON.stringify(f).includes( - "restricted agent cannot launch full-access OpenCode" - ) - ) - ).toBe(true); - expect(agentManager.createAgent).not.toHaveBeenCalled(); + expect(result.failures).toEqual([]); + expect(agentManager.createAgent).toHaveBeenCalledTimes(2); + for (const [launch] of agentManager.createAgent.mock.calls) { + expect(launch).toMatchObject({ + cwd, + type: "claude", + role: "review", + fullAccess: true, + agentArgs: expect.arrayContaining(["--dangerously-skip-permissions"]), + }); + } } ); - it("blocks restricted direct personas using a saved OpenCode reviewer", async () => { - const { handlers, agentManager } = setup({ reviewAgentType: "opencode" }); - await expect( - handlers.launchPersonaAgent("parent", { - persona: "owner-one", - context: "review", - }) - ).rejects.toThrow(/restricted agent cannot launch full-access OpenCode/); - expect(agentManager.createAgent).not.toHaveBeenCalled(); - }); - it("keeps owner reviews restricted when a full-access author chooses OpenCode", async () => { - const { handlers, agentManager } = setup({ fullAccess: true }); - const result = await handlers.launchOwnerReviews("parent", { + it("launches a saved OpenCode reviewer from a restricted author", async () => { + const { handlers, agentManager } = setup({ reviewAgentType: "opencode" }); + await handlers.launchPersonaAgent("parent", { + persona: "owner-one", context: "Review", - agentType: "opencode", }); - expect(result.failures[0]?.error).toMatch(/requires full access/i); - expect(agentManager.createAgent).not.toHaveBeenCalled(); + expect(agentManager.createAgent).toHaveBeenCalledWith( + expect.objectContaining({ type: "opencode", fullAccess: true }), + { detachLaunch: true } + ); }); it.each([false, true])( @@ -464,7 +459,7 @@ describe("code owner launches through the checkout boundary", () => { ); expect(agentManager.createAgent).toHaveBeenCalledWith( expect.objectContaining({ - fullAccess: false, + fullAccess: true, agentArgs: expect.arrayContaining([ expect.stringContaining(builtin.body.trimEnd()), ]), @@ -533,7 +528,7 @@ describe("code owner launches through the checkout boundary", () => { expect.objectContaining({ cwd: "runner://older/@session", type: "claude", - fullAccess: false, + fullAccess: true, }), { detachLaunch: true, useWorktreeOf: "parent" } ); From cc1c4abbba7703e032f6721f6c93ab67766a7721 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 10:17:47 -0700 Subject: [PATCH 177/642] Close runner HTTP relays after each response Avoid idle pooled TLS sockets around MCP calls. Finish slow and streaming responses before closing, and log relay close direction at debug level. --- apps/server/src/agents/remote/service.ts | 103 ++++++++------- apps/server/src/server.ts | 1 + .../test/remote-runner-enrollment.test.ts | 118 ++++++++++++++---- 3 files changed, 151 insertions(+), 71 deletions(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 897fa2e46..0f8571682 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -8,7 +8,7 @@ import { X509Certificate } from "node:crypto"; import { readFileSync, watchFile, unwatchFile } from "node:fs"; import http from "node:http"; import https from "node:https"; -import { connect as connectTcp, isIP, type Socket } from "node:net"; +import { connect as connectTcp, isIP } from "node:net"; import os from "node:os"; import { createServer, type Server, type TLSSocket } from "node:tls"; import { @@ -20,6 +20,7 @@ export { RunnerHostGone, } from "@dispatch/runner-protocol/connection"; import type { Pool } from "pg"; +import type { FastifyBaseLogger } from "fastify"; import { parseRunnerHealth, type RunnerHealth, @@ -183,7 +184,6 @@ type Peer = { }; const MAX_UNAUTHENTICATED = 64; -const PROXY_KEEP_ALIVE_TIMEOUT = 75_000; function validHost(host: string) { return ( @@ -269,6 +269,7 @@ export function configuredRunner(input?: { host: string; apiPort: number; apiTls: boolean; + logger?: Pick; validAgentToken?: (token: string, agentId: string) => boolean; validJobToken?: (token: string, runId: string, agentId: string) => boolean; }) { @@ -304,7 +305,8 @@ export function configuredRunner(input?: { tls: input.apiTls, validAgentToken: input.validAgentToken, validJobToken: input.validJobToken, - } + }, + input?.logger ) : undefined; } @@ -333,6 +335,10 @@ export class RemoteRunnerService { private port?: number; private readonly proxy: http.Server; private proxyPort?: Promise; + private readonly proxyConnections = new Map< + number, + { release: () => void; requestStarted: boolean; requestsServed: number } + >(); constructor( private readonly legacy?: LegacyConfig, @@ -349,7 +355,8 @@ export class RemoteRunnerService { runId: string, agentId: string ) => boolean; - } + }, + private readonly logger?: Pick ) { if (legacy) { httpsOrigin(legacy.mcpOrigin, "Runner MCP origin"); @@ -369,15 +376,29 @@ export class RemoteRunnerService { // MCP tool calls may legitimately run for a long time. requestTimeout: 0, headersTimeout: 30_000, - // Manage keep-alive below because Bun ignores this option. - keepAliveTimeout: 0, }, (request, response) => { - const firstRequest = this.proxyFirstRequests.get( + const connection = this.proxyConnections.get( request.socket.remotePort! ); - firstRequest?.(); - this.trackProxyRequest(request.socket, response); + if (!connection) { + response.writeHead(400, { connection: "close" }).end(); + return; + } + // Do not dispatch a second (pipelined) request while the first drains. + if (connection.requestStarted) return; + connection.requestStarted = true; + connection.release(); + response.shouldKeepAlive = false; + response.setHeader("connection", "close"); + response.once("finish", () => { + connection.requestsServed++; + // Bun can leave the loopback socket open despite the close header. + // Let the response finish flushing before ending the relay. + setImmediate(() => { + if (!request.socket.destroyed) request.socket.end(); + }); + }); this.forward(request, response); } ); @@ -625,62 +646,52 @@ export class RemoteRunnerService { * http.Server) works the same under Node and Bun. */ private async relay(socket: TLSSocket, head: Buffer, release: () => void) { + const started = performance.now(); + const connection = { release, requestStarted: false, requestsServed: 0 }; + let closedBy: "client" | "proxy" | undefined; + socket.once("end", () => (closedBy ??= "client")); + socket.once("error", () => (closedBy ??= "client")); + socket.once("close", () => { + this.logger?.debug( + { + ageMs: Math.round(performance.now() - started), + requestsServed: connection.requestsServed, + closedBy: closedBy ?? "proxy", + }, + "Runner HTTP relay closed" + ); + }); socket.pause(); try { const port = await this.ensureProxy(); if (socket.destroyed) return; const upstream = connectTcp(port, "127.0.0.1"); - upstream.on("error", () => socket.destroy()); + upstream.once("end", () => (closedBy ??= "proxy")); + upstream.on("error", () => { + closedBy ??= "proxy"; + socket.destroy(); + }); socket.on("close", () => upstream.destroy()); upstream.on("close", () => { - if (!upstream.readableEnded) socket.destroy(); + if (!upstream.readableEnded && !socket.destroyed) { + closedBy ??= "proxy"; + socket.destroy(); + } }); upstream.once("connect", () => { const relayPort = upstream.localPort!; - this.proxyFirstRequests.set(relayPort, () => { - this.proxyFirstRequests.delete(relayPort); - release(); - }); - upstream.once("close", () => this.proxyFirstRequests.delete(relayPort)); + this.proxyConnections.set(relayPort, connection); + upstream.once("close", () => this.proxyConnections.delete(relayPort)); upstream.write(head); socket.pipe(upstream).pipe(socket); socket.resume(); }); } catch { + closedBy ??= "proxy"; socket.destroy(); } } - private readonly proxyIdleTimeout = PROXY_KEEP_ALIVE_TIMEOUT; - private readonly proxyFirstRequests = new Map void>(); - private readonly proxyRequests = new WeakMap< - Socket, - { pending: number; idleTimer?: ReturnType } - >(); - - private trackProxyRequest(socket: Socket, response: http.ServerResponse) { - let entry = this.proxyRequests.get(socket); - if (!entry) { - const state: { - pending: number; - idleTimer?: ReturnType; - } = { pending: 0 }; - socket.once("close", () => clearTimeout(state.idleTimer)); - this.proxyRequests.set(socket, state); - entry = state; - } - clearTimeout(entry.idleTimer); - entry.pending++; - const state = entry; - response.once("finish", () => { - if (--state.pending === 0) - state.idleTimer = setTimeout( - () => socket.end(), - this.proxyIdleTimeout - ).unref(); - }); - } - private ensureProxy() { this.proxyPort ??= new Promise((resolve, reject) => { this.proxy.once("error", reject); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 600e7b6c0..d79baf58d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -228,6 +228,7 @@ const remoteRunner = configuredRunner({ host: config.listenHosts?.[0] ?? config.host, apiPort: config.port, apiTls: Boolean(config.tls), + logger: app.log, // authToken is resolved at startup; read it per request. validAgentToken: (token, agentId) => validateAgentMcpToken(config.authToken, token, agentId), diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 852829e5a..e53e1569a 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -5,7 +5,15 @@ import https from "node:https"; import type { AddressInfo } from "node:net"; import { connect, createServer, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; -import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from "vitest"; import { exchangeCode } from "../src/agents/remote/enrollment.js"; import { wireFrames, @@ -998,32 +1006,56 @@ describe("runner enrollment service", () => { }); }); -it("releases the handshake slot for HTTP and closes the idle relay cleanly", async () => { +it("closes each relayed HTTP connection after its entire response", async () => { const authority = issueAuthority("relay-test"); const leaf = issueServer(authority, [HOST]); let requests = 0; const api = http.createServer((_request, response) => { - const delay = requests++ === 0 ? 0 : 150; - setTimeout(() => response.end("ok"), delay); + if (requests++ === 0) { + response.setHeader("Connection", "keep-alive"); + response.end("ok"); + return; + } + // Simulate both a silent tool call and a streamed response that stays open. + setTimeout(() => { + response.write("first "); + setTimeout(() => response.end("last"), 100); + }, 2_500); }); api.listen(0, HOST); await once(api, "listening"); - const service = new RemoteRunnerService(undefined, undefined, { - host: HOST, - port: (api.address() as AddressInfo).port, - tls: false, - }); - const listener = createServer({ cert: leaf.cert, key: leaf.key }, (socket) => - service["accept"](socket, "legacy") + const debug = vi.fn(); + const service = new RemoteRunnerService( + undefined, + undefined, + { host: HOST, port: (api.address() as AddressInfo).port, tls: false }, + { debug } + ); + const listener = createServer( + { + cert: leaf.cert, + key: leaf.key, + requestCert: true, + rejectUnauthorized: false, + }, + (socket) => service["accept"](socket, "legacy") ); listener.listen(0, HOST); await once(listener, "listening"); - const agent = new https.Agent({ keepAlive: true, ca: authority.cert }); + const agent = new https.Agent({ + keepAlive: true, + maxSockets: 1, + ca: authority.cert, + }); try { - expect(service["proxyIdleTimeout"]).toBeGreaterThan(60_000); - Object.defineProperty(service, "proxyIdleTimeout", { value: 100 }); - const ping = () => - new Promise((resolve, reject) => { + function ping() { + return new Promise<{ + socket: TLSSocket; + closed: Promise; + status?: number; + connection?: string; + body: string; + }>((resolve, reject) => { const request = https.get( { host: HOST, @@ -1032,27 +1064,63 @@ it("releases the handshake slot for HTTP and closes the idle relay cleanly", asy agent, }, (response) => { - const connection = response.socket as TLSSocket; - response.resume(); - response.once("end", () => resolve(connection)); + const socket = response.socket as TLSSocket; + const closed = new Promise((done) => + socket.once("close", done) + ); + let body = ""; + response.setEncoding("utf8"); + response.on("data", (chunk: string) => (body += chunk)); + response.once("end", () => + resolve({ + socket, + closed, + status: response.statusCode, + connection: response.headers.connection, + body, + }) + ); response.once("error", reject); } ); request.on("error", reject); }); - const socket = await ping(); + } + const first = await ping(); + expect(first).toMatchObject({ + status: 200, + connection: "close", + body: "ok", + }); expect(service["unauthenticated"]).toBe(0); - expect(await ping()).toBe(socket); - expect(socket.destroyed).toBe(false); - const [hadError] = await once(socket, "close"); - expect(hadError).toBe(false); + const second = await ping(); + expect(second.socket).not.toBe(first.socket); + expect(second).toMatchObject({ + status: 200, + connection: "close", + body: "first last", + }); + expect(await first.closed).toBe(false); + expect(await second.closed).toBe(false); + expect(requests).toBe(2); + await vi.waitFor(() => expect(debug).toHaveBeenCalledTimes(2)); + for (const call of debug.mock.calls) { + expect(call).toEqual([ + expect.objectContaining({ + ageMs: expect.any(Number), + requestsServed: 1, + closedBy: "proxy", + }), + "Runner HTTP relay closed", + ]); + } } finally { agent.destroy(); service.close(); listener.close(); api.close(); } -}); +}, 10_000); describe("legacy runner config", () => { it("keeps its locator and gates MCP on the live approval file", async () => { From 65e58ea298575d5e1669bdcabcc9f9cd36399278 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 10:33:44 -0700 Subject: [PATCH 178/642] Revert "Close runner HTTP relays after each response" This reverts commit cc1c4abbba7703e032f6721f6c93ab67766a7721. --- apps/server/src/agents/remote/service.ts | 103 +++++++-------- apps/server/src/server.ts | 1 - .../test/remote-runner-enrollment.test.ts | 118 ++++-------------- 3 files changed, 71 insertions(+), 151 deletions(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 0f8571682..897fa2e46 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -8,7 +8,7 @@ import { X509Certificate } from "node:crypto"; import { readFileSync, watchFile, unwatchFile } from "node:fs"; import http from "node:http"; import https from "node:https"; -import { connect as connectTcp, isIP } from "node:net"; +import { connect as connectTcp, isIP, type Socket } from "node:net"; import os from "node:os"; import { createServer, type Server, type TLSSocket } from "node:tls"; import { @@ -20,7 +20,6 @@ export { RunnerHostGone, } from "@dispatch/runner-protocol/connection"; import type { Pool } from "pg"; -import type { FastifyBaseLogger } from "fastify"; import { parseRunnerHealth, type RunnerHealth, @@ -184,6 +183,7 @@ type Peer = { }; const MAX_UNAUTHENTICATED = 64; +const PROXY_KEEP_ALIVE_TIMEOUT = 75_000; function validHost(host: string) { return ( @@ -269,7 +269,6 @@ export function configuredRunner(input?: { host: string; apiPort: number; apiTls: boolean; - logger?: Pick; validAgentToken?: (token: string, agentId: string) => boolean; validJobToken?: (token: string, runId: string, agentId: string) => boolean; }) { @@ -305,8 +304,7 @@ export function configuredRunner(input?: { tls: input.apiTls, validAgentToken: input.validAgentToken, validJobToken: input.validJobToken, - }, - input?.logger + } ) : undefined; } @@ -335,10 +333,6 @@ export class RemoteRunnerService { private port?: number; private readonly proxy: http.Server; private proxyPort?: Promise; - private readonly proxyConnections = new Map< - number, - { release: () => void; requestStarted: boolean; requestsServed: number } - >(); constructor( private readonly legacy?: LegacyConfig, @@ -355,8 +349,7 @@ export class RemoteRunnerService { runId: string, agentId: string ) => boolean; - }, - private readonly logger?: Pick + } ) { if (legacy) { httpsOrigin(legacy.mcpOrigin, "Runner MCP origin"); @@ -376,29 +369,15 @@ export class RemoteRunnerService { // MCP tool calls may legitimately run for a long time. requestTimeout: 0, headersTimeout: 30_000, + // Manage keep-alive below because Bun ignores this option. + keepAliveTimeout: 0, }, (request, response) => { - const connection = this.proxyConnections.get( + const firstRequest = this.proxyFirstRequests.get( request.socket.remotePort! ); - if (!connection) { - response.writeHead(400, { connection: "close" }).end(); - return; - } - // Do not dispatch a second (pipelined) request while the first drains. - if (connection.requestStarted) return; - connection.requestStarted = true; - connection.release(); - response.shouldKeepAlive = false; - response.setHeader("connection", "close"); - response.once("finish", () => { - connection.requestsServed++; - // Bun can leave the loopback socket open despite the close header. - // Let the response finish flushing before ending the relay. - setImmediate(() => { - if (!request.socket.destroyed) request.socket.end(); - }); - }); + firstRequest?.(); + this.trackProxyRequest(request.socket, response); this.forward(request, response); } ); @@ -646,52 +625,62 @@ export class RemoteRunnerService { * http.Server) works the same under Node and Bun. */ private async relay(socket: TLSSocket, head: Buffer, release: () => void) { - const started = performance.now(); - const connection = { release, requestStarted: false, requestsServed: 0 }; - let closedBy: "client" | "proxy" | undefined; - socket.once("end", () => (closedBy ??= "client")); - socket.once("error", () => (closedBy ??= "client")); - socket.once("close", () => { - this.logger?.debug( - { - ageMs: Math.round(performance.now() - started), - requestsServed: connection.requestsServed, - closedBy: closedBy ?? "proxy", - }, - "Runner HTTP relay closed" - ); - }); socket.pause(); try { const port = await this.ensureProxy(); if (socket.destroyed) return; const upstream = connectTcp(port, "127.0.0.1"); - upstream.once("end", () => (closedBy ??= "proxy")); - upstream.on("error", () => { - closedBy ??= "proxy"; - socket.destroy(); - }); + upstream.on("error", () => socket.destroy()); socket.on("close", () => upstream.destroy()); upstream.on("close", () => { - if (!upstream.readableEnded && !socket.destroyed) { - closedBy ??= "proxy"; - socket.destroy(); - } + if (!upstream.readableEnded) socket.destroy(); }); upstream.once("connect", () => { const relayPort = upstream.localPort!; - this.proxyConnections.set(relayPort, connection); - upstream.once("close", () => this.proxyConnections.delete(relayPort)); + this.proxyFirstRequests.set(relayPort, () => { + this.proxyFirstRequests.delete(relayPort); + release(); + }); + upstream.once("close", () => this.proxyFirstRequests.delete(relayPort)); upstream.write(head); socket.pipe(upstream).pipe(socket); socket.resume(); }); } catch { - closedBy ??= "proxy"; socket.destroy(); } } + private readonly proxyIdleTimeout = PROXY_KEEP_ALIVE_TIMEOUT; + private readonly proxyFirstRequests = new Map void>(); + private readonly proxyRequests = new WeakMap< + Socket, + { pending: number; idleTimer?: ReturnType } + >(); + + private trackProxyRequest(socket: Socket, response: http.ServerResponse) { + let entry = this.proxyRequests.get(socket); + if (!entry) { + const state: { + pending: number; + idleTimer?: ReturnType; + } = { pending: 0 }; + socket.once("close", () => clearTimeout(state.idleTimer)); + this.proxyRequests.set(socket, state); + entry = state; + } + clearTimeout(entry.idleTimer); + entry.pending++; + const state = entry; + response.once("finish", () => { + if (--state.pending === 0) + state.idleTimer = setTimeout( + () => socket.end(), + this.proxyIdleTimeout + ).unref(); + }); + } + private ensureProxy() { this.proxyPort ??= new Promise((resolve, reject) => { this.proxy.once("error", reject); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d79baf58d..600e7b6c0 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -228,7 +228,6 @@ const remoteRunner = configuredRunner({ host: config.listenHosts?.[0] ?? config.host, apiPort: config.port, apiTls: Boolean(config.tls), - logger: app.log, // authToken is resolved at startup; read it per request. validAgentToken: (token, agentId) => validateAgentMcpToken(config.authToken, token, agentId), diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index e53e1569a..852829e5a 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -5,15 +5,7 @@ import https from "node:https"; import type { AddressInfo } from "node:net"; import { connect, createServer, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; -import { - afterAll, - afterEach, - beforeAll, - describe, - expect, - it, - vi, -} from "vitest"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { exchangeCode } from "../src/agents/remote/enrollment.js"; import { wireFrames, @@ -1006,56 +998,32 @@ describe("runner enrollment service", () => { }); }); -it("closes each relayed HTTP connection after its entire response", async () => { +it("releases the handshake slot for HTTP and closes the idle relay cleanly", async () => { const authority = issueAuthority("relay-test"); const leaf = issueServer(authority, [HOST]); let requests = 0; const api = http.createServer((_request, response) => { - if (requests++ === 0) { - response.setHeader("Connection", "keep-alive"); - response.end("ok"); - return; - } - // Simulate both a silent tool call and a streamed response that stays open. - setTimeout(() => { - response.write("first "); - setTimeout(() => response.end("last"), 100); - }, 2_500); + const delay = requests++ === 0 ? 0 : 150; + setTimeout(() => response.end("ok"), delay); }); api.listen(0, HOST); await once(api, "listening"); - const debug = vi.fn(); - const service = new RemoteRunnerService( - undefined, - undefined, - { host: HOST, port: (api.address() as AddressInfo).port, tls: false }, - { debug } - ); - const listener = createServer( - { - cert: leaf.cert, - key: leaf.key, - requestCert: true, - rejectUnauthorized: false, - }, - (socket) => service["accept"](socket, "legacy") + const service = new RemoteRunnerService(undefined, undefined, { + host: HOST, + port: (api.address() as AddressInfo).port, + tls: false, + }); + const listener = createServer({ cert: leaf.cert, key: leaf.key }, (socket) => + service["accept"](socket, "legacy") ); listener.listen(0, HOST); await once(listener, "listening"); - const agent = new https.Agent({ - keepAlive: true, - maxSockets: 1, - ca: authority.cert, - }); + const agent = new https.Agent({ keepAlive: true, ca: authority.cert }); try { - function ping() { - return new Promise<{ - socket: TLSSocket; - closed: Promise; - status?: number; - connection?: string; - body: string; - }>((resolve, reject) => { + expect(service["proxyIdleTimeout"]).toBeGreaterThan(60_000); + Object.defineProperty(service, "proxyIdleTimeout", { value: 100 }); + const ping = () => + new Promise((resolve, reject) => { const request = https.get( { host: HOST, @@ -1064,63 +1032,27 @@ it("closes each relayed HTTP connection after its entire response", async () => agent, }, (response) => { - const socket = response.socket as TLSSocket; - const closed = new Promise((done) => - socket.once("close", done) - ); - let body = ""; - response.setEncoding("utf8"); - response.on("data", (chunk: string) => (body += chunk)); - response.once("end", () => - resolve({ - socket, - closed, - status: response.statusCode, - connection: response.headers.connection, - body, - }) - ); + const connection = response.socket as TLSSocket; + response.resume(); + response.once("end", () => resolve(connection)); response.once("error", reject); } ); request.on("error", reject); }); - } - const first = await ping(); - expect(first).toMatchObject({ - status: 200, - connection: "close", - body: "ok", - }); + const socket = await ping(); expect(service["unauthenticated"]).toBe(0); - const second = await ping(); - expect(second.socket).not.toBe(first.socket); - expect(second).toMatchObject({ - status: 200, - connection: "close", - body: "first last", - }); - expect(await first.closed).toBe(false); - expect(await second.closed).toBe(false); - expect(requests).toBe(2); - await vi.waitFor(() => expect(debug).toHaveBeenCalledTimes(2)); - for (const call of debug.mock.calls) { - expect(call).toEqual([ - expect.objectContaining({ - ageMs: expect.any(Number), - requestsServed: 1, - closedBy: "proxy", - }), - "Runner HTTP relay closed", - ]); - } + expect(await ping()).toBe(socket); + expect(socket.destroyed).toBe(false); + const [hadError] = await once(socket, "close"); + expect(hadError).toBe(false); } finally { agent.destroy(); service.close(); listener.close(); api.close(); } -}, 10_000); +}); describe("legacy runner config", () => { it("keeps its locator and gates MCP on the live approval file", async () => { From dba1ee78af06b166ea796ca04c8e5bb574b76ed7 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 10:35:38 -0700 Subject: [PATCH 179/642] Log runner relay closures at debug level Record relay age, completed requests, and the first closing side while leaving the working keep-alive behavior in place. --- apps/server/src/agents/remote/service.ts | 59 ++++++++++++++----- apps/server/src/server.ts | 1 + .../test/remote-runner-enrollment.test.ts | 28 +++++++-- 3 files changed, 68 insertions(+), 20 deletions(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 897fa2e46..c93e75217 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -20,6 +20,7 @@ export { RunnerHostGone, } from "@dispatch/runner-protocol/connection"; import type { Pool } from "pg"; +import type { FastifyBaseLogger } from "fastify"; import { parseRunnerHealth, type RunnerHealth, @@ -269,6 +270,7 @@ export function configuredRunner(input?: { host: string; apiPort: number; apiTls: boolean; + logger?: Pick; validAgentToken?: (token: string, agentId: string) => boolean; validJobToken?: (token: string, runId: string, agentId: string) => boolean; }) { @@ -304,7 +306,8 @@ export function configuredRunner(input?: { tls: input.apiTls, validAgentToken: input.validAgentToken, validJobToken: input.validJobToken, - } + }, + input?.logger ) : undefined; } @@ -349,7 +352,8 @@ export class RemoteRunnerService { runId: string, agentId: string ) => boolean; - } + }, + private readonly logger?: Pick ) { if (legacy) { httpsOrigin(legacy.mcpOrigin, "Runner MCP origin"); @@ -373,10 +377,12 @@ export class RemoteRunnerService { keepAliveTimeout: 0, }, (request, response) => { - const firstRequest = this.proxyFirstRequests.get( - request.socket.remotePort! - ); - firstRequest?.(); + const relay = this.proxyRelays.get(request.socket.remotePort!); + if (relay) { + relay.firstRequest?.(); + relay.firstRequest = undefined; + response.once("finish", () => relay.requestsServed++); + } this.trackProxyRequest(request.socket, response); this.forward(request, response); } @@ -625,23 +631,45 @@ export class RemoteRunnerService { * http.Server) works the same under Node and Bun. */ private async relay(socket: TLSSocket, head: Buffer, release: () => void) { + const started = performance.now(); + const relay: { firstRequest?: () => void; requestsServed: number } = { + firstRequest: release, + requestsServed: 0, + }; + let closedBy: "client" | "proxy" | undefined; + socket.once("end", () => (closedBy ??= "client")); + socket.once("error", () => (closedBy ??= "client")); + socket.once("close", () => { + this.logger?.debug( + { + ageMs: Math.round(performance.now() - started), + requestsServed: relay.requestsServed, + closedBy: closedBy ?? "proxy", + }, + "Runner HTTP relay closed" + ); + }); socket.pause(); try { const port = await this.ensureProxy(); if (socket.destroyed) return; const upstream = connectTcp(port, "127.0.0.1"); - upstream.on("error", () => socket.destroy()); + upstream.once("end", () => (closedBy ??= "proxy")); + upstream.on("error", () => { + closedBy ??= "proxy"; + socket.destroy(); + }); socket.on("close", () => upstream.destroy()); upstream.on("close", () => { - if (!upstream.readableEnded) socket.destroy(); + if (!upstream.readableEnded && !socket.destroyed) { + closedBy ??= "proxy"; + socket.destroy(); + } }); upstream.once("connect", () => { const relayPort = upstream.localPort!; - this.proxyFirstRequests.set(relayPort, () => { - this.proxyFirstRequests.delete(relayPort); - release(); - }); - upstream.once("close", () => this.proxyFirstRequests.delete(relayPort)); + this.proxyRelays.set(relayPort, relay); + upstream.once("close", () => this.proxyRelays.delete(relayPort)); upstream.write(head); socket.pipe(upstream).pipe(socket); socket.resume(); @@ -652,7 +680,10 @@ export class RemoteRunnerService { } private readonly proxyIdleTimeout = PROXY_KEEP_ALIVE_TIMEOUT; - private readonly proxyFirstRequests = new Map void>(); + private readonly proxyRelays = new Map< + number, + { firstRequest?: () => void; requestsServed: number } + >(); private readonly proxyRequests = new WeakMap< Socket, { pending: number; idleTimer?: ReturnType } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 600e7b6c0..d79baf58d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -228,6 +228,7 @@ const remoteRunner = configuredRunner({ host: config.listenHosts?.[0] ?? config.host, apiPort: config.port, apiTls: Boolean(config.tls), + logger: app.log, // authToken is resolved at startup; read it per request. validAgentToken: (token, agentId) => validateAgentMcpToken(config.authToken, token, agentId), diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 852829e5a..e7ae2d2ab 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -5,7 +5,15 @@ import https from "node:https"; import type { AddressInfo } from "node:net"; import { connect, createServer, type TLSSocket } from "node:tls"; import type { Pool } from "pg"; -import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, +} from "vitest"; import { exchangeCode } from "../src/agents/remote/enrollment.js"; import { wireFrames, @@ -1008,11 +1016,13 @@ it("releases the handshake slot for HTTP and closes the idle relay cleanly", asy }); api.listen(0, HOST); await once(api, "listening"); - const service = new RemoteRunnerService(undefined, undefined, { - host: HOST, - port: (api.address() as AddressInfo).port, - tls: false, - }); + const debug = vi.fn(); + const service = new RemoteRunnerService( + undefined, + undefined, + { host: HOST, port: (api.address() as AddressInfo).port, tls: false }, + { debug } + ); const listener = createServer({ cert: leaf.cert, key: leaf.key }, (socket) => service["accept"](socket, "legacy") ); @@ -1046,6 +1056,12 @@ it("releases the handshake slot for HTTP and closes the idle relay cleanly", asy expect(socket.destroyed).toBe(false); const [hadError] = await once(socket, "close"); expect(hadError).toBe(false); + await vi.waitFor(() => + expect(debug).toHaveBeenCalledExactlyOnceWith( + { ageMs: expect.any(Number), requestsServed: 2, closedBy: "proxy" }, + "Runner HTTP relay closed" + ) + ); } finally { agent.destroy(); service.close(); From 7742c13e8b9332ed4461b1f053c52945e72367fb Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 10:41:58 -0700 Subject: [PATCH 180/642] Route resumed anonymous TLS sessions to runner HTTP Require a client certificate for runner peer authentication. Bun can report an anonymous TLS resumption as authorized, causing the listener to reset valid HTTP requests before reading them. --- apps/server/src/agents/remote/service.ts | 4 +- .../test/remote-runner-enrollment.test.ts | 89 ++++++++++++++----- 2 files changed, 72 insertions(+), 21 deletions(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index c93e75217..1a412c09f 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -597,7 +597,9 @@ export class RemoteRunnerService { socket.on("error", () => socket.destroy()); this.sockets.add(socket); socket.on("close", () => this.sockets.delete(socket)); - if (socket.authorized) { + // Bun can mark a resumed TLS session authorized even when the client + // never presented a certificate. Only certificate peers use runner RPC. + if (socket.authorized && socket.getPeerCertificate()?.fingerprint256) { const gate = this.gateFor(socket, kind); return gate ? this.attachPeer(socket, gate) : socket.destroy(); } diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index e7ae2d2ab..38a09eb99 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -1006,13 +1006,28 @@ describe("runner enrollment service", () => { }); }); -it("releases the handshake slot for HTTP and closes the idle relay cleanly", async () => { +it("relays complete HTTP responses on a resumed connection without a client certificate", async () => { const authority = issueAuthority("relay-test"); const leaf = issueServer(authority, [HOST]); - let requests = 0; - const api = http.createServer((_request, response) => { - const delay = requests++ === 0 ? 0 : 150; - setTimeout(() => response.end("ok"), delay); + const requests: string[] = []; + const api = http.createServer((request, response) => { + requests.push(request.method ?? ""); + const status = request.method === "POST" ? 400 : 405; + const body = JSON.stringify({ + error: + status === 400 ? "Unsupported protocol version" : "Method not allowed", + }); + setTimeout( + () => { + response.writeHead(status, { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(body), + Connection: "close", + }); + response.end(body); + }, + status === 400 ? 0 : 150 + ); }); api.listen(0, HOST); await once(api, "listening"); @@ -1020,11 +1035,27 @@ it("releases the handshake slot for HTTP and closes the idle relay cleanly", asy const service = new RemoteRunnerService( undefined, undefined, - { host: HOST, port: (api.address() as AddressInfo).port, tls: false }, + { + host: HOST, + port: (api.address() as AddressInfo).port, + tls: false, + validAgentToken: (token, id) => + token === "agent-token" && id === "agt_probe", + }, { debug } ); - const listener = createServer({ cert: leaf.cert, key: leaf.key }, (socket) => - service["accept"](socket, "legacy") + const listener = createServer( + { + cert: leaf.cert, + key: leaf.key, + requestCert: true, + rejectUnauthorized: false, + }, + (socket) => { + // Bun reports an anonymous TLS resumption as authorized without a cert. + socket.authorized = true; + service["accept"](socket, "legacy"); + } ); listener.listen(0, HOST); await once(listener, "listening"); @@ -1032,30 +1063,48 @@ it("releases the handshake slot for HTTP and closes the idle relay cleanly", asy try { expect(service["proxyIdleTimeout"]).toBeGreaterThan(60_000); Object.defineProperty(service, "proxyIdleTimeout", { value: 100 }); - const ping = () => - new Promise((resolve, reject) => { - const request = https.get( + const call = (method: string) => + new Promise<{ + socket: TLSSocket; + status: number | undefined; + body: string; + }>((resolve, reject) => { + const request = https.request( { host: HOST, port: (listener.address() as AddressInfo).port, - path: "/ping", + path: "/api/mcp/agt_probe", + method, + headers: { Authorization: "Bearer agent-token" }, agent, }, (response) => { - const connection = response.socket as TLSSocket; - response.resume(); - response.once("end", () => resolve(connection)); + const socket = response.socket as TLSSocket; + let body = ""; + response.setEncoding("utf8"); + response.on("data", (chunk: string) => (body += chunk)); + response.once("end", () => + resolve({ socket, status: response.statusCode, body }) + ); response.once("error", reject); } ); request.on("error", reject); + request.end(); }); - const socket = await ping(); + const first = await call("POST"); + expect(first.status).toBe(400); + expect(JSON.parse(first.body)).toEqual({ + error: "Unsupported protocol version", + }); expect(service["unauthenticated"]).toBe(0); - expect(await ping()).toBe(socket); - expect(socket.destroyed).toBe(false); - const [hadError] = await once(socket, "close"); - expect(hadError).toBe(false); + const close = once(first.socket, "close"); + const second = await call("GET"); + expect(second.socket).toBe(first.socket); + expect(second.status).toBe(405); + expect(JSON.parse(second.body)).toEqual({ error: "Method not allowed" }); + expect(requests).toEqual(["POST", "GET"]); + expect(await close).toEqual([false]); await vi.waitFor(() => expect(debug).toHaveBeenCalledExactlyOnceWith( { ageMs: expect.any(Number), requestsServed: 2, closedBy: "proxy" }, From 390e1953b8048778e235cb390bba1c6c4aef3e5e Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 11:08:49 -0700 Subject: [PATCH 181/642] Classify fragmented runner HTTP prefixes Keep a bounded prefix until it can be routed, preserving the handshake deadline and original request bytes. --- apps/server/src/agents/remote/service.ts | 30 ++++-- .../test/remote-runner-enrollment.test.ts | 97 +++++++++++++++++++ 2 files changed, 119 insertions(+), 8 deletions(-) diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 1a412c09f..356c789e0 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -613,18 +613,32 @@ export class RemoteRunnerService { this.unauthenticated--; }; socket.once("close", release); - socket.once("data", (chunk: Buffer) => { - if (chunk[0] === 0x7b && kind === "enrolled") { + let prefix = ""; + const classify = (chunk: Buffer) => { + if (!prefix && chunk[0] === 0x7b && kind === "enrolled") { + socket.off("data", classify); socket.pause(); socket.unshift(chunk); this.pair(socket); socket.resume(); - } else if ( - /^[A-Z]{3,7} \//.test(chunk.subarray(0, 9).toString("latin1")) - ) { - void this.relay(socket, chunk, release); - } else socket.destroy(); - }); + return; + } + // Inspect at most seven method letters, a space and a slash. Keep only + // a prefix that could become valid, with the original deadline running. + const candidate = prefix + chunk.toString("latin1", 0, 9 - prefix.length); + if (/^[A-Z]{3,7} \//.test(candidate)) { + socket.off("data", classify); + const head = prefix + ? Buffer.concat([Buffer.from(prefix, "latin1"), chunk]) + : chunk; + void this.relay(socket, head, release); + } else if (/^(?:[A-Z]{1,7}|[A-Z]{3,7} )$/.test(candidate)) { + prefix = candidate; + } else { + socket.destroy(); + } + }; + socket.on("data", classify); } /** diff --git a/apps/server/test/remote-runner-enrollment.test.ts b/apps/server/test/remote-runner-enrollment.test.ts index 38a09eb99..0a9e6e24b 100644 --- a/apps/server/test/remote-runner-enrollment.test.ts +++ b/apps/server/test/remote-runner-enrollment.test.ts @@ -4,6 +4,7 @@ import http from "node:http"; import https from "node:https"; import type { AddressInfo } from "node:net"; import { connect, createServer, type TLSSocket } from "node:tls"; +import { setTimeout as delay } from "node:timers/promises"; import type { Pool } from "pg"; import { afterAll, @@ -1119,6 +1120,102 @@ it("relays complete HTTP responses on a resumed connection without a client cert } }); +describe("runner listener request prefixes", () => { + const authority = issueAuthority("prefix-test"); + let api: http.Server; + let listener: ReturnType; + let service: RemoteRunnerService; + + beforeAll(async () => { + api = http.createServer((_request, response) => response.end("ping ok")); + api.listen(0, HOST); + await once(api, "listening"); + service = new RemoteRunnerService(undefined, undefined, { + host: HOST, + port: (api.address() as AddressInfo).port, + tls: false, + validAgentToken: () => false, + }); + const leaf = issueServer(authority, [HOST]); + service["authority"] = { + caFingerprint: new X509Certificate(authority.cert).fingerprint256, + caPem: authority.cert, + serverCert: leaf.cert, + }; + listener = createServer({ cert: leaf.cert, key: leaf.key }, (socket) => + service["accept"](socket, "enrolled") + ); + listener.listen(0, HOST); + await once(listener, "listening"); + }); + + afterAll(() => { + service.close(); + listener.close(); + api.close(); + }); + + async function dial() { + const socket = connect({ + host: HOST, + port: (listener.address() as AddressInfo).port, + ca: authority.cert, + }); + await once(socket, "secureConnect"); + return socket; + } + + async function exchange(chunks: string[], interval: number) { + const socket = await dial(); + let response = ""; + socket.setEncoding("utf8"); + socket.on("data", (chunk) => (response += chunk)); + const closed = once(socket, "close"); + try { + for (const [index, chunk] of chunks.entries()) { + if (index > 0) await delay(interval); + if (socket.destroyed) break; + socket.write(chunk); + } + await closed; + return response; + } finally { + socket.destroy(); + } + } + + const rest = "ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; + it.each([ + { chunks: ["GE", "T /" + rest], interval: 150 }, + { chunks: [..."GET /", rest], interval: 20 }, + ])("relays a fragmented HTTP request (%j)", async ({ chunks, interval }) => { + expect(await exchange(chunks, interval)).toMatch( + /^HTTP\/1\.1 200 OK[\s\S]*\r\n\r\nping ok$/ + ); + }); + + it.each(["nope", "G ", "ABCDEFGH", "GET x"])( + "drops a prefix that cannot become an HTTP request (%s)", + async (prefix) => { + expect(await exchange([prefix], 0)).toBe(""); + } + ); + + it("drops an idle incomplete prefix at the original deadline", async () => { + const started = performance.now(); + expect(await exchange(["G", "E"], 150)).toBe(""); + expect(performance.now() - started).toBeGreaterThanOrEqual(9_500); + }, 15_000); + + it("reads a pairing frame split after its leading brace", async () => { + const reply = await exchange( + ["{", '"type":"ca_request","version":1}\n'], + 50 + ); + expect(JSON.parse(reply)).toEqual({ type: "ca", ca: authority.cert }); + }); +}); + describe("legacy runner config", () => { it("keeps its locator and gates MCP on the live approval file", async () => { const { mkdtemp, writeFile } = await import("node:fs/promises"); From 9d69d9ab704965642dd7424ec68bcdc78f00e283 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Fri, 20 Nov 2026 11:14:10 -0700 Subject: [PATCH 182/642] Keep model picker labels visible after selection changes Render the selected label directly in the trigger and wait for catalog readiness in template tests now that the picker opens while loading. --- apps/web/src/components/app/agent-model-select.tsx | 13 +++++-------- .../app/automations-launch-dialog.test.tsx | 6 +++++- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/app/agent-model-select.tsx b/apps/web/src/components/app/agent-model-select.tsx index 3e868e44a..9b5b97527 100644 --- a/apps/web/src/components/app/agent-model-select.tsx +++ b/apps/web/src/components/app/agent-model-select.tsx @@ -31,8 +31,9 @@ export function AgentModelSelect({ testId = "create-agent-model", }: AgentModelSelectProps): JSX.Element { const fallback = catalogDefault ?? DEFAULT_VALUE; - const selectedValue = - value && options.some((option) => option.id === value) ? value : fallback; + const selected = + options.find((option) => option.id === value) ?? + options.find((option) => option.id === fallback); return (
    @@ -40,7 +41,7 @@ export function AgentModelSelect({ Model { // Radix's hidden form input echoes an empty value back through // onValueChange when its native
    )} - {updateAvailable && target.command && ( + {updateAvailable && target.command && !updatesItself(runner) && (
    diff --git a/apps/web/src/components/app/runner-settings.test.tsx b/apps/web/src/components/app/runner-settings.test.tsx index 963c66165..c422eada9 100644 --- a/apps/web/src/components/app/runner-settings.test.tsx +++ b/apps/web/src/components/app/runner-settings.test.tsx @@ -20,7 +20,10 @@ import type { Runner } from "@/hooks/use-runners"; import { api } from "@/lib/api"; import { RunnerSettings } from "./runner-settings"; -vi.mock("@/lib/api", () => ({ api: vi.fn() })); +vi.mock("@/lib/api", () => ({ + api: vi.fn(), + ApiError: class extends Error {}, +})); vi.mock("./runner-github-account", () => ({ RunnerGitHubAccount: ({ runner }: { runner: Runner }) => (

    GitHub for {runner.name}

    @@ -404,3 +407,42 @@ it("clears the displayed revoked runners and shows the empty roster", async () = screen.queryByRole("button", { name: "Clear revoked runners" }) ).toBeNull(); }); + +it("polls faster while a selected runner updates and offers the action in its detail", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + let reads = 0; + vi.mocked(api).mockImplementation(async (path) => { + if (path !== "/api/runners") return {} as never; + reads++; + return { + runners: [ + reads === 1 + ? { + ...online, + engineManagement: false, + update: { attempt: { id: "a", phase: "staging" } }, + } + : { + ...online, + engineManagement: false, + update: { available: { version: "1.8.0", action: "update" } }, + }, + ], + } as never; + }); + renderSettings("/settings/runners?runner=build"); + expect(await screen.findByText("Runner update in progress")).toBeTruthy(); + await act(async () => { + await vi.advanceTimersByTimeAsync(2_100); + }); + expect(await screen.findByTestId("runner-update-build")).toBeTruthy(); + const readsAfterUpdate = reads; + await act(async () => { + await vi.advanceTimersByTimeAsync(2_100); + }); + expect(reads).toBe(readsAfterUpdate); + } finally { + vi.useRealTimers(); + } +}); diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index ee2692762..79552550a 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -36,6 +36,7 @@ import { cn } from "@/lib/utils"; import { RunnerGitHubAccount } from "./runner-github-account"; import { isRunnerHealthFresh, RunnerHealthDetails } from "./runner-health"; import { RunnerOnboarding, RunnerPairingRequests } from "./runner-onboarding"; +import { RunnerUpdateStatus } from "./runner-update"; const STATUS_LABEL: Record = { pending: "Waiting to pair", @@ -408,6 +409,7 @@ function RunnerDetail({
    + {runner.workspaces.length > 0 && !runner.managedWorkspace && (

    diff --git a/apps/web/src/components/app/runner-update.test.tsx b/apps/web/src/components/app/runner-update.test.tsx new file mode 100644 index 000000000..1f8b034e0 --- /dev/null +++ b/apps/web/src/components/app/runner-update.test.tsx @@ -0,0 +1,242 @@ +// @vitest-environment jsdom +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import type { RunnerUpdateView } from "@dispatch/shared"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { runnersQueryKey, type Runner } from "@/hooks/use-runners"; +import { api, ApiError } from "@/lib/api"; +import { RunnerHealthDetails } from "./runner-health"; +import { RunnerUpdateStatus } from "./runner-update"; + +vi.mock("@/lib/api", async (original) => ({ + ...(await original()), + api: vi.fn(), +})); +vi.mock("./runner-onboarding", () => ({ + RunnerCommand: ({ value }: { value: string }) => ( +

    {value}
    + ), + useRunnerInstaller: () => ({ + data: { version: "1.8.0", revision: "bbbbbbb", command: "update-command" }, + }), +})); + +afterEach(() => { + cleanup(); + vi.resetAllMocks(); +}); + +const runner = (update?: RunnerUpdateView): Runner => ({ + id: "rnr/one", + name: "Build machine", + status: "online", + workspaces: [], + update, + healthReceivedAt: "2026-01-15T08:42:17.123Z", + health: { + version: "1.7.0", + revision: "aaaaaaa", + sessions: 1, + working: 0, + cpuPercent: 1, + memoryUsed: 1, + memoryTotal: 2, + }, +}); + +function show(update?: RunnerUpdateView, health = false) { + const client = new QueryClient(); + const invalidate = vi.spyOn(client, "invalidateQueries"); + const tree = (next?: RunnerUpdateView) => ( + + + {health && } + + ); + const view = render(tree(update)); + return { + invalidate, + update: (next?: RunnerUpdateView) => view.rerender(tree(next)), + }; +} + +const text = () => screen.getByTestId("runner-update").textContent; +const version = "1.8.0"; +const available = { version, action: "update" } as const; + +it("offers Update with its consequence", () => { + show({ available }); + expect(text()).toContain("Update available: 1.8.0"); + expect(text()).toContain("Updating closes open terminals on this runner."); + expect(screen.getByRole("button", { name: "Update" })).toBeTruthy(); +}); + +it.each([ + ["staging", "Downloading and verifying…"], + ["settling", "Waiting for work to settle…"], + ["switching", "Switching to the new build…"], + ["confirming", "Confirming the new build…"], + ["cancelling", "Cancelling the update…"], +] as const)("shows %s", (phase, progress) => { + show({ attempt: { id: "a", phase, version } }); + expect(text()).toContain("Updating to 1.8.0"); + expect(text()).toContain(progress); + expect(text()).toContain("New work waits until the update finishes."); + expect(screen.queryByRole("button")).toBeNull(); +}); + +it.each([ + [1, "1 agent still on the previous build"], + [3, "3 agents still on the previous build"], +])("counts %d agents on the previous build", (count, words) => { + show({ result: { state: "updated", version }, previousBuildAgents: count }); + expect(text()).toContain("Updated to 1.8.0"); + expect(text()).toContain(words); + expect(screen.queryByRole("button")).toBeNull(); +}); + +it("puts a newer update ahead of the last success", () => { + show({ result: { state: "updated", version: "1.7.0" }, available }); + expect(text()).toContain("Update available: 1.8.0"); + expect(text()).not.toContain("Updated to"); +}); + +it.each([ + ["boot_failed", "The new build didn’t start."], + ["confirm_timeout", "The new build wasn’t confirmed in time."], + ["reattach_failed", "Running agents didn’t reconnect to the new build."], + [ + "trial_interrupted", + "The runner was interrupted while testing the new build.", + ], + ["verify_failed", "The new build didn’t match the one Dispatch sent."], + ["dispatch_changed", "Dispatch changed builds during the update."], + ["unknown_code", "The runner restored its previous build."], +])("explains a rollback for %s", (reason, words) => { + show({ + result: { state: "rolled_back", version, reason }, + available: { version, action: "retry" }, + }); + expect(text()).toContain("Update to 1.8.0 rolled back"); + expect(text()).toContain(words); + expect(text()).toContain( + "This build is blocked on this runner until you retry." + ); + expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy(); +}); + +it.each([ + ["operations_pending", "The runner was still busy, so it didn’t switch."], + ["verify_failed", "The runner couldn’t download or verify the build."], + ["settle_timeout", "Work on the runner didn’t settle in time."], + [ + "attach_unavailable", + "Dispatch couldn’t reach every agent running on the runner.", + ], + ["no_response", "The runner didn’t report back in time."], + ["unknown_code", "The runner stopped the update."], +])("explains a deferral for %s", (reason, words) => { + show({ result: { state: "deferred", version, reason }, available }); + expect(text()).toContain("Update to 1.8.0 didn’t finish"); + expect(text()).toContain(words); + expect(screen.getByRole("button", { name: "Update" })).toBeTruthy(); +}); + +it("names the floor of a refused downgrade", () => { + show({ + result: { + state: "deferred", + version, + reason: "downgrade", + floorVersion: "1.9.0", + }, + }); + expect(text()).toContain("Update to 1.8.0 was refused"); + expect(text()).toContain("Its version floor is 1.9.0."); +}); + +it("offers Retry for a suppressed build and sends it", async () => { + vi.mocked(api).mockResolvedValue({ attemptId: "a" }); + const { invalidate } = show({ + result: { state: "deferred", version, reason: "suppressed" }, + available: { version, action: "retry" }, + }); + expect(text()).toContain("Update to 1.8.0 is blocked"); + fireEvent.click(screen.getByRole("button", { name: "Retry" })); + await vi.waitFor(() => + expect(invalidate).toHaveBeenCalledWith({ queryKey: runnersQueryKey }) + ); + expect(api).toHaveBeenCalledWith("/api/v1/runners/rnr%2Fone/update", { + method: "POST", + body: '{"action":"retry"}', + }); +}); + +it("names the newer build next to an older failure", () => { + show({ + result: { state: "rolled_back", version, reason: "dispatch_changed" }, + available: { version: "1.8.1", action: "update" }, + }); + expect(text()).toContain("Update available: 1.8.1"); +}); + +it("sends one request while the first is pending", async () => { + vi.mocked(api).mockReturnValue(new Promise(() => {})); + show({ available }); + const button = screen.getByRole("button"); + fireEvent.click(button); + await vi.waitFor(() => expect(button.disabled).toBe(true)); + fireEvent.click(button); + expect(api).toHaveBeenCalledTimes(1); + expect(api).toHaveBeenCalledWith("/api/v1/runners/rnr%2Fone/update", { + method: "POST", + body: '{"action":"update"}', + }); +}); + +it("shows a refusal, its command, and drops it once an update runs", async () => { + vi.mocked(api).mockRejectedValue( + new ApiError(409, "No signed build.", "no_artifact") + ); + const view = show({ available }); + fireEvent.click(screen.getByRole("button")); + expect((await screen.findByRole("alert")).textContent).toBe( + "No signed build." + ); + expect(screen.getByTestId("command").textContent).toBe("update-command"); + expect(view.invalidate).toHaveBeenCalled(); + view.update({ attempt: { id: "a", phase: "staging", version } }); + expect(screen.queryByRole("alert")).toBeNull(); + expect(screen.queryByTestId("command")).toBeNull(); + view.update({ result: { state: "updated", version } }); + expect(screen.queryByRole("alert")).toBeNull(); +}); + +describe("the manual command", () => { + it.each([ + ["without the capability", undefined, 1], + ["after a refusal it cannot retry", { result: { state: "deferred" } }, 1], + ["while it can update itself", { available }, 0], + ["while updating", { attempt: { id: "a", phase: "staging" } }, 0], + ["when all agents must be idle", { result: { state: "needs_idle" } }, 1], + ] as const)("shows %s", (_case, update, count) => { + show(update as RunnerUpdateView | undefined, true); + expect(screen.queryAllByTestId("command")).toHaveLength(count); + }); + + it("explains needing all agents idle without a button", () => { + show({ result: { state: "needs_idle", version } }); + expect(text()).toContain("Update to 1.8.0 needs all agents idle"); + expect(text()).toContain( + "This build can’t take over running agents. When they’re idle, run this on the runner." + ); + expect(screen.getByTestId("command")).toBeTruthy(); + expect(screen.queryByRole("button")).toBeNull(); + }); + + it("renders no update state for an unchanged runner", () => { + show(undefined); + expect(screen.queryByTestId("runner-update")).toBeNull(); + }); +}); diff --git a/apps/web/src/components/app/runner-update.tsx b/apps/web/src/components/app/runner-update.tsx new file mode 100644 index 000000000..8dcf81768 --- /dev/null +++ b/apps/web/src/components/app/runner-update.tsx @@ -0,0 +1,203 @@ +import type { RunnerUpdatePhaseView, RunnerUpdateView } from "@dispatch/shared"; +import { Loader2 } from "lucide-react"; + +import { LoadingButton } from "@/components/ui/button"; +import { useStartRunnerUpdate, type Runner } from "@/hooks/use-runners"; +import { ApiError } from "@/lib/api"; +import { RunnerCommand, useRunnerInstaller } from "./runner-onboarding"; + +const PHASES: Record = { + staging: "Downloading and verifying…", + settling: "Waiting for work to settle…", + switching: "Switching to the new build…", + confirming: "Confirming the new build…", + cancelling: "Cancelling the update…", +}; + +const ROLLED_BACK: Record = { + boot_failed: "The new build didn’t start.", + confirm_timeout: "The new build wasn’t confirmed in time.", + reattach_failed: "Running agents didn’t reconnect to the new build.", + trial_interrupted: "The runner was interrupted while testing the new build.", + verify_failed: "The new build didn’t match the one Dispatch sent.", + identity_mismatch: "The new build didn’t match the one Dispatch sent.", + cancelled: "The runner cancelled the update.", +}; + +const DEFERRED: Record = { + operations_pending: "The runner was still busy, so it didn’t switch.", + verify_failed: "The runner couldn’t download or verify the build.", + boot_failed: "The runner couldn’t restart to switch builds.", + trial_interrupted: "The runner was interrupted before it could switch.", + suppressed: "This build failed on this runner before.", + cancelled: "The runner cancelled the update before switching.", + staging_timeout: "Downloading and verifying took too long.", + settle_timeout: "Work on the runner didn’t settle in time.", + attach_unavailable: + "Dispatch couldn’t reach every agent running on the runner.", + runner_newer: "The runner already has this version or newer.", +}; + +/** Reasons Dispatch gives, whatever state the runner ended in. */ +const STOPPED: Record = { + dispatch_changed: "Dispatch changed builds during the update.", + interrupted: "Dispatch lost track of the update, so it cancelled it.", + no_response: "The runner didn’t report back in time.", + switch_timeout: "The runner didn’t finish switching in time.", + state_unsaved: "Dispatch couldn’t save the update’s progress.", + unsupported: "The runner reconnected without update support.", + revoked: "The runner’s access was revoked.", +}; + +function describeResult({ + state, + version, + reason = "", + floorVersion, +}: NonNullable): { + title: string; + detail?: string; +} { + const update = version ? `Update to ${version}` : "The update"; + switch (state) { + case "updated": + return { title: version ? `Updated to ${version}` : "Runner updated" }; + case "needs_idle": + return { + title: `${update} needs all agents idle`, + detail: + "This build can’t take over running agents. When they’re idle, run this on the runner.", + }; + case "rolled_back": + return { + title: `${update} rolled back`, + detail: + ROLLED_BACK[reason] ?? + STOPPED[reason] ?? + "The runner restored its previous build.", + }; + case "deferred": + if (reason === "downgrade") + return { + title: `${update} was refused`, + detail: floorVersion + ? `The runner refused it as a downgrade. Its version floor is ${floorVersion}.` + : "The runner refused it as a downgrade.", + }; + return { + title: + reason === "suppressed" + ? `${update} is blocked` + : `${update} didn’t finish`, + detail: + DEFERRED[reason] ?? + STOPPED[reason] ?? + "The runner stopped the update.", + }; + } +} + +function UpdateCommand() { + const { data } = useRunnerInstaller(true); + return data?.command ? ( +
    + +
    + ) : null; +} + +export function RunnerUpdateStatus({ runner }: { runner: Runner }) { + const start = useStartRunnerUpdate(runner.id); + const { attempt, available, result, previousBuildAgents } = + runner.update ?? {}; + // A refusal is stale once an update is running or has landed. + const error = + attempt || (!available && result?.state === "updated") ? null : start.error; + if (!attempt && !available && !result && !previousBuildAgents && !error) + return null; + + const failed = result !== undefined && result.state !== "updated"; + let title: string | undefined; + let detail: string | undefined; + if (attempt) { + title = attempt.version + ? `Updating to ${attempt.version}` + : "Runner update in progress"; + detail = PHASES[attempt.phase]; + } else if (result && (failed || !available)) { + ({ title, detail } = describeResult(result)); + } else if (available) { + title = `Update available: ${available.version}`; + } + const needsCommand = + (!attempt && result?.state === "needs_idle") || + (error instanceof ApiError && + ["no_artifact", "same_version", "unsupported"].includes( + error.code ?? "" + )); + + return ( +
    +
    +
    + {title && ( +

    + {title} +

    + )} + {detail && ( +

    + {attempt && ( +

    + )} + {attempt &&

    New work waits until the update finishes.

    } + {!attempt && previousBuildAgents ? ( +

    + {previousBuildAgents}{" "} + {previousBuildAgents === 1 ? "agent" : "agents"} still on the + previous build +

    + ) : null} + {!attempt && available && ( + <> + {failed && available.version !== result.version && ( +

    Update available: {available.version}

    + )} + {available.action === "retry" && ( +

    This build is blocked on this runner until you retry.

    + )} +

    Updating closes open terminals on this runner.

    + + )} +
    + {!attempt && available && ( + start.mutate(available.action)} + data-testid={`runner-update-${runner.id}`} + > + {available.action === "retry" ? "Retry" : "Update"} + + )} +
    + {error && ( +

    + {error.message} +

    + )} + {needsCommand && } +
    + ); +} diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index 91039baae..a89325bb4 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -1,4 +1,5 @@ import { type RunnerHealth, workspaceLocator } from "@dispatch/runner-protocol"; +import type { RunnerUpdateAction, RunnerUpdateView } from "@dispatch/shared"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "@/lib/api"; @@ -17,6 +18,7 @@ export type Runner = { repositoryPicker?: boolean; health?: RunnerHealth; healthReceivedAt?: string; + update?: RunnerUpdateView; }; export type RunnerPairing = { id: string; command: string; expiresAt: string }; @@ -44,7 +46,13 @@ export function useRunners( : "/api/runners" ) ).runners, - refetchInterval: options.poll ? 5000 : false, + refetchInterval: (query) => { + if (!options.poll) return false; + // An update's phases last seconds. + return query.state.data?.some((runner) => runner.update?.attempt) + ? 2000 + : 5000; + }, }); } @@ -58,6 +66,20 @@ export function useRunnerName(runnerId: string | undefined) { : undefined; } +export function useStartRunnerUpdate(runnerId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (action: RunnerUpdateAction) => + api<{ attemptId: string }>( + `/api/v1/runners/${encodeURIComponent(runnerId)}/update`, + { method: "POST", body: JSON.stringify({ action }) } + ), + // A refusal also means the runner's state moved on. + onSettled: () => + queryClient.invalidateQueries({ queryKey: runnersQueryKey }), + }); +} + export function useRunnerMutations() { const queryClient = useQueryClient(); const invalidate = () => From c9591e6475d83f6a024078fd5cda3b7d5c2f9321 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 19:29:24 -0700 Subject: [PATCH 292/642] Prove the coordinator's adoption, hold and evidence guards Co-Authored-By: Claude Opus 5.5 --- .../test/runner-update-coordinator.test.ts | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/apps/server/test/runner-update-coordinator.test.ts b/apps/server/test/runner-update-coordinator.test.ts index 19d1261a2..75633ebe5 100644 --- a/apps/server/test/runner-update-coordinator.test.ts +++ b/apps/server/test/runner-update-coordinator.test.ts @@ -437,15 +437,15 @@ describe("confirmation evidence", () => { expect(world.sent("update_confirm")).toEqual([]); }); - it("forgets the trial report of an earlier connection", async () => { + it("needs a trial report on this connection, however good the attach", async () => { await online(); const attemptId = await confirming(); await world.disconnect(); // The next supervisor has not reached the trial yet. world.runner.trial = { ...world.runner.trial!, phase: "starting" } as never; - world.hosts.reply = "ready"; + world.agents.isRunnerSessionAttached = () => true; await world.connect(); - await world.settle(1_500); + await world.settle(300); expect(world.sent("update_confirm")).toEqual([]); expect(world.attempt()?.id).toBe(attemptId); }); @@ -935,7 +935,8 @@ describe("Dispatch restarts", () => { // No fence on the runner any more, and the new report is still to come. world.runner.fence.record = null; world.runner.staging = new Promise(() => {}); - world.hosts.reply = "ready"; + // Good evidence alone must not switch on the old report. + world.agents.isRunnerSessionAttached = () => true; await world.restartRunner(); await world.settle(300); expect(world.sent("update_activate")).toEqual([]); @@ -1077,6 +1078,20 @@ describe("runner reconnects", () => { ); }); + it("replaces a hold left by another attempt with its own", async () => { + await online(); + const attemptId = await confirming(); + const [hold] = world.saved.holds.holds; + world.saved.holds.holds = [ + { ...hold!, attemptId: "7f1c1d1e-2a3b-4c5d-8e9f-0a1b2c3d4e5f" }, + ]; + await world.restartController(); + await world.connect(); + await world.until( + () => world.holds.current(RUNNER)?.attemptId === attemptId + ); + }); + it("holds and cancels a pending attempt it has no record of", async () => { await online(); const attemptId = await confirming(); @@ -1103,6 +1118,20 @@ describe("runner reconnects", () => { expect(world.sent("update_confirm")).toEqual([]); }); + it("holds a pending attempt until the runner answers the cancel", async () => { + await online(); + const attemptId = await confirming(); + world.saved.records = []; + world.saved.holds = { holds: [], resuming: [] }; + await world.restartController(); + world.service.cancelUpdate = () => ({ epoch: 1 }); + await world.connect(); + await world.until(() => world.phase() === "cancelling"); + await world.until( + () => world.holds.current(RUNNER)?.attemptId === attemptId + ); + }); + it("adopts a commit of an attempt it has no record of", async () => { await online(); const attemptId = await confirming(); From c588b2d9308180717021a049f65125a9e2e168c2 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 19:29:24 -0700 Subject: [PATCH 293/642] Keep the manual command after a floor refusal and say blocked once Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/app/runner-health.tsx | 10 +++++----- apps/web/src/components/app/runner-update.test.tsx | 8 ++++++++ apps/web/src/components/app/runner-update.tsx | 7 ++++--- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/app/runner-health.tsx b/apps/web/src/components/app/runner-health.tsx index 7d83ad3c9..c6de31e0b 100644 --- a/apps/web/src/components/app/runner-health.tsx +++ b/apps/web/src/components/app/runner-health.tsx @@ -87,11 +87,11 @@ export function sameRevision(a: string, b: string) { /** Dispatch is updating this runner, can, or already shows the command. */ function updatesItself({ update }: Runner) { - return Boolean( - update?.attempt || - update?.available || - update?.result?.state === "needs_idle" - ); + if (!update) return false; + const { attempt, available, result } = update; + if (attempt || result?.state === "needs_idle") return true; + // Trying again cannot get past the runner's version floor; the command can. + return Boolean(available) && result?.reason !== "downgrade"; } export function RunnerHealthDetails({ runner }: { runner: Runner }) { diff --git a/apps/web/src/components/app/runner-update.test.tsx b/apps/web/src/components/app/runner-update.test.tsx index 1f8b034e0..96c7a7e95 100644 --- a/apps/web/src/components/app/runner-update.test.tsx +++ b/apps/web/src/components/app/runner-update.test.tsx @@ -163,6 +163,9 @@ it("offers Retry for a suppressed build and sends it", async () => { available: { version, action: "retry" }, }); expect(text()).toContain("Update to 1.8.0 is blocked"); + expect(text()).toContain("This build failed on this runner before."); + // The title already says so. + expect(text()).not.toContain("until you retry"); fireEvent.click(screen.getByRole("button", { name: "Retry" })); await vi.waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: runnersQueryKey }) @@ -218,6 +221,11 @@ describe("the manual command", () => { ["without the capability", undefined, 1], ["after a refusal it cannot retry", { result: { state: "deferred" } }, 1], ["while it can update itself", { available }, 0], + [ + "after the runner's floor refused this build", + { available, result: { state: "deferred", reason: "downgrade" } }, + 1, + ], ["while updating", { attempt: { id: "a", phase: "staging" } }, 0], ["when all agents must be idle", { result: { state: "needs_idle" } }, 1], ] as const)("shows %s", (_case, update, count) => { diff --git a/apps/web/src/components/app/runner-update.tsx b/apps/web/src/components/app/runner-update.tsx index 8dcf81768..aaab2ac9b 100644 --- a/apps/web/src/components/app/runner-update.tsx +++ b/apps/web/src/components/app/runner-update.tsx @@ -172,9 +172,10 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { {failed && available.version !== result.version && (

    Update available: {available.version}

    )} - {available.action === "retry" && ( -

    This build is blocked on this runner until you retry.

    - )} + {available.action === "retry" && + result?.reason !== "suppressed" && ( +

    This build is blocked on this runner until you retry.

    + )}

    Updating closes open terminals on this runner.

    )} From 08344da3910da89167ddc7efef544f00b5bface1 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 19:44:56 -0700 Subject: [PATCH 294/642] Tell update results apart by build, not revision alone Co-Authored-By: Claude Opus 5.5 --- .../src/agents/remote/update-coordinator.ts | 8 +++--- .../test/runner-update-coordinator.test.ts | 25 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index 09e66f6b3..ac51eba82 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -956,7 +956,9 @@ export class RunnerUpdateCoordinator { this.confirms.delete(runnerId); } - private isOwnBuild(target: RunnerUpdateTarget | undefined) { + private isOwnBuild( + target: { version: string; revision: string } | undefined + ) { const { version, revision } = this.options.build; return target?.version === version && target.revision === revision; } @@ -974,9 +976,9 @@ export class RunnerUpdateCoordinator { ) { const { target } = attempt; if (outcome.state === "updated") - return !advert || !target || advert.revision === target.revision; + return !advert || !target || advert.installedSha256 === target.sha256; // A failure is history once the runner has this build anyway. - if (advert && advert.revision === this.options.build.revision) return false; + if (advert && this.isOwnBuild(advert)) return false; return ( !target || this.isOwnBuild(target) || diff --git a/apps/server/test/runner-update-coordinator.test.ts b/apps/server/test/runner-update-coordinator.test.ts index 75633ebe5..a58cc804a 100644 --- a/apps/server/test/runner-update-coordinator.test.ts +++ b/apps/server/test/runner-update-coordinator.test.ts @@ -734,6 +734,31 @@ describe("outcomes", () => { expect(world.coordinator.view(RUNNER)).toBeUndefined(); }); + it("still reports a rollback between versions of one revision", async () => { + await online({ identity: { ...identity, revision: target.revision } }); + await rolledBack(); + expect(world.coordinator.view(RUNNER)).toEqual({ + available: { version: target.version, action: "retry" }, + result: { + state: "rolled_back", + version: target.version, + reason: "boot_failed", + }, + }); + }); + + it("hides a success that another version of the same revision replaced", async () => { + await online(); + await updated(); + world.runner.identity = { + ...identity, + version: "1.7.40", + revision: target.revision, + }; + await world.restartRunner(); + expect(world.coordinator.view(RUNNER)).toBeUndefined(); + }); + it("hides success and stops recycling after another build is installed", async () => { await online(); await updated(); From 9d0aa9094387548fd3dc20c4879a293e9279ff50 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 20:21:38 -0700 Subject: [PATCH 295/642] Say why an update closed a runner terminal The notice was written into the terminal's output, then the socket closed with the generic reason and the pane replaced the screen that held it. Carry the reason in the close itself, which the pane's alert already shows. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/terminal/manager.ts | 11 +- apps/server/src/terminal/remote.ts | 9 +- .../test/remote-terminal-update.test.ts | 118 ++++++++++++------ .../terminal/terminal-panel.test.tsx | 16 +++ 4 files changed, 110 insertions(+), 44 deletions(-) diff --git a/apps/server/src/terminal/manager.ts b/apps/server/src/terminal/manager.ts index dc9b51be5..63d85a46c 100644 --- a/apps/server/src/terminal/manager.ts +++ b/apps/server/src/terminal/manager.ts @@ -18,6 +18,11 @@ export function terminalOwner(session: string): string { type TerminalProcess = TerminalInfo & { terminal: PtyProcess["terminal"] & { detach?(): void; resume?(): void }; exited: Promise; + /** + * Why it ended without an exit code. The panel drops its screen on close, + * so only the socket's close reason is seen. At most 123 bytes. + */ + endReason?(): string | undefined; kill(): void; }; @@ -122,7 +127,11 @@ export class HumanTerminalManager { void process.exited.then((code) => { if (this.sessions.get(id) !== session) return; if (code === null) { - this.end(id, owner, "Runner terminal connection ended."); + this.end( + id, + owner, + process.endReason?.() ?? "Runner terminal connection ended." + ); } else { if (session.socket?.readyState === 1) session.socket.send(JSON.stringify({ type: "exit", code })); diff --git a/apps/server/src/terminal/remote.ts b/apps/server/src/terminal/remote.ts index 5e966b1dc..4d35ac1dd 100644 --- a/apps/server/src/terminal/remote.ts +++ b/apps/server/src/terminal/remote.ts @@ -7,12 +7,9 @@ import { } from "@dispatch/runner-protocol"; import { wireFrames } from "@dispatch/runner-protocol/node"; import type { RemoteRunnerService } from "../agents/remote/service.js"; +import { TERMINAL_UPDATE_MESSAGE } from "../agents/remote/update-admission.js"; import type { TerminalBackend } from "./manager.js"; -/** Shown in the terminal when the runner closes it for a supervisor update. */ -export const RUNNER_UPDATE_TERMINAL_NOTICE = - "\r\n[Runner updating: this terminal was closed. Reopen it after the update.]\r\n"; - export function remoteTerminal( runner: Pick, placement: Placement, @@ -29,6 +26,7 @@ export function remoteTerminal( if (!channel || !isTerminalInfo(info)) throw new Error("Invalid runner terminal response."); let finish!: (code: number | null) => void; + let endReason: string | undefined; const exited = new Promise((resolve) => { finish = resolve; }); @@ -42,7 +40,7 @@ export function remoteTerminal( output(Buffer.from(event.data, "base64")); else { if (event.type === "error" && event.reason === "update") - output(Buffer.from(RUNNER_UPDATE_TERMINAL_NOTICE)); + endReason = TERMINAL_UPDATE_MESSAGE; finish(event.type === "exit" ? event.code : null); channel.destroy(); } @@ -52,6 +50,7 @@ export function remoteTerminal( return { ...info, exited, + endReason: () => endReason, kill: () => channel.destroy(), terminal: { write(data) { diff --git a/apps/server/test/remote-terminal-update.test.ts b/apps/server/test/remote-terminal-update.test.ts index b5273e377..a67238270 100644 --- a/apps/server/test/remote-terminal-update.test.ts +++ b/apps/server/test/remote-terminal-update.test.ts @@ -1,52 +1,94 @@ -import { Duplex } from "node:stream"; -import { describe, expect, it, vi } from "vitest"; -import { - RUNNER_UPDATE_TERMINAL_NOTICE, - remoteTerminal, -} from "../src/terminal/remote.js"; +import { EventEmitter } from "node:events"; +import type { WebSocket } from "ws"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { RunnerConnection } from "@dispatch/runner-protocol/connection"; +import type { ServiceFrame } from "@dispatch/runner-protocol"; +import { TERMINAL_UPDATE_MESSAGE } from "../src/agents/remote/update-admission.js"; +import { HumanTerminalManager } from "../src/terminal/manager.js"; +import { remoteTerminal } from "../src/terminal/remote.js"; -function open() { - const channel = new Duplex({ - read() {}, - write(_chunk, _encoding, callback) { - callback(); - }, +let manager: HumanTerminalManager; +afterEach(() => manager.shutdown()); + +/** The runner's frames through the real connection, backend and manager. */ +async function open() { + let id!: string; + const connection = new RunnerConnection((frame: ServiceFrame) => { + if (frame.type !== "request") return; + id = frame.id; + queueMicrotask(() => + connection.receive({ + type: "result", + id, + value: JSON.stringify({ cwd: "/w", host: "runner", user: "u" }), + }) + ); }); - const toClient = { write: (line: string) => channel.push(line) }; const runner = { - requestSession: vi.fn(async () => ({ - value: JSON.stringify({ cwd: "/w", host: "runner", user: "u" }), - channel, - })), + requestSession: () => + connection.request( + { kind: "openTerminal", agentId: "agt_one", workspace: "@session" }, + { openChannel: true } + ), }; - const output = vi.fn(); - const backend = remoteTerminal( - runner as never, - { runner: "rnr_1", workspace: "@session" }, - "agt_one" + manager = new HumanTerminalManager(); + const terminal = await manager.open( + "owner", + "tab", + "agt_one", + remoteTerminal( + runner as never, + { runner: "rnr_1", workspace: "@session" }, + "agt_one" + ) ); - return { toClient, output, started: backend(output) }; + const socket = Object.assign(new EventEmitter(), { + send: vi.fn(), + close: vi.fn(), + readyState: 1, + bufferedAmount: 0, + }); + manager.attach(terminal.id, "owner", socket as unknown as WebSocket); + /** What a runner writes when it closes a terminal, in one read. */ + const closes = (event?: object) => { + if (event) + connection.receive({ + type: "data", + id, + data: Buffer.from(JSON.stringify(event) + "\n").toString("base64"), + }); + connection.receive({ type: "close", id }); + }; + return { socket, closes }; } describe("remote terminal update closure", () => { - it("shows the update reason before the terminal ends", async () => { - const { toClient, output, started } = open(); - const terminal = await started; - toClient.write( - JSON.stringify({ type: "error", message: "closed", reason: "update" }) + - "\n" + it("closes the pane's socket with the update notice", async () => { + const { socket, closes } = await open(); + closes({ type: "error", message: "closed", reason: "update" }); + await vi.waitFor(() => + expect(socket.close).toHaveBeenCalledExactlyOnceWith( + 1000, + TERMINAL_UPDATE_MESSAGE + ) ); - await expect(terminal.exited).resolves.toBeNull(); - expect(output).toHaveBeenCalledWith( - Buffer.from(RUNNER_UPDATE_TERMINAL_NOTICE) + }); + + it.each([ + ["another error", { type: "error", message: "full" }], + ["a lost connection", undefined], + ])("keeps the generic reason for %s", async (_case, event) => { + const { socket, closes } = await open(); + closes(event); + await vi.waitFor(() => + expect(socket.close).toHaveBeenCalledExactlyOnceWith( + 1000, + "Runner terminal connection ended." + ) ); }); - it("keeps other errors silent", async () => { - const { toClient, output, started } = open(); - const terminal = await started; - toClient.write(JSON.stringify({ type: "error", message: "full" }) + "\n"); - await expect(terminal.exited).resolves.toBeNull(); - expect(output).not.toHaveBeenCalled(); + it("fits in a WebSocket close reason", () => { + expect(Buffer.byteLength(TERMINAL_UPDATE_MESSAGE)).toBeLessThanOrEqual(123); }); }); diff --git a/apps/web/src/components/terminal/terminal-panel.test.tsx b/apps/web/src/components/terminal/terminal-panel.test.tsx index b76716c01..068617067 100644 --- a/apps/web/src/components/terminal/terminal-panel.test.tsx +++ b/apps/web/src/components/terminal/terminal-panel.test.tsx @@ -588,6 +588,22 @@ describe("terminal panel", () => { expect(screen.queryByRole("button", { name: "End terminal" })).toBeNull(); expect(screen.getByRole("button", { name: "New terminal" })).toBeTruthy(); }); + it("shows why the shell was closed in the alert", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ ok: true, json: async () => info }) + ); + render(); + await waitFor(() => expect(Socket.instances).toHaveLength(1)); + const socket = Socket.instances[0]; + act(() => socket.onopen?.()); + const reason = + "The runner is updating. This terminal was closed; reopen it after the update."; + act(() => socket.onclose?.({ code: 1000, reason } as CloseEvent)); + expect(screen.getByRole("alert").textContent).toBe(reason); + expect(screen.getByRole("button", { name: "New terminal" })).toBeTruthy(); + }); + it("shows the browser setup/auth error and actives no socket when rejected", async () => { vi.stubGlobal( "fetch", From 7ae8b625c11fbda6664b2ed6e0390736bd0a90ae Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 20:23:14 -0700 Subject: [PATCH 296/642] Keep Health's wanted build in step with the update above it The installer query stayed fresh for five minutes while the runners query polled, so an open detail compared a new runner with the old controller build. Invalidate it when the update state, the reported build or Dispatch's version changes, including version changes after the first mismatch. Co-Authored-By: Claude Opus 5.5 --- .../src/components/app/runner-onboarding.tsx | 4 +- .../components/app/runner-settings.test.tsx | 127 +++++++++++++++++- .../src/components/app/runner-settings.tsx | 2 + apps/web/src/hooks/use-runners.ts | 24 ++++ apps/web/src/lib/version.ts | 17 ++- 5 files changed, 162 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/app/runner-onboarding.tsx b/apps/web/src/components/app/runner-onboarding.tsx index 99d0866fb..1730b5da0 100644 --- a/apps/web/src/components/app/runner-onboarding.tsx +++ b/apps/web/src/components/app/runner-onboarding.tsx @@ -15,7 +15,7 @@ import { } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { api } from "@/lib/api"; -import { runnersQueryKey } from "@/hooks/use-runners"; +import { runnerInstallerQueryKey, runnersQueryKey } from "@/hooks/use-runners"; export function RunnerCommand({ value, @@ -188,7 +188,7 @@ export type RunnerInstaller = { export function useRunnerInstaller(enabled: boolean) { return useQuery({ - queryKey: ["runner-installer"], + queryKey: runnerInstallerQueryKey, queryFn: () => api("/api/v1/runners/installer"), enabled, staleTime: 300_000, diff --git a/apps/web/src/components/app/runner-settings.test.tsx b/apps/web/src/components/app/runner-settings.test.tsx index c422eada9..729cf6ffd 100644 --- a/apps/web/src/components/app/runner-settings.test.tsx +++ b/apps/web/src/components/app/runner-settings.test.tsx @@ -14,10 +14,11 @@ import { within, } from "@testing-library/react"; import { MemoryRouter, useLocation } from "react-router-dom"; -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import type { Runner } from "@/hooks/use-runners"; import { api } from "@/lib/api"; +import { noteServerVersion } from "@/lib/version"; import { RunnerSettings } from "./runner-settings"; vi.mock("@/lib/api", () => ({ @@ -53,10 +54,12 @@ function SearchValue() { return {useLocation().search}; } -function renderSettings(entry = "/settings/runners") { - const queryClient = new QueryClient({ +function renderSettings( + entry = "/settings/runners", + queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } }, - }); + }) +) { return render( @@ -446,3 +449,119 @@ it("polls faster while a selected runner updates and offers the action in its de vi.useRealTimers(); } }); + +describe("the wanted build in Health", () => { + const health = { + version: "1.7.28", + revision: "aaaaaaa", + sessions: 0, + working: 0, + cpuPercent: 1, + memoryUsed: 1, + memoryTotal: 2, + }; + const shown: Runner = { + ...online, + engineManagement: undefined, + health, + healthReceivedAt: "2026-01-15T08:42:17.123Z", + }; + const old = { version: "1.7.28", revision: "aaaaaaa", command: null }; + const next = { version: "1.7.29", revision: "bbbbbbb", command: null }; + + async function openHealth() { + const world = { runner: shown, installer: old }; + vi.mocked(api).mockImplementation(async (path) => { + if (path === "/api/runners") return { runners: [world.runner] } as never; + if (path === "/api/v1/runners/installer") return world.installer as never; + return {} as never; + }); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + renderSettings("/settings/runners?runner=build", client); + const details = + await screen.findByTestId("runner-health"); + details.open = true; + fireEvent(details, new Event("toggle")); + await within(details).findByText("Wanted build"); + world.installer = next; + const changes = (runner: Partial) => + act(async () => { + world.runner = { ...shown, ...runner }; + await client.refetchQueries({ queryKey: ["runners"] }); + }); + const showsNext = () => + waitFor(() => expect(details.textContent).toContain("bbbbbbb")); + return { world, details, changes, showsNext }; + } + + it.each<[string, Partial]>([ + [ + "an update becomes available", + { update: { available: { version: "1.7.29", action: "update" } } }, + ], + [ + "an update starts", + { update: { attempt: { id: "a", phase: "staging" } } }, + ], + ["an update ends", { update: { result: { state: "rolled_back" } } }], + [ + "the runner reports another version", + { health: { ...health, version: "1.7.29" } }, + ], + [ + "the runner reports another revision", + { health: { ...health, revision: "ccccccc" } }, + ], + ])("is read again when %s", async (_case, runner) => { + const { changes, showsNext } = await openHealth(); + await changes(runner); + await showsNext(); + }); + + it("agrees with the update that just finished", async () => { + const { changes, details, showsNext } = await openHealth(); + await changes({ + health: { ...health, version: "1.7.29", revision: "bbbbbbb" }, + update: { result: { state: "updated", version: "1.7.29" } }, + }); + await showsNext(); + await waitFor(() => + expect(details.textContent).toContain("Wanted build1.7.29") + ); + expect(details.textContent).toContain("Up to date"); + expect(details.textContent).not.toContain("Runner is newer"); + }); + + it("is read again each time Dispatch's version changes", async () => { + const { world, details, showsNext } = await openHealth(); + act(() => noteServerVersion("1.7.29")); + await showsNext(); + world.installer = { ...next, version: "1.7.30", revision: "ddddddd" }; + act(() => noteServerVersion("1.7.30")); + await waitFor(() => expect(details.textContent).toContain("ddddddd")); + // Every response repeats the header; only a change is a signal. + const reads = vi.mocked(api).mock.calls.length; + await act(async () => noteServerVersion("1.7.30")); + expect(vi.mocked(api).mock.calls).toHaveLength(reads); + }); + + it("is read again when a detail opens on a cached build", async () => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + client.setQueryData(["runner-installer"], old); + vi.mocked(api).mockImplementation(async (path) => { + if (path === "/api/runners") return { runners: [shown] } as never; + if (path === "/api/v1/runners/installer") return next as never; + return {} as never; + }); + renderSettings("/settings/runners?runner=build", client); + const details = + await screen.findByTestId("runner-health"); + details.open = true; + fireEvent(details, new Event("toggle")); + await waitFor(() => expect(details.textContent).toContain("bbbbbbb")); + }); +}); diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index 79552550a..0a3f0c55f 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -28,6 +28,7 @@ import { runnersQueryKey, useRunnerMutations, useRunners, + useWantedBuildRefresh, type Runner, type RunnerStatus, } from "@/hooks/use-runners"; @@ -350,6 +351,7 @@ function RunnerDetail({ heading: React.RefObject; onRevoked: () => void; }) { + useWantedBuildRefresh(runner); return (
    diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index a89325bb4..98afbc6aa 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -1,8 +1,10 @@ import { type RunnerHealth, workspaceLocator } from "@dispatch/runner-protocol"; import type { RunnerUpdateAction, RunnerUpdateView } from "@dispatch/shared"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useEffect } from "react"; import { api } from "@/lib/api"; +import { subscribeVersionMismatch } from "@/lib/version"; export type RunnerStatus = "pending" | "online" | "offline" | "revoked"; @@ -24,6 +26,28 @@ export type Runner = { export type RunnerPairing = { id: string; command: string; expiresAt: string }; export const runnersQueryKey = ["runners"] as const; +export const runnerInstallerQueryKey = ["runner-installer"] as const; + +/** + * The wanted build is cached for minutes and follows Dispatch's build. Read + * it again when what is shown beside it moves, or Dispatch's version does. + */ +export function useWantedBuildRefresh({ health, update }: Runner) { + const queryClient = useQueryClient(); + const shown = JSON.stringify([ + health?.version, + health?.revision, + update?.available, + update?.attempt, + update?.result, + ]); + useEffect(() => { + const refresh = () => + void queryClient.invalidateQueries({ queryKey: runnerInstallerQueryKey }); + refresh(); + return subscribeVersionMismatch(refresh); + }, [queryClient, shown]); +} /** Locator the server stores in an agent's cwd: opaque runner id, both parts encoded. */ export function runnerLocator(runnerId: string, workspace: string): string { diff --git a/apps/web/src/lib/version.ts b/apps/web/src/lib/version.ts index 101c53305..63485736a 100644 --- a/apps/web/src/lib/version.ts +++ b/apps/web/src/lib/version.ts @@ -33,11 +33,12 @@ export function dismissVersionMismatch(): void { notify(); } -// Listeners fire whenever the toast's input state (mismatch flag or -// dismissal) changes, so the component can stay in sync without owning -// any of it locally — important because the toast may unmount and -// remount (logout/login, Strict Mode double-mount, future layout -// changes) and dismissal needs to survive those. +// Listeners fire whenever the toast's input state (mismatch flag, the +// mismatched server's version, or dismissal) changes, so the component +// can stay in sync without owning any of it locally — important because +// the toast may unmount and remount (logout/login, Strict Mode +// double-mount, future layout changes) and dismissal needs to survive +// those. export function subscribeVersionMismatch(listener: Listener): () => void { listeners.add(listener); return () => { @@ -51,8 +52,12 @@ function notify(): void { export function noteServerVersion(version: string | null | undefined): void { if (!version) return; + const changed = version !== serverVersion; serverVersion = version; - if (mismatch) return; + if (mismatch) { + if (changed) notify(); + return; + } if (version === BUILD_VERSION) return; mismatch = true; notify(); From a17a4d0163b40c915d1940c90adfd650d31519ab Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 20:25:58 -0700 Subject: [PATCH 297/642] Let an installed build supersede an older maintenance failure The installer deletes its failure record on exit, after the new runner has already sent its first health sample with it, and a self-update never deleted it. Report a failure only while it is newer than the installed-build record both write, and sample again when a commit is confirmed. The service now serves that second sample and still bounds what it stores. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/remote/health.ts | 40 +++++--- apps/server/src/agents/remote/runner.ts | 11 ++- apps/server/src/agents/remote/service.ts | 10 +- apps/server/test/runner-health.test.ts | 98 +++++++++++++++++++- apps/server/test/runner-update-fence.test.ts | 85 ++++++++++++++++- scripts/remote-runner/test-installer.sh | 2 + 6 files changed, 226 insertions(+), 20 deletions(-) diff --git a/apps/server/src/agents/remote/health.ts b/apps/server/src/agents/remote/health.ts index ba7d1082f..401dfd5b7 100644 --- a/apps/server/src/agents/remote/health.ts +++ b/apps/server/src/agents/remote/health.ts @@ -42,7 +42,33 @@ async function cgroupDirectory() { return root; } -export function runnerHealthSampler() { +/** + * The last failed maintenance, unless the installed build is newer than it. + * The installer records a build before that build first starts, and the trial + * helper when it commits one, so this also covers the time before the + * installer's own cleanup, and a success by self-update, which has none. + */ +async function currentMaintenanceFailure(runtime: string) { + const file = path.join(runtime, "last-maintenance-failure.json"); + const diagnostic = await readMetric(file); + if (!diagnostic) return; + let failure; + try { + failure = parseMaintenanceFailure(JSON.parse(diagnostic)); + } catch { + /* Health remains available if the local record is invalid. */ + } + if (!failure) return; + const installed = await lstat(path.join(runtime, "installed-release")).catch( + () => null + ); + // `at` is truncated to the second it happened in. + if (installed && Date.parse(failure.at) + 1000 <= installed.mtimeMs) return; + return failure; +} + +/** `runtime` is the directory the installer keeps the build and records in. */ +export function runnerHealthSampler(runtime: string) { const group = cgroupDirectory(); let previous: CpuReading | undefined; return async (liveHostDirs: string[]): Promise => { @@ -90,17 +116,7 @@ export function runnerHealthSampler() { Number(memMax) > 0 && Number(memMax) <= hostTotal && !!memCurrent; const memoryTotal = limited ? Number(memMax) : hostTotal; const memoryUsed = limited ? Number(memCurrent) : hostTotal - os.freemem(); - let maintenanceFailure; - const diagnostic = await readMetric( - "/opt/dispatch-runner/last-maintenance-failure.json" - ); - if (diagnostic) { - try { - maintenanceFailure = parseMaintenanceFailure(JSON.parse(diagnostic)); - } catch { - /* Health remains available if the local record is invalid. */ - } - } + const maintenanceFailure = await currentMaintenanceFailure(runtime); return { version: packageVersion, ...(gitSha ? { revision: gitSha } : {}), diff --git a/apps/server/src/agents/remote/runner.ts b/apps/server/src/agents/remote/runner.ts index 44d63a682..06d782ada 100644 --- a/apps/server/src/agents/remote/runner.ts +++ b/apps/server/src/agents/remote/runner.ts @@ -318,7 +318,9 @@ export async function runRemoteRunner( cert: readFileSync(config.cert), key: readFileSync(config.key), }; - const sampleHealth = runnerHealthSampler(); + const sampleHealth = runnerHealthSampler( + path.dirname(updateLayout.installed) + ); // gh and git come from the workload account's own login environment, the // one its agent sessions get, not from whatever the system package put in // /usr/bin. Looked up once; a missing resolved path triggers a new lookup. @@ -1265,7 +1267,12 @@ export async function runRemoteRunner( launchReconcile: true, ...(advert ? { selfUpdate: advert } : {}), }); - updateConnection = updates.connect((frame) => safeSend(frame)); + updateConnection = updates.connect((frame) => { + safeSend(frame); + // A commit supersedes what this connection's first sample said. + if (frame.phase === "confirmed" && healthInterval) + void reportHealth(); + }); }); }).catch((error) => { supervisor.close(); diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 88e5749f5..3c8f0ce24 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -184,6 +184,7 @@ type Peer = { managedWorkspace: boolean; gate: Gate; health?: { sample: RunnerHealth; receivedAt: Date }; + healthStoredAt?: number; reportsHealth?: boolean; engineCapabilities: boolean; /** Advertised in `ready`; whether this peer answers the `"engine"` command. */ @@ -1031,13 +1032,16 @@ export class RemoteRunnerService { const sample = parseRunnerHealth(frame.sample); if (!sample) return socket.destroy(); const receivedAt = new Date(); + // The latest sample is served: an update's commit can follow the + // connection's first one within a second. + peer.health = { sample, receivedAt }; // Bound storage writes from an over-eager peer. if ( - peer.health && - receivedAt.getTime() - peer.health.receivedAt.getTime() < 1000 + peer.healthStoredAt !== undefined && + receivedAt.getTime() - peer.healthStoredAt < 1000 ) return; - peer.health = { sample, receivedAt }; + peer.healthStoredAt = receivedAt.getTime(); if (gate.registrationId) void this.enrollment?.registry .recordHealth(gate.registrationId, sample, receivedAt) diff --git a/apps/server/test/runner-health.test.ts b/apps/server/test/runner-health.test.ts index 0e6a6f095..0569853b6 100644 --- a/apps/server/test/runner-health.test.ts +++ b/apps/server/test/runner-health.test.ts @@ -1,5 +1,13 @@ -import { describe, expect, it } from "vitest"; -import { cpuPercentage } from "../src/agents/remote/health.js"; +import { mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { Duplex } from "node:stream"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + cpuPercentage, + runnerHealthSampler, +} from "../src/agents/remote/health.js"; +import { RemoteRunnerService } from "../src/agents/remote/service.js"; import { parseRunnerHealth } from "@dispatch/runner-protocol"; describe("runner health samples", () => { @@ -51,3 +59,89 @@ describe("runner health samples", () => { } }); }); + +describe("the last maintenance failure", () => { + let runtime: string; + beforeEach(async () => { + runtime = await mkdtemp(path.join(os.tmpdir(), "dispatch-runner-health-")); + }); + afterEach(() => rm(runtime, { recursive: true, force: true })); + + const failure = { step: "stage", exitCode: 1, at: "2026-01-10T12:00:00Z" }; + async function reported(installedAt?: string) { + await writeFile( + path.join(runtime, "last-maintenance-failure.json"), + JSON.stringify(failure) + ); + if (installedAt) { + const file = path.join(runtime, "installed-release"); + await writeFile(file, "1:2 v1.2.3\n"); + await utimes(file, new Date(installedAt), new Date(installedAt)); + } + return (await runnerHealthSampler(runtime)([])).maintenanceFailure; + } + + it("is superseded by a build installed after it", async () => { + expect(await reported("2026-01-10T12:00:01.000Z")).toBeUndefined(); + }); + + it.each([ + ["no build was recorded", undefined], + ["the build is older", "2026-01-10T11:59:00.000Z"], + // The record truncates to seconds, so this build may be the older. + ["both fall in one second", "2026-01-10T12:00:00.900Z"], + ])("is reported when %s", async (_case, installedAt) => { + expect(await reported(installedAt)).toEqual(failure); + }); +}); + +describe("a runner's health reports", () => { + it("serves the latest sample and stores at most one a second", async () => { + const service = new RemoteRunnerService(); + const recordHealth = vi.fn(async () => {}); + const registration = { + id: "rnr_one", + name: "one", + enrolled: true, + workspaces: [], + }; + Object.assign(service as any, { + enrollment: { + registry: { + recordHealth, + seen: async () => {}, + list: async () => [registration], + }, + }, + }); + const socket = Object.assign( + new Duplex({ read() {}, write: (_chunk, _encoding, done) => done() }), + { setKeepAlive() {} } + ); + (service as any).attachPeer(socket, { + key: registration.id, + registrationId: registration.id, + approved: () => true, + allows: () => true, + }); + const send = (frame: object) => socket.push(JSON.stringify(frame) + "\n"); + send({ type: "ready", version: 1, workspaces: ["work"], health: true }); + for (const sessions of [1, 2]) + send({ + type: "health", + sample: { + version: "1.2.3", + sessions, + working: 0, + cpuPercent: null, + memoryUsed: 1, + memoryTotal: 2, + }, + }); + await vi.waitFor(async () => + expect((await service.list())[0]?.health?.sessions).toBe(2) + ); + expect(recordHealth).toHaveBeenCalledOnce(); + socket.destroy(); + }); +}); diff --git a/apps/server/test/runner-update-fence.test.ts b/apps/server/test/runner-update-fence.test.ts index 202ffb253..c027649e5 100644 --- a/apps/server/test/runner-update-fence.test.ts +++ b/apps/server/test/runner-update-fence.test.ts @@ -1,6 +1,13 @@ import { parseReadyFrame } from "@dispatch/runner-protocol"; import { EventEmitter } from "node:events"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { + mkdir, + mkdtemp, + readFile, + rm, + utimes, + writeFile, +} from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { PassThrough } from "node:stream"; @@ -310,6 +317,82 @@ describe("runner update fence", () => { ); }); + it("reports health again once an update is confirmed", async () => { + const at = "2026-01-10T12:00:00Z"; + await writeFile( + path.join(root, "last-maintenance-failure.json"), + JSON.stringify({ step: "stage", exitCode: 1, at }) + ); + await start({ + updateIdentity: identity, + updater: mockUpdater(), + fenceStore: memoryStore(), + updateLayout: { + config: "", + installed: path.join(root, "dispatch"), + staging: "", + state: root, + }, + }); + const samples = () => + frames() + .filter((frame) => frame.type === "health") + .map((frame) => frame.sample); + emit({ type: "accept_health" }); + await vi.waitFor(() => + expect(samples()[0]?.maintenanceFailure?.at).toBe(at) + ); + // What a commit does before its confirmation is reported. + const installed = path.join(root, "installed-release"); + await writeFile(installed, "1:2 v1.7.28\n"); + const later = new Date(Date.parse(at) + 60_000); + await utimes(installed, later, later); + emit({ + type: "update_offer", + attemptId, + target: { ...target, sha256: identity.sha256 }, + retry: false, + }); + await vi.waitFor(() => expect(samples()).toHaveLength(2)); + expect(samples()[1].maintenanceFailure).toBeUndefined(); + }); + + it("samples again for nothing short of a confirmation", async () => { + await start({ + updateIdentity: identity, + updater: mockUpdater(compatible), + fenceStore: memoryStore(), + }); + const samples = () => frames().filter((frame) => frame.type === "health"); + emit({ type: "accept_health" }); + await vi.waitFor(() => expect(samples()).toHaveLength(1)); + emit({ type: "update_offer", attemptId, target, retry: false }); + await vi.waitFor(() => + expect(statuses().at(-1)).toMatchObject({ reason: "ready" }) + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(samples()).toHaveLength(1); + }); + + it("sends no health to a controller that never accepted it", async () => { + await start({ + updateIdentity: identity, + updater: mockUpdater(), + fenceStore: memoryStore(), + }); + emit({ + type: "update_offer", + attemptId, + target: { ...target, sha256: identity.sha256 }, + retry: false, + }); + await vi.waitFor(() => + expect(statuses().at(-1)).toMatchObject({ phase: "confirmed" }) + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(frames().filter((frame) => frame.type === "health")).toEqual([]); + }); + it("a supervisor restarted while fenced refuses every spawning command before it starts", async () => { const state = path.join(root, "update"); await mkdir(state, { mode: 0o700 }); diff --git a/scripts/remote-runner/test-installer.sh b/scripts/remote-runner/test-installer.sh index 5848ed8db..8da0d7060 100644 --- a/scripts/remote-runner/test-installer.sh +++ b/scripts/remote-runner/test-installer.sh @@ -94,6 +94,8 @@ systemctl() { start) if [[ -e "$root/require-startup-units" ]] && grep -q release-new "$runtime/dispatch"; then fixture_update_units_ready && [[ -e "$root/loaded-update-units" ]] || return 1 + # Health drops a failure older than this record in its first sample. + grep -Fq " $tag" "$runtime/installed-release" || return 1 : > "$root/candidate-saw-units" fi if [[ -e "$root/reject-new" ]] && grep -q release-new "$runtime/dispatch"; then From a10aaac7a76e856744b999e3a990d2d2852c5179 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 20:28:18 -0700 Subject: [PATCH 298/642] Keep the last known engines while a runner can't be read The candidate build reconnects behind the update fence, so the new connection has no pushed inventory and refuses the status read. That failure was reported as every engine not installed. Keep the last pushed inventory without actions, or the loading state when none is known, and read again when the update ends. Co-Authored-By: Claude Opus 5.5 --- .../src/agents/remote/engine-manager.ts | 24 +++- .../src/agents/remote/engine-transport.ts | 3 + apps/server/src/agents/remote/service.ts | 12 ++ apps/server/test/engine-manager.test.ts | 14 ++ .../test/runner-engine-last-known.test.ts | 121 ++++++++++++++++++ .../components/app/runner-settings.test.tsx | 28 ++++ .../src/components/app/runner-settings.tsx | 2 + .../runner-engines/runner-engines.test.tsx | 37 ++++++ .../runner-engines/runner-engines.tsx | 5 +- .../runner-engines/runner-provider-usage.tsx | 2 +- apps/web/src/hooks/use-runner-engines.ts | 32 ++++- 11 files changed, 270 insertions(+), 10 deletions(-) create mode 100644 apps/server/test/runner-engine-last-known.test.ts diff --git a/apps/server/src/agents/remote/engine-manager.ts b/apps/server/src/agents/remote/engine-manager.ts index 381ebd25f..6c31de6fb 100644 --- a/apps/server/src/agents/remote/engine-manager.ts +++ b/apps/server/src/agents/remote/engine-manager.ts @@ -58,6 +58,11 @@ export interface RunnerEngineTransport { * transport doesn't track a cache). */ cachedInventory?(runnerId: string): EngineInventoryEntry[] | undefined; + /** + * The last inventory from any connection: what to show while the runner + * can't be read, as during its update. + */ + lastKnownInventory?(runnerId: string): EngineInventoryEntry[] | undefined; } export type LocalEngineDeps = { @@ -114,12 +119,13 @@ export class EngineManager { this.events.emit(engineScopeKey(scope), entries); } - async inventory(scope: EngineScope): Promise { + /** Null while a runner's engines are not known yet. */ + async inventory(scope: EngineScope): Promise { const entries = scope.kind === "local" ? await this.localInventory() : await this.remoteInventory(scope); - this.emitChanged(scope, entries); + if (entries) this.emitChanged(scope, entries); return entries; } @@ -189,7 +195,7 @@ export class EngineManager { private async remoteInventory( scope: Extract, opts: { force?: boolean } = {} - ): Promise { + ): Promise { const cached = opts.force ? undefined : this.deps.remote.cachedInventory?.(scope.runnerId); @@ -203,8 +209,16 @@ export class EngineManager { } ); if (!ack.ok) { - // Unsupported or offline: report every engine as unknown rather than - // throwing, so the UI can show "unavailable" instead of an error page. + // A failed read, as behind an update fence, doesn't mean "not + // installed". Nothing can be changed there until a read succeeds. + if (!ack.unsupported) + return ( + this.deps.remote + .lastKnownInventory?.(scope.runnerId) + ?.map((entry) => ({ ...entry, actions: [] })) ?? null + ); + // Unsupported: report every engine as unknown rather than throwing, + // so the UI can show "unavailable" instead of an error page. return RUNNER_ENGINES.map((id) => ({ id, label: LABELS[id], diff --git a/apps/server/src/agents/remote/engine-transport.ts b/apps/server/src/agents/remote/engine-transport.ts index 4b76efa4d..8d8cc477d 100644 --- a/apps/server/src/agents/remote/engine-transport.ts +++ b/apps/server/src/agents/remote/engine-transport.ts @@ -32,6 +32,9 @@ export function remoteEngineTransport( cachedInventory(runnerId) { return service.engineInventorySnapshot(runnerId); }, + lastKnownInventory(runnerId) { + return service.lastEngineInventory(runnerId); + }, async send(runnerId, operation, onEvent) { const scoped = isEngineCapabilityOperation(operation); try { diff --git a/apps/server/src/agents/remote/service.ts b/apps/server/src/agents/remote/service.ts index 3c8f0ce24..d3c38c339 100644 --- a/apps/server/src/agents/remote/service.ts +++ b/apps/server/src/agents/remote/service.ts @@ -383,6 +383,7 @@ export class RemoteRunnerService { | "managedWorkspace" | "sessionFiles" | "sharedWorktree" + | "engines" > >(); private peerEpoch = 0; @@ -1015,6 +1016,7 @@ export class RemoteRunnerService { managedWorkspace: peer.managedWorkspace, sessionFiles: peer.sessionFiles, sharedWorktree: peer.sharedWorktree, + engines: this.lastSeen.get(gate.key)?.engines, }); previous?.socket.destroy(); gate.ready?.(ready.workspaces, peer.managedWorkspace); @@ -1059,6 +1061,7 @@ export class RemoteRunnerService { const entries = parseEngineInventory(frame.entries); if (entries === null) return socket.destroy(); peer.engines = entries; + this.lastSeen.get(gate.key)!.engines = entries; } else if ( frame.type === "launch_progress" && peer.workspacePreparation @@ -1680,6 +1683,15 @@ export class RemoteRunnerService { return peer?.gate.approved() ? peer.engines : undefined; } + /** + * What the runner last pushed, on this connection or an earlier one. A new + * connection has pushed nothing while an update fence refuses engine work. + */ + lastEngineInventory(runnerId: string): EngineInventoryEntry[] | undefined { + const seen = this.lastSeen.get(runnerId); + return seen?.gate.approved() ? seen.engines : undefined; + } + requestSession( placement: Placement, operation: SessionOperation, diff --git a/apps/server/test/engine-manager.test.ts b/apps/server/test/engine-manager.test.ts index bb3510b26..28ff7e2d8 100644 --- a/apps/server/test/engine-manager.test.ts +++ b/apps/server/test/engine-manager.test.ts @@ -259,6 +259,20 @@ describe("EngineManager runner scope", () => { expect(inventory).toHaveLength(3); }); + it("announces nothing while a runner's engines are unknown", async () => { + const manager = new EngineManager({ + local: { logins: fakeLogins(), updates: fakeUpdates() }, + remote: fakeTransport({ + send: vi.fn(async () => ({ ok: false, error: "fenced" })), + }), + }); + const scope = { kind: "runner" as const, runnerId: "r1" }; + const listener = vi.fn(); + manager.onChanged(scope, listener); + expect(await manager.inventory(scope)).toBeNull(); + expect(listener).not.toHaveBeenCalled(); + }); + it("notifies onChanged listeners after a state-changing operation", async () => { const transport = fakeTransport({ send: vi.fn(async (_r, op) => { diff --git a/apps/server/test/runner-engine-last-known.test.ts b/apps/server/test/runner-engine-last-known.test.ts new file mode 100644 index 000000000..80b1be684 --- /dev/null +++ b/apps/server/test/runner-engine-last-known.test.ts @@ -0,0 +1,121 @@ +import { Duplex } from "node:stream"; +import type { EngineInventoryEntry } from "@dispatch/runner-protocol/engine-management"; +import { afterEach, describe, expect, it } from "vitest"; + +import { EngineManager } from "../src/agents/remote/engine-manager.js"; +import { remoteEngineTransport } from "../src/agents/remote/engine-transport.js"; +import { RemoteRunnerService } from "../src/agents/remote/service.js"; + +const scope = { kind: "runner", runnerId: "rnr_one" } as const; +const claude: EngineInventoryEntry = { + id: "claude", + label: "Claude Code", + installed: true, + signedIn: true, + version: "2.1.325", + actions: ["update", "login"], +}; + +const sockets: Duplex[] = []; +afterEach(() => { + for (const socket of sockets.splice(0)) socket.destroy(); +}); + +/** A runner on the real service; a fenced one refuses the status read. */ +function world() { + const service = new RemoteRunnerService(); + let approved = true; + function connect({ fenced = false } = {}) { + const socket = Object.assign( + new Duplex({ + read() {}, + write(chunk, _encoding, done) { + done(); + for (const line of String(chunk).trim().split("\n")) { + const frame = JSON.parse(line); + if (frame.type === "request" && fenced) + send({ + type: "result", + id: frame.id, + code: "update-fenced", + error: "The runner is updating; the operation was not started.", + }); + } + }, + }), + { setKeepAlive() {} } + ); + sockets.push(socket); + const send = (frame: object) => socket.push(JSON.stringify(frame) + "\n"); + (service as any).attachPeer(socket, { + key: scope.runnerId, + approved: () => approved, + allows: () => true, + }); + send({ + type: "ready", + version: 1, + workspaces: ["work"], + health: true, + engineManagement: true, + }); + return { + push: (entries: EngineInventoryEntry[]) => + send({ type: "engine_inventory", entries }), + drop: () => socket.destroy(), + }; + } + const manager = new EngineManager({ + local: { logins: {} as never, updates: {} as never }, + remote: remoteEngineTransport(service), + }); + const settle = () => new Promise((resolve) => setTimeout(resolve, 5)); + const read = async () => { + await settle(); + return manager.inventory(scope); + }; + return { connect, read, revoke: () => (approved = false) }; +} + +describe("a runner's engines across its update", () => { + it("keeps the last known state, without actions, behind the fence", async () => { + const { connect, read } = world(); + connect().push([claude]); + expect(await read()).toEqual([claude]); + // The candidate build reconnects fenced, so it pushes and answers nothing. + connect({ fenced: true }); + expect(await read()).toEqual([{ ...claude, actions: [] }]); + }); + + it("keeps it while the runner is between supervisors", async () => { + const { connect, read } = world(); + const runner = connect(); + runner.push([claude]); + expect(await read()).toEqual([claude]); + runner.drop(); + expect(await read()).toEqual([{ ...claude, actions: [] }]); + }); + + it("is unknown, not uninstalled, with nothing known", async () => { + const { connect, read } = world(); + connect({ fenced: true }); + expect(await read()).toBeNull(); + }); + + it("follows what the new connection pushes", async () => { + const { connect, read } = world(); + connect().push([claude]); + await read(); + const updated = { ...claude, version: "2.2.0" }; + connect().push([updated]); + expect(await read()).toEqual([updated]); + }); + + it("forgets a revoked runner", async () => { + const { connect, read, revoke } = world(); + connect().push([claude]); + await read(); + revoke(); + expect(await read()).toBeNull(); + }); +}); diff --git a/apps/web/src/components/app/runner-settings.test.tsx b/apps/web/src/components/app/runner-settings.test.tsx index 729cf6ffd..d5a056650 100644 --- a/apps/web/src/components/app/runner-settings.test.tsx +++ b/apps/web/src/components/app/runner-settings.test.tsx @@ -14,6 +14,7 @@ import { within, } from "@testing-library/react"; import { MemoryRouter, useLocation } from "react-router-dom"; +import { engineScopeKey } from "@dispatch/runner-protocol/engine-management"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Runner } from "@/hooks/use-runners"; @@ -565,3 +566,30 @@ describe("the wanted build in Health", () => { await waitFor(() => expect(details.textContent).toContain("bbbbbbb")); }); }); + +it("reads engines, plugins and usage again when an update ends", async () => { + let runner: Runner = { ...online, engineManagement: undefined }; + vi.mocked(api).mockImplementation(async (path) => + path === "/api/runners" ? { runners: [runner] } : ({} as never) + ); + const client = new QueryClient(); + const invalidate = vi.spyOn(client, "invalidateQueries"); + renderSettings("/settings/runners?runner=build", client); + await screen.findByTestId("runner-detail"); + runner = { ...runner, update: { attempt: { id: "a", phase: "confirming" } } }; + await act(() => client.refetchQueries({ queryKey: ["runners"] })); + await screen.findByText("Runner update in progress"); + const keys = [ + ["runner-engines", engineScopeKey({ kind: "runner", runnerId: "build" })], + ["runner-plugin", "build"], + ["runner-provider-usage", "build"], + ]; + for (const queryKey of keys) + expect(invalidate).not.toHaveBeenCalledWith({ queryKey }); + runner = { ...runner, update: { result: { state: "updated" } } }; + await act(() => client.refetchQueries({ queryKey: ["runners"] })); + await waitFor(() => { + for (const queryKey of keys) + expect(invalidate).toHaveBeenCalledWith({ queryKey }); + }); +}); diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index 0a3f0c55f..994a6d359 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -24,6 +24,7 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { RunnerEngines } from "@/components/runner-engines/runner-engines"; +import { useEnginesRefreshAfterUpdate } from "@/hooks/use-runner-engines"; import { runnersQueryKey, useRunnerMutations, @@ -352,6 +353,7 @@ function RunnerDetail({ onRevoked: () => void; }) { useWantedBuildRefresh(runner); + useEnginesRefreshAfterUpdate(runner.id, Boolean(runner.update?.attempt)); return (
    diff --git a/apps/web/src/components/runner-engines/runner-engines.test.tsx b/apps/web/src/components/runner-engines/runner-engines.test.tsx index f884c902b..d4b97bf2c 100644 --- a/apps/web/src/components/runner-engines/runner-engines.test.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.test.tsx @@ -15,7 +15,10 @@ import type { EngineOperationAck, } from "@dispatch/runner-protocol/engine-management"; +import { runnerEnginesKey } from "@/hooks/use-runner-engines"; + import { RunnerEngines } from "./runner-engines"; +import { RunnerProviderUsage } from "./runner-provider-usage"; vi.mock("@/lib/api", () => ({ api: vi.fn() })); @@ -74,6 +77,40 @@ it("renders each engine's installed/signed-in state and available actions", asyn expect(screen.getByTestId("runner-engine-codex-install")).toBeTruthy(); }); +it("keeps loading while a runner's engines are not known yet", async () => { + vi.mocked(api).mockResolvedValue({ entries: null }); + const client = new QueryClient(); + render( + + + + + ); + await waitFor(() => + expect( + client.getQueryData(runnerEnginesKey({ kind: "runner", runnerId: "r1" })) + ).toEqual({ entries: null }) + ); + expect(screen.getByText("Loading engines…")).toBeTruthy(); + expect(screen.queryByText("No engines reported.")).toBeNull(); + expect(screen.queryByText("Set up Claude or Codex")).toBeNull(); +}); + +it("shows a failed read over unknown engines", async () => { + vi.mocked(api).mockRejectedValue(new Error("down")); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const scope = { kind: "runner", runnerId: "r1" } as const; + client.setQueryData(runnerEnginesKey(scope), { entries: null }); + render( + + + + ); + expect(await screen.findByText("Could not load engines.")).toBeTruthy(); +}); + it("posts an install operation scoped to a runner and refreshes", async () => { const ack: EngineOperationAck = { ok: true, operationId: "op-1" }; vi.mocked(api).mockImplementation( diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index 4ee13777f..689b9e45e 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -36,7 +36,10 @@ export function RunnerEngines({ const entries = inventory.data?.entries ?? []; const [activeLogin, setActiveLogin] = useState(null); - if (inventory.isLoading) { + if ( + inventory.isLoading || + (!inventory.isError && inventory.data?.entries === null) + ) { return (

    entry.id === "claude" || entry.id === "codex" ); const canReadUsage = diff --git a/apps/web/src/hooks/use-runner-engines.ts b/apps/web/src/hooks/use-runner-engines.ts index 9c8943e97..a10d2c3fa 100644 --- a/apps/web/src/hooks/use-runner-engines.ts +++ b/apps/web/src/hooks/use-runner-engines.ts @@ -1,5 +1,6 @@ import type { RunnerEngine } from "@dispatch/runner-protocol"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useEffect } from "react"; import { engineScopeKey, @@ -19,7 +20,8 @@ import { api } from "@/lib/api"; * running locally or on a named runner (runner-wide, not per-workspace). * Expects the HTTP routes: * - * - `GET /api/v1/engine-management/inventory?{scope query}` → `{ entries }` + * - `GET /api/v1/engine-management/inventory?{scope query}` → `{ entries }`, + * null while a runner's engines are not known yet * - `POST /api/v1/engine-management/operations` with `{ scope, operation }` * body → `{ ack }` * @@ -39,7 +41,9 @@ export function runnerEnginesKey(scope: EngineScope) { } /** Whether an operation leaves something still running, worth polling for. */ -function hasPendingWork(entries: EngineInventoryEntry[] | undefined): boolean { +function hasPendingWork( + entries: EngineInventoryEntry[] | null | undefined +): boolean { // Sign-in is the only state this inventory can't settle on its own; an // install/update's completion is the inventory's own version/installed // change, so no separate "pending" flag is needed here. @@ -50,7 +54,7 @@ function hasPendingWork(entries: EngineInventoryEntry[] | undefined): boolean { } export function useRunnerEngineInventory(scope: EngineScope, enabled = true) { - return useQuery<{ entries: EngineInventoryEntry[] }>({ + return useQuery<{ entries: EngineInventoryEntry[] | null }>({ queryKey: runnerEnginesKey(scope), enabled, queryFn: () => @@ -60,6 +64,28 @@ export function useRunnerEngineInventory(scope: EngineScope, enabled = true) { }); } +/** + * A runner refuses engine work while it updates, so what was read then is + * the last known state, or a failure. Read it again when the update ends. + */ +export function useEnginesRefreshAfterUpdate( + runnerId: string, + updating: boolean +) { + const queryClient = useQueryClient(); + useEffect(() => { + if (!updating) return; + return () => { + for (const queryKey of [ + runnerEnginesKey({ kind: "runner", runnerId }), + ["runner-plugin", runnerId], + ["runner-provider-usage", runnerId], + ]) + void queryClient.invalidateQueries({ queryKey }); + }; + }, [queryClient, runnerId, updating]); +} + /** Run one operation against a scope and refresh its inventory on completion. */ export function useRunnerEngineOperation(scope: EngineScope) { const queryClient = useQueryClient(); From 522cfde457cf217c79cdbed1f2c31ed7401d9dbd Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 20:37:08 -0700 Subject: [PATCH 299/642] Hold work from ready, not through the runner's download Begin the hold when the runner reports the build staged, saved and before the fence is asked for. An attempt that is still staging, or was cancelled there, holds nothing, also across reconnects and restarts; the view says when one does, so the copy follows it. With the fence now straight after the hold, a stop begun just before it waits and repeats a refused hook request instead of skipping the repo's stop hook. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/archive.ts | 27 ++-- apps/server/src/agents/lifecycle-hooks.ts | 28 ++-- apps/server/src/agents/manager.ts | 18 ++- .../src/agents/remote/update-coordinator.ts | 62 ++++---- apps/server/test/agent-archive.test.ts | 3 +- .../db/runner-update-hold-manager.test.ts | 46 ++++++ apps/server/test/lifecycle-hooks.test.ts | 35 +++++ .../test/runner-update-coordinator.test.ts | 136 +++++++++++++++--- .../src/components/app/runner-update.test.tsx | 9 +- apps/web/src/components/app/runner-update.tsx | 2 +- docs/remote-runner-linux.md | 7 +- packages/shared/src/runner-update-types.ts | 8 +- 12 files changed, 308 insertions(+), 73 deletions(-) diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index f66d44d4d..e49ff7e54 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -52,6 +52,11 @@ export type ArchiveDeps = { ) => Promise; /** Resolves once the agent's runner is not held for an update. */ waitForRunner?: (agent: AgentRecord) => Promise; + /** Repeats a request the runner's update fence refused, once it opens. */ + whileFenced?: ( + agent: AgentRecord, + request: () => Promise + ) => Promise; }; /** @@ -182,10 +187,13 @@ export async function executeArchive( const t = Date.now(); try { await deps.waitForRunner?.(agent); - await runLifecycleHook("stop", agent, logger, { - local: deps.localRunner, - remote: deps.remote, - }).catch((err) => + await runLifecycleHook( + "stop", + agent, + logger, + { local: deps.localRunner, remote: deps.remote }, + deps.whileFenced && ((request) => deps.whileFenced!(agent, request)) + ).catch((err) => logger.warn( { err, agentId: id }, "Stop hook failed during archive; continuing" @@ -330,10 +338,13 @@ export async function deleteAgentDirect( // and letting a fresh archive take this agent mid-teardown. try { await deps.waitForRunner?.(agent); - await runLifecycleHook("stop", agent, logger, { - local: deps.localRunner, - remote: deps.remote, - }).catch((err) => + await runLifecycleHook( + "stop", + agent, + logger, + { local: deps.localRunner, remote: deps.remote }, + deps.whileFenced && ((request) => deps.whileFenced!(agent, request)) + ).catch((err) => logger.warn( { err, agentId: id }, "Stop hook failed during delete; continuing" diff --git a/apps/server/src/agents/lifecycle-hooks.ts b/apps/server/src/agents/lifecycle-hooks.ts index b1ae1f34b..48ce3a415 100644 --- a/apps/server/src/agents/lifecycle-hooks.ts +++ b/apps/server/src/agents/lifecycle-hooks.ts @@ -31,20 +31,24 @@ export type LifecycleHookName = "stop"; * * Runs with `DISPATCH_AGENT_ID` exported in env so the hook can * disambiguate which agent triggered it. 15-second hard timeout. + * + * A runner's update fence can land between any two of its requests: + * `whileFenced` repeats the refused one once the runner's hold opens. */ export async function runLifecycleHook( hookName: LifecycleHookName, agent: AgentRecord, logger: FastifyBaseLogger, - runners: CheckoutCommandRunners + runners: CheckoutCommandRunners, + whileFenced: (request: () => Promise) => Promise = (request) => + request() ): Promise { for (const checkout of ["launch", "moved"] as const) { try { const target = { checkout, path: REPO_TOOL_MANIFEST_PATH }; - const file = await requestCheckoutCommand(runners, agent, { - ...target, - kind: "read", - }); + const file = await whileFenced(() => + requestCheckoutCommand(runners, agent, { ...target, kind: "read" }) + ); const hook = file && parseRepoHooks(parseRepoToolFile(file.content))[hookName]; if (!hook) continue; @@ -52,12 +56,14 @@ export async function runLifecycleHook( { agentId: agent.id, hook: hookName, checkout }, "Running lifecycle hook" ); - const result = await requestCheckoutCommand(runners, agent, { - ...target, - kind: "run", - state: file.state, - argv: hook.command, - }); + const result = await whileFenced(() => + requestCheckoutCommand(runners, agent, { + ...target, + kind: "run", + state: file.state, + argv: hook.command, + }) + ); if (result.exitCode !== 0) { logger.warn( { diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 68df213c9..184e4bf7d 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -2731,8 +2731,9 @@ export class AgentManager { } /** - * A step after the host is up that the fence refused: the host exists, so - * wait for the hold in place and try the same step again. + * A step the fence refused partway through work that was admitted before + * it: nothing of the step started, so wait for the hold in place and try + * the same step again. */ private async whileFenced( agent: AgentRecord, @@ -3396,10 +3397,13 @@ export class AgentManager { await this.setAgentStatus(id, "stopping", null); // Run repo-defined stop hook (best-effort, non-blocking) - await runLifecycleHook("stop", agent, this.logger, { - local: this.localRunner, - remote: this.remote, - }).catch((err) => + await runLifecycleHook( + "stop", + agent, + this.logger, + { local: this.localRunner, remote: this.remote }, + (request) => this.whileFenced(agent, request) + ).catch((err) => this.logger.warn( { err, agentId: id }, "Stop hook failed; continuing shutdown" @@ -3809,6 +3813,8 @@ export class AgentManager { const placement = remotePlacement(agent.cwd); if (placement) await this.holds!.wait(placement.runner, "stop"); }, + whileFenced: (agent: AgentRecord, request: () => Promise) => + this.whileFenced(agent, request), }), }; } diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index ac51eba82..bd01f4ad0 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -31,7 +31,8 @@ import { compareRunnerVersions } from "./update-verify.js"; * and from any of them an outcome: updated, rolled_back, deferred or * needs_idle. Each step is saved before the frame that causes it is sent, so * a restarted Dispatch or a reconnected runner resumes the same attempt or - * ends it. The runner owns the swap and its rollback; this only asks, + * ends it. Work goes on while the runner stages, and is held from `ready`, + * before the fence is asked for. The runner owns the swap and its rollback; this only asks, * observes and confirms. It never drains, forces or picks an update itself. */ @@ -52,7 +53,7 @@ export const UPDATE_TIMING = { tickMs: 1_000, } as const; -/** The task-5 hold outlasts every phase above. */ +/** The task-5 hold outlasts every phase it covers. */ export const UPDATE_HOLD_BOUND_MS = 20 * 60_000; const targetSchema = z.object({ @@ -321,6 +322,8 @@ export class RunnerUpdateCoordinator { id: attempt.id, phase: attempt.phase, ...(attempt.target && { version: attempt.target.version }), + ...(this.options.holds.current(runnerId)?.attemptId === + attempt.id && { held: true }), }, }; @@ -398,8 +401,8 @@ export class RunnerUpdateCoordinator { sha256, revision: build.revision!, }; - // A restart already past host shutdown must finish before work is held, - // or it would wait on the hold with its agent down. + // A restart already past host shutdown must finish before the attempt + // starts, or it could meet the hold at `ready` with its agent down. this.opening.add(runnerId); try { await agents.settleRunnerHostRecycling(runnerId); @@ -413,15 +416,6 @@ export class RunnerUpdateCoordinator { deadline: this.now() + UPDATE_TIMING.stagingMs, }; await this.save({ ...this.records.get(runnerId), runnerId, attempt }); - try { - await this.holdFor(runnerId, attempt.id); - } catch (error) { - await this.finish(runnerId, attempt, { - state: "deferred", - reason: "state_unsaved", - }); - throw error; - } this.resumed.set(runnerId, epoch); this.forgetTrial(runnerId); logger.info( @@ -503,14 +497,12 @@ export class RunnerUpdateCoordinator { return; } - try { - await this.holdFor(runnerId, attempt.id); - } catch (error) { - this.options.logger.error( - { err: error, runnerId }, - "could not restore the runner update hold" - ); - return this.cancel(runnerId, attempt, "state_unsaved"); + // Nothing waits on an attempt the runner is not fenced for and was not + // asked to fence. + if (pending || attempt.phase === "settling" || attempt.activated) { + if (!(await this.holdOrCancel(runnerId, attempt))) return; + } else { + this.releaseOther(runnerId, attempt.id); } switch (attempt.phase) { case "cancelling": @@ -681,6 +673,8 @@ export class RunnerUpdateCoordinator { }; if (!(await this.step(runnerId, attempt, settling))) return; } else if (phase !== "settling") return; + // Staged: work waits from here, before anything can be refused. + if (!(await this.holdOrCancel(runnerId, attempt))) return; this.send(runnerId, () => service.fenceUpdate(runnerId, attempt.id, true, epoch) ); @@ -874,12 +868,32 @@ export class RunnerUpdateCoordinator { ); } + /** False when the hold could not be saved, which ends the attempt. */ + private async holdOrCancel(runnerId: string, attempt: Attempt) { + try { + await this.holdFor(runnerId, attempt.id); + return true; + } catch (error) { + this.options.logger.error( + { err: error, runnerId }, + "could not hold the runner for its update" + ); + await this.cancel(runnerId, attempt, "state_unsaved"); + return false; + } + } + private async holdFor(runnerId: string, attemptId: string) { - const { holds } = this.options; - const other = holds.current(runnerId); + this.releaseOther(runnerId, attemptId); + await this.options.holds.begin(runnerId, attemptId, { + boundMs: UPDATE_HOLD_BOUND_MS, + }); + } + + private releaseOther(runnerId: string, attemptId: string) { + const other = this.options.holds.current(runnerId); if (other && other.attemptId !== attemptId) this.release(runnerId, other.attemptId, "fence_released"); - await holds.begin(runnerId, attemptId, { boundMs: UPDATE_HOLD_BOUND_MS }); } /** Move hosts to the last confirmed build while the runner still runs it. */ diff --git a/apps/server/test/agent-archive.test.ts b/apps/server/test/agent-archive.test.ts index e50bb95fc..d8371004e 100644 --- a/apps/server/test/agent-archive.test.ts +++ b/apps/server/test/agent-archive.test.ts @@ -614,7 +614,8 @@ describe("executeArchive", () => { "stop", agent, expect.anything(), - { local: deps.localRunner, remote: undefined } + { local: deps.localRunner, remote: undefined }, + undefined ); }); diff --git a/apps/server/test/db/runner-update-hold-manager.test.ts b/apps/server/test/db/runner-update-hold-manager.test.ts index cf94f1712..d4e32b214 100644 --- a/apps/server/test/db/runner-update-hold-manager.test.ts +++ b/apps/server/test/db/runner-update-hold-manager.test.ts @@ -45,6 +45,8 @@ vi.mock("../../src/agents/workspace-prep.js", () => ({ })); const { AgentManager } = await import("../../src/agents/manager.js"); +type Manager = InstanceType; +const { deleteAgentDirect } = await import("../../src/agents/archive.js"); const { createInertRuntime } = await import("../../src/agents/runtime.js"); const { RunnerUpdateFenced } = await import("../../src/agents/remote/service.js"); @@ -558,6 +560,50 @@ describe("launches on a runner held for an update", () => { expect(await statusOf(held.id)).toBe("stopped"); }); + it.each([ + ["a stop", (manager: Manager, id: string) => manager.stopAgent(id)], + [ + "an archive", + async (manager: Manager, id: string) => { + await manager.beginArchive(id, "keep"); + await manager.executeArchive(id, { + onPhaseChange: () => {}, + onComplete: () => {}, + onError: () => {}, + }); + }, + ], + [ + "a cascade", + (manager: Manager, id: string) => + deleteAgentDirect((manager as any).archiveDeps(), id), + ], + ] as const)( + "finishes the hook of %s that the fence landed in", + async (_case, end) => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + // The hold begins at `ready`, the fence straight after it. + refuseNext.set("checkoutCommand", async () => { + await holds.begin("r1", ATTEMPT); + }); + const hookRequests = () => + requestSession.mock.calls + .map(([, operation]) => operation as any) + .filter(({ kind }) => kind === "checkoutCommand") + .map(({ operation }) => operation.checkout); + const ending = end(manager, agent.id); + await vi.waitFor(() => expect(holds.isHeld("r1")).toBe(true)); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(hookRequests()).toEqual(["launch"]); + await holds.release("r1", ATTEMPT, "committed"); + await ending; + expect(hookRequests()).toEqual(["launch", "launch", "moved"]); + } + ); + it("runs held launches at the bound when the hold is never released", async () => { const holds = await openHolds(300); const runtime = spyRuntime(); diff --git a/apps/server/test/lifecycle-hooks.test.ts b/apps/server/test/lifecycle-hooks.test.ts index 04c710724..6e7ea0895 100644 --- a/apps/server/test/lifecycle-hooks.test.ts +++ b/apps/server/test/lifecycle-hooks.test.ts @@ -132,6 +132,41 @@ describe("runLifecycleHook", () => { }); }); +it("puts each of a hook's runner requests through the fence retry", async () => { + const refused = new Set(["read", "run"]); + const kinds: string[] = []; + const requestSession = vi.fn(async (_placement, { operation }) => { + kinds.push(`${operation.checkout} ${operation.kind}`); + if (refused.delete(operation.kind)) throw new Error("fenced"); + const content = JSON.stringify({ hooks: { stop: { command: ["true"] } } }); + return { + value: JSON.stringify( + operation.kind === "read" + ? { content, state: "a".repeat(64) } + : { exitCode: 0, stderr: "", stdout: "", truncated: false } + ), + }; + }); + await runLifecycleHook( + "stop", + { id: "session", cwd: "runner://machine/work" } as AgentRecord, + logger, + { + local: createLocalRunner("/tmp/runner-hooks-unused", logger), + remote: { requestSession } as unknown as RemoteRunnerService, + }, + (request) => request().catch(request) + ); + expect(kinds).toEqual([ + "launch read", + "launch read", + "launch run", + "launch run", + "moved read", + "moved run", + ]); +}); + it("reports a runner hook failure and still runs the moved checkout on each teardown attempt", async () => { const warn = vi.fn(); const call = vi.fn(async (_placement, { operation }) => { diff --git a/apps/server/test/runner-update-coordinator.test.ts b/apps/server/test/runner-update-coordinator.test.ts index a58cc804a..a8d5ed9dc 100644 --- a/apps/server/test/runner-update-coordinator.test.ts +++ b/apps/server/test/runner-update-coordinator.test.ts @@ -1,7 +1,7 @@ import { mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { fileRunnerUpdateStore, @@ -93,8 +93,9 @@ describe("a live update", () => { available: { version: target.version, action: "update" }, }); const { attemptId } = await update(); - expect(world.holds.current(RUNNER)?.attemptId).toBe(attemptId); await world.until(() => world.runner.trial?.phase === "prepared"); + expect(world.holds.current(RUNNER)?.attemptId).toBe(attemptId); + expect(world.coordinator.view(RUNNER)?.attempt?.held).toBe(true); expect(world.agents.startRunnerHostRecycling).not.toHaveBeenCalled(); expect(world.attempt()).toMatchObject({ id: attemptId, @@ -172,11 +173,29 @@ describe("a live update", () => { ); }); - it("begins that hold before the offer leaves", async () => { + it("lets work through while the runner stages", async () => { + await online(); + const begin = vi.spyOn(world.holds, "begin"); + const { attemptId, release } = await staging(); + await world.settle(); + expect(begin).not.toHaveBeenCalled(); + expect(world.holds.isHeld(RUNNER)).toBe(false); + expect(world.admission.closed).toBe(false); + expect(world.coordinator.view(RUNNER)?.attempt).toEqual({ + id: attemptId, + phase: "staging", + version: target.version, + }); + release(); + await world.until(() => world.holds.isHeld(RUNNER)); + }); + + it("begins that hold at ready, before the fence is asked for", async () => { await online(); const order: string[] = []; const begin = world.holds.begin.bind(world.holds); world.holds.begin = async (...args) => { + order.push(world.attempt()!.phase); const hold = await begin(...args); order.push("held"); expect(Date.parse(hold.expiresAt) - Date.parse(hold.beganAt)).toBe( @@ -189,8 +208,14 @@ describe("a live update", () => { order.push(world.saved.records.length ? "saved" : "unsaved", "offered"); return offer(...args); }; + const fence = world.service.fenceUpdate.bind(world.service); + world.service.fenceUpdate = (...args) => { + order.push("fence"); + return fence(...args); + }; await update(); - expect(order).toEqual(["held", "saved", "offered"]); + await world.until(() => order.includes("fence")); + expect(order).toEqual(["saved", "offered", "settling", "held", "fence"]); }); }); @@ -294,7 +319,7 @@ describe("requests", () => { await expect(update()).rejects.toEqual(ineligible("update_in_progress")); }); - it("settles recycling before holding and does not restart it meanwhile", async () => { + it("settles recycling before the attempt and does not restart it meanwhile", async () => { await online(); await updated(); await world.restartController({ @@ -312,13 +337,17 @@ describe("requests", () => { const request = update(); await world.until(() => settled); expect(world.holds.isHeld(RUNNER)).toBe(false); + const offers = world.sent("update_offer").length; // A reconnect while the pass settles must not start it again. await world.connect(); await world.settle(); expect(world.agents.startRunnerHostRecycling).not.toHaveBeenCalled(); + expect(world.sent("update_offer")).toHaveLength(offers); settled(); await request; - expect(world.holds.isHeld(RUNNER)).toBe(true); + // Nor while the runner stages, when nothing is held yet. + await world.connect(); + await world.settle(); expect(world.agents.startRunnerHostRecycling).not.toHaveBeenCalled(); }); @@ -794,27 +823,30 @@ describe("outcomes", () => { }); describe("deadlines", () => { - it("cancels staging, and holds until the runner answers", async () => { + it("cancels staging without ever holding work", async () => { await online(); await staging(); + const begin = vi.spyOn(world.holds, "begin"); world.advance(UPDATE_TIMING.stagingMs - 1); await world.settle(); expect(world.sent("update_cancel")).toEqual([]); world.advance(1); await world.until(() => world.result()?.reason === "staging_timeout"); expect(world.sent("update_cancel")[0].reason).toBe("policy_changed"); + expect(begin).not.toHaveBeenCalled(); expect(world.holds.isHeld(RUNNER)).toBe(false); }); it("stays held until the cancel is answered or its bound passes", async () => { await online(); - await staging(); + await settling(); world.service.cancelUpdate = () => ({ epoch: 1 }); - world.advance(UPDATE_TIMING.stagingMs); + world.advance(UPDATE_TIMING.attachMs); await world.until(() => world.phase() === "cancelling"); expect(world.holds.isHeld(RUNNER)).toBe(true); + expect(world.coordinator.view(RUNNER)?.attempt?.held).toBe(true); world.advance(UPDATE_TIMING.cancelMs); - await world.until(() => world.result()?.reason === "staging_timeout"); + await world.until(() => world.result()?.reason === "attach_unavailable"); expect(world.holds.isHeld(RUNNER)).toBe(false); }); @@ -927,14 +959,18 @@ describe("deadlines", () => { }); describe("Dispatch restarts", () => { - it("resumes while staging", async () => { + it("resumes while staging, still without a hold", async () => { await online(); const { attemptId, release } = await staging(); await world.restartController(); - expect(world.holds.current(RUNNER)?.attemptId).toBe(attemptId); expect(world.phase()).toBe("staging"); await world.connect(); + await world.settle(); + expect(world.holds.isHeld(RUNNER)).toBe(false); release(); + await world.until( + () => world.holds.current(RUNNER)?.attemptId === attemptId + ); await world.swap(); await world.until(() => world.result()?.state === "updated"); expect(world.attempt()?.id).toBe(attemptId); @@ -1037,15 +1073,17 @@ describe("Dispatch restarts", () => { } ); - it("finishes cancelling", async () => { + it("finishes cancelling, without holding for a cancel of staging", async () => { await online(); await staging(); world.service.cancelUpdate = () => ({ epoch: 1 }); world.advance(UPDATE_TIMING.stagingMs); await world.until(() => world.phase() === "cancelling"); await world.restartController(); + const begin = vi.spyOn(world.holds, "begin"); await world.connect(); await world.until(() => world.result()?.reason === "staging_timeout"); + expect(begin).not.toHaveBeenCalled(); expect(world.sent("update_cancel")).toHaveLength(1); }); @@ -1103,6 +1141,69 @@ describe("runner reconnects", () => { ); }); + it("holds again while settling on a runner that lost its fence", async () => { + await online(); + const attemptId = await settling(); + await world.disconnect(); + await world.holds.release(RUNNER, attemptId, "expired"); + world.runner.fence.record = null; + world.runner.staging = new Promise(() => {}); + await world.restartRunner(); + await world.until( + () => world.holds.current(RUNNER)?.attemptId === attemptId + ); + }); + + it("holds an attempt saved as staging that the runner is fenced for", async () => { + await online(); + const attemptId = await settling(); + const { retained: _, ...attempt } = world.saved.records[0]!.attempt; + world.saved.records[0]!.attempt = { ...attempt, phase: "staging" }; + world.saved.holds = { holds: [], resuming: [] }; + await world.restartController(); + await world.connect(); + await world.until( + () => world.holds.current(RUNNER)?.attemptId === attemptId + ); + }); + + it("holds an activated attempt until its outcome is learned", async () => { + await online(); + const attemptId = await confirming(); + await world.disconnect(); + await world.holds.release(RUNNER, attemptId, "expired"); + world.runner.fence.record = null; + world.runner.trial = null; + world.service.cancelUpdate = () => ({ epoch: 1 }); + await world.restartRunner(); + await world.until( + () => world.holds.current(RUNNER)?.attemptId === attemptId + ); + }); + + it("opens another attempt's hold while its own is staging", async () => { + await online(); + await staging(); + await world.holds.begin(RUNNER, "7f1c1d1e-2a3b-4c5d-8e9f-0a1b2c3d4e5f"); + expect(world.coordinator.view(RUNNER)?.attempt?.held).toBeUndefined(); + await world.connect(); + await world.until(() => !world.holds.isHeld(RUNNER)); + expect(world.phase()).toBe("staging"); + }); + + it("cancels what it cannot hold again", async () => { + await online(); + const attemptId = await settling(); + await world.disconnect(); + await world.holds.release(RUNNER, attemptId, "expired"); + world.holds.begin = async () => { + throw new Error("hold failed"); + }; + await world.connect(); + await world.until(() => world.result()?.reason === "state_unsaved"); + expect(world.sent("update_offer")).toHaveLength(1); + }); + it("replaces a hold left by another attempt with its own", async () => { await online(); const attemptId = await confirming(); @@ -1355,14 +1456,15 @@ describe("saving", () => { expect(world.holds.isHeld(RUNNER)).toBe(false); }); - it("starts nothing it cannot hold", async () => { + it("fences nothing it cannot hold", async () => { await online(); world.holds.begin = async () => { throw new Error("hold failed"); }; - await expect(update()).rejects.toThrow("hold failed"); - expect(world.runner.frames).toEqual([]); - expect(world.attempt()?.outcome?.reason).toBe("state_unsaved"); + await update(); + await world.until(() => world.result()?.reason === "state_unsaved"); + expect(world.sent("update_fence")).toEqual([]); + expect(world.admission.closed).toBe(false); }); it("keeps a private file and sets a damaged one aside", async () => { diff --git a/apps/web/src/components/app/runner-update.test.tsx b/apps/web/src/components/app/runner-update.test.tsx index 96c7a7e95..483af12a5 100644 --- a/apps/web/src/components/app/runner-update.test.tsx +++ b/apps/web/src/components/app/runner-update.test.tsx @@ -82,10 +82,17 @@ it.each([ show({ attempt: { id: "a", phase, version } }); expect(text()).toContain("Updating to 1.8.0"); expect(text()).toContain(progress); - expect(text()).toContain("New work waits until the update finishes."); + expect(text()).not.toContain("New work waits"); expect(screen.queryByRole("button")).toBeNull(); }); +it("says new work waits once, and only while, it is held", () => { + const view = show({ attempt: { id: "a", phase: "staging", version } }); + expect(text()).not.toContain("New work waits"); + view.update({ attempt: { id: "a", phase: "settling", version, held: true } }); + expect(text()).toContain("New work waits until the update finishes."); +}); + it.each([ [1, "1 agent still on the previous build"], [3, "3 agents still on the previous build"], diff --git a/apps/web/src/components/app/runner-update.tsx b/apps/web/src/components/app/runner-update.tsx index aaab2ac9b..47ae232e8 100644 --- a/apps/web/src/components/app/runner-update.tsx +++ b/apps/web/src/components/app/runner-update.tsx @@ -159,7 +159,7 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { {detail}

    )} - {attempt &&

    New work waits until the update finishes.

    } + {attempt?.held &&

    New work waits until the update finishes.

    } {!attempt && previousBuildAgents ? (

    {previousBuildAgents}{" "} diff --git a/docs/remote-runner-linux.md b/docs/remote-runner-linux.md index b07774009..3a1130bc6 100644 --- a/docs/remote-runner-linux.md +++ b/docs/remote-runner-linux.md @@ -146,9 +146,10 @@ branch. A public HTTPS URL or an empty session folder works without signing in. ## Update or recover A runner that supports self-update shows **Update** in its Settings when -Dispatch serves a newer version. Dispatch holds new work for that runner, the -runner switches under its running agents, and each agent moves to the new -build when it is next idle. Open terminals close. A failed update returns to +Dispatch serves a newer version. Work goes on while the runner downloads and +verifies it. Then Dispatch holds new work for that runner, the runner switches +under its running agents, and each agent moves to the new build when it is +next idle. Open terminals close. A failed update returns to the previous build, and that build needs **Retry** to install again. Dispatch never offers a runner an older build or another build of the version it has. diff --git a/packages/shared/src/runner-update-types.ts b/packages/shared/src/runner-update-types.ts index 8bce0c580..910cf5ab2 100644 --- a/packages/shared/src/runner-update-types.ts +++ b/packages/shared/src/runner-update-types.ts @@ -18,7 +18,13 @@ export type RunnerUpdateResultState = export type RunnerUpdateView = { /** An update Dispatch can run now, and the action that starts it. */ available?: { version: string; action: RunnerUpdateAction }; - attempt?: { id: string; phase: RunnerUpdatePhaseView; version?: string }; + attempt?: { + id: string; + phase: RunnerUpdatePhaseView; + version?: string; + /** New work for the runner waits: from staged until the attempt ends. */ + held?: boolean; + }; result?: { state: RunnerUpdateResultState; version?: string; From 611ac9b64eaa09c53e121058717cf337ecb5d359 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 20:39:40 -0700 Subject: [PATCH 300/642] Recheck a dev artifact directory when its files change A dev directory is republished in place, so a failure found in half published files, or a build loaded before them, hid the new one. Cache either only while the files they came from are unchanged. Releases keep their 60 second backoff. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/server/runner-artifacts.ts | 74 ++++++++++++++--- apps/server/test/runner-artifacts.test.ts | 93 ++++++++++++++++++++++ 2 files changed, 156 insertions(+), 11 deletions(-) diff --git a/apps/server/src/server/runner-artifacts.ts b/apps/server/src/server/runner-artifacts.ts index da88f4bad..1bd9b8079 100644 --- a/apps/server/src/server/runner-artifacts.ts +++ b/apps/server/src/server/runner-artifacts.ts @@ -1,6 +1,6 @@ import { pipeline } from "node:stream/promises"; import { createGzip } from "node:zlib"; -import { constants, createWriteStream, type Stats } from "node:fs"; +import { constants, createWriteStream, lstatSync, type Stats } from "node:fs"; import { lstat, mkdtemp, open, rename, rm } from "node:fs/promises"; import path from "node:path"; import { @@ -137,6 +137,7 @@ export async function openRunnerArtifact( } const PREPARATION_RETRY_MS = 60_000; +type PreparationFailure = { error: unknown; retryAt: number; inputs?: string }; export function createRunnerArtifactSource( build: { revision: string; version: string; compiled: boolean }, @@ -154,7 +155,8 @@ export function createRunnerArtifactSource( RunnerArch | undefined, { loaded?: Promise; - failure?: { error: unknown; retryAt: number }; + inputs?: string; + failure?: PreparationFailure; } >(); const updateStates = new Map< @@ -162,13 +164,56 @@ export function createRunnerArtifactSource( { loaded?: Promise; evicting?: Promise; - failure?: { error: unknown; retryAt: number }; + inputs?: string; + failure?: PreparationFailure; } >(); const filePath = ( name: RunnerArtifactName | ReturnType ) => path.join(directory, name); + /** + * A dev directory is republished in place, so what was found in it, a + * failure too, lasts only as long as those files. A release's never change. + */ + function devInputs(arch?: RunnerArch) { + if (source !== "dev") return undefined; + const names = arch + ? [BOOTSTRAP, runnerArchiveName(arch), runnerManifestName(arch)] + : [BOOTSTRAP]; + return names + .map((name) => { + try { + const stat = lstatSync(path.join(directory, name)); + return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`; + } catch { + return "missing"; + } + }) + .join(); + } + + function stillFailed( + failure: PreparationFailure | undefined, + arch?: RunnerArch + ) { + return ( + failure !== undefined && + now() < failure.retryAt && + failure.inputs === devInputs(arch) + ); + } + + /** Drop what was loaded from files that have since been republished. */ + function followInputs( + state: { loaded?: unknown; inputs?: string }, + arch?: RunnerArch + ) { + const inputs = devInputs(arch); + if (state.inputs !== inputs) state.loaded = undefined; + state.inputs = inputs; + } + async function check( names: (RunnerArtifactName | ReturnType)[], verify: () => Promise @@ -298,8 +343,7 @@ export function createRunnerArtifactSource( // host's architecture, so a failing arch payload surfaces as a 503 when the // installer fetches it. function preparationFailed() { - const failure = states.get(undefined)?.failure; - return failure !== undefined && now() < failure.retryAt; + return stillFailed(states.get(undefined)?.failure); } async function get(arch?: RunnerArch) { @@ -308,8 +352,8 @@ export function createRunnerArtifactSource( state = {}; states.set(arch, state); } - if (state.failure && now() < state.failure.retryAt) - throw state.failure.error; + if (stillFailed(state.failure, arch)) throw state.failure!.error; + followInputs(state, arch); const pending = (state.loaded ??= load(arch)); try { const artifacts = await pending; @@ -323,7 +367,11 @@ export function createRunnerArtifactSource( return artifacts; } catch (error) { if (state.loaded === pending) { - state.failure = { error, retryAt: now() + PREPARATION_RETRY_MS }; + state.failure = { + error, + retryAt: now() + PREPARATION_RETRY_MS, + inputs: state.inputs, + }; state.loaded = undefined; } throw error; @@ -503,8 +551,8 @@ export function createRunnerArtifactSource( updateStates.set(arch, state); } await state.evicting; - if (state.failure && now() < state.failure.retryAt) - throw state.failure.error; + if (stillFailed(state.failure, arch)) throw state.failure!.error; + followInputs(state, arch); // Revalidate the underlying archive even when an update is already loaded. const pending = (state.loaded ??= get(arch).then(({ files }) => loadUpdate(arch, files[0]!) @@ -524,7 +572,11 @@ export function createRunnerArtifactSource( } catch (error) { if (state.loaded === pending) { state.loaded = undefined; - state.failure = { error, retryAt: now() + PREPARATION_RETRY_MS }; + state.failure = { + error, + retryAt: now() + PREPARATION_RETRY_MS, + inputs: state.inputs, + }; const stale = artifacts; if (stale) { state.evicting = (async () => { diff --git a/apps/server/test/runner-artifacts.test.ts b/apps/server/test/runner-artifacts.test.ts index a12df00c2..3a45fb99b 100644 --- a/apps/server/test/runner-artifacts.test.ts +++ b/apps/server/test/runner-artifacts.test.ts @@ -31,6 +31,7 @@ import * as cache from "../src/release-tarball-cache.js"; import { registerRunnerArtifacts } from "../src/routes/runner-artifacts.js"; import { registerRunnerInstaller } from "../src/routes/runner-installer.js"; import * as releases from "../src/server/release-helpers.js"; +import { createRunnerArtifactSource } from "../src/server/runner-artifacts.js"; import * as commands from "../src/shared/lib/run-command.js"; import * as files from "../src/update-recovery/files.js"; @@ -810,6 +811,98 @@ describe("runner update artifacts", () => { await vi.waitFor(() => expect(served?.fd).toBe(-1)); }); + it.each([ + ["a manifest for another version", {}, { version: "1.2.4" }], + ["an archive of another build", { revision: "fedcba654321" }, {}], + ])( + "retries a dev directory that held %s once it is republished", + async (_case, archive, fields) => { + await buildFixture(archive); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID, fields); + dev(); + expect((await app.inject(manifestUrl)).statusCode).toBe(503); + await buildFixture(); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID); + expect((await app.inject(manifestUrl)).statusCode).toBe(200); + } + ); + + it("serves a republished dev build in place of the one it loaded", async () => { + await buildFixture(); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID); + dev(); + expect((await app.inject(manifestUrl)).statusCode).toBe(200); + await buildFixture(); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID); + expect((await app.inject(manifestUrl)).statusCode).toBe(200); + }); + + it("retries a dev manifest republished on its own", async () => { + await buildFixture(); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID, { + version: "1.2.4", + }); + dev(); + expect((await app.inject(manifestUrl)).statusCode).toBe(503); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID); + expect((await app.inject(manifestUrl)).statusCode).toBe(200); + }); + + it("retries a dev archive republished on its own", async () => { + await buildFixture(); + const good = path.join(temp, archiveName); + await copyFile(path.join(inputs, archiveName), good); + await buildFixture({ revision: "fedcba654321" }); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID); + dev(); + expect((await app.inject(manifestUrl)).statusCode).toBe(503); + await copyFile(good, path.join(inputs, archiveName)); + expect((await app.inject(manifestUrl)).statusCode).toBe(200); + }); + + it("keeps a dev failure while its files are unchanged", async () => { + await buildFixture(); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID, { + version: "1.2.4", + }); + dev(); + expect((await app.inject(manifestUrl)).statusCode).toBe(503); + expect((await app.inject(manifestUrl)).statusCode).toBe(503); + expect(devKeys.readRunnerDevPublicKey).toHaveBeenCalledOnce(); + }); + + it("retries files that were republished while it read the old ones", async () => { + await buildFixture(); + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID, { + version: "1.2.4", + }); + dev(); + vi.mocked(devKeys.readRunnerDevPublicKey).mockImplementationOnce( + async () => { + await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID); + return pem; + } + ); + expect((await app.inject(manifestUrl)).statusCode).toBe(503); + expect((await app.inject(manifestUrl)).statusCode).toBe(200); + }); + + it("offers the dev install command once a missing bootstrap is published", async () => { + await buildFixture(); + await rm(path.join(inputs, bootstrapName)); + vi.stubEnv("DISPATCH_RUNNER_ARTIFACT_DEV_DIR", inputs); + const artifacts = createRunnerArtifactSource({ + revision, + version, + compiled: false, + }); + await expect(artifacts.get()).rejects.toThrow("Missing runner artifact"); + expect(artifacts.preparationFailed()).toBe(true); + await writeFile(path.join(inputs, bootstrapName), bootstrap); + expect(artifacts.preparationFailed()).toBe(false); + await expect(artifacts.get()).resolves.toMatchObject({ source: "dev" }); + }); + it("rejects a changed cached executable before serving either file", async () => { await buildFixture(); await signFixture(inputs, keys.RUNNER_UPDATE_DEV_KEY_ID); From 58d54e56f0c694908f0db3d772129b2c0422ae7d Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 21:28:57 -0700 Subject: [PATCH 301/642] Release queued prompts after an unexecuted runner delivery --- apps/server/src/agents/acp/host-client.ts | 18 +++---- apps/server/src/agents/acp/runtime.ts | 5 +- apps/server/test/acp-host.test.ts | 58 ++++++++++++++++++++--- 3 files changed, 66 insertions(+), 15 deletions(-) diff --git a/apps/server/src/agents/acp/host-client.ts b/apps/server/src/agents/acp/host-client.ts index 9c6c7f6bd..9848e0960 100644 --- a/apps/server/src/agents/acp/host-client.ts +++ b/apps/server/src/agents/acp/host-client.ts @@ -43,7 +43,10 @@ const UNKNOWN_EXECUTION = "Runner connection dropped before acknowledgement; execution is unknown."; export class UpdateAcknowledgementLost extends Error { - constructor(readonly reattached: Promise) { + constructor( + readonly reattached: Promise, + readonly receipt?: PromptReceiptState + ) { super(UNKNOWN_EXECUTION); } } @@ -700,16 +703,15 @@ export class HostClient { if (!(error instanceof UpdateAcknowledgementLost) || !journalId) throw error; const welcome = await error.reattached; - if ( - welcome?.promptReceiptSupported !== true || - welcome.journalId !== journalId || - !this.isCurrent(welcome) - ) - throw error; + if (!welcome || !this.isCurrent(welcome)) throw error; + if (welcome.journalId !== journalId) + throw new UpdateAcknowledgementLost(error.reattached, "rotated"); + if (welcome.promptReceiptSupported !== true) throw error; const state = await this.queryPromptReceipt(id, journalId); if (!this.isCurrent(welcome)) throw error; if (state === "accepted") return "accepted"; - if (state !== "unclaimed" || mayReplay?.() === false) throw error; + if (state !== "unclaimed" || mayReplay?.() === false) + throw new UpdateAcknowledgementLost(error.reattached, state); // The host atomically checks the same ID and journal again before // claiming, so even a query-to-send race cannot submit twice. return this.sendPrompt(command); diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index c10f66ff7..5404aff2b 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -720,7 +720,10 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { submitted && !( error instanceof UpdateAcknowledgementLost && - entry.client.isReady() + entry.client.isReady() && + (error.receipt === "claimed" || + (error.receipt === undefined && + entry.client.welcome?.turn != null)) ) ) entry.turnOpen = false; diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index 59cb02f8a..ed952a6b8 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -1142,6 +1142,7 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); it.each([ "unclaimed", "claimed", + "claimed-without-receipt", "accepted", "rotated", "old-host", @@ -1157,7 +1158,7 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); async (mode) => { const f = await updateFixture(); const fifo = path.join(f.folder, "image.png"); - const claimed = mode === "claimed"; + const claimed = mode === "claimed" || mode === "claimed-without-receipt"; const unclaimed = [ "unclaimed", "unheld", @@ -1211,9 +1212,21 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); if (message.type === "prompt_receipt_result") { if (mode === "silent-receipt") return false; if (mode === "receipt-channel-lost") queueMicrotask(drop); - if (mode === "wrong-receipt-journal") + if ( + mode === "wrong-receipt-journal" || + mode === "claimed-without-receipt" + ) return { ...message, journalId: "wrong" }; } + if ( + message.type === "welcome" && + dropped && + (mode === "aborted" || mode === "rotated") + ) + return { + ...message, + turn: { seq: 0, startedAt: new Date().toISOString() }, + }; if (message.type === "welcome" && mode === "old-host") return { ...message, promptReceiptSupported: undefined }; if ( @@ -1285,8 +1298,26 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); state: unclaimed ? "unclaimed" : claimed ? "claimed" : "accepted", }); } else expect(queries).toEqual([]); + const queued = [ + "aborted", + "rotated", + "silent-receipt", + "claimed", + "claimed-without-receipt", + ].includes(mode) + ? f.runtime.prompt(f.id, "next prompt", undefined, { + delivery: "queue", + }) + : undefined; + void queued?.accepted.catch(() => {}); + const sentNext = () => + f.commands.some( + (m) => m.type === "prompt" && m.text === "next prompt" + ); if (claimed) { + await f.holds.release("update-runner", attempt, "committed"); expect(f.runtime.hasOpenTurn(f.id)).toBe(true); + expect(sentNext()).toBe(false); releaseImage = writeFile(fifo, "image"); await releaseImage; } @@ -1297,11 +1328,18 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); ) ); expect( - f.seen.flatMap(({ event }) => - event.type === "turn" ? [event.state] : [] - ) + f.seen + .flatMap(({ event }) => + event.type === "turn" ? [event.state] : [] + ) + .slice(0, claimed ? 2 : undefined) ).toEqual(["started", "settled"]); } + if (mode === "silent-receipt") { + expect( + f.replies.filter((m) => m.type === "welcome").at(-1)?.turn + ).toBeNull(); + } if (mode === "rotated") { const welcomes = f.replies.filter((m) => m.type === "welcome"); expect(welcomes.at(-1)?.journalId).not.toBe(welcomes[0]?.journalId); @@ -1312,8 +1350,16 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); ).toHaveLength(0); } expect(f.invocations()).toBe(unclaimed && mode !== "unclaimed" ? 0 : 1); + if (queued) { + if (!claimed) + await f.holds.release("update-runner", attempt, "committed"); + await until(sentNext); + await queued.accepted; + await queued.settled; + expect(f.runtime.isBusy(f.id)).toBe(false); + } } finally { - if (claimed && !releaseImage && f.tap.offline) + if (claimed && !releaseImage) void writeFile(fifo, "image").catch(() => {}); await f.close(); } From 4ceb21a58cdcbff4293c21c5140a9e0aa4e7f4f8 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 21:28:57 -0700 Subject: [PATCH 302/642] Keep newer agent lifecycle state after a runner hold --- apps/server/src/agents/acp/runtime.ts | 8 +- apps/server/src/agents/archive.ts | 28 +-- apps/server/src/agents/errors.ts | 2 + apps/server/src/agents/lifecycle-hooks.ts | 2 + apps/server/src/agents/manager.ts | 119 +++++++++--- apps/server/src/agents/runtime.ts | 2 + .../db/runner-update-hold-manager.test.ts | 171 ++++++++++++++++++ .../runner-launch-reconcile-runtime.test.ts | 21 +++ 8 files changed, 311 insertions(+), 42 deletions(-) diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 5404aff2b..492a184ca 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -367,7 +367,8 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { placement: Placement | null | undefined, operation: Extract, settings: LocalLaunchSettings, - onProgress?: RuntimeLaunch["onWorkspaceProgress"] + onProgress?: RuntimeLaunch["onWorkspaceProgress"], + beforeReconcile?: RuntimeLaunch["beforeLaunchReconcile"] ): Promise { for (let attempt = 1; ; attempt++) { try { @@ -386,6 +387,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { const pollMs = deps.launchRetryPollMs ?? 250; while (!deps.remote?.available(placement) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, pollMs)); + await beforeReconcile?.(); if ( !deps.remote?.available(placement) || !deps.remote.reconcilesLaunches?.(placement) @@ -1309,13 +1311,15 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { env, pathPrefix, onWorkspaceProgress, + beforeLaunchReconcile, ...launch } = input; const { launchExited } = await requestLaunch( placement, { kind: "launch", agentId: input.agentId, launch }, { cwd, bins, env, pathPrefix }, - onWorkspaceProgress + onWorkspaceProgress, + beforeLaunchReconcile ); try { const entry = await connect( diff --git a/apps/server/src/agents/archive.ts b/apps/server/src/agents/archive.ts index e49ff7e54..456660ad8 100644 --- a/apps/server/src/agents/archive.ts +++ b/apps/server/src/agents/archive.ts @@ -17,7 +17,7 @@ import { import type { RemoteRunnerService } from "./remote/service.js"; import type { CheckoutCommandRunners } from "./checkout-commands.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; -import { AgentError } from "./errors.js"; +import { AgentError, LifecycleSuperseded } from "./errors.js"; import type { AgentRuntime } from "./runtime.js"; import type { AgentRecord, @@ -51,7 +51,7 @@ export type ArchiveDeps = { claim: () => Promise ) => Promise; /** Resolves once the agent's runner is not held for an update. */ - waitForRunner?: (agent: AgentRecord) => Promise; + waitForRunner?: (agent: AgentRecord) => Promise; /** Repeats a request the runner's update fence refused, once it opens. */ whileFenced?: ( agent: AgentRecord, @@ -186,19 +186,20 @@ export async function executeArchive( // Phase: stopping — tear down session without changing agent status const t = Date.now(); try { - await deps.waitForRunner?.(agent); + if ((await deps.waitForRunner?.(agent)) === false) return; await runLifecycleHook( "stop", agent, logger, { local: deps.localRunner, remote: deps.remote }, deps.whileFenced && ((request) => deps.whileFenced!(agent, request)) - ).catch((err) => + ).catch((err) => { + if (err instanceof LifecycleSuperseded) throw err; logger.warn( { err, agentId: id }, "Stop hook failed during archive; continuing" - ) - ); + ); + }); deps.beginStopStream(id); await runtime.stop(id, true); await deps.settleStream(id); @@ -208,6 +209,7 @@ export async function executeArchive( else await runtime.discard(id); stopped = true; } catch (err) { + if (err instanceof LifecycleSuperseded) return; logger.warn( { err, agentId: id }, "Stop during archive failed; continuing" @@ -337,19 +339,22 @@ export async function deleteAgentDirect( // Not stopAgent: it writes `stopping`/`stopped`, releasing the claim above // and letting a fresh archive take this agent mid-teardown. try { - await deps.waitForRunner?.(agent); + if ((await deps.waitForRunner?.(agent)) === false) return []; await runLifecycleHook( "stop", agent, logger, { local: deps.localRunner, remote: deps.remote }, - deps.whileFenced && ((request) => deps.whileFenced!(agent, request)) - ).catch((err) => + deps.whileFenced && + ((request) => + deps.whileFenced!({ ...agent, status: "archiving" }, request)) + ).catch((err) => { + if (err instanceof LifecycleSuperseded) throw err; logger.warn( { err, agentId: id }, "Stop hook failed during delete; continuing" - ) - ); + ); + }); deps.beginStopStream(id); await runtime.stop(id, true); await deps.settleStream(id); @@ -359,6 +364,7 @@ export async function deleteAgentDirect( else await runtime.discard(id); stopped = true; } catch (err) { + if (err instanceof LifecycleSuperseded) return []; logger.warn( { err, agentId: id }, "Stop during delete failed; continuing with deletion" diff --git a/apps/server/src/agents/errors.ts b/apps/server/src/agents/errors.ts index d198adfdf..e4b2075af 100644 --- a/apps/server/src/agents/errors.ts +++ b/apps/server/src/agents/errors.ts @@ -6,3 +6,5 @@ export class AgentError extends Error { this.statusCode = statusCode; } } + +export class LifecycleSuperseded extends Error {} diff --git a/apps/server/src/agents/lifecycle-hooks.ts b/apps/server/src/agents/lifecycle-hooks.ts index 48ce3a415..74309b07a 100644 --- a/apps/server/src/agents/lifecycle-hooks.ts +++ b/apps/server/src/agents/lifecycle-hooks.ts @@ -10,6 +10,7 @@ import { REPO_TOOL_MANIFEST_PATH, } from "../shared/mcp/repo-tools.js"; +import { LifecycleSuperseded } from "./errors.js"; import type { AgentRecord } from "./types.js"; /** @@ -78,6 +79,7 @@ export async function runLifecycleHook( ); } } catch (err) { + if (err instanceof LifecycleSuperseded) throw err; logger.warn( { err, agentId: agent.id, hook: hookName, checkout }, "Runner lifecycle hook failed; continuing shutdown" diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 184e4bf7d..eab235b5a 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -52,7 +52,7 @@ import { type ArchiveCheckoutAgent, } from "./archive-checkout.js"; import type { ArchiveOutcome } from "./archive-policy.js"; -import { AgentError } from "./errors.js"; +import { AgentError, LifecycleSuperseded } from "./errors.js"; import { admitLaunch } from "./launch-admission.js"; import { type AgentEventBus, createAgentEventBus } from "./events.js"; import { runLifecycleHook } from "./lifecycle-hooks.js"; @@ -562,8 +562,9 @@ export class AgentManager { runtime: this.runtime, diagnostics: this.diagnostics, getAgent: (id) => this.getAgent(id), - setAgentStatus: (id, status, lastError) => - this.setAgentStatus(id, status, lastError), + setAgentStatus: async (id, status, lastError) => { + await this.setAgentStatus(id, status, lastError); + }, notifyBlocked: (id, message) => this.emitAttention(id, "blocked", message), setReconnectProgress: (id, phase) => this.setReconnectProgress(id, phase), @@ -2603,6 +2604,7 @@ export class AgentManager { ); } } catch (error) { + if (error instanceof LifecycleSuperseded) throw error; await this.runtime .stop(id, true) .catch((err: unknown) => @@ -2649,7 +2651,8 @@ export class AgentManager { : undefined ); } catch (error) { - await this.failLaunch(id, error); + if (!(error instanceof LifecycleSuperseded)) + await this.failLaunch(id, error); } } @@ -2751,10 +2754,19 @@ export class AgentManager { ) throw error; await this.holds.wait(placement.runner); + await this.assertLifecycleCurrent(agent); } } } + private async assertLifecycleCurrent(agent: AgentRecord): Promise { + const current = await this.getAgent(agent.id); + if (current?.status !== agent.status || current.cwd !== agent.cwd) + throw new LifecycleSuperseded( + "The agent changed while its runner was held." + ); + } + private workspaceProgress( id: string, type: AgentType @@ -3045,7 +3057,11 @@ export class AgentManager { env, pathPrefix, resumeSessionId: opts.resumeSessionId, - ...(placement && opts.launchId && { launchId: opts.launchId }), + ...(placement && + opts.launchId && { + launchId: opts.launchId, + beforeLaunchReconcile: () => this.assertLifecycleCurrent(agent), + }), ...(onWorkspaceProgress && { onWorkspaceProgress }), }); } finally { @@ -3174,6 +3190,8 @@ export class AgentManager { await this.populateGitContext(id); this.eventBus.publish(await this.getRequiredAgent(id)); } catch (error) { + if (error instanceof LifecycleSuperseded) + return this.getRequiredAgent(id); if (error instanceof RecycleSuperseded) { await this.setAgentStatus(id, "stopped", null); return this.getRequiredAgent(id); @@ -3363,7 +3381,9 @@ export class AgentManager { id: string, input: StopAgentInput ): Promise { - const agent = await this.getRequiredAgent(id); + let agent = await this.getRequiredAgent(id); + const placement = remotePlacement(agent.cwd); + const guard = placement && this.holds ? agent.status : undefined; await this.cancelSchedules?.(id).catch((err) => this.logger.warn( { err, agentId: id }, @@ -3371,12 +3391,13 @@ export class AgentManager { ) ); const force = input.force ?? false; + if (guard === "archiving") return agent; // A launch still held for a runner update never reached the runner: // cancelling it is the whole stop. if (await this.holds?.takeLaunch(id)) { - await this.setAgentStatus(id, "stopped", null); - await this.setSetupPhase(id, null); + if (await this.setAgentStatus(id, "stopped", null, undefined, guard)) + await this.setSetupPhase(id, null); return this.getRequiredAgent(id); } @@ -3391,35 +3412,65 @@ export class AgentManager { // The stop hook and the stop run on the runner; its update fence would // refuse both. Wait for a held runner first, with the agent untouched. - const placement = remotePlacement(agent.cwd); - if (placement) await this.holds?.wait(placement.runner, "stop"); + if (placement && this.holds) { + await this.holds.wait(placement.runner, "stop"); + agent = await this.getRequiredAgent(id); + if (agent.status === "archiving" || agent.status === "stopped") + return agent; + } - await this.setAgentStatus(id, "stopping", null); + if ( + !(await this.setAgentStatus( + id, + "stopping", + null, + undefined, + guard && agent.status + )) + ) + return this.getRequiredAgent(id); - // Run repo-defined stop hook (best-effort, non-blocking) - await runLifecycleHook( - "stop", - agent, - this.logger, - { local: this.localRunner, remote: this.remote }, - (request) => this.whileFenced(agent, request) - ).catch((err) => + try { + await runLifecycleHook( + "stop", + agent, + this.logger, + { local: this.localRunner, remote: this.remote }, + (request) => this.whileFenced({ ...agent, status: "stopping" }, request) + ); + } catch (err) { + if (err instanceof LifecycleSuperseded) return this.getRequiredAgent(id); this.logger.warn( { err, agentId: id }, "Stop hook failed; continuing shutdown" - ) - ); + ); + } try { this.streamRecorder.beginStop(id); await this.runtime.stop(id, force); await this.streamRecorder.settleStopped(id); - await this.setAgentStatus(id, "stopped", null); + await this.setAgentStatus( + id, + "stopped", + null, + undefined, + guard && "stopping" + ); this.notifyStreamWrite(id, true); } catch (error) { const message = errorMessage(error); - await this.setAgentStatus(id, "error", message); + if ( + !(await this.setAgentStatus( + id, + "error", + message, + undefined, + guard && "stopping" + )) + ) + return this.getRequiredAgent(id); await this.emitAttention( id, "blocked", @@ -3663,8 +3714,9 @@ export class AgentManager { id: string, status: AgentStatus, lastError: string | null, - onUpdated?: (updatedAt: string) => void - ): Promise { + onUpdated?: (updatedAt: string) => void, + expectedStatus?: AgentStatus + ): Promise { if (status !== "error") this.attentionHistory.settleBlocked(id); if (status === "stopped" || status === "archiving") this.attentionHistory.permissions(id, []); @@ -3675,12 +3727,16 @@ export class AgentManager { last_error = $3, updated_at = NOW() WHERE id = $1 + ${expectedStatus === undefined ? "" : "AND deleted_at IS NULL AND status = $4"} RETURNING updated_at::text AS updated_at `, - [id, status, lastError] + expectedStatus === undefined + ? [id, status, lastError] + : [id, status, lastError, expectedStatus] ); if (result.rowCount !== 1) { + if (expectedStatus !== undefined) return false; this.logger.warn( { id, status }, "Agent status update skipped because row was missing." @@ -3689,6 +3745,7 @@ export class AgentManager { onUpdated?.(result.rows[0].updated_at); this.eventBus.publish(await this.getRequiredAgent(id)); } + return true; } // --- Files --- @@ -3801,8 +3858,9 @@ export class AgentManager { diffStatsRefresher: this.diffStatsRefresher, getAgent: (id) => this.getAgent(id), getRequiredAgent: (id) => this.getRequiredAgent(id), - setAgentStatus: (id, status, lastError) => - this.setAgentStatus(id, status, lastError), + setAgentStatus: async (id, status, lastError) => { + await this.setAgentStatus(id, status, lastError); + }, beginStopStream: (id) => this.streamRecorder.beginStop(id), settleStream: (id) => this.streamRecorder.settleStopped(id), setArchivePhase: (id, phase) => this.setArchivePhase(id, phase), @@ -3811,7 +3869,10 @@ export class AgentManager { ...(this.holds && { waitForRunner: async (agent: AgentRecord) => { const placement = remotePlacement(agent.cwd); - if (placement) await this.holds!.wait(placement.runner, "stop"); + if (!placement || !this.holds!.isHeld(placement.runner)) return true; + await this.holds!.wait(placement.runner, "stop"); + const current = await this.getAgent(agent.id); + return current?.status === "archiving" && current.cwd === agent.cwd; }, whileFenced: (agent: AgentRecord, request: () => Promise) => this.whileFenced(agent, request), diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index c3be0219e..f581d830a 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -29,6 +29,8 @@ export type RuntimeLaunch = HostLaunch & { placement?: Placement; repository?: RunnerRepository; onWorkspaceProgress?: (progress: LaunchProgress) => void; + /** Recheck ownership after waiting for a runner whose launch reply was lost. */ + beforeLaunchReconcile?: () => Promise; }; export type RuntimeEventListener = ( diff --git a/apps/server/test/db/runner-update-hold-manager.test.ts b/apps/server/test/db/runner-update-hold-manager.test.ts index d4e32b214..85aea5c0f 100644 --- a/apps/server/test/db/runner-update-hold-manager.test.ts +++ b/apps/server/test/db/runner-update-hold-manager.test.ts @@ -560,6 +560,177 @@ describe("launches on a runner held for an update", () => { expect(await statusOf(held.id)).toBe("stopped"); }); + it.each(["archiving", "stopped", "deleted"] as const)( + "leaves an agent that became %s alone after a held stop", + async (status) => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + await holds.begin("r1", ATTEMPT); + const stopping = manager.stopAgent(agent.id); + const outcome = stopping.catch((err: Error) => err); + await vi.waitFor(() => expect(holds.counts("r1").stops).toBe(1)); + if (status === "archiving") await manager.beginArchive(agent.id, "keep"); + else if (status === "deleted") + await pool.query("UPDATE agents SET deleted_at = NOW() WHERE id = $1", [ + agent.id, + ]); + else + await pool.query( + "UPDATE agents SET status = 'stopped', last_error = 'newer' WHERE id = $1", + [agent.id] + ); + const before = ( + await pool.query("SELECT * FROM agents WHERE id = $1", [agent.id]) + ).rows[0]; + const queries = vi.spyOn(pool, "query"); + try { + await holds.release("r1", ATTEMPT, "committed"); + if (status === "deleted") + expect(await outcome).toMatchObject({ message: "Agent not found." }); + else expect(await outcome).toMatchObject({ status }); + expect( + queries.mock.calls.some( + ([sql]) => typeof sql === "string" && sql.includes("UPDATE agents") + ) + ).toBe(false); + } finally { + queries.mockRestore(); + } + expect( + (await pool.query("SELECT * FROM agents WHERE id = $1", [agent.id])) + .rows[0] + ).toEqual(before); + expect(runtime.stop).not.toHaveBeenCalled(); + } + ); + + it("does not mark an archiving agent stopped if a late launch hold exists", async () => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + await holds.begin("r1", ATTEMPT); + await manager.beginArchive(agent.id, "keep"); + await holds.holdLaunch("r1", { + agentId: agent.id, + kind: "start", + launchId: ATTEMPT, + }); + expect(await manager.stopAgent(agent.id)).toMatchObject({ + status: "archiving", + }); + expect(await statusOf(agent.id)).toBe("archiving"); + expect(runtime.stop).not.toHaveBeenCalled(); + }); + + it("publishes stopping then stopped with no hold", async () => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + const statuses: string[] = []; + manager.onAgentUpdated((row) => { + if (row.id === agent.id) statuses.push(row.status); + }); + expect(await manager.stopAgent(agent.id)).toMatchObject({ + status: "stopped", + }); + expect(statuses).toEqual(["stopping", "stopped"]); + expect(runtime.stop).toHaveBeenCalledExactlyOnceWith(agent.id, false); + }); + + it("does not claim stopping if archive won after the post-hold read", async () => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + const query = pool.query.bind(pool); + const intercepted = vi.spyOn(pool, "query").mockImplementation((async ( + sql: string, + values?: unknown[] + ) => { + if (values?.[0] === agent.id && values[1] === "stopping") + await manager.beginArchive(agent.id, "keep"); + return query(sql, values); + }) as typeof pool.query); + try { + expect(await manager.stopAgent(agent.id)).toMatchObject({ + status: "archiving", + }); + expect(runtime.stop).not.toHaveBeenCalled(); + } finally { + intercepted.mockRestore(); + } + }); + + it.each([false, true])( + "preserves an archive claimed during runtime.stop (stop failed=%s)", + async (fails) => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + runtime.stop.mockImplementationOnce(async () => { + await manager.beginArchive(agent.id, "keep"); + if (fails) throw new Error("stop failed"); + }); + expect(await manager.stopAgent(agent.id)).toMatchObject({ + status: "archiving", + }); + expect(await statusOf(agent.id)).toBe("archiving"); + } + ); + + it("skips archive teardown if the agent was deleted during the hold", async () => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + await holds.begin("r1", ATTEMPT); + await manager.beginArchive(agent.id, "keep"); + const archiving = manager.executeArchive(agent.id, { + onPhaseChange: vi.fn(), + onComplete: vi.fn(), + onError: vi.fn(), + }); + await vi.waitFor(() => expect(holds.counts("r1").stops).toBe(1)); + await pool.query("UPDATE agents SET deleted_at = NOW() WHERE id = $1", [ + agent.id, + ]); + await holds.release("r1", ATTEMPT, "committed"); + await archiving; + expect(runtime.stop).not.toHaveBeenCalled(); + expect(runtime.discard).not.toHaveBeenCalled(); + }); + + it("skips retrying the refused stop hook after archive takes over", async () => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + refuseNext.set("checkoutCommand", async () => { + await holds.begin("r1", ATTEMPT); + }); + const stopping = manager.stopAgent(agent.id); + await vi.waitFor(() => expect(holds.isHeld("r1")).toBe(true)); + await manager.beginArchive(agent.id, "keep"); + await holds.release("r1", ATTEMPT, "committed"); + expect(await stopping).toMatchObject({ status: "archiving" }); + const hookReads = requestSession.mock.calls + .map( + ([, operation]) => + operation as { kind: string; operation?: { checkout: string } } + ) + .filter(({ kind }) => kind === "checkoutCommand") + .map(({ operation }) => operation?.checkout); + expect(hookReads.filter((checkout) => checkout === "launch")).toHaveLength( + 1 + ); + expect(runtime.stop).not.toHaveBeenCalled(); + }); + it.each([ ["a stop", (manager: Manager, id: string) => manager.stopAgent(id)], [ diff --git a/apps/server/test/runner-launch-reconcile-runtime.test.ts b/apps/server/test/runner-launch-reconcile-runtime.test.ts index 46bff43c3..578665686 100644 --- a/apps/server/test/runner-launch-reconcile-runtime.test.ts +++ b/apps/server/test/runner-launch-reconcile-runtime.test.ts @@ -50,6 +50,7 @@ async function fixture(options: { reconciles?: boolean; /** Polls the runner stays away after each lost reply. */ offlinePolls?: number; + beforeLaunchReconcile?: RuntimeLaunch["beforeLaunchReconcile"]; }) { const stateRoot = mkdtempSync(path.join(os.tmpdir(), "dispatch-launch-")); cleanup.push(() => rmSync(stateRoot, { recursive: true, force: true })); @@ -140,6 +141,7 @@ async function fixture(options: { env: {}, pathPrefix: [], ...(launchId !== null && { launchId }), + beforeLaunchReconcile: options.beforeLaunchReconcile, } as RuntimeLaunch); return { runtime, holds, launches, available, launch }; } @@ -159,6 +161,25 @@ describe("a launch reply lost across a runner update", () => { expect(available.mock.calls.length).toBeGreaterThanOrEqual(3); }); + it.each([false, true])( + "exits a superseded launch, even when the runner stays offline (%s)", + async (staysOffline) => { + const superseded = new Error( + "The agent changed while its runner was held." + ); + const { holds, launches, launch } = await fixture({ + outcomes: ["lost", "ok"], + ...(staysOffline && { offlinePolls: Number.MAX_SAFE_INTEGER }), + beforeLaunchReconcile: async () => { + throw superseded; + }, + }); + await holds.begin("r1", ATTEMPT, staysOffline ? { boundMs: 50 } : {}); + await expect(launch()).rejects.toBe(superseded); + expect(launches).toEqual([{ launchId: LAUNCH }]); + } + ); + it("hands a fenced repeat to the caller, which holds it", async () => { const { holds, launches, launch } = await fixture({ outcomes: ["lost", "fenced"], From f6a2102dd2c3c808edaa6494118026ad4756c993 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 21:28:57 -0700 Subject: [PATCH 303/642] Finish delivery give-up when a runner hold lookup fails --- apps/server/src/chat/service.ts | 11 +++++- apps/server/test/stream-service.test.ts | 46 +++++++++++++++---------- 2 files changed, 38 insertions(+), 19 deletions(-) diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index ddf645677..24c6270c3 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -4680,7 +4680,16 @@ export class StreamService { // doing its job, so keep waiting. if (this.delivery().activeTurn(agentId)) continue; // Held for a runner update, which is bounded: the queue again. - if (await this.delivery().updateHeld?.(agentId)) continue; + const updateHeld = await this.delivery() + .updateHeld?.(agentId) + .catch((error: unknown) => { + this.log.warn( + { err: error, agentId, ...logContext }, + "stream: could not check runner update hold" + ); + return false; + }); + if (updateHeld) continue; this.log.warn( { agentId, ...logContext }, "stream: the engine never took this prompt; marking it undelivered" diff --git a/apps/server/test/stream-service.test.ts b/apps/server/test/stream-service.test.ts index 693e09973..ab35bd9e3 100644 --- a/apps/server/test/stream-service.test.ts +++ b/apps/server/test/stream-service.test.ts @@ -5755,25 +5755,35 @@ describe("StreamService delivery that is never taken", () => { vi.useRealTimers(); }); - it("gives up on a prompt an idle engine never takes, so the post can be retried", async () => { - vi.useFakeTimers(); - const { svc } = build({ gate: never }); - const res = await svc.sendUserPost(A, { text: "are you there?" }); - expect(res.block.delivered).toBeNull(); - expect(res.held).toBe(true); // The fake queue includes this very prompt. - // Nothing has taken it, and the agent is not busy: past the bound it - // reads as undelivered rather than sending forever. - await vi.advanceTimersByTimeAsync(95_000); - // The give-up writes to the database, which is real work the timer - // flush does not wait for. - vi.useRealTimers(); - let row = await svc.store.getById(res.block.id); - for (let i = 0; i < 50 && row?.delivered === null; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 20)); - row = await svc.store.getById(res.block.id); + it.each([ + ["the local path", vi.fn().mockResolvedValue(false)], + [ + "a failed runner hold lookup", + vi.fn().mockRejectedValue(new Error("DB unavailable")), + ], + ] as const)( + "marks an unaccepted idle prompt undelivered with %s", + async (_, updateHeld) => { + vi.useFakeTimers(); + const { svc } = build({ gate: never, updateHeld }); + const res = await svc.sendUserPost(A, { text: "are you there?" }); + expect(res.block.delivered).toBeNull(); + expect(res.held).toBe(true); // The fake queue includes this very prompt. + // Nothing has taken it, and the agent is not busy: past the bound it + // reads as undelivered rather than sending forever. + await vi.advanceTimersByTimeAsync(95_000); + // The give-up writes to the database, which is real work the timer + // flush does not wait for. + vi.useRealTimers(); + let row = await svc.store.getById(res.block.id); + for (let i = 0; i < 50 && row?.delivered === null; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 20)); + row = await svc.store.getById(res.block.id); + } + expect(row).toMatchObject({ delivered: false }); + expect(updateHeld).toHaveBeenCalledTimes(1); } - expect(row).toMatchObject({ delivered: false }); - }); + ); it("gives up on multiple unaccepted prompts without treating their queue as active work", async () => { vi.useFakeTimers(); From 71d51465757ba12d745e30a17d11acf41affd751 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 21:28:57 -0700 Subject: [PATCH 304/642] Show empty runner engines after an update ends --- .../src/components/app/runner-settings.tsx | 1 + .../runner-engines/runner-engines.test.tsx | 46 +++++++++++-------- .../runner-engines/runner-engines.tsx | 4 +- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/app/runner-settings.tsx b/apps/web/src/components/app/runner-settings.tsx index 994a6d359..ab334887a 100644 --- a/apps/web/src/components/app/runner-settings.tsx +++ b/apps/web/src/components/app/runner-settings.tsx @@ -396,6 +396,7 @@ function RunnerDetail({ {runner.engineCapabilities ? ( { - vi.mocked(api).mockResolvedValue({ entries: null }); - const client = new QueryClient(); - render( - - - - - ); - await waitFor(() => - expect( - client.getQueryData(runnerEnginesKey({ kind: "runner", runnerId: "r1" })) - ).toEqual({ entries: null }) - ); - expect(screen.getByText("Loading engines…")).toBeTruthy(); - expect(screen.queryByText("No engines reported.")).toBeNull(); - expect(screen.queryByText("Set up Claude or Codex")).toBeNull(); -}); +it.each([true, false])( + "shows the unknown inventory state with updating=%s", + async (updating) => { + vi.mocked(api).mockResolvedValue({ entries: null }); + const client = new QueryClient(); + render( + + + + + ); + await waitFor(() => + expect( + client.getQueryData( + runnerEnginesKey({ kind: "runner", runnerId: "r1" }) + ) + ).toEqual({ entries: null }) + ); + const shown = updating ? "Loading engines…" : "No engines reported."; + const hidden = updating ? "No engines reported." : "Loading engines…"; + expect(await screen.findByText(shown)).toBeTruthy(); + expect(screen.queryByText(hidden)).toBeNull(); + expect(screen.queryByText("Set up Claude or Codex")).toBeNull(); + } +); it("shows a failed read over unknown engines", async () => { vi.mocked(api).mockRejectedValue(new Error("down")); diff --git a/apps/web/src/components/runner-engines/runner-engines.tsx b/apps/web/src/components/runner-engines/runner-engines.tsx index 689b9e45e..0c5647e52 100644 --- a/apps/web/src/components/runner-engines/runner-engines.tsx +++ b/apps/web/src/components/runner-engines/runner-engines.tsx @@ -28,9 +28,11 @@ import type { EngineScope } from "@dispatch/runner-protocol/engine-management"; export function RunnerEngines({ scope, capabilities = false, + updating = false, }: { scope: EngineScope; capabilities?: boolean; + updating?: boolean; }): JSX.Element { const inventory = useRunnerEngineInventory(scope); const entries = inventory.data?.entries ?? []; @@ -38,7 +40,7 @@ export function RunnerEngines({ if ( inventory.isLoading || - (!inventory.isError && inventory.data?.entries === null) + (updating && !inventory.isError && inventory.data?.entries === null) ) { return (

    Date: Sat, 21 Nov 2026 21:28:57 -0700 Subject: [PATCH 305/642] Preserve the server update toast across version changes --- .../app/update-available-toast.test.tsx | 56 +++++++++++++++++++ apps/web/src/hooks/use-runners.ts | 4 +- apps/web/src/lib/version.ts | 27 +++++---- 3 files changed, 75 insertions(+), 12 deletions(-) create mode 100644 apps/web/src/components/app/update-available-toast.test.tsx diff --git a/apps/web/src/components/app/update-available-toast.test.tsx b/apps/web/src/components/app/update-available-toast.test.tsx new file mode 100644 index 000000000..40db91beb --- /dev/null +++ b/apps/web/src/components/app/update-available-toast.test.tsx @@ -0,0 +1,56 @@ +// @vitest-environment jsdom +import { act, cleanup, render } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; + +const { info, dismiss, reloadApp } = vi.hoisted(() => ({ + info: vi.fn< + ( + message: string, + options: { + action: { label: string; onClick: () => void }; + onDismiss: () => void; + } + ) => void + >(), + dismiss: vi.fn(), + reloadApp: vi.fn(), +})); + +vi.mock("sonner", () => ({ toast: { info, dismiss } })); +vi.mock("@/lib/pwa-update", () => ({ reloadApp })); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +it("keeps main's toast and reload behavior while notifying Health of newer versions", async () => { + const { UpdateAvailableToast } = await import("./update-available-toast"); + const { BUILD_VERSION, noteServerVersion, subscribeServerVersion } = + await import("@/lib/version"); + const refresh = vi.fn(); + const unsubscribe = subscribeServerVersion(refresh); + const view = render(); + act(() => noteServerVersion(BUILD_VERSION)); + expect(info).not.toHaveBeenCalled(); + + act(() => noteServerVersion("1.0.1")); + expect(info).toHaveBeenCalledTimes(1); + const [message, options] = info.mock.calls[0]; + expect(message).toBe("Server updated to 1.0.1. Reload to pick it up."); + expect(options.action.label).toBe("Reload"); + + act(() => noteServerVersion("1.0.2")); + act(() => noteServerVersion("1.0.2")); + expect(info).toHaveBeenCalledTimes(1); + expect(refresh).toHaveBeenCalledTimes(2); + + options.action.onClick(); + options.action.onClick(); + expect(reloadApp).toHaveBeenCalledTimes(1); + act(options.onDismiss); + view.unmount(); + render(); + expect(info).toHaveBeenCalledTimes(1); + unsubscribe(); +}); diff --git a/apps/web/src/hooks/use-runners.ts b/apps/web/src/hooks/use-runners.ts index 98afbc6aa..f06284408 100644 --- a/apps/web/src/hooks/use-runners.ts +++ b/apps/web/src/hooks/use-runners.ts @@ -4,7 +4,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useEffect } from "react"; import { api } from "@/lib/api"; -import { subscribeVersionMismatch } from "@/lib/version"; +import { subscribeServerVersion } from "@/lib/version"; export type RunnerStatus = "pending" | "online" | "offline" | "revoked"; @@ -45,7 +45,7 @@ export function useWantedBuildRefresh({ health, update }: Runner) { const refresh = () => void queryClient.invalidateQueries({ queryKey: runnerInstallerQueryKey }); refresh(); - return subscribeVersionMismatch(refresh); + return subscribeServerVersion(refresh); }, [queryClient, shown]); } diff --git a/apps/web/src/lib/version.ts b/apps/web/src/lib/version.ts index 63485736a..30c46bae2 100644 --- a/apps/web/src/lib/version.ts +++ b/apps/web/src/lib/version.ts @@ -11,6 +11,7 @@ export const BUILD_VERSION: string = __DISPATCH_VERSION__; type Listener = () => void; const listeners = new Set(); +const serverVersionListeners = new Set(); let serverVersion: string | null = null; let mismatch = false; let dismissed = false; @@ -33,12 +34,11 @@ export function dismissVersionMismatch(): void { notify(); } -// Listeners fire whenever the toast's input state (mismatch flag, the -// mismatched server's version, or dismissal) changes, so the component -// can stay in sync without owning any of it locally — important because -// the toast may unmount and remount (logout/login, Strict Mode -// double-mount, future layout changes) and dismissal needs to survive -// those. +// Listeners fire whenever the toast's input state (mismatch flag or +// dismissal) changes, so the component can stay in sync without owning +// any of it locally — important because the toast may unmount and +// remount (logout/login, Strict Mode double-mount, future layout +// changes) and dismissal needs to survive those. export function subscribeVersionMismatch(listener: Listener): () => void { listeners.add(listener); return () => { @@ -46,18 +46,25 @@ export function subscribeVersionMismatch(listener: Listener): () => void { }; } +export function subscribeServerVersion(listener: Listener): () => void { + serverVersionListeners.add(listener); + return () => { + serverVersionListeners.delete(listener); + }; +} + function notify(): void { for (const listener of listeners) listener(); } export function noteServerVersion(version: string | null | undefined): void { if (!version) return; - const changed = version !== serverVersion; + const changed = serverVersion !== version; serverVersion = version; - if (mismatch) { - if (changed) notify(); - return; + if (changed && (mismatch || version !== BUILD_VERSION)) { + for (const listener of serverVersionListeners) listener(); } + if (mismatch) return; if (version === BUILD_VERSION) return; mismatch = true; notify(); From f796987d41893d6f0f1eadf82ea7d93450a2c5f4 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 23:05:22 -0700 Subject: [PATCH 306/642] Wait on conditions instead of durations in runner update tests Fixed sleeps raced the fsync behind a hold or a delivery, and teardown removed directories that a resumed launch or a prefetched gh command was still writing to. Await the hold waiter, the settled launch, the delivery and the sign-in itself, and drain background work before removing temp directories. Co-Authored-By: Claude Opus 5.5 --- .../db/runner-update-hold-manager.test.ts | 140 +++++++++-------- .../test/github-runner-executor.test.ts | 144 ++++++++++++------ apps/server/test/helpers/hold-work.ts | 44 ++++++ apps/server/test/runner-update-fence.test.ts | 10 +- .../server/test/runner-update-handoff.test.ts | 12 +- .../test/runner-update-hold-runtime.test.ts | 15 +- .../test/runner-update-hold-scheduled.test.ts | 37 +++-- apps/server/test/runner-update-hold.test.ts | 10 +- 8 files changed, 275 insertions(+), 137 deletions(-) create mode 100644 apps/server/test/helpers/hold-work.ts diff --git a/apps/server/test/db/runner-update-hold-manager.test.ts b/apps/server/test/db/runner-update-hold-manager.test.ts index 85aea5c0f..7fe66adfa 100644 --- a/apps/server/test/db/runner-update-hold-manager.test.ts +++ b/apps/server/test/db/runner-update-hold-manager.test.ts @@ -22,6 +22,7 @@ import { import type { RemoteRunnerService } from "../../src/agents/remote/service.js"; import type { AgentRuntime, RuntimeLaunch } from "../../src/agents/runtime.js"; +import { trackHoldWork } from "../helpers/hold-work.js"; import { setupTestDb, teardownTestDb, runTestMigrations } from "./setup.js"; vi.mock("../../src/shared/lib/run-command.js", () => ({ @@ -65,20 +66,21 @@ const noopLogger = { level: "silent", } as unknown as import("fastify").FastifyBaseLogger; -const testConfig = { - host: "127.0.0.1", - port: 6767, - databaseUrl: "", - authToken: "test-token", - filesRoot: "/tmp/dispatch-test-files", - dispatchBinDir: "/tmp/dispatch-test-bin", - codexBin: "/bin/echo", - claudeBin: "/bin/echo", - opencodeBin: "/bin/opencode", - agentStateRoot: "/tmp/dispatch-test-agents", - agentRuntime: "acp", - tls: null, -} satisfies import("../../src/config.js").AppConfig; +const testConfig = (root: string) => + ({ + host: "127.0.0.1", + port: 6767, + databaseUrl: "", + authToken: "test-token", + filesRoot: path.join(root, "files"), + dispatchBinDir: path.join(root, "bin"), + codexBin: "/bin/echo", + claudeBin: "/bin/echo", + opencodeBin: "/bin/opencode", + agentStateRoot: path.join(root, "agents"), + agentRuntime: "acp", + tls: null, + }) satisfies import("../../src/config.js").AppConfig; const ATTEMPT = "11111111-1111-4111-8111-111111111111"; const HELD = "runner://r1/@session"; @@ -88,6 +90,10 @@ let pool: Pool; let dir: string; let holdsFile: string; let opened: InstanceType[] = []; +let work = new Map< + InstanceType, + ReturnType +>(); function spyRuntime() { let sessions = 0; @@ -143,6 +149,7 @@ async function openHolds(boundMs?: number) { ...(boundMs ? { boundMs } : {}), }); opened.push(holds); + work.set(holds, trackHoldWork(holds)); await holds.load(); holds.start(); return holds; @@ -152,7 +159,7 @@ function managerOn( holds: InstanceType, runtime: Spy ) { - return new AgentManager(pool, noopLogger, testConfig, { + return new AgentManager(pool, noopLogger, testConfig(dir), { runtime, remote, holds, @@ -186,7 +193,11 @@ beforeEach(async () => { holdsFile = path.join(dir, "holds.json"); }); afterEach(async () => { + vi.useRealTimers(); for (const holds of opened.splice(0)) holds.close(); + // A released launch saves its outcome after the agent already reads running. + for (const tracked of work.values()) await tracked.settled(); + work.clear(); await rm(dir, { recursive: true, force: true }); }); @@ -219,9 +230,8 @@ describe("launches on a runner held for an update", () => { expect(await statusOf(local.id)).toBe("running"); await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(held.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(held.id)).toBe("running"); expect(launchesFor(runtime, held.id)).toEqual([ [ expect.objectContaining({ @@ -230,11 +240,9 @@ describe("launches on a runner held for an update", () => { }), ], ]); - await vi.waitFor(() => - expect( - promptsFor(runtime, held.id).filter((p) => p.includes("held work")) - ).toHaveLength(1) - ); + expect( + promptsFor(runtime, held.id).filter((p) => p.includes("held work")) + ).toHaveLength(1); expect(holds.counts("r1").launches).toBe(0); }); @@ -265,18 +273,13 @@ describe("launches on a runner held for an update", () => { expect(runtime.attach).not.toHaveBeenCalledWith(held.id); await holds.release("r1", ATTEMPT, "rolled_back"); - await vi.waitFor(async () => - expect(await statusOf(held.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(held.id)).toBe("running"); expect(launchesFor(runtime, held.id)).toHaveLength(1); expect(launchesFor(before, held.id)).toHaveLength(0); - await vi.waitFor(() => - expect( - promptsFor(runtime, held.id).filter((p) => - p.includes("survives restart") - ) - ).toHaveLength(1) - ); + expect( + promptsFor(runtime, held.id).filter((p) => p.includes("survives restart")) + ).toHaveLength(1); }); it("lets a stop during the hold cancel the launch", async () => { @@ -292,7 +295,7 @@ describe("launches on a runner held for an update", () => { expect(holds.counts("r1").launches).toBe(0); await holds.release("r1", ATTEMPT, "committed"); - await new Promise((resolve) => setTimeout(resolve, 50)); + await work.get(holds)!.settled(); expect(launchesFor(runtime, held.id)).toHaveLength(0); expect(await statusOf(held.id)).toBe("stopped"); }); @@ -308,7 +311,7 @@ describe("launches on a runner held for an update", () => { held.id, ]); await holds.release("r1", ATTEMPT, "committed"); - await new Promise((resolve) => setTimeout(resolve, 50)); + await work.get(holds)!.settled(); expect(launchesFor(runtime, held.id)).toHaveLength(0); }); @@ -329,15 +332,12 @@ describe("launches on a runner held for an update", () => { expect(holds.counts("r1").launches).toBe(1); await holds.release("r1", ATTEMPT, "fence_released"); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchesFor(runtime, agent.id)).toHaveLength(2); - await vi.waitFor(() => - expect( - promptsFor(runtime, agent.id).filter((p) => p.includes("refused once")) - ).toHaveLength(1) - ); + expect( + promptsFor(runtime, agent.id).filter((p) => p.includes("refused once")) + ).toHaveLength(1); }); it("fails any other launch error under a hold, as before", async () => { @@ -366,7 +366,7 @@ describe("launches on a runner held for an update", () => { agent.id, ]); await holds.release("r1", ATTEMPT, "committed"); - await new Promise((resolve) => setTimeout(resolve, 50)); + await work.get(holds)!.settled(); expect(launchesFor(runtime, agent.id)).toHaveLength(1); expect(await statusOf(agent.id)).toBe("stopped"); }); @@ -393,11 +393,13 @@ describe("launches on a runner held for an update", () => { }); const stop = manager.stopAgent(agent.id); await inside; + const serialize = vi.spyOn(manager as any, "serializeLifecycle"); await holds.release("r1", ATTEMPT, "committed"); - await new Promise((resolve) => setTimeout(resolve, 50)); + // Queued behind the stop before the stop may finish. + expect(serialize).toHaveBeenCalledWith(agent.id, expect.any(Function)); proceed(); await stop; - await new Promise((resolve) => setTimeout(resolve, 100)); + await work.get(holds)!.settled(); expect(await statusOf(agent.id)).toBe("stopped"); expect(launchesFor(runtime, agent.id)).toHaveLength(1); }); @@ -427,9 +429,8 @@ describe("launches on a runner held for an update", () => { expect((await manager.startAgent(agent.id)).status).toBe("creating"); expect(holds.counts("r1").launches).toBe(1); await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchesFor(runtime, agent.id)).toHaveLength(3); }); @@ -442,7 +443,7 @@ describe("launches on a runner held for an update", () => { await manager.beginArchive(held.id); expect(holds.counts("r1").launches).toBe(0); await holds.release("r1", ATTEMPT, "committed"); - await new Promise((resolve) => setTimeout(resolve, 50)); + await work.get(holds)!.settled(); expect(launchesFor(runtime, held.id)).toHaveLength(0); }); @@ -463,7 +464,7 @@ describe("launches on a runner held for an update", () => { .then(() => { done = true; }); - await new Promise((resolve) => setTimeout(resolve, 50)); + await Promise.race([work.get(holds)!.blocked, archive]); expect(done).toBe(false); expect(runtime.stop).not.toHaveBeenCalled(); expect(holds.counts("r1").stops).toBe(1); @@ -497,8 +498,8 @@ describe("launches on a runner held for an update", () => { created = true; return agent; }); - await vi.waitFor(() => expect(holds.isHeld("r1")).toBe(true)); - await new Promise((resolve) => setTimeout(resolve, 50)); + await Promise.race([work.get(holds)!.blocked, creating]); + expect(holds.isHeld("r1")).toBe(true); expect(created).toBe(false); expect(runtime.stop).not.toHaveBeenCalled(); await holds.release("r1", ATTEMPT, "committed"); @@ -526,9 +527,8 @@ describe("launches on a runner held for an update", () => { expect(launchesFor(runtime, agent.id)).toHaveLength(1); await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchesFor(runtime, agent.id).at(-1)).toEqual([ expect.objectContaining({ resumeSessionId: "sess_1" }), ]); @@ -548,7 +548,7 @@ describe("launches on a runner held for an update", () => { }); await manager.stopAgent(other.id); expect(runtime.stop).toHaveBeenCalledWith(other.id, false); - await new Promise((resolve) => setTimeout(resolve, 50)); + await Promise.race([work.get(holds)!.blocked, stopping]); expect(done).toBe(false); expect(runtime.stop).not.toHaveBeenCalledWith(held.id, false); expect(await statusOf(held.id)).toBe("running"); @@ -570,7 +570,8 @@ describe("launches on a runner held for an update", () => { await holds.begin("r1", ATTEMPT); const stopping = manager.stopAgent(agent.id); const outcome = stopping.catch((err: Error) => err); - await vi.waitFor(() => expect(holds.counts("r1").stops).toBe(1)); + await Promise.race([work.get(holds)!.blocked, outcome]); + expect(holds.counts("r1").stops).toBe(1); if (status === "archiving") await manager.beginArchive(agent.id, "keep"); else if (status === "deleted") await pool.query("UPDATE agents SET deleted_at = NOW() WHERE id = $1", [ @@ -695,7 +696,8 @@ describe("launches on a runner held for an update", () => { onComplete: vi.fn(), onError: vi.fn(), }); - await vi.waitFor(() => expect(holds.counts("r1").stops).toBe(1)); + await Promise.race([work.get(holds)!.blocked, archiving]); + expect(holds.counts("r1").stops).toBe(1); await pool.query("UPDATE agents SET deleted_at = NOW() WHERE id = $1", [ agent.id, ]); @@ -714,7 +716,8 @@ describe("launches on a runner held for an update", () => { await holds.begin("r1", ATTEMPT); }); const stopping = manager.stopAgent(agent.id); - await vi.waitFor(() => expect(holds.isHeld("r1")).toBe(true)); + await Promise.race([work.get(holds)!.blocked, stopping]); + expect(holds.isHeld("r1")).toBe(true); await manager.beginArchive(agent.id, "keep"); await holds.release("r1", ATTEMPT, "committed"); expect(await stopping).toMatchObject({ status: "archiving" }); @@ -766,8 +769,8 @@ describe("launches on a runner held for an update", () => { .filter(({ kind }) => kind === "checkoutCommand") .map(({ operation }) => operation.checkout); const ending = end(manager, agent.id); - await vi.waitFor(() => expect(holds.isHeld("r1")).toBe(true)); - await new Promise((resolve) => setTimeout(resolve, 50)); + await Promise.race([work.get(holds)!.blocked, ending]); + expect(holds.isHeld("r1")).toBe(true); expect(hookRequests()).toEqual(["launch"]); await holds.release("r1", ATTEMPT, "committed"); await ending; @@ -779,13 +782,18 @@ describe("launches on a runner held for an update", () => { const holds = await openHolds(300); const runtime = spyRuntime(); const manager = managerOn(holds, runtime); + const expired = Promise.withResolvers(); + holds.onRelease(({ outcome }) => expired.resolve(outcome)); + // Otherwise the bound races the launch it is meant to hold. + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); await holds.begin("r1", ATTEMPT); const held = await manager.createAgent({ cwd: HELD }); expect(launchesFor(runtime, held.id)).toHaveLength(0); - await vi.waitFor( - async () => expect(await statusOf(held.id)).toBe("running"), - { timeout: 3000 } - ); + await vi.advanceTimersByTimeAsync(300); + vi.useRealTimers(); + expect(await expired.promise).toBe("expired"); + await work.get(holds)!.settled(); + expect(await statusOf(held.id)).toBe("running"); expect(holds.isHeld("r1")).toBe(false); expect(launchesFor(runtime, held.id)).toHaveLength(1); }); diff --git a/apps/server/test/github-runner-executor.test.ts b/apps/server/test/github-runner-executor.test.ts index 70025b8bd..d87575edd 100644 --- a/apps/server/test/github-runner-executor.test.ts +++ b/apps/server/test/github-runner-executor.test.ts @@ -7,6 +7,7 @@ import { rm, writeFile, } from "node:fs/promises"; +import { once } from "node:events"; import os from "node:os"; import path from "node:path"; import { setTimeout as delay } from "node:timers/promises"; @@ -14,6 +15,13 @@ import { expect, it, vi } from "vitest"; import { GitHubRunnerExecutor } from "../src/agents/remote/github-runner-executor.js"; import { runnerGitArgs } from "../src/agents/remote/runner.js"; +/** The running sign-in printed its code, or ended without one. */ +async function codeShown(executor: GitHubRunnerExecutor) { + const login = executor["login"]; + while (login && !login.code && executor["login"] === login) + await Promise.race([once(login.child.stderr!, "data"), login.finished]); +} + async function fixture( run: (input: { executor: GitHubRunnerExecutor; @@ -193,7 +201,22 @@ esac undefined, privateHome ); - await run({ executor, root, gh, env }); + const commands = new Set>(); + const runCommand = executor["runCommand"].bind(executor); + executor["runCommand"] = (...args) => { + const command = runCommand(...args); + commands.add(command); + const forget = () => commands.delete(command); + command.then(forget, forget); + return command; + }; + try { + await run({ executor, root, gh, env }); + } finally { + // Sign-in and prefetched pages outlive the calls that started them. + await executor["stopLogin"](); + while (commands.size) await Promise.allSettled([...commands]); + } } finally { await rm(root, { recursive: true, force: true }); } @@ -218,8 +241,24 @@ it("invalidates in-flight repository searches and prevents cache refills during await fixture(async ({ executor, root }) => { const signal = new AbortController().signal; const flag = (name: string) => writeFile(path.join(root, name), ""); - const waitForFlag = (name: string) => - vi.waitFor(() => access(path.join(root, name))); + /** The command wrote its marker, unless it ended without doing so. */ + const waitForFlag = async (name: string, command: Promise) => { + let ended = false; + const end = () => (ended = true); + command.then(end, end); + for (;;) { + const last = ended; + if ( + await access(path.join(root, name)).then( + () => true, + () => false + ) + ) + return; + if (last) throw new Error(`ended before ${name}`); + await delay(20); + } + }; const search = () => executor.handle( { type: "repositorySearch", query: "org/project" }, @@ -229,9 +268,9 @@ it("invalidates in-flight repository searches and prevents cache refills during await Promise.all([flag("hold-repositories"), flag("hold-logout")]); const beforeLogout = search().catch((error: unknown) => error); - await waitForFlag("repository-search-started"); + await waitForFlag("repository-search-started", beforeLogout); const logout = executor.handle({ type: "logout" }, signal); - await waitForFlag("logout-started"); + await waitForFlag("logout-started", logout); const duringLogout = search().catch((error: unknown) => error); await flag("release-repositories"); await flag("release-logout"); @@ -253,7 +292,17 @@ it("returns the first twelve matches while a later repository page is pending", new AbortController().signal ); try { - const result = await Promise.race([search, delay(1500, null)]); + const result = await search; + const pageTwo = executor["repositories"]!.pages.get(2)!; + expect( + await Promise.race([ + pageTwo.then( + () => "ended", + () => "ended" + ), + new Promise((resolve) => setImmediate(resolve, "pending")), + ]) + ).toBe("pending"); expect(result).toMatchObject({ repositories: expect.arrayContaining([ { @@ -332,24 +381,23 @@ it("completes a device login without setting a global credential helper", async try { expect(await handle("status")).toEqual({ status: "signed-out" }); expect(await handle("login")).toMatchObject({ status: "pending" }); - await vi.waitFor(async () => - expect(await handle("status")).toEqual({ - status: "pending", - code: "ABCD-1234", - verificationUrl: "https://github.com/login/device", - }) - ); + await codeShown(executor); + expect(await handle("status")).toEqual({ + status: "pending", + code: "ABCD-1234", + verificationUrl: "https://github.com/login/device", + }); expect(await handle("login")).toMatchObject({ status: "pending", code: "ABCD-1234", }); + const authorized = executor["login"]!.finished; await writeFile(path.join(root, "authorize"), ""); - await vi.waitFor(async () => - expect(await handle("status")).toEqual({ - status: "signed-in", - login: "fixture-user", - }) - ); + await authorized; + expect(await handle("status")).toEqual({ + status: "signed-in", + login: "fixture-user", + }); expect( await readFile(path.join(root, ".gitconfig"), "utf8") ).not.toContain("credential"); @@ -553,31 +601,30 @@ it("clears pending device codes on cancel, disconnect and failed authorization", executor.handle({ type }, controller.signal); const pending = async () => { await handle("login"); - await vi.waitFor(async () => - expect(await handle("status")).toMatchObject({ - status: "pending", - code: "ABCD-1234", - }) - ); + await codeShown(executor); + expect(await handle("status")).toMatchObject({ + status: "pending", + code: "ABCD-1234", + }); }; try { await pending(); expect(await handle("cancel")).toEqual({ status: "signed-out" }); await pending(); + const disconnected = executor["login"]!.finished; controller.abort(); controller = new AbortController(); - await vi.waitFor(async () => - expect(await handle("status")).toEqual({ status: "signed-out" }) - ); + await disconnected; + expect(await handle("status")).toEqual({ status: "signed-out" }); await pending(); + const rejected = executor["login"]!.finished; await writeFile(path.join(root, "reject"), ""); - await vi.waitFor(async () => - expect(await handle("status")).toEqual({ - status: "failed", - message: - "GitHub device authorization did not finish. Start sign-in again.", - }) - ); + await rejected; + expect(await handle("status")).toEqual({ + status: "failed", + message: + "GitHub device authorization did not finish. Start sign-in again.", + }); } finally { controller.abort(); } @@ -594,21 +641,20 @@ it("returns the device code and signs out with the Ubuntu 22.04 single-account C "gh version 2.4.0+dfsg1 (Ubuntu)" ); await executor.handle({ type: "login" }, connection.signal); - await vi.waitFor(async () => - expect( - await executor.handle({ type: "status" }, connection.signal) - ).toMatchObject({ - status: "pending", - code: "ABCD-1234", - verificationUrl: "https://github.com/login/device", - }) - ); + await codeShown(executor); + expect( + await executor.handle({ type: "status" }, connection.signal) + ).toMatchObject({ + status: "pending", + code: "ABCD-1234", + verificationUrl: "https://github.com/login/device", + }); + const authorized = executor["login"]!.finished; await writeFile(path.join(root, "authorize"), ""); - await vi.waitFor(async () => - expect( - await executor.handle({ type: "status" }, connection.signal) - ).toMatchObject({ status: "signed-in" }) - ); + await authorized; + expect( + await executor.handle({ type: "status" }, connection.signal) + ).toMatchObject({ status: "signed-in" }); expect( await executor.handle({ type: "logout" }, connection.signal) ).toMatchObject({ status: "signed-out" }); diff --git a/apps/server/test/helpers/hold-work.ts b/apps/server/test/helpers/hold-work.ts new file mode 100644 index 000000000..cd8adb38d --- /dev/null +++ b/apps/server/test/helpers/hold-work.ts @@ -0,0 +1,44 @@ +import type { RunnerUpdateHolds } from "../../src/agents/remote/update-hold.js"; + +/** + * What a test can await of the work holds run in the background. Create it + * before the manager, so a release is recorded before the manager resumes it. + */ +export function trackHoldWork(holds: RunnerUpdateHolds) { + const unsettled = new Map>(); + const track = (launches: { id: string }[]) => { + for (const { id } of launches) + unsettled.set(id, Promise.withResolvers()); + }; + holds.onRelease(({ launches }) => track(launches)); + holds.onResume(track); + const settleLaunch = holds.settleLaunch.bind(holds); + holds.settleLaunch = async (id) => { + try { + await settleLaunch(id); + } finally { + unsettled.get(id)?.resolve(); + unsettled.delete(id); + } + }; + const blocked = Promise.withResolvers(); + const wait = holds.wait.bind(holds); + holds.wait = (runnerId, kind) => { + const waited = wait(runnerId, kind); + if (holds.isHeld(runnerId)) blocked.resolve(); + return waited; + }; + return { + /** Something is waiting for a hold to open. */ + blocked: blocked.promise, + /** Every resumed launch reached its outcome and that outcome was saved. */ + async settled() { + // `start` hands recovered launches to its listeners in a microtask. + await new Promise((resolve) => setImmediate(resolve)); + while (unsettled.size) + await Promise.all([...unsettled.values()].map((work) => work.promise)); + }, + /** This controller died: what it was driving never settles. */ + abandon: () => unsettled.clear(), + }; +} diff --git a/apps/server/test/runner-update-fence.test.ts b/apps/server/test/runner-update-fence.test.ts index c027649e5..f9fa05140 100644 --- a/apps/server/test/runner-update-fence.test.ts +++ b/apps/server/test/runner-update-fence.test.ts @@ -566,12 +566,20 @@ describe("runner update fence", () => { await vi.waitFor(() => expect(resultFor("terminal")).toMatchObject({ value: expect.any(String) }) ); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); await stagedAndFenced(); // The terminal is open until its grace period ends, and the boundary // is reported only after it was closed with its notice. - await new Promise((resolve) => setTimeout(resolve, 200)); + await vi.advanceTimersByTimeAsync(999); expect(child.kill).not.toHaveBeenCalled(); expect(statuses().at(-1)?.reason).toBe("ready"); + // Fire it from a macrotask, as a real timer is: the close is a nextTick. + await new Promise((resolve) => + setImmediate(() => { + vi.advanceTimersByTime(1); + resolve(); + }) + ); await vi.waitFor(() => expect(statuses().at(-1)).toMatchObject({ reason: "fence_ready" }) ); diff --git a/apps/server/test/runner-update-handoff.test.ts b/apps/server/test/runner-update-handoff.test.ts index 69e024f37..93a4e3d9e 100644 --- a/apps/server/test/runner-update-handoff.test.ts +++ b/apps/server/test/runner-update-handoff.test.ts @@ -363,15 +363,25 @@ describe("candidate compatibility probe", () => { it("kills descendants when the probe exceeds the deadline", async () => { const dir = await mkdtemp(path.join(tmpdir(), "runner-probe-timeout-")); const marker = path.join(dir, "survived"); + const go = path.join(dir, "go"); try { await expect( readRunnerCompatibility( "/bin/sh", - ["-c", '(sleep 0.3; touch "$1") & wait', "probe", marker], + [ + "-c", + // Only once told to, so a late kill cannot look like a survivor. + '(until [ -f "$2" ]; do [ -d "$3" ] || exit; sleep 0.02; done; touch "$1") & wait', + "probe", + marker, + go, + dir, + ], compatibility.version, 100 ) ).rejects.toThrow("timed out"); + await writeFile(go, ""); await delay(350); await expect(stat(marker)).rejects.toMatchObject({ code: "ENOENT" }); } finally { diff --git a/apps/server/test/runner-update-hold-runtime.test.ts b/apps/server/test/runner-update-hold-runtime.test.ts index 1b970b76a..8c788149c 100644 --- a/apps/server/test/runner-update-hold-runtime.test.ts +++ b/apps/server/test/runner-update-hold-runtime.test.ts @@ -298,8 +298,11 @@ describe("runner update hold in the runtime queue", () => { () => outcome("accepted"), () => outcome("rejected") ); - await settle(); - expect(prepared).toHaveBeenCalledTimes(1); + // Refused, then back in the queue. + await vi.waitFor(() => { + expect(prepared).toHaveBeenCalledTimes(1); + expect(holds.counts("r1")).toMatchObject({ prompts: 1 }); + }); expect(outcome).not.toHaveBeenCalled(); expect(built.held.prompts).toEqual([]); expect(holds.counts("r1")).toMatchObject({ prompts: 1 }); @@ -335,7 +338,9 @@ describe("runner update hold in the runtime queue", () => { }); const otherStop = runtime.stop("agt_other", false); await otherStop; - await settle(); + await vi.waitFor(() => + expect(holds.counts("r1")).toMatchObject({ stops: 1 }) + ); expect(operations).toContain("stop:agt_other"); expect(operations).not.toContain("stop:agt_held"); expect(stopped).toBe(false); @@ -357,7 +362,9 @@ describe("runner update hold in the runtime queue", () => { const heldDiscard = runtime.discard("agt_other").then(() => { discarded = true; }); - await settle(); + await vi.waitFor(() => + expect(holds.counts("r2")).toMatchObject({ stops: 1 }) + ); expect(discarded).toBe(false); await holds.release("r2", ATTEMPT, "fence_released"); await heldDiscard; diff --git a/apps/server/test/runner-update-hold-scheduled.test.ts b/apps/server/test/runner-update-hold-scheduled.test.ts index 655304e57..3e285453b 100644 --- a/apps/server/test/runner-update-hold-scheduled.test.ts +++ b/apps/server/test/runner-update-hold-scheduled.test.ts @@ -101,6 +101,7 @@ async function controller(socket: string, stateRoot: string) { holds, }); expect(await runtime.attach(id)).toBe(true); + const deliveries: ReturnType[] = []; const service = new ScheduledMessageService( pool, { @@ -111,7 +112,11 @@ async function controller(socket: string, stateRoot: string) { text: string, source: never, opts: never - ) => runtime.prompt(agentId, text, source, opts), + ) => { + const delivery = runtime.prompt(agentId, text, source, opts); + deliveries.push(delivery); + return delivery; + }, } as unknown as AgentManager, { scheduledNoticeOutcome: async () => {}, @@ -123,7 +128,13 @@ async function controller(socket: string, stateRoot: string) { { warn: () => {} } ); cleanup.push(() => service.stop()); - return { holds, runtime, service }; + /** Every submitted occurrence settled, and the service recorded it. */ + async function delivered() { + await Promise.all(deliveries.map(({ settled }) => settled)); + // The service queues its bookkeeping in the agent's order as each settles. + await service["serial"](id, async () => {}); + } + return { holds, runtime, service, delivered }; } async function host() { @@ -141,30 +152,28 @@ const recurring = () => ({ stop_when: "Deployment complete", max_deliveries: 20, }); -const settle = () => new Promise((resolve) => setTimeout(resolve, 100)); describe("scheduled occurrences on a held runner", () => { it("keeps one pending occurrence across recurring ticks and delivers it once on release", async () => { const { prompts, socket, stateRoot } = await host(); - const { holds, service } = await controller(socket, stateRoot); + const { holds, service, delivered } = await controller(socket, stateRoot); await holds.begin("r1", ATTEMPT); const s = await service.create(id, recurring()); const due = Date.parse(s.deliverAt); await service.tick(due); - await settle(); const first = (await service.list(id))[0]!.outstanding!; expect(first.phase).toBe("pending"); expect(holds.counts("r1")).toMatchObject({ scheduled: 1 }); await service.tick(due + 15 * 60 * 1000); - await settle(); + expect(holds.counts("r1")).toMatchObject({ scheduled: 1 }); const later = (await service.list(id))[0]!.outstanding!; expect(later).toMatchObject({ id: first.id, phase: "pending", ticks: 4 }); expect(prompts).toEqual([]); await holds.release("r1", ATTEMPT, "committed"); - await settle(); + await delivered(); expect(prompts).toHaveLength(1); expect(prompts[0]!.text).toContain("Schedule ID: " + s.id); const after = (await service.list(id))[0]!; @@ -173,17 +182,17 @@ describe("scheduled occurrences on a held runner", () => { it("expires a held occurrence and never sends it", async () => { const { prompts, socket, stateRoot } = await host(); - const { holds, service } = await controller(socket, stateRoot); + const { holds, service, delivered } = await controller(socket, stateRoot); await holds.begin("r1", ATTEMPT); const s = await service.create(id, recurring()); await service.tick(Date.parse(s.deliverAt)); - await settle(); + expect(holds.counts("r1")).toMatchObject({ scheduled: 1 }); await pool.query( "UPDATE scheduled_messages SET payload=jsonb_set(payload,'{expiresAt}',to_jsonb($2::text)) WHERE id=$1", [s.id, new Date(Date.now() - 1).toISOString()] ); await service.tick(); - await settle(); + await delivered(); expect((await service.list(id))[0]!).toMatchObject({ status: "expired", outstanding: null, @@ -191,7 +200,7 @@ describe("scheduled occurrences on a held runner", () => { expect(holds.counts("r1")).toMatchObject({ scheduled: 0 }); await holds.release("r1", ATTEMPT, "committed"); - await settle(); + await delivered(); expect(prompts).toEqual([]); }); @@ -201,7 +210,7 @@ describe("scheduled occurrences on a held runner", () => { await before.holds.begin("r1", ATTEMPT); const s = await before.service.create(id, recurring()); await before.service.tick(Date.parse(s.deliverAt)); - await settle(); + expect(before.holds.counts("r1")).toMatchObject({ scheduled: 1 }); const pending = (await before.service.list(id))[0]!.outstanding!; // The old process dies holding it in memory; its hold is never released. before.service.stop(); @@ -212,7 +221,7 @@ describe("scheduled occurrences on a held runner", () => { await after.service.start(); after.service.stop(); await after.service.tick(); - await settle(); + expect(after.holds.counts("r1")).toMatchObject({ scheduled: 1 }); expect((await after.service.list(id))[0]!.outstanding).toMatchObject({ id: pending.id, phase: "pending", @@ -220,7 +229,7 @@ describe("scheduled occurrences on a held runner", () => { expect(prompts).toEqual([]); await after.holds.release("r1", ATTEMPT, "rolled_back"); - await settle(); + await after.delivered(); expect(prompts).toHaveLength(1); expect((await after.service.list(id))[0]!.deliveredCount).toBe(1); }); diff --git a/apps/server/test/runner-update-hold.test.ts b/apps/server/test/runner-update-hold.test.ts index 3e310ae07..5fb5a5b69 100644 --- a/apps/server/test/runner-update-hold.test.ts +++ b/apps/server/test/runner-update-hold.test.ts @@ -215,7 +215,9 @@ describe("runner update holds", () => { holds.start(); await holds.begin("r1", ATTEMPT); const released = vi.fn(); + const releasing = Promise.withResolvers(); holds.onRelease(released); + holds.onRelease(() => releasing.resolve()); let stopped = false; void holds.wait("r1", "stop").then(() => { stopped = true; @@ -224,7 +226,8 @@ describe("runner update holds", () => { await vi.advanceTimersByTimeAsync(999); expect(released).not.toHaveBeenCalled(); await vi.advanceTimersByTimeAsync(1); - await vi.waitFor(() => expect(released).toHaveBeenCalledTimes(1)); + await releasing.promise; + expect(released).toHaveBeenCalledTimes(1); expect(released.mock.calls[0]![0]).toMatchObject({ outcome: "expired" }); expect(stopped).toBe(true); expect(holds.isHeld("r1")).toBe(false); @@ -242,12 +245,15 @@ describe("runner update holds", () => { await second.load(); const released = vi.fn(); second.onRelease(released); + const releasing = Promise.withResolvers(); + second.onRelease(() => releasing.resolve()); // Loading alone opens nothing: boot recovery runs before the bound. await new Promise((resolve) => setTimeout(resolve, 20)); expect(released).not.toHaveBeenCalled(); expect(second.isHeld("r1")).toBe(true); second.start(); - await vi.waitFor(() => expect(released).toHaveBeenCalledTimes(1)); + await releasing.promise; + expect(released).toHaveBeenCalledTimes(1); expect(released.mock.calls[0]![0]).toMatchObject({ outcome: "expired", launches: [expect.objectContaining({ agentId: "agt_a" })], From 1ccc6638ba96df9cfad9522b36d0021f0377034b Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 23:12:29 -0700 Subject: [PATCH 307/642] Make the host recycle and launch reconcile tests deterministic Start the fixture engine only once its client has attached, so a late start-up welcome cannot drop the recycler's lease. Await recycle and launch outcomes instead of polling deadlines, keep the periodic rescan out of tests of first-pass and settlement promptness, and settle resumed launches before removing their directory. Co-Authored-By: Claude Opus 5.5 --- .../test/db/runner-host-recycle.test.ts | 223 ++++++++++++------ .../runner-launch-reconcile-manager.test.ts | 155 ++++++------ .../test/helpers/recycle-acp-fixture.ts | 6 + 3 files changed, 233 insertions(+), 151 deletions(-) diff --git a/apps/server/test/db/runner-host-recycle.test.ts b/apps/server/test/db/runner-host-recycle.test.ts index 342782fb4..a0285aa9b 100644 --- a/apps/server/test/db/runner-host-recycle.test.ts +++ b/apps/server/test/db/runner-host-recycle.test.ts @@ -2,7 +2,6 @@ import { spawn, type ChildProcess } from "node:child_process"; import { randomUUID } from "node:crypto"; import { once } from "node:events"; import { - existsSync, mkdirSync, mkdtempSync, readFileSync, @@ -12,10 +11,11 @@ import { import net from "node:net"; import path from "node:path"; import { Duplex } from "node:stream"; +import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import type { FastifyBaseLogger } from "fastify"; import type { Pool } from "pg"; -import { afterAll, beforeAll, expect, it, vi } from "vitest"; +import { afterAll, beforeAll, expect, it, onTestFinished, vi } from "vitest"; import { AgentManager } from "../../src/agents/manager.js"; import { encodeMessage, @@ -55,7 +55,31 @@ beforeAll(async () => { }); afterAll(async () => teardownTestDb()); -async function fixture() { +function listening(socketPath: string) { + return new Promise((resolve) => { + const probe = net.createConnection(socketPath); + probe.once("connect", () => { + probe.destroy(); + resolve(true); + }); + probe.once("error", () => resolve(false)); + }); +} + +function isRunning(pid: number) { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +/** + * The recycler's periodic rescan would cover for a first pass, or a pass on + * settlement, that did nothing; only tests that need it keep it. + */ +async function fixture({ periodicRescan = false } = {}) { const directory = mkdtempSync("/tmp/dr-recycle-"); const state = path.join(directory, "s"); const runnerState = path.join(directory, "r"); @@ -79,6 +103,30 @@ async function fixture() { const welcomedReplacement = new Set(); const swapping = new Set(); let online = true; + const closing = Promise.withResolvers(); + let closed = false; + const waiting = new Set<() => void>(); + const changed = () => { + for (const check of waiting) check(); + }; + /** + * Resolves when the fixture sees `check` become true, with no deadline + * but the test's. + */ + function reached(check: () => boolean) { + return new Promise((resolve, reject) => { + const look = () => { + if (closed) reject(new Error(`closed before ${check}`)); + else if (check()) resolve(); + else return; + waiting.delete(look); + }; + waiting.add(look); + look(); + }); + } + const unlessClosing = (gate?: Promise) => + gate && Promise.race([gate, closing.promise]); const hostDir = (id: string) => path.join(runnerState, id); const checkout = (id: string) => path.join(directory, "w", id); @@ -110,6 +158,7 @@ async function fixture() { const attempts = launches.get(id) ?? []; attempts.push(operation.launch.resumeSessionId); launches.set(id, attempts); + changed(); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true }); mkdirSync(checkout(id), { recursive: true }); @@ -122,7 +171,10 @@ async function fixture() { bins: { claudeBin: "/bin/echo", codexBin: null, - adapter: { bin: "bun", args: [adapter] }, + adapter: { + bin: "bun", + args: [adapter, path.join(dir, "attached")], + }, }, env: {}, pathPrefix: [], @@ -133,16 +185,18 @@ async function fixture() { }); hostPids.set(id, child.pid!); processes.set(id, { child, exited: once(child, "exit") }); - await vi.waitFor( - () => expect(existsSync(path.join(dir, "session.json"))).toBe(true), - { timeout: 5_000 } - ); + while (!(await listening(path.join(dir, "host.sock")))) { + if (closed || child.exitCode !== null || child.signalCode !== null) + throw new Error("The host ended before it was listening."); + await delay(25); + } return { value: true }; } if (operation.kind === "alive") return { value: processes.has(id) }; if (operation.kind === "stop") { swapping.add(id); - await holdStop.get(id); + changed(); + await unlessClosing(holdStop.get(id)); await stop(id); return { value: true }; } @@ -156,6 +210,7 @@ async function fixture() { write(chunk, _encoding, callback) { for (const message of outbound(chunk)) { commands.push({ id, message }); + changed(); host.write(encodeMessage(message)); } callback(); @@ -170,8 +225,13 @@ async function fixture() { host.on("data", (chunk) => { for (const message of inbound(chunk)) { if (message.type === "welcome") { - if ((launches.get(id)?.length ?? 0) > 1 && message.running) + // The engine starts once attached, so the host's start-up welcome + // is the last one: a later one would drop the recycler's lease. + writeFileSync(path.join(dir, "attached"), ""); + if ((launches.get(id)?.length ?? 0) > 1 && message.running) { welcomedReplacement.add(id); + changed(); + } message.hostBuild = { version: "1.7.28", revision: @@ -186,7 +246,7 @@ async function fixture() { ? holdReplay.get(id) : undefined; if (pause) { - void pause.then(() => { + void unlessClosing(pause)!.then(() => { if (!link.destroyed) link.push(encodeMessage(message)); }); } else { @@ -217,9 +277,44 @@ async function fixture() { { remote: remote as unknown as RemoteRunnerService } ); + if (!periodicRescan) { + const recycler = manager["hostRecycler"]; + const scan = recycler["scan"].bind(recycler); + recycler["scan"] = (run) => { + scan(run); + clearTimeout(run.timer); + }; + } + const recycle = manager["recycleRunnerHost"].bind(manager); + manager["recycleRunnerHost"] = (...args) => + // After the recycler has counted the result. + recycle(...args).finally(() => setImmediate(changed)); + const localIds: string[] = []; + let closure: Promise | undefined; + const close = () => (closure ??= teardown()); + async function teardown() { + closed = true; + closing.resolve(); + changed(); + // A restart under way would spawn into, and write to, what is removed. + await manager.settleRunnerHostRecycling("r1"); + await Promise.all([...processes.keys()].map(stop)); + for (const id of localIds) { + await manager.stopAgent(id, { force: true }); + // A local stop signals the host without awaiting its exit. + const pid = hostPids.get(id); + while (pid && isRunning(pid)) await delay(25); + } + vi.unstubAllEnvs(); + rmSync(directory, { recursive: true, force: true }); + } + // Also when the test times out before it reaches its own close. + onTestFinished(close); return { manager, + reached, + close, launches, hostPids, commands, @@ -255,18 +350,12 @@ async function fixture() { Number(readFileSync(path.join(state, id, "host.pid"), "utf8")) ); }, - async close() { - manager.stopRunnerHostRecycling("r1"); - await Promise.all([...processes.keys()].map(stop)); - for (const id of localIds) await manager.stopAgent(id, { force: true }); - vi.unstubAllEnvs(); - rmSync(directory, { recursive: true, force: true }); - }, }; } it("rolls idle hosts independently, preserves the queue and session, and leaves legacy and local hosts serving", async () => { - const f = await fixture(); + // A settlement during a pass in flight is picked up by the rescan. + const f = await fixture({ periodicRescan: true }); const busy = "agt_recycle_busy"; const idle = "agt_recycle_idle"; const legacy = "agt_recycle_legacy"; @@ -297,9 +386,7 @@ it("rolls idle hosts independently, preserves the queue and session, and leaves recycled: 0, waiting: 1, }); - await vi.waitFor(() => expect(f.swapping.has(idle)).toBe(true), { - timeout: 4_000, - }); + await f.reached(() => f.swapping.has(idle)); expect(f.hostPids.get(busy)).toBe(oldPid); expect(f.launches.get(busy)).toEqual([null]); expect(await f.manager.getTerminalAccess(idle)).toEqual({ mode: "live" }); @@ -315,7 +402,7 @@ it("rolls idle hosts independently, preserves the queue and session, and leaves f.holdReplay.set(idle, replay.promise); stop.resolve(); - await vi.waitFor(() => expect(f.welcomedReplacement.has(idle)).toBe(true)); + await f.reached(() => f.welcomedReplacement.has(idle)); await expect( Promise.race([ gap.accepted.then(() => "accepted"), @@ -349,15 +436,14 @@ it("rolls idle hosts independently, preserves the queue and session, and leaves writeFileSync(path.join(f.checkout(busy), "finish-turn"), ""); await active.settled; - await vi.waitFor( - () => - expect(f.manager.runnerHostRecycleProgress("r1")).toEqual({ - oldBuild: 1, - recycled: 2, - waiting: 1, - }), - { timeout: 7_000 } + await f.reached( + () => f.manager.runnerHostRecycleProgress("r1")?.recycled === 2 ); + expect(f.manager.runnerHostRecycleProgress("r1")).toEqual({ + oldBuild: 1, + recycled: 2, + waiting: 1, + }); expect(f.hostPids.get(busy)).not.toBe(oldPid); expect(f.launches.get(busy)).toEqual([null, "sess_1"]); await f.manager.promptAgent(busy, "continue this conversation").settled; @@ -376,7 +462,8 @@ it("rolls idle hosts independently, preserves the queue and session, and leaves }, 25_000); it("delivers a child's awaited reply once to the original parent session before recycling", async () => { - const f = await fixture(); + // Nothing signals a child's stop: the rescan finds the parent eligible. + const f = await fixture({ periodicRescan: true }); const parent = "agt_waiting_parent"; const child = "agt_reply_child"; try { @@ -384,13 +471,10 @@ it("delivers a child's awaited reply once to the original parent session before await f.start(child, { parent, legacy: true }); const pid = f.hostPids.get(parent); f.manager.startRunnerHostRecycling(update); - await vi.waitFor(() => - expect( - f.commands.some( - ({ id, message }) => - id === parent && message.type === "release_quiesce" - ) - ).toBe(true) + await f.reached(() => + f.commands.some( + ({ id, message }) => id === parent && message.type === "release_quiesce" + ) ); expect(f.hostPids.get(parent)).toBe(pid); const reply = f.manager.promptAgent(parent, "child result", { @@ -402,13 +486,10 @@ it("delivers a child's awaited reply once to the original parent session before await reply.settled; expect(f.hostPids.get(parent)).toBe(pid); await f.manager.stopAgent(child); - await vi.waitFor( - () => expect(f.launches.get(parent)).toEqual([null, "sess_1"]), - { timeout: 7_000 } - ); - await vi.waitFor(() => - expect(f.manager.runnerHostRecycleProgress("r1")?.recycled).toBe(1) + await f.reached( + () => f.manager.runnerHostRecycleProgress("r1")?.recycled === 1 ); + expect(f.launches.get(parent)).toEqual([null, "sess_1"]); expect( f.commands.filter( ({ id, message }) => @@ -454,13 +535,11 @@ it.each(["stop", "archive", "revoke", "cancel"] as const)( if (action === "stop") expect(result?.status).toBe("stopped"); if (action === "archive") expect(result?.status).toBe("archiving"); if (action !== "stop") - await vi.waitFor(() => - expect( - f.commands.some( - (entry) => - entry.id === id && entry.message.type === "release_quiesce" - ) - ).toBe(true) + await f.reached(() => + f.commands.some( + (entry) => + entry.id === id && entry.message.type === "release_quiesce" + ) ); expect(f.launches.get(id)).toEqual([null]); expect( @@ -484,17 +563,16 @@ it("does not hand queued work to a host that resumes a different session", async f.wrongSession.add(id); f.holdStop.set(id, stop.promise); f.manager.startRunnerHostRecycling(update); - await vi.waitFor(() => expect(f.swapping.has(id)).toBe(true)); + await f.reached(() => f.swapping.has(id)); const queued = f.manager.promptAgent(id, "only for the previous session"); const rejected = expect(queued.accepted).rejects.toThrow("before delivery"); stop.resolve(); await rejected; - await vi.waitFor(async () => - expect(await f.manager.getAgent(id)).toMatchObject({ - status: "error", - cliSessionId: "sess_1", - }) - ); + await f.manager.settleRunnerHostRecycling("r1"); + expect(await f.manager.getAgent(id)).toMatchObject({ + status: "error", + cliSessionId: "sess_1", + }); expect( f.commands.some( (entry) => entry.id === id && entry.message.type === "prompt" @@ -522,13 +600,14 @@ it("does not acquire a lease across an in-flight delivery or send around an acqu }); await preparing.promise; f.manager.startRunnerHostRecycling(update); - await vi.waitFor(() => - expect(f.manager.runnerHostRecycleProgress("r1")).toEqual({ - oldBuild: 1, - recycled: 0, - waiting: 1, - }) + await f.reached( + () => f.manager.runnerHostRecycleProgress("r1")?.waiting === 1 ); + expect(f.manager.runnerHostRecycleProgress("r1")).toEqual({ + oldBuild: 1, + recycled: 0, + waiting: 1, + }); expect( f.commands.some( (entry) => entry.id === id && entry.message.type === "quiesce" @@ -539,14 +618,10 @@ it("does not acquire a lease across an in-flight delivery or send around an acqu f.holdReply.set(id, lease.promise); writeFileSync(path.join(f.checkout(id), "finish-turn"), ""); await active.settled; - await vi.waitFor( - () => - expect( - f.commands.some( - (entry) => entry.id === id && entry.message.type === "quiesce" - ) - ).toBe(true), - { timeout: 3_000 } + await f.reached(() => + f.commands.some( + (entry) => entry.id === id && entry.message.type === "quiesce" + ) ); const submitted = Promise.withResolvers(); const queued = f.manager.promptAgent(id, "send to replacement", undefined, { @@ -585,7 +660,7 @@ it.each(["stop", "archive"] as const)( await f.start(id); f.holdStop.set(id, cleanup.promise); f.manager.startRunnerHostRecycling(update); - await vi.waitFor(() => expect(f.swapping.has(id)).toBe(true)); + await f.reached(() => f.swapping.has(id)); const terminal = action === "stop" ? f.manager.stopAgent(id) diff --git a/apps/server/test/db/runner-launch-reconcile-manager.test.ts b/apps/server/test/db/runner-launch-reconcile-manager.test.ts index e15c604eb..6de95bf97 100644 --- a/apps/server/test/db/runner-launch-reconcile-manager.test.ts +++ b/apps/server/test/db/runner-launch-reconcile-manager.test.ts @@ -23,6 +23,7 @@ import { import type { RemoteRunnerService } from "../../src/agents/remote/service.js"; import type { AgentRuntime, RuntimeLaunch } from "../../src/agents/runtime.js"; +import { trackHoldWork } from "../helpers/hold-work.js"; import { setupTestDb, teardownTestDb, runTestMigrations } from "./setup.js"; vi.mock("../../src/shared/lib/run-command.js", () => ({ @@ -64,20 +65,21 @@ const noopLogger = { level: "silent", } as unknown as import("fastify").FastifyBaseLogger; -const testConfig = { - host: "127.0.0.1", - port: 6767, - databaseUrl: "", - authToken: "test-token", - filesRoot: "/tmp/dispatch-test-files", - dispatchBinDir: "/tmp/dispatch-test-bin", - codexBin: "/bin/echo", - claudeBin: "/bin/echo", - opencodeBin: "/bin/opencode", - agentStateRoot: "/tmp/dispatch-test-agents", - agentRuntime: "acp", - tls: null, -} satisfies import("../../src/config.js").AppConfig; +const testConfig = (root: string) => + ({ + host: "127.0.0.1", + port: 6767, + databaseUrl: "", + authToken: "test-token", + filesRoot: path.join(root, "files"), + dispatchBinDir: path.join(root, "bin"), + codexBin: "/bin/echo", + claudeBin: "/bin/echo", + opencodeBin: "/bin/opencode", + agentStateRoot: path.join(root, "agents"), + agentRuntime: "acp", + tls: null, + }) satisfies import("../../src/config.js").AppConfig; const ATTEMPT = "11111111-1111-4111-8111-111111111111"; const HELD = "runner://r1/@session"; @@ -87,6 +89,10 @@ let pool: Pool; let dir: string; let holdsFile: string; let opened: InstanceType[] = []; +let work = new Map< + InstanceType, + ReturnType +>(); function spyRuntime() { let sessions = 0; @@ -167,6 +173,7 @@ async function openHolds() { logger: noopLogger, }); opened.push(holds); + work.set(holds, trackHoldWork(holds)); await holds.load(); return holds; } @@ -175,12 +182,13 @@ function managerOn( holds: InstanceType, runtime: Spy ) { - return new AgentManager(pool, noopLogger, testConfig, { + return new AgentManager(pool, noopLogger, testConfig(dir), { runtime, remote, holds, recoveredLaunchPollMs: 10, - recoveredLaunchWaitMs: 2_000, + // Beyond the test, so only a reconnect can end the wait. + recoveredLaunchWaitMs: 120_000, }); } @@ -222,6 +230,7 @@ beforeEach(async () => { refuseNext.clear(); requestSession.mockClear(); vi.mocked(remote.lastSeenCapabilities).mockClear(); + vi.mocked(remote.available).mockImplementation(() => peer.online); await pool.query("DELETE FROM blocks"); await pool.query("DELETE FROM files"); await pool.query("DELETE FROM agents"); @@ -229,7 +238,11 @@ beforeEach(async () => { holdsFile = path.join(dir, "holds.json"); }); afterEach(async () => { + vi.useRealTimers(); for (const holds of opened.splice(0)) holds.close(); + // A released launch saves its outcome after the agent already reads running. + for (const tracked of work.values()) await tracked.settled(); + work.clear(); await rm(dir, { recursive: true, force: true }); }); @@ -243,30 +256,23 @@ describe("launch IDs", () => { const held = await manager.createAgent({ cwd: HELD, initialPrompt: "a" }); const other = await manager.createAgent({ cwd: OTHER }); const local = await manager.createAgent({ cwd: "/tmp" }); - await vi.waitFor(() => expect(holds.counts("r1").launches).toBe(1)); + expect(holds.counts("r1").launches).toBe(1); const heldId = holds.current("r1")!.launches[0]!.launchId; expect(heldId).toMatch(UUID); - await vi.waitFor(() => - expect(launchIdsFor(runtime, other.id)).toHaveLength(1) - ); + expect(launchIdsFor(runtime, other.id)).toHaveLength(1); expect(launchIdsFor(runtime, other.id)[0]).toMatch(UUID); - await vi.waitFor(() => - expect(launchesFor(runtime, local.id)).toHaveLength(1) - ); + expect(launchesFor(runtime, local.id)).toHaveLength(1); expect(launchesFor(runtime, local.id)[0]![0]).not.toHaveProperty( "launchId" ); await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(held.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(held.id)).toBe("running"); expect(launchIdsFor(runtime, held.id)).toEqual([heldId]); // Settled: nothing left to drive after a restart. - await vi.waitFor(async () => - expect(await heldFile()).not.toHaveProperty("resuming") - ); + expect(await heldFile()).not.toHaveProperty("resuming"); // A new Start is a new attempt with a new ID. await manager.stopAgent(other.id); @@ -288,14 +294,13 @@ describe("launch IDs", () => { const manager = managerOn(holds, runtime); holds.start(); const agent = await manager.createAgent({ cwd: HELD, initialPrompt: "x" }); - await vi.waitFor(() => expect(holds.counts("r1").launches).toBe(1)); + expect(holds.counts("r1").launches).toBe(1); const [first] = launchIdsFor(runtime, agent.id); expect(holds.current("r1")!.launches[0]!.launchId).toBe(first); await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchIdsFor(runtime, agent.id)).toEqual([first, first]); }); @@ -305,18 +310,15 @@ describe("launch IDs", () => { const manager = managerOn(holds, runtime); holds.start(); const agent = await manager.createAgent({ cwd: HELD }); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + expect(await statusOf(agent.id)).toBe("running"); await manager.stopAgent(agent.id); await holds.begin("r1", ATTEMPT); await manager.startAgent(agent.id); const heldId = holds.current("r1")!.launches[0]!.launchId; expect(heldId).toMatch(UUID); await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchIdsFor(runtime, agent.id).at(-1)).toBe(heldId); }); }); @@ -326,7 +328,11 @@ describe("a launch released before a controller restart", () => { const first = await openHolds(); const before = spyRuntime(); // Released, then the controller stops before the runner answers. - before.launch.mockImplementation(() => new Promise(() => {})); + const reached = Promise.withResolvers(); + before.launch.mockImplementation(() => { + reached.resolve(); + return new Promise(() => {}); + }); const manager = managerOn(first, before); first.start(); await first.begin("r1", ATTEMPT); @@ -334,16 +340,16 @@ describe("a launch released before a controller restart", () => { cwd: HELD, initialPrompt: "after restart", }); - await vi.waitFor(() => expect(first.counts("r1").launches).toBe(1)); + expect(first.counts("r1").launches).toBe(1); const launchId = first.current("r1")!.launches[0]!.launchId; await first.release("r1", ATTEMPT, "committed"); - await vi.waitFor(() => - expect(launchIdsFor(before, agent.id)).toEqual([launchId]) - ); + await reached.promise; + expect(launchIdsFor(before, agent.id)).toEqual([launchId]); expect((await heldFile()).resuming).toEqual([ expect.objectContaining({ agentId: agent.id, launchId, runnerId: "r1" }), ]); first.close(); + work.get(first)!.abandon(); peer.online = !options.offline; const holds = await openHolds(); @@ -365,19 +371,14 @@ describe("a launch released before a controller restart", () => { expect(await statusOf(agent.id)).toBe("creating"); holds.start(); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchIdsFor(runtime, agent.id)).toEqual([launchId]); expect(launchIdsFor(before, agent.id)).toEqual([launchId]); - await vi.waitFor(() => - expect( - promptsFor(runtime, agent.id).filter((p) => p.includes("after restart")) - ).toHaveLength(1) - ); - await vi.waitFor(async () => - expect(await heldFile()).not.toHaveProperty("resuming") - ); + expect( + promptsFor(runtime, agent.id).filter((p) => p.includes("after restart")) + ).toHaveLength(1); + expect(await heldFile()).not.toHaveProperty("resuming"); expect(holds.hasLaunch(agent.id)).toBe(false); }); @@ -385,13 +386,18 @@ describe("a launch released before a controller restart", () => { const { agent, launchId, holds, runtime } = await releasedThenRestarted({ offline: true, }); + const polledAgain = Promise.withResolvers(); + let polls = 0; + vi.mocked(remote.available).mockImplementation(() => { + if (++polls === 2) polledAgain.resolve(); + return peer.online; + }); holds.start(); - await new Promise((resolve) => setTimeout(resolve, 100)); + await polledAgain.promise; expect(launchesFor(runtime, agent.id)).toHaveLength(0); peer.online = true; - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchIdsFor(runtime, agent.id)).toEqual([launchId]); }); @@ -401,9 +407,8 @@ describe("a launch released before a controller restart", () => { agent.id, ]); holds.start(); - await vi.waitFor(async () => - expect(await heldFile()).not.toHaveProperty("resuming") - ); + await work.get(holds)!.settled(); + expect(await heldFile()).not.toHaveProperty("resuming"); expect(launchesFor(runtime, agent.id)).toHaveLength(0); }); }); @@ -420,7 +425,7 @@ describe("a new launch while a held runner is between supervisors", () => { cwd: HELD, initialPrompt: "while offline", }); - await vi.waitFor(() => expect(holds.counts("r1").launches).toBe(1)); + expect(holds.counts("r1").launches).toBe(1); expect(await statusOf(agent.id)).toBe("creating"); expect(launchesFor(runtime, agent.id)).toHaveLength(0); expect( @@ -433,9 +438,8 @@ describe("a new launch while a held runner is between supervisors", () => { peer.online = true; await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("running") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("running"); expect(launchesFor(runtime, agent.id)).toHaveLength(1); }); @@ -449,7 +453,7 @@ describe("a new launch while a held runner is between supervisors", () => { await holds.begin("r1", ATTEMPT); peer.online = false; const agent = await manager.createAgent({ cwd: HELD }); - await vi.waitFor(() => expect(holds.counts("r1").launches).toBe(1)); + expect(holds.counts("r1").launches).toBe(1); peer.online = true; if (change === "workspace mode changed") peer.managed = false; @@ -460,9 +464,8 @@ describe("a new launch while a held runner is between supervisors", () => { ); }); await holds.release("r1", ATTEMPT, "committed"); - await vi.waitFor(async () => - expect(await statusOf(agent.id)).toBe("error") - ); + await work.get(holds)!.settled(); + expect(await statusOf(agent.id)).toBe("error"); const { last_error } = ( await pool.query("SELECT last_error FROM agents WHERE id = $1", [ agent.id, @@ -476,7 +479,7 @@ describe("a new launch while a held runner is between supervisors", () => { expect(launchesFor(runtime, agent.id)).toHaveLength( change === "workspace mode changed" ? 0 : 1 ); - await vi.waitFor(() => expect(holds.hasLaunch(agent.id)).toBe(false)); + expect(holds.hasLaunch(agent.id)).toBe(false); } ); @@ -508,7 +511,7 @@ describe("a new launch while a held runner is between supervisors", () => { peer.managed = false; peer.last = { managedWorkspace: true }; const agent = await manager.createAgent({ cwd: HELD }); - await vi.waitFor(() => expect(holds.counts("r1").launches).toBe(1)); + expect(holds.counts("r1").launches).toBe(1); expect(remote.lastSeenCapabilities).not.toHaveBeenCalled(); expect( ( @@ -544,7 +547,7 @@ describe("a new launch while a held runner is between supervisors", () => { ); peer.last = {}; await manager.createAgent(withFiles); - await vi.waitFor(() => expect(holds.counts("r1").launches).toBe(1)); + expect(holds.counts("r1").launches).toBe(1); }); it("checks the last-seen capabilities a launch needs", async () => { @@ -553,9 +556,7 @@ describe("a new launch while a held runner is between supervisors", () => { const manager = managerOn(holds, runtime); holds.start(); const author = await manager.createAgent({ cwd: HELD }); - await vi.waitFor(async () => - expect(await statusOf(author.id)).toBe("running") - ); + expect(await statusOf(author.id)).toBe("running"); await holds.begin("r1", ATTEMPT); peer.online = false; const review = { @@ -573,6 +574,6 @@ describe("a new launch while a held runner is between supervisors", () => { expect(holds.counts("r1").launches).toBe(0); peer.sharedWorktree = true; await manager.createAgent(review, { useWorktreeOf: author.id }); - await vi.waitFor(() => expect(holds.counts("r1").launches).toBe(1)); + expect(holds.counts("r1").launches).toBe(1); }); }); diff --git a/apps/server/test/helpers/recycle-acp-fixture.ts b/apps/server/test/helpers/recycle-acp-fixture.ts index 20a056ee1..91c1901ad 100644 --- a/apps/server/test/helpers/recycle-acp-fixture.ts +++ b/apps/server/test/helpers/recycle-acp-fixture.ts @@ -21,6 +21,12 @@ const fake = createFakeAcpAgent({ return "end_turn"; }, }); +/** A file that must exist before this engine answers its host. */ +const attached = process.argv[2]; +while (attached && !existsSync(attached)) { + if (!existsSync(path.dirname(attached))) process.exit(0); + await new Promise((resolve) => setTimeout(resolve, 25)); +} process.stdin.pipe(fake.child.stdin); fake.child.stdout.pipe(process.stdout); process.stdin.once("end", () => process.exit(0)); From 41c6e25fc9bd49c0ac0600ce9c59ee40f5f24c72 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 23:20:25 -0700 Subject: [PATCH 308/642] Avoid duplicate ACP startup welcomes --- apps/server/src/agents/acp/host/main.ts | 2 +- apps/server/test/acp-host.test.ts | 58 +++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/apps/server/src/agents/acp/host/main.ts b/apps/server/src/agents/acp/host/main.ts index 24fca3216..19360901b 100644 --- a/apps/server/src/agents/acp/host/main.ts +++ b/apps/server/src/agents/acp/host/main.ts @@ -726,12 +726,12 @@ async function main(): Promise { } : undefined ); - running = true; await writeFile( hostFile(stateDir, "session"), JSON.stringify({ sessionId, resumed: session.resumed }), { mode: 0o600 } ); + running = driver.isRunning(agentId); // A client that connected before the engine was up gets the session. send(client, { type: "welcome", diff --git a/apps/server/test/acp-host.test.ts b/apps/server/test/acp-host.test.ts index ed952a6b8..0043f260e 100644 --- a/apps/server/test/acp-host.test.ts +++ b/apps/server/test/acp-host.test.ts @@ -745,6 +745,64 @@ await import(${JSON.stringify(pathToFileURL(fakeAgent).href)}); ); }, 40_000); + it("sends one running welcome when a client attaches during the session write", async () => { + const dir = mkdtempSync("/tmp/dispatch-acp-welcome-"); + const preload = path.join(dir, "hold-session-write.mjs"); + const pending = path.join(dir, "write-pending"); + const release = path.join(dir, "release-write"); + writeFileSync( + preload, + `import { mock } from "bun:test"; +import { existsSync, writeFileSync } from "node:fs"; +import * as fs from "node:fs/promises"; +const { writeFile } = fs; +mock.module("node:fs/promises", () => ({ + ...fs, + async writeFile(file, ...args) { + if (file === ${JSON.stringify(path.join(dir, "session.json"))}) { + writeFileSync(${JSON.stringify(pending)}, ""); + while (!existsSync(${JSON.stringify(release)})) await Bun.sleep(10); + } + return writeFile(file, ...args); + }, +})); +` + ); + writeFileSync( + path.join(dir, "launch.json"), + JSON.stringify(launchFor("agt_starting", cwd)) + ); + const host = spawn( + "bun", + ["--preload", preload, mainTs, "agent-host", "--state", dir], + { stdio: "ignore" } + ); + const exited = once(host, "exit"); + let socket: net.Socket | undefined; + try { + await until(() => existsSync(pending), 5000); + socket = net.createConnection(path.join(dir, "host.sock")); + const messages: HostMessage[] = []; + const decode = ndjsonDecoder(); + socket.on("data", (chunk) => messages.push(...decode(chunk))); + await once(socket, "connect"); + socket.write( + encodeMessage({ type: "hello", fromSeq: 0, replayComplete: true }) + ); + await until(() => messages.some((m) => m.type === "replay_complete")); + + writeFileSync(release, ""); + const welcomes = () => messages.filter((m) => m.type === "welcome"); + await until(() => welcomes().length >= 2); + expect(welcomes().map((m) => m.running)).toEqual([false, true]); + } finally { + socket?.destroy(); + host.kill(); + await exited; + rmSync(dir, { recursive: true, force: true }); + } + }, 15_000); + it("keeps a runner attachment across a passive inventory connection", async () => { const dir = mkdtempSync("/tmp/dispatch-acp-inventory-"); const instanceId = "01234567-89ab-4cde-8fab-0123456789ab"; From 3181550413b4137a1760df391e4197218979f5e7 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sat, 21 Nov 2026 23:47:21 -0700 Subject: [PATCH 309/642] Drain incompatible runner updates and recover stopped sessions --- apps/server/src/agents/acp/prompt-source.ts | 2 + apps/server/src/agents/acp/runtime.ts | 94 +++++- apps/server/src/agents/manager.ts | 170 +++++++++- apps/server/src/agents/reconciler.ts | 4 + .../src/agents/remote/update-coordinator.ts | 305 +++++++++++++++--- apps/server/src/agents/remote/update-hold.ts | 25 +- apps/server/src/agents/runtime.ts | 6 +- apps/server/src/chat/service.ts | 1 + apps/server/src/routes/runners.ts | 26 +- .../src/update-recovery/resume-receipt.ts | 18 +- .../db/runner-update-hold-manager.test.ts | 51 +++ .../runner-update-coordinator-fixtures.ts | 42 +++ .../test/runner-update-coordinator.test.ts | 116 +++++-- .../test/runner-update-hold-fixtures.ts | 32 +- .../test/runner-update-hold-runtime.test.ts | 59 +++- apps/web/src/components/app/runner-update.tsx | 41 ++- apps/web/src/hooks/use-runners.ts | 11 +- packages/shared/src/runner-update-types.ts | 3 + 18 files changed, 905 insertions(+), 101 deletions(-) diff --git a/apps/server/src/agents/acp/prompt-source.ts b/apps/server/src/agents/acp/prompt-source.ts index c1afb78c1..a3f6744ff 100644 --- a/apps/server/src/agents/acp/prompt-source.ts +++ b/apps/server/src/agents/acp/prompt-source.ts @@ -25,6 +25,8 @@ export type PromptSource = { userMessage?: boolean; /** Structured answers and commands retain their dedicated delivery policy. */ steeringExcluded?: boolean; + /** An answer to a specific question or form in the source conversation. */ + correlatedReply?: true; /** Agent-authored scheduled content, explicitly eligible for steering. */ scheduleId?: string; scheduleDeliveryId?: string; diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 492a184ca..755c347d7 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -102,6 +102,7 @@ type Waiting = { /** Cancellation belongs to the turn active when this post arrived. */ interruptHandled: boolean; interruptTargetSeq?: number; + wakeTurnSeq?: number; }; type Live = { @@ -332,6 +333,16 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { (deps.holds?.isHeld(entry.runner) === true || recycleHolds.has(entry.agentId)); + const draining = (entry: Live) => + entry.runner !== undefined && + deps.holds?.current(entry.runner)?.draining === true && + !recycleHolds.has(entry.agentId); + const canWake = (w: Waiting, entry: Live) => + draining(entry) && + entry.turnOpen && + w.wakeTurnSeq !== undefined && + w.wakeTurnSeq === entry.turnSeq; + /** * Stop and discard start runner processes, so a held runner's fence would * refuse them: wait for the hold, and wait again if a refusal says the @@ -475,13 +486,14 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { while ( entry.queue.waiting.length && (!entry.remote || entry.client.isReady()) && - !held(entry) && !entry.deliveryInterrupts.size && live.get(agentId) === entry ) { - const urgent = entry.queue.waiting.filter( - (w) => w.delivery === "interrupt" - ); + const gated = held(entry); + if (gated && !entry.queue.waiting.some((w) => canWake(w, entry))) break; + const urgent = gated + ? [] + : entry.queue.waiting.filter((w) => w.delivery === "interrupt"); for (const w of urgent) { // A steering request may settle the arrival-time turn while the pump // is locked. Its interrupt must never migrate to a subsequent turn. @@ -549,7 +561,8 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { if (!entry.client.welcome?.steeringSupported) break; const index = entry.queue.waiting.findIndex( (w) => - w.delivery === "auto" && + (!gated || canWake(w, entry)) && + (w.delivery === "auto" || (gated && canWake(w, entry))) && !w.requiresPrompt && !w.steering?.pending && !( @@ -558,7 +571,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { .slice(0, entry.queue.waiting.indexOf(w)) .some( (earlier) => - isUserPost(earlier) && earlier.steering?.pending + (!gated || canWake(earlier, entry)) && + isUserPost(earlier) && + earlier.steering?.pending ) ) && steers(w, entry) @@ -601,6 +616,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { for (const w of batch) { w.taken = false; w.delivery = "queue"; + w.wakeTurnSeq = undefined; } // Keep declined input ahead of ordinary queued work, but behind // interrupts that arrived while the request was pending. @@ -639,7 +655,10 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { if (!images) throw new Error("Runner prompt file delivery is unavailable."); if (steering) { - if (held(entry)) { + if ( + (gated || held(entry)) && + !batch.every((w) => canWake(w, entry)) + ) { for (const w of batch) finishDecision(w, "queued"); await requeue(); continue; @@ -674,6 +693,10 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { { mode: 0o600, flush: true } ); } + if (entry.runner && deps.holds?.current(entry.runner)?.draining) { + await requeue(); + continue; + } // Set this before submitting: ack and settle can arrive together. submitted = true; entry.turnOpen = true; @@ -1023,7 +1046,19 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { input.runnerName === undefined || isPromptImageMimeType(input.mimeType) ) ?? false; + const wakeTurnSeq = + opts?.delivery === "auto" && + !requiresPrompt && + entry.turnOpen && + !source?.scheduleId && + (source?.awaited || + (source?.correlatedReply && + source.conversation && + sameConversation(source.conversation, entry.conversation))) + ? entry.turnSeq + : undefined; const own: Waiting = { + wakeTurnSeq, requiresPrompt, text, ...(opts?.beforeSubmit ? { beforeSubmit: opts.beforeSubmit } : {}), @@ -1207,16 +1242,38 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { .map(identify); }, - holdForRecycle(runnerId, host) { + async runnerHostAlive(runnerId, agentId) { + const placement = await placementOf(agentId); + if (placement?.runner !== runnerId) + throw new Error("No matching runner placement for this host."); + const { value } = await requestSession(placement, { + kind: "alive", + agentId, + }); + return value === true; + }, + + wakeRunnerDrain(runnerId) { + for (const [agentId, entry] of live) + if (entry.runner === runnerId) void pump(agentId, entry); + }, + + holdForRecycle(runnerId, host, drainEpoch) { const { agentId } = host; const entry = live.get(agentId); + const drain = drainEpoch !== undefined; if ( !entry || entry.runner !== runnerId || !host.instanceId || entry.client.welcome?.hostInstanceId !== host.instanceId || entry.client.welcome?.quiesceSupported !== true || - held(entry) || + (drain + ? entry.channelEpoch !== drainEpoch || + !entry.client.isReady() || + entry.turnOpen || + recycleHolds.has(agentId) + : held(entry)) || entry.pumping || entry.deliveryInterrupts.size ) @@ -1312,8 +1369,17 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { pathPrefix, onWorkspaceProgress, beforeLaunchReconcile, + requireResume, ...launch } = input; + if (requireResume) { + const previous = live.get(input.agentId); + if (previous && preserving(previous)) { + live.delete(input.agentId); + previous.client.close(); + await previous.events; + } + } const { launchExited } = await requestLaunch( placement, { kind: "launch", agentId: input.agentId, launch }, @@ -1331,10 +1397,16 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { if (!welcome) throw new Error("no welcome from the agent host"); const recycle = recycleHolds.get(input.agentId); if ( - recycle?.restarting && + (requireResume || recycle?.restarting) && (!welcome.resumed || welcome.sessionId !== input.resumeSessionId) ) { - await runtime.stop(input.agentId, false); + if (requireResume && placement) { + await requestSession(placement, { + kind: "stop", + agentId: input.agentId, + force: false, + }); + } else await runtime.stop(input.agentId, false); throw new Error( "The replacement host could not resume the existing session." ); diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index eab235b5a..c56cfb455 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -71,6 +71,7 @@ import { type QueuedPromptAction, type QueuedPromptControl, type RunnerHostIdentity, + type RunnerHostRecycleHold, createAgentRuntime, } from "./runtime.js"; import { @@ -357,7 +358,7 @@ export const LAUNCH_CONTEXT_RESOLVE_TIMEOUT_MS = 5_000; const TIMED_OUT = Symbol("timed-out"); class RecycleSuperseded extends Error {} -type RecycleRestart = { mayStart(): boolean }; +type RecycleRestart = { mayStart(): boolean; drain?: true }; /** Resolve with the promise's value, or `TIMED_OUT` after `ms`. */ function withTimeout( @@ -377,6 +378,8 @@ export const UPDATE_RESUME_MESSAGE = "Dispatch stopped this idle agent for an update. Start it to continue if automatic resume did not finish."; export class AgentManager { + private readonly runnerDrainReceipts = new Map>(); + private readonly drainedHostHolds = new Map(); private readonly hostRecycler: RunnerHostRecycler; private readonly recyclingHosts = new Set(); private readonly stoppingOrArchiving = new Map(); @@ -572,6 +575,7 @@ export class AgentManager { (await this.streamStore.settleInterrupted(id, reason)).length, ...(this.holds && { launchHeld: (id: string) => this.holds!.hasLaunch(id), + updateResumePending: (id: string) => this.hasRunnerDrainReceipt(id), }), }); this.holds?.onRelease((release) => @@ -1301,7 +1305,8 @@ export class AgentManager { ); for (const row of result.rows) { // Its launch is held for a runner update and runs when that opens. - if (this.holds?.hasLaunch(row.id)) continue; + if (this.holds?.hasLaunch(row.id) || this.hasRunnerDrainReceipt(row.id)) + continue; this.streamRecorder.setCwd( row.id, remotePlacement(row.cwd) ? row.cwd : (row.workspacePath ?? row.cwd) @@ -3061,6 +3066,7 @@ export class AgentManager { opts.launchId && { launchId: opts.launchId, beforeLaunchReconcile: () => this.assertLifecycleCurrent(agent), + ...(opts.recycle?.drain && { requireResume: true }), }), ...(onWorkspaceProgress && { onWorkspaceProgress }), }); @@ -3144,7 +3150,7 @@ export class AgentManager { return (await this.getAgent(id)) as AgentRecord; } - await this.setAgentStatus(id, "creating", null); + if (!recycle?.drain) await this.setAgentStatus(id, "creating", null); try { if (!remotePlacement(agent.cwd) && !agent.worktreePath) { const workspace = await this.localRunner.resumeWorkspace( @@ -3159,7 +3165,7 @@ export class AgentManager { // A stopped job still needs its run-scoped tools and launch rules when // its host is recreated. Reattaching above keeps the existing context. if (recycle && !recycle.mayStart()) throw new RecycleSuperseded(); - if (await this.holdLaunch(agent, "start", launchId)) + if (!recycle?.drain && (await this.holdLaunch(agent, "start", launchId))) return (await this.getAgent(id)) as AgentRecord; const jobRun = await this.pool.query<{ id: string }>( "SELECT id FROM job_runs WHERE agent_id = $1 AND status IN ('started', 'running', 'needs_input') ORDER BY started_at DESC LIMIT 1", @@ -3176,7 +3182,10 @@ export class AgentManager { }); } catch (error) { // Refused by the runner's update fence: nothing started. - if (await this.holdRefusedLaunch(agent, error, "start", launchId)) + if ( + !recycle?.drain && + (await this.holdRefusedLaunch(agent, error, "start", launchId)) + ) return (await this.getAgent(id)) as AgentRecord; throw error; } @@ -3192,6 +3201,7 @@ export class AgentManager { } catch (error) { if (error instanceof LifecycleSuperseded) return this.getRequiredAgent(id); + if (recycle?.drain) throw error; if (error instanceof RecycleSuperseded) { await this.setAgentStatus(id, "stopped", null); return this.getRequiredAgent(id); @@ -3295,6 +3305,137 @@ export class AgentManager { await this.runtime.attach(agentId); } + setRunnerDrainReceipt(runnerId: string, ids: string[]): void { + const next = new Set(ids); + for (const id of this.runnerDrainReceipts.get(runnerId) ?? []) { + if (next.has(id)) continue; + this.drainedHostHolds.get(id)?.release(); + this.drainedHostHolds.delete(id); + } + if (ids.length) this.runnerDrainReceipts.set(runnerId, next); + else this.runnerDrainReceipts.delete(runnerId); + } + + private hasRunnerDrainReceipt(id: string): boolean { + return [...this.runnerDrainReceipts.values()].some((ids) => ids.has(id)); + } + + /** Legacy identities can be absent from the runner's retained list. */ + async runnerDrainHosts(runnerId: string, retainedIds: string[]) { + this.runtime.wakeRunnerDrain?.(runnerId); + const hosts = new Map( + (this.runtime.runnerHosts?.(runnerId) ?? []).map((host) => [ + host.agentId, + host, + ]) + ); + const { rows } = await this.pool.query<{ id: string; cwd: string }>( + `SELECT id, cwd FROM agents + WHERE status IN ('running', 'creating', 'stopping', 'archiving') + AND cwd LIKE 'runner://%' AND deleted_at IS NULL` + ); + const ids = new Set([ + ...retainedIds, + ...hosts.keys(), + ...rows + .filter( + ({ id, cwd }) => + remotePlacement(cwd)?.runner === runnerId && + !this.holds?.hasLaunch(id) + ) + .map(({ id }) => id), + ]); + const inventory = await Promise.all( + [...ids].map(async (id) => { + try { + if ((await this.runtime.runnerHostAlive?.(runnerId, id)) === false) + return null; + } catch { + return { id, host: undefined }; + } + return { id, host: hosts.get(id) }; + }) + ); + return inventory.filter((entry) => entry !== null); + } + + /** Persist the running-row receipt before asking an idle host to exit. */ + async stopRunnerHostForDrain( + runnerId: string, + host: RunnerHostIdentity, + epoch: number, + mayStop: () => boolean, + record: (entry: { id: string; updatedAt: string }) => Promise + ): Promise { + const id = host.agentId; + if (this.lifecycleOperations.has(id) || this.drainedHostHolds.has(id)) + return; + await this.serializeLifecycle(id, async () => { + const agent = await this.getAgent(id); + if ( + agent?.status !== "running" || + !agent.cliSessionId || + remotePlacement(agent.cwd)?.runner !== runnerId || + this.stoppingOrArchiving.has(id) + ) + return; + const hold = this.runtime.holdForRecycle?.(runnerId, host, epoch); + if (!hold) return; + let keep = false; + try { + if (!(await hold.quiesce())) return; + const [entry] = await this.updateResumeSnapshot([id]); + if (!entry || this.stoppingOrArchiving.has(id) || !mayStop()) return; + await record(entry); + if (this.stoppingOrArchiving.has(id) || !hold.current() || !mayStop()) + return; + keep = await hold.shutdown(); + if (keep) this.drainedHostHolds.set(id, hold); + } finally { + if (!keep) hold.release(); + } + }); + } + + /** The unchanged running row remains the claim until recovery is recorded. */ + async resumeRunnerDrainHost( + runnerId: string, + attemptId: string, + entry: { id: string; updatedAt: string } + ): Promise { + const id = entry.id; + const release = () => { + this.drainedHostHolds.get(id)?.release(); + this.drainedHostHolds.delete(id); + }; + // Stop can be inside the lifecycle lock waiting for the runner hold. + if (this.stoppingOrArchiving.has(id)) return release(); + await this.serializeLifecycle(id, async () => { + if (!(await this.eligibleUpdateResumes([entry])).has(id)) + return release(); + const agent = await this.getAgent(id); + if ( + !agent?.cliSessionId || + remotePlacement(agent.cwd)?.runner !== runnerId + ) + return release(); + if (await this.runtime.runnerHostAlive?.(runnerId, id)) { + if (this.drainedHostHolds.has(id)) + throw new Error("The quiesced runner host is still exiting."); + release(); + if (!(await this.runtime.attach(id))) + throw new Error("The runner host has not reattached."); + return; + } + if (this.stoppingOrArchiving.has(id)) return release(); + await this.startAgentClaimed(id, attemptId, { + drain: true, + mayStart: () => !this.stoppingOrArchiving.has(id), + }); + release(); + }); + } + private async recycleRunnerHost( update: ConfirmedRunnerUpdate, host: RunnerHostIdentity, @@ -3410,6 +3551,17 @@ export class AgentManager { return this.getRequiredAgent(id); } + if ( + placement && + this.hasRunnerDrainReceipt(id) && + (await this.runtime + .runnerHostAlive?.(placement.runner, id) + .catch(() => true)) === false + ) { + await this.setAgentStatus(id, "stopped", null, undefined, guard); + return this.getRequiredAgent(id); + } + // The stop hook and the stop run on the runner; its update fence would // refuse both. Wait for a held runner first, with the agent untouched. if (placement && this.holds) { @@ -3506,7 +3658,7 @@ export class AgentManager { checkoutState ); }, - this.recyclingHosts.has(id) + this.recyclingHosts.has(id) || this.hasRunnerDrainReceipt(id) ); } @@ -3865,7 +4017,11 @@ export class AgentManager { settleStream: (id) => this.streamRecorder.settleStopped(id), setArchivePhase: (id, phase) => this.setArchivePhase(id, phase), claimArchive: (id, claim) => - this.terminateLifecycle(id, claim, this.recyclingHosts.has(id)), + this.terminateLifecycle( + id, + claim, + this.recyclingHosts.has(id) || this.hasRunnerDrainReceipt(id) + ), ...(this.holds && { waitForRunner: async (agent: AgentRecord) => { const placement = remotePlacement(agent.cwd); diff --git a/apps/server/src/agents/reconciler.ts b/apps/server/src/agents/reconciler.ts index 1e2d89329..2933e89a1 100644 --- a/apps/server/src/agents/reconciler.ts +++ b/apps/server/src/agents/reconciler.ts @@ -49,6 +49,7 @@ export type ReconcilerDeps = { settleStream: (id: string, reason: string) => Promise; /** A launch held for a runner update: not a launch that failed. */ launchHeld?: (id: string) => boolean; + updateResumePending?: (id: string) => boolean; }; export type Reconciler = { @@ -103,6 +104,7 @@ async function reconcileAgentStatuses( (row) => runtime.tracksProcesses() && !deps.launchHeld?.(row.id) && + !deps.updateResumePending?.(row.id) && (row.status === "running" || row.status === "creating") && !( row.status === "creating" && @@ -127,6 +129,8 @@ async function reconcileAgentStatuses( ); for (const row of result.rows) { + if (deps.updateResumePending?.(row.id) && row.status === "running") + continue; const stuckSeconds = (Date.now() - new Date(row.updatedAt).getTime()) / 1000; diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index bd01f4ad0..3fab21e8d 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -4,6 +4,7 @@ import type { FastifyBaseLogger } from "fastify"; import { z } from "zod"; import type { RunnerArtifactSource } from "../../server/runner-artifacts.js"; +import { resumeAgentSchema } from "../../update-recovery/resume-receipt.js"; import type { AgentManager } from "../manager.js"; import { endsUpdateAttempt, @@ -28,12 +29,10 @@ import { compareRunnerVersions } from "./update-verify.js"; * staging ─ready→ settling ─fence_ready→ switching ─trial→ confirming * └───────────────┴──────────────┴─────────────────┴──→ cancelling * - * and from any of them an outcome: updated, rolled_back, deferred or - * needs_idle. Each step is saved before the frame that causes it is sent, so - * a restarted Dispatch or a reconnected runner resumes the same attempt or - * ends it. Work goes on while the runner stages, and is held from `ready`, - * before the fence is asked for. The runner owns the swap and its rollback; this only asks, - * observes and confirms. It never drains, forces or picks an update itself. + * Incompatible hosts drain before settling with an empty retained set. + * Once the runner reports an outcome, Dispatch resumes the stopped hosts + * before releasing held work. Work goes on during staging, and is held + * before the first fence. The runner owns the swap and its rollback. */ /** Phase budgets. Each is saved as a deadline and never extended by a restart. */ @@ -55,6 +54,8 @@ export const UPDATE_TIMING = { /** The task-5 hold outlasts every phase it covers. */ export const UPDATE_HOLD_BOUND_MS = 20 * 60_000; +const DRAIN_WAIT_MS = 2 * 60 * 60_000; +const DRAIN_HOLD_BOUND_MS = DRAIN_WAIT_MS + UPDATE_HOLD_BOUND_MS; const targetSchema = z.object({ version: z.string(), @@ -64,6 +65,12 @@ const targetSchema = z.object({ revision: z.string(), }); +const outcomeSchema = z.object({ + state: z.enum(["updated", "rolled_back", "deferred", "needs_idle"]), + reason: z.string().optional(), + floorVersion: z.string().optional(), +}); + const attemptSchema = z.object({ id: z.string().uuid(), /** Absent only for a runner's attempt that Dispatch has no record of. */ @@ -72,6 +79,8 @@ const attemptSchema = z.object({ phase: z.enum([ "staging", "settling", + "draining", + "resuming", "switching", "confirming", "cancelling", @@ -87,11 +96,13 @@ const attemptSchema = z.object({ activated: z.boolean().optional(), /** Why Dispatch cancelled. */ reason: z.string().optional(), - outcome: z + outcome: outcomeSchema.optional(), + drain: z .object({ - state: z.enum(["updated", "rolled_back", "deferred", "needs_idle"]), - reason: z.string().optional(), - floorVersion: z.string().optional(), + retainedIds: z.array(z.string()).max(1024), + waiting: z.number().int().nonnegative().optional(), + agents: z.array(resumeAgentSchema).max(10_000), + result: outcomeSchema.optional(), }) .optional(), }); @@ -145,6 +156,7 @@ export function fileRunnerUpdateStore( } const INELIGIBLE = { + stale_drain: "This drain is no longer waiting.", not_ready: "Dispatch is still starting. Try again in a moment.", offline: "The runner is offline.", unsupported: @@ -197,6 +209,10 @@ type CoordinatorAgents = Pick< | "settleRunnerHostRecycling" | "startRunnerHostRecycling" | "stopRunnerHostRecycling" + | "runnerDrainHosts" + | "stopRunnerHostForDrain" + | "resumeRunnerDrainHost" + | "setRunnerDrainReceipt" >; export class RunnerUpdateCoordinator { @@ -209,6 +225,8 @@ export class RunnerUpdateCoordinator { /** The connection that reported `activating/trial`. */ private readonly trials = new Map(); private readonly confirms = new Map(); + private readonly waiting = new Map(); + private readonly drainCancellations = new Set(); private readonly attaching = new Set(); private readonly ticking = new Set(); /** Between stopping a recycling pass and the attempt that replaces it. */ @@ -253,8 +271,10 @@ export class RunnerUpdateCoordinator { } async load(): Promise { - for (const record of await this.options.store.read()) + for (const record of await this.options.store.read()) { this.records.set(record.runnerId, record); + this.syncReceipt(record); + } } /** @@ -269,6 +289,7 @@ export class RunnerUpdateCoordinator { this.release(runnerId, attempt.id, holdOutcome(attempt.outcome)); else if ( attempt.phase !== "cancelling" && + attempt.phase !== "resuming" && !this.isOwnBuild(attempt.target) ) // Never offer or confirm another Dispatch build's target. Without a @@ -311,6 +332,31 @@ export class RunnerUpdateCoordinator { return request; } + async cancelDrain(runnerId: string, attemptId: string) { + if (!this.options.service.isRegistered(runnerId)) + throw new RunnerUpdateIneligible("not_found"); + if (!this.started) throw new RunnerUpdateIneligible("not_ready"); + const valid = (attempt: Attempt | undefined): attempt is Attempt => + attempt?.id === attemptId && attempt.phase === "draining"; + if (!valid(this.active(runnerId))) + throw new RunnerUpdateIneligible("stale_drain"); + this.drainCancellations.add(attemptId); + try { + return await this.enqueue(runnerId, async () => { + const attempt = this.active(runnerId); + if (!valid(attempt)) throw new RunnerUpdateIneligible("stale_drain"); + // The incompatible fence was released before the waiting phase. + await this.finish(runnerId, attempt, { + state: "deferred", + reason: "drain_cancelled", + }); + return { attemptId }; + }); + } finally { + this.drainCancellations.delete(attemptId); + } + } + view(runnerId: string): RunnerUpdateView | undefined { const { service, agents, artifacts, build } = this.options; const record = this.records.get(runnerId); @@ -321,6 +367,15 @@ export class RunnerUpdateCoordinator { attempt: { id: attempt.id, phase: attempt.phase, + ...(attempt.phase === "draining" && { + agents: + this.waiting.get(runnerId) ?? + attempt.drain!.waiting ?? + attempt.drain!.retainedIds.length, + }), + ...(attempt.phase === "resuming" && { + agents: attempt.drain!.agents.length, + }), ...(attempt.target && { version: attempt.target.version }), ...(this.options.holds.current(runnerId)?.attemptId === attempt.id && { held: true }), @@ -329,7 +384,11 @@ export class RunnerUpdateCoordinator { const view: RunnerUpdateView = {}; const last = record?.attempt; - if (last?.outcome && this.showsResult(last, last.outcome, advert)) + if ( + last?.outcome && + last.outcome.state !== "needs_idle" && + this.showsResult(last, last.outcome, advert) + ) view.result = { ...last.outcome, ...(last.target && { version: last.target.version }), @@ -339,8 +398,7 @@ export class RunnerUpdateCoordinator { build.revision && !advert.pendingAttemptId && artifacts()?.updateEnabled && - versionOrder(build.version, advert.version) === 1 && - view.result?.state !== "needs_idle" + versionOrder(build.version, advert.version) === 1 ) view.available = { version: build.version, @@ -475,6 +533,9 @@ export class RunnerUpdateCoordinator { const pending = advert?.pendingAttemptId; let attempt = this.active(runnerId); + if (attempt?.phase === "resuming") return this.advance(runnerId); + if (attempt?.phase === "draining" && !pending) + return this.advance(runnerId); if (attempt && !advert) { await this.finish(runnerId, attempt, { state: "deferred", @@ -499,12 +560,21 @@ export class RunnerUpdateCoordinator { // Nothing waits on an attempt the runner is not fenced for and was not // asked to fence. - if (pending || attempt.phase === "settling" || attempt.activated) { + if ( + pending || + attempt.phase === "settling" || + attempt.activated || + attempt.drain + ) { if (!(await this.holdOrCancel(runnerId, attempt))) return; } else { this.releaseOther(runnerId, attempt.id); } switch (attempt.phase) { + case "draining": + // An earlier fence might still be unwinding on this connection. + await this.cancel(runnerId, attempt, "interrupted"); + return; case "cancelling": return this.sendCancel(runnerId, attempt, epoch); case "staging": @@ -563,7 +633,8 @@ export class RunnerUpdateCoordinator { const live = this.options.service.selfUpdate(runnerId); if (live?.epoch !== epoch) return; const attempt = this.records.get(runnerId)?.attempt; - if (attempt?.id !== status.attemptId) return; + if (attempt?.id !== status.attemptId || attempt.phase === "resuming") + return; const ended = endsUpdateAttempt(status); const { target, outcome } = attempt; @@ -605,9 +676,33 @@ export class RunnerUpdateCoordinator { return this.sendOffer(runnerId, attempt, live.advert, epoch); if ( status.phase === "deferred" && - (status.reason === "incompatible_handoff" || status.requiresQuiescence) + (status.reason === "incompatible_handoff" || status.requiresQuiescence) && + (attempt.phase === "staging" || attempt.phase === "settling") && + !attempt.drain + ) { + const hold = await this.options.holds.begin(runnerId, attempt.id, { + boundMs: DRAIN_HOLD_BOUND_MS, + draining: true, + }); + const retainedIds = [ + ...new Set(status.retained?.map((host) => host.sessionId)), + ]; + const waiting: Attempt = { + ...attempt, + phase: "draining", + retained: undefined, + deadline: Date.parse(hold.beganAt) + DRAIN_WAIT_MS, + drain: { retainedIds, agents: [] }, + }; + if (!(await this.step(runnerId, attempt, waiting))) return; + return this.advance(runnerId); + } + if ( + attempt.phase === "draining" && + status.phase === "deferred" && + status.reason === "incompatible_handoff" ) - return this.finish(runnerId, attempt, { state: "needs_idle" }); + return; // The runner's reason wins, unless it only echoes Dispatch's own cancel. const reason = attempt.reason && @@ -631,7 +726,7 @@ export class RunnerUpdateCoordinator { status: RunnerUpdateEvent["status"] ): Promise { const { phase, target } = attempt; - if (phase === "cancelling" || !target) return; + if (phase === "cancelling" || phase === "draining" || !target) return; const { service } = this.options; if (status.phase === "activating") { @@ -676,7 +771,7 @@ export class RunnerUpdateCoordinator { // Staged: work waits from here, before anything can be refused. if (!(await this.holdOrCancel(runnerId, attempt))) return; this.send(runnerId, () => - service.fenceUpdate(runnerId, attempt.id, true, epoch) + service.fenceUpdate(runnerId, attempt.id, !attempt.drain, epoch) ); return; } @@ -690,7 +785,7 @@ export class RunnerUpdateCoordinator { return; } if (phase !== "settling") return; - if (!status.retained) + if (!status.retained || (attempt.drain && status.retained.length)) return this.cancel(runnerId, attempt, "interrupted"); const fenced: Attempt = { ...attempt, @@ -712,6 +807,8 @@ export class RunnerUpdateCoordinator { const attempt = this.active(runnerId); if (!attempt) return; const { service } = this.options; + if (attempt.phase === "resuming") + return this.resumeDrain(runnerId, attempt); if (!service.isRegistered(runnerId)) return this.finish(runnerId, attempt, { state: "deferred", @@ -720,6 +817,18 @@ export class RunnerUpdateCoordinator { const now = this.now(); const live = service.selfUpdate(runnerId); const { phase } = attempt; + if (phase === "draining") { + if ( + now >= attempt.deadline || + this.options.holds.current(runnerId)?.attemptId !== attempt.id + ) + return this.finish(runnerId, attempt, { + state: "deferred", + reason: "drain_timeout", + }); + if (live) await this.drain(runnerId, attempt, live.advert, live.epoch); + return; + } if (now >= attempt.deadline) { if (phase === "cancelling" || !live) return this.finish(runnerId, attempt, { @@ -766,6 +875,99 @@ export class RunnerUpdateCoordinator { ); } + private async drain( + runnerId: string, + attempt: Attempt, + advert: SelfUpdateAdvert, + epoch: number + ) { + const { agents } = this.options; + const drain = attempt.drain!; + const mayStop = () => + !this.closed && + !this.drainCancellations.has(attempt.id) && + this.now() < attempt.deadline && + this.options.service.connectionEpoch(runnerId) === epoch && + this.options.holds.current(runnerId)?.attemptId === attempt.id; + const hosts = await agents.runnerDrainHosts(runnerId, drain.retainedIds); + if (!mayStop()) return; + const waiting = new Set(hosts.map(({ id }) => id)).size; + this.waiting.set(runnerId, waiting); + if (waiting !== drain.waiting) { + attempt = { ...attempt, drain: { ...drain, waiting } }; + await this.save({ ...this.records.get(runnerId), runnerId, attempt }); + if (!mayStop()) return; + } + if (!hosts.length) { + const next: Attempt = { + ...attempt, + phase: "settling", + deadline: this.now() + UPDATE_TIMING.settlingMs, + }; + if (await this.step(runnerId, attempt, next)) + this.sendOffer(runnerId, next, advert, epoch); + return; + } + for (const { id, host } of hosts) { + if (!mayStop()) return; + if (host?.attachedEpoch !== epoch) { + this.attach(runnerId, id); + continue; + } + await agents.stopRunnerHostForDrain( + runnerId, + host, + epoch, + mayStop, + async (entry) => { + const current = this.active(runnerId)!; + const drain = current.drain!; + const next = { + ...current, + drain: { + ...drain, + agents: [ + ...drain.agents.filter(({ id }) => id !== entry.id), + entry, + ], + }, + }; + // A failed write must never allow the host to shut down. + await this.save({ + ...this.records.get(runnerId), + runnerId, + attempt: next, + }); + } + ); + } + } + + private async resumeDrain(runnerId: string, attempt: Attempt) { + const drain = attempt.drain!; + const { agents, service } = this.options; + if (drain.agents.length && service.isRegistered(runnerId)) { + // A reconnect with an outstanding trial is not an installed build yet. + const live = service.selfUpdate(runnerId); + if ( + service.connectionEpoch(runnerId) === undefined || + live?.advert.pendingAttemptId + ) + return; + const [entry, ...remaining] = drain.agents; + await agents.resumeRunnerDrainHost(runnerId, attempt.id, entry!); + const next = { ...attempt, drain: { ...drain, agents: remaining } }; + await this.save({ + ...this.records.get(runnerId), + runnerId, + attempt: next, + }); + if (remaining.length) return; + attempt = next; + } + return this.finish(runnerId, attempt, drain.result!); + } + /** * Proof is the host's own welcome and completed replay, for the recorded * instance, on an attach opened over this connection. A connected runner @@ -776,27 +978,29 @@ export class RunnerUpdateCoordinator { retained: RetainedSession[], epoch: number ): boolean { - const { agents, logger } = this.options; + const { agents } = this.options; const missing = retained.filter( (session) => !agents.isRunnerSessionAttached(runnerId, session, epoch) ); - for (const { sessionId } of missing) { - const key = `${runnerId}/${sessionId}`; - if (this.attaching.has(key)) continue; - this.attaching.add(key); - void agents - .attachRunnerSession(runnerId, sessionId) - .catch((error: unknown) => - logger.warn( - { err: error, runnerId, sessionId }, - "could not attach a retained runner session" - ) - ) - .finally(() => this.attaching.delete(key)); - } + for (const { sessionId } of missing) this.attach(runnerId, sessionId); return missing.length === 0; } + private attach(runnerId: string, sessionId: string) { + const key = `${runnerId}/${sessionId}`; + if (this.attaching.has(key)) return; + this.attaching.add(key); + void this.options.agents + .attachRunnerSession(runnerId, sessionId) + .catch((err: unknown) => + this.options.logger.warn( + { err, runnerId, sessionId }, + "could not attach a retained runner session" + ) + ) + .finally(() => this.attaching.delete(key)); + } + // --- Ending an attempt --- private cancelling(attempt: Attempt, reason: string): Attempt { @@ -819,6 +1023,15 @@ export class RunnerUpdateCoordinator { } private async finish(runnerId: string, attempt: Attempt, outcome: Outcome) { + if (attempt.drain?.agents.length && attempt.phase !== "resuming") { + await this.record(runnerId, { + ...attempt, + phase: "resuming", + drain: { ...attempt.drain, result: outcome }, + }); + return; + } + this.waiting.delete(runnerId); const { target } = attempt; let { confirmed, failed } = this.records.get(runnerId) ?? {}; if (outcome.state === "updated" && target) { @@ -836,7 +1049,7 @@ export class RunnerUpdateCoordinator { } await this.saveOrKeep({ runnerId, - attempt: { ...attempt, outcome }, + attempt: { ...attempt, drain: undefined, outcome }, ...(confirmed && { confirmed }), ...(failed && { failed }), }); @@ -885,6 +1098,11 @@ export class RunnerUpdateCoordinator { private async holdFor(runnerId: string, attemptId: string) { this.releaseOther(runnerId, attemptId); + if (this.active(runnerId)?.drain) { + if (this.options.holds.current(runnerId)?.attemptId !== attemptId) + throw new Error("The drain hold expired."); + return; + } await this.options.holds.begin(runnerId, attemptId, { boundMs: UPDATE_HOLD_BOUND_MS, }); @@ -1033,9 +1251,18 @@ export class RunnerUpdateCoordinator { "could not save runner update state" ); this.records.set(record.runnerId, record); + this.syncReceipt(record); } } + private syncReceipt({ runnerId, attempt }: RunnerUpdateRecord) { + if (attempt.drain) + this.options.agents.setRunnerDrainReceipt( + runnerId, + attempt.drain.agents.map(({ id }) => id) + ); + } + /** Writes are serialized, and memory follows the file. */ private save(record: RunnerUpdateRecord): Promise { const write = this.writes @@ -1043,7 +1270,11 @@ export class RunnerUpdateCoordinator { .then(async () => { const next = new Map(this.records).set(record.runnerId, record); await this.options.store.write([...next.values()]); + const hadDrain = this.records.get(record.runnerId)?.attempt.drain; this.records.set(record.runnerId, record); + if (hadDrain && !record.attempt.drain) + this.options.agents.setRunnerDrainReceipt(record.runnerId, []); + this.syncReceipt(record); }); this.writes = write; return write; diff --git a/apps/server/src/agents/remote/update-hold.ts b/apps/server/src/agents/remote/update-hold.ts index 6c0d1ef92..0106d8cd1 100644 --- a/apps/server/src/agents/remote/update-hold.ts +++ b/apps/server/src/agents/remote/update-hold.ts @@ -88,6 +88,7 @@ const runnerHold = z beganAt: z.string().datetime(), expiresAt: z.string().datetime(), launches: z.array(heldLaunch).max(10_000), + draining: z.literal(true).optional(), }) .strict(); export type RunnerHold = z.infer; @@ -251,11 +252,29 @@ export class RunnerUpdateHolds { async begin( runnerId: string, attemptId: string, - options: { boundMs?: number } = {} + options: { boundMs?: number; draining?: true } = {} ): Promise { const existing = this.holds.get(runnerId); if (existing) { - if (existing.attemptId === attemptId) return snapshot(existing); + if (existing.attemptId === attemptId) { + if (options.draining && !existing.draining) { + const expiresAt = existing.expiresAt; + existing.draining = true; + existing.expiresAt = new Date( + Date.parse(existing.beganAt) + (options.boundMs ?? this.boundMs) + ).toISOString(); + try { + await this.persist(); + } catch (error) { + delete existing.draining; + existing.expiresAt = expiresAt; + throw error; + } + if (this.holds.get(runnerId) === existing) this.arm(existing); + else throw new RunnerHoldConflict("The runner hold expired."); + } + return snapshot(existing); + } throw new RunnerHoldConflict( "Another update attempt is holding this runner." ); @@ -269,6 +288,7 @@ export class RunnerUpdateHolds { now + (options.boundMs ?? this.boundMs) ).toISOString(), launches: [], + ...(options.draining && { draining: true }), }; this.holds.set(runnerId, hold); try { @@ -481,5 +501,6 @@ function snapshot(hold: Live): RunnerHold { beganAt: hold.beganAt, expiresAt: hold.expiresAt, launches: [...hold.launches], + ...(hold.draining && { draining: true }), }; } diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index f581d830a..625ff3eb5 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -31,6 +31,7 @@ export type RuntimeLaunch = HostLaunch & { onWorkspaceProgress?: (progress: LaunchProgress) => void; /** Recheck ownership after waiting for a runner whose launch reply was lost. */ beforeLaunchReconcile?: () => Promise; + requireResume?: true; }; export type RuntimeEventListener = ( @@ -86,9 +87,12 @@ export type AgentRuntime = { attach(agentId: string): Promise; isAlive(agentId: string): Promise; runnerHosts?(runnerId: string): RunnerHostIdentity[]; + wakeRunnerDrain?(runnerId: string): void; + runnerHostAlive?(runnerId: string, agentId: string): Promise; holdForRecycle?( runnerId: string, - host: RunnerHostIdentity + host: RunnerHostIdentity, + drainEpoch?: number ): RunnerHostRecycleHold | null; /** Inspect an existing session without starting it or submitting chat. */ getMcpInventory(agentId: string): Promise; diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index 24c6270c3..a68936a30 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -4424,6 +4424,7 @@ export class StreamService { ...(structuredAnswer || block.kind !== "text" || own.rawPrompt ? { steeringExcluded: true } : {}), + ...(structuredAnswer && { correlatedReply: true as const }), // A review, or a word under one of its findings, is what the agent // on the other side is waiting for: it reaches a busy agent now. ...(block.kind === "review" || finding ? { awaited: true } : {}), diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts index 888fa7bca..af6c27326 100644 --- a/apps/server/src/routes/runners.ts +++ b/apps/server/src/routes/runners.ts @@ -69,11 +69,29 @@ export async function registerRunnerRoutes( app.post(`${base}/:id/update`, async (request, reply) => { const { id } = request.params as { id: string }; - const { action } = (request.body ?? {}) as { action?: unknown }; + const { action, attemptId } = (request.body ?? {}) as { + action?: unknown; + attemptId?: unknown; + }; + if (action === "cancel") { + if (typeof attemptId !== "string") + return reply + .code(400) + .send({ error: "The drain attempt ID is required." }); + if (!deps.updates) + return reply.code(404).send({ error: "Runner not found." }); + try { + return reply + .code(202) + .send(await deps.updates.cancelDrain(id, attemptId)); + } catch (error) { + return fail(reply, error); + } + } if (action !== "update" && action !== "retry") - return reply - .code(400) - .send({ error: 'The action must be "update" or "retry".' }); + return reply.code(400).send({ + error: 'The action must be "update", "retry", or "cancel".', + }); if (!deps.updates) return reply.code(404).send({ error: "Runner not found." }); try { diff --git a/apps/server/src/update-recovery/resume-receipt.ts b/apps/server/src/update-recovery/resume-receipt.ts index 1222d5c54..272258384 100644 --- a/apps/server/src/update-recovery/resume-receipt.ts +++ b/apps/server/src/update-recovery/resume-receipt.ts @@ -5,21 +5,19 @@ import { uuid } from "./protocol.js"; import { readPrivate, writeAtomic, syncDirectory } from "./files.js"; const readPrivateFile = (file: string) => readPrivate(file, { maxBytes: 64 * 1024 }); +export const resumeAgentSchema = z + .object({ + id: z.string().regex(/^agt_[A-Za-z0-9_-]{1,64}$/), + updatedAt: z.string().min(1).max(64), + }) + .strict(); + const resumeReceiptSchema = z .object({ formatVersion: z.literal(1), transactionId: uuid, createdAt: z.string().datetime(), - agents: z - .array( - z - .object({ - id: z.string().regex(/^agt_[A-Za-z0-9_-]{1,64}$/), - updatedAt: z.string().min(1).max(64), - }) - .strict() - ) - .max(10_000), + agents: z.array(resumeAgentSchema).max(10_000), }) .strict(); export type ResumeReceipt = z.infer; diff --git a/apps/server/test/db/runner-update-hold-manager.test.ts b/apps/server/test/db/runner-update-hold-manager.test.ts index 7fe66adfa..23e42fc32 100644 --- a/apps/server/test/db/runner-update-hold-manager.test.ts +++ b/apps/server/test/db/runner-update-hold-manager.test.ts @@ -811,3 +811,54 @@ describe("launches on a runner held for an update", () => { expect(await manager.isUpdateHeld(local.id)).toBe(false); }); }); + +describe("runner drain resume receipts", () => { + it("protects the receipt at boot and never restarts a user-stopped, archived or deleted agent", async () => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const [resume, stopped, archived, deleted] = await Promise.all( + Array.from({ length: 4 }, () => manager.createAgent({ cwd: HELD })) + ); + const entries = await manager.updateResumeSnapshot([ + resume.id, + stopped.id, + archived.id, + deleted.id, + ]); + await holds.begin("r1", ATTEMPT, { draining: true }); + const afterRestart = managerOn(holds, runtime); + afterRestart.setRunnerDrainReceipt( + "r1", + entries.map(({ id }) => id) + ); + expect((await afterRestart.restoreRunningAgents()).lost).toEqual([]); + await afterRestart.reconcileAgentStatuses(); + expect(await statusOf(resume.id)).toBe("running"); + Object.assign(runtime, { runnerHostAlive: vi.fn(async () => false) }); + await afterRestart.stopAgent(stopped.id); + await afterRestart.beginArchive(archived.id); + await pool.query("UPDATE agents SET deleted_at = NOW() WHERE id = $1", [ + deleted.id, + ]); + runtime.launch.mockClear(); + for (const entry of entries) + await afterRestart.resumeRunnerDrainHost("r1", ATTEMPT, entry); + for (const entry of entries) + await afterRestart.resumeRunnerDrainHost("r1", ATTEMPT, entry); + expect(runtime.launch.mock.calls).toEqual([ + [ + expect.objectContaining({ + agentId: resume.id, + launchId: ATTEMPT, + resumeSessionId: resume.cliSessionId, + requireResume: true, + }), + ], + ]); + expect(await statusOf(stopped.id)).toBe("stopped"); + expect(await statusOf(archived.id)).toBe("archiving"); + expect(await afterRestart.getAgent(deleted.id)).toBeNull(); + expect(holds.isHeld("r1")).toBe(true); + }); +}); diff --git a/apps/server/test/runner-update-coordinator-fixtures.ts b/apps/server/test/runner-update-coordinator-fixtures.ts index 8217d1833..ff4502569 100644 --- a/apps/server/test/runner-update-coordinator-fixtures.ts +++ b/apps/server/test/runner-update-coordinator-fixtures.ts @@ -218,6 +218,13 @@ export async function updateWorld( }); } + const drain = { + hosts: new Map(), + stopped: [] as string[], + resumed: [] as Array<{ id: string; revision: string }>, + recovery: Promise.resolve(), + }; + // --- The controller, rebuilt on restart --- function controller() { const service = new RemoteRunnerService(); @@ -307,6 +314,40 @@ export async function updateWorld( ), settleRunnerHostRecycling: vi.fn(async () => {}), startRunnerHostRecycling: vi.fn(), + runnerDrainHosts: vi.fn(async () => + [...drain.hosts].map(([id, state]) => ({ + id, + host: + state === "unattached" + ? undefined + : { + agentId: id, + attachedEpoch: service.connectionEpoch(RUNNER), + build: runner.identity, + instanceId: INSTANCE, + quiesceSupported: true, + }, + })) + ), + stopRunnerHostForDrain: vi.fn( + async (_runner, host, _epoch, _mayStop, record) => { + const id = host.agentId as string; + if (drain.hosts.get(id) !== "idle") return; + await record({ id, updatedAt: "2026-11-21 12:00:00+00" }); + drain.stopped.push(id); + drain.hosts.delete(id); + runner.inventory = { + retained: [], + requiresQuiescence: true, + live: drain.hosts.size, + }; + } + ), + resumeRunnerDrainHost: vi.fn(async (_runner, _attempt, { id }) => { + await drain.recovery; + drain.resumed.push({ id, revision: runner.identity.revision }); + }), + setRunnerDrainReceipt: vi.fn(), stopRunnerHostRecycling: vi.fn(), }; const coordinator = new RunnerUpdateCoordinator({ @@ -332,6 +373,7 @@ export async function updateWorld( const api = { runner, + drain, hosts, saved, artifacts, diff --git a/apps/server/test/runner-update-coordinator.test.ts b/apps/server/test/runner-update-coordinator.test.ts index a8d5ed9dc..6011947da 100644 --- a/apps/server/test/runner-update-coordinator.test.ts +++ b/apps/server/test/runner-update-coordinator.test.ts @@ -719,34 +719,114 @@ describe("outcomes", () => { expect(world.sent("update_fence")).toEqual([]); }); - it("reports an incompatible handoff as needing idle without forcing it", async () => { + async function waitingDrain() { await online(); + world.drain.hosts.set(AGENT, "idle"); + world.drain.hosts.set("agt_busy", "busy"); + world.drain.hosts.set("agt_unattached", "unattached"); world.runner.inventory = { retained: [], requiresQuiescence: true, - live: 1, + live: world.drain.hosts.size, }; - await update(); - await world.until(() => world.result()); - expect(world.coordinator.view(RUNNER)).toEqual({ - result: { state: "needs_idle", version: target.version }, - }); - expect(world.sent("update_fence")).toHaveLength(1); - expect(world.sent("update_fence")[0].retainSessions).toBe(true); + const { attemptId } = await update(); + await world.until( + () => world.coordinator.view(RUNNER)?.attempt?.agents === 2 + ); + return attemptId; + } + + it("counts busy and unattached hosts and resumes only a partially drained host on cancellation", async () => { + const attemptId = await waitingDrain(); + const release = vi.fn(); + world.holds.onRelease(release); + expect(world.phase()).toBe("draining"); expect(world.sent("update_activate")).toEqual([]); - expect(world.holds.isHeld(RUNNER)).toBe(false); + expect(world.drain.stopped).toEqual([AGENT]); + const recovery = Promise.withResolvers(); + world.drain.recovery = recovery.promise; + await world.coordinator.cancelDrain(RUNNER, attemptId); + await expect( + world.coordinator.cancelDrain(RUNNER, attemptId) + ).rejects.toMatchObject({ + code: "stale_drain", + }); + const pass = world.coordinator.tick(); + try { + await vi.waitFor(() => + expect(world.agents.resumeRunnerDrainHost).toHaveBeenCalledTimes(1) + ); + expect(world.phase()).toBe("resuming"); + expect(world.holds.isHeld(RUNNER)).toBe(true); + expect(release).not.toHaveBeenCalled(); + } finally { + recovery.resolve(); + await pass; + } + await world.until(() => world.result()?.reason === "drain_cancelled"); + await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1)); + expect(world.drain.resumed).toEqual([ + { id: AGENT, revision: identity.revision }, + ]); + await world.coordinator.tick(); + expect(await world.holds.release(RUNNER, attemptId, "cancelled")).toBe( + false + ); + expect(release).toHaveBeenCalledTimes(1); }); - it.each([ - { reason: "incompatible_handoff" }, - { reason: "operations_pending", requiresQuiescence: true }, - ] as const)("reads %o as needing idle", async (status) => { - await online(); - const { attemptId } = await staging(); - world.inject({ attemptId, ...status }); - await world.until(() => world.result()?.state === "needs_idle"); + it("keeps a partial receipt and the original deadline across a controller restart, then recovers on abort", async () => { + await waitingDrain(); + const deadline = world.attempt()!.deadline; + const hold = world.holds.current(RUNNER); + await world.restartController(); + expect(world.holds.current(RUNNER)).toEqual(hold); + expect(world.attempt()?.deadline).toBe(deadline); + expect(world.agents.setRunnerDrainReceipt).toHaveBeenCalledWith(RUNNER, [ + AGENT, + ]); + await world.connect(); + await world.until( + () => world.coordinator.view(RUNNER)?.attempt?.agents === 2 + ); + world.advance(deadline - world.now()); + await world.until(() => world.result()?.reason === "drain_timeout"); + expect(world.holds.isHeld(RUNNER)).toBe(false); + expect(world.drain.resumed).toEqual([ + { id: AGENT, revision: identity.revision }, + ]); }); + it.each(["updated", "rolled_back"] as const)( + "activates with no hosts and recovers on %s", + async (outcome) => { + await waitingDrain(); + world.drain.hosts.set("agt_busy", "idle"); + world.drain.hosts.set("agt_unattached", "idle"); + await world.until(() => world.runner.trial?.phase === "prepared"); + expect(world.sent("update_fence").at(-1)?.retainSessions).toBe(false); + expect(world.runner.trial?.fence.retained).toEqual([]); + expect(world.holds.isHeld(RUNNER)).toBe(true); + expect(world.drain.resumed).toEqual([]); + if (outcome === "rolled_back") { + // Reconnect the prior build with the updater's terminal receipt. + await world.disconnect(); + await world.endTrial("rolled_back", "boot_failed"); + await world.restartRunner(); + } else { + await world.swap(); + } + await world.until(() => world.result()?.state === outcome); + expect(world.drain.resumed).toEqual( + [AGENT, "agt_busy", "agt_unattached"].map((id) => ({ + id, + revision: outcome === "updated" ? target.revision : identity.revision, + })) + ); + expect(world.holds.isHeld(RUNNER)).toBe(false); + } + ); + it("releases when work did not settle", async () => { await online(); const { attemptId } = await staging(); diff --git a/apps/server/test/runner-update-hold-fixtures.ts b/apps/server/test/runner-update-hold-fixtures.ts index 4d4f5a483..a3141bd12 100644 --- a/apps/server/test/runner-update-hold-fixtures.ts +++ b/apps/server/test/runner-update-hold-fixtures.ts @@ -27,6 +27,8 @@ export async function scriptedHost( ); cleanup.push(() => host.kill()); writeFileSync(hostFile(dir, "pid"), String(host.pid)); + const sockets = new Set(); + const steers: string[] = []; const prompts: { text: string; images?: unknown }[] = []; let seq = 0; const event = (e: unknown): HostMessage => @@ -37,6 +39,8 @@ export async function scriptedHost( event: e, }) as HostMessage; const server = net.createServer((socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); const decode = ndjsonDecoder(); socket.on("data", (chunk) => { for (const message of decode(chunk)) { @@ -57,6 +61,15 @@ export async function scriptedHost( ); if (message.replayComplete) socket.write(encodeMessage({ type: "replay_complete" })); + } else if (message.type === "steer") { + steers.push(message.text); + socket.write( + encodeMessage({ + type: "steer_result", + id: message.id, + outcome: "steered", + } as HostMessage) + ); } else if (message.type === "prompt") { prompts.push({ text: message.text, images: message.images }); socket.write( @@ -75,6 +88,21 @@ export async function scriptedHost( await new Promise((resolve) => server.listen(hostFile(dir, "socket"), resolve) ); - cleanup.push(() => server.close()); - return { prompts, socket: hostFile(dir, "socket") }; + const close = () => + new Promise((resolve) => { + for (const socket of sockets) socket.destroy(); + server.close(() => resolve()); + }); + cleanup.push(() => close()); + return { + prompts, + steers, + socket: hostFile(dir, "socket"), + turn(state: "started" | "settled", source?: unknown) { + const message = encodeMessage( + event({ type: "turn", agentId, state, source }) + ); + for (const socket of sockets) socket.write(message); + }, + }; } diff --git a/apps/server/test/runner-update-hold-runtime.test.ts b/apps/server/test/runner-update-hold-runtime.test.ts index 8c788149c..c1c80fdcd 100644 --- a/apps/server/test/runner-update-hold-runtime.test.ts +++ b/apps/server/test/runner-update-hold-runtime.test.ts @@ -34,9 +34,9 @@ const logger = { const ATTEMPT = "11111111-1111-4111-8111-111111111111"; const OTHER_ATTEMPT = "22222222-2222-4222-8222-222222222222"; -let cleanup: Array<() => void> = []; -afterEach(() => { - for (const run of cleanup.splice(0).reverse()) run(); +let cleanup: Array<() => void | Promise> = []; +afterEach(async () => { + for (const run of cleanup.splice(0).reverse()) await run(); }); function memoryHolds() { @@ -130,6 +130,59 @@ async function fixture( const settle = () => new Promise((resolve) => setTimeout(resolve, 100)); describe("runner update hold in the runtime queue", () => { + it("lets only replies scoped to the open turn through a drain", async () => { + const { runtime, holds, held } = await fixture(); + const conversation = { streamId: "agt_held", threadId: "active" }; + const chat = { + source: "chat", + chatMessageId: "question", + conversation, + } as const; + held.turn("started", chat); + await vi.waitFor(() => expect(runtime.hasOpenTurn("agt_held")).toBe(true)); + await holds.begin("r1", ATTEMPT, { draining: true }); + const enqueue = ( + text: string, + source: Partial & { + awaited?: true; + correlatedReply?: true; + scheduleId?: string; + } = {} + ) => + runtime.prompt( + "agt_held", + text, + { ...chat, ...source }, + { delivery: "auto" } + ); + const regular = enqueue("ordinary"); + const unrelated = runtime.prompt( + "agt_held", + "unrelated reply", + { + ...chat, + correlatedReply: true, + conversation: { ...conversation, threadId: "different" }, + }, + { delivery: "auto" } + ); + const scheduled = enqueue("scheduled", { scheduleId: "schedule" }); + const reply = enqueue("matching answer", { correlatedReply: true }); + const awaited = enqueue("awaited review", { awaited: true }); + await Promise.all([reply.accepted, awaited.accepted]); + expect(held.steers).toEqual(["matching answer", "awaited review"]); + expect(held.prompts).toEqual([]); + held.turn("settled"); + await Promise.all([reply.settled, awaited.settled]); + await holds.release("r1", ATTEMPT, "cancelled"); + await Promise.all([regular.settled, unrelated.settled, scheduled.settled]); + const delivered = held.prompts.map(({ text }) => text).join("\n"); + expect(delivered).toContain("ordinary"); + expect(delivered).toContain("unrelated reply"); + expect(delivered).toContain("scheduled"); + expect(held.steers).toHaveLength(2); + }); + it("holds only the held runner's prompts and delivers them once, in order, on release", async () => { const { runtime, holds, held, other, local } = await fixture(); await holds.begin("r1", ATTEMPT); diff --git a/apps/web/src/components/app/runner-update.tsx b/apps/web/src/components/app/runner-update.tsx index 47ae232e8..a7f394ab3 100644 --- a/apps/web/src/components/app/runner-update.tsx +++ b/apps/web/src/components/app/runner-update.tsx @@ -6,7 +6,10 @@ import { useStartRunnerUpdate, type Runner } from "@/hooks/use-runners"; import { ApiError } from "@/lib/api"; import { RunnerCommand, useRunnerInstaller } from "./runner-onboarding"; -const PHASES: Record = { +const PHASES: Record< + Exclude, + string +> = { staging: "Downloading and verifying…", settling: "Waiting for work to settle…", switching: "Switching to the new build…", @@ -25,6 +28,7 @@ const ROLLED_BACK: Record = { }; const DEFERRED: Record = { + drain_timeout: "The wait for agents timed out.", operations_pending: "The runner was still busy, so it didn’t switch.", verify_failed: "The runner couldn’t download or verify the build.", boot_failed: "The runner couldn’t restart to switch builds.", @@ -77,6 +81,8 @@ function describeResult({ "The runner restored its previous build.", }; case "deferred": + if (reason === "drain_cancelled") + return { title: `${update} was cancelled` }; if (reason === "downgrade") return { title: `${update} was refused`, @@ -112,7 +118,10 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { runner.update ?? {}; // A refusal is stale once an update is running or has landed. const error = - attempt || (!available && result?.state === "updated") ? null : start.error; + (attempt && attempt.phase !== "draining") || + (!available && result?.state === "updated") + ? null + : start.error; if (!attempt && !available && !result && !previousBuildAgents && !error) return null; @@ -123,7 +132,14 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { title = attempt.version ? `Updating to ${attempt.version}` : "Runner update in progress"; - detail = PHASES[attempt.phase]; + const count = attempt.agents ?? 0; + const agents = `${count} ${count === 1 ? "agent" : "agents"}`; + detail = + attempt.phase === "draining" + ? `Waiting on ${agents}` + : attempt.phase === "resuming" + ? `Resuming ${agents}` + : PHASES[attempt.phase]; } else if (result && (failed || !available)) { ({ title, detail } = describeResult(result)); } else if (available) { @@ -159,7 +175,11 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { {detail}

    )} - {attempt?.held &&

    New work waits until the update finishes.

    } + {attempt?.held && + attempt.phase !== "draining" && + attempt.phase !== "resuming" && ( +

    New work waits until the update finishes.

    + )} {!attempt && previousBuildAgents ? (

    {previousBuildAgents}{" "} @@ -180,6 +200,19 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { )}

    + {attempt?.phase === "draining" && ( + + start.mutate({ action: "cancel", attemptId: attempt.id }) + } + > + Cancel + + )} {!attempt && available && ( + mutationFn: ( + action: RunnerUpdateAction | { action: "cancel"; attemptId: string } + ) => api<{ attemptId: string }>( `/api/v1/runners/${encodeURIComponent(runnerId)}/update`, - { method: "POST", body: JSON.stringify({ action }) } + { + method: "POST", + body: JSON.stringify( + typeof action === "string" ? { action } : action + ), + } ), // A refusal also means the runner's state moved on. onSettled: () => diff --git a/packages/shared/src/runner-update-types.ts b/packages/shared/src/runner-update-types.ts index 910cf5ab2..4afb23a16 100644 --- a/packages/shared/src/runner-update-types.ts +++ b/packages/shared/src/runner-update-types.ts @@ -3,6 +3,8 @@ export type RunnerUpdateAction = "update" | "retry"; export type RunnerUpdatePhaseView = | "staging" | "settling" + | "draining" + | "resuming" | "switching" | "confirming" | "cancelling"; @@ -22,6 +24,7 @@ export type RunnerUpdateView = { id: string; phase: RunnerUpdatePhaseView; version?: string; + agents?: number; /** New work for the runner waits: from staged until the attempt ends. */ held?: boolean; }; From ac4933455b94e5d05bd0eefb5411ed959c681415 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sun, 22 Nov 2026 00:17:46 -0700 Subject: [PATCH 310/642] Force a runner update and resume the agents it interrupted Update now interrupts the turns Dispatch saved, stops every host on the runner, and switches with nothing retained. Each session is resumed on whichever build ends up installed, and each agent whose turn was cut is told to continue exactly once before held work is released. The runner's resume receipt is the attempt file with per-agent progress. The local self-update receipt is unchanged. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/acp/host-client.ts | 11 + apps/server/src/agents/acp/prompt-source.ts | 5 + apps/server/src/agents/acp/runtime.ts | 154 +++- apps/server/src/agents/acp/stream-store.ts | 11 + apps/server/src/agents/manager.ts | 94 ++- .../src/agents/remote/force-sessions.ts | 264 +++++++ .../src/agents/remote/update-coordinator.ts | 443 +++++++++++- apps/server/src/agents/runtime.ts | 24 +- apps/server/src/routes/runners.ts | 17 +- .../src/update-recovery/resume-receipt.ts | 31 + .../test/db/runner-update-force.test.ts | 604 ++++++++++++++++ .../test/helpers/runner-force-fixture.ts | 666 ++++++++++++++++++ apps/server/test/runner-update-routes.test.ts | 32 + .../test/update-recovery-maintenance.test.ts | 18 + .../src/components/app/runner-update.test.tsx | 58 +- apps/web/src/components/app/runner-update.tsx | 123 +++- apps/web/src/hooks/use-runners.ts | 4 +- packages/shared/src/runner-update-types.ts | 2 + 18 files changed, 2477 insertions(+), 84 deletions(-) create mode 100644 apps/server/src/agents/remote/force-sessions.ts create mode 100644 apps/server/test/db/runner-update-force.test.ts create mode 100644 apps/server/test/helpers/runner-force-fixture.ts diff --git a/apps/server/src/agents/acp/host-client.ts b/apps/server/src/agents/acp/host-client.ts index 9848e0960..b7481167f 100644 --- a/apps/server/src/agents/acp/host-client.ts +++ b/apps/server/src/agents/acp/host-client.ts @@ -722,6 +722,17 @@ export class HostClient { return this.isReady() && this.lastWelcome === welcome; } + /** What the host did with a prompt ID. Undefined when it cannot say now. */ + async promptReceipt( + id: string + ): Promise { + const welcome = this.lastWelcome; + if (!welcome || !this.isReady()) return undefined; + if (welcome.promptReceiptSupported !== true || !welcome.journalId) + return "unsupported"; + return this.queryPromptReceipt(id, welcome.journalId); + } + private queryPromptReceipt( id: string, journalId: string diff --git a/apps/server/src/agents/acp/prompt-source.ts b/apps/server/src/agents/acp/prompt-source.ts index a3f6744ff..c2cf21ff4 100644 --- a/apps/server/src/agents/acp/prompt-source.ts +++ b/apps/server/src/agents/acp/prompt-source.ts @@ -140,4 +140,9 @@ export type PromptOptions = { signal?: AbortSignal; images?: PromptImage[]; delivery?: "auto" | "queue" | "interrupt"; + /** + * A stable host prompt ID for the one prompt that may pass a runner update + * hold, ahead of the work it holds. The host claims each ID only once. + */ + continuationId?: string; }; diff --git a/apps/server/src/agents/acp/runtime.ts b/apps/server/src/agents/acp/runtime.ts index 755c347d7..60c9e280f 100644 --- a/apps/server/src/agents/acp/runtime.ts +++ b/apps/server/src/agents/acp/runtime.ts @@ -103,6 +103,7 @@ type Waiting = { interruptHandled: boolean; interruptTargetSeq?: number; wakeTurnSeq?: number; + continuationId?: string; }; type Live = { @@ -307,7 +308,8 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { // Assigned below; launch() refers back to it to tear down a failed host. let runtime: AgentRuntime; const live = new Map(); - const recycleHolds = new Map(); + type RecycleHold = { entry: Live; restarting: boolean; forced?: true }; + const recycleHolds = new Map(); const inputEntry = (agentId: string) => live.get(agentId) ?? recycleHolds.get(agentId)?.entry; const preserving = (entry: Live) => { @@ -490,10 +492,19 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { live.get(agentId) === entry ) { const gated = held(entry); - if (gated && !entry.queue.waiting.some((w) => canWake(w, entry))) break; - const urgent = gated - ? [] - : entry.queue.waiting.filter((w) => w.delivery === "interrupt"); + const continuation = entry.turnOpen + ? undefined + : entry.queue.waiting.find((w) => w.continuationId); + if ( + gated && + !continuation && + !entry.queue.waiting.some((w) => canWake(w, entry)) + ) + break; + const urgent = + gated || continuation + ? [] + : entry.queue.waiting.filter((w) => w.delivery === "interrupt"); for (const w of urgent) { // A steering request may settle the arrival-time turn while the pump // is locked. Its interrupt must never migrate to a subsequent turn. @@ -582,11 +593,16 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { batch = entry.queue.waiting.splice(index, 1); } else { for (const w of entry.queue.waiting) finishDecision(w, "expired"); - batch = takeBatch(entry.queue.waiting); + batch = continuation + ? entry.queue.waiting.splice( + entry.queue.waiting.indexOf(continuation), + 1 + ) + : takeBatch(entry.queue.waiting); } for (const w of batch) w.taken = true; const { text, source } = combine(batch); - const id = crypto.randomUUID(); + const id = batch[0]!.continuationId ?? crypto.randomUUID(); let ended = false; let accepted = false; let submitted = false; @@ -693,7 +709,11 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { { mode: 0o600, flush: true } ); } - if (entry.runner && deps.holds?.current(entry.runner)?.draining) { + if ( + !continuation && + entry.runner && + deps.holds?.current(entry.runner)?.draining + ) { await requeue(); continue; } @@ -887,6 +907,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { journalId: cursor.journalId, settleWaiters: [], }; + // A replacement replays the old host's exit; that ends no held work. + const replaced = recycleHolds.get(agentId); + if (replaced?.forced && replaced.restarting) replaced.entry = entry; entry.client = new HostClient({ agentId, remote: Boolean(placement), @@ -1066,6 +1089,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { ...(opts?.signal ? { signal: opts.signal } : {}), ...(opts?.images?.length ? { images: opts.images } : {}), ...(source ? { source } : {}), + ...(opts?.continuationId && { continuationId: opts.continuationId }), alone: opts?.delivery === "interrupt" || opts?.alone === true || @@ -1089,7 +1113,9 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { (entry.turnSeq !== undefined && entry.interruptedTurnSeq === entry.turnSeq), }; - if (own.delivery === "interrupt") { + if (own.continuationId) { + entry.queue.waiting.unshift(own); + } else if (own.delivery === "interrupt") { const firstOrdinary = entry.queue.waiting.findIndex( (w) => w.delivery !== "interrupt" ); @@ -1223,6 +1249,19 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { return { prompts, scheduled }; }); + /** Work queued for a held host goes on to its replacement, or fails. */ + function releaseHold(agentId: string, hold: RecycleHold) { + if (recycleHolds.get(agentId) !== hold) return; + recycleHolds.delete(agentId); + const replacement = live.get(agentId); + if (replacement) void pump(agentId, replacement); + else + failWaiting( + hold.entry, + new Error("The agent host is unavailable before delivery.") + ); + } + const identify = (entry: Live): RunnerHostIdentity => { const welcome = entry.client.welcome; return { @@ -1299,17 +1338,91 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { release() { if (recycleHolds.get(agentId) !== hold) return; lease?.release(); - recycleHolds.delete(agentId); - const replacement = live.get(agentId); - if (replacement) void pump(agentId, replacement); - else - failWaiting( - entry, - new Error("The agent host is unavailable before delivery.") - ); + releaseHold(agentId, hold); }, }; }, + + holdRunnerHosts(runnerId) { + for (const [agentId, entry] of live) + if (entry.runner === runnerId && !recycleHolds.has(agentId)) + recycleHolds.set(agentId, { entry, restarting: false, forced: true }); + }, + + reattachRunnerHost(agentId) { + const hold = recycleHolds.get(agentId); + if (hold?.forced) hold.restarting = false; + }, + + releaseRunnerHost(agentId) { + const hold = recycleHolds.get(agentId); + if (hold?.forced) releaseHold(agentId, hold); + }, + + releaseRunnerHosts(runnerId) { + for (const [agentId, hold] of recycleHolds) + if (hold.forced && hold.entry.runner === runnerId) + releaseHold(agentId, hold); + }, + + async runnerTurn(agentId) { + const entry = live.get(agentId); + if (!entry) return null; + const turn = { open: entry.turnOpen, seq: entry.turnSeq }; + await entry.events; + return turn; + }, + + async interruptRunnerTurn(agentId, seq) { + const entry = live.get(agentId); + if (!entry) return true; + if (!entry.turnOpen || entry.turnSeq !== seq) { + await entry.events; + return true; + } + // Reconnecting: the host's welcome says whether this turn still runs. + if (!entry.client.isReady()) return false; + if (!entry.client.welcome?.interruptSupported) return true; + if (entry.interruptedTurnSeq !== seq) { + entry.interruptedTurnSeq = seq; + void entry.client + .interrupt(crypto.randomUUID(), seq) + .catch((err: unknown) => { + if (entry.interruptedTurnSeq === seq) + entry.interruptedTurnSeq = undefined; + logger.warn( + { err, agentId, seq }, + "could not interrupt a turn for the runner update" + ); + }); + } + return false; + }, + + async stopRunnerHost(runnerId, agentId) { + const placement = await placementOf(agentId); + if (placement?.runner !== runnerId) + throw new Error("No matching runner placement for this host."); + const entry = live.get(agentId); + let hold = recycleHolds.get(agentId); + if (entry && hold?.entry !== entry) { + hold = { entry, restarting: false, forced: true }; + recycleHolds.set(agentId, hold); + } + // Kept if the reply is lost: the host may still be exiting. + if (hold) hold.restarting = true; + await requestSession(placement, { kind: "stop", agentId, force: false }); + if (!entry) return; + if (live.get(agentId) === entry) live.delete(agentId); + entry.client.close(); + entry.turnOpen = false; + for (const resolve of entry.settleWaiters.splice(0)) resolve(); + await entry.events; + }, + + async promptReceipt(agentId, id) { + return live.get(agentId)?.client.promptReceipt(id); + }, tracksProcesses: () => true, async getBackgroundWork(agentId) { const entry = live.get(agentId); @@ -1374,6 +1487,12 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { } = input; if (requireResume) { const previous = live.get(input.agentId); + const forced = recycleHolds.get(input.agentId); + // The manager found no host, so a channel that isn't ready is stale. + if (previous && forced?.forced && !previous.client.isReady()) { + forced.entry = previous; + forced.restarting = true; + } if (previous && preserving(previous)) { live.delete(input.agentId); previous.client.close(); @@ -1411,6 +1530,7 @@ export function createAcpRuntime(deps: AcpRuntimeDeps): AgentRuntime { "The replacement host could not resume the existing session." ); } + if (requireResume && recycle?.forced) recycle.restarting = false; return { sessionId: welcome.sessionId, resumed: welcome.resumed }; } catch (err) { if (placement) throw err; // A disconnected remote host may still be running. diff --git a/apps/server/src/agents/acp/stream-store.ts b/apps/server/src/agents/acp/stream-store.ts index 23e901d0c..bdcb3a81b 100644 --- a/apps/server/src/agents/acp/stream-store.ts +++ b/apps/server/src/agents/acp/stream-store.ts @@ -329,6 +329,17 @@ export class StreamStore { : null; } + /** These turn rows of this agent's, by row id. */ + async turns(agentId: string, ids: number[]): Promise { + const result = await this.db.query( + `SELECT * FROM agent_stream_events + WHERE agent_id = $1 AND kind = 'turn' AND id = ANY($2::bigint[]) + ORDER BY seq`, + [agentId, ids] + ); + return result.rows.map(toRow); + } + /** The agent's newest turn row, open or settled. */ async lastTurn(agentId: string): Promise { const result = await this.db.query( diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index c56cfb455..e5bf6e908 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -129,7 +129,9 @@ import { type ConfirmedRunnerUpdate, type RunnerHostRecycleProgress, } from "./remote/host-recycler.js"; +import { RunnerForceSessions } from "./remote/force-sessions.js"; import type { HeldLaunch, RunnerUpdateHolds } from "./remote/update-hold.js"; +import type { RunnerResumeAgent } from "../update-recovery/resume-receipt.js"; import { buildLaunchEnv } from "./acp/launch-env.js"; import { dispatchMcpUrl } from "./acp/mcp-url.js"; import { @@ -377,7 +379,12 @@ function withTimeout( export const UPDATE_RESUME_MESSAGE = "Dispatch stopped this idle agent for an update. Start it to continue if automatic resume did not finish."; +const RUNNER_RESUME_FAILED = + "Dispatch couldn't resume this agent after the runner update. Start it to continue."; + export class AgentManager { + /** A forced runner update's steps on this manager's sessions. */ + readonly runnerForce: RunnerForceSessions; private readonly runnerDrainReceipts = new Map>(); private readonly drainedHostHolds = new Map(); private readonly hostRecycler: RunnerHostRecycler; @@ -556,6 +563,19 @@ export class AgentManager { this.recycleRunnerHost(update, host, active), logger, }); + this.runnerForce = new RunnerForceSessions({ + runtime: this.runtime, + recorder: this.streamRecorder, + turns: this.streamStore, + getAgent: (id) => this.getAgent(id), + leaving: (id) => this.stoppingOrArchiving.has(id), + rowClaims: (ids) => this.updateResumeSnapshot(ids), + resolveSource: async (id, source) => + (await this.launchContextRecorder?.resolvePromptSource?.(id, source)) ?? + source, + streamChanged: (id) => this.notifyStreamWrite(id, true), + logger, + }); this.runtime.onEvent((agentId, event, seq, receivedRemotely) => this.handleRuntimeEvent(agentId, event, seq, receivedRemotely) ); @@ -750,7 +770,12 @@ export class AgentManager { if (event.type === "config") { await this.applyEngineConfig(agentId, event.options); } - if (event.type === "exit" && !event.expected) { + // A host an update takes down still has its session to resume. + if ( + event.type === "exit" && + !event.expected && + !this.hasRunnerDrainReceipt(agentId) + ) { const how = event.code === null ? event.signal @@ -3311,6 +3336,7 @@ export class AgentManager { if (next.has(id)) continue; this.drainedHostHolds.get(id)?.release(); this.drainedHostHolds.delete(id); + this.runtime.releaseRunnerHost?.(id); } if (ids.length) this.runnerDrainReceipts.set(runnerId, next); else this.runnerDrainReceipts.delete(runnerId); @@ -3397,45 +3423,87 @@ export class AgentManager { }); } - /** The unchanged running row remains the claim until recovery is recorded. */ + /** + * The unchanged running row remains the claim until recovery is recorded. + * Launching moves that row, so an entry saved as launching also claims the + * host that launch left alive: a restart in between neither loses the + * resume nor runs it twice. False when there is nothing to resume. + */ async resumeRunnerDrainHost( runnerId: string, attemptId: string, - entry: { id: string; updatedAt: string } - ): Promise { + entry: RunnerResumeAgent, + /** Records that the launch is about to happen. */ + beforeLaunch?: () => Promise + ): Promise { const id = entry.id; const release = () => { this.drainedHostHolds.get(id)?.release(); this.drainedHostHolds.delete(id); }; - // Stop can be inside the lifecycle lock waiting for the runner hold. - if (this.stoppingOrArchiving.has(id)) return release(); - await this.serializeLifecycle(id, async () => { - if (!(await this.eligibleUpdateResumes([entry])).has(id)) - return release(); + const dropped = () => { + release(); + return false; + }; + // Stop or restart can be inside the lifecycle lock waiting for the hold. + if ( + this.stoppingOrArchiving.has(id) || + (await this.getAgent(id))?.status !== "running" + ) + return dropped(); + return this.serializeLifecycle(id, async () => { + const unchanged = ( + await this.eligibleUpdateResumes([{ id, updatedAt: entry.updatedAt }]) + ).has(id); + if (!unchanged && !entry.launching) return dropped(); const agent = await this.getAgent(id); if ( - !agent?.cliSessionId || + agent?.status !== "running" || + !agent.cliSessionId || remotePlacement(agent.cwd)?.runner !== runnerId ) - return release(); + return dropped(); if (await this.runtime.runnerHostAlive?.(runnerId, id)) { if (this.drainedHostHolds.has(id)) throw new Error("The quiesced runner host is still exiting."); release(); + this.runtime.reattachRunnerHost?.(id); if (!(await this.runtime.attach(id))) throw new Error("The runner host has not reattached."); - return; + return true; } - if (this.stoppingOrArchiving.has(id)) return release(); + if (!unchanged || this.stoppingOrArchiving.has(id)) return dropped(); + await beforeLaunch?.(); await this.startAgentClaimed(id, attemptId, { drain: true, mayStart: () => !this.stoppingOrArchiving.has(id), }); release(); + return true; }); } + /** + * A resume that kept failing ends as a failed start, so it does not keep + * the runner's other work held. False while a host may still be alive. + */ + async abandonRunnerResume(runnerId: string, id: string): Promise { + if ((await this.runtime.runnerHostAlive?.(runnerId, id)) !== false) + return false; + if ( + !this.stoppingOrArchiving.has(id) && + (await this.setAgentStatus( + id, + "error", + RUNNER_RESUME_FAILED, + undefined, + "running" + )) + ) + await this.emitAttention(id, "blocked", RUNNER_RESUME_FAILED); + return true; + } + private async recycleRunnerHost( update: ConfirmedRunnerUpdate, host: RunnerHostIdentity, diff --git a/apps/server/src/agents/remote/force-sessions.ts b/apps/server/src/agents/remote/force-sessions.ts new file mode 100644 index 000000000..44f2ef828 --- /dev/null +++ b/apps/server/src/agents/remote/force-sessions.ts @@ -0,0 +1,264 @@ +import type { FastifyBaseLogger } from "fastify"; + +import type { RunnerResumeAgent } from "../../update-recovery/resume-receipt.js"; +import type { PromptSource } from "../acp/prompt-source.js"; +import type { StreamRecorder } from "../acp/stream-recorder.js"; +import type { StreamStore, TurnPayload } from "../acp/stream-store.js"; +import type { AgentRuntime, RunnerHostIdentity } from "../runtime.js"; +import type { AgentRecord } from "../types.js"; +import { remotePlacement } from "./protocol.js"; + +/* + * Dispatch's policy for a forced runner update: which turns it cuts, and + * what those agents are told afterwards. The coordinator decides when each + * step runs and saves what it returns before the next one. The runner only + * sees ordinary interrupt, stop, launch and prompt requests. + */ + +export const UPDATE_CONTINUATION_MESSAGE = + "Dispatch interrupted this turn to update the runner. Continue from where you left off."; + +/** Stable across retries and restarts; the host claims each ID only once. */ +export const continuationId = (attemptId: string, agentId: string) => + `runner-update:${attemptId}:${agentId}`; + +/** How long one pass waits on a continuation before looking again. */ +const DELIVERY_WAIT_MS = 1_000; + +/** A turn that ended by itself, however late the interrupt, was not cut. */ +function wasCut({ state, error, stopReason }: TurnPayload): boolean { + return state === "settled" && (Boolean(error) || stopReason === "cancelled"); +} + +export class RunnerForceSessions { + private readonly deliveries = new Map>(); + + constructor( + private readonly deps: { + runtime: AgentRuntime; + recorder: Pick; + turns: Pick; + getAgent(id: string): Promise; + /** A user's stop or archive is under way. */ + leaving(id: string): boolean; + rowClaims(ids: string[]): Promise<{ id: string; updatedAt: string }[]>; + resolveSource(id: string, source: PromptSource): Promise; + streamChanged(id: string): void; + logger: Pick; + } + ) {} + + hold(runnerId: string): void { + this.deps.runtime.holdRunnerHosts?.(runnerId); + } + + release(runnerId: string): void { + this.deps.runtime.releaseRunnerHosts?.(runnerId); + } + + /** + * Every host's claim and open turn, before anything is destroyed. Null + * while one cannot be told yet: a launch finishing, an attach replaying, + * or a submitted turn that has not started. `final` stops waiting for the + * last two and takes what Dispatch has recorded. + */ + async snapshot( + runnerId: string, + hosts: { id: string; host?: RunnerHostIdentity }[], + { epoch, final }: { epoch: number; final: boolean } + ): Promise { + const entries: RunnerResumeAgent[] = []; + for (const { id, host } of hosts) { + const agent = await this.agentOn(runnerId, id); + if (agent?.status === "creating") return null; + if (!this.resumable(agent)) continue; + const attached = host?.attachedEpoch === epoch; + if (!attached && !final) return null; + const live = attached ? await this.deps.runtime.runnerTurn?.(id) : null; + const row = await this.deps.turns.openTurn(id); + if (live?.open && (live.seq === undefined || !row) && !final) return null; + const [claim] = await this.deps.rowClaims([id]); + if (!claim) continue; + const open = row && (attached ? live?.open : true); + entries.push({ + ...claim, + ...(open && { + turns: [ + { + id: row.id, + ...(live?.seq !== undefined && { seq: live.seq }), + }, + ], + }), + }); + } + return entries; + } + + /** True once none of the snapshotted turns still runs. */ + async interrupt(entry: RunnerResumeAgent): Promise { + let settled = true; + for (const { seq } of entry.turns ?? []) { + if (seq === undefined) continue; + // Whatever error the cut settles with is the stop, not a failure. + this.deps.recorder.beginStop(entry.id); + if ( + (await this.deps.runtime.interruptRunnerTurn?.(entry.id, seq)) === false + ) + settled = false; + } + return settled; + } + + /** + * What to save before stopping this host. A turn that started since the + * snapshot is cut by the stop. "wait" leaves a launch to finish; null is + * a host to stop and not resume. + */ + async prepareStop( + runnerId: string, + id: string, + entry: RunnerResumeAgent | undefined + ): Promise { + const agent = await this.agentOn(runnerId, id); + if (agent?.status === "creating") return "wait"; + if (!this.resumable(agent)) return null; + const live = await this.deps.runtime.runnerTurn?.(id); + const row = await this.deps.turns.openTurn(id); + const [claim] = await this.deps.rowClaims([id]); + if (!claim) return null; + const turns = [...(entry?.turns ?? [])]; + if ( + row && + (!live || live.open) && + !turns.some((turn) => turn.id === row.id) + ) + turns.push({ id: row.id }); + return { ...claim, ...(turns.length && { turns: turns.slice(-16) }) }; + } + + /** Stops the host and returns its row's claim as the stop left it. */ + async stop( + runnerId: string, + id: string + ): Promise<{ id: string; updatedAt: string } | undefined> { + const { runtime, recorder } = this.deps; + recorder.beginStop(id); + await runtime.stopRunnerHost?.(runnerId, id); + await recorder.settleStopped(id); + this.deps.streamChanged(id); + if (this.deps.leaving(id)) return undefined; + return (await this.deps.rowClaims([id]))[0]; + } + + /** + * Tell one resumed agent that its turn was cut, exactly once. "done" when + * it was told, when nothing was cut, or when it is no longer wanted. + * Never waits long: "waiting" is asked again on a later pass. + */ + async continue( + runnerId: string, + attemptId: string, + entry: RunnerResumeAgent, + options: { + /** An interrupt may still be settling. */ + settling: boolean; + /** Saved before the first hand-off to the host. */ + markSent(): Promise; + } + ): Promise<"done" | "waiting"> { + const { runtime, turns } = this.deps; + const { id } = entry; + const wanted = async () => this.resumable(await this.agentOn(runnerId, id)); + if (!(await wanted())) return "done"; + const key = continuationId(attemptId, id); + const delivering = this.deliveries.get(key); + if (delivering) return this.delivered(delivering); + if (!(await runtime.attach(id))) + return (await runtime.runnerHostAlive?.(runnerId, id)) === false + ? "done" + : "waiting"; + await runtime.runnerTurn?.(id); + const rows = await turns.turns( + id, + (entry.turns ?? []).map((turn) => turn.id) + ); + const payloads = rows.map((row) => row.payload as unknown as TurnPayload); + if (!entry.continuationSent && !payloads.some(wasCut)) + return options.settling && + payloads.some(({ state }) => state === "started") + ? "waiting" + : "done"; + + const receipt = await runtime.promptReceipt?.(id, key); + if (receipt === "accepted" || receipt === "claimed") return "done"; + if (receipt === undefined) return "waiting"; + // A host with no receipts gets it at most once. + if (receipt === "unsupported" && entry.continuationSent) return "done"; + + // Answered where the turn that was cut was answering. + const conversation = payloads.find(wasCut)?.prompt?.conversation; + const source = await this.deps.resolveSource(id, { + source: "system", + text: UPDATE_CONTINUATION_MESSAGE, + ...(conversation && { conversation }), + }); + const { accepted, settled } = runtime.prompt( + id, + UPDATE_CONTINUATION_MESSAGE, + source, + { + continuationId: key, + alone: true, + delivery: "queue", + beforeSubmit: async () => { + if (!(await wanted())) return false; + await options.markSent(); + return true; + }, + } + ); + settled.catch(() => {}); + const delivery = accepted + .then( + () => true, + (err: unknown) => { + this.deps.logger.warn( + { err, agentId: id }, + "runner update continuation was not accepted" + ); + return false; + } + ) + .finally(() => this.deliveries.delete(key)); + this.deliveries.set(key, delivery); + return this.delivered(delivery); + } + + private async delivered(delivery: Promise) { + let timer: ReturnType | undefined; + const waited = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), DELIVERY_WAIT_MS); + }); + try { + return (await Promise.race([delivery, waited])) ? "done" : "waiting"; + } finally { + clearTimeout(timer); + } + } + + private async agentOn(runnerId: string, id: string) { + const agent = await this.deps.getAgent(id); + return agent && remotePlacement(agent.cwd)?.runner === runnerId + ? agent + : null; + } + + private resumable(agent: AgentRecord | null): boolean { + return ( + agent?.status === "running" && + Boolean(agent.cliSessionId) && + !this.deps.leaving(agent.id) + ); + } +} diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index 3fab21e8d..96509157c 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -4,7 +4,10 @@ import type { FastifyBaseLogger } from "fastify"; import { z } from "zod"; import type { RunnerArtifactSource } from "../../server/runner-artifacts.js"; -import { resumeAgentSchema } from "../../update-recovery/resume-receipt.js"; +import { + runnerResumeAgentSchema, + type RunnerResumeAgent, +} from "../../update-recovery/resume-receipt.js"; import type { AgentManager } from "../manager.js"; import { endsUpdateAttempt, @@ -29,9 +32,15 @@ import { compareRunnerVersions } from "./update-verify.js"; * staging ─ready→ settling ─fence_ready→ switching ─trial→ confirming * └───────────────┴──────────────┴─────────────────┴──→ cancelling * - * Incompatible hosts drain before settling with an empty retained set. - * Once the runner reports an outcome, Dispatch resumes the stopped hosts - * before releasing held work. Work goes on during staging, and is held + * Incompatible hosts drain before settling with an empty retained set. An + * operator's force replaces that wait, or is asked for at the start: + * + * staging | draining ─force→ interrupting ─no hosts→ settling + * + * Interrupting saves each host's receipt entry, interrupts the turns it + * saved, and stops every host. Once the runner reports an outcome, Dispatch + * resumes the stopped hosts and tells the agents it interrupted to continue, + * both before releasing held work. Work goes on during staging, and is held * before the first fence. The runner owns the swap and its rollback. */ @@ -49,6 +58,14 @@ export const UPDATE_TIMING = { cancelMs: 15_000, rollbackMs: 60_000, confirmRetryMs: 5_000, + /** A forced update has this long to empty the runner. */ + interruptingMs: 3 * 60_000, + /** For every host to attach and report its turn. */ + snapshotMs: 15_000, + /** For interrupted turns to settle before their hosts are stopped anyway. */ + interruptMs: 30_000, + /** A session that still won't resume after this is a failed start. */ + resumeRetryMs: 5 * 60_000, tickMs: 1_000, } as const; @@ -76,10 +93,13 @@ const attemptSchema = z.object({ /** Absent only for a runner's attempt that Dispatch has no record of. */ target: targetSchema.optional(), retry: z.boolean(), + /** An operator asked to interrupt rather than wait. Never set otherwise. */ + force: z.literal(true).optional(), phase: z.enum([ "staging", "settling", "draining", + "interrupting", "resuming", "switching", "confirming", @@ -101,7 +121,14 @@ const attemptSchema = z.object({ .object({ retainedIds: z.array(z.string()).max(1024), waiting: z.number().int().nonnegative().optional(), - agents: z.array(resumeAgentSchema).max(10_000), + agents: z.array(runnerResumeAgentSchema).max(10_000), + force: z + .object({ + snapshotBy: z.number(), + /** Set with the snapshot, so before any turn is interrupted. */ + interruptBy: z.number().optional(), + }) + .optional(), result: outcomeSchema.optional(), }) .optional(), @@ -212,8 +239,20 @@ type CoordinatorAgents = Pick< | "runnerDrainHosts" | "stopRunnerHostForDrain" | "resumeRunnerDrainHost" + | "abandonRunnerResume" | "setRunnerDrainReceipt" ->; +> & { + runnerForce: Pick< + AgentManager["runnerForce"], + | "hold" + | "release" + | "snapshot" + | "interrupt" + | "prepareStop" + | "stop" + | "continue" + >; +}; export class RunnerUpdateCoordinator { private readonly records = new Map(); @@ -226,7 +265,8 @@ export class RunnerUpdateCoordinator { private readonly trials = new Map(); private readonly confirms = new Map(); private readonly waiting = new Map(); - private readonly drainCancellations = new Set(); + /** Cancelled or forced: their drain stops no more hosts. */ + private readonly endingDrains = new Set(); private readonly attaching = new Set(); private readonly ticking = new Set(); /** Between stopping a recycling pass and the attempt that replaces it. */ @@ -321,17 +361,61 @@ export class RunnerUpdateCoordinator { /** Start one attempt. Simultaneous requests for a runner share it. */ request( runnerId: string, - action: RunnerUpdateAction + action: RunnerUpdateAction | "force" ): Promise<{ attemptId: string }> { - const running = this.requests.get(runnerId); + // A force never shares a plain update's attempt, nor the other way. + const key = action === "force" ? `${runnerId}/force` : runnerId; + const running = this.requests.get(key); if (running) return running; const request = this.open(runnerId, action).finally(() => - this.requests.delete(runnerId) + this.requests.delete(key) ); - this.requests.set(runnerId, request); + this.requests.set(key, request); return request; } + /** + * Update now: start a forced update, or stop waiting in a drain. Only an + * operator's request gets here. + */ + async forceUpdate(runnerId: string, attemptId?: string) { + if (!this.options.service.isRegistered(runnerId)) + throw new RunnerUpdateIneligible("not_found"); + if (!this.started) throw new RunnerUpdateIneligible("not_ready"); + const asked = this.active(runnerId); + if (!asked && !attemptId) return this.request(runnerId, "force"); + const valid = (attempt: Attempt | undefined): attempt is Attempt => + attempt !== undefined && + attempt.id === (attemptId ?? asked?.id) && + (attempt.force === true || attempt.phase === "draining"); + const refuse = () => + attemptId + ? new RunnerUpdateIneligible("stale_drain") + : new RunnerUpdateIneligible("update_in_progress", asked?.id); + if (!valid(asked)) throw refuse(); + this.endingDrains.add(asked.id); + try { + return await this.enqueue(runnerId, async () => { + const attempt = this.active(runnerId); + if (!valid(attempt)) throw refuse(); + if (!attempt.force) { + await this.save({ + ...this.records.get(runnerId), + runnerId, + attempt: this.interrupting(attempt), + }); + this.options.logger.info( + { runnerId, attemptId: attempt.id }, + "runner update forced" + ); + } + return { attemptId: attempt.id }; + }); + } finally { + this.endingDrains.delete(asked.id); + } + } + async cancelDrain(runnerId: string, attemptId: string) { if (!this.options.service.isRegistered(runnerId)) throw new RunnerUpdateIneligible("not_found"); @@ -340,7 +424,7 @@ export class RunnerUpdateCoordinator { attempt?.id === attemptId && attempt.phase === "draining"; if (!valid(this.active(runnerId))) throw new RunnerUpdateIneligible("stale_drain"); - this.drainCancellations.add(attemptId); + this.endingDrains.add(attemptId); try { return await this.enqueue(runnerId, async () => { const attempt = this.active(runnerId); @@ -353,7 +437,7 @@ export class RunnerUpdateCoordinator { return { attemptId }; }); } finally { - this.drainCancellations.delete(attemptId); + this.endingDrains.delete(attemptId); } } @@ -373,6 +457,9 @@ export class RunnerUpdateCoordinator { attempt.drain!.waiting ?? attempt.drain!.retainedIds.length, }), + ...(attempt.phase === "interrupting" && { + agents: this.waiting.get(runnerId) ?? attempt.drain!.waiting, + }), ...(attempt.phase === "resuming" && { agents: attempt.drain!.agents.length, }), @@ -434,7 +521,7 @@ export class RunnerUpdateCoordinator { private async open( runnerId: string, - action: RunnerUpdateAction + action: RunnerUpdateAction | "force" ): Promise<{ attemptId: string }> { const { service, agents, artifacts, build, logger } = this.options; if (!service.isRegistered(runnerId)) @@ -470,6 +557,7 @@ export class RunnerUpdateCoordinator { id: randomUUID(), target, retry: action === "retry", + ...(action === "force" && { force: true }), phase: "staging", deadline: this.now() + UPDATE_TIMING.stagingMs, }; @@ -489,7 +577,7 @@ export class RunnerUpdateCoordinator { } } - private eligible(runnerId: string, action: RunnerUpdateAction) { + private eligible(runnerId: string, action: RunnerUpdateAction | "force") { const { service, artifacts, build } = this.options; const refuse = (code: IneligibleCode, attemptId?: string) => new RunnerUpdateIneligible(code, attemptId); @@ -511,7 +599,7 @@ export class RunnerUpdateCoordinator { throw refuse( advert.revision === build.revision ? "up_to_date" : "same_version" ); - if (action === "update" && this.suppressed(runnerId)) + if (action !== "retry" && this.suppressed(runnerId)) throw refuse("needs_retry"); return live; } @@ -533,8 +621,15 @@ export class RunnerUpdateCoordinator { const pending = advert?.pendingAttemptId; let attempt = this.active(runnerId); - if (attempt?.phase === "resuming") return this.advance(runnerId); - if (attempt?.phase === "draining" && !pending) + if (attempt?.phase === "resuming") { + if (pending && pending !== attempt.id) + this.sendCancel(runnerId, { ...attempt, id: pending }, epoch); + return this.advance(runnerId); + } + if ( + (attempt?.phase === "draining" || attempt?.phase === "interrupting") && + !pending + ) return this.advance(runnerId); if (attempt && !advert) { await this.finish(runnerId, attempt, { @@ -548,7 +643,10 @@ export class RunnerUpdateCoordinator { state: "deferred", reason: "interrupted", }); - attempt = undefined; + attempt = this.active(runnerId); + // Adopting would replace the receipt. The other fence only needs to go. + if (attempt?.phase === "resuming") + return this.sendCancel(runnerId, { ...attempt, id: pending }, epoch); } if (!attempt) { if (pending) return this.adopt(runnerId, pending, epoch); @@ -572,6 +670,7 @@ export class RunnerUpdateCoordinator { } switch (attempt.phase) { case "draining": + case "interrupting": // An earlier fence might still be unwinding on this connection. await this.cancel(runnerId, attempt, "interrupted"); return; @@ -698,7 +797,7 @@ export class RunnerUpdateCoordinator { return this.advance(runnerId); } if ( - attempt.phase === "draining" && + (attempt.phase === "draining" || attempt.phase === "interrupting") && status.phase === "deferred" && status.reason === "incompatible_handoff" ) @@ -726,7 +825,13 @@ export class RunnerUpdateCoordinator { status: RunnerUpdateEvent["status"] ): Promise { const { phase, target } = attempt; - if (phase === "cancelling" || phase === "draining" || !target) return; + if ( + phase === "cancelling" || + phase === "draining" || + phase === "interrupting" || + !target + ) + return; const { service } = this.options; if (status.phase === "activating") { @@ -760,6 +865,8 @@ export class RunnerUpdateCoordinator { switch (status.reason) { case "ready": { if (attempt.retained) return; + if (phase === "staging" && attempt.force) + return this.startInterrupting(runnerId, attempt); if (phase === "staging") { const settling: Attempt = { ...attempt, @@ -829,6 +936,19 @@ export class RunnerUpdateCoordinator { if (live) await this.drain(runnerId, attempt, live.advert, live.epoch); return; } + if (phase === "interrupting") { + if ( + now >= attempt.deadline || + this.options.holds.current(runnerId)?.attemptId !== attempt.id + ) + return this.finish(runnerId, attempt, { + state: "deferred", + reason: "force_timeout", + }); + if (live) + await this.interrupt(runnerId, attempt, live.advert, live.epoch); + return; + } if (now >= attempt.deadline) { if (phase === "cancelling" || !live) return this.finish(runnerId, attempt, { @@ -885,7 +1005,7 @@ export class RunnerUpdateCoordinator { const drain = attempt.drain!; const mayStop = () => !this.closed && - !this.drainCancellations.has(attempt.id) && + !this.endingDrains.has(attempt.id) && this.now() < attempt.deadline && this.options.service.connectionEpoch(runnerId) === epoch && this.options.holds.current(runnerId)?.attemptId === attempt.id; @@ -943,9 +1063,160 @@ export class RunnerUpdateCoordinator { } } + /** Staged under force: work waits, then nothing waits on the agents. */ + private async startInterrupting(runnerId: string, attempt: Attempt) { + try { + this.releaseOther(runnerId, attempt.id); + await this.options.holds.begin(runnerId, attempt.id, { + boundMs: UPDATE_TIMING.interruptingMs + UPDATE_HOLD_BOUND_MS, + draining: true, + }); + } catch (error) { + this.options.logger.error( + { err: error, runnerId }, + "could not hold the runner for its forced update" + ); + return this.cancel(runnerId, attempt, "state_unsaved"); + } + if (!(await this.step(runnerId, attempt, this.interrupting(attempt)))) + return; + return this.advance(runnerId); + } + + private interrupting(attempt: Attempt): Attempt { + const now = this.now(); + return { + ...attempt, + force: true, + phase: "interrupting", + retained: undefined, + deadline: now + UPDATE_TIMING.interruptingMs, + drain: { + ...(attempt.drain ?? { retainedIds: [], agents: [] }), + force: { snapshotBy: now + UPDATE_TIMING.snapshotMs }, + }, + }; + } + + /** + * One pass of a forced update, each step saved before the next acts: + * receipt, interrupt and settle, receipt again, stop. A pass that fails + * or loses its connection repeats from what was saved. + */ + private async interrupt( + runnerId: string, + attempt: Attempt, + advert: SelfUpdateAdvert, + epoch: number + ) { + const { agents, service, holds, logger } = this.options; + const sessions = agents.runnerForce; + const current = () => + !this.closed && + service.connectionEpoch(runnerId) === epoch && + holds.current(runnerId)?.attemptId === attempt.id; + const saveDrain = async ( + change: Partial> + ) => { + attempt = { ...attempt, drain: { ...attempt.drain!, ...change } }; + await this.save({ ...this.records.get(runnerId), runnerId, attempt }); + }; + + sessions.hold(runnerId); + const hosts = await agents.runnerDrainHosts( + runnerId, + attempt.drain!.retainedIds + ); + if (!current()) return; + const waiting = new Set(hosts.map(({ id }) => id)).size; + this.waiting.set(runnerId, waiting); + if (waiting !== attempt.drain!.waiting) await saveDrain({ waiting }); + for (const { id, host } of hosts) + if (host?.attachedEpoch !== epoch) this.attach(runnerId, id); + + const now = this.now(); + let force = attempt.drain!.force!; + if (force.interruptBy === undefined) { + const found = await sessions.snapshot(runnerId, hosts, { + epoch, + final: now >= force.snapshotBy, + }); + if (!found || !current()) return; + const ids = new Set(found.map(({ id }) => id)); + force = { ...force, interruptBy: now + UPDATE_TIMING.interruptMs }; + await saveDrain({ + force, + agents: [ + ...attempt.drain!.agents.filter(({ id }) => !ids.has(id)), + ...found, + ], + }); + } + if (!current()) return; + + if (!hosts.length) { + const next: Attempt = { + ...attempt, + phase: "settling", + deadline: this.now() + UPDATE_TIMING.settlingMs, + }; + if (await this.step(runnerId, attempt, next)) + this.sendOffer(runnerId, next, advert, epoch); + return; + } + + const saved = new Map(attempt.drain!.agents.map((e) => [e.id, e])); + if (now < force.interruptBy!) { + const settled = await Promise.all( + hosts.map(({ id, host }) => { + const entry = saved.get(id); + if (!entry?.turns?.some((turn) => turn.seq !== undefined)) + return true; + // A restart or reconnect replays first: only then is the turn known. + return host?.attachedEpoch === epoch && sessions.interrupt(entry); + }) + ); + if (settled.includes(false) || !current()) return; + } + + const stops: string[] = []; + for (const { id } of hosts) { + const entry = await sessions.prepareStop(runnerId, id, saved.get(id)); + if (entry === "wait") continue; + if (entry) saved.set(id, entry); + else saved.delete(id); + stops.push(id); + } + if (!stops.length || !current()) return; + // A failed write must never allow a host to be stopped. + await saveDrain({ agents: [...saved.values()] }); + if (!current()) return; + await Promise.all( + stops.map(async (id) => { + try { + const claim = await sessions.stop(runnerId, id); + const entry = saved.get(id); + if (claim && entry) + saved.set(id, { ...entry, updatedAt: claim.updatedAt }); + } catch (error) { + logger.warn( + { err: error, runnerId, agentId: id }, + "could not stop a host for the runner update" + ); + } + }) + ); + await saveDrain({ agents: [...saved.values()] }); + } + + /** + * One pass of recovery: one session resumed, and every continuation still + * owed offered. Each agent's progress is saved, so a restart takes up + * where this stopped. The hold opens once no entry is left. + */ private async resumeDrain(runnerId: string, attempt: Attempt) { const drain = attempt.drain!; - const { agents, service } = this.options; + const { agents, service, logger } = this.options; if (drain.agents.length && service.isRegistered(runnerId)) { // A reconnect with an outstanding trial is not an installed build yet. const live = service.selfUpdate(runnerId); @@ -954,20 +1225,120 @@ export class RunnerUpdateCoordinator { live?.advert.pendingAttemptId ) return; - const [entry, ...remaining] = drain.agents; - await agents.resumeRunnerDrainHost(runnerId, attempt.id, entry!); - const next = { ...attempt, drain: { ...drain, agents: remaining } }; - await this.save({ - ...this.records.get(runnerId), - runnerId, - attempt: next, - }); - if (remaining.length) return; - attempt = next; + const next = drain.agents.find((entry) => !entry.resumed); + if (next) await this.resumeAgent(runnerId, attempt.id, next); + const interruptBy = drain.force?.interruptBy; + await Promise.all( + this.receipt(runnerId, attempt.id) + .filter((entry) => entry.resumed) + .map(async (entry) => { + try { + const told = await agents.runnerForce.continue( + runnerId, + attempt.id, + entry, + { + settling: + interruptBy !== undefined && this.now() < interruptBy, + markSent: () => this.markSent(runnerId, attempt.id, entry.id), + } + ); + if (told === "done") + await this.editReceipt(runnerId, attempt.id, (entries) => + entries.filter(({ id }) => id !== entry.id) + ); + } catch (error) { + logger.warn( + { err: error, runnerId, agentId: entry.id }, + "could not continue an interrupted agent" + ); + } + }) + ); + if (this.receipt(runnerId, attempt.id).length) return; + attempt = this.active(runnerId)!; } return this.finish(runnerId, attempt, drain.result!); } + private async resumeAgent( + runnerId: string, + attemptId: string, + entry: RunnerResumeAgent + ) { + const { agents, logger } = this.options; + const { id } = entry; + const edit = (change: (entry: RunnerResumeAgent) => RunnerResumeAgent[]) => + this.editReceipt(runnerId, attemptId, (entries) => + entries.flatMap((saved) => (saved.id === id ? change(saved) : [saved])) + ); + try { + const resumed = await agents.resumeRunnerDrainHost( + runnerId, + attemptId, + entry, + () => edit((saved) => [{ ...saved, launching: true }]) + ); + await edit(({ failedAt: _, ...saved }) => + resumed && saved.turns?.length ? [{ ...saved, resumed: true }] : [] + ); + } catch (error) { + logger.warn( + { err: error, runnerId, agentId: id }, + "could not resume an agent after the runner update" + ); + const failedAt = entry.failedAt ?? this.now(); + if ( + this.now() - failedAt >= UPDATE_TIMING.resumeRetryMs && + (await agents.abandonRunnerResume(runnerId, id).catch(() => false)) + ) + return edit(() => []); + // Behind the others, so one failure holds none of them back. + await this.editReceipt(runnerId, attemptId, (entries) => [ + ...entries.filter((saved) => saved.id !== id), + ...entries + .filter((saved) => saved.id === id) + .map((saved) => ({ ...saved, failedAt })), + ]); + } + } + + private receipt(runnerId: string, attemptId: string): RunnerResumeAgent[] { + const attempt = this.active(runnerId); + return attempt?.id === attemptId ? (attempt.drain?.agents ?? []) : []; + } + + /** A delivery can outlast its pass, so this reads inside the write. */ + private editReceipt( + runnerId: string, + attemptId: string, + change: (entries: RunnerResumeAgent[]) => RunnerResumeAgent[] + ) { + return this.save(() => { + const attempt = this.active(runnerId); + if (attempt?.id !== attemptId || attempt.phase !== "resuming") + throw new Error("The runner update receipt has ended."); + return { + ...this.records.get(runnerId), + runnerId, + attempt: { + ...attempt, + drain: { ...attempt.drain!, agents: change(attempt.drain!.agents) }, + }, + }; + }); + } + + private markSent(runnerId: string, attemptId: string, id: string) { + return this.editReceipt(runnerId, attemptId, (entries) => { + if (!entries.some((entry) => entry.id === id)) + throw new Error("The continuation is no longer owed."); + return entries.map((entry) => + entry.id === id ? { ...entry, continuationSent: true } : entry + ); + }); + } + /** * Proof is the host's own welcome and completed replay, for the recorded * instance, on an attach opened over this connection. A connected runner @@ -1032,6 +1403,7 @@ export class RunnerUpdateCoordinator { return; } this.waiting.delete(runnerId); + if (attempt.drain?.force) this.options.agents.runnerForce.release(runnerId); const { target } = attempt; let { confirmed, failed } = this.records.get(runnerId) ?? {}; if (outcome.state === "updated" && target) { @@ -1264,10 +1636,13 @@ export class RunnerUpdateCoordinator { } /** Writes are serialized, and memory follows the file. */ - private save(record: RunnerUpdateRecord): Promise { + private save( + input: RunnerUpdateRecord | (() => RunnerUpdateRecord) + ): Promise { const write = this.writes .catch(() => {}) .then(async () => { + const record = typeof input === "function" ? input() : input; const next = new Map(this.records).set(record.runnerId, record); await this.options.store.write([...next.values()]); const hadDrain = this.records.get(record.runnerId)?.attempt.drain; diff --git a/apps/server/src/agents/runtime.ts b/apps/server/src/agents/runtime.ts index 625ff3eb5..5cadc2785 100644 --- a/apps/server/src/agents/runtime.ts +++ b/apps/server/src/agents/runtime.ts @@ -11,7 +11,7 @@ import type { RunnerRepository, } from "./remote/protocol.js"; import type { BuildIdentity } from "./build-identity.js"; -import type { HostLaunch } from "./acp/host-protocol.js"; +import type { HostLaunch, PromptReceiptState } from "./acp/host-protocol.js"; import type { AppConfig } from "../config.js"; import type { DriverEvent } from "./acp/driver.js"; import type { @@ -94,6 +94,28 @@ export type AgentRuntime = { host: RunnerHostIdentity, drainEpoch?: number ): RunnerHostRecycleHold | null; + /** + * A forced update takes over this runner's hosts: their queues outlive + * them, and nothing wakes a turn that is about to be cut. + */ + holdRunnerHosts?(runnerId: string): void; + /** The host is still there after all: attach to it, keeping its queue. */ + reattachRunnerHost?(agentId: string): void; + releaseRunnerHost?(agentId: string): void; + releaseRunnerHosts?(runnerId: string): void; + /** The open turn, once everything received before the call is recorded. */ + runnerTurn?(agentId: string): Promise<{ open: boolean; seq?: number } | null>; + /** + * Interrupt exactly this turn, at most once. True once it no longer runs, + * or when this host cannot interrupt it. + */ + interruptRunnerTurn?(agentId: string, seq: number): Promise; + /** Stop a host without waiting on its update hold or needing a lease. */ + stopRunnerHost?(runnerId: string, agentId: string): Promise; + promptReceipt?( + agentId: string, + id: string + ): Promise; /** Inspect an existing session without starting it or submitting chat. */ getMcpInventory(agentId: string): Promise; getBackgroundWork?(agentId: string): Promise; diff --git a/apps/server/src/routes/runners.ts b/apps/server/src/routes/runners.ts index af6c27326..8739b361e 100644 --- a/apps/server/src/routes/runners.ts +++ b/apps/server/src/routes/runners.ts @@ -88,9 +88,24 @@ export async function registerRunnerRoutes( return fail(reply, error); } } + if (action === "force") { + if (attemptId !== undefined && typeof attemptId !== "string") + return reply + .code(400) + .send({ error: "The update attempt ID must be a string." }); + if (!deps.updates) + return reply.code(404).send({ error: "Runner not found." }); + try { + return reply + .code(202) + .send(await deps.updates.forceUpdate(id, attemptId)); + } catch (error) { + return fail(reply, error); + } + } if (action !== "update" && action !== "retry") return reply.code(400).send({ - error: 'The action must be "update", "retry", or "cancel".', + error: 'The action must be "update", "retry", "force", or "cancel".', }); if (!deps.updates) return reply.code(404).send({ error: "Runner not found." }); diff --git a/apps/server/src/update-recovery/resume-receipt.ts b/apps/server/src/update-recovery/resume-receipt.ts index 272258384..34a78fe45 100644 --- a/apps/server/src/update-recovery/resume-receipt.ts +++ b/apps/server/src/update-recovery/resume-receipt.ts @@ -22,6 +22,37 @@ const resumeReceiptSchema = z .strict(); export type ResumeReceipt = z.infer; +/** + * A runner attempt's entry: the same running-row claim, plus progress. The + * attempt keeps each one until that agent is resumed and, if its turn was + * cut, told to continue. The local receipt above is strict and has none of + * this. + */ +export const runnerResumeAgentSchema = resumeAgentSchema + .extend({ + /** Turns a forced update cut or tried to: stream row, host sequence. */ + turns: z + .array( + z + .object({ + id: z.number().int().nonnegative(), + seq: z.number().int().nonnegative().optional(), + }) + .strict() + ) + .max(16) + .optional(), + /** Saved before the launch, which itself moves the row's timestamp. */ + launching: z.literal(true).optional(), + resumed: z.literal(true).optional(), + /** Saved before the continuation is first handed to the host. */ + continuationSent: z.literal(true).optional(), + /** When resuming first failed. */ + failedAt: z.number().optional(), + }) + .strict(); +export type RunnerResumeAgent = z.infer; + export const RESUME_RECEIPT_MAX_AGE_MS = 24 * 60 * 60 * 1000; /** Atomically replace the receipt: private temp file, fsync, rename, fsync dir. */ diff --git a/apps/server/test/db/runner-update-force.test.ts b/apps/server/test/db/runner-update-force.test.ts new file mode 100644 index 000000000..3b94a12a9 --- /dev/null +++ b/apps/server/test/db/runner-update-force.test.ts @@ -0,0 +1,604 @@ +/** + * A forced runner update end to end on Dispatch's side: receipt before any + * interrupt, exact turns cut, every session resumed once, and one + * continuation to each agent whose turn was cut, ahead of held work. + */ +import type { Pool } from "pg"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; + +import { UPDATE_TIMING } from "../../src/agents/remote/update-coordinator.js"; +import { + continuationId, + UPDATE_CONTINUATION_MESSAGE, +} from "../../src/agents/remote/force-sessions.js"; +import { + forceWorld, + RUNNER, + type Host, +} from "../helpers/runner-force-fixture.js"; +import { setupTestDb, teardownTestDb, runTestMigrations } from "./setup.js"; + +vi.mock("../../src/shared/lib/run-command.js", () => ({ + runCommand: vi.fn(async () => ({ exitCode: 0, stdout: "", stderr: "" })), +})); + +let pool: Pool; +let world: Awaited>; + +beforeAll(async () => { + pool = await setupTestDb(); + await runTestMigrations(); +}); +afterAll(async () => { + await teardownTestDb(); +}); +beforeEach(async () => { + await pool.query("DELETE FROM blocks"); + await pool.query("DELETE FROM files"); + await pool.query("DELETE FROM agents"); + world = await forceWorld(pool); +}); +afterEach(async () => { + await world.close(); +}); + +const force = () => world.coordinator.forceUpdate(RUNNER); +const continuations = (host: Host) => + host.prompts.filter(({ text }) => text === UPDATE_CONTINUATION_MESSAGE); +const statusOf = async (id: string) => + (await pool.query("SELECT status FROM agents WHERE id = $1", [id])).rows[0] + ?.status; +const finished = (state = "updated") => + world.until(() => world.view()?.result?.state === state); +async function updated() { + await world.activated(); + world.swap(); + await finished(); +} +/** Resumed into its own session, by this attempt, and only once. */ +function resumedOnce(host: Host) { + expect(host.launches.slice(1)).toEqual([ + { launchId: world.attempt()!.id, resume: host.sessionId }, + ]); + expect(host.alive).toBe(true); +} + +describe("a forced update", () => { + it("resumes a long turn, a waiting parent and idle agents once, and tells only the cut ones to continue, before held work", async () => { + const long = await world.agent(); + const parent = await world.agent(); + const idle = await world.agent(); + const legacy = await world.agent({ legacy: true }); + const conversation = { streamId: long.id, threadId: "thread" }; + const longSeq = await world.working(long, { + source: "system", + text: "long", + conversation, + }); + const parentSeq = await world.working(parent); + + let receiptAtInterrupt: string[] | undefined; + let heldAtInterrupt: boolean | undefined; + const append = long.append; + long.append = (event) => { + receiptAtInterrupt ??= world + .attempt() + ?.drain?.agents.map(({ id }) => id) + .sort(); + heldAtInterrupt ??= world.holds.isHeld(RUNNER); + append(event); + }; + const { attemptId } = await force(); + await world.until(() => world.view()?.attempt?.phase === "interrupting"); + const ordinary = world.prompt(long, "ordinary"); + await world.activated(); + + expect(long.interrupts).toEqual([longSeq]); + expect(parent.interrupts).toEqual([parentSeq]); + expect(idle.interrupts).toEqual([]); + expect(legacy.interrupts).toEqual([]); + expect(heldAtInterrupt).toBe(true); + expect(receiptAtInterrupt).toEqual( + [long.id, parent.id, idle.id, legacy.id].sort() + ); + for (const host of [long, parent, idle, legacy]) { + expect(host.alive).toBe(false); + expect(host.launches).toHaveLength(1); + expect(await statusOf(host.id)).toBe("running"); + } + // The fence saw an empty runner. + expect(world.runner.frames.filter((f) => f.type === "fence")).toEqual([ + { type: "fence", attemptId, retainSessions: false }, + ]); + + world.swap(); + await finished(); + await ordinary.accepted; + for (const host of [long, parent, idle, legacy]) resumedOnce(host); + expect(long.prompts.map(({ text }) => text)).toEqual([ + UPDATE_CONTINUATION_MESSAGE, + "ordinary", + ]); + expect(long.prompts[0]).toMatchObject({ + id: continuationId(attemptId, long.id), + source: { source: "system", conversation }, + }); + expect(parent.prompts.map(({ text }) => text)).toEqual([ + UPDATE_CONTINUATION_MESSAGE, + ]); + expect(idle.prompts).toEqual([]); + expect(legacy.prompts).toEqual([]); + expect(world.holds.isHeld(RUNNER)).toBe(false); + }); + + it("leaves a plain update waiting, and escalates it only when asked", async () => { + world.runner.incompatible = true; + const drained = await world.agent(); + const busy = await world.agent({ legacy: true }); + const seq = await world.working(busy); + const { attemptId } = await world.coordinator.request(RUNNER, "update"); + await world.until( + () => !drained.alive && world.view()?.attempt?.agents === 1 + ); + expect(world.view()?.attempt?.phase).toBe("draining"); + expect(busy.interrupts).toEqual([]); + expect(busy.stops).toBe(0); + expect(world.attempt()?.force).toBeUndefined(); + + await expect( + world.coordinator.forceUpdate(RUNNER, crypto.randomUUID()) + ).rejects.toMatchObject({ code: "stale_drain" }); + expect(await world.coordinator.forceUpdate(RUNNER, attemptId)).toEqual({ + attemptId, + }); + expect(world.view()?.attempt).toMatchObject({ + phase: "interrupting", + agents: 1, + }); + // A second click is the same force, and nothing is left to cancel. + expect(await world.coordinator.forceUpdate(RUNNER, attemptId)).toEqual({ + attemptId, + }); + await expect( + world.coordinator.cancelDrain(RUNNER, attemptId) + ).rejects.toMatchObject({ code: "stale_drain" }); + + await updated(); + expect(busy.interrupts).toEqual([seq]); + resumedOnce(drained); + resumedOnce(busy); + expect(drained.prompts).toEqual([]); + expect(continuations(busy)).toHaveLength(1); + }); + + it("does not share an attempt with a plain update", async () => { + const plain = world.coordinator.request(RUNNER, "update"); + const forced = world.coordinator.forceUpdate(RUNNER); + const results = await Promise.allSettled([plain, forced]); + expect(results.map((r) => r.status)).toEqual(["fulfilled", "rejected"]); + expect(world.attempt()?.force).toBeUndefined(); + }); + + it("sends nothing for a turn that finished just as it was interrupted", async () => { + const racing = await world.agent(); + racing.onInterrupt = "completes"; + const seq = await world.working(racing); + await force(); + await updated(); + expect(racing.interrupts).toEqual([seq]); + resumedOnce(racing); + expect(racing.prompts).toEqual([]); + }); + + it("stops a host whose turn will not settle, after a bounded wait", async () => { + const stuck = await world.agent(); + stuck.onInterrupt = "ignores"; + await world.working(stuck); + await force(); + await world.until(() => stuck.interrupts.length === 1); + expect(stuck.stops).toBe(0); + world.advance(UPDATE_TIMING.interruptMs); + await updated(); + expect(stuck.interrupts).toHaveLength(1); + expect(stuck.stops).toBe(1); + resumedOnce(stuck); + expect(continuations(stuck)).toHaveLength(1); + }); + + it("interrupts only the snapshotted turn, and tells an agent once when a later turn is cut by the stop", async () => { + const busy = await world.agent(); + const other = await world.agent(); + other.onInterrupt = "ignores"; + const seq = await world.working(busy); + await world.working(other); + await force(); + await world.until(() => !busy.turn && other.interrupts.length); + // The engine goes on by itself while the other host is still settling. + await world.working(busy, { source: "engine", text: "goal" }); + world.advance(UPDATE_TIMING.interruptMs); + await updated(); + expect(busy.interrupts).toEqual([seq]); + expect(continuations(busy)).toHaveLength(1); + }); + + it("interrupts the same turn again from the welcome after a reconnect, and no other", async () => { + const busy = await world.agent(); + busy.onInterrupt = "silent"; + const seq = await world.working(busy); + await force(); + await world.until(() => busy.interrupts.length === 1); + world.disconnect(); + busy.onInterrupt = "cancel"; + world.reconnect(); + await updated(); + expect(busy.interrupts).toEqual([seq, seq]); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + }); + + it("waits for a turn that settled while the runner was away without interrupting its successor", async () => { + const busy = await world.agent(); + busy.onInterrupt = "silent"; + const seq = await world.working(busy); + await force(); + await world.until(() => busy.interrupts.length === 1); + world.disconnect(); + busy.settle("end_turn"); + world.reconnect(); + await updated(); + expect(busy.interrupts).toEqual([seq]); + expect(busy.prompts).toEqual([]); + }); + + it("repeats nothing on a duplicate terminal status", async () => { + const busy = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + world.swap(); + await world.until(() => world.view()?.attempt?.phase === "resuming"); + world.report("confirmed"); + world.report("rolled_back", "boot_failed"); + await finished(); + world.report("confirmed"); + await world.coordinator.tick(); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + expect(world.view()?.result?.state).toBe("updated"); + }); +}); + +describe("failure after interruption", () => { + it("resumes on the previous build after a rollback and still continues once", async () => { + const busy = await world.agent(); + const idle = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + world.rollBack(); + await finished("rolled_back"); + resumedOnce(busy); + resumedOnce(idle); + expect(continuations(busy)).toHaveLength(1); + expect(idle.prompts).toEqual([]); + }); + + it("recovers a partial stop: the live host reattaches, the stopped one resumes", async () => { + const stays = await world.agent(); + const stops = await world.agent(); + stays.stopFails = true; + await world.working(stays); + await world.working(stops); + await force(); + await world.until(() => !stops.alive && stays.stops > 0); + expect(world.effects).not.toContain("activate"); + world.advance(UPDATE_TIMING.interruptingMs); + await finished("deferred"); + expect(world.view()?.result?.reason).toBe("force_timeout"); + expect(stays.launches).toHaveLength(1); + resumedOnce(stops); + expect(continuations(stays)).toHaveLength(1); + expect(continuations(stops)).toHaveLength(1); + }); + + it("gives up on a session that won't resume without holding up the others", async () => { + const broken = await world.agent(); + const fine = await world.agent(); + await world.working(fine); + await force(); + await world.activated(); + broken.resumeFails = true; + world.swap(); + await world.until( + () => continuations(fine).length && world.entry(broken.id)?.failedAt + ); + expect(world.holds.isHeld(RUNNER)).toBe(true); + world.advance(UPDATE_TIMING.resumeRetryMs); + await finished(); + expect(await statusOf(broken.id)).toBe("error"); + expect(continuations(fine)).toHaveLength(1); + expect(broken.prompts).toEqual([]); + }); +}); + +describe("hosts that go down untidily", () => { + it("resumes and continues an agent whose engine died of the interrupt", async () => { + const busy = await world.agent(); + busy.onInterrupt = "crashes"; + await world.working(busy); + await force(); + await updated(); + expect(await statusOf(busy.id)).toBe("running"); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + }); + + it("keeps held work when the replacement replays the old host's exit", async () => { + const busy = await world.agent(); + busy.stopLosesExit = true; + await world.working(busy); + await force(); + await world.until(() => world.view()?.attempt?.phase === "interrupting"); + const ordinary = world.prompt(busy, "ordinary"); + await updated(); + await ordinary.accepted; + expect(busy.prompts.map(({ text }) => text)).toEqual([ + UPDATE_CONTINUATION_MESSAGE, + "ordinary", + ]); + }); + + it("keeps the receipt when the runner returns fenced for another attempt", async () => { + const busy = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + world.disconnect(); + world.reconnect(crypto.randomUUID()); + await finished("deferred"); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + }); +}); + +describe("agents the user changed during the update", () => { + it("never resumes or messages a stopped, archived, deleted or changed agent", async () => { + const stopped = await world.agent(); + const archived = await world.agent(); + const deleted = await world.agent(); + const changed = await world.agent(); + const all = [stopped, archived, deleted, changed]; + for (const host of all) await world.working(host); + await force(); + await world.activated(); + await world.manager.stopAgent(stopped.id); + await world.manager.beginArchive(archived.id); + await pool.query("UPDATE agents SET deleted_at = NOW() WHERE id = $1", [ + deleted.id, + ]); + await world.manager.renameAgent(changed.id, "changed"); + world.swap(); + await finished(); + for (const host of all) { + expect(host.launches).toHaveLength(1); + expect(host.prompts).toEqual([]); + } + expect(await statusOf(stopped.id)).toBe("stopped"); + expect(await statusOf(archived.id)).toBe("archiving"); + }); + + it("lets a stop asked for while interrupting win", async () => { + const busy = await world.agent(); + busy.onInterrupt = "ignores"; + await world.working(busy); + await force(); + await world.until(() => busy.interrupts.length === 1); + const stop = world.manager.stopAgent(busy.id); + await world.until(() => (world.manager as any).stoppingOrArchiving.size); + world.advance(UPDATE_TIMING.interruptMs); + await updated(); + await stop; + expect(busy.launches).toHaveLength(1); + expect(busy.prompts).toEqual([]); + expect(await statusOf(busy.id)).toBe("stopped"); + }); + + it("sends no continuation to an agent stopped after it resumed", async () => { + const busy = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + let stop: Promise | undefined; + world.saved.afterWrite = () => { + if (!stop && world.entry(busy.id)?.resumed) + stop = world.manager.stopAgent(busy.id); + }; + world.swap(); + await finished(); + await stop; + expect(busy.prompts).toEqual([]); + expect(await statusOf(busy.id)).toBe("stopped"); + }); +}); + +describe("a controller crash", () => { + it("after the receipt, before any interrupt", async () => { + const busy = await world.agent(); + const idle = await world.agent(); + const seq = await world.working(busy); + world.saved.afterWrite = () => { + if (!world.entry(busy.id)) return; + world.saved.afterWrite = undefined; + world.crash(); + }; + await force(); + await world.until(() => !world.saved.afterWrite); + expect(busy.interrupts).toEqual([]); + expect(idle.stops).toBe(0); + await world.restart(); + await updated(); + expect(busy.interrupts).toEqual([seq]); + resumedOnce(busy); + resumedOnce(idle); + expect(continuations(busy)).toHaveLength(1); + }); + + it("after the stop, before its claim was refreshed", async () => { + const busy = await world.agent(); + await world.working(busy); + world.saved.beforeWrite = () => { + if (busy.stops === 0) return; + world.saved.beforeWrite = undefined; + world.crash(); + throw new Error("controller stopped"); + }; + await force(); + await world.until(() => !world.saved.beforeWrite); + await world.restart(); + await updated(); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + }); + + it("with the hosts stopped, before the switch", async () => { + const busy = await world.agent(); + await world.working(busy); + world.saved.afterWrite = () => { + if (world.attempt()?.phase !== "settling") return; + world.saved.afterWrite = undefined; + world.crash(); + }; + await force(); + await world.until(() => !world.saved.afterWrite); + expect(busy.alive).toBe(false); + await world.restart(); + expect(await statusOf(busy.id)).toBe("running"); + await updated(); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + }); + + type Records = Parameters>[0]; + const agentsIn = (records: Records) => records[0]?.attempt.drain?.agents; + + it.each([ + [ + "after the launch, before its progress was saved", + (next: Records) => agentsIn(next)?.some((entry) => entry.resumed), + ], + [ + "after the continuation was accepted, before that was saved", + (next: Records) => + next[0]?.attempt.phase === "resuming" && agentsIn(next)?.length === 0, + ], + [ + "before the continuation was marked sent", + (next: Records) => + agentsIn(next)?.some((entry) => entry.continuationSent), + ], + ])("during resume, %s", async (_case, at) => { + const busy = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + world.saved.beforeWrite = (next) => { + if (!at(next)) return; + world.saved.beforeWrite = undefined; + world.crash(); + throw new Error("controller stopped"); + }; + world.swap(); + await world.until(() => !world.saved.beforeWrite); + await world.restart(); + await finished(); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + }); + + it("after the continuation was marked sent, before it left", async () => { + const busy = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + world.saved.afterWrite = () => { + if (!world.entry(busy.id)?.continuationSent) return; + world.saved.afterWrite = undefined; + world.crash(); + }; + world.swap(); + await world.until(() => !world.saved.afterWrite); + expect(busy.prompts).toEqual([]); + await world.restart(); + await finished(); + resumedOnce(busy); + expect(continuations(busy)).toHaveLength(1); + }); + + it("does not launch again when the host it launched died while Dispatch was down", async () => { + const busy = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + world.saved.beforeWrite = (next) => { + if (!agentsIn(next)?.some((entry) => entry.resumed)) return; + world.saved.beforeWrite = undefined; + world.crash(); + busy.alive = false; + throw new Error("controller stopped"); + }; + world.swap(); + await world.until(() => !world.saved.beforeWrite); + await world.restart(); + await finished(); + expect(busy.launches).toHaveLength(2); + expect(busy.prompts).toEqual([]); + }); + + it("leaves a continuation the host only claimed", async () => { + const busy = await world.agent(); + await world.working(busy); + const { attemptId } = await force(); + await world.activated(); + world.saved.beforeWrite = (next) => { + if (next[0]?.attempt.phase !== "resuming" || agentsIn(next)?.length) + return; + world.saved.beforeWrite = undefined; + world.crash(); + busy.receipts.set(continuationId(attemptId, busy.id), "claimed"); + throw new Error("controller stopped"); + }; + world.swap(); + await world.until(() => !world.saved.beforeWrite); + await world.restart(); + await finished(); + expect(continuations(busy)).toHaveLength(1); + }); + + it("never resends to a host without receipts", async () => { + const busy = await world.agent({ legacy: true }); + await world.working(busy); + await force(); + await world.activated(); + world.saved.beforeWrite = (next) => { + if (next[0]?.attempt.phase !== "resuming" || agentsIn(next)?.length) + return; + world.saved.beforeWrite = undefined; + world.crash(); + throw new Error("controller stopped"); + }; + world.swap(); + await world.until(() => !world.saved.beforeWrite); + await world.restart(); + await finished(); + expect(continuations(busy)).toHaveLength(1); + }); +}); diff --git a/apps/server/test/helpers/runner-force-fixture.ts b/apps/server/test/helpers/runner-force-fixture.ts new file mode 100644 index 000000000..65b9dd198 --- /dev/null +++ b/apps/server/test/helpers/runner-force-fixture.ts @@ -0,0 +1,666 @@ +/** + * A forced runner update without a runner: the real manager on Postgres, the + * real ACP runtime, holds and coordinator, over scripted hosts that keep + * their journal and prompt receipts across a relaunch as a runner's do. + */ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { Duplex } from "node:stream"; + +import type { FastifyBaseLogger } from "fastify"; +import type { Pool } from "pg"; +import { expect, vi } from "vitest"; + +import { + encodeMessage, + ndjsonDecoder, + type ClientMessage, + type HostMessage, + type JournalEntry, +} from "../../src/agents/acp/host-protocol.js"; +import type { PromptSource } from "../../src/agents/acp/prompt-source.js"; +import { AgentManager } from "../../src/agents/manager.js"; +import { + RunnerUnavailable, + type RemoteRunnerService, + type RunnerUpdateEvent, +} from "../../src/agents/remote/service.js"; +import { + RunnerUpdateCoordinator, + type RunnerUpdateRecord, +} from "../../src/agents/remote/update-coordinator.js"; +import { + RunnerUpdateHolds, + type RunnerHoldState, +} from "../../src/agents/remote/update-hold.js"; +import { identity, target } from "../runner-update-fixtures.js"; +import { trackHoldWork } from "./hold-work.js"; + +export const RUNNER = "r1"; +const PLACE = `runner://${RUNNER}/@session`; + +export const logger = { + info: () => {}, + warn: () => {}, + error: () => {}, + debug: () => {}, + fatal: () => {}, + trace: () => {}, + child: () => logger, + silent: () => {}, + level: "silent", +} as unknown as FastifyBaseLogger; + +function socketPair(): [Duplex, Duplex] { + let a!: Duplex; + let b!: Duplex; + const side = (other: () => Duplex) => + new Duplex({ + read() {}, + write(chunk, _encoding, done) { + if (!other().destroyed) other().push(chunk); + done(); + }, + destroy(error, done) { + queueMicrotask(() => other().destroy()); + done(error); + }, + }); + a = side(() => b); + b = side(() => a); + return [a, b]; +} + +type Interrupt = + /** The engine stops and reports the turn cancelled. */ + | "cancel" + /** The turn finished just as the interrupt arrived. */ + | "completes" + /** The engine never settles it. */ + | "ignores" + /** No reply at all, until the test says. */ + | "silent" + /** The engine dies of it. */ + | "crashes"; + +export type Host = { + id: string; + sessionId: string; + alive: boolean; + instanceId: string; + /** A pre-phase-3 host has neither a lease nor receipts. */ + legacy: boolean; + onInterrupt: Interrupt; + stopFails: boolean; + /** The channel drops before the stop's exit event is forwarded. */ + stopLosesExit: boolean; + resumeFails: boolean; + journal: JournalEntry[]; + turn: { seq: number; startedAt: string; source?: PromptSource } | null; + receipts: Map; + prompts: { id: string; text: string; source?: PromptSource }[]; + interrupts: number[]; + launches: { launchId?: string; resume: string | null }[]; + stops: number; + socket?: Duplex; + append(event: object): void; + startTurn(text?: string, source?: PromptSource): void; + settle(stopReason?: string): void; +}; + +export async function forceWorld(pool: Pool) { + const dir = await mkdtemp(path.join(os.tmpdir(), "dispatch-force-")); + const hosts = new Map(); + const saved = { + records: [] as RunnerUpdateRecord[], + holds: { holds: [], resuming: [] } as RunnerHoldState, + /** Runs before a write lands; throwing fails the write. */ + beforeWrite: undefined as + | undefined + | ((next: RunnerUpdateRecord[]) => void), + /** Runs once a write landed. */ + afterWrite: undefined as undefined | ((now: RunnerUpdateRecord[]) => void), + }; + /** Every side effect, in the order the runner saw it. */ + const effects: string[] = []; + let offset = 0; + const now = () => Date.now() + offset; + let epoch: number | undefined = 1; + let connections = 1; + let installed = { ...identity }; + let pending: string | undefined; + const runner = { incompatible: false, frames: [] as any[] }; + + function host(id: string): Host { + const existing = hosts.get(id); + if (existing) return existing; + const created: Host = { + id, + sessionId: `sess_${id}`, + alive: false, + instanceId: randomUUID(), + legacy: false, + onInterrupt: "cancel", + stopFails: false, + stopLosesExit: false, + resumeFails: false, + journal: [], + turn: null, + receipts: new Map(), + prompts: [], + interrupts: [], + launches: [], + stops: 0, + append(event) { + const entry = { + seq: created.journal.length + 1, + at: new Date().toISOString(), + event: { agentId: id, ...event }, + } as JournalEntry; + created.journal.push(entry); + if (created.socket && !created.socket.destroyed) + created.socket.write(encodeMessage({ type: "event", ...entry })); + }, + startTurn(text = "work", source) { + created.turn = { + seq: created.journal.length + 1, + startedAt: new Date().toISOString(), + ...(source && { source }), + }; + created.append({ + type: "turn", + state: "started", + text, + sessionId: created.sessionId, + ...(source && { source }), + }); + }, + settle(stopReason = "end_turn") { + created.turn = null; + created.append({ type: "turn", state: "settled", stopReason }); + }, + }; + hosts.set(id, created); + return created; + } + + function channel(h: Host) { + const [ours, theirs] = socketPair(); + h.socket?.destroy(); + h.socket = theirs; + const send = (message: HostMessage) => { + if (!theirs.destroyed) theirs.write(encodeMessage(message)); + }; + const decode = ndjsonDecoder(); + theirs.on("data", (chunk) => { + for (const message of decode(chunk)) { + if (message.type === "hello") { + send({ + type: "welcome", + agentId: h.id, + engine: "claude", + sessionId: h.sessionId, + resumed: h.launches.length > 1 && !h.resumeFails, + running: true, + turn: h.turn, + journalSeq: h.journal.length, + journalId: `journal_${h.id}`, + interruptSupported: true, + ...(!h.legacy && { + hostInstanceId: h.instanceId, + quiesceSupported: true as const, + promptReceiptSupported: true as const, + }), + } as HostMessage); + for (const entry of h.journal) + if (entry.seq > message.fromSeq) + send({ type: "event", ...entry } as HostMessage); + send({ type: "replay_complete" }); + } else if (message.type === "prompt_receipt") { + send({ + type: "prompt_receipt_result", + id: message.id, + journalId: message.journalId, + state: h.receipts.get(message.id) ?? "unclaimed", + }); + } else if (message.type === "prompt") { + if (!h.legacy && h.receipts.get(message.id) === "claimed") { + send({ + type: "error", + id: message.id, + message: "Prompt execution is unknown; do not resubmit.", + }); + continue; + } + if (!h.legacy && h.receipts.get(message.id) === "accepted") { + send({ type: "prompt_accepted", id: message.id }); + continue; + } + effects.push(`prompt:${h.id}:${message.text}`); + h.prompts.push({ + id: message.id, + text: message.text, + source: message.source, + }); + h.receipts.set(message.id, "accepted"); + h.startTurn(message.text, message.source); + send({ type: "prompt_accepted", id: message.id }); + h.settle(); + } else if (message.type === "interrupt") { + effects.push(`interrupt:${h.id}`); + h.interrupts.push(message.turnSeq); + if (h.onInterrupt === "silent") continue; + const current = h.turn?.seq === message.turnSeq; + if (current && h.onInterrupt === "crashes") { + exit(h, false); + continue; + } + if (current && h.onInterrupt === "completes") h.settle("end_turn"); + send({ type: "interrupt_result", id: message.id }); + if (current && h.onInterrupt === "cancel") h.settle("cancelled"); + } else if (message.type === "quiesce") { + send({ + type: "quiesce_result", + id: message.id, + state: h.turn ? "busy" : "idle", + }); + } else if (message.type === "shutdown" && "quiesceId" in message) { + send({ + type: "quiesce_shutdown_result", + id: message.quiesceId, + accepted: !h.turn, + }); + if (!h.turn) exit(h); + } + } + }); + return ours; + } + + function exit(h: Host, expected = true) { + if (!h.alive) return; + h.turn = null; + if (expected && h.stopLosesExit) { + h.socket?.destroy(); + h.socket = undefined; + } + h.append({ + type: "exit", + code: expected ? 0 : 1, + signal: null, + stderrTail: "", + expected, + }); + h.alive = false; + const socket = h.socket; + h.socket = undefined; + setImmediate(() => socket?.destroy()); + } + + function controller() { + let dead = false; + const guard = () => { + if (dead || epoch === undefined) throw new RunnerUnavailable("offline"); + }; + const channels = new Set(); + const remote = { + available: () => !dead && epoch !== undefined, + connectionEpoch: () => (dead ? undefined : epoch), + isManagedWorkspace: () => true, + originFor: () => "https://example.test", + supportsSessionFiles: () => true, + reconcilesLaunches: () => true, + selfUpdate: () => undefined, + async requestSession( + _placement: unknown, + operation: { kind: string; agentId: string; launch?: any } + ) { + guard(); + if (operation.kind === "sessionFile") + return { value: "/runner/files/x" }; + const h = host(operation.agentId); + switch (operation.kind) { + case "launch": { + const { launchId, resumeSessionId } = operation.launch; + h.launches.push({ launchId, resume: resumeSessionId ?? null }); + effects.push(`launch:${h.id}`); + if (!h.alive) h.instanceId = randomUUID(); + h.alive = true; + return { value: true }; + } + case "attach": { + if (!h.alive) throw new RunnerUnavailable("no host"); + const socket = channel(h); + channels.add(socket); + return { value: true, channel: socket }; + } + case "alive": + return { value: h.alive }; + case "stop": + h.stops++; + if (h.stopFails) throw new RunnerUnavailable("stop failed"); + effects.push(`stop:${h.id}`); + exit(h); + return { value: true }; + case "log": + return { value: "" }; + default: + return { value: true }; + } + }, + } as unknown as RemoteRunnerService; + + const holds = new RunnerUpdateHolds({ + store: { + read: async () => structuredClone(saved.holds), + async write(state) { + if (dead) throw new Error("controller stopped"); + saved.holds = structuredClone(state); + }, + }, + logger, + now, + }); + const work = trackHoldWork(holds); + const manager = new AgentManager( + pool, + logger, + { + host: "127.0.0.1", + port: 6767, + databaseUrl: "", + authToken: "test-token", + filesRoot: path.join(dir, "files"), + dispatchBinDir: path.join(dir, "bin"), + codexBin: "/bin/echo", + claudeBin: "/bin/echo", + opencodeBin: "/bin/opencode", + agentStateRoot: path.join(dir, "agents"), + agentRuntime: "acp", + tls: null, + }, + { remote, holds } + ); + let receive: ((event: RunnerUpdateEvent) => unknown) | undefined; + let connected: ((runnerId: string) => unknown) | undefined; + const frame = (value: object) => { + guard(); + runner.frames.push(value); + return { epoch: epoch! }; + }; + const status = (value: object) => + setImmediate(() => { + if (dead || epoch === undefined) return; + receive?.({ + runnerId: RUNNER, + epoch, + status: { + type: "update_status", + installed: { + version: installed.version, + revision: installed.revision, + sha256: installed.sha256, + }, + ...value, + }, + } as RunnerUpdateEvent); + }); + const service = { + isRegistered: () => true, + connectedRunnerIds: () => (epoch === undefined ? [] : [RUNNER]), + connectionEpoch: remote.connectionEpoch, + selfUpdate: () => + dead || epoch === undefined + ? undefined + : { + epoch, + advert: { + protocol: 1, + os: "linux", + arch: "x64", + version: installed.version, + revision: installed.revision, + installedSha256: installed.sha256, + handoff: { reads: [1, 2], writes: 2 }, + ...(pending && { pendingAttemptId: pending }), + }, + }, + onConnectionChange(listener: (runnerId: string) => unknown) { + connected = listener; + return () => (connected = undefined); + }, + onUpdateStatus(listener: (event: RunnerUpdateEvent) => unknown) { + receive = listener; + return () => (receive = undefined); + }, + offerUpdate(_runner: string, attemptId: string) { + status({ attemptId, phase: "deferred", reason: "ready" }); + return frame({ type: "offer", attemptId }); + }, + fenceUpdate(_runner: string, attemptId: string, retainSessions: boolean) { + const live = [...hosts.values()].filter((h) => h.alive); + const retained = live + .filter((h) => !h.legacy) + .map((h) => ({ sessionId: h.id, instanceId: h.instanceId })); + status({ + attemptId, + phase: "deferred", + retained, + ...(retainSessions && runner.incompatible + ? { reason: "incompatible_handoff", requiresQuiescence: true } + : !retainSessions && live.length + ? { reason: "operations_pending" } + : { reason: "fence_ready" }), + }); + return frame({ type: "fence", attemptId, retainSessions }); + }, + activateUpdate(_runner: string, attemptId: string) { + effects.push("activate"); + return frame({ type: "activate", attemptId }); + }, + confirmUpdate(_runner: string, attemptId: string) { + status({ attemptId, phase: "confirmed" }); + return frame({ type: "confirm", attemptId }); + }, + cancelUpdate(_runner: string, attemptId: string) { + if (pending === attemptId) pending = undefined; + status({ attemptId, phase: "deferred", reason: "cancelled" }); + return frame({ type: "cancel", attemptId }); + }, + }; + const coordinator = new RunnerUpdateCoordinator({ + service: service as never, + holds, + agents: manager, + artifacts: () => + ({ + updateEnabled: true, + getUpdate: async () => ({ manifest: { sha256: target.sha256 } }), + }) as never, + build: { version: target.version, revision: target.revision }, + logger, + now, + store: { + read: async () => structuredClone(saved.records), + async write(records) { + if (dead) throw new Error("controller stopped"); + saved.beforeWrite?.(records); + saved.records = structuredClone(records); + saved.afterWrite?.(records); + }, + }, + }); + return { + manager, + holds, + work, + coordinator, + status, + reconnected: () => connected?.(RUNNER), + disconnect() { + for (const socket of channels) socket.destroy(); + channels.clear(); + }, + kill() { + if (dead) return; + dead = true; + coordinator.close(); + holds.close(); + work.abandon(); + for (const socket of channels) socket.destroy(); + channels.clear(); + }, + }; + } + + let current = controller(); + const made: string[] = []; + await current.holds.load(); + await current.coordinator.load(); + current.holds.start(); + await current.coordinator.start(); + + const runtime = () => (current.manager as any).runtime; + const recorded = async () => { + for (const id of made) await runtime().runnerTurn(id); + }; + + const api = { + hosts, + saved, + effects, + runner, + recorded, + get manager() { + return current.manager; + }, + get coordinator() { + return current.coordinator; + }, + get holds() { + return current.holds; + }, + advance(ms: number) { + offset += ms; + }, + async agent(options: { legacy?: boolean } = {}) { + const agent = await current.manager.createAgent( + { cwd: PLACE }, + { + beforeLaunch: async (id) => { + host(id).legacy = options.legacy === true; + }, + } + ); + made.push(agent.id); + const h = host(agent.id); + await vi.waitFor(async () => { + expect((await current.manager.getAgent(agent.id))?.status).toBe( + "running" + ); + expect(h.turn).toBeNull(); + expect(runtime().isBusy(agent.id)).toBe(false); + }); + await recorded(); + h.prompts.length = 0; + return h; + }, + /** An open turn Dispatch has recorded. */ + async working(h: Host, source?: PromptSource) { + h.startTurn("work", source); + await vi.waitFor(() => expect(runtime().hasOpenTurn(h.id)).toBe(true)); + await recorded(); + return h.turn!.seq; + }, + prompt(h: Host, text: string) { + const { accepted, settled } = runtime().prompt(h.id, text, { + source: "system", + text, + }); + settled.catch(() => {}); + accepted.catch(() => {}); + return { accepted: accepted as Promise }; + }, + attempt: () => saved.records[0]?.attempt, + entry: (id: string) => + saved.records[0]?.attempt.drain?.agents.find((e) => e.id === id), + view: () => current.coordinator.view(RUNNER), + /** Tick until true, without moving the clock. */ + async until(check: () => unknown, timeoutMs = 10_000) { + const deadline = Date.now() + timeoutMs; + while (!(await check())) { + if (Date.now() > deadline) + throw new Error( + `not reached: ${check}\nview ${JSON.stringify( + current.coordinator.view(RUNNER) + )}\neffects ${effects.join(", ")}` + ); + await current.coordinator.tick(); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + }, + activated: () => api.until(() => effects.includes("activate")), + /** The updater swaps, and the trial is confirmed. */ + swap() { + installed = { + ...installed, + version: target.version, + revision: target.revision, + sha256: target.sha256, + }; + current.status({ + attemptId: api.attempt()!.id, + phase: "activating", + reason: "trial", + retained: [], + }); + }, + rollBack() { + installed = { ...identity }; + api.report("rolled_back", "boot_failed"); + }, + report(phase: string, reason?: string) { + current.status({ + attemptId: api.attempt()!.id, + phase, + ...(reason && { reason }), + }); + }, + disconnect() { + epoch = undefined; + current.disconnect(); + }, + reconnect(pendingAttempt?: string) { + pending = pendingAttempt; + epoch = ++connections; + current.reconnected(); + }, + crash: () => current.kill(), + /** A new Dispatch process, as server.ts starts one. */ + async restart() { + current.kill(); + current = controller(); + await current.holds.load(); + await current.coordinator.load(); + await current.manager.restoreRunningAgents(); + await current.manager.reconcileAgentStatuses(); + current.holds.start(); + await current.coordinator.start(); + }, + async close() { + saved.beforeWrite = saved.afterWrite = undefined; + // Let the pass in flight finish before its hosts go away. + current.coordinator.close(); + await current.coordinator.tick(); + for (const hold of saved.holds.holds) + await current.holds.release(hold.runnerId, hold.attemptId, "cancelled"); + await current.work.settled(); + await recorded().catch(() => {}); + current.kill(); + await rm(dir, { recursive: true, force: true }); + }, + }; + return api; +} diff --git a/apps/server/test/runner-update-routes.test.ts b/apps/server/test/runner-update-routes.test.ts index 263524807..db0c3d9d1 100644 --- a/apps/server/test/runner-update-routes.test.ts +++ b/apps/server/test/runner-update-routes.test.ts @@ -19,6 +19,7 @@ const runner = (id: string, status: string) => ({ async function routes() { const updates = { request: vi.fn(async () => ({ attemptId: "attempt" })), + forceUpdate: vi.fn(async () => ({ attemptId: "forced" })), view: vi.fn((id: string) => id === "plain" ? undefined @@ -70,6 +71,37 @@ describe("runner update routes", () => { }); }); + it.each([undefined, "waiting"])( + "forces only when asked to, with attempt %s", + async (attemptId) => { + const { app, updates } = await routes(); + const post = (action: string) => + app.inject({ + method: "POST", + url: "/api/v1/runners/capable/update", + payload: { action, attemptId }, + }); + await post("update"); + expect(updates.forceUpdate).not.toHaveBeenCalled(); + const reply = await post("force"); + expect(reply.statusCode).toBe(202); + expect(reply.json()).toEqual({ attemptId: "forced" }); + expect(updates.forceUpdate).toHaveBeenCalledWith("capable", attemptId); + expect(updates.request).toHaveBeenCalledTimes(1); + } + ); + + it("refuses a malformed force", async () => { + const { app, updates } = await routes(); + const reply = await app.inject({ + method: "POST", + url: "/api/v1/runners/capable/update", + payload: { action: "force", attemptId: 7 }, + }); + expect(reply.statusCode).toBe(400); + expect(updates.forceUpdate).not.toHaveBeenCalled(); + }); + it("adds update state only where there is any", async () => { const { app } = await routes(); const { runners } = (await app.inject("/api/v1/runners")).json(); diff --git a/apps/server/test/update-recovery-maintenance.test.ts b/apps/server/test/update-recovery-maintenance.test.ts index 13d2c399e..3960fe312 100644 --- a/apps/server/test/update-recovery-maintenance.test.ts +++ b/apps/server/test/update-recovery-maintenance.test.ts @@ -822,6 +822,24 @@ describe("resume receipt", () => { expect(await takeResumeReceipt(file)).toEqual({ status: "none" }); }); + it("has none of a runner attempt's progress, and refuses it", async () => { + const file = path.join(await tempDir(), "update-recovery", "r.json"); + const local = receipt(); + for (const progress of [ + { turns: [{ id: 1, seq: 2 }] }, + { launching: true }, + { resumed: true }, + { continuationSent: true }, + { failedAt: 1 }, + ]) + await expect( + writeResumeReceipt(file, { + ...local, + agents: [{ ...local.agents[0]!, ...progress }], + } as ResumeReceipt) + ).rejects.toThrow(); + }); + it("sets aside expired, malformed and unsafe receipts without resuming", async () => { const dir = await tempDir(); const now = Date.parse("2026-10-02T00:00:00Z"); diff --git a/apps/web/src/components/app/runner-update.test.tsx b/apps/web/src/components/app/runner-update.test.tsx index 483af12a5..e969da1ed 100644 --- a/apps/web/src/components/app/runner-update.test.tsx +++ b/apps/web/src/components/app/runner-update.test.tsx @@ -1,6 +1,12 @@ // @vitest-environment jsdom import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { + cleanup, + fireEvent, + render, + screen, + within, +} from "@testing-library/react"; import type { RunnerUpdateView } from "@dispatch/shared"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -93,6 +99,55 @@ it("says new work waits once, and only while, it is held", () => { expect(text()).toContain("New work waits until the update finishes."); }); +it("asks before Update now, and forces only on the confirm", async () => { + vi.mocked(api).mockResolvedValue({ attemptId: "a" }); + const waiting = { + attempt: { id: "a", phase: "draining", version, agents: 2 }, + } as const; + show(waiting); + fireEvent.click(screen.getByRole("button", { name: "Update now" })); + const dialog = await screen.findByRole("alertdialog"); + expect(dialog.textContent).toContain("Update Build machine now?"); + expect(dialog.textContent).toContain( + "Running turns are interrupted and resumed after the update. Open terminals close, and any tool call in progress is lost." + ); + fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + expect(screen.queryByRole("alertdialog")).toBeNull(); + expect(api).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole("button", { name: "Update now" })); + fireEvent.click( + within(await screen.findByRole("alertdialog")).getByRole("button", { + name: "Update now", + }) + ); + await vi.waitFor(() => expect(api).toHaveBeenCalledTimes(1)); + expect(api).toHaveBeenCalledWith("/api/v1/runners/rnr%2Fone/update", { + method: "POST", + body: '{"action":"force","attemptId":"a"}', + }); +}); + +it("closes the question when the wait ends by itself", async () => { + const view = show({ attempt: { id: "a", phase: "draining", version } }); + fireEvent.click(screen.getByRole("button", { name: "Update now" })); + await screen.findByRole("alertdialog"); + view.update({ attempt: { id: "a", phase: "settling", version } }); + expect(screen.queryByRole("alertdialog")).toBeNull(); +}); + +it.each([ + ["interrupting", undefined, "Interrupting agents…"], + ["interrupting", 1, "Interrupting 1 agent"], + ["interrupting", 3, "Interrupting 3 agents"], + ["resuming", 3, "Resuming 3 agents"], +] as const)("shows %s with %s agents", (phase, agents, progress) => { + show({ attempt: { id: "a", phase, version, agents, held: true } }); + expect(text()).toContain(progress); + expect(text()).not.toContain("New work waits"); + expect(screen.queryByRole("button")).toBeNull(); +}); + it.each([ [1, "1 agent still on the previous build"], [3, "3 agents still on the previous build"], @@ -134,6 +189,7 @@ it.each([ }); it.each([ + ["force_timeout", "Dispatch couldn’t stop every agent in time."], ["operations_pending", "The runner was still busy, so it didn’t switch."], ["verify_failed", "The runner couldn’t download or verify the build."], ["settle_timeout", "Work on the runner didn’t settle in time."], diff --git a/apps/web/src/components/app/runner-update.tsx b/apps/web/src/components/app/runner-update.tsx index a7f394ab3..5ad86c9f6 100644 --- a/apps/web/src/components/app/runner-update.tsx +++ b/apps/web/src/components/app/runner-update.tsx @@ -1,13 +1,22 @@ import type { RunnerUpdatePhaseView, RunnerUpdateView } from "@dispatch/shared"; import { Loader2 } from "lucide-react"; +import { useState } from "react"; -import { LoadingButton } from "@/components/ui/button"; +import { + AlertDialog, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { Button, LoadingButton } from "@/components/ui/button"; import { useStartRunnerUpdate, type Runner } from "@/hooks/use-runners"; import { ApiError } from "@/lib/api"; import { RunnerCommand, useRunnerInstaller } from "./runner-onboarding"; const PHASES: Record< - Exclude, + Exclude, string > = { staging: "Downloading and verifying…", @@ -29,6 +38,7 @@ const ROLLED_BACK: Record = { const DEFERRED: Record = { drain_timeout: "The wait for agents timed out.", + force_timeout: "Dispatch couldn’t stop every agent in time.", operations_pending: "The runner was still busy, so it didn’t switch.", verify_failed: "The runner couldn’t download or verify the build.", boot_failed: "The runner couldn’t restart to switch builds.", @@ -112,10 +122,73 @@ function UpdateCommand() { ) : null; } +/** Update now cuts work off, so it asks first. */ +function UpdateNow({ + runnerName, + loading, + disabled, + onConfirm, +}: { + runnerName: string; + loading: boolean; + disabled: boolean; + onConfirm: () => void; +}) { + const [open, setOpen] = useState(false); + return ( + + + {/* Not a LoadingButton: focus returns here through the ref. */} + + + + + Update {runnerName} now? + + + Running turns are interrupted and resumed after the update. Open + terminals close, and any tool call in progress is lost. + +
    + Cancel + +
    +
    +
    + ); +} + export function RunnerUpdateStatus({ runner }: { runner: Runner }) { const start = useStartRunnerUpdate(runner.id); const { attempt, available, result, previousBuildAgents } = runner.update ?? {}; + const pending = + start.isPending && typeof start.variables === "object" + ? start.variables.action + : undefined; // A refusal is stale once an update is running or has landed. const error = (attempt && attempt.phase !== "draining") || @@ -137,9 +210,14 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { detail = attempt.phase === "draining" ? `Waiting on ${agents}` - : attempt.phase === "resuming" - ? `Resuming ${agents}` - : PHASES[attempt.phase]; + : attempt.phase === "interrupting" + ? // Not counted until Dispatch has looked at the runner's hosts. + attempt.agents + ? `Interrupting ${agents}` + : "Interrupting agents…" + : attempt.phase === "resuming" + ? `Resuming ${agents}` + : PHASES[attempt.phase]; } else if (result && (failed || !available)) { ({ title, detail } = describeResult(result)); } else if (available) { @@ -177,6 +255,7 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { )} {attempt?.held && attempt.phase !== "draining" && + attempt.phase !== "interrupting" && attempt.phase !== "resuming" && (

    New work waits until the update finishes.

    )} @@ -201,17 +280,29 @@ export function RunnerUpdateStatus({ runner }: { runner: Runner }) { )}
    {attempt?.phase === "draining" && ( - - start.mutate({ action: "cancel", attemptId: attempt.id }) - } - > - Cancel - +
    + + start.mutate({ action: "cancel", attemptId: attempt.id }) + } + > + Cancel + + + start.mutate({ action: "force", attemptId: attempt.id }) + } + /> +
    )} {!attempt && available && ( api<{ attemptId: string }>( `/api/v1/runners/${encodeURIComponent(runnerId)}/update`, diff --git a/packages/shared/src/runner-update-types.ts b/packages/shared/src/runner-update-types.ts index 4afb23a16..0ab184d4d 100644 --- a/packages/shared/src/runner-update-types.ts +++ b/packages/shared/src/runner-update-types.ts @@ -4,6 +4,8 @@ export type RunnerUpdatePhaseView = | "staging" | "settling" | "draining" + /** Update now: turns are being interrupted and hosts stopped. */ + | "interrupting" | "resuming" | "switching" | "confirming" From 890f03c484244983799dcc7c4af995b0d04e3ae2 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sun, 22 Nov 2026 00:20:48 -0700 Subject: [PATCH 311/642] Check that only an operator can force a runner update Co-Authored-By: Claude Opus 5.5 --- apps/server/test/runner-routes.test.ts | 46 +++++++++++++++----------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/apps/server/test/runner-routes.test.ts b/apps/server/test/runner-routes.test.ts index 9dbd140a6..0856d76e1 100644 --- a/apps/server/test/runner-routes.test.ts +++ b/apps/server/test/runner-routes.test.ts @@ -72,15 +72,21 @@ describe("runner control API", () => { const url = "/api/v1/runners/rnr_missing/update"; const hostToken = await ctx.auth.getOrCreateAuthToken(ctx.pool); const scoped = ctx.auth.createAgentMcpToken(hostToken, "agt_fixture"); - const denied = await ctx.app.inject({ - method: "POST", - url, - headers: { authorization: `Bearer ${scoped}` }, - payload: { action: "update" }, - }); - expect(denied.statusCode).toBe(401); + for (const action of ["update", "force"]) { + const denied = await ctx.app.inject({ + method: "POST", + url, + headers: { authorization: `Bearer ${scoped}` }, + payload: { action }, + }); + expect(denied.statusCode).toBe(401); + } const cookie = await ctx.sessionCookie(); - for (const payload of [{}, { action: "force" }, { action: "drain" }]) { + for (const payload of [ + {}, + { action: "force", attemptId: 7 }, + { action: "drain" }, + ]) { const invalid = await ctx.app.inject({ method: "POST", url, @@ -89,17 +95,19 @@ describe("runner control API", () => { }); expect(invalid.statusCode).toBe(400); } - const missing = await ctx.app.inject({ - method: "POST", - url, - headers: { cookie }, - payload: { action: "update" }, - }); - expect(missing.statusCode).toBe(404); - expect(missing.json()).toEqual({ - error: "Runner not found.", - code: "not_found", - }); + for (const action of ["update", "force"]) { + const missing = await ctx.app.inject({ + method: "POST", + url, + headers: { cookie }, + payload: { action }, + }); + expect(missing.statusCode).toBe(404); + expect(missing.json()).toEqual({ + error: "Runner not found.", + code: "not_found", + }); + } }); it("creates, lists and revokes a registration", async () => { From 084604a14bfdb589009bcfd6593eea500d4a1558 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sun, 22 Nov 2026 00:55:47 -0700 Subject: [PATCH 312/642] Let Stop and Archive through while a runner drain waits A waiting drain holds the runner's work for up to two hours but does not fence the runner. Stop and archive now pass then, and an agent they end loses its resume entry. They still wait for the fenced phases. A host restart keeps waiting, outside the lifecycle lock so a stop can win. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/manager.ts | 46 ++++++++-- .../src/agents/remote/update-coordinator.ts | 40 ++++++++- apps/server/src/agents/remote/update-hold.ts | 41 ++++++++- .../test/db/runner-update-force.test.ts | 85 +++++++++++++++++++ .../db/runner-update-hold-manager.test.ts | 15 ++++ .../runner-update-coordinator-fixtures.ts | 1 + 6 files changed, 217 insertions(+), 11 deletions(-) diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index e5bf6e908..87c5fddca 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -2770,7 +2770,8 @@ export class AgentManager { */ private async whileFenced( agent: AgentRecord, - step: () => Promise + step: () => Promise, + kind: "stop" | "other" = "other" ): Promise { const placement = remotePlacement(agent.cwd); for (;;) { @@ -2783,7 +2784,7 @@ export class AgentManager { !this.holds?.isHeld(placement.runner) ) throw error; - await this.holds.wait(placement.runner); + await this.holds.wait(placement.runner, kind); await this.assertLifecycleCurrent(agent); } } @@ -3252,9 +3253,26 @@ export class AgentManager { * A host that is not running is just started. */ async restartHost(id: string): Promise { - return this.serializeLifecycle(id, async () => - this.restartHostLocked(await this.getRequiredAgent(id)) - ); + let waited = false; + for (;;) { + let heldRunner: string | undefined; + const result = await this.serializeLifecycle(id, async () => { + const agent = await this.getRequiredAgent(id); + if (agent.status === "running") { + const runner = remotePlacement(agent.cwd)?.runner; + if (runner && this.holds?.isHeld(runner)) { + heldRunner = runner; + return agent; + } + } else if (waited) return agent; + return this.restartHostLocked(agent); + }); + if (!heldRunner) return result; + // A restart can't come back until the hold opens, so unlike a stop it + // waits, and outside the lock so a stop or archive can still win. + await this.holds!.wait(heldRunner); + waited = true; + } } private async restartHostLocked( @@ -3346,6 +3364,16 @@ export class AgentManager { return [...this.runnerDrainReceipts.values()].some((ids) => ids.has(id)); } + /** Resume entries a stop, archive or delete has ended. */ + async endedRunnerResumes(ids: string[]): Promise { + const running = new Set( + (await this.updateResumeSnapshot(ids)).map(({ id }) => id) + ); + return ids.filter( + (id) => !running.has(id) || this.stoppingOrArchiving.has(id) + ); + } + /** Legacy identities can be absent from the runner's retained list. */ async runnerDrainHosts(runnerId: string, retainedIds: string[]) { this.runtime.wakeRunnerDrain?.(runnerId); @@ -3631,7 +3659,8 @@ export class AgentManager { } // The stop hook and the stop run on the runner; its update fence would - // refuse both. Wait for a held runner first, with the agent untouched. + // refuse both. Wait for it first, with the agent untouched. A drain that + // is only waiting has no fence, and lets both through. if (placement && this.holds) { await this.holds.wait(placement.runner, "stop"); agent = await this.getRequiredAgent(id); @@ -3656,7 +3685,8 @@ export class AgentManager { agent, this.logger, { local: this.localRunner, remote: this.remote }, - (request) => this.whileFenced({ ...agent, status: "stopping" }, request) + (request) => + this.whileFenced({ ...agent, status: "stopping" }, request, "stop") ); } catch (err) { if (err instanceof LifecycleSuperseded) return this.getRequiredAgent(id); @@ -4099,7 +4129,7 @@ export class AgentManager { return current?.status === "archiving" && current.cwd === agent.cwd; }, whileFenced: (agent: AgentRecord, request: () => Promise) => - this.whileFenced(agent, request), + this.whileFenced(agent, request, "stop"), }), }; } diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index 96509157c..e3f235a91 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -241,6 +241,7 @@ type CoordinatorAgents = Pick< | "resumeRunnerDrainHost" | "abandonRunnerResume" | "setRunnerDrainReceipt" + | "endedRunnerResumes" > & { runnerForce: Pick< AgentManager["runnerForce"], @@ -286,7 +287,10 @@ export class RunnerUpdateCoordinator { constructor( private readonly options: { service: CoordinatorService; - holds: Pick; + holds: Pick< + RunnerUpdateHolds, + "begin" | "current" | "release" | "setDrainWaiting" + >; agents: CoordinatorAgents; store: RunnerUpdateStore; /** This controller's signed update builds, by architecture. */ @@ -1002,6 +1006,11 @@ export class RunnerUpdateCoordinator { epoch: number ) { const { agents } = this.options; + const ended = await this.endedResumes(attempt); + if (ended.size) { + attempt = withoutResumes(attempt, ended); + await this.save({ ...this.records.get(runnerId), runnerId, attempt }); + } const drain = attempt.drain!; const mayStop = () => !this.closed && @@ -1303,6 +1312,22 @@ export class RunnerUpdateCoordinator { } } + /** Entries a stop, archive or delete ended: nothing to resume. */ + private async endedResumes(attempt: Attempt): Promise> { + const ids = attempt.drain?.agents.map(({ id }) => id) ?? []; + if (!ids.length) return new Set(); + try { + return new Set(await this.options.agents.endedRunnerResumes(ids)); + } catch (error) { + this.options.logger.warn( + { err: error, attemptId: attempt.id }, + "could not check runner update resume entries" + ); + // Resuming checks each one again. + return new Set(); + } + } + private receipt(runnerId: string, attemptId: string): RunnerResumeAgent[] { const attempt = this.active(runnerId); return attempt?.id === attemptId ? (attempt.drain?.agents ?? []) : []; @@ -1628,6 +1653,11 @@ export class RunnerUpdateCoordinator { } private syncReceipt({ runnerId, attempt }: RunnerUpdateRecord) { + this.options.holds.setDrainWaiting( + runnerId, + attempt.id, + attempt.phase === "draining" && !attempt.outcome + ); if (attempt.drain) this.options.agents.setRunnerDrainReceipt( runnerId, @@ -1717,6 +1747,14 @@ function versionOrder(left: string, right: string) { } } +function withoutResumes(attempt: Attempt, ids: Set): Attempt { + const drain = attempt.drain!; + return { + ...attempt, + drain: { ...drain, agents: drain.agents.filter(({ id }) => !ids.has(id)) }, + }; +} + function sameSessions( left: RetainedSession[] | undefined, right: RetainedSession[] | undefined diff --git a/apps/server/src/agents/remote/update-hold.ts b/apps/server/src/agents/remote/update-hold.ts index 0106d8cd1..2b5f3609a 100644 --- a/apps/server/src/agents/remote/update-hold.ts +++ b/apps/server/src/agents/remote/update-hold.ts @@ -10,7 +10,8 @@ import { privateStateFile } from "./update-state-file.js"; * reaching the runner. Prompts and scheduled occurrences wait in the agent * runtime's own queue (the same gate a disconnected runner uses), launches * are recorded here before any attempt is made, and stop/discard wait on - * the gate. Nothing here decides when to update; a coordinator begins a + * the gate, except while a drain waits for its agents: the runner is not + * fenced then. Nothing here decides when to update; a coordinator begins a * hold for one attempt and releases it with an outcome. * * A hold is bounded: it opens by itself at `expiresAt` (outcome `expired`) @@ -187,6 +188,8 @@ export class RunnerUpdateHolds { private readonly releaseListeners = new Set< (release: RunnerHoldRelease) => void | Promise >(); + /** Runner → the attempt whose drain is waiting, so it isn't fenced. */ + private readonly drainWaits = new Map(); private readonly counters = new Set< (runnerId: string) => Partial >(); @@ -317,6 +320,7 @@ export class RunnerUpdateHolds { const hold = this.holds.get(runnerId); if (!hold || hold.attemptId !== attemptId) return false; this.holds.delete(runnerId); + this.drainWaits.delete(runnerId); clearTimeout(hold.timer); // Recorded with the release, in the same write. this.resuming.push(...hold.launches.map((l) => ({ ...l, runnerId }))); @@ -365,9 +369,42 @@ export class RunnerUpdateHolds { return hold && snapshot(hold); } - /** Resolves once the runner is not held (now, if it is not). */ + /** + * Whether this attempt's drain is waiting. Not persisted: the coordinator + * restates it from its saved phase, before it sends that phase's frame. + */ + setDrainWaiting(runnerId: string, attemptId: string, waiting: boolean) { + if (!waiting) { + if (this.drainWaits.get(runnerId) === attemptId) + this.drainWaits.delete(runnerId); + return; + } + this.drainWaits.set(runnerId, attemptId); + if (!this.stopsPass(runnerId)) return; + // A stop that began waiting before the runner released its fence. + const queue = this.waiters.get(runnerId) ?? []; + this.waiters.set( + runnerId, + queue.filter(({ kind, resolve }) => { + if (kind !== "stop") return true; + resolve(); + return false; + }) + ); + } + + private stopsPass(runnerId: string): boolean { + const hold = this.holds.get(runnerId); + return !!hold && this.drainWaits.get(runnerId) === hold.attemptId; + } + + /** + * Resolves once the runner is not held (now, if it is not). A stop also + * resolves while a drain is waiting. + */ wait(runnerId: string, kind: "stop" | "other" = "other"): Promise { if (!this.holds.has(runnerId)) return Promise.resolve(); + if (kind === "stop" && this.stopsPass(runnerId)) return Promise.resolve(); return new Promise((resolve) => { const queue = this.waiters.get(runnerId) ?? []; queue.push({ kind, resolve }); diff --git a/apps/server/test/db/runner-update-force.test.ts b/apps/server/test/db/runner-update-force.test.ts index 3b94a12a9..1e3c573b8 100644 --- a/apps/server/test/db/runner-update-force.test.ts +++ b/apps/server/test/db/runner-update-force.test.ts @@ -430,6 +430,91 @@ describe("agents the user changed during the update", () => { }); }); +describe("stop and archive while a drain waits", () => { + it("go through without the hold opening, and neither agent is resumed", async () => { + world.runner.incompatible = true; + const drained = await world.agent(); + const keeps = await world.agent(); + const stopping = await world.agent(); + const archiving = await world.agent(); + const blocker = await world.agent(); + for (const host of [stopping, archiving, blocker]) + await world.working(host); + const { attemptId } = await world.coordinator.request(RUNNER, "update"); + await world.until( + () => + !drained.alive && !keeps.alive && world.view()?.attempt?.agents === 3 + ); + expect(world.entry(drained.id)).toBeDefined(); + + await world.manager.stopAgent(drained.id); + await world.manager.stopAgent(stopping.id); + expect(await statusOf(stopping.id)).toBe("stopped"); + await world.manager.beginArchive(archiving.id); + await world.manager.executeArchive(archiving.id, { + onPhaseChange() {}, + onComplete() {}, + onError(error) { + throw error; + }, + }); + await world.until( + () => !world.entry(drained.id) && world.view()?.attempt?.agents === 1 + ); + expect(world.view()?.attempt?.phase).toBe("draining"); + expect(world.holds.isHeld(RUNNER)).toBe(true); + expect(stopping.alive || archiving.alive).toBe(false); + expect(await world.manager.getAgent(archiving.id)).toBeNull(); + + await world.coordinator.cancelDrain(RUNNER, attemptId); + await finished("deferred"); + resumedOnce(keeps); + for (const host of [drained, stopping, archiving, blocker]) + expect(host.launches).toHaveLength(1); + expect(await statusOf(drained.id)).toBe("stopped"); + }); + + it("keeps a host restart waiting without holding up a stop", async () => { + world.runner.incompatible = true; + const busy = await world.agent(); + await world.working(busy); + const { attemptId } = await world.coordinator.request(RUNNER, "update"); + await world.until(() => world.view()?.attempt?.phase === "draining"); + const restart = world.manager.restartHost(busy.id); + await world.until(() => (world.holds as any).waiters.get(RUNNER)?.length); + expect(busy.alive).toBe(true); + await world.manager.stopAgent(busy.id); + await world.coordinator.cancelDrain(RUNNER, attemptId); + await finished("deferred"); + await restart; + expect(busy.launches).toHaveLength(1); + expect(await statusOf(busy.id)).toBe("stopped"); + }); + + it("lets a stop through that began waiting before the drain did", async () => { + world.runner.incompatible = true; + const busy = await world.agent(); + const later = await world.agent(); + await world.working(busy); + await world.holds.begin(RUNNER, crypto.randomUUID()); + const waiting = world.holds.current(RUNNER)!.attemptId; + const stop = world.manager.stopAgent(busy.id); + await world.until(() => world.holds.counts(RUNNER).stops === 1); + world.holds.setDrainWaiting(RUNNER, waiting, true); + await stop; + expect(await statusOf(busy.id)).toBe("stopped"); + expect(world.holds.isHeld(RUNNER)).toBe(true); + + // Fenced again: the next one waits. + world.holds.setDrainWaiting(RUNNER, waiting, false); + const next = world.manager.stopAgent(later.id); + await world.until(() => world.holds.counts(RUNNER).stops === 1); + expect(later.alive).toBe(true); + await world.holds.release(RUNNER, waiting, "cancelled"); + await next; + }); +}); + describe("a controller crash", () => { it("after the receipt, before any interrupt", async () => { const busy = await world.agent(); diff --git a/apps/server/test/db/runner-update-hold-manager.test.ts b/apps/server/test/db/runner-update-hold-manager.test.ts index 23e42fc32..9d413c90c 100644 --- a/apps/server/test/db/runner-update-hold-manager.test.ts +++ b/apps/server/test/db/runner-update-hold-manager.test.ts @@ -707,6 +707,21 @@ describe("launches on a runner held for an update", () => { expect(runtime.discard).not.toHaveBeenCalled(); }); + it("retries a refused stop hook once the drain is only waiting", async () => { + const holds = await openHolds(); + const runtime = spyRuntime(); + const manager = managerOn(holds, runtime); + const agent = await manager.createAgent({ cwd: HELD }); + refuseNext.set("checkoutCommand", async () => { + await holds.begin("r1", ATTEMPT); + }); + const stopping = manager.stopAgent(agent.id); + await Promise.race([work.get(holds)!.blocked, stopping]); + holds.setDrainWaiting("r1", ATTEMPT, true); + expect(await stopping).toMatchObject({ status: "stopped" }); + expect(holds.isHeld("r1")).toBe(true); + }); + it("skips retrying the refused stop hook after archive takes over", async () => { const holds = await openHolds(); const runtime = spyRuntime(); diff --git a/apps/server/test/runner-update-coordinator-fixtures.ts b/apps/server/test/runner-update-coordinator-fixtures.ts index ff4502569..f1fbcd3da 100644 --- a/apps/server/test/runner-update-coordinator-fixtures.ts +++ b/apps/server/test/runner-update-coordinator-fixtures.ts @@ -348,6 +348,7 @@ export async function updateWorld( drain.resumed.push({ id, revision: runner.identity.revision }); }), setRunnerDrainReceipt: vi.fn(), + endedRunnerResumes: vi.fn(async (): Promise => []), stopRunnerHostRecycling: vi.fn(), }; const coordinator = new RunnerUpdateCoordinator({ From 5e7fb78d0ac13989925f209cb36359f66bf5ab50 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sun, 22 Nov 2026 01:02:20 -0700 Subject: [PATCH 313/642] End a runner update's resume at a persisted deadline Resuming now has 25 minutes: the 20 a hold allows for switch, rollback and recovery, plus one five-minute resume retry. The hold ends no later, so a launch waiting for a lost runner cannot outlast it. Past the deadline the attempt finishes with its saved result and the reconciler takes the agents. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/manager.ts | 8 +- .../src/agents/remote/update-coordinator.ts | 40 +++++- apps/server/src/agents/remote/update-hold.ts | 17 +++ .../test/db/runner-update-force.test.ts | 117 ++++++++++++++++++ 4 files changed, 176 insertions(+), 6 deletions(-) diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index 87c5fddca..c4bdfea71 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -1329,13 +1329,15 @@ export class AgentManager { ORDER BY created_at` ); for (const row of result.rows) { - // Its launch is held for a runner update and runs when that opens. - if (this.holds?.hasLaunch(row.id) || this.hasRunnerDrainReceipt(row.id)) - continue; + // Set for a receipt's agent too: the reconciler attaches it if the + // update gives up resuming it. this.streamRecorder.setCwd( row.id, remotePlacement(row.cwd) ? row.cwd : (row.workspacePath ?? row.cwd) ); + // Its launch is held for a runner update and runs when that opens. + if (this.holds?.hasLaunch(row.id) || this.hasRunnerDrainReceipt(row.id)) + continue; const attachedToHost = await this.runtime.attach(row.id); if (!remotePlacement(row.cwd) && this.runtime.inspectNativeHost) { try { diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index e3f235a91..13d8e9e70 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -66,6 +66,12 @@ export const UPDATE_TIMING = { interruptMs: 30_000, /** A session that still won't resume after this is a failed start. */ resumeRetryMs: 5 * 60_000, + /** + * For all of recovery: the 20 minutes a hold allows for switch, rollback + * and recovery, and one whole retry after that. Past it the reconciler + * has the agents, however unreachable the runner is. + */ + resumingMs: 25 * 60_000, tickMs: 1_000, } as const; @@ -289,7 +295,7 @@ export class RunnerUpdateCoordinator { service: CoordinatorService; holds: Pick< RunnerUpdateHolds, - "begin" | "current" | "release" | "setDrainWaiting" + "begin" | "current" | "endBy" | "release" | "setDrainWaiting" >; agents: CoordinatorAgents; store: RunnerUpdateStore; @@ -1221,11 +1227,17 @@ export class RunnerUpdateCoordinator { /** * One pass of recovery: one session resumed, and every continuation still * owed offered. Each agent's progress is saved, so a restart takes up - * where this stopped. The hold opens once no entry is left. + * where this stopped. The hold opens once no entry is left, or at the + * phase's deadline whether or not the runner can be reached. */ private async resumeDrain(runnerId: string, attempt: Attempt) { const drain = attempt.drain!; - const { agents, service, logger } = this.options; + const { agents, holds, service, logger } = this.options; + if (this.now() >= attempt.deadline) + return this.abandonResumes(runnerId, attempt); + // A launch whose reply was lost waits for the runner as long as the hold + // lasts, so the hold must not outlast the deadline. + await holds.endBy(runnerId, attempt.id, attempt.deadline); if (drain.agents.length && service.isRegistered(runnerId)) { // A reconnect with an outstanding trial is not an installed build yet. const live = service.selfUpdate(runnerId); @@ -1270,6 +1282,25 @@ export class RunnerUpdateCoordinator { return this.finish(runnerId, attempt, drain.result!); } + /** Out of time: whatever is left is the ordinary reconciler's. */ + private async abandonResumes(runnerId: string, attempt: Attempt) { + const { agents, logger } = this.options; + const { agents: entries, result } = attempt.drain!; + await Promise.all( + entries + .filter((entry) => !entry.resumed) + .map(({ id }) => + // Only a host known to be gone is a failed start. + agents.abandonRunnerResume(runnerId, id).catch(() => false) + ) + ); + logger.warn( + { runnerId, attemptId: attempt.id, agents: entries.length }, + "runner update resume reached its deadline" + ); + return this.finish(runnerId, attempt, result!); + } + private async resumeAgent( runnerId: string, attemptId: string, @@ -1423,6 +1454,7 @@ export class RunnerUpdateCoordinator { await this.record(runnerId, { ...attempt, phase: "resuming", + deadline: this.now() + UPDATE_TIMING.resumingMs, drain: { ...attempt.drain, result: outcome }, }); return; @@ -1648,6 +1680,8 @@ export class RunnerUpdateCoordinator { "could not save runner update state" ); this.records.set(record.runnerId, record); + if (!record.attempt.drain) + this.options.agents.setRunnerDrainReceipt(record.runnerId, []); this.syncReceipt(record); } } diff --git a/apps/server/src/agents/remote/update-hold.ts b/apps/server/src/agents/remote/update-hold.ts index 2b5f3609a..4cb828ceb 100644 --- a/apps/server/src/agents/remote/update-hold.ts +++ b/apps/server/src/agents/remote/update-hold.ts @@ -308,6 +308,23 @@ export class RunnerUpdateHolds { return snapshot(hold); } + /** Bring this attempt's bound forward to `at`. Never moves it later. */ + async endBy(runnerId: string, attemptId: string, at: number) { + const hold = this.holds.get(runnerId); + if (hold?.attemptId !== attemptId || Date.parse(hold.expiresAt) <= at) + return; + hold.expiresAt = new Date(at).toISOString(); + this.arm(hold); + try { + await this.persist(); + } catch (error) { + this.options.logger.error( + { err: error, runnerId, attemptId }, + "could not persist a runner hold's earlier bound" + ); + } + } + /** * Open the gate for this attempt. True exactly once; a stale or repeated * release changes nothing. The record is gone before any work moves. diff --git a/apps/server/test/db/runner-update-force.test.ts b/apps/server/test/db/runner-update-force.test.ts index 1e3c573b8..f07cd404b 100644 --- a/apps/server/test/db/runner-update-force.test.ts +++ b/apps/server/test/db/runner-update-force.test.ts @@ -15,6 +15,7 @@ import { vi, } from "vitest"; +import { RECONNECT_WARNING } from "../../src/agents/reconciler.js"; import { UPDATE_TIMING } from "../../src/agents/remote/update-coordinator.js"; import { continuationId, @@ -515,6 +516,122 @@ describe("stop and archive while a drain waits", () => { }); }); +describe("a runner that stays offline while resuming", () => { + /** Both hosts are down and owed a resume when the runner drops. */ + async function offlineResuming() { + const busy = await world.agent(); + const idle = await world.agent(); + await world.working(busy); + await force(); + await world.activated(); + world.saved.afterWrite = () => { + if (world.attempt()?.phase !== "resuming") return; + world.saved.afterWrite = undefined; + world.disconnect(); + }; + world.swap(); + await world.until(() => !world.saved.afterWrite); + await world.until( + () => + Date.parse(world.saved.holds.holds[0]!.expiresAt) <= + world.attempt()!.deadline + ); + expect(world.view()?.attempt).toMatchObject({ + phase: "resuming", + agents: 2, + }); + return { busy, idle }; + } + + it.each([false, true])( + "ends at the deadline and leaves its agents to the reconciler (controller restarted: %s)", + async (restarted) => { + const { busy, idle } = await offlineResuming(); + const deadline = world.attempt()!.deadline; + if (restarted) world.crash(); + world.advance(UPDATE_TIMING.resumingMs); + if (restarted) await world.restart(); + await world.until( + () => !world.holds.isHeld(RUNNER) && !world.view()?.attempt + ); + + expect(world.attempt()).toMatchObject({ + deadline, + outcome: { state: "updated" }, + }); + expect(world.attempt()?.drain).toBeUndefined(); + for (const host of [busy, idle]) { + expect((world.manager as any).hasRunnerDrainReceipt(host.id)).toBe( + false + ); + } + // Unreachable is not gone. + await world.manager.reconcileAgentStatuses(); + for (const host of [busy, idle]) + expect(await world.manager.getAgent(host.id)).toMatchObject({ + status: "running", + lastError: RECONNECT_WARNING, + }); + world.reconnect(); + await world.manager.reconcileAgentStatuses(); + for (const host of [busy, idle]) { + expect(await statusOf(host.id)).toBe("stopped"); + expect(host.launches).toHaveLength(1); + expect(host.prompts).toEqual([]); + } + } + ); + + it.each([false, true])( + "resumes normally when the runner is back before it (controller restarted: %s)", + async (restarted) => { + const { busy, idle } = await offlineResuming(); + if (restarted) world.crash(); + world.advance(UPDATE_TIMING.resumingMs - 60_000); + if (restarted) await world.restart(); + await world.coordinator.tick(); + expect(world.view()?.attempt?.phase).toBe("resuming"); + world.reconnect(); + await finished(); + resumedOnce(busy); + resumedOnce(idle); + expect(continuations(busy)).toHaveLength(1); + } + ); + + it("brings a cancelled drain's two-hour hold in to the deadline", async () => { + world.runner.incompatible = true; + const drained = await world.agent(); + const busy = await world.agent(); + await world.working(busy); + const { attemptId } = await world.coordinator.request(RUNNER, "update"); + await world.until( + () => !drained.alive && world.view()?.attempt?.agents === 1 + ); + world.disconnect(); + await world.coordinator.cancelDrain(RUNNER, attemptId); + const { deadline } = world.attempt()!; + await world.until( + () => Date.parse(world.saved.holds.holds[0]!.expiresAt) === deadline + ); + world.reconnect(); + await finished("deferred"); + resumedOnce(drained); + }); + + it("fails what it can tell is gone", async () => { + const { busy, idle } = await offlineResuming(); + busy.resumeFails = idle.resumeFails = true; + world.advance(UPDATE_TIMING.resumingMs - 60_000); + world.reconnect(); + await world.until(() => world.entry(busy.id)?.failedAt); + world.advance(60_000); + await finished(); + for (const host of [busy, idle]) + expect(await statusOf(host.id)).toBe("error"); + }); +}); + describe("a controller crash", () => { it("after the receipt, before any interrupt", async () => { const busy = await world.agent(); From 661a60a8b2cc78e7f026838d88a9c0753f97415f Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sun, 22 Nov 2026 01:04:31 -0700 Subject: [PATCH 314/642] Stop probing every host each second while a drain waits A host attached on the runner's current connection counts as alive without asking. Others are asked, and reattached, at most every ten seconds, and only fresh answers end the wait. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/agents/manager.ts | 28 ++++++++-- .../src/agents/remote/update-coordinator.ts | 31 +++++++++- .../test/db/runner-update-force.test.ts | 56 +++++++++++++++++++ .../test/helpers/runner-force-fixture.ts | 7 +++ 4 files changed, 115 insertions(+), 7 deletions(-) diff --git a/apps/server/src/agents/manager.ts b/apps/server/src/agents/manager.ts index c4bdfea71..727e66f63 100644 --- a/apps/server/src/agents/manager.ts +++ b/apps/server/src/agents/manager.ts @@ -3376,8 +3376,17 @@ export class AgentManager { ); } - /** Legacy identities can be absent from the runner's retained list. */ - async runnerDrainHosts(runnerId: string, retainedIds: string[]) { + /** + * The runner's hosts that may still be alive. Legacy identities can be + * absent from its retained list. A waiting drain passes its connection and + * what the runner last answered: a host attached on that connection needs + * no question, and any other is asked only when it has no answer yet. + */ + async runnerDrainHosts( + runnerId: string, + retainedIds: string[], + waiting?: { epoch: number; answers: Map } + ) { this.runtime.wakeRunnerDrain?.(runnerId); const hosts = new Map( (this.runtime.runnerHosts?.(runnerId) ?? []).map((host) => [ @@ -3403,13 +3412,22 @@ export class AgentManager { ]); const inventory = await Promise.all( [...ids].map(async (id) => { + const host = hosts.get(id); + if (waiting && host?.attachedEpoch === waiting.epoch) { + waiting.answers.delete(id); + return { id, host }; + } + const answer = waiting?.answers.get(id); + if (answer !== undefined) return answer ? { id, host } : null; try { - if ((await this.runtime.runnerHostAlive?.(runnerId, id)) === false) - return null; + const alive = + (await this.runtime.runnerHostAlive?.(runnerId, id)) !== false; + waiting?.answers.set(id, alive); + return alive ? { id, host } : null; } catch { + waiting?.answers.set(id, true); return { id, host: undefined }; } - return { id, host: hosts.get(id) }; }) ); return inventory.filter((entry) => entry !== null); diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index 13d8e9e70..632a59720 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -58,6 +58,8 @@ export const UPDATE_TIMING = { cancelMs: 15_000, rollbackMs: 60_000, confirmRetryMs: 5_000, + /** How often a waiting drain asks about the hosts it isn't attached to. */ + drainProbeMs: 10_000, /** A forced update has this long to empty the runner. */ interruptingMs: 3 * 60_000, /** For every host to attach and report its turn. */ @@ -272,6 +274,11 @@ export class RunnerUpdateCoordinator { private readonly trials = new Map(); private readonly confirms = new Map(); private readonly waiting = new Map(); + /** What a waiting drain was last told about hosts it isn't attached to. */ + private readonly probes = new Map< + string, + { epoch: number; at: number; answers: Map } + >(); /** Cancelled or forced: their drain stops no more hosts. */ private readonly endingDrains = new Set(); private readonly attaching = new Set(); @@ -1024,7 +1031,25 @@ export class RunnerUpdateCoordinator { this.now() < attempt.deadline && this.options.service.connectionEpoch(runnerId) === epoch && this.options.holds.current(runnerId)?.attemptId === attempt.id; - const hosts = await agents.runnerDrainHosts(runnerId, drain.retainedIds); + let probe = this.probes.get(runnerId); + const now = this.now(); + if ( + probe?.epoch !== epoch || + now - probe.at >= UPDATE_TIMING.drainProbeMs + ) { + probe = { epoch, at: now, answers: new Map() }; + this.probes.set(runnerId, probe); + } + const known = new Set(probe.answers.keys()); + const ask = () => + agents.runnerDrainHosts(runnerId, drain.retainedIds, probe); + let hosts = await ask(); + if (!hosts.length && known.size) { + // Only fresh answers end the wait. + probe.answers.clear(); + known.clear(); + hosts = await ask(); + } if (!mayStop()) return; const waiting = new Set(hosts.map(({ id }) => id)).size; this.waiting.set(runnerId, waiting); @@ -1046,7 +1071,8 @@ export class RunnerUpdateCoordinator { for (const { id, host } of hosts) { if (!mayStop()) return; if (host?.attachedEpoch !== epoch) { - this.attach(runnerId, id); + // Attaching asks the runner too, so no more often than the probe. + if (!known.has(id)) this.attach(runnerId, id); continue; } await agents.stopRunnerHostForDrain( @@ -1460,6 +1486,7 @@ export class RunnerUpdateCoordinator { return; } this.waiting.delete(runnerId); + this.probes.delete(runnerId); if (attempt.drain?.force) this.options.agents.runnerForce.release(runnerId); const { target } = attempt; let { confirmed, failed } = this.records.get(runnerId) ?? {}; diff --git a/apps/server/test/db/runner-update-force.test.ts b/apps/server/test/db/runner-update-force.test.ts index f07cd404b..f69f66471 100644 --- a/apps/server/test/db/runner-update-force.test.ts +++ b/apps/server/test/db/runner-update-force.test.ts @@ -516,6 +516,62 @@ describe("stop and archive while a drain waits", () => { }); }); +describe("liveness while a drain waits", () => { + it("asks only about hosts it isn't attached to, and only every ten seconds", async () => { + world.runner.incompatible = true; + const busy = await world.agent(); + const idle = await world.agent(); + const detached = await world.agent(); + await world.working(busy); + detached.attachFails = true; + detached.socket!.destroy(); + await vi.waitFor(() => + expect( + (world.manager as any).runtime + .runnerHosts(RUNNER) + .find((h: { agentId: string }) => h.agentId === detached.id) + ?.attachedEpoch + ).toBeUndefined() + ); + await world.coordinator.request(RUNNER, "update"); + await world.until(() => !idle.alive && world.view()?.attempt?.agents === 2); + await world.coordinator.tick(); + // Attaches run beside the pass that started them. + await vi.waitFor(() => + expect((world.coordinator as any).attaching.size).toBe(0) + ); + const hosts = [busy, idle, detached]; + for (const host of hosts) host.asked = 0; + for (let i = 0; i < 5; i++) await world.coordinator.tick(); + expect(hosts.map(({ asked }) => asked)).toEqual([0, 0, 0]); + + world.advance(UPDATE_TIMING.drainProbeMs); + await world.coordinator.tick(); + expect(busy.asked).toBe(0); + expect(idle.asked).toBe(1); + expect(detached.asked).toBeGreaterThan(0); + }); + + it("ends the wait only on fresh answers", async () => { + world.runner.incompatible = true; + const busy = await world.agent(); + const gone = await world.agent(); + await world.working(busy); + await world.coordinator.request(RUNNER, "update"); + await world.until(() => !gone.alive && world.view()?.attempt?.agents === 1); + await world.coordinator.tick(); + // Back, as a launch admitted before the hold would be. + gone.alive = gone.attachFails = true; + gone.asked = 0; + busy.settle(); + await world.until(() => !busy.alive && gone.asked > 0); + expect(world.view()?.attempt).toMatchObject({ + phase: "draining", + agents: 1, + }); + }); +}); + describe("a runner that stays offline while resuming", () => { /** Both hosts are down and owed a resume when the runner drops. */ async function offlineResuming() { diff --git a/apps/server/test/helpers/runner-force-fixture.ts b/apps/server/test/helpers/runner-force-fixture.ts index 65b9dd198..022354798 100644 --- a/apps/server/test/helpers/runner-force-fixture.ts +++ b/apps/server/test/helpers/runner-force-fixture.ts @@ -104,6 +104,9 @@ export type Host = { interrupts: number[]; launches: { launchId?: string; resume: string | null }[]; stops: number; + /** Times the runner was asked whether it is alive. */ + asked: number; + attachFails: boolean; socket?: Duplex; append(event: object): void; startTurn(text?: string, source?: PromptSource): void; @@ -153,6 +156,8 @@ export async function forceWorld(pool: Pool) { interrupts: [], launches: [], stops: 0, + asked: 0, + attachFails: false, append(event) { const entry = { seq: created.journal.length + 1, @@ -332,11 +337,13 @@ export async function forceWorld(pool: Pool) { } case "attach": { if (!h.alive) throw new RunnerUnavailable("no host"); + if (h.attachFails) throw new Error("attach failed"); const socket = channel(h); channels.add(socket); return { value: true, channel: socket }; } case "alive": + h.asked++; return { value: h.alive }; case "stop": h.stops++; From 4c0e847ee47b27bca83da3cec90c872277fb9748 Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sun, 22 Nov 2026 01:05:18 -0700 Subject: [PATCH 315/642] Accept a repeated force only while it is interrupting In any later phase Update now has nothing left to change, so it now answers stale_drain instead of 202. Co-Authored-By: Claude Opus 5.5 --- .../src/agents/remote/update-coordinator.ts | 3 ++- .../test/db/runner-update-force.test.ts | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/apps/server/src/agents/remote/update-coordinator.ts b/apps/server/src/agents/remote/update-coordinator.ts index 632a59720..e09aac1d3 100644 --- a/apps/server/src/agents/remote/update-coordinator.ts +++ b/apps/server/src/agents/remote/update-coordinator.ts @@ -404,7 +404,8 @@ export class RunnerUpdateCoordinator { const valid = (attempt: Attempt | undefined): attempt is Attempt => attempt !== undefined && attempt.id === (attemptId ?? asked?.id) && - (attempt.force === true || attempt.phase === "draining"); + // The second is a repeat of the same click. + (attempt.phase === "draining" || attempt.phase === "interrupting"); const refuse = () => attemptId ? new RunnerUpdateIneligible("stale_drain") diff --git a/apps/server/test/db/runner-update-force.test.ts b/apps/server/test/db/runner-update-force.test.ts index f69f66471..13890d710 100644 --- a/apps/server/test/db/runner-update-force.test.ts +++ b/apps/server/test/db/runner-update-force.test.ts @@ -181,6 +181,32 @@ describe("a forced update", () => { expect(continuations(busy)).toHaveLength(1); }); + it.each([ + "staging", + "settling", + "cancelling", + "resuming", + "switching", + "confirming", + ] as const)("is not asked for again while %s", async (phase) => { + const { attemptId } = await force(); + await world.activated(); + const records = (world.coordinator as any).records; + const record = records.get(RUNNER); + records.set(RUNNER, { + ...record, + attempt: { ...record.attempt, phase }, + }); + await expect( + world.coordinator.forceUpdate(RUNNER, attemptId) + ).rejects.toMatchObject({ code: "stale_drain" }); + await expect(force()).rejects.toMatchObject({ + code: "update_in_progress", + }); + records.set(RUNNER, record); + await updated(); + }); + it("does not share an attempt with a plain update", async () => { const plain = world.coordinator.request(RUNNER, "update"); const forced = world.coordinator.forceUpdate(RUNNER); From 84329568001eaa2908125a4442135ee6f085716a Mon Sep 17 00:00:00 2001 From: Brad Harris Date: Sun, 22 Nov 2026 01:05:34 -0700 Subject: [PATCH 316/642] Make Update now the one filled action while a drain waits Cancel stays the bordered button. Also covers that an agent-scoped token cannot cancel a runner update. Co-Authored-By: Claude Opus 5.5 --- apps/server/test/runner-routes.test.ts | 8 ++++++-- apps/web/src/components/app/runner-update.tsx | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/server/test/runner-routes.test.ts b/apps/server/test/runner-routes.test.ts index 0856d76e1..89ee4e7dc 100644 --- a/apps/server/test/runner-routes.test.ts +++ b/apps/server/test/runner-routes.test.ts @@ -72,12 +72,16 @@ describe("runner control API", () => { const url = "/api/v1/runners/rnr_missing/update"; const hostToken = await ctx.auth.getOrCreateAuthToken(ctx.pool); const scoped = ctx.auth.createAgentMcpToken(hostToken, "agt_fixture"); - for (const action of ["update", "force"]) { + for (const payload of [ + { action: "update" }, + { action: "force" }, + { action: "cancel", attemptId: crypto.randomUUID() }, + ]) { const denied = await ctx.app.inject({ method: "POST", url, headers: { authorization: `Bearer ${scoped}` }, - payload: { action }, + payload, }); expect(denied.statusCode).toBe(401); } diff --git a/apps/web/src/components/app/runner-update.tsx b/apps/web/src/components/app/runner-update.tsx index 5ad86c9f6..5a0bddaef 100644 --- a/apps/web/src/components/app/runner-update.tsx +++ b/apps/web/src/components/app/runner-update.tsx @@ -142,7 +142,7 @@ function UpdateNow({