Skip to content

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

fix: contain failed direct CLI spawns (#5729)

Adam Eivy19e8c421907f
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index fc237ede3d..19c8e65493 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -418,31 +418,45 @@ export async function spawnDirectly({
env: childEnv
});
- registerSpawnedAgent(claudeProcess.pid, {
- fullCommand,
- agentId,
- taskId: task.id,
- model,
- workspacePath: cwd,
- prompt: (task.description || '').substring(0, 500)
+ // spawn() can hand back a handle with no pid or stdio when command lookup
+ // fails. Listen immediately so that failure cannot become an unhandled error
+ // while the async setup below is still yielding.
+ let pendingSpawnError = null;
+ let handleSpawnError = null;
+ claudeProcess.on('error', (err) => {
+ if (handleSpawnError) void handleSpawnError(err);
+ else pendingSpawnError = err;
});
- if (writePromptToStdin) claudeProcess.stdin.write(prompt);
- claudeProcess.stdin.end();
-
- activeAgents.set(agentId, {
- process: claudeProcess,
- taskId: task.id,
- startedAt: Date.now(),
- runId,
- pid: claudeProcess.pid,
- providerId: provider.id,
- executionId,
- laneName
- });
+ const spawnedPid = claudeProcess.pid;
+ if (spawnedPid != null) {
+ registerSpawnedAgent(spawnedPid, {
+ fullCommand,
+ agentId,
+ taskId: task.id,
+ model,
+ workspacePath: cwd,
+ prompt: (task.description || '').substring(0, 500)
+ });
+
+ if (writePromptToStdin && claudeProcess.stdin) claudeProcess.stdin.write(prompt);
+ claudeProcess.stdin?.end();
+
+ activeAgents.set(agentId, {
+ process: claudeProcess,
+ taskId: task.id,
+ startedAt: Date.now(),
+ runId,
+ pid: spawnedPid,
+ providerId: provider.id,
+ executionId,
+ laneName
+ });
- // Store PID in persisted state for zombie detection
- await updateAgent(agentId, { pid: claudeProcess.pid });
+ // Store PID in persisted state for zombie detection only after spawn gave
+ // us a live process identity.
+ await updateAgent(agentId, { pid: spawnedPid });
+ }
let outputBuffer = '';
let rawStreamBuffer = ''; // Raw stdout for stream-json (used for error analysis)
@@ -618,13 +632,14 @@ export async function spawnDirectly({
}
});
- claudeProcess.on('error', async (err) => {
+ handleSpawnError = async (err) => {
// Runs outside the request lifecycle — an uncaught throw from the awaited
// completeAgent/completeAgentRun would crash the process, so wrap the body.
try {
clearTimeout(initializationTimeout);
cleanupPromptFile();
console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);
+ outputBatcher.push(`❌ Agent ${agentId} spawn error: ${err.message}`);
// Release execution lane
if (laneName) {
@@ -656,7 +671,8 @@ export async function spawnDirectly({
console.error(`❌ Agent ${agentId} error handler failed: ${handlerErr.message}`);
activeAgents.delete(agentId);
}
- });
+ };
+ if (pendingSpawnError) void handleSpawnError(pendingSpawnError);
claudeProcess.on('close', async (code) => {
// Runs outside the request lifecycle — a throw from outputBatcher.flush,
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index c114d7ad2c..b8d023fa8b 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -521,12 +521,15 @@ describe('buildCliSpawnConfig', () => {
describe('stream error containment', () => {
// Build a minimal fake process with stdin/stdout/stderr EventEmitters.
- function makeFakeProcess() {
+ function makeFakeProcess({ failWith = null, noStdin = false } = {}) {
const proc = new EventEmitter();
- proc.pid = 12345;
- proc.stdin = { write: vi.fn(), end: vi.fn() };
+ if (!noStdin) {
+ proc.pid = 12345;
+ proc.stdin = { write: vi.fn(), end: vi.fn() };
+ }
proc.stdout = new EventEmitter();
proc.stderr = new EventEmitter();
+ if (failWith) setImmediate(() => proc.emit('error', failWith));
return proc;
}
@@ -578,6 +581,60 @@ describe('stream error containment', () => {
vi.restoreAllMocks();
});
+ describe('spawn failure containment', () => {
+ const failedSpawn = () => makeFakeProcess({
+ noStdin: true,
+ failWith: Object.assign(new Error('spawn claude ENOENT'), { code: 'ENOENT' }),
+ });
+
+ const waitForSpawnFailure = async () => {
+ await new Promise((resolve) => setImmediate(resolve));
+ await new Promise((resolve) => setImmediate(resolve));
+ };
+
+ it('the failing fake really has no stdin (bypass probe)', () => {
+ expect(makeFakeProcess({ noStdin: true }).stdin).toBeUndefined();
+ });
+
+ it('settles with a startup failure when the provider CLI is missing', async () => {
+ fakeProcess = failedSpawn();
+
+ await expect(spawnDirectly(minimalArgs)).resolves.toBe('agent-test');
+ await waitForSpawnFailure();
+
+ expect(agentStateMocks.completeAgent).toHaveBeenCalledWith(
+ 'agent-test',
+ expect.objectContaining({ success: false, error: expect.stringContaining('ENOENT') }),
+ );
+ });
+
+ it('does not leave the agent registered in activeAgents after a failed spawn', async () => {
+ const { activeAgents, registerSpawnedAgent } = await import('./agentState.js');
+ activeAgents.clear();
+ registerSpawnedAgent.mockClear();
+ agentStateMocks.updateAgent.mockClear();
+ fakeProcess = failedSpawn();
+
+ await spawnDirectly(minimalArgs);
+ await waitForSpawnFailure();
+
+ expect(activeAgents.has('agent-test')).toBe(false);
+ expect(registerSpawnedAgent).not.toHaveBeenCalled();
+ expect(agentStateMocks.updateAgent).not.toHaveBeenCalled();
+ });
+
+ it('surfaces the spawn error message to the run log', async () => {
+ agentStateMocks.appendAgentOutputLines.mockClear();
+ fakeProcess = failedSpawn();
+
+ await spawnDirectly(minimalArgs);
+ await waitForSpawnFailure();
+
+ const lines = agentStateMocks.appendAgentOutputLines.mock.calls.flatMap(([, batch]) => batch);
+ expect(lines.some((line) => line.includes('ENOENT'))).toBe(true);
+ });
+ });
+
// ─── Lifecycle ledger — the first-output boundary (#4540) ─────────────────
it('records ONE run.output on the first real byte, and never again', async () => {