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

fix: preserve CoS agent visibility and perpetual claim refills (#8562)

[._.]/1ee112e95416
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index 8c98e494f4..7aeec55e23 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -35,7 +35,7 @@ const RESUME_MESSAGES = {
const needsAgentFeedback = isAgentFeedbackEligible;
-export default function AgentsTab({ completedRevision = 0, agents, onRefresh, liveOutputs, providers, providersLoaded, apps }) {
+export default function AgentsTab({ agentsLoaded = true, agentsError = null, onRetryAgents, completedRevision = 0, agents, onRefresh, liveOutputs, providers, providersLoaded, apps }) {
const { agentId } = useParams();
const [focusedAgent, setFocusedAgent] = useState(null);
const [focusLoading, setFocusLoading] = useState(false);
@@ -255,11 +255,19 @@ export default function AgentsTab({ completedRevision = 0, agents, onRefresh, li
</span>
)}
</div>
- {runningAgents.length === 0 ? (
+ {agentsError && (
+ <div role="alert" className="mb-3 text-sm text-red-400">
+ {agentsError} {agentsLoaded && 'Showing the last loaded agents.'}
+ <button type="button" onClick={onRetryAgents || onRefresh} className="ml-2 underline">Retry agents</button>
+ </div>
+ )}
+ {!agentsLoaded && !agentsError && <div role="status">Loading active agents…</div>}
+ {runningAgents.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>
- ) : (
+ )}
+ {runningAgents.length > 0 && (
<div className="space-y-2">
{runningAgents.map(agent => (
<AgentCard
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 1bc5411b28..fe3afcdd28 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -145,6 +145,9 @@ export default function ChiefOfStaff() {
const [status, setStatus] = useState(null);
const [tasks, setTasks] = useState({ user: null, cos: null });
const [agents, setAgents] = useState([]);
+ const [agentsLoaded, setAgentsLoaded] = useState(false);
+ const [agentsError, setAgentsError] = useState(null);
+ const agentReadRef = useRef(null);
const [completedRevision, setCompletedRevision] = useState(0);
const [taskHistoryRevision, setTaskHistoryRevision] = useState(0);
const [health, setHealth] = useState(null);
@@ -297,6 +300,30 @@ export default function ChiefOfStaff() {
return 'thinking';
}, []);
+ // Agent snapshots settle independently of status/tasks. Overlay socket changes
+ // received during the read so a slow snapshot cannot undo a live transition.
+ const readAgents = useCallback(async (controller) => {
+ if (!needsAgents) return null;
+ const request = { updates: new Map() };
+ agentReadRef.current = request;
+ setAgentsError(null);
+ const data = await api.getCosAgents({ active: true, signal: controller.signal, silent: true }).catch(() => null);
+ if (controller.signal.aborted || queryRef.current !== queryKey || agentReadRef.current !== request) return null;
+ 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');
+ setAgents(snapshot);
+ setAgentsLoaded(true);
+ } else {
+ setAgentsError('Could not load active agents.');
+ }
+ // Opening Agents must not wait for unrelated status or task summaries.
+ if (activeTab === 'agents') setLoading(false);
+ return data;
+ }, [needsAgents, queryKey, activeTab]);
+
const fetchData = useCallback(async function refreshPageData() {
const route = activeTab;
if (inFlight.current?.key === queryKey && !inFlight.current.controller.signal.aborted) {
@@ -311,7 +338,7 @@ export default function ChiefOfStaff() {
const coreRead = Promise.all([
api.getCosStatus().catch(() => null),
needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTask, signal: controller.signal, silent: true }).catch(() => null) : Promise.resolve(null),
- needsAgents ? api.getCosAgents({ active: true, signal: controller.signal, silent: true }).catch(() => null) : Promise.resolve([]),
+ readAgents(controller),
]);
const healthRead = api.getCosHealth().catch(() => null).then((data) => {
// Health is independently useful to the Health tab. Commit it as soon
@@ -340,7 +367,6 @@ export default function ChiefOfStaff() {
// returns to the pending-AND-active state this guard exists to remove.
if (queueSeqRef.current === queueSeq) {
if (tasksData) setTasks(tasksData);
- if (agentResult) setAgents(agentsData);
}
setLoading(false);
@@ -388,7 +414,7 @@ export default function ChiefOfStaff() {
if (pending.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshPageData();
});
return pending.promise;
- }, [activeTab, queryKey, selectedTask, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, applyProviders, applyApps]);
+ }, [activeTab, queryKey, selectedTask, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, applyProviders, applyApps, readAgents]);
// Coalesce event bursts into a read of the visible queue and scalar shell
// status. Insights use persisted health; invalidation never runs PM2 repair.
@@ -408,12 +434,11 @@ export default function ChiefOfStaff() {
request.promise = Promise.all([
api.getCosStatus().catch(() => null),
needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTask, signal: controller.signal, silent: true }).catch(() => null) : null,
- needsAgents ? api.getCosAgents({ active: true, signal: controller.signal, silent: true }).catch(() => null) : null,
- ]).then(async ([summary, tasksData, agentsData]) => {
+ readAgents(controller),
+ ]).then(async ([summary, tasksData]) => {
if (controller.signal.aborted || queryRef.current !== queryKey || queueSeqRef.current !== queueSeq) return;
if (summary) setStatus(summary);
if (tasksData) setTasks(tasksData);
- if (agentsData) setAgents(agentsData);
const insightsData = await insightsRead;
if (!controller.signal.aborted && queueSeqRef.current === queueSeq && insightsData?.insights) setInsights(insightsData.insights);
}).finally(() => {
@@ -421,7 +446,7 @@ export default function ChiefOfStaff() {
if (request.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshQueueData();
});
return request.promise;
- }, [queryKey, needsTasks, needsAgents, selectedTask]);
+ }, [queryKey, needsTasks, selectedTask, readAgents]);
// All page insight reads use cached health. Explicit Run Check owns repairs;
// task invalidations must never trigger a health-check/socket feedback loop.
@@ -512,7 +537,7 @@ export default function ChiefOfStaff() {
const handleAgentSpawned = (data) => {
if (needsAgents && data?.id) {
- queueSeqRef.current += 1;
+ agentReadRef.current?.updates.set(data.id, data);
setAgents(prev => [...prev.filter(agent => agent.id !== data.id), data]);
}
setAgentState('coding');
@@ -533,6 +558,7 @@ export default function ChiefOfStaff() {
const handleAgentUpdated = (updatedAgent) => {
if (!needsAgents) return;
+ agentReadRef.current?.updates.set(updatedAgent.id, updatedAgent);
// Update the specific agent in the agents list without fetching all data
setAgents(prev => prev.map(agent =>
agent.id === updatedAgent.id ? updatedAgent : agent
@@ -552,6 +578,11 @@ export default function ChiefOfStaff() {
socket.on('cos:agent:output', handleAgentOutput);
const handleAgentCompleted = (data) => {
+ const id = data?.id || data?.agentId;
+ if (needsAgents && id) {
+ agentReadRef.current?.updates.set(id, { ...data, id, status: 'completed' });
+ setAgents(prev => prev.filter(agent => agent.id !== id));
+ }
setCompletedRevision(value => value + 1);
setAgentState('reviewing');
// Three outcomes, not two: a run retired by Resume/Relaunch never reached a
@@ -1358,7 +1389,7 @@ export default function ChiefOfStaff() {
{activeTab === 'agents' && (
<div role="tabpanel" id="tabpanel-agents" aria-labelledby="tab-agents">
<Suspense fallback={<TabLoadFallback label="agents" />}>
- <AgentsTab completedRevision={completedRevision} agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} providers={providers} providersLoaded={providersLoaded} apps={apps} />
+ <AgentsTab agentsLoaded={agentsLoaded} agentsError={agentsError} onRetryAgents={fetchQueue} completedRevision={completedRevision} agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} providers={providers} providersLoaded={providersLoaded} apps={apps} />
</Suspense>
</div>
)}
diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsx
index 8b51df8b07..fedc0a05e2 100644
--- a/client/src/pages/ChiefOfStaff.test.jsx
+++ b/client/src/pages/ChiefOfStaff.test.jsx
@@ -1217,3 +1217,59 @@ describe('ChiefOfStaff route-scoped data', () => {
expect(api.getCosTasks).not.toHaveBeenCalled();
});
});
+
+
+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 pending on navigation and paints agents before a slow status summary', async () => {
+ await renderSettledAt('mind');
+ let resolveAgents;
+ api.getCosAgents.mockReturnValueOnce(new Promise(resolve => { resolveAgents = resolve; }));
+ api.getCosStatus.mockReturnValue(new Promise(() => {}));
+ fireEvent.click(screen.getByRole('tab', { name: 'Agents' }));
+ expect(await screen.findByText('Loading active agents…')).toBeInTheDocument();
+ expect(screen.queryByText(/No active agents/)).toBeNull();
+ await act(async () => resolveAgents([agent]));
+ expect(await screen.findByText('Example active work')).toBeInTheDocument();
+ });
+
+ it('distinguishes a failed initial read from empty and retries without reloading the page', async () => {
+ api.getCosAgents.mockRejectedValueOnce(new Error('Unavailable'));
+ await renderSettledAt('agents');
+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load active agents.');
+ expect(screen.queryByText(/No active agents/)).toBeNull();
+ api.getCosAgents.mockResolvedValue([agent]);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry agents' }));
+ expect(await screen.findByText('Example active work')).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ it('preserves known agents across non-agent tabs and a failed refresh', async () => {
+ api.getCosAgents.mockResolvedValue([agent]);
+ await renderSettledAt('agents');
+ expect(await screen.findByText('Example active work')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('tab', { name: 'Mind' }));
+ await screen.findByTestId('mind-tab');
+ api.getCosAgents.mockRejectedValue(new Error('Unavailable'));
+ fireEvent.click(screen.getByRole('tab', { name: 'Agents' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent('Showing the last loaded agents.');
+ expect(screen.getByText('Example active work')).toBeInTheDocument();
+ expect(screen.queryByText(/No active agents/)).toBeNull();
+ });
+
+ it('merges lifecycle events received while the initial snapshot is in flight', async () => {
+ await renderSettledAt('mind');
+ let resolveAgents;
+ api.getCosAgents.mockReturnValueOnce(new Promise(resolve => { resolveAgents = resolve; }));
+ fireEvent.click(screen.getByRole('tab', { name: 'Agents' }));
+ await waitFor(() => expect(api.getCosAgents).toHaveBeenCalled());
+ await act(async () => {
+ socketHandler('cos:agent:updated')({ ...agent, status: 'paused' });
+ resolveAgents([agent]);
+ });
+ expect(await screen.findByText('Paused Agents')).toBeInTheDocument();
+ expect(screen.queryByText('1 running')).toBeNull();
+ });
+});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 7975e68a67..28e72a7753 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -362,12 +362,12 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
const other = existsSync(otherPath) ? await readTaskFile(otherPath) : [];
const owner = [...tasks, ...other].find(task => task.id !== ignoreTaskId
&& DEVELOPMENT_ACTIVE_STATUSES.has(task.status) && sameDevelopmentWork(task, taskData)
- // A pinned claim of one specific issue is not a duplicate of an already-running
- // unpinned (wildcard) claim-issue drain for the same app: the drain works the
- // backlog in bulk, but the operator must still be able to hand-pick a specific
- // issue while it runs. Two pinned claims for the same issue, or two unpinned
- // drains for the same app, remain duplicates.
- && !(newWorkIdentity.kind === 'issue' && newWorkIdentity.key !== '*' && developmentWorkIdentity(task)?.key === '*'));
+ // Targeted claims and the backlog drain coexist in either admission order.
+ // Otherwise a completed drain cannot refill while a targeted claim runs:
+ // the on-demand request is consumed as a duplicate with nothing queued.
+ // Two claims of the same issue, or two unpinned drains, still deduplicate.
+ && !(newWorkIdentity.kind === 'issue'
+ && (newWorkIdentity.key === '*') !== (developmentWorkIdentity(task)?.key === '*')));
if (owner) return { ...owner, duplicate: true };
}
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 5cc4e0a854..e2ca59fb58 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -2361,6 +2361,15 @@ describe('shared development work admission', () => {
await updateTask(manual.id, { status: 'completed' }, 'user');
expect((await addTask({ description: 'New evidence', metadata }, 'internal')).duplicate).not.toBe(true);
});
+ it('persists a perpetual refill while targeted claims are running, without admitting a second drain', async () => {
+ const targeted = await addTask({ description: 'Claim example issue', app: 'example', claimFlow: true, claimTarget: '42' }, 'user');
+ await updateTask(targeted.id, { status: 'in_progress' }, 'user');
+ const refill = await addTask({ description: 'Continue backlog', app: 'example', claimFlow: true }, 'internal');
+ expect(refill.duplicate).not.toBe(true);
+ expect((await getCosTasks()).tasks).toEqual(expect.arrayContaining([expect.objectContaining({ id: refill.id, status: 'pending' })]));
+ expect(await addTask({ description: 'Another backlog continuation', app: 'example', claimFlow: true }, 'internal'))
+ .toMatchObject({ id: refill.id, duplicate: true });
+ });
it('lets a manual pinned claim proceed alongside a running untargeted drain, but still blocks true duplicates', async () => {
const claim = await addTask({ description: 'Claim next', app: 'example', claimFlow: true }, 'internal');
// A manual claim of a specific issue is not a duplicate of the app's running