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 async errors, cap unbounded maps, and parallelize hot paths

[._.]/ Adam Eivy1db5b990d3e7
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index e090d5f961..df488c6f86 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -11,7 +11,7 @@ import { existsSync } from 'fs';
import { spawn } from 'child_process';
import { homedir } from 'os';
import { cosEvents, emitLog } from './cosEvents.js';
-import { updateAgent, completeAgent, appendAgentOutput } from './cosAgents.js';
+import { updateAgent, completeAgent, appendAgentOutput, appendAgentOutputLines } from './cosAgents.js';
import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
import { release } from './executionLanes.js';
import { completeExecution, errorExecution } from './toolStateMachine.js';
@@ -410,48 +410,53 @@ export async function spawnDirectly({
}, 3000);
claudeProcess.stdout.on('data', async (data) => {
- const text = data.toString();
-
- if (!hasStartedWorking) {
- hasStartedWorking = true;
- await updateAgent(agentId, { metadata: { phase: 'working' } });
- emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });
- }
+ try {
+ const text = data.toString();
- if (streamParser) {
- // Parse stream-json and emit extracted text lines (cap buffer at 512KB for error analysis)
- rawStreamBuffer += text;
- if (rawStreamBuffer.length > 512 * 1024) {
- rawStreamBuffer = rawStreamBuffer.slice(-512 * 1024);
+ if (!hasStartedWorking) {
+ hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });
}
- const lines = streamParser.processChunk(text);
- for (const line of lines) {
- outputBuffer += line + '\n';
- await appendAgentOutput(agentId, line);
+
+ if (streamParser) {
+ // Parse stream-json and emit extracted text lines (cap buffer at 512KB for error analysis)
+ rawStreamBuffer += text;
+ if (rawStreamBuffer.length > 512 * 1024) {
+ rawStreamBuffer = rawStreamBuffer.slice(-512 * 1024);
+ }
+ const lines = streamParser.processChunk(text);
+ for (const line of lines) outputBuffer += line + '\n';
+ await appendAgentOutputLines(agentId, lines);
+ await writeFile(outputFile, outputBuffer).catch(() => {});
+ } else {
+ // Non-stream providers: emit raw stdout as before
+ outputBuffer += text;
+ await writeFile(outputFile, outputBuffer).catch(() => {});
+ await appendAgentOutput(agentId, text);
}
- await writeFile(outputFile, outputBuffer).catch(() => {});
- } else {
- // Non-stream providers: emit raw stdout as before
- outputBuffer += text;
- await writeFile(outputFile, outputBuffer).catch(() => {});
- await appendAgentOutput(agentId, text);
+ } catch (err) {
+ console.error(`❌ agentCli stdout handler failed: ${err.message}`);
}
});
claudeProcess.stderr.on('data', async (data) => {
- const text = data.toString();
- // Codex stderr: show thinking + tool names, skip config dump and command output
- if (codexStderrFormatter) {
- for (const line of codexStderrFormatter.processChunk(text)) {
- outputBuffer += line + '\n';
- await appendAgentOutput(agentId, line);
+ try {
+ const text = data.toString();
+ // Codex stderr: show thinking + tool names, skip config dump and command output
+ if (codexStderrFormatter) {
+ const lines = codexStderrFormatter.processChunk(text);
+ for (const line of lines) outputBuffer += line + '\n';
+ await appendAgentOutputLines(agentId, lines);
+ await writeFile(outputFile, outputBuffer).catch(() => {});
+ return;
}
+ outputBuffer += `[stderr] ${text}`;
await writeFile(outputFile, outputBuffer).catch(() => {});
- return;
+ await appendAgentOutput(agentId, `[stderr] ${text}`);
+ } catch (err) {
+ console.error(`❌ agentCli stderr handler failed: ${err.message}`);
}
- outputBuffer += `[stderr] ${text}`;
- await writeFile(outputFile, outputBuffer).catch(() => {});
- await appendAgentOutput(agentId, `[stderr] ${text}`);
});
claudeProcess.on('error', async (err) => {
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 7c988116fa..e5a0ff083d 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -1,5 +1,51 @@
-import { describe, it, expect } from 'vitest';
-import { buildCliSpawnConfig, createStreamJsonParser } from './agentCliSpawning.js';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+// Heavy modules needed only by spawnDirectly — mock them all before importing.
+vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));
+vi.mock('./cosAgents.js', () => ({
+ updateAgent: vi.fn().mockResolvedValue(undefined),
+ completeAgent: vi.fn().mockResolvedValue(undefined),
+ appendAgentOutput: vi.fn().mockResolvedValue(undefined),
+ appendAgentOutputLines: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('./agents.js', () => ({
+ registerSpawnedAgent: vi.fn(),
+ unregisterSpawnedAgent: vi.fn(),
+}));
+vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));
+vi.mock('./toolStateMachine.js', () => ({
+ completeExecution: vi.fn(),
+ errorExecution: vi.fn(),
+}));
+vi.mock('./agentErrorAnalysis.js', () => ({ analyzeAgentFailure: vi.fn().mockResolvedValue(null) }));
+vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('./agentLifecycle.js', () => ({
+ finalizeAgent: vi.fn().mockResolvedValue(undefined),
+ releaseAgentLane: vi.fn(),
+}));
+vi.mock('./agentState.js', () => ({
+ activeAgents: new Map(),
+ userTerminatedAgents: new Set(),
+}));
+vi.mock('../lib/fileUtils.js', () => ({
+ safeJSONParse: (str, fallback) => { try { return JSON.parse(str); } catch { return fallback; } },
+ PATHS: { root: '/tmp', cosAgents: '/tmp/agents', data: '/tmp/data' },
+}));
+vi.mock('../lib/codexCliOutput.js', () => ({ createCodexStderrFormatter: vi.fn() }));
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn().mockResolvedValue('{}'),
+ writeFile: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));
+
+// Mock child_process.spawn to return a controllable fake process
+let fakeProcess;
+vi.mock('child_process', () => ({
+ spawn: vi.fn(() => fakeProcess),
+}));
+
+import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';
// Helper: feed the parser a sequence of stream-json lines
function runStream(parser, events) {
@@ -99,3 +145,125 @@ describe('buildCliSpawnConfig', () => {
expect(config.args).toEqual(['exec', '--model', 'gpt-5.4']);
});
});
+
+describe('stream error containment', () => {
+ // Build a minimal fake process with stdin/stdout/stderr EventEmitters.
+ function makeFakeProcess() {
+ const proc = new EventEmitter();
+ proc.pid = 12345;
+ proc.stdin = { write: vi.fn(), end: vi.fn() };
+ proc.stdout = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ return proc;
+ }
+
+ const minimalArgs = {
+ agentId: 'agent-test',
+ task: { id: 'task-1', description: 'do stuff' },
+ prompt: 'Hello',
+ workspacePath: '/tmp',
+ model: 'claude-3',
+ provider: { id: 'claude-code', type: 'cli', command: 'claude', args: [], envVars: {} },
+ runId: 'run-1',
+ cliConfig: {
+ command: 'claude',
+ args: ['--dangerously-skip-permissions', '--print', '--output-format', 'stream-json', '--verbose', '--include-partial-messages'],
+ stdinMode: 'prompt',
+ streamFormat: 'stream-json',
+ },
+ agentDir: '/tmp',
+ executionId: null,
+ laneName: null,
+ cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined),
+ isTruthyMetaFn: vi.fn().mockReturnValue(false),
+ };
+
+ // Re-import the mocked cosAgents module reference once — mocking is module-scoped.
+ let cosAgentsMocks;
+ beforeEach(async () => {
+ fakeProcess = makeFakeProcess();
+ // Fresh mocked module reference for each test so mockRejectedValueOnce is clean.
+ cosAgentsMocks = await import('./cosAgents.js');
+ // Reset all implementations to their default "resolve" state before each test.
+ cosAgentsMocks.updateAgent.mockResolvedValue(undefined);
+ cosAgentsMocks.completeAgent.mockResolvedValue(undefined);
+ cosAgentsMocks.appendAgentOutput.mockResolvedValue(undefined);
+ cosAgentsMocks.appendAgentOutputLines.mockResolvedValue(undefined);
+ (await import('./agentRunTracking.js')).completeAgentRun.mockResolvedValue(undefined);
+ (await import('./agentLifecycle.js')).finalizeAgent.mockResolvedValue(undefined);
+ minimalArgs.cleanupWorktreeFn.mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('stdout handler catches appendAgentOutputLines rejection and logs ❌ prefix — no unhandled rejection escapes', async () => {
+ // Arrange: make appendAgentOutputLines reject so the handler's catch is exercised.
+ // Use mockRejectedValueOnce so only the first call (during data event) throws;
+ // subsequent calls in the close handler are unaffected.
+ cosAgentsMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('db write failed'));
+
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const unhandledRejections = [];
+ const onUnhandled = (reason) => unhandledRejections.push(reason);
+ process.on('unhandledRejection', onUnhandled);
+
+
+ // Act: start spawnDirectly. Note: spawnDirectly awaits getClaudeSettingsEnv()
+ // before registering stdout/stderr listeners, so we must yield before emitting.
+ const spawnPromise = spawnDirectly(minimalArgs);
+
+ // Yield to let the await inside spawnDirectly resolve so listeners are registered.
+ await new Promise((r) => setTimeout(r, 10));
+
+ // Emit data on stdout to trigger the async handler
+ fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));
+
+ // Give the microtask queue a chance to drain so the async handler runs.
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Trigger close so spawnDirectly resolves
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+
+ process.off('unhandledRejection', onUnhandled);
+
+ // Assert: error was swallowed into console.error, not an unhandled rejection
+ expect(unhandledRejections).toHaveLength(0);
+ const logged = consoleSpy.mock.calls.some(
+ (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agentCli stdout handler failed:')
+ );
+ expect(logged).toBe(true);
+ });
+
+ it('stderr handler catches appendAgentOutput rejection and logs ❌ prefix — no unhandled rejection escapes', async () => {
+ cosAgentsMocks.appendAgentOutput.mockRejectedValueOnce(new Error('stderr db write failed'));
+
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const unhandledRejections = [];
+ const onUnhandled = (reason) => unhandledRejections.push(reason);
+ process.on('unhandledRejection', onUnhandled);
+
+ const spawnPromise = spawnDirectly(minimalArgs);
+
+ // Yield to let the await inside spawnDirectly resolve so listeners are registered.
+ await new Promise((r) => setTimeout(r, 10));
+
+ // Emit data on stderr to trigger the async stderr handler
+ fakeProcess.stderr.emit('data', Buffer.from('some stderr output\n'));
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+
+ process.off('unhandledRejection', onUnhandled);
+
+ expect(unhandledRejections).toHaveLength(0);
+ const logged = consoleSpy.mock.calls.some(
+ (args) => typeof args[0] === 'string' && args[0].startsWith('❌ agentCli stderr handler failed:')
+ );
+ expect(logged).toBe(true);
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 5d59007c0c..ddea59743f 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -429,26 +429,34 @@ export async function spawnTuiAgent({
// comply.
const doneSentinelPath = workspacePath ? join(workspacePath, DONE_SENTINEL_NAME) : null;
const doneSentinelTimer = doneSentinelPath ? setInterval(() => {
- if (finalized) return;
- if (!existsSync(doneSentinelPath)) return;
- clearInterval(doneSentinelTimer);
- readFile(doneSentinelPath, 'utf8')
- .then(contents => {
- const trimmed = contents.trim();
- if (!trimmed) return;
- appendLine(`✅ Agent signaled completion`);
- // Cap at 4 KB so a runaway agent that pasted the entire diff into
- // the sentinel doesn't blow up the agent record / downstream
- // memory-extraction prompts.
- const truncated = trimmed.length > 4096 ? `${trimmed.slice(0, 4096)}\n…[truncated]` : trimmed;
- for (const line of truncated.split('\n')) appendLine(line);
- })
- .catch(() => {})
- .finally(() => {
- finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' }).catch(err => {
- emitLog('error', `Failed to finalize TUI agent ${agentId} after sentinel: ${err.message}`, { agentId });
+ try {
+ if (finalized) return;
+ if (!existsSync(doneSentinelPath)) return;
+ clearInterval(doneSentinelTimer);
+ readFile(doneSentinelPath, 'utf8')
+ .then(contents => {
+ const trimmed = contents.trim();
+ if (!trimmed) return;
+ appendLine(`✅ Agent signaled completion`);
+ // Cap at 4 KB so a runaway agent that pasted the entire diff into
+ // the sentinel doesn't blow up the agent record / downstream
+ // memory-extraction prompts.
+ const truncated = trimmed.length > 4096 ? `${trimmed.slice(0, 4096)}\n…[truncated]` : trimmed;
+ for (const line of truncated.split('\n')) appendLine(line);
+ })
+ .catch(err => console.error(`❌ doneSentinelTimer readFile failed: ${err.message}`))
+ .finally(() => {
+ try {
+ finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' }).catch(err => {
+ emitLog('error', `Failed to finalize TUI agent ${agentId} after sentinel: ${err.message}`, { agentId });
+ });
+ } catch (err) {
+ console.error(`❌ doneSentinelTimer finish call failed: ${err.message}`);
+ }
});
- });
+ } catch (err) {
+ console.error(`❌ doneSentinelTimer interval callback failed: ${err.message}`);
+ }
}, DONE_POLL_INTERVAL_MS) : null;
activeAgents.set(agentId, {
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index f1450e08bc..edff714361 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -509,15 +509,12 @@ export async function exportMedia(items, bucketId) {
export async function exportByKind({ kind, ids, items, bucketId }) {
if (kind === 'series') {
if (!Array.isArray(ids) || ids.length === 0) throw new Error('exportByKind: ids required for series');
- // For v1 we export one series per request; loop if multiple are passed.
- const results = [];
- for (const id of ids) results.push(await exportSeries(id, bucketId));
+ const results = await Promise.all(ids.map((id) => exportSeries(id, bucketId)));
return { exports: results };
}
if (kind === 'universe') {
if (!Array.isArray(ids) || ids.length === 0) throw new Error('exportByKind: ids required for universe');
- const results = [];
- for (const id of ids) results.push(await exportUniverse(id, bucketId));
+ const results = await Promise.all(ids.map((id) => exportUniverse(id, bucketId)));
return { exports: results };
}
if (kind === 'media') {
diff --git a/server/services/toolStateMachine.js b/server/services/toolStateMachine.js
index 2d173cb5a9..f88b5dde3a 100644
--- a/server/services/toolStateMachine.js
+++ b/server/services/toolStateMachine.js
@@ -32,6 +32,7 @@ const TRANSITIONS = {
// In-memory execution storage
const executions = new Map()
+const MAX_EXECUTIONS = 1000
// Execution history (limited to last 1000)
const executionHistory = []
@@ -65,6 +66,10 @@ function createToolExecution(toolId, agentId, metadata = {}) {
createdAt: now
}
+ if (executions.size >= MAX_EXECUTIONS) {
+ const oldestKey = executions.keys().next().value;
+ executions.delete(oldestKey);
+ }
executions.set(executionId, execution)
return execution
}
diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.js
index 9db7c32590..fee851e00c 100644
--- a/server/services/voice/bootstrap.js
+++ b/server/services/voice/bootstrap.js
@@ -231,7 +231,7 @@ const LMS_BASE = () => (process.env.LM_STUDIO_URL || 'http://localhost:1234')
.replace(/\/+$/, '').replace(/\/v1$/, '');
const listLmStudioModels = async () => {
- const res = await fetch(`${LMS_BASE()}/v1/models`).catch(() => null);
+ const res = await fetch(`${LMS_BASE()}/v1/models`, { signal: AbortSignal.timeout(5000) }).catch(() => null);
if (!res?.ok) return [];
const body = await res.json().catch(() => ({}));
return (body?.data || []).map((m) => m.id);
diff --git a/server/services/voice/llm.js b/server/services/voice/llm.js
index 8d6982ac30..85bee89a4b 100644
--- a/server/services/voice/llm.js
+++ b/server/services/voice/llm.js
@@ -96,7 +96,7 @@ const sortBySpeed = (list) => list.slice().sort((a, b) => {
});
const resolveModel = async (requested, { requireTools = false } = {}) => {
- const res = await fetch(`${LM_STUDIO_BASE()}/v1/models`).catch(() => null);
+ const res = await fetch(`${LM_STUDIO_BASE()}/v1/models`, { signal: AbortSignal.timeout(5000) }).catch(() => null);
if (!res || !res.ok) return requested && requested !== 'auto' ? requested : null;
const body = await res.json();
const ids = (body?.data || []).map((m) => m.id);