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

settle the CoS spawn window so one task stops counting as both pending and active

[._.]/ Adam Eivyb8b88c79dc3b
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index 8a0e878ac1..714653dc2e 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -22,6 +22,7 @@ import SortableTaskItem from './SortableTaskItem';
import TaskAddForm from '../TaskAddForm';
import { MicroGlyph, SchematicLabel } from '../../micrographics';
import useAssignableInstances from '../../../hooks/useAssignableInstances';
+import { runningAgentsByTaskId, isSpawningTask } from '../../../lib/cosSpawnWindow';
// Maps a task-section status → micrographic glyph spec. Animation only on
// states where motion communicates real work happening (running tasks).
@@ -71,22 +72,15 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
task.id === selectedTaskId && source === selectedTaskSource
);
- // The live agent working each task, keyed by task id. spawnAgentForTask registers its
- // agent as running BEFORE flipping the task off 'pending', so between those
- // two writes a task reads 'pending' on the task list and 'running' on the
- // agent list — and the row showed up under Pending AND as an active agent.
- // Defense in depth, not the whole fix: ChiefOfStaff now subscribes to the
- // store's task events so the flip lands in ~400ms instead of a 30s poll. This
- // settles the render from whichever of the two signals arrived first, so the
- // split is right even when an event is delayed or dropped.
- // The map (rather than a Set of ids) is what lets an Active row offer a relaunch
- // onto a different provider/model without fetching the agent list of its own.
- const runningAgentByTaskId = useMemo(() => new Map(
- agents.filter(a => a.status === 'running' && a.taskId).map(a => [a.taskId, a])
- ), [agents]);
+ // The live agent working each task, keyed by task id — mid-spawn tasks are
+ // active, not queued (lib/cosSpawnWindow.js). Settled client-side here rather
+ // than trusting the route's `spawning` stamp because this tab also has the
+ // socket agent feed, which lands ~400ms ahead of the next task refetch; the
+ // map is what lets an Active row offer relaunch without its own agent fetch.
+ const runningAgentByTaskId = useMemo(() => runningAgentsByTaskId(agents), [agents]);
const isSpawning = useCallback(
- (task) => task.status === 'pending' && runningAgentByTaskId.has(task.id),
+ (task) => isSpawningTask(task, runningAgentByTaskId),
[runningAgentByTaskId]
);
diff --git a/client/src/components/cos/tabs/TasksTab.test.jsx b/client/src/components/cos/tabs/TasksTab.test.jsx
index 527e0f129f..d14546bb58 100644
--- a/client/src/components/cos/tabs/TasksTab.test.jsx
+++ b/client/src/components/cos/tabs/TasksTab.test.jsx
@@ -70,11 +70,14 @@ describe('TasksTab Run Now', () => {
// the agent list rather than rendering the task in both sections at once.
describe('TasksTab spawning window', () => {
const pendingTask = (id, extra = {}) => ({ id, description: `Task ${id}`, status: 'pending', metadata: {}, ...extra });
+ // `startedAt` is how the settlement tells a live spawn from a zombie record —
+ // registerAgent always stamps it. See server/lib/cosSpawnWindow.js.
+ const liveAgent = (id, taskId, ageMs = 0) => ({ id, status: 'running', taskId, startedAt: new Date(Date.now() - ageMs).toISOString() });
it('moves a pending task with a live agent out of Pending and into Active', async () => {
renderTab({
tasks: { user: { tasks: [pendingTask('task-spawning'), pendingTask('task-waiting')] }, cos: { tasks: [] } },
- agents: [{ id: 'agent-1', status: 'running', taskId: 'task-spawning' }],
+ agents: [liveAgent('agent-1', 'task-spawning')],
liveOutputs: { 'agent-1': [{ line: 'Implementing the change' }] },
});
@@ -95,10 +98,24 @@ describe('TasksTab spawning window', () => {
expect(screen.queryByText(/^Active \(/)).not.toBeInTheDocument();
});
+ it('hands the task back to Pending once its holder is too old to be mid-spawn', async () => {
+ // Past SPAWN_CLAIM_GRACE_MS a `running` agent on a `pending` task is a zombie,
+ // not a spawn in flight — and `forceSpawnTask` supersedes it on the same
+ // bound. Keeping it under Active would hide the stuck task in a section whose
+ // rows are presented as work already underway.
+ renderTab({
+ tasks: { user: { tasks: [pendingTask('task-stuck')] }, cos: { tasks: [] } },
+ agents: [liveAgent('agent-1', 'task-stuck', 10 * 60 * 1000)],
+ });
+
+ await waitFor(() => expect(screen.getByText('Pending (1)')).toBeInTheDocument());
+ expect(screen.queryByText(/^Active \(/)).not.toBeInTheDocument();
+ });
+
it('keeps Process now reachable for a task whose agent record is stuck running', async () => {
renderTab({
tasks: { user: { tasks: [pendingTask('task-spawning')] }, cos: { tasks: [] } },
- agents: [{ id: 'agent-1', status: 'running', taskId: 'task-spawning' }],
+ agents: [liveAgent('agent-1', 'task-spawning')],
});
await waitFor(() => expect(screen.getByText('Active (1)')).toBeInTheDocument());
diff --git a/client/src/components/system-resources/QueuesPanel.jsx b/client/src/components/system-resources/QueuesPanel.jsx
index 738fbac7df..5369a57f4e 100644
--- a/client/src/components/system-resources/QueuesPanel.jsx
+++ b/client/src/components/system-resources/QueuesPanel.jsx
@@ -44,8 +44,12 @@ export default function QueuesPanel() {
...internal.map((task) => ({ ...task, source: 'internal' })),
];
}, [data]);
- const pending = tasks.filter((task) => task.status === 'pending');
- const running = tasks.filter((task) => task.status === 'in_progress');
+ // `spawning` is stamped by GET /api/cos/tasks: a task keeps `status: 'pending'`
+ // for a beat after its agent registers as running, and counting it here would
+ // put the one task being worked under BOTH cards — and offer "Run now" for a
+ // run already underway. See server/lib/cosSpawnWindow.js.
+ const pending = tasks.filter((task) => task.status === 'pending' && !task.spawning);
+ const running = tasks.filter((task) => task.status === 'in_progress' || task.spawning);
const awaitingApproval = pending.filter((task) => task.approvalRequired);
const queueKnown = data != null;
diff --git a/client/src/components/system-resources/QueuesPanel.test.jsx b/client/src/components/system-resources/QueuesPanel.test.jsx
index 399d875b2c..4c87849a25 100644
--- a/client/src/components/system-resources/QueuesPanel.test.jsx
+++ b/client/src/components/system-resources/QueuesPanel.test.jsx
@@ -14,6 +14,10 @@ vi.mock('../media/MediaJobsQueue.jsx', () => ({
const QueuesPanel = (await import('./QueuesPanel.jsx')).default;
+// The count cards render their label and value as sibling divs; read the value
+// without pinning which wrapper element holds them.
+const countCard = (label) => screen.getByText(label).nextElementSibling?.textContent;
+
const renderPanel = () => render(
<MemoryRouter>
<QueuesPanel />
@@ -49,4 +53,23 @@ describe('QueuesPanel', () => {
'/cos/tasks?task=review-7&source=internal',
);
});
+
+ // The spawn window: a task keeps `status: 'pending'` for a beat after its
+ // agent registers as running, so the one task being worked was counted on BOTH
+ // cards and still offered a "Run now" button for a run already underway. The
+ // route settles it and stamps `spawning`; the panel must honour that rather
+ // than re-reading the raw status.
+ it('counts a task the server marked mid-spawn as running, not pending', async () => {
+ api.getCosTasks.mockResolvedValue({
+ user: { tasks: [{ id: 'user/42', description: 'Run an example task', status: 'pending', spawning: true }] },
+ cos: { tasks: [] },
+ });
+
+ renderPanel();
+
+ expect(await screen.findByText('No pending agent tasks.')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Run task user/42 now' })).not.toBeInTheDocument();
+ expect(countCard('Agent pending')).toBe('0');
+ expect(countCard('Agent running')).toBe('1');
+ });
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f617dd6565..79cd9f78fd 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -141,6 +141,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `falVideoHandoff.js` | `buildFalH3MaxPrompt(prompt, negativePrompt)` composes the provider-neutral shot prompt fal's free MiniMax H3 Max tool is driven with; `FAL_H3_MAX_FREE_URL` and `FAL_H3_MAX_FREE_ALLOWANCE_NOTE` carry the tool URL and current vendor allowance copy. The free web allowance is deliberately a handoff, not the separately metered fal API. |
| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
| `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |
+| `cosSpawnWindow.js` | Re-export of the spawn-window settlement from the pure server leaf `server/lib/cosSpawnWindow.js`. A task keeps `status: 'pending'` for a beat after its agent registers as `running`, so a view rendering both lists must decide which side it belongs to (ACTIVE, until `SPAWN_CLAIM_GRACE_MS`). `GET /api/cos/tasks` already settles its payload, so most surfaces just read `task.spawning`; `cos/tabs/TasksTab.jsx` settles client-side because it also has the socket agent feed, which lands ahead of the next task refetch. |
| `cosTaskType.js` | CoS task-learning bucket resolver for ETA surfaces: `extractCosTaskType(task)` mirrors the server's metadata-first `extractTaskType` handling for live tasks and archived-agent projections, so `self-improve:*`, `user-task`, and fallback estimates use the same history bucket that recorded the run. |
| `diffLines.js` | `diffLineBlocks(oldText, newText)` → `{ blocks }` (`{ type: 'same', lines }` / `{ type: 'change', oldLines, newLines }`) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell `LINE_DIFF_CELL_CAP` guard. The structural layer behind `HunkDiff` (collapse same-blocks to context, word-diff each change-block). |
| `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard on the trimmed middle). Shared by `InlineDiff` (stacked), `SideBySideDiff` (columnar), and `HunkDiff`'s change blocks. |
diff --git a/client/src/lib/cosSpawnWindow.js b/client/src/lib/cosSpawnWindow.js
new file mode 100644
index 0000000000..39e8fe8ce9
--- /dev/null
+++ b/client/src/lib/cosSpawnWindow.js
@@ -0,0 +1,17 @@
+/**
+ * Re-export of the CoS spawn-window settlement from the pure server leaf
+ * `server/lib/cosSpawnWindow.js`.
+ *
+ * Importing rather than copying means the Tasks tab and the server's own
+ * counters cannot drift into disagreeing about which side of the pending/active
+ * line a mid-spawn task falls on. See that file for the full contract.
+ */
+export {
+ SPAWN_CLAIM_GRACE_MS,
+ spawnClaimAgeMs,
+ runningAgentsByTaskId,
+ spawningAgentForTask,
+ isSpawningTask,
+ withoutSpawningTasks,
+ unclaimedTaskIds,
+} from '../../../server/lib/cosSpawnWindow.js';
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 0fcbb0bb35..6625a111e2 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -107,6 +107,7 @@ export * from './clipboard.js';
export * from './effortCostEstimate.js';
export * from './compareHelpers.js';
export * from './consoleFilters.js';
+export * from './cosSpawnWindow.js';
export * from './cosTaskType.js';
export * from './diffLines.js';
export * from './diffWords.js';
diff --git a/server/lib/README.md b/server/lib/README.md
index 4da19b2e00..5032be5c45 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -61,6 +61,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. |
| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). |
| `cosAgentListProjection.js` | What a CoS agent LIST response may carry. `toAgentListItem` / `toAgentListItems` drop the transcript and bound `metadata.taskDescription` to `AGENT_LIST_DESCRIPTION_CHARS` (2000, on a clause boundary via `textUtils.clampToCharLimit`), stamping `taskDescriptionTruncated` + the original `taskDescriptionLength` so the UI can hydrate the rest from `GET /api/cos/agents/:id`. That one field was 68% of the Agents tab payload — p50 is 75 characters but a pasted-prompt description runs past 50 KB, and `GET /api/cos/agents` sits on the first-paint critical path of every `/cos/*` tab and re-reads every 30s. Applied at the ROUTE layer only: `getAgents`/`getAgentsByDate` also feed the weekly digest and CoS reports, which need the whole text. |
+| `cosSpawnWindow.js` | The one settlement for the window in which a CoS task is BOTH pending and active. `spawnAgentForTask` registers an agent as `running` before it flips that agent's task off `pending`, so a surface counting the task list and the agent list independently reports the same task as queued AND active — "1 pending, 1 active" for a queue of one, clearing only on a later poll. Reversing the two writes would not close it (two stores, and the UI joins the lists from two separate HTTP reads anyway). `runningAgentsByTaskId(agents)` → `Map<taskId, agent>` (keyed by `taskId` or `metadata.taskId`, matching `agentManagement.js`), `isSpawningTask` / `withoutSpawningTasks` / `countSpawningTasks` / `unclaimedTaskIds` (the id-list form) and `settleTaskSourceSpawnWindow(source, …)`, which stamps `spawning` and moves the task from `grouped.pending` to `grouped.in_progress` for a RESPONSE — that is how `GET /api/cos/tasks` spares its consumers from knowing the window exists, while the dispatch readers of `getAllTasks()` keep the raw truth. **Bounded by `SPAWN_CLAIM_GRACE_MS`** (60s, shared with `services/cos.js#forceSpawnTask`): past it a `pending` task under a `running` agent is a zombie, and settling it as active forever would hide the stuck task from every count AND from the list that renders its "Run now" recovery. Pure leaf with no imports, so `client/src/lib/cosSpawnWindow.js` re-exports it. |
| `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |
| `persistentMindIssues.js` | Persistent-mind forge-issue contracts: bounded list/file schemas, the required-both dispatch axes, the closed category-label vocabulary with its lazily-created colors, the `persistent-mind` attribution label, and the title key the duplicate guard compares on. |
| `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, bounded strictly-allowlisted per-provider-call execution receipts (route, run id, elapsed time, outcome, usage that stays `unknown` rather than zero) with their safe public projection, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. |
diff --git a/server/lib/cosSpawnWindow.js b/server/lib/cosSpawnWindow.js
new file mode 100644
index 0000000000..460713c3e2
--- /dev/null
+++ b/server/lib/cosSpawnWindow.js
@@ -0,0 +1,121 @@
+/**
+ * The window in which one CoS task is BOTH pending and active, and the single
+ * settlement every reader that pairs the task list with the agent list makes.
+ *
+ * `spawnAgentForTask` (services/agentLifecycle.js) registers an agent as
+ * `running` BEFORE it flips that agent's task off `pending`. Between those two
+ * writes the task reads `pending` on the task list and `running` on the agent
+ * list, so a surface that counts each list on its own reports "1 pending" AND
+ * "1 active" for what is one task — and the phantom only clears on a later
+ * poll, which is why it reads as a counter stuck rather than as a race.
+ * Reversing the two writes would not close it: they land in two different
+ * stores, and the UI joins the lists from two separate HTTP reads anyway.
+ *
+ * A task a live agent already holds is ACTIVE, never queued. Counting it as
+ * queued is the direction that misleads: it invites the user (and the dequeue
+ * surfaces) to believe there is backlog waiting on a free slot when there is
+ * none.
+ *
+ * BOUNDED BY `SPAWN_CLAIM_GRACE_MS`, for the reason `forceSpawnTask` is. Past
+ * that window a `pending` task carrying a `running` agent is not mid-spawn, it
+ * is a BROKEN state — a zombie record whose process died before the sweep
+ * caught it. Settling it as active indefinitely would hide the stuck task from
+ * every pending count AND drop it out of the lists that render its "Run now"
+ * recovery, so the bound hands it back as queued work the user can restart.
+ *
+ * Pure leaf with no imports, so `client/src/lib/cosSpawnWindow.js` re-exports
+ * it and the UI shares this settlement rather than keeping a copy that can
+ * drift.
+ */
+
+/**
+ * How long a `running` agent on a still-`pending` task is read as mid-spawn
+ * rather than as a zombie. `services/cos.js#forceSpawnTask` bounds its
+ * live-agent refusal on the same constant, so the count, the list, and the
+ * button agree about which tasks are still yours to start.
+ */
+export const SPAWN_CLAIM_GRACE_MS = 60_000;
+
+/** How long ago this agent started, or `Infinity` when it never said. */
+export function spawnClaimAgeMs(agent, now = Date.now()) {
+ const startedAt = new Date(agent?.startedAt ?? NaN).getTime();
+ return Number.isFinite(startedAt) ? now - startedAt : Infinity;
+}
+
+/**
+ * Map a task id → the live agent holding it.
+ *
+ * A Map rather than a Set of ids because the CoS Tasks tab renders an Active
+ * row's relaunch control off the agent record, and the age bound above needs
+ * the agent's `startedAt`.
+ *
+ * `taskId` falls back to `metadata.taskId` — `registerAgent` stamps the
+ * top-level field, but the resume/relaunch paths in `agentManagement.js` read
+ * both, and a settlement that recognized fewer holders than they do would
+ * disagree with them about which task is running.
+ */
+export function runningAgentsByTaskId(agents) {
+ const held = new Map();
+ for (const agent of agents || []) {
+ if (agent?.status !== 'running') continue;
+ const taskId = agent.taskId || agent.metadata?.taskId;
+ if (taskId) held.set(taskId, agent);
+ }
+ return held;
+}
+
+/** The live agent mid-spawn on this task id, or `null`. */
+export function spawningAgentForTask(taskId, runningAgents, { now = Date.now(), graceMs = SPAWN_CLAIM_GRACE_MS } = {}) {
+ const holder = runningAgents?.get(taskId) || null;
+ return holder && spawnClaimAgeMs(holder, now) < graceMs ? holder : null;
+}
+
+/** A task the task list still reads `pending` while a live agent already holds it. */
+export function isSpawningTask(task, runningAgents, options) {
+ return task?.status === 'pending' && Boolean(spawningAgentForTask(task.id, runningAgents, options));
+}
+
+/** `tasks` minus the ones a live agent already holds — the honest queued set. */
+export function withoutSpawningTasks(tasks, runningAgents, options) {
+ return (tasks || []).filter((task) => !isSpawningTask(task, runningAgents, options));
+}
+
+/** How many of `tasks` are mid-spawn — what the queued set sheds, and the active set owes. */
+export function countSpawningTasks(tasks, runningAgents, options) {
+ return (tasks || []).filter((task) => isSpawningTask(task, runningAgents, options)).length;
+}
+
+/** The id-list form, for callers that read pending task IDS rather than records. */
+export function unclaimedTaskIds(taskIds, runningAgents, options) {
+ return (taskIds || []).filter((id) => !spawningAgentForTask(id, runningAgents, options));
+}
+
+/**
+ * Settle one `{ tasks, grouped }` task source for a RESPONSE.
+ *
+ * Stamps `spawning: true` on each mid-spawn task and moves it from
+ * `grouped.pending` to `grouped.in_progress`, so a consumer counting
+ * `grouped.pending.length` gets the honest queue depth without knowing this
+ * module exists — the failure mode being that every new reader of the payload
+ * has to remember to fetch the agent list and subtract.
+ *
+ * `status` is deliberately left at its persisted `pending`: it is what the
+ * record says, a client may PATCH against it, and `spawning` is the flag a row
+ * renders its mid-spawn state from. Only the API layer settles — the dispatch
+ * readers of `getAllTasks()` (task generation, retry revival, dedup) must keep
+ * seeing the raw truth.
+ */
+export function settleTaskSourceSpawnWindow(source, runningAgents, options) {
+ if (!source || typeof source !== 'object' || !Array.isArray(source.tasks)) return source;
+ const spawningIds = new Set(
+ source.tasks.filter((task) => isSpawningTask(task, runningAgents, options)).map((task) => task.id)
+ );
+ if (spawningIds.size === 0) return source;
+ const stamp = (task) => (spawningIds.has(task?.id) ? { ...task, spawning: true } : task);
+ const grouped = source.grouped && {
+ ...source.grouped,
+ pending: (source.grouped.pending || []).filter((task) => !spawningIds.has(task?.id)),
+ in_progress: [...(source.grouped.in_progress || []), ...(source.grouped.pending || []).filter((task) => spawningIds.has(task?.id)).map(stamp)],
+ };
+ return { ...source, tasks: source.tasks.map(stamp), ...(grouped ? { grouped } : {}) };
+}
diff --git a/server/lib/cosSpawnWindow.test.js b/server/lib/cosSpawnWindow.test.js
new file mode 100644
index 0000000000..3fe4f278a6
--- /dev/null
+++ b/server/lib/cosSpawnWindow.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect } from 'vitest';
+import {
+ SPAWN_CLAIM_GRACE_MS,
+ runningAgentsByTaskId,
+ isSpawningTask,
+ withoutSpawningTasks,
+ countSpawningTasks,
+ unclaimedTaskIds,
+ settleTaskSourceSpawnWindow,
+} from './cosSpawnWindow.js';
+
+const NOW = Date.UTC(2026, 0, 1, 12, 0, 0);
+const running = (taskId, ageMs = 0, extra = {}) => ({
+ id: `agent-${taskId}`, taskId, status: 'running', startedAt: new Date(NOW - ageMs).toISOString(), ...extra,
+});
+const pending = (id) => ({ id, status: 'pending' });
+const at = { now: NOW };
+
+describe('cosSpawnWindow', () => {
+ it('moves a mid-spawn task to the active side and leaves real backlog queued', () => {
+ // The defect this module exists for: the agent registers as `running` a beat
+ // before its task leaves `pending`, and a status module counting each list on
+ // its own read "1 pending" AND "1 active" for one task.
+ const tasks = [pending('user/42'), pending('sys-7')];
+ const agents = runningAgentsByTaskId([running('sys-7')]);
+
+ expect(withoutSpawningTasks(tasks, agents, at).map((t) => t.id)).toEqual(['user/42']);
+ expect(countSpawningTasks(tasks, agents, at)).toBe(1);
+ expect(unclaimedTaskIds(['user/42', 'sys-7'], agents, at)).toEqual(['user/42']);
+ });
+
+ it('hands a task back as queued once its holder is too old to be mid-spawn', () => {
+ // A zombie agent record on a still-pending task is a BROKEN state, not a
+ // spawn in flight. Settling it as active forever would hide the stuck task
+ // from every count AND drop it out of the list that renders its "Run now".
+ const tasks = [pending('user/42')];
+ const fresh = runningAgentsByTaskId([running('user/42', SPAWN_CLAIM_GRACE_MS - 1)]);
+ const stale = runningAgentsByTaskId([running('user/42', SPAWN_CLAIM_GRACE_MS)]);
+
+ expect(withoutSpawningTasks(tasks, fresh, at)).toEqual([]);
+ expect(withoutSpawningTasks(tasks, stale, at)).toEqual(tasks);
+ });
+
+ it('treats an agent that never recorded a start as stale, never as mid-spawn', () => {
+ // Same direction as the bound above: an unmeasurable claim may not be the
+ // thing that hides a task from the queue it is actually sitting in.
+ const agents = runningAgentsByTaskId([{ id: 'agent-1', taskId: 'user/42', status: 'running' }]);
+ expect(isSpawningTask(pending('user/42'), agents, at)).toBe(false);
+ });
+
+ it('ignores an agent that is not running, so a finished run cannot hide a real backlog', () => {
+ for (const status of ['completed', 'paused', 'failed']) {
+ const agents = runningAgentsByTaskId([{ ...running('user/42'), status }]);
+ expect(withoutSpawningTasks([pending('user/42')], agents, at)).toHaveLength(1);
+ }
+ });
+
+ it('never settles a task that is not pending', () => {
+ // in_progress / blocked / completed tasks are already counted by their own
+ // status; settling them here would double-discount a running task.
+ const agents = runningAgentsByTaskId([running('user/42')]);
+ for (const status of ['in_progress', 'blocked', 'completed', 'challenged']) {
+ expect(isSpawningTask({ id: 'user/42', status }, agents, at)).toBe(false);
+ }
+ });
+
+ it('reads a missing agent list and a missing task list as nothing, not as a throw', () => {
+ // Every caller reaches this off a `.catch(() => null)` read, so a failed probe
+ // must degrade to "no claims to settle" rather than take the status route down.
+ const agents = runningAgentsByTaskId(null);
+ expect(agents.size).toBe(0);
+ expect(withoutSpawningTasks(null, agents, at)).toEqual([]);
+ expect(unclaimedTaskIds(undefined, agents, at)).toEqual([]);
+ expect(isSpawningTask(pending('user/42'), null, at)).toBe(false);
+ });
+
+ it('recognizes a holder that names its task only in metadata', () => {
+ // `agentManagement.js`'s resume/relaunch paths read both spellings; a
+ // settlement that saw fewer holders than they do would disagree with them.
+ const agents = runningAgentsByTaskId([
+ { id: 'agent-1', status: 'running', startedAt: new Date(NOW).toISOString(), metadata: { taskId: 'user/42' } },
+ ]);
+ expect(isSpawningTask(pending('user/42'), agents, at)).toBe(true);
+ });
+
+ describe('settleTaskSourceSpawnWindow', () => {
+ const source = () => ({
+ type: 'user',
+ tasks: [pending('user/42'), pending('user/43'), { id: 'user/7', status: 'in_progress' }],
+ grouped: {
+ pending: [pending('user/42'), pending('user/43')],
+ in_progress: [{ id: 'user/7', status: 'in_progress' }],
+ },
+ });
+
+ it('regroups a mid-spawn task so a raw grouped.pending count is already honest', () => {
+ // This is what spares every consumer of GET /api/cos/tasks from having to
+ // know the window exists — the count they already write is the right one.
+ const agents = runningAgentsByTaskId([running('user/42')]);
+
+ const settled = settleTaskSourceSpawnWindow(source(), agents, at);
+
+ expect(settled.grouped.pending.map((t) => t.id)).toEqual(['user/43']);
+ expect(settled.grouped.in_progress.map((t) => t.id)).toEqual(['user/7', 'user/42']);
+ expect(settled.tasks.find((t) => t.id === 'user/42')).toMatchObject({ status: 'pending', spawning: true });
+ expect(settled.tasks.find((t) => t.id === 'user/43').spawning).toBeUndefined();
+ });
+
+ it('leaves a source with nothing mid-spawn exactly as it was', () => {
+ const untouched = source();
+ expect(settleTaskSourceSpawnWindow(untouched, runningAgentsByTaskId([]), at)).toBe(untouched);
+ expect(settleTaskSourceSpawnWindow(null, runningAgentsByTaskId([]), at)).toBeNull();
+ });
+ });
+});
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index c60de2c9b6..3007dc9c11 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -701,7 +701,15 @@ describe('deferred imports stay deferred (#6156)', () => {
// module gained an eager import (the per-module closure diff against the
// pre-merge tree shows only those three new entries growing). Measured after
// the merge: 112,982; the ceiling keeps the same ~300 of headroom.
-const MAX_STATIC_INSTANTIATIONS = 113300;
+// 113,300 → 113,700 (CoS spawn-window settlement): `lib/cosSpawnWindow.js` is a
+// dependency-free leaf, so it adds one node per closure that reaches it — six
+// server modules (`routes/cosTaskRoutes.js`, `routes/cosInsightRoutes.js`,
+// `routes/systemHealth.js`, `services/cos.js`, `services/activeProcessing.js`,
+// `services/systemResources.js`) plus its own suite. No subtree. Measured after
+// the change: 113,350 — the pre-change tree had already eroded to within single
+// digits of the old ceiling, so this restores the ~350 of headroom the recent
+// entries carry rather than leaving the next unrelated commit to trip it.
+const MAX_STATIC_INSTANTIATIONS = 113700;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/index.js b/server/lib/index.js
index 39792548f0..8255bb5365 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -37,6 +37,7 @@ export * as cosValidation from './cosValidation.js';
export * from './cronFields.js';
export * from './cronValidation.js';
export * from './cosAgentListProjection.js';
+export * from './cosSpawnWindow.js';
export * from './cosToolContracts.js';
export * as creativeCommissionValidation from './creativeCommissionValidation.js';
// The generation-key spec creativeCommissionValidation.js builds its Zod schema
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 211bbc3c2a..94a2b59176 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -166,6 +166,8 @@ describe('CoS Routes', () => {
// Reset all mocks
vi.clearAllMocks();
+ // GET /tasks settles its payload against the live agent list (#spawn window).
+ cos.getAgents.mockResolvedValue([]);
});
describe('GET /api/cos', () => {
diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.js
index 8de267cc0c..f4c940ecc5 100644
--- a/server/routes/cosInsightRoutes.js
+++ b/server/routes/cosInsightRoutes.js
@@ -10,6 +10,7 @@ import * as goalProgress from '../services/goalProgress.js';
import * as decisionLog from '../services/decisionLog.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { parsePagination } from '../lib/validation.js';
+import { runningAgentsByTaskId, withoutSpawningTasks } from '../lib/cosSpawnWindow.js';
import { detectIdleLeftoverBranches } from '../services/userActionDetectors.js';
const router = Router();
@@ -26,14 +27,17 @@ router.get('/activity-calendar', asyncHandler(async (req, res) => {
// GET /api/cos/actionable-insights - Get prioritized action items requiring user attention
// Surfaces the most important things to address right now across all CoS subsystems
router.get('/actionable-insights', asyncHandler(async (req, res) => {
- const [tasksData, learningSummary, healthCheck, notificationsModule, pendingFeedbackCount, leftoverFindings] = await Promise.all([
+ const [tasksData, learningSummary, healthCheck, notificationsModule, pendingFeedbackCount, leftoverFindings, agents] = await Promise.all([
cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),
taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),
cos.runHealthCheck().catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),
import('../services/notifications.js').catch(err => { console.error(`❌ Failed to load notifications: ${err.message}`); return null; }),
cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; }),
- detectIdleLeftoverBranches().catch(err => { console.error(`❌ Failed to detect leftover branches: ${err.message}`); return []; })
+ detectIdleLeftoverBranches().catch(err => { console.error(`❌ Failed to detect leftover branches: ${err.message}`); return []; }),
+ // Settles the pending list against live agents — see lib/cosSpawnWindow.js.
+ cos.getAgents().catch(err => { console.error(`❌ Failed to load agents: ${err.message}`); return []; })
]);
+ const runningAgents = runningAgentsByTaskId(agents);
const notificationsData = notificationsModule ? await notificationsModule.getNotifications({ unreadOnly: true, limit: 10 }).catch(() => []) : [];
@@ -175,7 +179,7 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {
}
// 7. Pending user tasks (informational)
- const pendingUserTasks = tasksData.user?.grouped?.pending || [];
+ const pendingUserTasks = withoutSpawningTasks(tasksData.user?.grouped?.pending, runningAgents);
if (pendingUserTasks.length > 0 && insights.length < 4) {
insights.push({
type: 'tasks',
@@ -211,16 +215,22 @@ router.get('/recent-tasks', asyncHandler(async (req, res) => {
// GET /api/cos/quick-summary - Get at-a-glance dashboard summary
// Combines today's activity and queue counts into one efficient call.
router.get('/quick-summary', asyncHandler(async (req, res) => {
- const [todayActivity, tasksData] = await Promise.all([
+ const [todayActivity, tasksData, agents] = await Promise.all([
cos.getTodayActivity(),
- cos.getAllTasks()
+ cos.getAllTasks(),
+ // The dashboard widget renders this queue total beside its own "N agents
+ // running" line, so a raw pending count showed the one task already being
+ // worked on both — see lib/cosSpawnWindow.js.
+ cos.getAgents().catch(() => [])
]);
+ const runningAgents = runningAgentsByTaskId(agents);
- // Count pending approvals from system tasks
+ // Count pending approvals from system tasks. Not settled: approval is a
+ // pre-spawn gate, so no live agent can hold one.
const pendingApprovals = tasksData.cos?.awaitingApproval?.length || 0;
// Count pending user tasks
- const pendingUserTasks = tasksData.user?.grouped?.pending?.length || 0;
+ const pendingUserTasks = withoutSpawningTasks(tasksData.user?.grouped?.pending, runningAgents).length;
res.json({
today: {
diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.js
index 247040a8c5..30fcc0124b 100644
--- a/server/routes/cosInsightRoutes.test.js
+++ b/server/routes/cosInsightRoutes.test.js
@@ -5,6 +5,7 @@ import insightRoutes from './cosInsightRoutes.js';
vi.mock('../services/cos.js', () => ({
getAllTasks: vi.fn(),
+ getAgents: vi.fn(async () => []),
runHealthCheck: vi.fn(),
getPendingAgentFeedbackCount: vi.fn(),
getTodayActivity: vi.fn(),
@@ -303,6 +304,29 @@ describe('CoS Insight Routes', () => {
expect(response.body.queue).not.toHaveProperty('estimate');
expect(response.body).not.toHaveProperty('velocity');
});
+
+ it('does not count a task its agent is already running as queued', async () => {
+ // The dashboard widget renders this payload's queue total beside its own
+ // "N agents running" line, so the one task being worked read as BOTH.
+ cos.getTodayActivity.mockResolvedValue({
+ stats: { completed: 0, succeeded: 0, failed: 0, running: 1, successRate: 0 },
+ time: { combined: '0s' },
+ isRunning: true,
+ isPaused: false,
+ lastEvaluation: Date.now()
+ });
+ cos.getAllTasks.mockResolvedValue({
+ user: { grouped: { pending: [{ id: 'user/42', status: 'pending' }] } },
+ cos: { awaitingApproval: [], grouped: { pending: [] } }
+ });
+ cos.getAgents.mockResolvedValue([{ id: 'agent-1', taskId: 'user/42', status: 'running', startedAt: new Date().toISOString() }]);
+
+ const response = await request(app).get('/api/cos/quick-summary');
+
+ expect(response.status).toBe(200);
+ expect(response.body.queue).toMatchObject({ pendingUserTasks: 0, total: 0 });
+ expect(response.body.today.running).toBe(1);
+ });
});
describe('GET /api/cos/goal-progress', () => {
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index fc2a5e1d3f..4eb395f436 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -13,6 +13,7 @@ import { prepareAppIssueClaim } from '../services/appIssues.js';
import { getAssignableInstances } from '../services/instances.js';
import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';
import { workTrackerLabel } from '../lib/workTracker.js';
+import { runningAgentsByTaskId, settleTaskSourceSpawnWindow } from '../lib/cosSpawnWindow.js';
import { getSlashdoWorkflow, slashdoWorkflowAppliesTo, SLASHDO_COMMAND_NAMES } from '../lib/slashdoCatalog.js';
import { NON_PM2_TYPES } from '../services/streamingDetect.js';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
@@ -131,6 +132,15 @@ const router = Router();
// GET /api/cos/tasks - Get all tasks (user + internal), grouped by source.
//
+// Settled for the spawn window (lib/cosSpawnWindow.js): an agent registers as
+// `running` a beat before its task leaves `pending`, so a caller that counted
+// `grouped.pending` raw reported the one task it was already working as queued
+// too. Settling HERE rather than in `getAllTasks()` keeps the dispatch readers
+// (task generation, retry revival, dedup) on the raw truth they need, while
+// every API consumer gets an honest queue depth without knowing the window
+// exists. `cos.getAgents()` is free at this point — `getAllTasks()` has already
+// warmed the same `loadState()` snapshot it reads.
+//
// Backward-compatible by default: with no pagination params it returns the full
// `{ user, cos }` structure every existing consumer expects (tasks + grouped
// buckets + awaiting/auto-approved derived lists). When a client passes
@@ -141,7 +151,16 @@ const router = Router();
// caller asked to page through, defeating the bound. A `pagination` block with
// the true per-source totals is added so the caller can page.
router.get('/tasks', asyncHandler(async (req, res) => {
- const tasks = await cos.getAllTasks();
+ const [allTasks, agents] = await Promise.all([
+ cos.getAllTasks(),
+ cos.getAgents().catch(() => []),
+ ]);
+ const runningAgents = runningAgentsByTaskId(agents);
+ const tasks = {
+ ...allTasks,
+ user: settleTaskSourceSpawnWindow(allTasks?.user, runningAgents),
+ cos: settleTaskSourceSpawnWindow(allTasks?.cos, runningAgents),
+ };
if (!isPaginationRequested(req.query)) {
return res.json(tasks);
}
diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.js
index eaf575c45d..cb304785c8 100644
--- a/server/routes/cosTaskRoutes.test.js
+++ b/server/routes/cosTaskRoutes.test.js
@@ -43,6 +43,7 @@ vi.mock('../services/cos.js', () => ({
addTask: vi.fn(),
updateTask: vi.fn(),
getAllTasks: vi.fn(),
+ getAgents: vi.fn(),
getUserTasks: vi.fn(),
getCosTasks: vi.fn(),
getTaskById: vi.fn(),
@@ -98,6 +99,7 @@ beforeEach(() => {
]);
cos.addTask.mockImplementation(async (taskData) => ({ id: 'task-1', ...taskData }));
cos.getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });
+ cos.getAgents.mockResolvedValue([]);
// The producer's storm counter is module state shared across this file's cases.
__resetInvestigationCircuit();
cos.updateTask.mockResolvedValue({ id: 'task-1' });
@@ -469,3 +471,44 @@ describe('CoS task routes write operator-action rows (#5594)', () => {
expect(await listUserActions()).toEqual([]);
});
});
+
+// An agent registers as `running` a beat before `spawnAgentForTask` flips its
+// task off `pending`, so every consumer that counted `grouped.pending` raw
+// reported the one task already being worked as queued too — "1 pending and 1
+// active" for a queue of one. The route settles that once, here, so no consumer
+// has to know the window exists.
+describe('GET /api/cos/tasks — the spawn window (lib/cosSpawnWindow.js)', () => {
+ const live = (taskId) => ({ id: `agent-${taskId}`, taskId, status: 'running', startedAt: new Date().toISOString() });
+ const source = () => ({
+ tasks: [{ id: 'user/42', status: 'pending' }, { id: 'user/43', status: 'pending' }],
+ grouped: { pending: [{ id: 'user/42', status: 'pending' }, { id: 'user/43', status: 'pending' }], in_progress: [] },
+ });
+
+ beforeEach(() => {
+ cos.getAllTasks.mockResolvedValue({ user: source(), cos: { tasks: [], grouped: { pending: [], in_progress: [] } } });
+ });
+
+ it('regroups a task its agent already holds and stamps it spawning', async () => {
+ cos.getAgents.mockResolvedValue([live('user/42')]);
+
+ const res = await request(buildApp()).get('/api/cos/tasks');
+
+ expect(res.status).toBe(200);
+ expect(res.body.user.grouped.pending.map((t) => t.id)).toEqual(['user/43']);
+ expect(res.body.user.grouped.in_progress.map((t) => t.id)).toEqual(['user/42']);
+ // `status` stays the persisted truth — a client may PATCH against it, and the
+ // row renders its mid-spawn state from `spawning`.
+ expect(res.body.user.tasks.find((t) => t.id === 'user/42')).toMatchObject({ status: 'pending', spawning: true });
+ });
+
+ it('leaves the queue alone when the agent list cannot be read', async () => {
+ // Over-reporting the queue is the safe direction: a failed probe may not be
+ // what hides a task the user is waiting on.
+ cos.getAgents.mockRejectedValue(new Error('state unreadable'));
+
+ const res = await request(buildApp()).get('/api/cos/tasks');
+
+ expect(res.status).toBe(200);
+ expect(res.body.user.grouped.pending.map((t) => t.id)).toEqual(['user/42', 'user/43']);
+ });
+});
diff --git a/server/routes/health.test.js b/server/routes/health.test.js
index 2e56096bda..ab48a6b05e 100644
--- a/server/routes/health.test.js
+++ b/server/routes/health.test.js
@@ -4,6 +4,7 @@ import express from 'express';
import { request } from '../lib/testHelper.js';
import systemHealthRoutes from './systemHealth.js';
import { listProcesses } from '../services/pm2.js';
+import { getStatus, getPendingTaskIds, getAgents } from '../services/cos.js';
import { getSelf } from '../services/instanceIdentity.js';
import { isAuthEnabled } from '../services/auth.js';
import { checkGhHealth } from '../services/github.js';
@@ -59,7 +60,9 @@ vi.mock('../services/apps.js', () => ({
}));
vi.mock('../services/cos.js', () => ({
- getStatus: vi.fn().mockResolvedValue(null)
+ getStatus: vi.fn().mockResolvedValue(null),
+ getPendingTaskIds: vi.fn().mockResolvedValue([]),
+ getAgents: vi.fn().mockResolvedValue([])
}));
vi.mock('../lib/db.js', () => ({
@@ -487,4 +490,67 @@ describe('System Health Routes', () => {
});
});
});
+
+ describe('GET /health/details — CoS queue depth', () => {
+ const live = (taskId) => ({ id: `agent-${taskId}`, taskId, status: 'running', startedAt: new Date().toISOString() });
+
+ beforeEach(() => {
+ getStatus.mockResolvedValue({ running: true, paused: false, activeAgents: 1 });
+ });
+
+ it('reports the pending tasks no live agent is already working', async () => {
+ // Regression: this read `cosStatus.queueLength`, a field getStatus has never
+ // returned, so the dashboard's "N queued" was dead and always rendered 0.
+ getPendingTaskIds.mockResolvedValueOnce(['user/42', 'sys-7']);
+ getAgents.mockResolvedValueOnce([live('user/99')]);
+
+ const response = await request(app).get('/api/system/health/details');
+
+ expect(response.status).toBe(200);
+ expect(response.body.cos).toMatchObject({ activeAgents: 1, queuedTasks: 2 });
+ });
+
+ it('does not also count the task its running agent already holds', async () => {
+ // The spawn window: the agent registers as running a beat before its task
+ // leaves 'pending', and the widget read "1 agent · 1 queued" for one task.
+ getPendingTaskIds.mockResolvedValueOnce(['user/42']);
+ getAgents.mockResolvedValueOnce([live('user/42')]);
+
+ const response = await request(app).get('/api/system/health/details');
+
+ expect(response.body.cos).toMatchObject({ activeAgents: 1, queuedTasks: 0 });
+ });
+
+ it('takes active and queued off the SAME agent read, so the two cannot skew', async () => {
+ // Pairing getStatus()'s own tally with a separately-read queue is the
+ // defect one layer down (services/activeProcessing.js) — here it would
+ // report the daemon's stale count beside a freshly-settled queue.
+ getStatus.mockResolvedValue({ running: true, paused: false, activeAgents: 7 });
+ getPendingTaskIds.mockResolvedValueOnce(['user/42']);
+ getAgents.mockResolvedValueOnce([live('user/99'), live('user/98')]);
+
+ const response = await request(app).get('/api/system/health/details');
+
+ expect(response.body.cos).toMatchObject({ activeAgents: 2, queuedTasks: 1 });
+ });
+
+ it('falls back to the daemon tally when the agent list cannot be read', async () => {
+ getPendingTaskIds.mockResolvedValueOnce(['user/42']);
+ getAgents.mockRejectedValueOnce(new Error('state unreadable'));
+
+ const response = await request(app).get('/api/system/health/details');
+
+ // No claim set to subtract, so the queue over-reports rather than hiding
+ // work — the safe direction — and active falls back rather than reading 0.
+ expect(response.body.cos).toMatchObject({ activeAgents: 1, queuedTasks: 1 });
+ });
+
+ it('reports an unreadable pending list as unknown rather than as an empty queue', async () => {
+ getPendingTaskIds.mockRejectedValueOnce(new Error('task file unreadable'));
+
+ const response = await request(app).get('/api/system/health/details');
+
+ expect(response.body.cos.queuedTasks).toBeNull();
+ });
+ });
});
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index bd7f437a47..b7822fe78c 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -18,6 +18,7 @@ import { isAuthEnabled } from '../services/auth.js';
import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';
import { getActiveProcessing } from '../services/activeProcessing.js';
import { getMediaCapacity } from '../services/mediaCapacity.js';
+import { runningAgentsByTaskId, unclaimedTaskIds } from '../lib/cosSpawnWindow.js';
import { getBuildIdentity } from '../lib/buildIdentity.js';
// Defaults are tuned for a real dev machine: memory routinely sits in the
@@ -132,10 +133,16 @@ router.get('/health/details', asyncHandler(async (req, res) => {
const startTime = Date.now();
// Gather data in parallel
- const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, healthSettings, forgeHealth, mediaCapacity] = await Promise.all([
+ const [pm2Processes, appStatusSummary, cosStatus, cosPendingTaskIds, cosAgents, self, dbHealth, version, diskStats, memStats, healthSettings, forgeHealth, mediaCapacity] = await Promise.all([
listProcesses().catch(() => []),
apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),
cos.getStatus().catch(() => null),
+ // Queue depth is read here rather than taken off `getStatus()`, which has no
+ // such field — `cosStatus.queueLength` never existed, so the widget's
+ // "N queued" was dead and always rendered 0. Both reads ride the same
+ // `loadState()`/parse caches `getStatus()` above already warmed.
+ cos.getPendingTaskIds().catch(() => null),
+ cos.getAgents().catch(() => null),
getSelf().catch(() => null),
checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),
getCurrentVersion().catch(() => null),
@@ -288,12 +295,20 @@ router.get('/health/details', asyncHandler(async (req, res) => {
? 'critical'
: warnings.length > 0 ? 'warning' : 'healthy';
- // CoS status
+ // CoS status. Active and queued BOTH come off the one agent read when it is
+ // readable — mixing `getStatus()`'s tally with a separately-read queue lets the
+ // two skew, which is the defect one layer down (services/activeProcessing.js).
+ // A task a live agent already holds is active, not queued (lib/cosSpawnWindow.js).
+ // An unreadable list degrades to null — unknown, which the widget hides —
+ // rather than to a manufactured zero.
+ const heldByRunningAgent = runningAgentsByTaskId(cosAgents);
const cosInfo = cosStatus ? {
running: cosStatus.running,
paused: cosStatus.paused,
- activeAgents: cosStatus.activeAgents || 0,
- queuedTasks: cosStatus.queueLength || 0
+ activeAgents: cosAgents
+ ? cosAgents.filter((agent) => agent?.status === 'running').length
+ : (cosStatus.activeAgents || 0),
+ queuedTasks: cosPendingTaskIds ? unclaimedTaskIds(cosPendingTaskIds, heldByRunningAgent).length : null
} : null;
const uptime = process.uptime();
diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.js
index 08afb17a61..700548d510 100644
--- a/server/services/activeProcessing.js
+++ b/server/services/activeProcessing.js
@@ -1,5 +1,6 @@
import { getCudaCapability, getCudaUtilization } from '../lib/cudaCapability.js';
import { summarizeSystemActivity } from '../lib/systemIdle.js';
+import { runningAgentsByTaskId, unclaimedTaskIds } from '../lib/cosSpawnWindow.js';
import { listJobs, getRunningJob } from './mediaJobQueue/index.js';
import { sanitizeJob } from './mediaJobQueue/sanitizeJob.js';
import { listGeneratingModelSummaries } from './imageTo3d/models.js';
@@ -65,7 +66,9 @@ function llmRunState(count) {
* A task stays 'pending' until spawnAgentForTask flips it to 'in_progress',
* which happens AFTER its agent is registered as running — so a snapshot taken
* in between would count one task as queued AND active, and the widget read
- * 'N active, N queued' for a queue of N. A task a live agent holds is active.
+ * 'N active, N queued' for a queue of N. A task a live agent holds is active —
+ * the settlement in lib/cosSpawnWindow.js, shared with every other surface that
+ * pairs the two lists.
*
* When the agent list is readable, BOTH counts come off that one read: taking
* `active` from `getStatus()` and `queued` from here would let the two skew
@@ -84,14 +87,14 @@ function llmRunState(count) {
*/
function agentCounts(agents, cosStatus, pendingTaskIds) {
const runningAgents = agents === null ? null : agents.filter((agent) => agent.status === 'running');
- const claimedTaskIds = new Set((runningAgents || []).map((agent) => agent.taskId).filter(Boolean));
+ const heldByRunningAgent = runningAgentsByTaskId(agents);
return {
// An unreadable pending-task list is its own untrusted reading: zero queued
// tasks is the value that unlocks a restart, so it may not come from a
// failed read any more than a zero agent count may.
trusted: (agents !== null || Boolean(cosStatus)) && pendingTaskIds !== null,
active: runningAgents ? runningAgents.length : (cosStatus?.activeAgents || 0),
- queued: pendingTaskIds ? pendingTaskIds.filter((id) => !claimedTaskIds.has(id)).length : 0,
+ queued: pendingTaskIds ? unclaimedTaskIds(pendingTaskIds, heldByRunningAgent).length : 0,
};
}
diff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.js
index 449977ebd9..496eb2eddf 100644
--- a/server/services/activeProcessing.test.js
+++ b/server/services/activeProcessing.test.js
@@ -160,7 +160,9 @@ describe('queued agent count', () => {
it('does not count a pending task a running agent already holds', async () => {
deps.tasks.mockResolvedValue(['task-spawning', 'task-waiting']);
- deps.agents.mockResolvedValue([{ id: 'agent-1', status: 'running', taskId: 'task-spawning' }]);
+ // `startedAt` is what tells a live spawn from a zombie record — registerAgent
+ // always stamps it (see lib/cosSpawnWindow.js's grace window).
+ deps.agents.mockResolvedValue([{ id: 'agent-1', status: 'running', taskId: 'task-spawning', startedAt: new Date().toISOString() }]);
const snapshot = await getActiveProcessing();
expect(snapshot.agents).toEqual({ trusted: true, active: 1, queued: 1 });
});
diff --git a/server/services/cos.js b/server/services/cos.js
index 72fe798710..569fa7858a 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -20,6 +20,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { getActiveProvider } from './providers.js';
import { isInternalTaskId } from '../lib/taskParser.js';
+import { runningAgentsByTaskId, spawningAgentForTask, spawnClaimAgeMs } from '../lib/cosSpawnWindow.js';
import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';
import { clearStaleActiveAgents } from './appActivity.js';
// The single Priority-0 on-demand loop body, shared with the evaluateTasks
@@ -102,12 +103,6 @@ const POST_STARTUP_QUEUE_DELAY_MS = 30_000;
// "recently completed" and protected from resetOrphanedTasks's reaper.
const RECENT_COMPLETION_GRACE_MS = 60_000;
-// How long an agent registered against a still-`pending` task is treated as
-// legitimately mid-spawn rather than a zombie. spawnAgentForTask registers the
-// agent then flips the task within the same function, so the real window is
-// sub-second; this is generous cover for a slow worktree/JIRA provisioning step.
-const SPAWN_CLAIM_GRACE_MS = 60_000;
-
// Boot can reach the auto-start path from more than one initializer while the
// server and runner settle. A boolean check is not sufficient: both callers
// can observe the daemon as stopped before either one sets the in-memory flag.
@@ -697,20 +692,22 @@ export async function forceSpawnTask(taskId) {
// withSpawnDedupGuard then silently drops. Refuse it here instead, where every
// caller (UI, voice, API) sees the same honest answer.
//
- // Bounded to the spawn window on purpose. Outside it, a `pending` task carrying
- // a `running` agent is a BROKEN state — a zombie record whose process died
- // before cleanupZombieAgents (which this route does not run) swept it — and
- // "Run now" is the user's recovery for exactly that. Refusing indefinitely
- // would turn the guard into a trap: the task is visibly stuck and nothing in
- // the UI can restart it. So refuse only while the holder is young enough to
- // plausibly still be mid-spawn, and let an older one be superseded.
- const holder = running.find(agent => agent.taskId === taskId);
- const holderAgeMs = holder ? Date.now() - new Date(holder.startedAt || 0).getTime() : Infinity;
- if (holder && holderAgeMs < SPAWN_CLAIM_GRACE_MS) {
+ // Bounded to the spawn window on purpose, via the same age-bounded settlement
+ // the status counters and task lists use (lib/cosSpawnWindow.js):
+ // outside it, a `pending` task carrying a `running` agent is a BROKEN state —
+ // a zombie record whose process died before cleanupZombieAgents (which this
+ // route does not run) swept it — and "Run now" is the user's recovery for
+ // exactly that. Refusing indefinitely would turn the guard into a trap: the
+ // task is visibly stuck and nothing in the UI can restart it. Sharing the
+ // bound is what keeps the pending LIST that renders this button in agreement
+ // with the refusal behind it.
+ const runningAgents = runningAgentsByTaskId(running);
+ const holder = runningAgents.get(taskId);
+ if (spawningAgentForTask(taskId, runningAgents)) {
return { error: `Agent ${holder.id} is already running this task` };
}
if (holder) {
- emitLog('warn', `⚠️ Force-spawning ${taskId} over stale agent ${holder.id} (running for ${Math.round(holderAgeMs / 1000)}s on a still-pending task)`, { taskId, agentId: holder.id });
+ emitLog('warn', `⚠️ Force-spawning ${taskId} over stale agent ${holder.id} (running for ${Math.round(spawnClaimAgeMs(holder) / 1000)}s on a still-pending task)`, { taskId, agentId: holder.id });
}
if (running.length >= state.config.maxConcurrentAgents) {
return { error: `No available agent slots (${running.length}/${state.config.maxConcurrentAgents})` };
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 072f49ee9a..1abb531197 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -54,6 +54,7 @@ import { PERSISTENT_MIND_SCHEMA_VERSION } from '../lib/persistentMind.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');
+const SPAWN_WINDOW_SRC = readFileSync(join(__dirname, '..', 'lib', 'cosSpawnWindow.js'), 'utf-8');
// The task-generation engine (evaluateTasks + the improvement/idle generators
// + applyPlanIdMetadata) was extracted to cosTaskGenerator.js (issue-741). The
// spawn-side scheduler (dequeueNextTask, tryImmediateSpawn, the tasks:changed
@@ -2034,7 +2035,7 @@ describe('forceSpawnTask — pre-validate provider before task:ready', () => {
// landing there answers `{ success: true }` and toasts "Spawning" for a second
// dispatch that withSpawnDedupGuard then silently drops.
it('refuses a task a running agent already holds', () => {
- const holderIdx = forceFn.indexOf('agent.taskId === taskId');
+ const holderIdx = forceFn.indexOf('spawningAgentForTask(taskId, runningAgents)');
expect(holderIdx, 'forceSpawnTask must reject a task a running agent holds')
.toBeGreaterThan(-1);
expect(forceFn, 'the refusal must name the agent that holds it')
@@ -2048,11 +2049,19 @@ describe('forceSpawnTask — pre-validate provider before task:ready', () => {
// route never runs cleanupZombieAgents — so an unbounded refusal would turn the
// task's own recovery action into a permanent no-op.
it('bounds the refusal so a stale holder can still be superseded', () => {
- expect(forceFn, 'the holder refusal must be age-bounded')
- .toContain('SPAWN_CLAIM_GRACE_MS');
+ // The bound now lives in lib/cosSpawnWindow.js, shared with the status
+ // counters and the task lists — so the pending LIST that renders the "Run
+ // now" button and the refusal behind it agree about which holders are stale.
+ expect(forceFn, 'the holder refusal must go through the age-bounded settlement')
+ .toMatch(/spawningAgentForTask\(taskId, runningAgents\)/);
expect(forceFn, 'a stale holder must fall through to the spawn, not return')
- .toMatch(/holderAgeMs < SPAWN_CLAIM_GRACE_MS/);
- expect(COS_SRC, 'the grace window must be defined').toMatch(/const SPAWN_CLAIM_GRACE_MS = /);
+ .toMatch(/const holder = runningAgents\.get\(taskId\);/);
+ expect(COS_SRC, 'the bound must come from the shared settlement, not a local copy')
+ .toMatch(/spawningAgentForTask[\s\S]*?from '\.\.\/lib\/cosSpawnWindow\.js'/);
+ expect(COS_SRC, 'no second grace window may be declared here')
+ .not.toMatch(/const SPAWN_CLAIM_GRACE_MS = /);
+ expect(SPAWN_WINDOW_SRC, 'the grace window must be defined')
+ .toMatch(/export const SPAWN_CLAIM_GRACE_MS = /);
});
});
diff --git a/server/services/systemResources.js b/server/services/systemResources.js
index 6b01592d51..b4f7dcfbfe 100644
--- a/server/services/systemResources.js
+++ b/server/services/systemResources.js
@@ -24,6 +24,7 @@ import * as ollamaManager from './ollamaManager.js';
import * as lmStudioManager from './lmStudioManager.js';
import { getQueueCapacity } from './mediaJobQueue/index.js';
import * as cos from './cos.js';
+import { runningAgentsByTaskId, countSpawningTasks } from '../lib/cosSpawnWindow.js';
import { getSettings } from './settings.js';
import {
hfInventoryRow,
@@ -311,14 +312,30 @@ function loadedModelInventory({ ollamaLoaded, lmStudioLoaded }) {
];
}
-function agentQueueSummary(tasks, status) {
+/**
+ * Queue depth vs work in flight, settled against the agent list.
+ *
+ * A mid-spawn task moves from the pending counts to `inProgress` rather than
+ * being counted on both sides (lib/cosSpawnWindow.js), so the two halves move
+ * together and the summary's queued+running total never dips while a spawn
+ * lands. `awaitingApproval` needs no settling: approval is a pre-spawn gate
+ * (`forceSpawnTask` refuses an unapproved task and approving clears the flag),
+ * so no live agent can hold one.
+ */
+function agentQueueSummary(tasks, status, agents) {
if (!tasks) return null;
+ const runningAgents = runningAgentsByTaskId(agents);
+ const pendingUser = tasks.user?.grouped?.pending || [];
+ const pendingSystem = tasks.cos?.grouped?.pending || [];
+ const spawningUser = countSpawningTasks(pendingUser, runningAgents);
+ const spawningSystem = countSpawningTasks(pendingSystem, runningAgents);
return {
- pendingUser: tasks.user?.grouped?.pending?.length || 0,
- pendingSystem: tasks.cos?.grouped?.pending?.length || 0,
+ pendingUser: pendingUser.length - spawningUser,
+ pendingSystem: pendingSystem.length - spawningSystem,
awaitingApproval: tasks.cos?.awaitingApproval?.length || 0,
inProgress: (tasks.user?.grouped?.in_progress?.length || 0)
- + (tasks.cos?.grouped?.in_progress?.length || 0),
+ + (tasks.cos?.grouped?.in_progress?.length || 0)
+ + spawningUser + spawningSystem,
activeAgents: status ? status.activeAgents || 0 : null,
pausedAgents: status ? status.pausedAgents || 0 : null,
daemonRunning: status?.running ?? null,
@@ -355,6 +372,7 @@ export async function buildSystemResourceReport() {
browserDownloadsBytes,
cosTasks,
cosStatus,
+ cosAgents,
modelDuplicates,
] = await Promise.all([
statfs('/').catch(() => null),
@@ -379,6 +397,7 @@ export async function buildSystemResourceReport() {
dirSize(PATHS.browserDownloads, { strict: true }).catch(() => null),
cos.getAllTasks().catch(() => null),
cos.getStatus().catch(() => null),
+ cos.getAgents().catch(() => null),
scanModelDuplicates().catch(() => ({ pinokioDetected: null, items: [], totalReclaimableBytes: 0, error: 'Duplicate model scan unavailable' })),
]);
@@ -429,7 +448,7 @@ export async function buildSystemResourceReport() {
running: capacity.totals.running,
byKind: capacity.byKind,
};
- const agentQueue = agentQueueSummary(cosTasks, cosStatus);
+ const agentQueue = agentQueueSummary(cosTasks, cosStatus, cosAgents);
const modelBytes = sumKnownBytes([hf?.totalBytes, loraStorage?.totalBytes, ollamaBytes, lmStudioBytes]);
const storageAreas = [
{
diff --git a/server/services/systemResources.test.js b/server/services/systemResources.test.js
index 9db955fee9..399acf41cb 100644
--- a/server/services/systemResources.test.js
+++ b/server/services/systemResources.test.js
@@ -89,6 +89,7 @@ vi.mock('./cos.js', () => ({
},
})),
getStatus: vi.fn(async () => ({ running: true, paused: false, activeAgents: 0, pausedAgents: 0 })),
+ getAgents: vi.fn(async () => []),
}));
vi.mock('./settings.js', () => ({
getSettings: vi.fn(async () => ({})),
@@ -270,6 +271,25 @@ describe('system resource reporting', () => {
expect(report.cleanupCandidates.some((candidate) => candidate.kind === 'data')).toBe(false);
});
+ it('moves a task its agent already holds from pending to in flight, without changing the total', async () => {
+ // An agent is registered as running a beat before its task leaves 'pending'
+ // (lib/cosSpawnWindow.js), so counting the two lists independently reported
+ // the same task as queued AND running — "Agent pending 1 / Agent running 1"
+ // for a queue of one. It must move sides, not appear on both and not vanish.
+ cos.getAllTasks.mockResolvedValueOnce({
+ user: { grouped: { pending: [{ id: 'user/42', status: 'pending' }], in_progress: [] } },
+ cos: { grouped: { pending: [], in_progress: [] }, awaitingApproval: [] },
+ });
+ cos.getAgents.mockResolvedValueOnce([{ id: 'agent-1', taskId: 'user/42', status: 'running', startedAt: new Date().toISOString() }]);
+
+ const report = await buildSystemResourceReport();
+
+ expect(report.queues.agents).toMatchObject({ pendingUser: 0, pendingSystem: 0, inProgress: 1 });
+ // The media lane contributes a fixed 3 queued / 1 running, so the one agent
+ // task crossing sides leaves the combined total at 5 either way.
+ expect(report.summary).toMatchObject({ queuedJobs: 3, runningJobs: 2 });
+ });
+
it('preserves failed agent queue and status probes as unknown', async () => {
cos.getAllTasks.mockRejectedValueOnce(new Error('task store unavailable'));
cos.getStatus.mockRejectedValueOnce(new Error('daemon status unavailable'));