Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): stale queue reads, zombie holders, failed agent reads
[._.]/ Adam Eivy947fb87839ff
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex d6bb7695d0..a219c4fdff 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -108,6 +108,9 @@ export default function ChiefOfStaff() {const [canScrollLeft, setCanScrollLeft] = useState(false);const [canScrollRight, setCanScrollRight] = useState(false);const tabsRef = useRef(null);+ // Monotonic counter for queue-state writes, so a slow fetchData cannot overwrite+ // a fresher fetchQueue result (see both functions below).+ const queueSeqRef = useRef(0);const socket = useSocket();// Derive avatar style from server config, with optional dynamic override@@ -141,6 +144,7 @@ export default function ChiefOfStaff() {}, []);const fetchData = useCallback(async () => {+ const queueSeq = queueSeqRef.current;const [statusData, tasksData, agentsData, healthData, providersData, appsData, learningSummaryData, insightsData] = await Promise.all([api.getCosStatus().catch(() => null),api.getCosTasks().catch(() => ({ user: null, cos: null })),@@ -154,8 +158,15 @@ export default function ChiefOfStaff() {api.getCosActionableInsights({ silent: true }).catch(() => null)]);setStatus(statusData);- setTasks(tasksData);- setAgents(agentsData);+ // fetchData is the SLOW read (8 endpoints, one of which runs a server health+ // check), so a queue refresh started later routinely resolves first. Its task+ // payload would then be clobbered by this older, pre-flip one — restoring the+ // pending-AND-active render this change exists to remove. Drop only the queue+ // half of a superseded read; the rest of the batch has no fresher writer.+ if (queueSeqRef.current === queueSeq) {+ setTasks(tasksData);+ setAgents(agentsData);+ }// `getCosHealth` above reads the *pre-check* persisted health, while the// getCosActionableInsights call in this same batch triggers a fresh server// health check (cos.runHealthCheck) that emits `cos:health:check` — the@@ -209,6 +220,10 @@ export default function ChiefOfStaff() {]);if (tasksData) setTasks(tasksData);if (Array.isArray(agentsData)) setAgents(agentsData);+ // Supersede any fetchData still in flight — see the guard in fetchData. Bumped+ // even when both reads failed: a failed refresh still means this queue state+ // is newer than whatever an older, slower batch is about to report.+ queueSeqRef.current += 1;}, []);// NOTE: there is deliberately no on-demand "refresh just the banner insights"diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 3a6b9da026..9997306378 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -531,3 +531,48 @@ describe('ChiefOfStaff task-change subscriptions', () => {expect(api.getCosActionableInsights.mock.calls.length).toBe(insightsBefore);});});++// fetchData reads 8 endpoints, one of which runs a server-side health check, so a+// queue refresh started LATER routinely resolves FIRST. Without a guard, the slow+// batch's pre-flip task payload lands last and restores the pending-AND-active+// render — the exact symptom the queue refresh exists to clear.+describe('ChiefOfStaff stale queue-read guard', () => {+ const getSocketHandler = (event) => socketStub.on.mock.calls.find(([evt]) => evt === event)?.[1];++ it('does not let a slow full fetch overwrite a fresher queue refresh', async () => {+ const stale = { user: { tasks: [{ id: 'task-1', description: 'STALE pending copy', status: 'pending', metadata: {} }] }, cos: { tasks: [] } };+ const fresh = { user: { tasks: [{ id: 'task-1', description: 'FRESH in-progress copy', status: 'in_progress', metadata: {} }] }, cos: { tasks: [] } };++ // Initial paint.+ api.getCosTasks.mockResolvedValue(stale);+ render(+ <MemoryRouter initialEntries={['/cos/tasks']}>+ <Routes>+ <Route path="/cos/:tab" element={<ChiefOfStaff />} />+ </Routes>+ </MemoryRouter>,+ );+ expect(await screen.findByText('STALE pending copy')).toBeInTheDocument();++ // A spawn kicks off the slow full fetch, whose insights read we hold open so+ // the whole batch resolves only after the queue refresh below has landed.+ let releaseInsights;+ api.getCosActionableInsights.mockReturnValue(new Promise((resolve) => { releaseInsights = resolve; }));+ await act(async () => { getSocketHandler('cos:agent:spawned')({ agentId: 'agent-1', metadata: {} }); });++ // The store event's queue refresh resolves first, with the post-flip truth.+ api.getCosTasks.mockResolvedValue(fresh);+ await act(async () => { getSocketHandler('cos:tasks:changed')({ type: 'user', action: 'updated' }); });+ expect(await screen.findByText('FRESH in-progress copy')).toBeInTheDocument();++ // Now the slow batch finally returns — carrying the stale pre-flip snapshot.+ api.getCosTasks.mockResolvedValue(stale);+ await act(async () => {+ releaseInsights({ insights: [] });+ await new Promise(resolve => setTimeout(resolve, 50));+ });++ expect(screen.queryByText('STALE pending copy')).not.toBeInTheDocument();+ expect(screen.getByText('FRESH in-progress copy')).toBeInTheDocument();+ });+});diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.jsindex dfd53dc20c..5f900365f2 100644--- a/server/services/activeProcessing.js+++ b/server/services/activeProcessing.js@@ -8,25 +8,31 @@ import * as cos from './cos.js';const LIVE_STATUSES = new Set(['queued', 'running']);export async function getActiveProcessing() {- const [capability, jobs, models, loadedModels, taskData, agents] = await Promise.all([+ const [capability, jobs, models, loadedModels, taskData, cosStatus, agents] = await Promise.all([getCudaCapability(),Promise.resolve(listJobs()).then((items) => items.filter((job) => LIVE_STATUSES.has(job.status))),listModels().catch(() => []),getLoadedModels().catch(() => []),cos.getAllTasks().catch(() => ({ user: {}, cos: {} })),- cos.getAgents().catch(() => []),+ cos.getStatus().catch(() => null),+ // `null` = the read FAILED, distinct from `[]` = read fine, no agents. The+ // counts below degrade differently for the two, so they must stay separable.+ cos.getAgents().catch(() => null),]);const utilization = capability.status === 'available' ? await getCudaUtilization() : { status: capability.status, gpus: [] };- // Both agent counts come off ONE read of the agent list. `cos.getStatus()`- // reports the same running tally, but taking `active` from there and `queued`- // from here would reintroduce the very skew this guards against.- //// 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.- const runningAgents = agents.filter((agent) => agent.status === 'running');- const claimedTaskIds = new Set(runningAgents.map((agent) => agent.taskId).filter(Boolean));+ //+ // 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+ // against each other, which is the same defect one layer up. When it is NOT+ // readable, there is no claim set to subtract — fall back to `getStatus()`'s+ // own tally rather than reporting zero active agents while still counting+ // their tasks as queued, which would understate BOTH numbers at once.+ const runningAgents = agents === null ? null : agents.filter((agent) => agent.status === 'running');+ const claimedTaskIds = new Set((runningAgents || []).map((agent) => agent.taskId).filter(Boolean));const pendingTasks = [...(taskData.user?.tasks || []), ...(taskData.cos?.tasks || [])].filter((task) => task.status === 'pending' && !claimedTaskIds.has(task.id)).length;const gpuBusy = Boolean(getRunningJob());@@ -49,7 +55,7 @@ export async function getActiveProcessing() {ollama: loadedModels,},agents: {- active: runningAgents.length,+ active: runningAgents ? runningAgents.length : (cosStatus?.activeAgents || 0),queued: pendingTasks,},};diff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.jsindex 45942e5c98..18820bcad7 100644--- a/server/services/activeProcessing.test.js+++ b/server/services/activeProcessing.test.js@@ -1,14 +1,14 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const deps = vi.hoisted(() => ({- capability: vi.fn(), utilization: vi.fn(), jobs: vi.fn(), running: vi.fn(), models: vi.fn(), loaded: vi.fn(), tasks: vi.fn(), agents: vi.fn(),+ capability: vi.fn(), utilization: vi.fn(), jobs: vi.fn(), running: vi.fn(), models: vi.fn(), loaded: vi.fn(), tasks: vi.fn(), status: vi.fn(), agents: vi.fn(),}));vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: deps.capability, getCudaUtilization: deps.utilization }));vi.mock('./mediaJobQueue/index.js', () => ({ listJobs: deps.jobs, getRunningJob: deps.running }));vi.mock('./mediaJobQueue/sanitizeJob.js', () => ({ sanitizeJob: (job) => ({ id: job.id, kind: job.kind, status: job.status, params: { musicStudio: job.params.musicStudio } }) }));vi.mock('./imageTo3d/models.js', () => ({ listModels: deps.models }));vi.mock('./ollamaManager.js', () => ({ getLoadedModels: deps.loaded }));-vi.mock('./cos.js', () => ({ getAllTasks: deps.tasks, getAgents: deps.agents }));+vi.mock('./cos.js', () => ({ getAllTasks: deps.tasks, getStatus: deps.status, getAgents: deps.agents }));const { getActiveProcessing } = await import('./activeProcessing.js');@@ -25,6 +25,7 @@ describe('active processing snapshot', () => {deps.models.mockResolvedValue([{ id: 'mesh-1', name: 'Fake mesh', status: 'generating' }]);deps.loaded.mockResolvedValue([{ id: 'model-1', name: 'Fake model' }]);deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [{ id: 'cos-task-1', status: 'completed' }] } });+ deps.status.mockResolvedValue({ activeAgents: 99 });deps.agents.mockResolvedValue([{ id: 'agent-1', status: 'running', taskId: 'task-a' },{ id: 'agent-2', status: 'running', taskId: 'task-b' },@@ -45,6 +46,7 @@ describe('active processing snapshot', () => {deps.models.mockResolvedValue([]);deps.loaded.mockResolvedValue([]);deps.tasks.mockResolvedValue({ user: {}, cos: {} });+ deps.status.mockResolvedValue({ activeAgents: 0 });deps.agents.mockResolvedValue([]);const snapshot = await getActiveProcessing();expect(snapshot.gpu).toMatchObject({ status: 'absent', laneBusy: false, laneKind: null, gpus: [] });@@ -64,6 +66,7 @@ describe('queued agent count', () => {deps.running.mockReturnValue(null);deps.models.mockResolvedValue([]);deps.loaded.mockResolvedValue([]);+ deps.status.mockResolvedValue({ activeAgents: 0 });});it('does not count a pending task a running agent already holds', async () => {@@ -83,10 +86,23 @@ describe('queued agent count', () => {expect(snapshot.agents).toEqual({ active: 0, queued: 1 });});- it('falls back to counting every pending task when the agent read fails', async () => {+ // A failed agent read is not an empty one. Collapsing the two would report+ // zero active agents AND still count their tasks as queued — understating both+ // numbers at once — so the failure path falls back to getStatus()'s own tally.+ it('falls back to the status tally when the agent read fails, without dropping pending tasks', async () => {+ deps.status.mockResolvedValue({ activeAgents: 3 });deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [] } });deps.agents.mockRejectedValue(new Error('state unreadable'));const snapshot = await getActiveProcessing();+ expect(snapshot.agents).toEqual({ active: 3, queued: 1 });+ });++ // ...and a successful read of an EMPTY list still means zero, not the fallback.+ it('reports zero active from a successfully empty agent list', async () => {+ deps.status.mockResolvedValue({ activeAgents: 7 });+ deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [] } });+ deps.agents.mockResolvedValue([]);+ const snapshot = await getActiveProcessing();expect(snapshot.agents).toEqual({ active: 0, queued: 1 });});});diff --git a/server/services/cos.js b/server/services/cos.jsindex 2169bda36a..e78f79a230 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -93,6 +93,12 @@ 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;+// Internal imports for functions used in this moduleimport { pruneOldAgentArchives, loadAgentIndex } from './cosAgentIndex.js';import { archiveStaleAgents as _archiveStaleAgents } from './cosAgentArchive.js';@@ -552,10 +558,22 @@ export async function forceSpawnTask(taskId) {// `{ success: true }` and a "Spawning" toast for a second dispatch that// 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);- if (holder) {+ const holderAgeMs = holder ? Date.now() - new Date(holder.startedAt || 0).getTime() : Infinity;+ if (holder && holderAgeMs < SPAWN_CLAIM_GRACE_MS) {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 });+ }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.jsindex 2bda21f478..a675d8e55d 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1255,6 +1255,18 @@ describe('forceSpawnTask — pre-validate provider before task:ready', () => {expect(holderIdx, 'the live-agent check must precede the task:ready emit').toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));});++ // ...but only while that agent is plausibly still mid-spawn. Outside the window,+ // a `pending` task carrying a `running` agent is a zombie record — and this+ // 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');+ 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 = /);+ });});describe('the runner-down hold — spawn-side gates', () => {