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

hold queued agent tasks while the cos-runner app is down instead of failing them

[._.]/ Adam Eivyf46fd0549458
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 24cd71fcf9..6cab3a0f8c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -19,3 +19,4 @@
- **A provider outage no longer hands a CoS task's model pin to a provider that can't run it.** A task pinned to Antigravity with `gemini-3.6-flash` hit an auth outage on that provider; the fallback chain correctly swapped it onto the Claude CLI but carried the Antigravity model id along, so every retry spawned `claude --model gemini-3.6-flash` and died in ~1.5s ("There's an issue with the selected model") until the task exhausted its retries and blocked. The pass-through exemption that let it through is deliberate — it exists so an explicit pin isn't silently downgraded to the provider's heaviest default just because the provider's `models` list spells an alias differently — but it only makes sense on the provider the pin was chosen *for*. A `metadata.model` pin is provider-scoped (the task form picks a provider, then a model from that provider's catalog), so a fallback swap now drops it back to the new provider's own default unless that provider actually lists it, logging the substitution rather than doing it silently. A swap between siblings that both serve the pinned id (claude-code ↔ claude-code-tui) still keeps it, and a run with no swap at all is untouched. The check also covers a fallback provider that enumerates no models, which the existing model-list validation could not inspect at all.
- **The Claude CLI's own model rejection is now a recognized, actionable failure.** "There's an issue with the selected model (…)" is printed by the CLI at startup, before any API call, so it carries no `API Error: 4NN` token and matched none of the model-error patterns. It landed in the `unknown` bucket with "Error did not match known patterns" — which autoFixer maps to Tier 4 (escalate), so a task with a bad model id burned all three retries against an id that could never work and then spent an agent run on an investigation task. It now classifies as `model-not-found` with the rejected id extracted from the message, putting it in Tier 1 (config/env) where a model correction belongs. Promoted to a structured `provider`-origin signal, since the full banner with the parenthesised id and the `--model` hint is CLI text rather than something a task's own output prints in passing.
+- **Stopping the CoS Runner no longer burns through queued agent tasks.** `portos-cos` is a separate PM2 app you can stop from the Apps page, and while runner mode is active it owns every agent process — but the spawn path dispatched into it regardless and recorded the resulting rejection as a task failure. The CLI arm charged a retry each time (a runner left off overnight walked every queued task through its retry budget and into `blocked`), and the TUI arm reported an *actionable* spawn error, parking the task for a human over an app you had simply turned off. Tasks now hold instead, gated in two places: the queue stops dequeuing entirely while the runner is down — before the priority tiers drain on-demand requests, advance review cooldowns, or bind an app's "in review" marker — and dispatch itself holds anything that still reaches it, releasing that marker and freeing the scheduler's spawn reservation so an autonomous job re-registers instead of sitting wedged for five minutes. A held task keeps its exact queued record: pending, unclaimed, no agent, no retry charged. It spawns for real the moment the runner is back, because the runner socket's reconnect re-runs the dequeue. That reconnect is also now unbounded: the socket gave up after ten attempts (~10 seconds), so a runner that came back a minute later left the server connected to nothing while still routing every spawn at it. Backoff is capped at 10s and the resulting dequeue is debounced, so neither a long outage nor a crash-looping runner is expensive. You get one log line when the runner drops and one when it returns, not one per task. "Run now" is never held — it answers with the real reason (runner unreachable, or the daemon stopped, which was never checked at all) instead of toasting "Spawning" at a task that would sit pending.
diff --git a/PLAN.md b/PLAN.md
index 9b751cca81..3ad25f732d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -350,3 +350,7 @@ is not reliably announced.
### Show the restricted-model license gate on the remaining video render surfaces
- [ ] A restricted video model's license acknowledgement is now an install-wide recorded fact (`settings.videoGen.acceptedModelTerms`, written through `POST /api/video-gen/model-terms`), and `ModelTermsGate` + `useVideoModelTerms` are shared so any surface can render the acceptance UI. Two do: `client/src/pages/VideoGen.jsx` and the music-video board (`client/src/pages/MusicVideo.jsx` via `useMusicVideoModelSettings`). The other surfaces that let a user pin a video model still dead-end on the server's 403 the first time — before anything has been accepted anywhere: `client/src/pages/CreativeDirector.jsx` (`<ModelSelect>` per project), `client/src/components/creative-commission/CommissionConfigForm.jsx` (`videoModelId`, including cron-scheduled runs), `client/src/components/pipeline/stages/EpisodeVideoStage.jsx`, `client/src/components/media/MediaJobsQueue.jsx`'s edit-and-retry (free-text `modelId`, re-enqueued via `server/routes/mediaJobs.js` so it never passes through `prepareVideoGenParams`), and `client/src/components/media/PromptRefineModal.jsx`'s requeue. **The call to make:** don't hand-wire a gate into five components — handle `VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED` once, centrally, so future surfaces are covered for free: catch the code in `client/src/services/apiCore.js`'s error path (and in the media-job failure channel, where a queue-time rejection arrives as a message with no `code` — `server/lib/videoDisclosure.js#videoModelTermsError` is the single wording to match on) and open a `ModelTermsGate` modal seeded from the failing model's `termsGate`. The interim mitigation already shipped: that error names where the acknowledgement is made, so a blocked user on any surface has a path. Surfaced by the /simplify altitude review.
+
+### Let runner mode recover when the cos-runner app comes up after the server
+
+- [ ] `useRunner` (`server/services/agentState.js`) is decided once, at boot, from a single `isRunnerAvailable()` probe in `subAgentSpawner.js#runInitSpawner` — and everything that keeps runner mode honest lives inside that `if (runnerAvailable)` branch: `initCosRunnerConnection()`, the `connection:ready` re-dequeue, the `connection:lost` warning. So if `portos-cos` is down when `portos-server` boots (a plain PM2 restart ordering, or the user stopped it and later restarts the server), the process silently degrades to direct mode **for its lifetime**: every agent becomes a child of `portos-server` and dies with it, which is the exact orphaning runner mode exists to prevent. Starting the runner afterwards recovers nothing until the next server restart, and there is no log or UI signal that the demotion happened. The new runner-down HOLD does not apply either — it is gated on `useRunner`, which is false. **The call to make:** always call `initCosRunnerConnection()` (the socket already reconnects indefinitely with capped backoff) and drive `setUseRunner` from `connection:ready` / `connection:lost` instead of from the boot probe, keeping the probe only as the cold-start seed. That collapses the two disagreeing sources of truth for "runner mode" into one and makes the hold correct in both directions. Watch two things while doing it: agents spawned directly before a mid-life promotion must keep completing through the direct path (`isAgentOwnedLocally` already distinguishes them), and `syncRunnerAgents()` should run on promotion so a runner that was up before this server took over is reconciled. Deferred from the runner-hold fix, which was scoped to the reported symptom (runner stopped while the server was already running). Surfaced by the /simplify altitude review.
diff --git a/server/services/cos.js b/server/services/cos.js
index 8d924fedff..887c959017 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -34,6 +34,9 @@ import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';
import { getDomainBudgetStatus } from './domainUsage.js';
+// Dependency-free leaf holding the shared agent maps + the runner-mode flag,
+// read by `isRunnerHolding` below.
+import { useRunner } from './agentState.js';
// Shared state management (extracted to avoid circular deps)
import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, canQueueImprovementTasks, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';
@@ -532,8 +535,17 @@ export async function forceSpawnTask(taskId) {
if (task.status !== 'pending') return { error: `Task is ${task.status}, not pending` };
if (task.approvalRequired) return { error: 'Task requires approval before it can be spawned' };
+ if (!isDaemonRunning()) return { error: 'CoS daemon is stopped — start it before force-spawning tasks' };
+
const state = await loadState();
if (state.paused) return { error: 'CoS daemon is paused — resume before force-spawning tasks' };
+ // Dispatch HOLDS a task while the runner is down rather than failing it —
+ // right for the autonomous queue, wrong for an explicit "Run now", which would
+ // get `{ success: true }` and a "Spawning" toast for a task that quietly stays
+ // pending. Say what is actually wrong instead.
+ if (await isRunnerHolding()) {
+ return { error: 'CoS Runner is not reachable — start the cos-runner app before force-spawning tasks' };
+ }
const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
if (runningAgents >= state.config.maxConcurrentAgents) {
return { error: `No available agent slots (${runningAgents}/${state.config.maxConcurrentAgents})` };
@@ -755,6 +767,21 @@ export function isRunning() {
return isDaemonRunning();
}
+/**
+ * Is spawning currently held because the CoS Runner is down?
+ *
+ * The single predicate behind the three places that must agree: the dequeue
+ * gate, `tryImmediateSpawn`, and `forceSpawnTask`'s refusal. False in direct
+ * mode, where there is no runner to be down. `cosRunnerClient` is imported
+ * lazily (mirroring cosAgentLifecycle's runner calls) so a static edge doesn't
+ * drag socket.io-client into the graph of every suite that loads this module.
+ */
+async function isRunnerHolding() {
+ if (!useRunner) return false;
+ const { isRunnerReachable } = await import('./cosRunnerClient.js');
+ return !(await isRunnerReachable());
+}
+
/**
* Attempt to immediately spawn a newly added user task if there are available agent slots.
* This bypasses the evaluation interval for user-submitted tasks so they start instantly.
@@ -765,6 +792,11 @@ async function tryImmediateSpawn(task) {
const paused = await isPaused();
if (paused) return;
+ if (await isRunnerHolding()) {
+ emitLog('debug', `⏳ Queued task ${task.id} - CoS Runner is down`);
+ return;
+ }
+
const state = await loadState();
const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
const availableSlots = state.config.maxConcurrentAgents - runningAgents;
@@ -1147,6 +1179,15 @@ async function spawnDequeuePriority4IdleReview(ctx) {
async function dequeueNextTask({ ignoreTaskId = null } = {}) {
if (!isDaemonRunning()) return;
+ // In runner mode the cos-runner app owns every agent process, so a cycle run
+ // while it is down can only produce holds. Bail before the tiers rather than
+ // after: they drain on-demand requests, advance review cooldowns, bind the
+ // synthetic app-review marker, and spend `capacity` — side effects a hold
+ // downstream cannot take back. Same shape as the `availableSlots <= 0` gate
+ // below; "the runner is off" is the same fact as "there is nowhere to spawn".
+ // `connection:ready` re-runs this the moment the runner returns.
+ if (await isRunnerHolding()) return;
+
// A global pause stops scheduled/autonomous spawning, but NOT explicit user
// triggers: on-demand requests (Priority 0) are processed even while paused so
// a manual "Run" from an app's automation page still fires. The autonomous
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 898ef2d1e7..19efae9df3 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -1207,6 +1207,55 @@ describe('forceSpawnTask — pre-validate provider before task:ready', () => {
expect(resolveIdx, 'provider resolution must precede the task:ready emit')
.toBeLessThan(readyIdx);
});
+
+ // Same failure mode, two more sources of a doomed spawn. A stopped daemon was
+ // never checked at all (only `paused` was), and in runner mode the spawn path
+ // now HOLDS the task while the cos-runner app is down instead of failing it —
+ // right for the autonomous queue, wrong for an explicit "Run now", which would
+ // get `{ success: true }` and a "Spawning" toast for a task that quietly stays
+ // pending. Both must answer with an actionable error instead.
+ it('refuses to force-spawn while the daemon is stopped', () => {
+ const stoppedIdx = forceFn.indexOf('!isDaemonRunning()');
+ expect(stoppedIdx, 'forceSpawnTask must check that the daemon is running').toBeGreaterThan(-1);
+ expect(stoppedIdx, 'the stopped check must precede the task:ready emit')
+ .toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));
+ });
+
+ it('refuses to force-spawn while the runner is holding', () => {
+ const holdIdx = forceFn.indexOf('isRunnerHolding');
+ expect(holdIdx, 'forceSpawnTask must consult the runner hold').toBeGreaterThan(-1);
+ expect(holdIdx, 'the runner check must precede the task:ready emit')
+ .toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));
+ });
+});
+
+describe('the runner-down hold — spawn-side gates', () => {
+ // Dispatch holds a task while the cos-runner app is down (the `task:ready`
+ // listener in subAgentSpawner.js, covered behaviorally in
+ // subAgentSpawner.runnerHold.test.js). The dequeue must ALSO bail before its
+ // priority tiers run: they drain on-demand requests, advance review cooldowns,
+ // bind the synthetic app-review marker, and spend `capacity` — side effects a
+ // downstream hold cannot take back.
+ const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));
+
+ it('bails on the runner hold before doing any tier work', () => {
+ const holdIdx = dequeueFn.indexOf('isRunnerHolding');
+ expect(holdIdx, 'dequeueNextTask must consult the runner hold').toBeGreaterThan(-1);
+ expect(holdIdx, 'the hold must be checked before capacity is computed')
+ .toBeLessThan(dequeueFn.indexOf('createDequeueCapacity'));
+ });
+
+ it('gates the immediate user-task spawn on the same predicate', () => {
+ const immediateFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function tryImmediateSpawn'));
+ expect(immediateFn).toMatch(/isRunnerHolding/);
+ });
+
+ // Direct mode has no runner to be down; probing there would hold every spawn
+ // on an install that never runs the cos-runner app.
+ it('is a no-op in direct mode', () => {
+ const holdFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function isRunnerHolding'));
+ expect(holdFn).toMatch(/if\s*\(!useRunner\)\s*return false/);
+ });
});
describe('addTask — first-line dedup', () => {
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index 946c8216d7..e64a5e35b2 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -88,10 +88,18 @@ const createTuiProxy = (sessionId, pid, state) => {
export function initCosRunnerConnection() {
if (socket) return;
+ // Reconnect FOREVER. The runner is a separate PM2 app the user can stop from
+ // the Apps page (or that PM2 can hold down through a long restart), and it is
+ // the only transport for `agent:output` / `agent:completed`. A finite attempt
+ // budget — this was 10 attempts at 1s, so ~10 seconds — permanently gave up on
+ // a runner that came back a minute later, leaving this server connected to
+ // nothing while `useRunner` still routed every spawn at it. The capped backoff
+ // keeps a long outage cheap (one probe every 10s) instead of a 1s hot loop.
socket = io(COS_RUNNER_URL, {
reconnection: true,
- reconnectionAttempts: 10,
- reconnectionDelay: 1000
+ reconnectionAttempts: Infinity,
+ reconnectionDelay: 1000,
+ reconnectionDelayMax: 10000
});
const dispatch = (event, data) => {
@@ -197,20 +205,51 @@ export function onCosRunnerEvent(event, handler) {
}
/**
- * Check if CoS Runner is available
+ * The one `GET /health` every liveness question in this module goes through.
+ * Resolves the raw response (or null if the runner never answered) — callers
+ * decide whether they want the boolean or the parsed body.
+ */
+const probeRunnerHealth = (timeoutMs) =>
+ fetchWithTimeout(`${COS_RUNNER_URL}/health`, {}, timeoutMs)
+ .then(response => (response?.ok ? response : null), () => null);
+
+/**
+ * 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.
*/
export async function isRunnerAvailable() {
- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/health`, {}, 10000).catch(() => null);
- if (!response || !response.ok) return false;
- return true;
+ return (await probeRunnerHealth(10000)) !== null;
+}
+
+/**
+ * Is the runner reachable right now?
+ *
+ * Answered for free from the socket this module already owns: in runner mode it
+ * is connected whenever the runner is up, and socket.io flips the flag the
+ * moment the runner goes away — no HTTP round-trip on the path that asks this
+ * most (a dequeue during an outage). The probe is only the cold path, for a
+ * caller asking before `initCosRunnerConnection()` has ever run.
+ *
+ * Caveat worth knowing: after a hard SIGKILL the flag can read `true` until
+ * socket.io's ping window closes. A graceful `pm2 stop` — the case this exists
+ * for — disconnects immediately.
+ */
+export async function isRunnerReachable() {
+ if (socket) return socket.connected;
+ return (await probeRunnerHealth(2000)) !== null;
}
/**
* Get runner health status
*/
export async function getRunnerHealth() {
- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/health`, {}, 10000).catch(() => null);
- if (!response || !response.ok) {
+ const response = await probeRunnerHealth(10000);
+ if (!response) {
return { available: false, error: 'Runner not available' };
}
const data = await readRunnerJson(response);
diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.js
index c6f8e6ad04..ebd7b074c2 100644
--- a/server/services/cosRunnerClient.test.js
+++ b/server/services/cosRunnerClient.test.js
@@ -28,6 +28,7 @@ import {
initCosRunnerConnection,
onCosRunnerEvent,
isRunnerAvailable,
+ isRunnerReachable,
getRunnerHealth,
spawnAgentViaRunner,
getActiveAgentsFromRunner,
@@ -59,14 +60,20 @@ describe('cosRunnerClient', () => {
// initCosRunnerConnection
// ===========================================================================
describe('initCosRunnerConnection', () => {
- it('should create a socket connection with correct options', () => {
+ // The attempt budget is UNBOUNDED on purpose: the runner is a separate PM2
+ // app the user can stop for as long as they like, and this socket is the
+ // only transport for agent output/completion events. A finite budget (this
+ // was 10 attempts at 1s) permanently gave up on a runner that came back a
+ // minute later. The delay cap keeps a long outage to one probe every 10s.
+ it('should create a socket connection that reconnects indefinitely with capped backoff', () => {
initCosRunnerConnection();
expect(io).toHaveBeenCalledWith(
expect.stringContaining('5558'),
expect.objectContaining({
reconnection: true,
- reconnectionAttempts: 10,
- reconnectionDelay: 1000
+ reconnectionAttempts: Infinity,
+ reconnectionDelay: 1000,
+ reconnectionDelayMax: 10000
})
);
});
@@ -141,6 +148,27 @@ describe('cosRunnerClient', () => {
});
});
+ // ===========================================================================
+ // isRunnerReachable — the spawn-path liveness gate
+ // ===========================================================================
+ describe('isRunnerReachable', () => {
+ // This is asked on every dispatch, and during an outage on every dequeue
+ // trigger. The socket this module already owns holds the answer, so the
+ // steady-state cost must be zero I/O.
+ it('reads the socket instead of probing once the connection exists', async () => {
+ initCosRunnerConnection();
+
+ await expect(isRunnerReachable()).resolves.toBe(true);
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+
+ capturedSocket.connected = false;
+ await expect(isRunnerReachable()).resolves.toBe(false);
+ expect(fetchWithTimeout).not.toHaveBeenCalled();
+
+ capturedSocket.connected = true;
+ });
+ });
+
// ===========================================================================
// getRunnerHealth
// ===========================================================================
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 1d1c967791..0e81cf4394 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -34,7 +34,7 @@ import { existsSync } from 'fs';
import { emitLog, cosEvents } from './cosEvents.js';
import { updateAgent } from './cosAgentLifecycle.js';
import { initProviderStatus } from './providerStatus.js';
-import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './cosRunnerClient.js';
+import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable, isRunnerReachable } from './cosRunnerClient.js';
import { PATHS } from '../lib/fileUtils.js';
import { loadSlashdoFile } from '../lib/slashdoLoader.js';
import { getRunnerOutputBatcher, flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
@@ -42,7 +42,8 @@ import { syncRunnerAgents } from './agentRunnerSync.js';
import { handleAgentCompletion } from './agentLifecycle.js';
import { cleanupOrphanedAgents } from './agentManagement.js';
import { completeAgentRun } from './agentRunTracking.js';
-import { runnerAgents, setUseRunner } from './agentState.js';
+import { runnerAgents, setUseRunner, useRunner } from './agentState.js';
+import { releaseAppReviewMarker } from './appActivity.js';
// This module's own event wiring drives three LIFECYCLE TRANSITIONS, so it takes
// them from the facade rather than from the three separate leaves that happen to
// implement them (#3450). It can: nothing the facade imports imports this module
@@ -51,6 +52,10 @@ import { completeAgent, spawnAgentForTask, terminateAgent } from './agentOrchest
const RUNS_DIR = PATHS.runs;
+// Coalesce reconnect storms (a crash-looping runner) into one dequeue.
+const RECONNECT_DEQUEUE_DEBOUNCE_MS = 1000;
+let reconnectDequeueTimer = null;
+
/**
* Load a slashdo command from the bundled submodule, resolving !`cat` lib includes inline.
*/
@@ -123,6 +128,29 @@ async function runInitSpawner() {
console.log(`🔄 Recovered ${synced} agents from CoS Runner`);
}
+ // 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');
+ });
+
+ 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?.();
+ });
+
// Set up event handlers for runner events
onCosRunnerEvent('agent:output', async (data) => {
const { agentId, text } = data;
@@ -197,6 +225,31 @@ async function runInitSpawner() {
}
cosEvents.on('task:ready', async (task) => {
+ // Runner-down HOLD, at the one chokepoint all seven `task:ready` emitters
+ // funnel through. 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.
+ //
+ // 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 two
+ // releases below are the same ones the spawn body owns.
+ if (useRunner && !(await isRunnerReachable())) {
+ emitLog('debug', `⏸️ Holding task ${task.id} — CoS Runner is down`, { taskId: task.id });
+ await releaseAppReviewMarker(task.metadata?.app).catch(err =>
+ emitLog('warn', `Failed to release app review marker for ${task.metadata?.app}: ${err.message}`, { taskId: task.id })
+ );
+ // Clears `spawningJobIds` immediately and re-registers the cron schedule.
+ // Without it an autonomous job sits wedged until the scheduler's 5-minute
+ // spawn timeout — per job, per outage.
+ if (task.metadata?.jobId) {
+ cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });
+ }
+ return;
+ }
try {
await spawnAgentForTask(task);
} catch (err) {
diff --git a/server/services/subAgentSpawner.runnerHold.test.js b/server/services/subAgentSpawner.runnerHold.test.js
new file mode 100644
index 0000000000..7f6e0e4c8b
--- /dev/null
+++ b/server/services/subAgentSpawner.runnerHold.test.js
@@ -0,0 +1,156 @@
+/**
+ * Runner-down HOLD at the dispatch chokepoint, and the reconnect that releases it.
+ *
+ * `portos-cos` is a separate PM2 app the user can stop from the Apps page, and
+ * in runner mode it owns every agent process. Dispatching into a stopped runner
+ * is not a task failure, but both spawn arms recorded it as one — see the
+ * `task:ready` listener in subAgentSpawner.js for the two failure modes.
+ *
+ * The hold lives in that listener, not inside `runAgentSpawn`, because a hold
+ * below the spawn body's entry returns past `releaseAppReviewMarker` and strands
+ * the synthetic "in review" marker for the whole outage (issue #989). The two
+ * side effects the dequeue tiers already committed — that marker and the
+ * scheduler's `spawningJobIds` reservation — are released here instead.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const runnerHandlers = new Map();
+
+vi.mock('./cosRunnerClient.js', () => ({
+ onCosRunnerEvent: vi.fn((event, handler) => { runnerHandlers.set(event, handler); }),
+ initCosRunnerConnection: vi.fn(),
+ isRunnerAvailable: vi.fn().mockResolvedValue(true),
+ isRunnerReachable: vi.fn().mockResolvedValue(true),
+}));
+
+vi.mock('./cosEvents.js', () => ({
+ emitLog: vi.fn(),
+ cosEvents: { emit: vi.fn(), on: vi.fn((event, handler) => { taskHandlers.set(event, handler); }) },
+}));
+
+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('./agentOrchestrator.js', () => ({
+ completeAgent: vi.fn(),
+ spawnAgentForTask: vi.fn().mockResolvedValue('agent-1'),
+ terminateAgent: vi.fn(),
+}));
+vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));
+
+const taskHandlers = new Map();
+
+import { initSpawner } from './subAgentSpawner.js';
+import { cosEvents, emitLog } from './cosEvents.js';
+import { isRunnerReachable } from './cosRunnerClient.js';
+import { spawnAgentForTask } from './agentOrchestrator.js';
+import { releaseAppReviewMarker } from './appActivity.js';
+import { setUseRunner } from './agentState.js';
+
+const dispatch = (task) => taskHandlers.get('task:ready')(task);
+
+describe('subAgentSpawner — runner-down hold', () => {
+ beforeEach(async () => {
+ await initSpawner();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ setUseRunner(true);
+ isRunnerReachable.mockResolvedValue(true);
+ });
+
+ it('spawns normally while the runner is up', async () => {
+ await dispatch({ id: 'cos-1', metadata: {} });
+
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds the task instead of dispatching it while the runner is down', async () => {
+ isRunnerReachable.mockResolvedValue(false);
+
+ await dispatch({ id: 'cos-2', metadata: {} });
+
+ // Never reaches the spawn body, so the task keeps its `pending` record: no
+ // claim, no agent, no retry charged, no `spawn-rejected` finalization.
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+ });
+
+ // Issue #989: the priority-0 tier binds a synthetic "in review" marker before
+ // emitting `task:ready`. A hold that skipped this would leave the app reading
+ // "in review" until the next daemon restart.
+ it('releases the app-review marker the dequeue tier already bound', async () => {
+ isRunnerReachable.mockResolvedValue(false);
+
+ await dispatch({ id: 'cos-3', metadata: { app: 'some-app' } });
+
+ expect(releaseAppReviewMarker).toHaveBeenCalledWith('some-app');
+ });
+
+ // cosJobScheduler reserves `spawningJobIds` before the emit and clears it on
+ // `job:spawned` / `job:spawn-failed`. Without this the job stays wedged until
+ // the scheduler's 5-minute spawn timeout — per job, per outage.
+ it('frees an autonomous job\'s spawn reservation so its schedule re-registers', async () => {
+ isRunnerReachable.mockResolvedValue(false);
+
+ await dispatch({ id: 'cos-4', metadata: { jobId: 'job-7' } });
+
+ expect(cosEvents.emit).toHaveBeenCalledWith('job:spawn-failed', { jobId: 'job-7' });
+ });
+
+ it('does not consult the runner in direct mode', async () => {
+ setUseRunner(false);
+ isRunnerReachable.mockResolvedValue(false);
+
+ await dispatch({ id: 'cos-5', metadata: {} });
+
+ expect(isRunnerReachable).not.toHaveBeenCalled();
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('subAgentSpawner — runner connection events', () => {
+ beforeEach(async () => {
+ await initSpawner();
+ vi.clearAllMocks();
+ });
+
+ it('warns once when the runner drops, rather than once per held task', () => {
+ runnerHandlers.get('connection:lost')();
+
+ const warnings = emitLog.mock.calls.filter(([level]) => level === 'warn');
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0][1]).toMatch(/CoS Runner disconnected/);
+ });
+
+ it('re-runs the dequeue when the runner returns, so held tasks spawn', async () => {
+ vi.useFakeTimers();
+ runnerHandlers.get('connection:ready')();
+ await vi.advanceTimersByTimeAsync(1000);
+ vi.useRealTimers();
+
+ expect(cosEvents.emit).toHaveBeenCalledWith('cos:dequeue-requested');
+ });
+
+ // `reconnectionAttempts` is unbounded, so a crash-looping runner emits
+ // `connect` repeatedly; each un-debounced edge would drive a full five-tier
+ // dequeue cycle.
+ it('coalesces a reconnect storm into one dequeue', async () => {
+ vi.useFakeTimers();
+ runnerHandlers.get('connection:ready')();
+ runnerHandlers.get('connection:ready')();
+ runnerHandlers.get('connection:ready')();
+ await vi.advanceTimersByTimeAsync(1000);
+ vi.useRealTimers();
+
+ const dequeues = cosEvents.emit.mock.calls.filter(([event]) => event === 'cos:dequeue-requested');
+ expect(dequeues).toHaveLength(1);
+ });
+});