Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop recording a lost runner acknowledgement as a spawn refusal (#4615)
[._.]/ Adam Eivy03140dd28ad1
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 8922554aa5..6ba5c68b17 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -41,7 +41,7 @@ import { registerAgent, updateAgent, completeAgent } from './cosAgentLifecycle.j// metadata.json back). That is megabytes and a disk write on a long TUI run —// paid to read one string. Same trap documented at agentWorktreeCleanup.js:562.import { getConfig, updateTask, getTaskById, getAgentRecord } from './cos.js';-import { spawnAgentViaRunner, getRunnerHealth } from './cosRunnerClient.js';+import { spawnAgentViaRunner, getRunnerHealth, classifyRunnerSpawnFailure, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';import { MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.js';import { isRetryHeld } from '../lib/taskRetryHold.js';@@ -847,6 +847,12 @@ export async function spawnViaRunner(agentId, task, opts) {// chain so the TASK is transitioned too — see the catch below. (The TUI arm of// this dispatch owns the equivalent handling inside spawnTuiAgent, where// `finish()` is the idempotent finalizer that runs the same chain.)+ //+ // A throw here therefore means "no child exists": `spawnAgentViaRunner`+ // reconciles an ambiguous transport failure against the runner's own /agents+ // view first and RESOLVES (with `adopted: true`) when the spawn had in fact+ // landed, so the `runnerAgents` entry set above survives and this run is never+ // finalized as a rejection it cannot know occurred (#4615).let result;try {result = await spawnAgentViaRunner({@@ -871,9 +877,14 @@ export async function spawnViaRunner(agentId, task, opts) {});} catch (err) {const message = err?.message || String(err);+ // Reaching here means the spawn rpc's own reconcile found no agent in the+ // runner, so no child is running under this id either way. What is still+ // unknown for an ambiguous failure is WHY — see RUNNER_SPAWN_AMBIGUOUS+ // (#4615).+ const refused = classifyRunnerSpawnFailure(err) === RUNNER_SPAWN_REFUSED;clearTimeout(agentInfo.initializationTimeout);runnerAgents.delete(agentId);- // A handoff that the runner REFUSED (#4540). Recorded as its own boundary+ // A handoff that did not land (#4540). Recorded as its own boundary// rather than left to the failure the finalize below records: "the run// never started because the runner would not take it" and "the run started// and failed" produce the same terminal record today, and only the ledger@@ -883,13 +894,19 @@ export async function spawnViaRunner(agentId, task, opts) {runId,agentId,taskId: task.id,- eventId: `handoff:${agentId}:${runId || 'no-run'}:rejected`,- // `accepted: false` mirrors what the finalize below already concludes. Note- // that the runner spawn path cannot currently tell an explicit refusal from- // an ambiguous transport failure (a lost acknowledgement for a spawn the- // runner DID accept) — a pre-existing conflation this event inherits rather- // than introduces. Tracked in #4615.- data: { to: 'none', accepted: false, reason: message },+ eventId: `handoff:${agentId}:${runId || 'no-run'}:${refused ? 'rejected' : 'unconfirmed'}`,+ // `accepted: false` is a claim only an explicit refusal earns. An+ // ambiguous transport failure never got an answer, so it records the+ // `null` sentinel — "not known to have been accepted" — rather than+ // asserting a rejection the server cannot actually have observed. A+ // diagnostic that reads a lost acknowledgement as a refusal sends the+ // reader after the wrong cause (#4615).+ data: {+ to: 'none',+ accepted: refused ? false : null,+ outcome: refused ? RUNNER_SPAWN_REFUSED : RUNNER_SPAWN_AMBIGUOUS,+ reason: message,+ },});releaseAgentLane({ agentId, success: false, exitCode: 1, executionId, laneName, errorExecutionMessage: message });// Finalize through the SAME chokepoint every other ending uses (#3632).@@ -959,12 +976,26 @@ export async function spawnViaRunner(agentId, task, opts) {agentId,taskId: task.id,eventId: `handoff:${agentId}:${runId || 'no-run'}:cos-runner`,- data: { to: 'cos-runner', accepted: true, pid: result.pid ?? null, providerId: provider.id, laneName: laneName ?? null },+ data: {+ to: 'cos-runner',+ accepted: true,+ pid: result.pid ?? null,+ providerId: provider.id,+ laneName: laneName ?? null,+ // The acknowledgement was lost and the runner turned out to have the+ // agent anyway (#4615). The handoff DID land, so `accepted` stays true —+ // `adopted` is what says the server learned it by asking rather than by+ // being told.+ ...(result.adopted ? { outcome: RUNNER_SPAWN_AMBIGUOUS, adopted: true, reason: result.adoptedReason ?? null } : {}),+ },});// Store PID in persisted state for zombie detectionawait updateAgent(agentId, { pid: result.pid });+ if (result.adopted) {+ emitLog('warn', `Agent ${agentId} spawn acknowledgement was lost (${result.adoptedReason}); adopted the live runner process (PID: ${result.pid})`, { agentId, taskId: task.id, pid: result.pid });+ }emitLog('info', `Agent ${agentId} spawned via runner (PID: ${result.pid})`, { agentId, pid: result.pid });return agentId;}diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.jsindex 47d24a09c4..2d7cc2c465 100644--- a/server/services/agentLifecycle.spawnViaRunner.test.js+++ b/server/services/agentLifecycle.spawnViaRunner.test.js@@ -27,7 +27,10 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('./cosRunnerClient.js', () => ({+// Real module except for the two rpcs: the spawn-failure classifier under test+// stays the production one rather than a copy of itself (#4615).+vi.mock('./cosRunnerClient.js', async (importOriginal) => ({+ ...(await importOriginal()),spawnAgentViaRunner: vi.fn(),// Reported healthy and long-lived so waitForRunnerStability returns on its// first check — the failure under test is the spawn call, not the wait.@@ -116,7 +119,7 @@ vi.mock('./executionLanes.js', () => ({}));import { spawnViaRunner } from './agentLifecycle.js';-import { spawnAgentViaRunner } from './cosRunnerClient.js';+import { spawnAgentViaRunner, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';import { completeAgent, updateAgent } from './cosAgentLifecycle.js';import { completeAgentRun } from './agentRunTracking.js';import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';@@ -127,6 +130,12 @@ import { runnerAgents } from './agentState.js';const REJECTION = 'Command not allowed: grok. Permitted commands: claude, codex';+// The runner ANSWERED and declined. The shape mirrors what `spawnAgentViaRunner`+// stamps on a non-2xx (pinned in cosRunnerClient.test.js); a bare Error would+// classify as AMBIGUOUS, which is the whole point of the split (#4615).+const refusal = (message = REJECTION) =>+ Object.assign(new Error(message), { spawnOutcome: RUNNER_SPAWN_REFUSED, status: 400 });+function runnerOpts() {return {prompt: 'do the thing',@@ -147,12 +156,12 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {});it('resolves instead of throwing, so the caller is not left to log-and-forget', async () => {- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBeNull();});it('finalizes through finalizeAgent with the runner\'s actual error, not a bare completeAgent', async () => {- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());@@ -175,7 +184,7 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {});it('classifies the rejection under the spawn-rejected reason, carrying the runner message', async () => {- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());@@ -187,7 +196,7 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {it('releases the retry hold so the task returns to pending instead of waiting on the orphan sweep', async () => {const task = { id: 'task-1' };- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());await spawnViaRunner('agent-1', task, runnerOpts());@@ -204,7 +213,7 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {});it('still finalizes when releaseRetryHold rejects — the orphan sweep is the fallback, not a crash', async () => {- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());vi.mocked(releaseRetryHold).mockRejectedValueOnce(new Error('task store unreadable'));await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBeNull();@@ -212,7 +221,7 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {});it('drops the runnerAgents entry so the orphan sweep can see the record', async () => {- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());@@ -222,7 +231,7 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {});it('releases the lane and tool execution', async () => {- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());@@ -237,7 +246,7 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {it('cancels the 3s initialization timer so the record cannot flip to "working"', async () => {vi.useFakeTimers();- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());vi.mocked(updateAgent).mockClear();@@ -261,6 +270,54 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {});});+// ─── Ambiguous transport failures (#4615) ────────────────────────────────────++/**+ * A spawn rpc that never got an answer cannot say the run did not start. The+ * rpc reconciles against the runner's own /agents view first, so what reaches+ * `spawnViaRunner` is either a resolved (possibly ADOPTED) spawn or a failure+ * for which no child exists. Both endings are pinned here: the adopted one must+ * NOT be finalized — it is a live run — and the unadopted one must keep the+ * existing non-actionable `spawn-rejected` retry semantics.+ */+describe('spawnViaRunner — an ambiguous spawn failure', () => {+ const transportFailure = () =>+ Object.assign(new Error('fetch failed'), { spawnOutcome: RUNNER_SPAWN_AMBIGUOUS });++ beforeEach(() => {+ vi.clearAllMocks();+ runnerAgents.clear();+ });++ it('keeps an adopted spawn tracked instead of finalizing a live agent as rejected', async () => {+ vi.mocked(spawnAgentViaRunner).mockResolvedValueOnce({ pid: 4242, adopted: true, adoptedReason: 'fetch failed' });++ await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBe('agent-1');++ // Dropping the entry here is what strands the process: nothing local would+ // own its completion event and the orphan sweep skips it either way.+ expect(runnerAgents.has('agent-1')).toBe(true);+ expect(updateAgent).toHaveBeenCalledWith('agent-1', { pid: 4242 });+ expect(finalizeAgent).not.toHaveBeenCalled();+ expect(releaseRetryHold).not.toHaveBeenCalled();+ expect(releaseAgentLane).not.toHaveBeenCalled();+ });++ it('still finalizes as spawn-rejected when the runner does not have the agent', async () => {+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(transportFailure());++ await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBeNull();++ // Unchanged from a refusal: `spawn-rejected` is non-actionable, so the task+ // is budgeted a retry rather than blocked for a human.+ expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({+ completionReason: 'spawn-rejected',+ error: 'fetch failed',+ }));+ expect(runnerAgents.has('agent-1')).toBe(false);+ });+});+// ─── Lifecycle ledger — the handoff boundary (#4540) ─────────────────────────describe('spawnViaRunner — records who owns the process', () => {@@ -290,12 +347,56 @@ describe('spawnViaRunner — records who owns the process', () => {it('records a REFUSED handoff as its own boundary', async () => {// "The runner would not take it" and "it ran and failed" collapse into the// same terminal record; only the ledger can still tell them apart.- vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(refusal());++ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());++ expect(handoffs()).toEqual([expect.objectContaining({+ eventId: 'handoff:agent-1:run-1:rejected',+ data: expect.objectContaining({ to: 'none', accepted: false, outcome: RUNNER_SPAWN_REFUSED, reason: REJECTION })+ })]);+ });++it('records an AMBIGUOUS handoff as unaccepted-but-unknown, never as a refusal', async () => {+ // The runner never answered, and the spawn rpc's own reconcile found no+ // agent. "Never started" and "refused" are different claims, and only one+ // of them the server can actually have observed (#4615).+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(+ Object.assign(new Error('fetch failed'), { spawnOutcome: RUNNER_SPAWN_AMBIGUOUS })+ );++ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());++ expect(handoffs()).toEqual([expect.objectContaining({+ eventId: 'handoff:agent-1:run-1:unconfirmed',+ data: expect.objectContaining({+ to: 'none',+ accepted: null,+ outcome: RUNNER_SPAWN_AMBIGUOUS,+ reason: 'fetch failed',+ }),+ })]);+ });++ it('records an ADOPTED handoff as accepted, naming the lost acknowledgement', async () => {+ vi.mocked(spawnAgentViaRunner).mockResolvedValueOnce({+ pid: 4242,+ adopted: true,+ adoptedReason: 'fetch failed',+ });await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());expect(handoffs()).toEqual([expect.objectContaining({- data: expect.objectContaining({ to: 'none', accepted: false, reason: REJECTION })+ eventId: 'handoff:agent-1:run-1:cos-runner',+ data: expect.objectContaining({+ to: 'cos-runner',+ accepted: true,+ adopted: true,+ outcome: RUNNER_SPAWN_AMBIGUOUS,+ pid: 4242,+ reason: 'fetch failed',+ }),})]);});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex bcca46080a..b8874e2413 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -27,7 +27,7 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { normalizeReviewers } from '../lib/validation.js';import * as git from './git.js';import { resolveReviewLoopOptions } from './codeReview.js';-import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';+import { spawnTuiSessionViaRunner, classifyRunnerSpawnFailure, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';import { formatShellCommandLine } from '../lib/shellCd.js';import { isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';@@ -1229,17 +1229,28 @@ export async function spawnTuiAgent({? 'command-not-found': useDurableRunner ? 'spawn-rejected' : 'spawn-error';if (useDurableRunner) {- // A handoff the runner REFUSED (#4540), recorded like the CLI path's. A+ // A handoff that did not land (#4540), recorded like the CLI path's. A// LOCAL PTY that won't open is a host problem, not a handoff, so it is// deliberately not recorded here.+ //+ // `accepted: false` is reserved for an explicit refusal. An ambiguous+ // transport failure records the `null` sentinel instead — the spawn rpc+ // already asked the runner whether it has the PTY (and would have adopted+ // it), so what is unknown here is the CAUSE, not the outcome (#4615).+ const refused = classifyRunnerSpawnFailure(err) === RUNNER_SPAWN_REFUSED;await appendRunEvent({kind: 'run.handoff',runId,agentId,taskId: task.id,- eventId: `handoff:${agentId}:${runId || 'no-run'}:rejected`,- // Same refusal-vs-lost-acknowledgement conflation as the CLI path (#4615).- data: { to: 'none', accepted: false, kind: 'tui', reason: message },+ eventId: `handoff:${agentId}:${runId || 'no-run'}:${refused ? 'rejected' : 'unconfirmed'}`,+ data: {+ to: 'none',+ accepted: refused ? false : null,+ outcome: refused ? RUNNER_SPAWN_REFUSED : RUNNER_SPAWN_AMBIGUOUS,+ kind: 'tui',+ reason: message,+ },});}await finish({@@ -1262,8 +1273,21 @@ export async function spawnTuiAgent({agentId,taskId: task.id,eventId: `handoff:${agentId}:${runId || 'no-run'}:cos-runner`,- data: { to: 'cos-runner', accepted: true, kind: 'tui', providerId: provider.id, sessionId: session.sessionId ?? null },+ data: {+ to: 'cos-runner',+ accepted: true,+ kind: 'tui',+ providerId: provider.id,+ sessionId: session.sessionId ?? null,+ // The handoff landed but its acknowledgement was lost; the relay was+ // re-attached to the PTY the runner already had (#4615).+ ...(session.adopted ? { outcome: RUNNER_SPAWN_AMBIGUOUS, adopted: true, reason: session.adoptedReason ?? null } : {}),+ },});+ if (session.adopted) {+ appendLine(`🔁 Spawn acknowledgement lost (${session.adoptedReason}) — re-attached to the live runner PTY`);+ emitLog('warn', `TUI agent ${agentId} spawn acknowledgement was lost; adopted the live runner PTY`, { agentId, taskId: task.id });+ }}// A durable runner can emit tui:exit before its spawn POST response reachesdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 02da3f5079..c71602cac3 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -14,7 +14,11 @@ vi.mock('./shell.js', () => ({registerExternalSession: vi.fn(),}));-vi.mock('./cosRunnerClient.js', () => ({+// Only the spawn rpc is faked. The refusal/ambiguity classifier is the real one+// (importOriginal): re-implementing it here would make the ledger assertions+// below agree with a copy of the rule rather than with the rule (#4615).+vi.mock('./cosRunnerClient.js', async (importOriginal) => ({+ ...(await importOriginal()),spawnTuiSessionViaRunner: vi.fn(),}));@@ -216,7 +220,7 @@ import { readFile } from 'fs/promises';import { execFile } from '../lib/childProcess.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import { releaseRetryHold } from './agentWorktreeCleanup.js';-import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';+import { spawnTuiSessionViaRunner, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';import * as shellService from './shell.js';import * as agentLifecycle from './agentFinalization.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';@@ -2082,6 +2086,74 @@ describe('spawnTuiAgent runtime', () => {);});+ // The ledger has to carry the outcome it actually knows (#4615). A runner+ // that ANSWERED with a refusal and a transport failure that answered+ // nothing are different facts, and a diagnostic that reads the second as+ // the first sends the reader after a rejection that never happened.+ const handoffs = () => appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === 'run.handoff');++ it('records a refused handoff as accepted:false', async () => {+ vi.mocked(spawnTuiSessionViaRunner).mockRejectedValueOnce(+ Object.assign(new Error('Command not allowed: grok'), { spawnOutcome: RUNNER_SPAWN_REFUSED, status: 400 }),+ );++ await runSpawn({ useDurableRunner: true });++ expect(handoffs()).toEqual([expect.objectContaining({+ eventId: 'handoff:agent-1:run-1:rejected',+ data: expect.objectContaining({ to: 'none', accepted: false, outcome: RUNNER_SPAWN_REFUSED, kind: 'tui' }),+ })]);+ });++ it('records an ambiguous handoff as accepted:null with the transport reason', async () => {+ vi.mocked(spawnTuiSessionViaRunner).mockRejectedValueOnce(+ Object.assign(new TypeError('fetch failed'), { spawnOutcome: RUNNER_SPAWN_AMBIGUOUS }),+ );++ await runSpawn({ useDurableRunner: true });++ expect(handoffs()).toEqual([expect.objectContaining({+ eventId: 'handoff:agent-1:run-1:unconfirmed',+ data: expect.objectContaining({+ to: 'none',+ accepted: null,+ outcome: RUNNER_SPAWN_AMBIGUOUS,+ kind: 'tui',+ reason: 'fetch failed',+ }),+ })]);+ });++ it('records an adopted PTY as an accepted handoff and keeps the run alive', async () => {+ // The spawn rpc re-attached the relay to a PTY the runner already had, so+ // this is a live run — it must not be finalized as a failed spawn.+ const spawnDefault = vi.mocked(spawnTuiSessionViaRunner).getMockImplementation();+ vi.mocked(spawnTuiSessionViaRunner).mockImplementationOnce(async (options) => ({+ ...(await spawnDefault(options)),+ adopted: true,+ adoptedReason: 'fetch failed',+ }));++ const spawnPromise = runSpawn({ useDurableRunner: true });+ await flushMicrotasks();++ expect(handoffs()).toEqual([expect.objectContaining({+ eventId: 'handoff:agent-1:run-1:cos-runner',+ data: expect.objectContaining({+ to: 'cos-runner',+ accepted: true,+ adopted: true,+ outcome: RUNNER_SPAWN_AMBIGUOUS,+ reason: 'fetch failed',+ }),+ })]);+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();++ await capturedOnExit({ exitCode: 0, killed: false, signal: null });+ await flushMicrotasks();+ await spawnPromise;+ });+it('keeps the actionable spawn-error when the local PTY path throws', async () => {vi.mocked(shellService.createShellSession).mockImplementationOnce(() => {throw new Error('posix_spawnp failed');diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex b1394f1444..3a555e2f16 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -164,6 +164,103 @@ export function initCosRunnerConnection() {socket.on('agents:orphaned', (data) => dispatch('agents:orphaned', data));}+/**+ * How a runner SPAWN rpc failed (#4615).+ *+ * `refused` — the runner ANSWERED, with a non-2xx: it saw the request and+ * declined it (command missing from its allowlist, malformed args, an agent id+ * already running). No child exists and none ever will, so the caller may+ * safely record that the run never started.+ *+ * `ambiguous` — there was no answer at all: a socket reset, the request+ * timeout, or a response lost after the runner had already accepted and forked+ * the child. "The runner never got it" and "the runner took it and the+ * acknowledgement was lost" are indistinguishable from this side, so this must+ * never be recorded as a refusal — that is what leaves a live agent running in+ * the runner with nothing on the server tracking it, surfacing ~15 minutes+ * later as an orphan attributed to the wrong cause.+ *+ * Anything UNLABELED classifies as ambiguous: only an explicit non-2xx is+ * evidence of a refusal, so absence of evidence must not become one.+ */+export const RUNNER_SPAWN_REFUSED = 'refused';+export const RUNNER_SPAWN_AMBIGUOUS = 'ambiguous';++/** @returns {'refused'|'ambiguous'} how a spawn rpc rejection should be read */+export const classifyRunnerSpawnFailure = (err) =>+ err?.spawnOutcome === RUNNER_SPAWN_REFUSED ? RUNNER_SPAWN_REFUSED : RUNNER_SPAWN_AMBIGUOUS;++const refusedSpawn = (message, status) =>+ Object.assign(new Error(message), { spawnOutcome: RUNNER_SPAWN_REFUSED, status });++const ambiguousSpawn = (err) => {+ const error = err instanceof Error ? err : new Error(String(err));+ error.spawnOutcome = RUNNER_SPAWN_AMBIGUOUS;+ return error;+};++/**+ * Run a spawn POST, splitting a transport failure from an answer.+ * `{ response }` — the runner answered (2xx or not). `{ transportError }` — it+ * did not, which is the ambiguous case above.+ */+const postSpawn = (path, body) =>+ fetchWithTimeout(`${COS_RUNNER_URL}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ }, 60000).then(+ response => ({ response }),+ err => ({ transportError: ambiguousSpawn(err) })+ );++/**+ * Does the runner have this agent after all? (#4615)+ *+ * The runner's own `/agents` view is the authority on what it is running —+ * `syncRunnerAgents` already adopts from it after a server restart, and this is+ * the same adoption a half-second earlier. A probe that cannot be answered+ * returns null: an unanswerable question is not evidence the agent is alive,+ * and the caller falls through to the failure it already had.+ */+const findLiveRunnerAgent = async (agentId) => {+ const agents = await getActiveAgentsFromRunner().catch(err => {+ console.error(`🔌 CoS runner spawn reconcile failed for ${agentId}: ${err.message}`);+ return [];+ });+ return (Array.isArray(agents) ? agents : []).find(agent => agent?.id === agentId) || null;+};++/**+ * Resolve an ambiguous spawn failure by asking the runner (#4615).+ *+ * `adopt(live)` builds the caller's normal success value from the runner's+ * record, or returns null when the record can't be the agent we spawned (a+ * `kind` mismatch). Adoption is stamped so the caller can record in the ledger+ * that this handoff was recovered rather than acknowledged. When the runner+ * does not have the agent, the original transport error is rethrown and the+ * caller's existing failure path runs unchanged.+ */+const reconcileAmbiguousSpawn = async (agentId, transportError, adopt) => {+ const live = await findLiveRunnerAgent(agentId);+ const adopted = live ? adopt(live) : null;+ if (!adopted) throw transportError;+ console.log(`🔁 CoS runner spawn ack lost for ${agentId} (${transportError.message}); adopted its live process (PID: ${live.pid})`);+ return { ...adopted, adopted: true, adoptedReason: transportError.message };+};++/**+ * Re-key the local relay onto the session id the runner reports and hand back a+ * proxy over the SAME handler state, so the `onData`/`onExit` callbacks+ * registered before the lost acknowledgement keep receiving the live PTY.+ */+const adoptTuiRelay = (live, sessionId, state) => {+ const liveSessionId = live.sessionId || sessionId;+ if (liveSessionId !== sessionId) tuiSessions.delete(sessionId);+ tuiSessions.set(liveSessionId, state);+ return createTuiProxy(liveSessionId, live.pid ?? null, state);+};+/*** Spawn a TUI PTY in the durable CoS runner and return a node-pty-compatible* proxy used by the existing Shell/TUI orchestration.@@ -177,18 +274,23 @@ export async function spawnTuiSessionViaRunner(options) {pendingControls: [],};tuiSessions.set(sessionId, state);- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/spawn-tui`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ ...requestOptions, sessionId }),- }, 60000).catch(err => {- tuiSessions.delete(sessionId);- throw err;- });+ const { response, transportError } = await postSpawn('/spawn-tui', { ...requestOptions, sessionId });+ if (transportError) {+ // The relay state stays registered across the probe: if the runner DOES+ // have the PTY, its `tui:output` events must still find these handlers.+ return reconcileAmbiguousSpawn(+ requestOptions.agentId || sessionId,+ transportError,+ live => (live.kind === 'tui' ? adoptTuiRelay(live, sessionId, state) : null)+ ).catch(err => {+ tuiSessions.delete(sessionId);+ throw err;+ });+ }if (!response.ok) {tuiSessions.delete(sessionId);const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to spawn runner-owned TUI session');+ throw refusedSpawn(error.error || 'Failed to spawn runner-owned TUI session', response.status);}const result = await readRunnerJson(response);@@ -291,25 +393,31 @@ export async function spawnAgentViaRunner(options) {claudePath} = options;- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/spawn`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({+ const { response, transportError } = await postSpawn('/spawn', {+ agentId,+ taskId,+ prompt,+ workspacePath,+ model,+ envVars,+ cliCommand,+ cliArgs,+ claudePath+ });++ // No answer at all — the child may already be running. Ask before letting the+ // caller record that the run never started (#4615).+ if (transportError) {+ return reconcileAmbiguousSpawn(agentId,- taskId,- prompt,- workspacePath,- model,- envVars,- cliCommand,- cliArgs,- claudePath- }),- }, 60000);+ transportError,+ live => (live.kind === 'tui' ? null : { pid: live.pid ?? null })+ );+ }if (!response.ok) {const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to spawn agent');+ throw refusedSpawn(error.error || 'Failed to spawn agent', response.status);}return readRunnerJson(response);diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.jsindex f9025bf3fe..fb2d44c91e 100644--- a/server/services/cosRunnerClient.test.js+++ b/server/services/cosRunnerClient.test.js@@ -39,6 +39,9 @@ import {getAgentOutputFromRunner,spawnTuiSessionViaRunner,connectTuiSessionViaRunner,+ classifyRunnerSpawnFailure,+ RUNNER_SPAWN_REFUSED,+ RUNNER_SPAWN_AMBIGUOUS,} from './cosRunnerClient.js';// The client reads the body via text() and tolerantly JSON.parses it, so a@@ -46,8 +49,9 @@ import {// { error: <raw text> } instead of crashing with "Unexpected token <".// A string `data` is treated as a raw (possibly non-JSON) body; an object is// serialized to JSON the way the real runner would respond.-const mockResponse = (ok, data) => ({+const mockResponse = (ok, data, status = ok ? 200 : 500) => ({ok,+ status,text: vi.fn().mockResolvedValue(typeof data === 'string' ? data : JSON.stringify(data))});@@ -276,6 +280,121 @@ describe('cosRunnerClient', () => {});});+ // ===========================================================================+ // Spawn failure discrimination + ambiguous-spawn reconcile (#4615)+ // ===========================================================================+ describe('spawn failures: refusal vs. lost acknowledgement', () => {+ // Route by URL so a spawn POST and the /agents reconcile probe can answer+ // differently within one call.+ const routeFetch = ({ spawn, agents }) => {+ fetchWithTimeout.mockImplementation((url) => {+ if (String(url).includes('/agents')) {+ return typeof agents === 'function' ? agents() : Promise.resolve(mockResponse(true, agents ?? []));+ }+ return typeof spawn === 'function' ? spawn() : Promise.resolve(spawn);+ });+ };+ const transportFailure = () => Promise.reject(new TypeError('fetch failed'));+ const liveCliAgent = { id: 'a1', taskId: 'task-1', pid: 4242, kind: 'cli' };++ it('marks an explicit non-2xx answer as a REFUSAL, carrying the runner status', async () => {+ routeFetch({ spawn: mockResponse(false, { error: 'Command not allowed: grok' }, 400) });++ const err = await spawnAgentViaRunner({ agentId: 'a1' }).catch(e => e);++ expect(err.message).toContain('Command not allowed: grok');+ expect(classifyRunnerSpawnFailure(err)).toBe(RUNNER_SPAWN_REFUSED);+ expect(err.status).toBe(400);+ });++ it('marks a transport failure as AMBIGUOUS, not a refusal', async () => {+ // No answer at all: the runner may have accepted, forked the child, and+ // lost only the acknowledgement. Recording this as a refusal is what+ // strands a live agent with nothing on the server tracking it.+ routeFetch({ spawn: transportFailure, agents: [] });++ const err = await spawnAgentViaRunner({ agentId: 'a1' }).catch(e => e);++ expect(err.message).toContain('fetch failed');+ expect(classifyRunnerSpawnFailure(err)).toBe(RUNNER_SPAWN_AMBIGUOUS);+ });++ it('reads an unlabeled error as ambiguous — only a non-2xx proves a refusal', () => {+ expect(classifyRunnerSpawnFailure(new Error('something else'))).toBe(RUNNER_SPAWN_AMBIGUOUS);+ expect(classifyRunnerSpawnFailure(null)).toBe(RUNNER_SPAWN_AMBIGUOUS);+ });++ it('adopts the live agent when the runner turns out to have it', async () => {+ routeFetch({ spawn: transportFailure, agents: [liveCliAgent] });++ const result = await spawnAgentViaRunner({ agentId: 'a1' });++ expect(result).toEqual({ pid: 4242, adopted: true, adoptedReason: expect.stringContaining('fetch failed') });+ });++ it('rethrows the transport failure when the runner does not have the agent', async () => {+ routeFetch({ spawn: transportFailure, agents: [{ id: 'someone-else', kind: 'cli' }] });++ const err = await spawnAgentViaRunner({ agentId: 'a1' }).catch(e => e);++ expect(err.message).toContain('fetch failed');+ expect(classifyRunnerSpawnFailure(err)).toBe(RUNNER_SPAWN_AMBIGUOUS);+ });++ it('rethrows when the reconcile probe itself cannot be answered', async () => {+ // An unanswerable question is not evidence the agent is alive.+ routeFetch({ spawn: transportFailure, agents: () => Promise.reject(new Error('runner down')) });++ await expect(spawnAgentViaRunner({ agentId: 'a1' })).rejects.toThrow('fetch failed');+ });++ it('does not adopt a TUI record for a CLI spawn of the same id', async () => {+ routeFetch({ spawn: transportFailure, agents: [{ id: 'a1', kind: 'tui', sessionId: 'a1', pid: 9 }] });++ await expect(spawnAgentViaRunner({ agentId: 'a1' })).rejects.toThrow('fetch failed');+ });++ it('never reconciles a refusal — the runner answered, so there is nothing to adopt', async () => {+ routeFetch({ spawn: mockResponse(false, { error: 'Command not allowed: grok' }, 400), agents: [liveCliAgent] });++ await expect(spawnAgentViaRunner({ agentId: 'a1' })).rejects.toThrow('Command not allowed');+ expect(fetchWithTimeout.mock.calls.some(([url]) => String(url).includes('/agents'))).toBe(false);+ });++ it('re-attaches the original TUI handlers to a PTY the runner already had', async () => {+ routeFetch({+ spawn: transportFailure,+ agents: [{ id: 'agent-tui-2', kind: 'tui', sessionId: 'agent-tui-2', pid: 7777 }],+ });+ const onData = vi.fn();++ const session = await spawnTuiSessionViaRunner({+ agentId: 'agent-tui-2',+ taskId: 'task-1',+ command: 'codex',+ args: [],+ onData,+ });++ expect(session).toMatchObject({ sessionId: 'agent-tui-2', pid: 7777, adopted: true });+ // The relay the lost acknowledgement would have discarded is still live:+ // the handler registered before the spawn still receives runner output.+ capturedSocketListeners['tui:output']({ sessionId: 'agent-tui-2', data: 'still working' });+ expect(onData).toHaveBeenCalledWith('still working');+ });++ it('drops the TUI relay when the runner does not have the PTY', async () => {+ routeFetch({ spawn: transportFailure, agents: [] });+ const onData = vi.fn();++ await expect(spawnTuiSessionViaRunner({ agentId: 'agent-tui-3', onData })).rejects.toThrow('fetch failed');++ // Nothing left holding the handlers — a later event for that id is a no-op.+ capturedSocketListeners['tui:output']({ sessionId: 'agent-tui-3', data: 'ghost' });+ expect(onData).not.toHaveBeenCalled();+ });+ });+describe('runner-owned TUI relay', () => {it('spawns a durable PTY and relays output, input, resize, and exit', async () => {fetchWithTimeout.mockResolvedValue(mockResponse(true, {