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: keep a throwing onRunStarted hook from crashing the server on CLI run spawn (#5792)
Adam Eivy441b21244d92
diff --git a/server/services/runner.js b/server/services/runner.jsindex 4353d15792..4cd3eb42ba 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -408,6 +408,20 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scenv: childEnv});+ // Claim the child's 'error' event in the SAME tick as spawn(). Everything+ // between here and the terminal handlers below — stdin delivery, the+ // external-run registration, the onRunStarted hook — can throw, and a throw+ // there leaves a live registered child whose 'error' has no listener; Node+ // re-throws an unhandled ChildProcess 'error' and kills the server process.+ // Buffer until the real handler is wired, then replay it exactly once+ // (same shape as `spawnDirectly` in agentCliSpawning.js).+ let pendingSpawnError = null;+ let handleSpawnError = null;+ childProcess.on('error', (err) => {+ if (handleSpawnError) handleSpawnError(err);+ else pendingSpawnError = err;+ });+// Guard the stdin pipe BEFORE writing: a child that exits before reading it// (bad flag, missing CLI) emits EPIPE, and an unlistened stream 'error' out// here crashes the server. The 'error'/'close' handlers below settle the run.@@ -422,8 +436,13 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc// stopRun/isRunActive/deleteRun account for this host-spawned child process.toolkit.services.runner.registerExternalRun(runId, childProcess);- // Call hooks- runnerConfig.hooks?.onRunStarted?.({ runId, provider: provider.name, model: provider.defaultModel });+ // Call hooks — isolated like every other hook invocation here: a throw would+ // otherwise reject executeCliRun with the child already spawned and+ // registered, leaving the run permanently non-terminal.+ safeSettle(+ () => runnerConfig.hooks?.onRunStarted?.({ runId, provider: provider.name, model: provider.defaultModel }),+ `Run ${runId} onRunStarted hook`,+ );// Set timeout (default 5 min, guard against undefined which would fire immediately)const effectiveTimeout = timeout ?? provider.timeout ?? 300000;@@ -573,14 +592,19 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, screturn finalizationPromise;};- childProcess.on('error', (err) => {+ handleSpawnError = (err) => {void finalizeOnce({ exitCode: -1, spawnError: err });- });+ };childProcess.on('close', (code, signal) => {void finalizeOnce({ exitCode: code, signal });});+ // A failed spawn emits 'error' and commonly 'close' after it; finalizeOnce+ // is idempotent, so replaying the buffered error here settles the run and+ // the later 'close' is a no-op.+ if (pendingSpawnError) handleSpawnError(pendingSpawnError);+return runId;}diff --git a/server/services/runner.test.js b/server/services/runner.test.jsindex 61d1c5e818..e5fc76ea33 100644--- a/server/services/runner.test.js+++ b/server/services/runner.test.js@@ -669,6 +669,76 @@ describe('executeCliRun — stdin pipe containment (#5655)', () => {});});+describe('executeCliRun — spawn-site error containment (#5792)', () => {+ const provider = {+ id: 'codex', command: 'codex', args: [],+ defaultModel: 'codex-configured-default', timeout: 5000,+ };++ it('contains a throwing onRunStarted instead of orphaning the spawned child', async () => {+ // Pre-fix, onRunStarted was the one hook invocation in runner.js not routed+ // through safeSettle: a throw rejected executeCliRun with the child already+ // spawned and registered, and the terminal 'error'/'close' handlers ~150+ // lines below never got wired.+ const child = makeChild();+ spawn.mockReturnValue(child);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ setAIToolkit(fakeToolkit(), {+ dataDir: '/tmp/test-runner',+ hooks: { onRunStarted: () => { throw new Error('started hook boom'); } },+ });++ const onComplete = vi.fn();+ await expect(executeCliRun({+ runId: 'run-started-hook-throws', provider, prompt: 'test prompt',+ workspacePath: TEST_WORKSPACE, onComplete,+ })).resolves.toBe('run-started-hook-throws');++ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('onRunStarted hook threw during recovery'));++ // The run is still fully wired: its terminal handler settles the caller.+ child.emit('close', 0);+ await new Promise((resolve) => setImmediate(resolve));+ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0]).toMatchObject({ success: true });+ errorSpy.mockRestore();+ });++ it('replays an error emitted before setup finishes into the terminal handler exactly once', async () => {+ // An unlistened 'error' on a ChildProcess is re-thrown by Node and kills the+ // server process, so the listener is claimed in the same tick as spawn() and+ // buffered until the real handler exists. onRunStarted fires inside that+ // window, which makes it a faithful stand-in for the racing child.+ const child = makeChild();+ spawn.mockReturnValue(child);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ setAIToolkit(fakeToolkit(), {+ dataDir: '/tmp/test-runner',+ hooks: {+ onRunStarted: () => {+ child.emit('error', Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' }));+ },+ },+ });++ const onComplete = vi.fn();+ await executeCliRun({+ runId: 'run-early-spawn-error', provider, prompt: 'test prompt',+ workspacePath: TEST_WORKSPACE, onComplete,+ });+ await new Promise((resolve) => setImmediate(resolve));++ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0]).toMatchObject({ success: false, errorCategory: 'spawn_error' });++ // Node commonly follows a failed spawn's 'error' with 'close'; the run stays settled once.+ child.emit('close', null);+ await new Promise((resolve) => setImmediate(resolve));+ expect(onComplete).toHaveBeenCalledTimes(1);+ errorSpy.mockRestore();+ });+});+describe('executeCliRun — close handler crash guard', () => {// Drive a codex run whose first write (output) succeeds and second write// (metadata) rejects, so the close handler's recovery path runs. Returns the