Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: distinguish CoS delivery cleanup from active agents
Adam Eivyd25f4f1902bb
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsxindex 19d1cf21c2..b446a005e0 100644--- a/client/src/components/cos/tabs/AgentsTab.jsx+++ b/client/src/components/cos/tabs/AgentsTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useMemo, useCallback } from 'react';-import { useParams, useSearchParams } from 'react-router';+import { Link, useParams, useSearchParams } from 'react-router';import { Trash2, Search, X, MessageSquare } from 'lucide-react';import toast from '../../ui/Toast';import * as api from '../../../services/api';@@ -195,6 +195,8 @@ export default function AgentsTab({ agentsLoaded = true, agentsError = null, onR// Running agents come from props (real-time via parent socket updates)const runningAgents = agents.filter(a => a.status === 'running' && !deletedIds.has(a.id));const pausedAgents = agents.filter(a => a.status === 'paused' && !deletedIds.has(a.id));+ const finalizingAgents = useMemo(() => agents.filter(agent => agent.deliveryPending && !deletedIds.has(agent.id)), [agents, deletedIds]);+ const finalizingIds = useMemo(() => new Set(finalizingAgents.map(agent => agent.id)), [finalizingAgents]);// Completed agents still in state (recently completed, not yet archived)const recentCompleted = agents.filter(a => a.status === 'completed');// Merge recent completed (from state) with loaded (from disk), deduplicate@@ -202,7 +204,7 @@ export default function AgentsTab({ agentsLoaded = true, agentsError = null, onRconst seen = new Set();const merged = [];const addAgent = (agent) => {- if (seen.has(agent.id) || deletedIds.has(agent.id)) return;+ if (seen.has(agent.id) || deletedIds.has(agent.id) || finalizingIds.has(agent.id)) return;seen.add(agent.id);const feedback = feedbackUpdates[agent.id];merged.push(feedback ? { ...agent, feedback } : agent);@@ -213,7 +215,7 @@ export default function AgentsTab({ agentsLoaded = true, agentsError = null, onRfor (const agent of loadedAgents) addAgent(agent);return merged.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));- }, [recentCompleted, loadedAgents, feedbackUpdates, deletedIds]);+ }, [recentCompleted, loadedAgents, feedbackUpdates, deletedIds, finalizingIds]);const totalCount = history.total ?? allCompleted.length;@@ -255,7 +257,8 @@ export default function AgentsTab({ agentsLoaded = true, agentsError = null, onR{selectedAgent ? <AgentCard key={agentId} agent={selectedAgent}initiallyExpanded liveOutput={liveOutputs[agentId]} completed={selectedAgent.status === 'completed'}paused={selectedAgent.status === 'paused'} durations={durations} onFeedbackChange={handleFeedbackChange}- onPause={handlePause} onKill={handleKill} onResume={handleResumeClick} onDelete={handleDelete} onRelaunch={handleRelaunchClick} />+ onPause={handlePause} onKill={handleKill} onResume={selectedAgent.deliveryPending ? undefined : handleResumeClick}+ onDelete={selectedAgent.deliveryPending ? undefined : handleDelete} onRelaunch={handleRelaunchClick} />: <p role="status">{focusLoading ? 'Loading agent…' : 'Agent not found or unavailable.'}</p>}</section>}{/* Active Agents */}@@ -275,7 +278,7 @@ export default function AgentsTab({ agentsLoaded = true, agentsError = null, onR</div>)}{!agentsLoaded && !agentsError && <div role="status">Loading active agents…</div>}- {runningAgents.length === 0 && agentsLoaded && !agentsError && (+ {runningAgents.length === 0 && finalizingAgents.length === 0 && agentsLoaded && !agentsError && (<div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">No active agents. Start CoS and add tasks to see agents working.</div>@@ -297,6 +300,21 @@ export default function AgentsTab({ agentsLoaded = true, agentsError = null, onR)}</div>+ {finalizingAgents.length > 0 && (+ <section aria-label="Finalizing delivery" className="space-y-2">+ <h3 className="text-lg font-semibold text-white">Finalizing delivery</h3>+ <p className="text-sm text-gray-400">Awaiting delivery verification and workspace cleanup.</p>+ {finalizingAgents.map(agent => (+ <div key={agent.id} className="space-y-1">+ <Link to={`/cos/tasks?task=${encodeURIComponent(agent.taskId)}`} className="inline-block text-sm text-port-accent hover:underline [overflow-wrap:anywhere]">+ View task {agent.taskId}+ </Link>+ <AgentCard agent={agent} completed durations={durations} onFeedbackChange={handleFeedbackChange} />+ </div>+ ))}+ </section>+ )}+{/* Paused Agents */}{pausedAgents.length > 0 && (<div>diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 03910c0e46..261b9347d3 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -36,10 +36,12 @@ import EffortSelect from '../EffortSelect';import RelaunchAgentModal from './RelaunchAgentModal';import AgentCard from './AgentCard';import PreflightProgress from './PreflightProgress';+import { isDeliveryCleanupHeld } from '../../../../../server/lib/taskRetryHold.js';const statusIcons = {pending: <Clock size={16} aria-hidden="true" className="text-yellow-500" />,in_progress: <Activity size={16} aria-hidden="true" className="text-port-accent animate-pulse" />,+ finalizing: <Clock size={16} aria-hidden="true" className="text-gray-400" />,completed: <CheckCircle size={16} aria-hidden="true" className="text-port-success" />,blocked: <Ban size={16} aria-hidden="true" className="text-port-error" />,// A sub-agent disputing a reviewer rejection (#2441) — awaiting resolution.@@ -151,7 +153,8 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spa// 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 finalizing = task.status === 'in_progress' && isDeliveryCleanupHeld(task.metadata) && agent?.status !== 'running';+ const displayStatus = finalizing ? 'finalizing' : spawning ? 'in_progress' : task.status;const idScope = isSystem ? 'sys' : 'user';// Either queue. A USER row can hold too: a row the importer had to RECOVER is// withheld from the unattended spawn and keeps that hold (#7300, #7367). Gating the button on `isSystem` would leave it pending with@@ -443,6 +446,7 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spa{statusIcons[displayStatus]}</button><div className="flex-1 min-w-0">+ {finalizing && <p className="mb-1 text-sm text-gray-400">Agent execution ended. Delivery verification and cleanup are pending.</p>}<div className="flex items-center gap-2 mb-1 flex-wrap"><span className="text-sm font-mono text-gray-500 min-w-0 break-words">{task.id}</span>{task.metadata?.app && apps?.find(a => a.id === task.metadata.app)?.name && (diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex 62e923f631..945231afac 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -27,6 +27,7 @@ import useAssignableInstances from '../../../hooks/useAssignableInstances';import { formatCount } from '../../../utils/formatters';import { runningAgentsByTaskId, isSpawningTask } from '../../../lib/cosSpawnWindow';import BrailleSpinner from '../../BrailleSpinner';+import { isDeliveryCleanupHeld } from '../../../../../server/lib/taskRetryHold.js';// Maps a task-section status → micrographic glyph spec. Animation only on// states where motion communicates real work happening (running tasks).@@ -115,6 +116,8 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li(task) => isSpawningTask(task, runningAgentByTaskId),[runningAgentByTaskId]);+ const isFinalizing = useCallback(task => task.status === 'in_progress'+ && isDeliveryCleanupHeld(task.metadata) && !runningAgentByTaskId.has(task.id), [runningAgentByTaskId]);// Split tasks by status for system tasksconst pendingSystemTasks = useMemo(() =>@@ -122,9 +125,10 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li[cosTasks, isSpawning]);const activeSystemTasks = useMemo(() =>- cosTasks.filter(t => t.status === 'in_progress' || isSpawning(t)),- [cosTasks, isSpawning]+ cosTasks.filter(t => (t.status === 'in_progress' || isSpawning(t)) && !isFinalizing(t)),+ [cosTasks, isSpawning, isFinalizing]);+ const finalizingSystemTasks = useMemo(() => cosTasks.filter(isFinalizing), [cosTasks, isFinalizing]);const blockedSystemTasks = useMemo(() =>cosTasks.filter(t => t.status === 'blocked'),[cosTasks]@@ -140,9 +144,10 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li[userTasksLocal, isSpawning]);const activeUserTasksLocal = useMemo(() =>- userTasksLocal.filter(t => t.status === 'in_progress' || isSpawning(t)),- [userTasksLocal, isSpawning]+ userTasksLocal.filter(t => (t.status === 'in_progress' || isSpawning(t)) && !isFinalizing(t)),+ [userTasksLocal, isSpawning, isFinalizing]);+ const finalizingUserTasksLocal = useMemo(() => userTasksLocal.filter(isFinalizing), [userTasksLocal, isFinalizing]);const blockedUserTasksLocal = useMemo(() =>userTasksLocal.filter(t => t.status === 'blocked'),[userTasksLocal]@@ -241,6 +246,20 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], liconst isUserLoading = tasks?.user == null;const isCosLoading = tasks?.cos == null;const isQueueLoading = isUserLoading || isCosLoading;+ const renderFinalizingTasks = (rows, source) => rows.length > 0 && (+ <section aria-label={`${source === 'internal' ? 'System' : 'User'} tasks finalizing delivery`} className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ <h3 className="px-3 py-2 text-sm font-medium text-gray-400 border-b border-port-border">+ Finalizing delivery ({formatCount(rows.length)})+ </h3>+ <div className="p-2 space-y-1.5">+ {rows.map(task => (+ <TaskItem key={task.id} task={task} isSystem={source === 'internal'} selected={isTaskSelected(task, source)}+ onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} onTaskDeleted={handleTaskDeleted}+ providers={providers} providersLoaded={providersLoaded} durations={durations} apps={apps} instances={assignableInstances} />+ ))}+ </div>+ </section>+ );return (<div className="space-y-6">@@ -257,6 +276,7 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li<>{formatCount(pendingUserTasksLocal.length + pendingSystemTasks.length)} pending{' · '}{formatCount(activeUserTasksLocal.length + activeSystemTasks.length)} active+ {' · '}{formatCount(finalizingUserTasksLocal.length + finalizingSystemTasks.length)} finalizing{' · '}{formatCount(blockedUserTasksLocal.length + blockedSystemTasks.length)} blocked</>)}@@ -269,7 +289,7 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li<div className="relative bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-400"><BrailleSpinner text="Loading task queue…" /></div>- ) : pendingUserTasksLocal.length === 0 && activeUserTasksLocal.length === 0 && blockedUserTasksLocal.length === 0 && (tasks.user?.completedCount ?? completedUserTasksLocal.length) === 0 ? (+ ) : pendingUserTasksLocal.length === 0 && activeUserTasksLocal.length === 0 && finalizingUserTasksLocal.length === 0 && blockedUserTasksLocal.length === 0 && (tasks.user?.completedCount ?? completedUserTasksLocal.length) === 0 ? (<div className="relative bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500"><SchematicLabel module="USER" status="EMPTY" glyph="bracket-pair" state="idle" variant="tab" />No user tasks. Add one above.@@ -323,6 +343,8 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li</div>)}+ {renderFinalizingTasks(finalizingUserTasksLocal, 'user')}+{/* Blocked Section */}{blockedUserTasksLocal.length > 0 && (<div className="bg-port-card border border-port-border rounded-lg overflow-hidden">@@ -377,7 +399,7 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li<div className="relative bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-400"><BrailleSpinner text="Loading system tasks…" /></div>- ) : pendingSystemTasks.length === 0 && activeSystemTasks.length === 0 && blockedSystemTasks.length === 0 && (tasks.cos?.completedCount ?? completedSystemTasks.length) === 0 ? (+ ) : pendingSystemTasks.length === 0 && activeSystemTasks.length === 0 && finalizingSystemTasks.length === 0 && blockedSystemTasks.length === 0 && (tasks.cos?.completedCount ?? completedSystemTasks.length) === 0 ? (<div className="relative bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500"><SchematicLabel module="COS" status="EMPTY" glyph="bracket-pair" state="idle" variant="tab" />No system tasks.@@ -418,6 +440,8 @@ export default function TasksTab({ completedRevision = 0, tasks, agents = [], li</div>)}+ {renderFinalizingTasks(finalizingSystemTasks, 'internal')}+{/* Blocked Section */}{blockedSystemTasks.length > 0 && (<div className="bg-port-card border border-port-border rounded-lg overflow-hidden">diff --git a/client/src/components/cos/tabs/TasksTab.test.jsx b/client/src/components/cos/tabs/TasksTab.test.jsxindex e50bc9a4d6..a084a54487 100644--- a/client/src/components/cos/tabs/TasksTab.test.jsx+++ b/client/src/components/cos/tabs/TasksTab.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { fireEvent, render, screen, waitFor, act } from '@testing-library/react';+import { fireEvent, render, screen, waitFor, act, within } from '@testing-library/react';import { MemoryRouter } from 'react-router';vi.mock('../../../hooks/useAssignableInstances', () => ({ default: () => ({ instances: [], isFederated: false }) }));@@ -49,6 +49,35 @@ describe('TasksTab spawning window', () => {// 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('separates cleanup-held user and system tasks from running work', async () => {+ const heldTask = id => ({ id, description: `Finalize ${id}`, status: 'in_progress',+ metadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: `agent-${id}` } });+ renderTab({+ tasks: { user: { tasks: [heldTask('task-example')] }, cos: { tasks: [heldTask('sys-rl-example')] } },+ agents: [{ id: 'agent-sys-rl-example', taskId: 'sys-rl-example', status: 'completed' }],+ });++ const user = await screen.findByRole('region', { name: 'User tasks finalizing delivery' });+ const system = screen.getByRole('region', { name: 'System tasks finalizing delivery' });+ expect(within(user).getByText('Finalize task-example')).toBeInTheDocument();+ expect(within(system).getByText('Finalize sys-rl-example')).toBeInTheDocument();+ expect(within(system).getByRole('button', { name: /Status: finalizing/ })).toBeInTheDocument();+ expect(screen.queryByText(/^Active \(/)).toBeNull();+ expect(screen.queryByText(/^Active agent /)).toBeNull();+ });++ it('keeps an actual running agent active even if an old cleanup marker remains', async () => {+ renderTab({+ tasks: { user: { tasks: [] }, cos: { tasks: [{ ...pendingTask('sys-running'), status: 'in_progress',+ metadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-older' } }] } },+ agents: [liveAgent('agent-current', 'sys-running')],+ });++ expect(await screen.findByText('Active (1)')).toBeInTheDocument();+ expect(screen.getByText('Active agent agent-current')).toBeInTheDocument();+ expect(screen.queryByRole('region', { name: /finalizing delivery/ })).toBeNull();+ });+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: [] } },diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 50801be420..41a7540bee 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -350,8 +350,8 @@ export default function ChiefOfStaff() {agentReadRef.current = null;if (Array.isArray(data)) {const merged = new Map(data.map(agent => [agent.id, agent]));- for (const [id, agent] of request.updates) merged.set(id, agent);- const snapshot = [...merged.values()].filter(agent => agent.status !== 'completed');+ for (const [id, agent] of request.updates) merged.set(id, { ...merged.get(id), ...agent });+ const snapshot = [...merged.values()].filter(agent => agent.status !== 'completed' || agent.deliveryPending);setAgents(snapshot);setAgentsLoaded(true);} else {@@ -600,8 +600,8 @@ export default function ChiefOfStaff() {agentReadRef.current?.updates.set(updatedAgent.id, updatedAgent);// Update the specific agent in the agents list without fetching all datasetAgents(prev => prev.map(agent =>- agent.id === updatedAgent.id ? updatedAgent : agent- ).filter(agent => agent.status !== 'completed'));+ agent.id === updatedAgent.id ? { ...agent, ...updatedAgent } : agent+ ).filter(agent => agent.status !== 'completed' || agent.deliveryPending));};socket.on('cos:agent:updated', handleAgentUpdated);diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 70af93abab..1524d60160 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -8,6 +8,7 @@ import { MemoryRouter, Routes, Route, useNavigate } from 'react-router';vi.mock('../hooks/useAssignableInstances', () => ({ default: () => ({ instances: [], isFederated: false }) }));const api = vi.hoisted(() => ({getCosStatus: vi.fn(),+ getInstanceFeatures: vi.fn(),getCosTasks: vi.fn(),getCosTask: vi.fn(),getCosAgents: vi.fn(),@@ -113,6 +114,7 @@ beforeEach(() => {vi.clearAllMocks();socketStub.resetListeners();api.getCosStatus.mockResolvedValue({ running: false, config, stats: {} });+ api.getInstanceFeatures.mockResolvedValue({ features: [] });api.getCosTasks.mockResolvedValue({ user: null, cos: null });api.getCosAgents.mockResolvedValue([]);api.getCosHealth.mockResolvedValue({ issues: [] });@@ -1357,6 +1359,34 @@ describe('ChiefOfStaff active-agent snapshot readiness', () => {const agent = { id: 'agent-example', taskId: 'task-example', status: 'running', startedAt: '2026-01-01T00:00:00.000Z', metadata: { taskDescription: 'Example active work' } };const socketHandler = event => socketStub.on.mock.calls.filter(([name]) => name === event).at(-1)[1];+ it('shows completed system cleanup owners until task events confirm delivery is finished', async () => {+ withFakeTimers();+ const finalizing = { ...agent, id: 'agent-system-example', taskId: 'sys-rl-example', status: 'completed', deliveryPending: true,+ completedAt: '2026-01-01T00:10:00.000Z', metadata: { taskType: 'internal', taskDescription: 'Example system delivery' } };+ const { deliveryPending: _deliveryPending, ...archived } = finalizing;+ api.getCosAgents.mockResolvedValue([finalizing]);+ api.getCosCompletedAgents.mockResolvedValue({ items: [archived], total: 1, nextCursor: null });+ await renderSettledAt('agents');++ const section = screen.getByRole('region', { name: 'Finalizing delivery' });+ expect(within(section).getByText('Example system delivery')).toBeInTheDocument();+ expect(within(section).getByRole('link', { name: /sys-rl-example/ })).toHaveAttribute('href', '/cos/tasks?task=sys-rl-example');+ expect(screen.getAllByText('Example system delivery')).toHaveLength(1);+ expect(screen.queryByText(/No active agents/)).toBeNull();+ expect(within(section).queryByRole('button', { name: /Resume|Remove agent/ })).toBeNull();++ await act(async () => socketHandler('cos:agent:updated')(archived));+ expect(screen.getByRole('region', { name: 'Finalizing delivery' })).toBeInTheDocument();++ api.getCosAgents.mockResolvedValue([]);+ await act(async () => {+ socketHandler('cos:tasks:changed')({ task: { id: finalizing.taskId, status: 'completed' } });+ await vi.advanceTimersByTimeAsync(450);+ });+ expect(screen.queryByRole('region', { name: 'Finalizing delivery' })).toBeNull();+ expect(screen.getByText('Example system delivery')).toBeInTheDocument();+ });+it.each([true, false])('keeps unknown CoS status out of the loaded Agents UI until running=%s arrives', async (running) => {let resolveStatus;api.getCosStatus.mockReturnValueOnce(new Promise(resolve => { resolveStatus = resolve; }));diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex 653923eeed..09e063a747 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -43,6 +43,7 @@ vi.mock('../services/cosState.js', () => ({}));vi.mock('../services/cosTaskStore.js', () => ({getAllTasks: vi.fn(),+ getTaskView: vi.fn(),getUserTasks: vi.fn(),getCosTasks: vi.fn(),reorderTasks: vi.fn(),@@ -64,6 +65,7 @@ vi.mock('../services/cosAgentLifecycle.js', () => ({cleanupZombieAgents: vi.fn(),getAgents: vi.fn(),getAgent: vi.fn(),+ getAgentRecord: vi.fn(),deleteAgent: vi.fn(),sendBtwToAgent: vi.fn()}));@@ -156,8 +158,8 @@ vi.mock('../services/codeReview.js', () => ({}));// Import mocked modules-import { addTask, approveTask, deleteTask, reorderTasks, updateTask } from '../services/cosTaskStore.js';-import { cleanupZombieAgents, deleteAgent, getAgent, getAgents, sendBtwToAgent } from '../services/cosAgentLifecycle.js';+import { addTask, approveTask, deleteTask, getTaskView, reorderTasks, updateTask } from '../services/cosTaskStore.js';+import { cleanupZombieAgents, deleteAgent, getAgent, getAgentRecord, getAgents, sendBtwToAgent } from '../services/cosAgentLifecycle.js';import { clearCompletedAgents } from '../services/cosAgentArchive.js';import { evaluateTasks } from '../services/cosTaskGenerator.js';import { generateReport, getBriefing, getLatestBriefing, getReport, getTodayActivity, getTodayReport, getWhileAwayActivity, listBriefings, listReports } from '../services/cosReports.js';@@ -188,6 +190,9 @@ describe('CoS Routes', () => {vi.clearAllMocks();// GET /tasks settles its payload against the live agent list (#spawn window).getAgents.mockResolvedValue([]);+ cleanupZombieAgents.mockResolvedValue({ cleaned: [], count: 0 });+ getTaskView.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });+ getAgentRecord.mockResolvedValue(null);});describe('GET /api/cos', () => {@@ -1858,6 +1863,55 @@ describe('CoS Routes', () => {});});describe('CoS scoped collections', () => {+ it('keeps the exact delivery cleanup owners visible, including archived system runs', async () => {+ const user = { id: 'agent-user', taskId: 'task-example', status: 'completed', output: ['transcript'] };+ const system = { id: 'agent-system', taskId: 'sys-rl-example', status: 'completed', metadata: { taskDescription: 'Finish example delivery' } };+ getAgents.mockResolvedValue([+ { id: 'agent-running', taskId: 'task-running', status: 'running' },+ { id: 'agent-paused', status: 'paused' },+ { id: 'agent-old', taskId: user.taskId, status: 'completed' },+ user,+ ]);+ const cleanupTask = agent => ({ id: agent.taskId, status: 'in_progress', metadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: agent.id } });+ getTaskView.mockResolvedValue({ user: { tasks: [cleanupTask(user)] }, cos: { tasks: [cleanupTask(system)] } });+ getAgentRecord.mockResolvedValue(system);++ const response = await request(app).get('/api/cos/agents?active=1');++ expect(response.status).toBe(200);+ expect(response.body.map(agent => agent.id)).toEqual(['agent-running', 'agent-paused', user.id, system.id]);+ expect(response.body.slice(2)).toEqual([+ { id: user.id, taskId: user.taskId, status: 'completed', deliveryPending: true },+ { ...system, deliveryPending: true },+ ]);+ expect(user).not.toHaveProperty('deliveryPending');+ expect(getAgentRecord).toHaveBeenCalledExactlyOnceWith(system.id);+ expect(getAgent).not.toHaveBeenCalled();++ getTaskView.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });+ expect((await request(app).get('/api/cos/agents?active=1')).body.map(agent => agent.id))+ .toEqual(['agent-running', 'agent-paused']);+ });++ it('does not revive finished, missing, mismatched or superseded cleanup owners', async () => {+ getAgents.mockResolvedValue([{ id: 'agent-running', taskId: 'task-running', status: 'running' }]);+ const task = (id, owner, status = 'in_progress') => ({ id, status, metadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: owner } });+ getTaskView.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [+ task('task-done', 'agent-done', 'completed'),+ task('task-running', 'agent-older'),+ task('task-missing', 'agent-missing'),+ task('task-mismatch', 'agent-mismatch'),+ ] } });+ getAgentRecord.mockImplementation(async id => id === 'agent-mismatch'+ ? { id, taskId: 'other-task', status: 'completed' } : null);++ const response = await request(app).get('/api/cos/agents?active=1');++ expect(response.status).toBe(200);+ expect(response.body).toEqual([{ id: 'agent-running', taskId: 'task-running', status: 'running' }]);+ expect(getAgentRecord.mock.calls.map(([id]) => id).sort()).toEqual(['agent-mismatch', 'agent-missing']);+ });+it('scopes live agents and validates completed page bounds without changing legacy lists', async () => {getAgents.mockResolvedValue([{ id: 'running', status: 'running' }, { id: 'done', status: 'completed' }]);expect((await request(app).get('/api/cos/agents?active=1')).body.map(agent => agent.id)).toEqual(['running']);diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex 82edc21e14..60b009467f 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -4,7 +4,8 @@import { Router } from 'express';import { z } from 'zod';-import { cleanupZombieAgents, deleteAgent, getAgent, getAgentPrompt, getAgents, sendBtwToAgent } from '../services/cosAgentLifecycle.js';+import { cleanupZombieAgents, deleteAgent, getAgent, getAgentPrompt, getAgentRecord, getAgents, sendBtwToAgent } from '../services/cosAgentLifecycle.js';+import { getTaskView } from '../services/cosTaskStore.js';import { clearCompletedAgents } from '../services/cosAgentArchive.js';import { getAgentDates, getAgentsByDate, getCompletedAgentPage } from '../services/cosAgentIndex.js';import { getFeedbackStats, getPendingAgentFeedback, getPendingAgentFeedbackCount, getPendingAgentFeedbackPage, submitAgentFeedback } from '../services/cosAgentFeedback.js';@@ -13,6 +14,7 @@ import { getHealthStatus, runHealthCheck } from '../services/cosHealthMonitor.jsimport * as agentOrchestrator from '../services/agentOrchestrator.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { toAgentListItems } from '../lib/cosAgentListProjection.js';+import { isDeliveryCleanupHeld } from '../lib/taskRetryHold.js';import { securityScanRequestSchema } from '../lib/securityScanEvidence.js';import { validateRequest, resumeCosAgentSchema, relaunchCosAgentSchema, cosAgentFeedbackBodySchema, cosAgentBtwBodySchema } from '../lib/validation.js';@@ -108,8 +110,28 @@ router.get('/agents', asyncHandler(async (req, res) => {console.error(`🧹 Background zombie cleanup failed: ${err.message}`);});const { active } = validateRequest(z.object({ active: z.literal('1').optional() }), req.query);- const agents = await getAgents();- res.json(toAgentListItems(active ? agents.filter(agent => agent.status !== 'completed') : agents));+ const [agents, taskView] = await Promise.all([+ getAgents(),+ active ? getTaskView({ kind: 'queue' }) : null,+ ]);+ if (!active) return res.json(toAgentListItems(agents));++ const resident = new Map(agents.map(agent => [agent.id, agent]));+ const visible = new Map(agents.filter(agent => agent.status !== 'completed').map(agent => [agent.id, agent]));+ const runningTasks = new Set(agents.filter(agent => agent.status === 'running').map(agent => agent.taskId));+ const tasks = [...(taskView.user?.tasks || []), ...(taskView.cos?.tasks || [])];+ // Execution can finish before delivery does. Follow only the task's exact+ // cleanup owner, including archived records, without loading transcripts or+ // changing the run's terminal status (and therefore scheduler capacity).+ await Promise.all(tasks.filter(task => task.status === 'in_progress' && isDeliveryCleanupHeld(task.metadata) && !runningTasks.has(task.id)).map(async task => {+ const id = task.metadata.deliveryRecoveryAgentId;+ if (visible.has(id)) return;+ const agent = resident.get(id) || await getAgentRecord(id);+ if (agent?.status === 'completed' && agent.taskId === task.id) {+ visible.set(id, { ...agent, deliveryPending: true });+ }+ }));+ res.json(toAgentListItems([...visible.values()]));}));// Bounded completed history, including state records not yet archived.