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: guard the fire-and-forget CoS dequeue/spawn schedules (#5644)
Adam Eivyc8adc1dc6bc5
diff --git a/server/services/cos.dequeueGuard.test.js b/server/services/cos.dequeueGuard.test.jsnew file mode 100644index 0000000000..839b7d23b3--- /dev/null+++ b/server/services/cos.dequeueGuard.test.js@@ -0,0 +1,67 @@+/**+ * #5644 — the CoS scheduler fires `dequeueNextTask` from ~10 timer/setImmediate+ * callbacks. Those run outside the Express request lifecycle, so a rejection+ * inside the cycle (a corrupt `cos-state.json`, a provider-list fetch that+ * throws, a runner transport error) has nowhere to bubble: it escapes as an+ * unhandled rejection, which `setupProcessErrorHandlers` classifies+ * `severity: 'critical'` and broadcasts to every connected browser.+ *+ * This is the behavioural half of the guard (the structural half — "no bare+ * `setImmediate(() => dequeueNextTask())` is ever re-added" — lives in+ * cos.test.js). It drives the REAL listener registered by `init()` with a+ * `loadState` that rejects, and asserts each failed cycle is logged and never+ * reaches the process-level unhandled-rejection handler.+ *+ * Lives in its own file because the `cosState.js` partial mock is module-wide+ * and cos.test.js exercises the real state helpers.+ */++import { describe, it, expect, vi, afterEach } from 'vitest';++const STATE_ERROR = 'corrupt cos-state.json';++vi.mock('./cosState.js', async (importOriginal) => ({+ ...(await importOriginal()),+ ensureDirectories: vi.fn(async () => {}),+ isDaemonRunning: () => true,+ loadState: vi.fn(async () => { throw new Error(STATE_ERROR); }),+}));++const { init } = await import('./cos.js');+const { cosEvents } = await import('./cosEvents.js');++// One macrotask turn is enough: the listener schedules with setImmediate and the+// wrapper's .catch settles on the microtask queue right after.+const drainScheduled = () => new Promise(resolve => setImmediate(() => setImmediate(resolve)));++afterEach(() => {+ vi.restoreAllMocks();+});++describe('scheduleDequeue — rejections stay inside the cycle (#5644)', () => {+ it('logs a rejecting dequeue cycle instead of leaking an unhandled rejection', async () => {+ const unhandled = [];+ const onUnhandled = (reason) => unhandled.push(reason);+ process.on('unhandledRejection', onUnhandled);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ // init() registers the scheduler listeners, then reads state itself — that+ // trailing read is the mocked rejection, so swallow it here. The listeners+ // are already attached by then, which is what this test drives.+ await init().catch(() => {});++ // Two independent event sources, so a guard added to only one of them fails.+ cosEvents.emit('tasks:cos:added');+ cosEvents.emit('tasks:changed', { action: 'approved' });+ await drainScheduled();++ process.off('unhandledRejection', onUnhandled);++ expect(unhandled, 'no rejection may escape the scheduled callback').toEqual([]);+ const logged = errorSpy.mock.calls+ .map(args => args.join(' '))+ .filter(line => line.includes('CoS dequeue cycle failed'));+ expect(logged).toHaveLength(2);+ expect(logged[0]).toContain(STATE_ERROR);+ });+});diff --git a/server/services/cos.js b/server/services/cos.jsindex bd73cb1931..53232a77fd 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -519,7 +519,7 @@ async function runStart() {if (!canQueueImprovementTasks(state)) return;const cosTaskData = await getCosTasks();await queueEligibleImprovementTasks(state, cosTaskData);- setImmediate(() => dequeueNextTask());+ scheduleDequeue();}).catch(err => emitLog('warn', `Post-startup improvement queuing failed: ${err.message}`));}, POST_STARTUP_QUEUE_DELAY_MS);@@ -606,7 +606,7 @@ export async function resume() {// Trigger immediate task dequeue on resume (outside lock to avoid holding it)if (result.success && isDaemonRunning()) {await handlePersistentMindGlobalResume();- setTimeout(() => dequeueNextTask(), RESUME_DEQUEUE_DELAY_MS);+ setTimeout(() => scheduleDequeue(), RESUME_DEQUEUE_DELAY_MS);}return result;@@ -1301,6 +1301,17 @@ async function spawnDequeuePriority4IdleReview(ctx) {}}+// Every dequeue below is scheduled from a timer/setImmediate outside the request+// lifecycle, so a rejection has nowhere to bubble: it escapes as an unhandled+// rejection, which setupProcessErrorHandlers classifies `critical` and broadcasts+// `system:critical-error` to every browser, while the open slot it was meant to+// fill stays empty until an unrelated event fires another cycle. One wrapper so+// the guard cannot drift between the ~10 call sites.+const scheduleDequeue = (options = {}) => setImmediate(() => {+ dequeueNextTask(options).catch(err =>+ console.error(`❌ CoS dequeue cycle failed: ${err?.message ?? String(err)}`));+});+/*** Event-driven task dequeue — the primary way tasks get spawned.*@@ -1673,11 +1684,12 @@ export async function init() {// tasks:changed — registering dequeue via this listener — before it called// setImmediate(tryImmediateSpawn)). dequeue fills slots in priority order// first; tryImmediateSpawn then handles the just-added task.- setImmediate(() => dequeueNextTask());- if (data.type === 'user' && data.task) setImmediate(() => tryImmediateSpawn(data.task));+ scheduleDequeue();+ if (data.type === 'user' && data.task) setImmediate(() => tryImmediateSpawn(data.task)+ .catch(err => console.error(`❌ Immediate spawn for task ${data.task?.id} failed: ${err?.message ?? String(err)}`)));} else if (data.action === 'approved' || data.action === 'unblocked' || data.action === 'requeued') {if (data.suppressDequeue) return;- setImmediate(() => dequeueNextTask());+ scheduleDequeue();} else if (data.task?.status === 'completed' && data.previousStatus !== 'completed') {// A finished investigation releases the task(s) its failure was blocking// (see investigationRetry.js). Keyed on the completion rather than on who@@ -1704,29 +1716,29 @@ export async function init() {});cosEvents.on('tasks:user:added', () => {- if (isDaemonRunning()) setImmediate(() => dequeueNextTask());+ if (isDaemonRunning()) scheduleDequeue();});// Changing the investigation override can make an already-queued held task// eligible. Re-run the normal dequeue so autonomy, budgets, leases, and// capacity remain the same as for every other system task.cosEvents.on('config:changed', () => {- if (isDaemonRunning()) setImmediate(() => dequeueNextTask());+ if (isDaemonRunning()) scheduleDequeue();});cosEvents.on('tasks:cos:added', () => {- if (isDaemonRunning()) setImmediate(() => dequeueNextTask());+ if (isDaemonRunning()) scheduleDequeue();});cosEvents.on('task:on-demand-requested', () => {- if (isDaemonRunning()) setImmediate(() => dequeueNextTask());+ if (isDaemonRunning()) scheduleDequeue();});// The improvement-check timer (cosJobScheduler.scheduleNextImprovementCheck)// queues eligible improvement tasks then asks for a dequeue via this event,// since dequeueNextTask lives here. Mirrors the pre-extraction direct call.cosEvents.on('cos:dequeue-requested', () => {- if (isDaemonRunning()) setImmediate(() => dequeueNextTask());+ if (isDaemonRunning()) scheduleDequeue();});// Autonomous job lifecycle → re-register/cancel individual job timersdiff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 85ea9638ba..5bc124198e 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1912,7 +1912,10 @@ describe('cos.js source — priority + capacity invariants', () => {expect(onIdx, 'tasks:changed listener must exist').toBeGreaterThan(-1);const handler = COS_SRC.slice(onIdx, COS_SRC.indexOf('});', onIdx) + 3);- const dequeueIdx = handler.indexOf('dequeueNextTask()');+ // Scheduled through the shared `scheduleDequeue` wrapper (#5644) — the bare+ // `setImmediate(() => dequeueNextTask())` it replaced left the rejection+ // unguarded outside the request lifecycle.+ const dequeueIdx = handler.indexOf('scheduleDequeue()');const spawnIdx = handler.indexOf('tryImmediateSpawn(');expect(dequeueIdx, 'listener must schedule dequeueNextTask').toBeGreaterThan(-1);expect(spawnIdx, 'listener must schedule tryImmediateSpawn').toBeGreaterThan(-1);@@ -1941,6 +1944,41 @@ describe('cos.js source — priority + capacity invariants', () => {expect(handler).toMatch(/data\.action\s*===\s*'requeued'/);});+ // #5644 — every dequeue/immediate-spawn here is scheduled from a timer or+ // setImmediate, i.e. outside the request lifecycle, where a rejection has+ // nowhere to bubble: it escapes as an unhandled rejection, which+ // setupProcessErrorHandlers classifies `critical` and broadcasts to every+ // connected browser as `system:critical-error` — and the open agent slot the+ // cycle was meant to fill stays empty until an unrelated event fires another+ // one. There is no runtime seam that would catch a future contributor+ // re-adding a bare `setImmediate(() => dequeueNextTask())`, so scan the source.+ it('never floats a dequeueNextTask / tryImmediateSpawn schedule without a .catch', () => {+ expect(+ COS_SRC,+ 'schedule the dequeue through scheduleDequeue() so the rejection is caught'+ ).not.toMatch(/set(?:Immediate|Timeout)\(\(\) => dequeueNextTask\(/);++ const lineStartOf = (idx) => COS_SRC.lastIndexOf('\n', idx) + 1;+ const unguarded = [];+ for (const name of ['dequeueNextTask', 'tryImmediateSpawn']) {+ const re = new RegExp(`${name}\\(`, 'g');+ let match;+ while ((match = re.exec(COS_SRC)) !== null) {+ const line = COS_SRC.slice(lineStartOf(match.index), COS_SRC.indexOf('\n', match.index));+ if (/^\s*(?:\/\/|\*)/.test(line)) continue; // prose mention in a comment+ const before = COS_SRC.slice(Math.max(0, match.index - 40), match.index);+ if (/function\s+$/.test(before)) continue; // the declaration itself+ if (/await\s+$/.test(before)) continue; // awaited by an async caller+ // Otherwise the promise floats, so a `.catch(` must follow inside the+ // same statement (before the terminating `;`).+ const tail = COS_SRC.slice(match.index, match.index + 400);+ if (/^[^;]*\.catch\(/s.test(tail)) continue;+ unguarded.push(line.trim());+ }+ }+ expect(unguarded, 'floated scheduler promises must be .catch-guarded').toEqual([]);+ });+// A finished investigation is what releases the failure-blocked task(s) it was// diagnosing. Without this branch the fix lands and the work it unblocked never// runs — the task sits `blocked` until a human notices or the 14-day reaper