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: promote to CoS Runner mode when the runner starts after the server (#4134)
Adam Eivy3599ab130cf1
diff --git a/.changelog/next/fixed-issue-4134.md b/.changelog/next/fixed-issue-4134.mdnew file mode 100644index 0000000000..dd47775954--- /dev/null+++ b/.changelog/next/fixed-issue-4134.md@@ -0,0 +1 @@+- CoS Runner mode now recovers when portos-cos starts after portos-server — the spawner keeps its socket open and promotes from direct to runner mode on connect, instead of degrading for the process lifetimediff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex e64a5e35b2..ae2f389811 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -119,7 +119,15 @@ export function initCosRunnerConnection() {}};+ // One connection-error line per outage, not one per retry. The socket is now+ // opened unconditionally (issue #4134) so a promotion can happen when the+ // runner comes up later — which means an install whose runner is simply off+ // would otherwise log a `connect_error` every 10s, forever. Reset on connect+ // so the NEXT outage is reported again.+ let connectErrorLogged = false;+socket.on('connect', () => {+ connectErrorLogged = false;console.log('🔌 Connected to CoS Runner');for (const [sessionId, state] of tuiSessions) {for (const { event, payload } of state.pendingControls.splice(0)) {@@ -135,7 +143,9 @@ export function initCosRunnerConnection() {});socket.on('connect_error', (err) => {- console.error(`🔌 CoS Runner connection error: ${err.message}`);+ if (connectErrorLogged) return;+ connectErrorLogged = true;+ console.error(`🔌 CoS Runner connection error: ${err.message} — retrying until it answers`);});// Forward events to registered handlers@@ -216,11 +226,14 @@ const probeRunnerHealth = (timeoutMs) =>/*** Check if CoS Runner is available.*- * The BOOT-time mode decision (`setUseRunner`), taken before any socket exists,- * which is why it probes rather than reading `socket.connected` the way- * `isRunnerReachable` does. The generous timeout is deliberate: during a rolling- * PM2 start the runner can be slow to answer, and a premature `false` here- * demotes the whole process to direct mode for its lifetime.+ * The COLD-START SEED for the mode decision (`setUseRunner`), taken before any+ * socket exists, which is why it probes rather than reading `socket.connected`+ * the way `isRunnerReachable` does. The generous timeout is deliberate: during a+ * rolling PM2 start the runner can be slow to answer, and a premature `false`+ * here starts the process in direct mode. It no longer strands it there —+ * `connection:ready` promotes the process the moment the socket lands (#4134) —+ * but every task dispatched in the meantime is spawned as a child of this+ * server, so the seed is still worth getting right.*/export async function isRunnerAvailable() {return (await probeRunnerHealth(10000)) !== null;diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 0646af4165..4617148221 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -85,6 +85,24 @@ async function holdTask(task, reason) {}}+/**+ * Adopt agents the runner is already driving that this process does not own.+ *+ * Runs on both edges that can find a live runner with pre-existing agents: the+ * boot seed (agents that outlived a `portos-server` restart) and a mid-life+ * promotion (a runner that was already up before this server took over). Agents+ * this process spawned DIRECTLY are never adopted — `syncRunnerAgents` skips+ * anything `isAgentOwnedLocally` claims, so they keep completing through their+ * own child-process close handler.+ */+async function recoverRunnerAgents() {+ const synced = await syncRunnerAgents().catch(err => {+ console.error(`❌ Failed to sync runner agents: ${err.message}`);+ return 0;+ });+ if (synced > 0) console.log(`🔄 Recovered ${synced} agents from CoS Runner`);+}+/*** Load a slashdo command from the bundled submodule, resolving !`cat` lib includes inline.*/@@ -140,118 +158,138 @@ async function runInitSpawner() {if (pruned > 0) console.log(`🗑️ Pruned ${pruned} old run directories (>30 days)`);}- // Check if CoS Runner is available- const runnerAvailable = await isRunnerAvailable();- setUseRunner(runnerAvailable);+ // ── SPAWN MODE. Runner mode is NOT a boot-time verdict (issue #4134).+ //+ // The probe is only the COLD-START SEED, for the window before the socket's+ // first `connect` lands: `portos-cos` is a separate PM2 app that can come up+ // after `portos-server`, and treating one probe as the answer left this+ // process in direct mode for its whole lifetime — every agent a child of+ // `portos-server`, dying with it, which is the exact orphaning runner mode+ // exists to prevent. The socket reconnects forever with capped backoff, so it,+ // not the probe, is the standing authority on whether the runner is there.+ setUseRunner(await isRunnerAvailable());+ console.log(useRunner+ ? '🤖 Sub-agent spawner initialized (using CoS Runner)'+ : '🤖 Sub-agent spawner initialized (direct mode — CoS Runner not up yet)');- if (runnerAvailable) {- console.log('🤖 Sub-agent spawner initialized (using CoS Runner)');- initCosRunnerConnection();-- // Sync any agents that were running before server restart- const synced = await syncRunnerAgents().catch(err => {- console.error(`❌ Failed to sync runner agents: ${err.message}`);- return 0;- });- if (synced > 0) {- console.log(`🔄 Recovered ${synced} agents from CoS Runner`);- }+ initCosRunnerConnection();- // Runner liveness → the queue holds, then re-drives. `portos-cos` is a- // separate PM2 app the user can stop, and in runner mode it owns every agent- // process — so while it is down, dispatch HOLDS tasks as `pending` (see the- // `task:ready` listener below and `dequeueNextTask`'s gate) rather than- // failing them. These two events are the outage's edges: one warning when it- // goes, one dequeue when it returns, instead of a line per held task.- //- // The reconnect is debounced because `reconnectionAttempts` is unbounded: a- // crash-looping runner would otherwise drive one full five-tier dequeue- // cycle per restart.- onCosRunnerEvent('connection:lost', () => {- emitLog('warn', '⏸️ CoS Runner disconnected — holding agent tasks until it returns');- });+ // Sync any agents that were running before server restart+ if (useRunner) await recoverRunnerAgents();- onCosRunnerEvent('connection:ready', () => {- clearTimeout(reconnectDequeueTimer);- reconnectDequeueTimer = setTimeout(() => {- emitLog('info', '▶️ CoS Runner reconnected — resuming held agent tasks');- cosEvents.emit('cos:dequeue-requested');- }, RECONNECT_DEQUEUE_DEBOUNCE_MS);- reconnectDequeueTimer.unref?.();- });+ // Runner liveness → the queue holds, then re-drives. `portos-cos` is a+ // separate PM2 app the user can stop, and in runner mode it owns every agent+ // process — so while it is down, dispatch HOLDS tasks as `pending` (see the+ // `task:ready` listener below and `dequeueNextTask`'s gate) rather than+ // failing them. These two events are the outage's edges: one warning when it+ // goes, one dequeue when it returns, instead of a line per held task.+ //+ // The reconnect is debounced because `reconnectionAttempts` is unbounded: a+ // crash-looping runner would otherwise drive one full five-tier dequeue+ // cycle per restart.+ onCosRunnerEvent('connection:lost', () => {+ // Deliberately NOT a demotion back to direct mode. `useRunner` stays true so+ // the dispatch gate keeps HOLDING tasks as `pending`; flipping it to false+ // here would silently convert every held task into a direct spawn — a child+ // of `portos-server` again — which is the orphaning runner mode exists to+ // prevent. The outage is a hold; it clears on `connection:ready` below.+ emitLog('warn', '⏸️ CoS Runner disconnected — staying in runner mode, holding agent tasks until it returns');+ });- // Set up event handlers for runner events- onCosRunnerEvent('agent:output', async (data) => {- const { agentId, text } = data;- // Drop output for an agent that's already finalized/removed. The runner- // registers the agent in `runnerAgents` before it spawns the process- // (agentLifecycle spawnViaRunner), so this never drops legitimate early- // output — it only ignores a stray event arriving after completion, which- // would otherwise lazily create a never-drained batcher (Map leak).- if (!runnerAgents.has(agentId)) return;- getRunnerOutputBatcher(agentId).push(text);+ onCosRunnerEvent('connection:ready', () => {+ // MID-LIFE PROMOTION (#4134): the runner came up after this server did, so+ // take over from the cold-start seed. Agents already spawned directly are+ // untouched — ownership is keyed by agent id in both maps+ // (`isAgentOwnedLocally`), so their close handlers still finalize them and+ // the recovery sweep below refuses to adopt them.+ if (!useRunner) {+ setUseRunner(true);+ console.log('🔼 CoS Runner came up — promoting agent spawning from direct to runner mode');+ recoverRunnerAgents().catch(err =>+ console.error(`❌ Failed to recover runner agents after promotion: ${err.message}`)+ );+ }+ clearTimeout(reconnectDequeueTimer);+ reconnectDequeueTimer = setTimeout(() => {+ emitLog('info', '▶️ CoS Runner reconnected — resuming held agent tasks');+ cosEvents.emit('cos:dequeue-requested');+ }, RECONNECT_DEQUEUE_DEBOUNCE_MS);+ reconnectDequeueTimer.unref?.();+ });- // Update phase on first output- const agent = runnerAgents.get(agentId);- if (agent && !agent.hasStartedWorking) {- agent.hasStartedWorking = true;- clearTimeout(agent.initializationTimeout);- await updateAgent(agentId, { metadata: { phase: 'working' } });- emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });- }- });+ // Runner event handlers are registered unconditionally: they are inert in+ // direct mode (each keys off `runnerAgents`, which only `spawnViaRunner`+ // populates), and registering them only when the boot probe succeeded left a+ // promoted process connected to a runner whose output/completions nothing was+ // listening for.+ onCosRunnerEvent('agent:output', async (data) => {+ const { agentId, text } = data;+ // Drop output for an agent that's already finalized/removed. The runner+ // registers the agent in `runnerAgents` before it spawns the process+ // (agentLifecycle spawnViaRunner), so this never drops legitimate early+ // output — it only ignores a stray event arriving after completion, which+ // would otherwise lazily create a never-drained batcher (Map leak).+ if (!runnerAgents.has(agentId)) return;+ getRunnerOutputBatcher(agentId).push(text);- onCosRunnerEvent('agent:completed', async (data) => {- const { agentId, exitCode, success, duration } = data;- const agent = runnerAgents.get(agentId);- // A runner-owned TUI is finalized by spawnTuiAgent while this server- // remains connected. Only a TUI recovered into runnerAgents after a- // server restart should use the generic runner completion path.- // That invariant is upheld elsewhere — `syncRunnerAgents` must not adopt an- // agent this process already owns (see `isAgentOwnedLocally`). When it did,- // this guard passed for a live TUI and double-finalized it; the sibling- // `agent:output` and `agent:error` handlers key off the same membership.- if (!agent) return;+ // Update phase on first output+ const agent = runnerAgents.get(agentId);+ if (agent && !agent.hasStartedWorking) {+ agent.hasStartedWorking = true;clearTimeout(agent.initializationTimeout);- // Drain pending output before completion so the final lines land in- // state before handleAgentCompletion writes the terminal record.- await flushRunnerOutputBatcher(agentId);- await handleAgentCompletion(agentId, exitCode, success, duration);- });+ await updateAgent(agentId, { metadata: { phase: 'working' } });+ emitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });+ }+ });- // Batch handler for orphaned agents (runner startup cleanup)- onCosRunnerEvent('agents:orphaned', async (data) => {- const { agents, count } = data;- console.log(`🧹 Processing ${count} orphaned agents from runner`);- for (const orphan of agents) {- const agent = runnerAgents.get(orphan.agentId);- if (agent) {- clearTimeout(agent.initializationTimeout);- }- await flushRunnerOutputBatcher(orphan.agentId);- await handleAgentCompletion(orphan.agentId, orphan.exitCode, orphan.success, 0);- }- });+ onCosRunnerEvent('agent:completed', async (data) => {+ const { agentId, exitCode, success, duration } = data;+ const agent = runnerAgents.get(agentId);+ // A runner-owned TUI is finalized by spawnTuiAgent while this server+ // remains connected. Only a TUI recovered into runnerAgents after a+ // server restart should use the generic runner completion path.+ // That invariant is upheld elsewhere — `syncRunnerAgents` must not adopt an+ // agent this process already owns (see `isAgentOwnedLocally`). When it did,+ // this guard passed for a live TUI and double-finalized it; the sibling+ // `agent:output` and `agent:error` handlers key off the same membership.+ if (!agent) return;+ clearTimeout(agent.initializationTimeout);+ // Drain pending output before completion so the final lines land in+ // state before handleAgentCompletion writes the terminal record.+ await flushRunnerOutputBatcher(agentId);+ await handleAgentCompletion(agentId, exitCode, success, duration);+ });- onCosRunnerEvent('agent:error', async (data) => {- const { agentId, error } = data;- console.error(`❌ Agent ${agentId} error from runner: ${error}`);- cosEvents.emit('agent:error', { agentId, error });- await flushRunnerOutputBatcher(agentId);- const agent = runnerAgents.get(agentId);+ // Batch handler for orphaned agents (runner startup cleanup)+ onCosRunnerEvent('agents:orphaned', async (data) => {+ const { agents, count } = data;+ console.log(`🧹 Processing ${count} orphaned agents from runner`);+ for (const orphan of agents) {+ const agent = runnerAgents.get(orphan.agentId);if (agent) {clearTimeout(agent.initializationTimeout);- // Runner-level error before the run could produce work — no success- // criterion was evaluated, so validation is the null sentinel (issue- // #2344), never a false that would look like a declared-and-failed run.- await completeAgent(agentId, { success: false, validationPassed: null, error });- await completeAgentRun(agent.runId, '', 1, 0, { message: error, category: 'runner-error' });- runnerAgents.delete(agentId);}- });- } else {- console.log('🤖 Sub-agent spawner initialized (direct mode - CoS Runner not available)');- }+ await flushRunnerOutputBatcher(orphan.agentId);+ await handleAgentCompletion(orphan.agentId, orphan.exitCode, orphan.success, 0);+ }+ });++ onCosRunnerEvent('agent:error', async (data) => {+ const { agentId, error } = data;+ console.error(`❌ Agent ${agentId} error from runner: ${error}`);+ cosEvents.emit('agent:error', { agentId, error });+ await flushRunnerOutputBatcher(agentId);+ const agent = runnerAgents.get(agentId);+ if (agent) {+ clearTimeout(agent.initializationTimeout);+ // Runner-level error before the run could produce work — no success+ // criterion was evaluated, so validation is the null sentinel (issue+ // #2344), never a false that would look like a declared-and-failed run.+ await completeAgent(agentId, { success: false, validationPassed: null, error });+ await completeAgentRun(agent.runId, '', 1, 0, { message: error, category: 'runner-error' });+ runnerAgents.delete(agentId);+ }+ });cosEvents.on('task:ready', async (task) => {// ── HOLDS, at the one chokepoint all seven `task:ready` emitters funneldiff --git a/server/services/subAgentSpawner.runnerPromotion.test.js b/server/services/subAgentSpawner.runnerPromotion.test.jsnew file mode 100644index 0000000000..294289a671--- /dev/null+++ b/server/services/subAgentSpawner.runnerPromotion.test.js@@ -0,0 +1,148 @@+/**+ * Mid-life runner promotion (issue #4134).+ *+ * `portos-cos` is a separate PM2 app, so it can come up AFTER `portos-server`.+ * Spawn mode used to be decided once, by the boot probe, with the socket and its+ * connection events wired only inside that `if (runnerAvailable)` branch — so a+ * server that booted while the runner was down stayed in direct mode for its+ * whole lifetime: every agent a child of `portos-server`, dying with it, which+ * is the exact orphaning runner mode exists to prevent.+ *+ * The socket is now always opened and the probe is only the cold-start seed;+ * `connection:ready` is the standing authority. The reverse edge is deliberately+ * NOT symmetric — `connection:lost` keeps runner mode so dispatch keeps HOLDING+ * tasks as `pending`, because demoting there would silently turn every held task+ * back into an orphan-prone direct spawn.+ */++import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';++const runnerHandlers = new Map();++vi.mock('./cosRunnerClient.js', () => ({+ onCosRunnerEvent: vi.fn((event, handler) => { runnerHandlers.set(event, handler); }),+ initCosRunnerConnection: vi.fn(),+ // The runner is DOWN at boot — the regression's starting condition.+ isRunnerAvailable: vi.fn().mockResolvedValue(false),+ isRunnerReachable: vi.fn().mockResolvedValue(false),+}));++vi.mock('./cosEvents.js', () => ({+ emitLog: vi.fn(),+ cosEvents: { emit: vi.fn(), on: vi.fn() },+}));++vi.mock('./providerStatus.js', () => ({ initProviderStatus: vi.fn().mockResolvedValue(undefined) }));+vi.mock('./agentRunnerSync.js', () => ({ syncRunnerAgents: vi.fn().mockResolvedValue(0) }));+vi.mock('./cosAgentLifecycle.js', () => ({ updateAgent: vi.fn() }));+vi.mock('./agentRunnerOutputBatchers.js', () => ({+ getRunnerOutputBatcher: vi.fn(),+ flushRunnerOutputBatcher: vi.fn().mockResolvedValue(undefined),+}));+vi.mock('./agentLifecycle.js', () => ({ handleAgentCompletion: vi.fn() }));+vi.mock('./agentManagement.js', () => ({ cleanupOrphanedAgents: vi.fn().mockResolvedValue(undefined) }));+vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn() }));+vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));+vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: vi.fn().mockReturnValue(false) }));+vi.mock('./agentOrchestrator.js', () => ({+ completeAgent: vi.fn(),+ spawnAgentForTask: vi.fn().mockResolvedValue('agent-1'),+ terminateAgent: vi.fn(),+}));+vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));++import { initSpawner } from './subAgentSpawner.js';+import { initCosRunnerConnection } from './cosRunnerClient.js';+import { syncRunnerAgents } from './agentRunnerSync.js';+import * as agentState from './agentState.js';++// Read through the module namespace: `useRunner` is reassigned by `setUseRunner`,+// and a destructured copy would freeze the value at import time.+const currentMode = () => agentState.useRunner;++// Boot-time call counts, snapshotted before `vi.clearAllMocks()` erases them.+const bootCalls = { initConnection: 0, sync: 0, mode: null };++describe('subAgentSpawner — runner promotion (#4134)', () => {+ beforeAll(async () => {+ // initSpawner is memoized, so this is the one run that wires the handlers.+ await initSpawner();+ bootCalls.initConnection = vi.mocked(initCosRunnerConnection).mock.calls.length;+ bootCalls.sync = vi.mocked(syncRunnerAgents).mock.calls.length;+ bootCalls.mode = currentMode();+ });++ beforeEach(() => {+ vi.clearAllMocks();+ agentState.setUseRunner(false);+ });++ it('seeds direct mode from the boot probe but still opens the runner socket', () => {+ // The socket reconnects forever with capped backoff. Opening it only when+ // the probe succeeded is what made the demotion permanent.+ expect(bootCalls.mode).toBe(false);+ expect(bootCalls.initConnection).toBe(1);+ });++ it('does not reconcile runner agents at boot when the probe found no runner', () => {+ // With the probe false there is nothing to adopt, and /agents would fail+ // anyway — the reconciliation belongs to the promotion edge instead.+ expect(bootCalls.sync).toBe(0);+ });++ it('wires the runner event handlers in direct mode, so a promotion has somewhere to land', () => {+ // Inert while `runnerAgents` is empty — every handler keys off it — but+ // registered, so a runner that comes up later is actually listened to.+ for (const event of ['agent:output', 'agent:completed', 'agents:orphaned', 'agent:error']) {+ expect(runnerHandlers.has(event)).toBe(true);+ }+ });++ it('promotes to runner mode when the runner comes up after the server', () => {+ expect(currentMode()).toBe(false);++ runnerHandlers.get('connection:ready')();++ expect(currentMode()).toBe(true);+ });++ it('reconciles agents a runner that was already up owns, on promotion', () => {+ runnerHandlers.get('connection:ready')();++ // Adopts only agents this process does not already own, so an agent spawned+ // DIRECTLY before the promotion keeps completing through its own close+ // handler (`isAgentOwnedLocally`, covered in agentRunnerSync.test.js).+ expect(syncRunnerAgents).toHaveBeenCalledTimes(1);+ });++ it('promotes once — a later reconnect in runner mode does not re-reconcile', () => {+ runnerHandlers.get('connection:ready')();+ runnerHandlers.get('connection:ready')();+ runnerHandlers.get('connection:ready')();++ expect(syncRunnerAgents).toHaveBeenCalledTimes(1);+ });++ it('survives a reconciliation failure without leaving the process unpromoted', async () => {+ vi.mocked(syncRunnerAgents).mockRejectedValueOnce(new Error('runner /agents 500'));++ runnerHandlers.get('connection:ready')();+ await Promise.resolve();++ // The promotion is the point; recovery is best-effort. An unguarded+ // rejection here would also crash the process — this runs on a socket+ // callback, outside any request lifecycle.+ expect(currentMode()).toBe(true);+ });++ it('keeps runner mode when the connection drops, so tasks hold instead of spawning direct', () => {+ runnerHandlers.get('connection:ready')();+ expect(currentMode()).toBe(true);++ runnerHandlers.get('connection:lost')();++ // Demoting here would flip the dispatch gate (`useRunner && !reachable`) off+ // and spawn every held task as a child of portos-server.+ expect(currentMode()).toBe(true);+ });+});