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: catch rejections in the spawner's task:ready and agent:terminate listeners (#5646)
Adam Eivya54c6384b6a8
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex ff903c164e..7cafebc068 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -364,8 +364,11 @@ describe('self-update spawn gate — funnel coverage (#4124)', () => {it('subAgentSpawner holds the dispatch on the synchronous update flag', () => {const src = readFileSync(join(SERVICES_DIR, 'subAgentSpawner.js'), 'utf-8');expect(src).toMatch(/import \{ isUpdateInProgress \} from '\.\/updateChecker\.js'/);- const idx = src.indexOf("cosEvents.on('task:ready'");- expect(idx, 'the task:ready listener must exist').toBeGreaterThan(-1);+ // The dispatch body lives in `handleTaskReady`, the named function the+ // `task:ready` registration wraps in a `.catch` (a plain EventEmitter would+ // otherwise leak an async listener's rejection).+ const idx = src.indexOf('async function handleTaskReady');+ expect(idx, 'the task:ready dispatch must exist').toBeGreaterThan(-1);const spawnIdx = src.indexOf('await spawnAgentForTask(task)', idx);expect(spawnIdx).toBeGreaterThan(idx);// The hold is BEFORE the spawn, and before the (awaited) runner probe — adiff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 85ea9638ba..2349b8443e 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1493,7 +1493,7 @@ describe('cos.js source — priority + capacity invariants', () => {.toMatch(/acquireLocalEndpointSpawnSlot\(/);// The reservation is only correct if it is released once the spawn settles;// a missing `finally` leaks the slot and wedges the endpoint forever.- const listener = SPAWNER_SRC.slice(SPAWNER_SRC.indexOf("cosEvents.on('task:ready'"));+ const listener = SPAWNER_SRC.slice(SPAWNER_SRC.indexOf('async function handleTaskReady'));expect(listener, 'the acquired slot must be released in a finally').toMatch(/finally\s*\{\s*\n\s*localSlot\.release\(\);/);expect(listener, 'a task at capacity must be HELD (left pending), not failed')diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex d311bd937f..462fccde51 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -142,6 +142,95 @@ export async function loadSlashdoCommand(commandName) {// later call can retry instead of being stuck on a half-initialized spawner.let spawnerInitPromise = null;+/**+ * Dispatch a ready task — the single chokepoint every `task:ready` emitter+ * funnels through.+ *+ * A named function rather than the `.on(...)` callback itself so the+ * registration can attach a `.catch`: `cosEvents` is a plain `EventEmitter`, so+ * it neither awaits nor catches an async listener's promise, and the awaits+ * ahead of the `try` below (`isRunnerReachable`, `forgeSpawnHoldReason`,+ * `loadState`, `holdTask`) would otherwise escape as an unhandled rejection —+ * leaving a queued task silently never dispatched, and surfacing only as a+ * process-level unhandled-rejection toast with no task id in it.+ */+async function handleTaskReady(task) {+ // ── HOLDS, at the one chokepoint all seven `task:ready` emitters funnel+ // through. Each leaves the task queued (no status write, no retry charged)+ // for a condition that clears on its own.+ //+ // Held HERE rather than inside `runAgentSpawn`: a hold below this line would+ // return past `releaseAppReviewMarker`, stranding the synthetic "in review"+ // marker for the whole outage — issue #989's exact failure mode. The+ // releases in `holdTask` are the same ones the spawn body owns.+ //+ // 1. Self-update in progress (issue #4124). `/api/update/execute` refuses to+ // start while an agent is live, but `update.sh` then spends multiple+ // seconds in `git pull` / submodule update / `npm install` before it+ // reaches `pm2 delete` — an agent spawned inside that window is severed+ // by the restart (its PTY/child process is a child of this server). The+ // flag reads synchronously, so nothing can slip between the check and the+ // spawn; the task runs on the other side of the restart.+ if (isUpdateInProgress()) {+ return holdTask(task, 'a PortOS self-update is in progress');+ }+ // 2. Runner down. Dispatching into a stopped runner is not a task failure,+ // but both spawn arms recorded it as one: the CLI arm finalized+ // `spawn-rejected` (a retry each time, so a runner left off overnight+ // walked every queued task through its retry budget into `blocked`), and+ // the TUI arm threw into the actionable `spawn-error`, parking the task+ // for a human over an app the user simply turned off.+ if (useRunner && !(await isRunnerReachable())) {+ return holdTask(task, 'CoS Runner is down');+ }+ // 3. Forge unreachable, for a task that cannot finish without it (#5110). An+ // agent whose task promises a change request does its work, fails to push,+ // and finalizes `forge-unreachable` — non-actionable, so the task retries,+ // and each retry re-runs the whole agent against the same dead network. One+ // VPN drop cost three runs (101 + 50 + 23 minutes) to reach `blocked`. See+ // cosForgeSpawnGate.js for the narrowings that keep the hold from becoming+ // the silent wedge a wrong hold would be.+ const forgeHold = await forgeSpawnHoldReason(task);+ if (forgeHold) return holdTask(task, forgeHold);+ // 4. Global capacity. Reserve across the spawn window so direct persistent+ // turns and ordinary agents cannot both pass a stale pre-registration+ // snapshot.+ const capacityState = await loadState();+ const globalSlot = acquireCosGlobalSlot({+ agents: capacityState.agents,+ limit: capacityState.config?.maxConcurrentAgents,+ reservationId: task.id,+ });+ if (!globalSlot.ok) return holdTask(task, globalSlot.reason);++ // 5. Local inference endpoint at capacity (issue #4834). A CoS agent runs a+ // vendor CLI that opens its own connection to the local model server, so+ // promptRunner's in-flight gate never sees it — without this, two agents+ // can be dispatched at one GPU and the runtime kills a turn with an+ // accelerator OOM. Held HERE because `dequeueNextTask` is only one of the+ // emitters: evaluateTasks, forceSpawnTask, the job scheduler and the+ // Creative Director bridge all reach this listener directly. The slot is+ // reserved across the spawn window and released below, since the agent+ // record isn't countable until it reaches `running`.+ try {+ const localSlot = await acquireLocalEndpointSpawnSlot(task, capacityState.agents);+ if (!localSlot.ok) return holdTask(task, localSlot.reason);+ try {+ await spawnAgentForTask(task);+ } catch (err) {+ emitLog('error', `Failed to spawn agent for task ${task.id}: ${err?.message || err}`, { taskId: task.id });+ const jobId = task.metadata?.jobId;+ if (jobId) {+ cosEvents.emit('job:spawn-failed', { jobId });+ }+ } finally {+ localSlot.release();+ }+ } finally {+ globalSlot.release();+ }+}+/*** Initialize the spawner — listen for task:ready events. Idempotent: repeated* calls return the same promise (and re-run only after a failed attempt).@@ -344,86 +433,22 @@ async function runInitSpawner() {}});- cosEvents.on('task:ready', async (task) => {- // ── HOLDS, at the one chokepoint all seven `task:ready` emitters funnel- // through. Each leaves the task queued (no status write, no retry charged)- // for a condition that clears on its own.- //- // Held HERE rather than inside `runAgentSpawn`: a hold below this line would- // return past `releaseAppReviewMarker`, stranding the synthetic "in review"- // marker for the whole outage — issue #989's exact failure mode. The- // releases in `holdTask` are the same ones the spawn body owns.- //- // 1. Self-update in progress (issue #4124). `/api/update/execute` refuses to- // start while an agent is live, but `update.sh` then spends multiple- // seconds in `git pull` / submodule update / `npm install` before it- // reaches `pm2 delete` — an agent spawned inside that window is severed- // by the restart (its PTY/child process is a child of this server). The- // flag reads synchronously, so nothing can slip between the check and the- // spawn; the task runs on the other side of the restart.- if (isUpdateInProgress()) {- return holdTask(task, 'a PortOS self-update is in progress');- }- // 2. Runner down. Dispatching into a stopped runner is not a task failure,- // but both spawn arms recorded it as one: the CLI arm finalized- // `spawn-rejected` (a retry each time, so a runner left off overnight- // walked every queued task through its retry budget into `blocked`), and- // the TUI arm threw into the actionable `spawn-error`, parking the task- // for a human over an app the user simply turned off.- if (useRunner && !(await isRunnerReachable())) {- return holdTask(task, 'CoS Runner is down');- }- // 3. Forge unreachable, for a task that cannot finish without it (#5110). An- // agent whose task promises a change request does its work, fails to push,- // and finalizes `forge-unreachable` — non-actionable, so the task retries,- // and each retry re-runs the whole agent against the same dead network. One- // VPN drop cost three runs (101 + 50 + 23 minutes) to reach `blocked`. See- // cosForgeSpawnGate.js for the narrowings that keep the hold from becoming- // the silent wedge a wrong hold would be.- const forgeHold = await forgeSpawnHoldReason(task);- if (forgeHold) return holdTask(task, forgeHold);- // 4. Global capacity. Reserve across the spawn window so direct persistent- // turns and ordinary agents cannot both pass a stale pre-registration- // snapshot.- const capacityState = await loadState();- const globalSlot = acquireCosGlobalSlot({- agents: capacityState.agents,- limit: capacityState.config?.maxConcurrentAgents,- reservationId: task.id,- });- if (!globalSlot.ok) return holdTask(task, globalSlot.reason);-- // 5. Local inference endpoint at capacity (issue #4834). A CoS agent runs a- // vendor CLI that opens its own connection to the local model server, so- // promptRunner's in-flight gate never sees it — without this, two agents- // can be dispatched at one GPU and the runtime kills a turn with an- // accelerator OOM. Held HERE because `dequeueNextTask` is only one of the- // emitters: evaluateTasks, forceSpawnTask, the job scheduler and the- // Creative Director bridge all reach this listener directly. The slot is- // reserved across the spawn window and released below, since the agent- // record isn't countable until it reaches `running`.- try {- const localSlot = await acquireLocalEndpointSpawnSlot(task, capacityState.agents);- if (!localSlot.ok) return holdTask(task, localSlot.reason);- try {- await spawnAgentForTask(task);- } catch (err) {- emitLog('error', `Failed to spawn agent for task ${task.id}: ${err?.message || err}`, { taskId: task.id });- const jobId = task.metadata?.jobId;- if (jobId) {- cosEvents.emit('job:spawn-failed', { jobId });- }- } finally {- localSlot.release();- }- } finally {- globalSlot.release();- }- });+ // `cosEvents` does not await or catch a listener's promise, so the async body+ // is wrapped rather than passed straight to `.on` (same reason as the guarded+ // orphan sweep below). `emitLog` rather than `console.error`: every other+ // failure path in this dispatch already logs there, and the CoS Logs tab is+ // where an operator looks for a task that never started.+ // The settled promise is RETURNED even though EventEmitter discards it: it is+ // what lets a test `await` a dispatch rather than racing it.+ cosEvents.on('task:ready', (task) =>+ handleTaskReady(task).catch(err =>+ emitLog('error', `Task ${task?.id} could not be dispatched: ${err?.message || err}`, { taskId: task?.id })));- cosEvents.on('agent:terminate', async (agentId) => {- await terminateAgent(agentId);- });+ // `terminateAgent` throws for an unknown or already-gone agent id, and this+ // listener is not on a request path — an unguarded rejection would escape.+ cosEvents.on('agent:terminate', (agentId) =>+ terminateAgent(agentId).catch(err =>+ emitLog('error', `Terminate request for agent ${agentId} failed: ${err?.message || err}`, { agentId })));// Clean up orphaned agents after a short delay (let other services finish init).// setTimeout runs outside the request lifecycle, so guard the async callback.diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.jsindex 9b0555cbcd..755f2e4a90 100644--- a/server/services/subAgentSpawner.test.js+++ b/server/services/subAgentSpawner.test.js@@ -23,8 +23,67 @@ vi.mock('./thinkingLevels.js', async (importOriginal) => {};});-import { describe, it, expect, vi } from 'vitest';+// ── Listener-guard suite support (see "CoS event listener rejection guards").+// `initSpawner()` wires the real `task:ready` / `agent:terminate` listeners onto+// the shared `cosEvents` emitter; these mocks keep that wiring off the network,+// the runner socket and the agent store, and let a single test force the one+// rejection it is about.+const listenerGuardState = vi.hoisted(() => ({ loadStateError: null, terminateError: null }));++vi.mock('./providerStatus.js', async (importOriginal) => ({+ ...(await importOriginal()),+ initProviderStatus: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('./cosRunnerClient.js', async (importOriginal) => ({+ ...(await importOriginal()),+ isRunnerAvailable: vi.fn().mockResolvedValue(false),+ isRunnerReachable: vi.fn().mockResolvedValue(false),+ initCosRunnerConnection: vi.fn(),+ onCosRunnerEvent: vi.fn(),+}));++vi.mock('./agentManagement.js', async (importOriginal) => ({+ ...(await importOriginal()),+ cleanupOrphanedAgents: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('./updateChecker.js', async (importOriginal) => ({+ ...(await importOriginal()),+ isUpdateInProgress: vi.fn().mockReturnValue(false),+}));++vi.mock('./cosForgeSpawnGate.js', async (importOriginal) => ({+ ...(await importOriginal()),+ forgeSpawnHoldReason: vi.fn().mockResolvedValue(null),+}));++vi.mock('./cosState.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ loadState: vi.fn(async () => {+ if (listenerGuardState.loadStateError) throw listenerGuardState.loadStateError;+ return actual.loadState();+ }),+ };+});++vi.mock('./agentOrchestrator.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ spawnAgentForTask: vi.fn().mockResolvedValue(undefined),+ terminateAgent: vi.fn(async () => {+ if (listenerGuardState.terminateError) throw listenerGuardState.terminateError;+ }),+ };+});++import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';import { isTruthyMeta, isFalsyMeta } from './agentState.js';+import { cosEvents } from './cosEvents.js';+import { initSpawner } from './subAgentSpawner.js';import { selectModelForTask } from './agentModelSelection.js';import { applyAppWorktreeDefault } from './cos.js';@@ -416,3 +475,70 @@ describe('Worktree & metadata flag helpers', () => {});++/**+ * `cosEvents` is a plain `EventEmitter` — it neither awaits nor catches what a+ * listener returns, so an `async` listener passed straight to `.on` turns any+ * rejection into a process-level `unhandledRejection`. For `task:ready`, the one+ * chokepoint every spawn emitter funnels through, that also means the queued+ * task is silently never dispatched and the failure carries no task id.+ *+ * These two cases pin the wrapper: they fail if the `.catch` is dropped, or if a+ * new `await` is added ahead of the listener's inner `try`.+ */+describe('CoS event listener rejection guards', () => {+ const flushMicrotasks = async () => {+ for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve));+ };++ let logs;+ let unhandled;+ const collectLog = entry => logs.push(entry);+ const collectUnhandled = reason => unhandled.push(reason);++ beforeAll(async () => {+ await initSpawner();+ });++ beforeEach(() => {+ logs = [];+ unhandled = [];+ cosEvents.on('log', collectLog);+ process.on('unhandledRejection', collectUnhandled);+ });++ afterEach(() => {+ cosEvents.off('log', collectLog);+ process.off('unhandledRejection', collectUnhandled);+ listenerGuardState.loadStateError = null;+ listenerGuardState.terminateError = null;+ });++ it('logs a task:ready dispatch failure with the task id instead of leaking a rejection', async () => {+ listenerGuardState.loadStateError = new Error('state read failed');++ cosEvents.emit('task:ready', { id: 'task-x' });+ await flushMicrotasks();++ expect(unhandled).toEqual([]);+ const errors = logs.filter(entry => entry.level === 'error');+ expect(errors).toHaveLength(1);+ expect(errors[0].message).toContain('task-x');+ expect(errors[0].message).toContain('state read failed');+ expect(errors[0].taskId).toBe('task-x');+ });++ it('logs an agent:terminate failure with the agent id instead of leaking a rejection', async () => {+ listenerGuardState.terminateError = new Error('Agent not found');++ cosEvents.emit('agent:terminate', 'agent-unknown');+ await flushMicrotasks();++ expect(unhandled).toEqual([]);+ const errors = logs.filter(entry => entry.level === 'error');+ expect(errors).toHaveLength(1);+ expect(errors[0].message).toContain('agent-unknown');+ expect(errors[0].message).toContain('Agent not found');+ expect(errors[0].agentId).toBe('agent-unknown');+ });+});