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
address review (codex): treat a runner 5xx as ambiguous, not a refusal (#4615)
[._.]/ Adam Eivy08df86e247e2
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 3a555e2f16..0f2278c82c 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -167,21 +167,23 @@ export function initCosRunnerConnection() {/*** 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.+ * `refused` — the runner DECIDED against the request: a 4xx, which its spawn+ * routes only ever answer from up-front validation (command missing from the+ * allowlist, malformed args, an agent id already running, an executable that+ * fails the preflight). Nothing was forked, 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.+ * `ambiguous` — everything else. No answer at all (a socket reset, the request+ * timeout, a response lost in flight) AND a 5xx: `POST /spawn` registers and+ * forks the child before its final state persist, so an internal error can be+ * answered with a process already running. "The runner never took it" and "the+ * runner took it and the acknowledgement was lost" are indistinguishable from+ * this side, and recording the second as a refusal 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.+ * Anything UNLABELED classifies as ambiguous: only a 4xx 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';@@ -190,8 +192,12 @@ export const RUNNER_SPAWN_AMBIGUOUS = 'ambiguous';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 });+/** The runner answered a non-2xx. Only the 4xx half is a decision — see above. */+const answeredSpawnFailure = (message, status) =>+ Object.assign(new Error(message), {+ spawnOutcome: status >= 400 && status < 500 ? RUNNER_SPAWN_REFUSED : RUNNER_SPAWN_AMBIGUOUS,+ status,+ });const ambiguousSpawn = (err) => {const error = err instanceof Error ? err : new Error(String(err));@@ -222,6 +228,14 @@ const postSpawn = (path, body) =>* 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.+ *+ * Presence in the runner's map is the whole test; the row's `processActive` is+ * deliberately NOT required. It comes from a `ps` probe that reports `dead` for+ * an exec failure as well as for a real exit, so gating on it would let a+ * flaky `ps` reject a live agent — reintroducing exactly the orphan this+ * reconcile removes. Adopting a row whose process has just exited is harmless+ * here: the caller registered its local ownership BEFORE the spawn rpc, so no+ * completion event can have been dropped for want of an entry.*/const findLiveRunnerAgent = async (agentId) => {const agents = await getActiveAgentsFromRunner().catch(err => {@@ -241,14 +255,23 @@ const findLiveRunnerAgent = async (agentId) => {* 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 reconcileAmbiguousSpawn = async (agentId, failure, 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 };+ if (!adopted) throw failure;+ console.log(`🔁 CoS runner spawn ack lost for ${agentId} (${failure.message}); adopted its live process (PID: ${live.pid})`);+ return { ...adopted, adopted: true, adoptedReason: failure.message };};+/**+ * The single resolution point for a failed spawn rpc: a refusal is final, an+ * ambiguous failure gets the reconcile above first.+ */+const resolveSpawnFailure = (agentId, failure, adopt) =>+ classifyRunnerSpawnFailure(failure) === RUNNER_SPAWN_REFUSED+ ? Promise.reject(failure)+ : reconcileAmbiguousSpawn(agentId, failure, adopt);+/*** 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@@ -275,23 +298,25 @@ export async function spawnTuiSessionViaRunner(options) {};tuiSessions.set(sessionId, state);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(+ const failure = transportError || (response.ok+ ? null+ : answeredSpawnFailure(+ (await readRunnerJson(response)).error || 'Failed to spawn runner-owned TUI session',+ response.status+ ));+ if (failure) {+ // The relay state stays registered across the reconcile: if the runner DOES+ // have the PTY, its `tui:output` events must still find these handlers. It+ // is only torn down once adoption is ruled out.+ return resolveSpawnFailure(requestOptions.agentId || sessionId,- transportError,+ failure,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 refusedSpawn(error.error || 'Failed to spawn runner-owned TUI session', response.status);- }const result = await readRunnerJson(response);const pid = result.pid;@@ -405,21 +430,19 @@ export async function spawnAgentViaRunner(options) {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(+ // Anything but a 4xx may have left a child running. Ask the runner before+ // letting the caller record that the run never started (#4615).+ const failure = transportError || (response.ok+ ? null+ : answeredSpawnFailure((await readRunnerJson(response)).error || 'Failed to spawn agent', response.status));+ if (failure) {+ return resolveSpawnFailure(agentId,- transportError,+ failure,live => (live.kind === 'tui' ? null : { pid: live.pid ?? null }));}- if (!response.ok) {- const error = await readRunnerJson(response);- 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 fb2d44c91e..564c2f66d4 100644--- a/server/services/cosRunnerClient.test.js+++ b/server/services/cosRunnerClient.test.js@@ -307,6 +307,26 @@ describe('cosRunnerClient', () => {expect(err.status).toBe(400);});+ it('reads a 5xx as AMBIGUOUS — the runner forks the child before its final state write', async () => {+ // `POST /spawn` registers and spawns, THEN persists state and answers. An+ // internal error after that point is answered with a process already+ // running, so a 5xx is no more a refusal than a dropped socket is.+ routeFetch({ spawn: mockResponse(false, { error: 'state write failed' }, 500), agents: [liveCliAgent] });++ const result = await spawnAgentViaRunner({ agentId: 'a1' });++ expect(result).toEqual({ pid: 4242, adopted: true, adoptedReason: 'state write failed' });+ });++ it('still fails a 5xx the runner cannot back with a live agent', async () => {+ routeFetch({ spawn: mockResponse(false, { error: 'state write failed' }, 500), agents: [] });++ const err = await spawnAgentViaRunner({ agentId: 'a1' }).catch(e => e);++ expect(err.message).toBe('state write failed');+ expect(classifyRunnerSpawnFailure(err)).toBe(RUNNER_SPAWN_AMBIGUOUS);+ });+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