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

simplify + extend crash guards to sibling handlers (#1825)

[._.]/ Adam Eivy3ebd4fa43f6b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 00736f662f..dece5b56f7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,5 +17,5 @@
## Fixed
-- **Unguarded async `child_process` handlers can no longer crash the Node process** — several `close`/`error` event handlers were `async` and `await`ed disk writes / completion bookkeeping with no `try/catch`, so a single failed write (e.g. a full disk) surfaced as an unhandled rejection and took down the whole server. Wrapped the at-risk handler bodies in `server/services/runner.js`, `videoTimeline/local.js`, `agentCliSpawning.js`, and the detached `processStream().catch` in `aiToolkit/runner.js`, and replaced the two silent recovery-critical `.catch(() => {})` swallows in `cos-runner/index.js` with logged failures so a lost completion-metadata write is visible instead of silently dropping a finished task. (#1825)
+- **Unguarded async `child_process` handlers can no longer crash the Node process** — several `close`/`error` event handlers were `async` and `await`ed disk writes / completion bookkeeping with no `try/catch`, so a single failed write (e.g. a full disk) or a throwing completion hook surfaced as an unhandled rejection and took down the whole server. Wrapped the at-risk handler bodies in `server/services/runner.js` (both `close` and `error`), `videoTimeline/local.js`, `agentCliSpawning.js` (both `close` and `error`), and both the CLI `close` handler and the detached `processStream().catch` in `aiToolkit/runner.js`. The recovery paths now still settle callers waiting on `onComplete` with failure metadata (so a finalization failure surfaces as a failed run instead of hanging forever), with the completion hook isolated from `onComplete` so a throwing `onRunFailed` can't block the caller from settling. Also replaced the two silent recovery-critical `.catch(() => {})` swallows in `cos-runner/index.js` with logged failures so a lost completion-metadata write is visible instead of silently dropping a finished task. (#1825)
- Catalog "Appears in" panel no longer renders dangling chips that deep-link to soft-deleted universe/series/creative-director targets — the detail page filters refs to live targets only (the orphan stays recoverable via the "Orphaned" album). Also fixed a stale resolver bug where soft-deleted Creative Director projects (#1564) wrongly resolved as live, and extended orphan-bucket detection so a deleted CD project's ex-cast surfaces as orphaned rather than unlinked. (#1812)
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 952fee27bb..7f36457ff8 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -6,6 +6,18 @@ import { spawn } from 'child_process';
import { randomUUID } from 'crypto';
import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';
+// Invoke a completion hook / callback so a throw is logged but never
+// propagates — these run at out-of-request boundaries where an uncaught throw
+// is an unhandled rejection that crashes the process. Each call is isolated so
+// a throwing hook can't prevent a later `onComplete` from settling the caller.
+function safeSettle(fn, label) {
+ try {
+ fn();
+ } catch (err) {
+ console.error(`❌ ${label} threw during recovery: ${err.message}`);
+ }
+}
+
export function createRunnerService(config = {}) {
const {
dataDir = './data',
@@ -249,40 +261,58 @@ export function createRunnerService(config = {}) {
});
childProcess.on('close', async (code) => {
- clearTimeout(timeoutHandle);
- activeRuns.delete(runId);
+ // Runs outside the request lifecycle — an uncaught throw from
+ // atomicWrite/handleProviderError/hooks would surface as an unhandled
+ // rejection and crash the process, so guard the body and still settle
+ // the caller on failure.
+ try {
+ clearTimeout(timeoutHandle);
+ activeRuns.delete(runId);
- await atomicWrite(outputPath, output);
+ await atomicWrite(outputPath, output);
- const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
- metadata.endTime = new Date().toISOString();
- metadata.duration = Date.now() - startTime;
- metadata.exitCode = code;
- metadata.success = code === 0;
- metadata.outputSize = Buffer.byteLength(output);
+ const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.exitCode = code;
+ metadata.success = code === 0;
+ metadata.outputSize = Buffer.byteLength(output);
- if (!metadata.success) {
- const errorAnalysis = analyzeError(output, code);
- metadata.error = errorAnalysis.message || `Process exited with code ${code}`;
- metadata.errorCategory = errorAnalysis.category;
- metadata.errorAnalysis = errorAnalysis;
+ if (!metadata.success) {
+ const errorAnalysis = analyzeError(output, code);
+ metadata.error = errorAnalysis.message || `Process exited with code ${code}`;
+ metadata.errorCategory = errorAnalysis.category;
+ metadata.errorAnalysis = errorAnalysis;
- if (errorAnalysis.hasError &&
- (errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||
- errorAnalysis.category === ERROR_CATEGORIES.USAGE_LIMIT)) {
- await handleProviderError(provider.id, errorAnalysis, output);
+ if (errorAnalysis.hasError &&
+ (errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||
+ errorAnalysis.category === ERROR_CATEGORIES.USAGE_LIMIT)) {
+ await handleProviderError(provider.id, errorAnalysis, output);
+ }
}
- }
- await atomicWrite(metadataPath, metadata);
+ await atomicWrite(metadataPath, metadata);
- if (metadata.success) {
- hooks.onRunCompleted?.(metadata, output);
- } else {
- hooks.onRunFailed?.(metadata, metadata.error, output);
- }
+ if (metadata.success) {
+ hooks.onRunCompleted?.(metadata, output);
+ } else {
+ hooks.onRunFailed?.(metadata, metadata.error, output);
+ }
- onComplete?.(metadata);
+ onComplete?.(metadata);
+ } catch (err) {
+ console.error(`❌ Run ${runId} close handler error: ${err.message}`);
+ const failMetadata = {
+ endTime: new Date().toISOString(),
+ duration: Date.now() - startTime,
+ exitCode: code,
+ success: false,
+ error: `Run finalization failed: ${err.message}`,
+ outputSize: Buffer.byteLength(output),
+ };
+ safeSettle(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);
+ safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);
+ }
});
return runId;
@@ -492,16 +522,8 @@ export function createRunnerService(config = {}) {
error: `Run finalization failed: ${handlerErr.message}`,
outputSize: Buffer.byteLength(output),
};
- try {
- hooks.onRunFailed?.(failMetadata, failMetadata.error, output);
- } catch (hookErr) {
- console.error(`❌ Run ${runId} onRunFailed hook threw during recovery: ${hookErr.message}`);
- }
- try {
- onComplete?.(failMetadata);
- } catch (settleErr) {
- console.error(`❌ Run ${runId} onComplete threw during recovery: ${settleErr.message}`);
- }
+ safeSettle(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);
+ safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);
}
});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index cbaf8f391a..e621772a4c 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -589,6 +589,11 @@ export async function spawnDirectly({
});
claudeProcess.on('close', async (code) => {
+ // Runs outside the request lifecycle — a throw from outputBatcher.flush,
+ // analyzeAgentFailure, or finalizeAgent would re-escape this async handler
+ // as an unhandled rejection and crash the process. The inner try/finally
+ // only covers finalizeAgent's cleanup; this outer guard is the crash net.
+ try {
clearTimeout(initializationTimeout);
const success = code === 0;
const agentData = activeAgents.get(agentId);
@@ -713,6 +718,11 @@ export async function spawnDirectly({
unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
activeAgents.delete(agentId);
}
+ } catch (handlerErr) {
+ console.error(`❌ Agent ${agentId} close handler error: ${handlerErr.message}`);
+ unregisterSpawnedAgent(claudeProcess.pid);
+ activeAgents.delete(agentId);
+ }
});
return agentId;
diff --git a/server/services/runner.js b/server/services/runner.js
index d3a9cf5b47..739fddbcfb 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -39,6 +39,18 @@ export function setAIToolkit(toolkit, config = {}) {
runnerConfig = { dataDir: config.dataDir || './data', hooks: config.hooks || {} };
}
+// Invoke a completion hook / callback so that a throw is logged but never
+// propagates — these run at out-of-request boundaries where an uncaught throw
+// is an unhandled rejection that crashes the process. Each call is isolated so
+// a throwing hook can't prevent a later `onComplete` from settling the caller.
+function safeSettle(fn, label) {
+ try {
+ fn();
+ } catch (err) {
+ console.error(`❌ ${label} threw during recovery: ${err.message}`);
+ }
+}
+
export async function createRun(options) {
// The toolkit's runner emits its own "🤖 AI run [source]: provider/model"
// line — don't duplicate it here.
@@ -233,8 +245,11 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
await writeFile(outputPath, output).catch(() => {});
await writeFile(metadataPath, JSON.stringify(metadata, null, 2)).catch(() => {});
- runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output);
- onComplete?.(metadata);
+ // Isolate the hook from onComplete — a throwing onRunFailed must not block
+ // the caller from settling, and an uncaught throw here would crash the
+ // process (this runs outside the request lifecycle).
+ safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);
+ safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);
});
childProcess.on('close', async (code) => {
@@ -293,16 +308,8 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
errorCategory: 'finalization_error',
outputSize: Buffer.byteLength(output),
};
- try {
- runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output);
- } catch (hookErr) {
- console.error(`❌ Run ${runId} onRunFailed hook threw during recovery: ${hookErr.message}`);
- }
- try {
- onComplete?.(failMetadata);
- } catch (settleErr) {
- console.error(`❌ Run ${runId} onComplete threw during recovery: ${settleErr.message}`);
- }
+ safeSettle(() => runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);
+ safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);
}
});
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 6de24dbefd..cb0837ee5a 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -164,29 +164,33 @@ describe('executeCliRun — Codex sentinel suppression', () => {
});
describe('executeCliRun — close handler crash guard', () => {
- it('does not crash and still settles the caller when a metadata write fails on close', async () => {
+ // Drive a codex run whose first write (output) succeeds and second write
+ // (metadata) rejects, so the close handler's recovery path runs. Returns the
+ // onComplete spy + console.error spy for assertions.
+ async function runWithMetadataWriteFailure(runId, { hooks } = {}) {
const child = makeChild();
spawn.mockReturnValue(child);
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- // First write (output) succeeds, second write (metadata) rejects — the
- // handler runs outside the request lifecycle, so an uncaught throw here
- // would crash the Node process.
writeFile
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new Error('ENOSPC: disk full'));
+ if (hooks) setAIToolkit(fakeToolkit(), { dataDir: '/tmp/test-runner', hooks });
const provider = {
id: 'codex', command: 'codex', args: [],
defaultModel: 'codex-configured-default', timeout: 5000,
};
-
const onComplete = vi.fn();
- await executeCliRun({ runId: 'run-write-fail', provider, prompt: 'test prompt', workspacePath: '/workspace', onComplete });
+ await executeCliRun({ runId, provider, prompt: 'test prompt', workspacePath: '/workspace', onComplete });
child.stdout.emit('data', Buffer.from('output'));
child.emit('close', 0);
- // Let the detached close handler settle.
- await new Promise((resolve) => setImmediate(resolve));
+ await new Promise((resolve) => setImmediate(resolve)); // let the detached handler settle
+ return { onComplete, errorSpy };
+ }
+
+ it('does not crash and still settles the caller when a metadata write fails on close', async () => {
+ const { onComplete, errorSpy } = await runWithMetadataWriteFailure('run-write-fail');
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('run-write-fail close handler error'));
// The caller must still be settled with failure metadata, not left hanging.
@@ -196,31 +200,12 @@ describe('executeCliRun — close handler crash guard', () => {
});
it('still settles onComplete when the recovery onRunFailed hook itself throws', async () => {
- const child = makeChild();
- spawn.mockReturnValue(child);
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- // Metadata write fails, AND the recovery onRunFailed hook throws — the
+ // Metadata write fails AND the recovery onRunFailed hook throws — the
// caller must STILL be settled (the hook must not block onComplete).
- writeFile
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error('ENOSPC: disk full'));
- setAIToolkit(fakeToolkit(), {
- dataDir: '/tmp/test-runner',
+ const { onComplete, errorSpy } = await runWithMetadataWriteFailure('run-hook-throws', {
hooks: { onRunFailed: () => { throw new Error('hook boom'); } },
});
- const provider = {
- id: 'codex', command: 'codex', args: [],
- defaultModel: 'codex-configured-default', timeout: 5000,
- };
-
- const onComplete = vi.fn();
- await executeCliRun({ runId: 'run-hook-throws', provider, prompt: 'test prompt', workspacePath: '/workspace', onComplete });
-
- child.stdout.emit('data', Buffer.from('output'));
- child.emit('close', 0);
- await new Promise((resolve) => setImmediate(resolve));
-
expect(onComplete).toHaveBeenCalledTimes(1);
expect(onComplete.mock.calls[0][0]).toMatchObject({ success: false, errorCategory: 'finalization_error' });
errorSpy.mockRestore();