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
show a queued CoS task in the pending list immediately, and only in one place
[._.]/ Adam Eivy4726042c7d99
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex ca5add86a9..eb89cb59ec 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -72,11 +72,15 @@ function getSuccessRateStyle(rate) {return { bg: 'bg-port-error/15', text: 'text-port-error', label: 'low' };}-export default function TaskItem({ task, isSystem, selected = false, onRefresh, providers, durations, dragHandleProps, apps, instances = null, onEditingChange }) {+export default function TaskItem({ task, isSystem, spawning = false, selected = false, onRefresh, providers, durations, dragHandleProps, apps, instances = null, onEditingChange }) {// System tasks are persisted in COS-TASKS.md. Every task// mutation must name that source; otherwise the API's user-queue default// searches TASKS.md and reports the system task as missing.const taskSource = isSystem ? 'internal' : 'user';+ // A spawning task is still persisted as 'pending' but is already running —+ // show the running glyph, not the queued clock. See spawnAgentForTask's+ // registration ordering for why the two disagree.+ const displayStatus = spawning ? 'in_progress' : task.status;const idScope = isSystem ? 'sys' : 'user';const requiresApproval = isSystem && task.approvalRequired;// Name the hold's reason on the APPROVE button so "why is this one waiting on@@ -149,7 +153,7 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,// Calculate duration estimate for pending tasks// Uses P80 estimate when available for more realistic time predictionsconst durationEstimate = useMemo(() => {- if (!durations || task.status !== 'pending') return null;+ if (!durations || displayStatus !== 'pending') return null;// Queue reads return raw parsed tasks without taskType. Supply the queue// source so this estimate stays in the same bucket the server records.@@ -182,7 +186,7 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,}return null;- }, [durations, task, task.status]);+ }, [durations, task, displayStatus]);const handleStatusChange = async (newStatus, blockedReasonText = '', successMessage = `Task marked as ${newStatus}`) => {const updates = { status: newStatus, type: taskSource };@@ -348,9 +352,9 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,}}}className="mt-0.5 hover:scale-110 transition-transform"- aria-label={`Status: ${task.status}. Click to mark as ${task.status === 'completed' || task.status === 'blocked' ? 'pending' : 'completed'}`}+ aria-label={`Status: ${displayStatus}. Click to mark as ${task.status === 'completed' || task.status === 'blocked' ? 'pending' : 'completed'}`}>- {statusIcons[task.status]}+ {statusIcons[displayStatus]}</button><div className="flex-1 min-w-0"><div className="flex items-center gap-2 mb-1 flex-wrap">@@ -645,6 +649,12 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,/>) : (<>+ {/* Deliberately gated on the PERSISTED status, not `displayStatus`:+ an agent record stuck at `running` (the zombie state+ cleanupZombieAgents exists to clear) would otherwise take this+ row's only recovery affordance away with it. forceSpawnTask+ refuses a task a live agent already holds, so a click during a+ real spawn gets an honest error rather than a duplicate run. */}{task.status === 'pending' && !task.approvalRequired && (<buttononClick={async () => {diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex abe681ce6e..c9b66ec81b 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useMemo } from 'react';+import { useState, useEffect, useCallback, useMemo } from 'react';import { useSearchParams } from 'react-router';import { Play, ChevronDown, ChevronRight } from 'lucide-react';import toast from '../../ui/Toast';@@ -38,7 +38,7 @@ function SectionGlyph({ status }) {return <MicroGlyph variant={spec.variant} state={spec.state} animated={spec.animated} size={13} />;}-export default function TasksTab({ tasks, onRefresh, providers, apps }) {+export default function TasksTab({ tasks, agents = [], onRefresh, providers, apps }) {const [searchParams] = useSearchParams();const [userTasksLocal, setUserTasksLocal] = useState([]);const [durations, setDurations] = useState(null);@@ -71,14 +71,30 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {task.id === selectedTaskId && source === selectedTaskSource);+ // Task ids a live agent is already working. 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.+ const spawningTaskIds = useMemo(() => new Set(+ agents.filter(a => a.status === 'running' && a.taskId).map(a => a.taskId)+ ), [agents]);+ const isSpawning = useCallback(+ (task) => task.status === 'pending' && spawningTaskIds.has(task.id),+ [spawningTaskIds]+ );+// Split tasks by status for system tasksconst pendingSystemTasks = useMemo(() =>- cosTasks.filter(t => t.status === 'pending'),- [cosTasks]+ cosTasks.filter(t => t.status === 'pending' && !isSpawning(t)),+ [cosTasks, isSpawning]);const activeSystemTasks = useMemo(() =>- cosTasks.filter(t => t.status === 'in_progress'),- [cosTasks]+ cosTasks.filter(t => t.status === 'in_progress' || isSpawning(t)),+ [cosTasks, isSpawning]);const blockedSystemTasks = useMemo(() =>cosTasks.filter(t => t.status === 'blocked'),@@ -91,12 +107,12 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {// Split user tasks by status (only pending tasks are sortable)const pendingUserTasksLocal = useMemo(() =>- userTasksLocal.filter(t => t.status === 'pending'),- [userTasksLocal]+ userTasksLocal.filter(t => t.status === 'pending' && !isSpawning(t)),+ [userTasksLocal, isSpawning]);const activeUserTasksLocal = useMemo(() =>- userTasksLocal.filter(t => t.status === 'in_progress'),- [userTasksLocal]+ userTasksLocal.filter(t => t.status === 'in_progress' || isSpawning(t)),+ [userTasksLocal, isSpawning]);const blockedUserTasksLocal = useMemo(() =>userTasksLocal.filter(t => t.status === 'blocked'),@@ -255,7 +271,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div><div className="p-2 space-y-1.5">{activeUserTasksLocal.map(task => (- <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} spawning={isSpawning(task)} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div></div>@@ -345,7 +361,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {</div><div className="p-2 space-y-1.5">{activeSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} isSystem spawning={isSpawning(task)} selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div></div>diff --git a/client/src/components/cos/tabs/TasksTab.test.jsx b/client/src/components/cos/tabs/TasksTab.test.jsxindex 5fb89299ee..1632f6e4ea 100644--- a/client/src/components/cos/tabs/TasksTab.test.jsx+++ b/client/src/components/cos/tabs/TasksTab.test.jsx@@ -62,3 +62,55 @@ describe('TasksTab Run Now', () => {expect(row).toHaveFocus();});});++// The server registers an agent as `running` BEFORE it flips the agent's task+// off `pending`, so between those two writes a task legitimately reads as+// pending on one list and running on the other. The tab must settle that from+// 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 });++ 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' }],+ });++ await waitFor(() => expect(screen.getByText(/^Pending \(/)).toBeInTheDocument());+ expect(screen.getByText('Pending (1)')).toBeInTheDocument();+ expect(screen.getByText('Active (1)')).toBeInTheDocument();+ });++ it('leaves a pending system task pending when its agent has already completed', async () => {+ renderTab({+ tasks: { user: { tasks: [] }, cos: { tasks: [pendingTask('cos-task-1')] } },+ agents: [{ id: 'agent-1', status: 'completed', taskId: 'cos-task-1' }],+ });++ 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' }],+ });++ await waitFor(() => expect(screen.getByText('Active (1)')).toBeInTheDocument());+ // An agent stuck at `running` (the zombie state cleanupZombieAgents clears)+ // would otherwise leave the row with no way to re-dispatch it. Duplicate+ // dispatch is refused server-side by forceSpawnTask, not by hiding this.+ expect(screen.getByRole('button', { name: /Process task now/i })).toBeInTheDocument();+ });++ it('still offers Process now for a genuinely queued task', async () => {+ renderTab({+ tasks: { user: { tasks: [pendingTask('task-waiting')] }, cos: { tasks: [] } },+ agents: [],+ });++ await waitFor(() => expect(screen.getByText('Pending (1)')).toBeInTheDocument());+ expect(screen.getByRole('button', { name: /Process task now/i })).toBeInTheDocument();+ });+});diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 005d85a53d..d6bb7695d0 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -5,6 +5,7 @@ import { useLocalStorageBool } from '../hooks/useLocalStorageBool';import { useAutoRefetch } from '../hooks/useAutoRefetch';import { useValidTab } from '../hooks/useValidTab';import * as api from '../services/api';+import { coalesce } from '../utils/coalesce';import { Play, Pause, Square, Clock, CheckCircle, AlertCircle, Cpu, ChevronDown, ChevronUp, ChevronLeft, ChevronRight, Brain, PanelLeftClose, PanelLeftOpen } from 'lucide-react';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';@@ -196,6 +197,20 @@ export default function ChiefOfStaff() {setActiveAgentMeta(runningAgent?.metadata || null);}, [deriveAgentState]);+ // A cheap, read-only refresh of just the queue — the task lists plus the agent+ // list the Tasks tab reads to tell an already-spawning task from a waiting one.+ // Deliberately NOT fetchData: that batch also pulls actionable insights, whose+ // endpoint runs a health check that auto-restarts errored PM2 processes (see+ // the note below), which must never ride the store's per-mutation task stream.+ const fetchQueue = useCallback(async () => {+ const [tasksData, agentsData] = await Promise.all([+ api.getCosTasks({ silent: true }).catch(() => null),+ api.getCosAgents({ silent: true }).catch(() => null)+ ]);+ if (tasksData) setTasks(tasksData);+ if (Array.isArray(agentsData)) setAgents(agentsData);+ }, []);+// NOTE: there is deliberately no on-demand "refresh just the banner insights"// path. The /cos/actionable-insights endpoint runs a health check that// AUTO-RESTARTS errored PM2 processes (see server/services/cosHealthMonitor.js)@@ -217,6 +232,7 @@ export default function ChiefOfStaff() {// Reduced polling since most updates come via socket eventsuseAutoRefetch(fetchData, 30_000, { pollOnly: true });+useEffect(() => {if (!socket) return;@@ -248,6 +264,26 @@ export default function ChiefOfStaff() {};socket.on('cos:tasks:user:changed', handleTasksUserChanged);+ // System (COS-TASKS.md) tasks change on their own file-watcher event, and+ // scheduled/on-demand CoS work IS an internal task — so without this handler+ // a freshly queued scheduled task only appeared once the 30s poll came+ // around. Same full-list payload as the user event, so swap it in directly.+ const handleTasksCosChanged = (data) => {+ setTasks(prev => ({ ...prev, cos: data }));+ };+ socket.on('cos:tasks:cos:changed', handleTasksCosChanged);++ // The store's own per-mutation event, which fires the instant a task is added+ // or its status flips — ahead of the debounced file watcher above. It carries+ // one task rather than the list, and also fires for writes with nothing to+ // show here (every running task's federation lease heartbeat), so it drives+ // one coalesced queue refresh rather than a fetch per event. This is what+ // collapses the pending→in_progress lag: 'cos:agent:spawned' fires BEFORE+ // spawnAgentForTask flips the task off 'pending', so the fetch it triggers+ // always reads the task as still-queued.+ const refreshQueue = coalesce(fetchQueue, 400);+ socket.on('cos:tasks:changed', refreshQueue);+const handleAgentSpawned = (data) => {setAgentState('coding');// Show actual task description if available@@ -349,6 +385,8 @@ export default function ChiefOfStaff() {socket.off('connect', subscribe);socket.off('cos:status', handleCosStatus);socket.off('cos:tasks:user:changed', handleTasksUserChanged);+ socket.off('cos:tasks:cos:changed', handleTasksCosChanged);+ socket.off('cos:tasks:changed', refreshQueue);socket.off('cos:agent:spawned', handleAgentSpawned);socket.off('cos:agent:updated', handleAgentUpdated);socket.off('cos:agent:output', handleAgentOutput);@@ -356,8 +394,9 @@ export default function ChiefOfStaff() {socket.off('cos:health:check', handleHealthCheck);socket.off('cos:log', handleCosLog);socket.off('apps:changed', handleAppsChanged);+ refreshQueue.cancel();};- }, [socket, fetchData]);+ }, [socket, fetchData, fetchQueue]);const handleStart = async () => {const result = await api.startCos({ silent: true }).catch(err => {@@ -967,7 +1006,7 @@ export default function ChiefOfStaff() {tabs that don't surface this data. */}<ActionableInsightsBanner insights={insights} onTaskUnblocked={handleTaskUnblocked} onRefresh={fetchData} /><QuickSummary />- <TasksTab tasks={tasks} onRefresh={fetchData} providers={providers} apps={apps} />+ <TasksTab tasks={tasks} agents={agents} onRefresh={fetchData} providers={providers} apps={apps} /></div>)}{activeTab === 'agents' && (diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 2d18433cfb..3a6b9da026 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -24,6 +24,10 @@ const api = vi.hoisted(() => ({getCosTodayActivity: vi.fn(),getCosLearning: vi.fn(),getProviderStatuses: vi.fn(),+ // TasksTab + TaskAddForm, rendered by the task-event tests below.+ getCosLearningDurations: vi.fn(),+ getCosPopularTemplates: vi.fn(),+ getCodeReviewDefaults: vi.fn(),}));const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));const socketStub = vi.hoisted(() => ({ connected: false, on: vi.fn(), off: vi.fn(), emit: vi.fn() }));@@ -31,6 +35,9 @@ const socketStub = vi.hoisted(() => ({ connected: false, on: vi.fn(), off: vi.fnvi.mock('../services/api', () => api);vi.mock('../components/ui/Toast', () => ({ default: toast }));vi.mock('../services/socket', () => ({ default: socketStub }));+// TaskAddForm drags in the reviewer/model picker plumbing (local-LLM status,+// prompt templates) that the task-event tests below have no stake in.+vi.mock('../components/cos/TaskAddForm', () => ({ default: () => null }));// ConfigTab's provider/model hook fetches over the network — stub it.vi.mock('../hooks/useProviderModels', () => ({default: () => ({@@ -75,6 +82,9 @@ beforeEach(() => {api.getCosBudgetUsage.mockResolvedValue({ usage: {} });api.pauseCos.mockResolvedValue({ success: true, pausedAt: '2026-01-01T00:00:00.000Z' });api.resumeCos.mockResolvedValue({ success: true });+ api.getCosLearningDurations.mockResolvedValue(null);+ api.getCosPopularTemplates.mockResolvedValue([]);+ api.getCodeReviewDefaults.mockResolvedValue({});});const renderConfigTab = () => render(@@ -447,3 +457,77 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();});});++// A scheduled CoS run is an INTERNAL task, and the page used to subscribe only+// to `cos:tasks:user:changed` — so a freshly queued scheduled task didn't appear+// until the 30s poll, and the pending→in_progress flip that ends a task's+// "queued" life was equally invisible. Since the server registers an agent as+// running BEFORE flipping its task off `pending`, the fetch fired by+// `cos:agent:spawned` always reads the task as still-queued, which is what left+// the row showing as pending AND active for up to a poll interval.+describe('ChiefOfStaff task-change subscriptions', () => {+ const getSocketHandler = (event) => socketStub.on.mock.calls.find(([evt]) => evt === event)?.[1];++ const renderTasksTab = () => render(+ <MemoryRouter initialEntries={['/cos/tasks']}>+ <Routes>+ <Route path="/cos/:tab" element={<ChiefOfStaff />} />+ </Routes>+ </MemoryRouter>,+ );++ it('renders a newly queued system task straight off the watcher event', async () => {+ renderTasksTab();+ await waitFor(() => expect(api.getCosTasks).toHaveBeenCalled());+ const before = api.getCosTasks.mock.calls.length;++ const handleCosTasksChanged = getSocketHandler('cos:tasks:cos:changed');+ expect(handleCosTasksChanged).toBeTypeOf('function');+ await act(async () => {+ handleCosTasksChanged({+ exists: true,+ tasks: [{ id: 'cos-task-1', description: 'Example scheduled task', status: 'pending', metadata: {} }],+ });+ });++ expect(await screen.findByText('Example scheduled task')).toBeInTheDocument();+ // The event carries the whole list, so it must not cost a round trip.+ expect(api.getCosTasks.mock.calls.length).toBe(before);+ });++ it('coalesces a burst of task-store changes into a single refetch', async () => {+ renderTasksTab();+ await waitFor(() => expect(api.getCosTasks).toHaveBeenCalled());+ const before = api.getCosTasks.mock.calls.length;++ const handleTasksChanged = getSocketHandler('cos:tasks:changed');+ expect(handleTasksChanged).toBeTypeOf('function');+ await act(async () => {+ handleTasksChanged({ type: 'internal', action: 'added' });+ handleTasksChanged({ type: 'internal', action: 'updated' });+ handleTasksChanged({ type: 'user', action: 'updated' });+ });++ await waitFor(() => expect(api.getCosTasks.mock.calls.length).toBe(before + 1), { timeout: 2000 });+ // `tasks:changed` also fires for writes with nothing to show here (every+ // running task's federation lease heartbeat), so the burst must settle into+ // one refresh rather than one per event. Any extra flush would land inside+ // the 400ms window the first one already closed.+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 200)); });+ expect(api.getCosTasks.mock.calls.length).toBe(before + 1);+ });++ it('refreshes the queue without re-running the health-checking insights read', async () => {+ renderTasksTab();+ await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());+ const insightsBefore = api.getCosActionableInsights.mock.calls.length;++ await act(async () => { getSocketHandler('cos:tasks:changed')({ type: 'internal', action: 'updated' }); });+ await waitFor(() => expect(api.getCosAgents.mock.calls.length).toBeGreaterThan(1), { timeout: 2000 });++ // /cos/actionable-insights runs a health check that AUTO-RESTARTS errored PM2+ // processes. Every task add, status flip, delete and lease heartbeat emits+ // `tasks:changed`, so this handler must never reach that endpoint.+ expect(api.getCosActionableInsights.mock.calls.length).toBe(insightsBefore);+ });+});diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex a597f21b8e..b627fda261 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -123,7 +123,7 @@ export const forceCosEvaluate = (options = {}) => request('/cos/evaluate', { metexport const forceSpawnTask = (taskId, options = {}) => request(`/cos/tasks/${taskId}/spawn`, { method: 'POST', ...options });export const getCosHealth = () => request('/cos/health');export const forceHealthCheck = (options = {}) => request('/cos/health/check', { method: 'POST', ...options });-export const getCosAgents = () => request('/cos/agents');+export const getCosAgents = (options) => request('/cos/agents', options);export const getCosAgentDates = () => request('/cos/agents/history');export const getCosAgentsByDate = (date) => request(`/cos/agents/history/${date}`);export const getCosAgent = (id) => request(`/cos/agents/${id}`);diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.jsindex 188d560c13..dfd53dc20c 100644--- a/server/services/activeProcessing.js+++ b/server/services/activeProcessing.js@@ -8,17 +8,27 @@ import * as cos from './cos.js';const LIVE_STATUSES = new Set(['queued', 'running']);export async function getActiveProcessing() {- const [capability, jobs, models, loadedModels, cosStatus, taskData] = await Promise.all([+ const [capability, jobs, models, loadedModels, taskData, agents] = await Promise.all([getCudaCapability(),Promise.resolve(listJobs()).then((items) => items.filter((job) => LIVE_STATUSES.has(job.status))),listModels().catch(() => []),getLoadedModels().catch(() => []),- cos.getStatus().catch(() => null),cos.getAllTasks().catch(() => ({ user: {}, cos: {} })),+ cos.getAgents().catch(() => []),]);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));const pendingTasks = [...(taskData.user?.tasks || []), ...(taskData.cos?.tasks || [])]- .filter((task) => task.status === 'pending').length;+ .filter((task) => task.status === 'pending' && !claimedTaskIds.has(task.id)).length;const gpuBusy = Boolean(getRunningJob());return {updatedAt: new Date().toISOString(),@@ -39,7 +49,7 @@ export async function getActiveProcessing() {ollama: loadedModels,},agents: {- active: cosStatus?.activeAgents || 0,+ active: runningAgents.length,queued: pendingTasks,},};diff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.jsindex 9fdc2d0e69..45942e5c98 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(), status: vi.fn(), tasks: vi.fn(),+ capability: vi.fn(), utilization: vi.fn(), jobs: vi.fn(), running: vi.fn(), models: vi.fn(), loaded: vi.fn(), tasks: 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', () => ({ getStatus: deps.status, getAllTasks: deps.tasks }));+vi.mock('./cos.js', () => ({ getAllTasks: deps.tasks, getAgents: deps.agents }));const { getActiveProcessing } = await import('./activeProcessing.js');@@ -24,8 +24,11 @@ describe('active processing snapshot', () => {deps.running.mockReturnValue({ kind: 'audio' });deps.models.mockResolvedValue([{ id: 'mesh-1', name: 'Fake mesh', status: 'generating' }]);deps.loaded.mockResolvedValue([{ id: 'model-1', name: 'Fake model' }]);- deps.status.mockResolvedValue({ activeAgents: 2 });- deps.tasks.mockResolvedValue({ user: { tasks: [{ status: 'pending' }] }, cos: { tasks: [{ status: 'completed' }] } });+ deps.tasks.mockResolvedValue({ user: { tasks: [{ id: 'task-1', status: 'pending' }] }, cos: { tasks: [{ id: 'cos-task-1', status: 'completed' }] } });+ deps.agents.mockResolvedValue([+ { id: 'agent-1', status: 'running', taskId: 'task-a' },+ { id: 'agent-2', status: 'running', taskId: 'task-b' },+ ]);const snapshot = await getActiveProcessing();expect(snapshot.jobs).toHaveLength(1);expect(snapshot.gpu).toMatchObject({ status: 'available', laneBusy: true, laneKind: 'audio' });@@ -41,10 +44,49 @@ describe('active processing snapshot', () => {deps.running.mockReturnValue(null);deps.models.mockResolvedValue([]);deps.loaded.mockResolvedValue([]);- deps.status.mockResolvedValue({ activeAgents: 0 });deps.tasks.mockResolvedValue({ user: {}, cos: {} });+ deps.agents.mockResolvedValue([]);const snapshot = await getActiveProcessing();expect(snapshot.gpu).toMatchObject({ status: 'absent', laneBusy: false, laneKind: null, gpus: [] });expect(deps.utilization).not.toHaveBeenCalled();});});++// The task record keeps its `pending` status until spawnAgentForTask flips it to+// `in_progress`, which the server does AFTER registering the agent as running.+// A snapshot taken inside that window used to report the one task as both+// queued AND active, so the widget read "1 active, 1 queued" for a single run.+describe('queued agent count', () => {+ beforeEach(() => {+ Object.values(deps).forEach((mock) => mock.mockReset());+ deps.capability.mockResolvedValue({ status: 'absent', gpus: [] });+ deps.jobs.mockReturnValue([]);+ deps.running.mockReturnValue(null);+ deps.models.mockResolvedValue([]);+ deps.loaded.mockResolvedValue([]);+ });++ it('does not count a pending task a running agent already holds', async () => {+ deps.tasks.mockResolvedValue({+ user: { tasks: [{ id: 'task-spawning', status: 'pending' }, { id: 'task-waiting', status: 'pending' }] },+ cos: { tasks: [] },+ });+ deps.agents.mockResolvedValue([{ id: 'agent-1', status: 'running', taskId: 'task-spawning' }]);+ const snapshot = await getActiveProcessing();+ expect(snapshot.agents).toEqual({ active: 1, queued: 1 });+ });++ it('still counts a pending task whose agent already completed', async () => {+ deps.tasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [{ id: 'cos-task-1', status: 'pending' }] } });+ deps.agents.mockResolvedValue([{ id: 'agent-1', status: 'completed', taskId: 'cos-task-1' }]);+ const snapshot = await getActiveProcessing();+ expect(snapshot.agents).toEqual({ active: 0, queued: 1 });+ });++ it('falls back to counting every pending task when the agent read fails', async () => {+ 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: 0, queued: 1 });+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 8c75c73fd8..8922554aa5 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -597,6 +597,12 @@ async function runAgentSpawn(task) {emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });+ // NOTE: the agent is already registered as `running` above, so until this+ // write lands the task still reads `pending` — one task, two live states.+ // Readers that pair the task list with the agent list must reconcile that+ // (forceSpawnTask's live-agent refusal, activeProcessing's queued count, the+ // CoS Tasks tab). Widening this gap widens their window.+ //// Mark the task as in_progress, increment the total spawn count, and refresh// the federation claim (issue #1563). The claim was already acquired up front// (above); re-stamping it here renews the lease at the moment the agentdiff --git a/server/services/cos.js b/server/services/cos.jsindex e2263e1519..2169bda36a 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -545,9 +545,19 @@ export async function forceSpawnTask(taskId) {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})` };+ const running = Object.values(state.agents).filter(a => a.status === 'running');+ // An agent is registered as running BEFORE spawnAgentForTask flips its task off+ // `pending`, so the status check above still passes for the seconds between+ // those two writes — an explicit "Run now" landing there would get a bogus+ // `{ 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.+ const holder = running.find(agent => agent.taskId === taskId);+ if (holder) {+ return { error: `Agent ${holder.id} is already running this task` };+ }+ if (running.length >= state.config.maxConcurrentAgents) {+ return { error: `No available agent slots (${running.length}/${state.config.maxConcurrentAgents})` };}// Pre-validate provider/model resolution before emitting `task:ready`. Thediff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 581486c3da..2bda21f478 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1240,6 +1240,21 @@ describe('forceSpawnTask — pre-validate provider before task:ready', () => {expect(holdIdx, 'the runner check must precede the task:ready emit').toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));});++ // spawnAgentForTask registers its agent as `running` BEFORE flipping the task+ // off `pending`, so the `status !== 'pending'` check above still passes for the+ // seconds between those two writes. Without a live-agent check, a "Run now"+ // 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');+ expect(holderIdx, 'forceSpawnTask must reject a task a running agent holds')+ .toBeGreaterThan(-1);+ expect(forceFn, 'the refusal must name the agent that holds it')+ .toContain('is already running this task');+ expect(holderIdx, 'the live-agent check must precede the task:ready emit')+ .toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));+ });});describe('the runner-down hold — spawn-side gates', () => {