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

Load CoS collections on demand and replace page polling (#7969)

[._.]/12a0c6abd559
diff --git a/client/src/AGENTS.md b/client/src/AGENTS.md
index fda00c0555..a16056d0b4 100644
--- a/client/src/AGENTS.md
+++ b/client/src/AGENTS.md
@@ -56,6 +56,10 @@ For the full "adding a new page" checklist (nav manifest entry shape, palette ac
- **The overlay is always portaled to `<body>` — never re-nest it.** The backdrop and panel are both `position:fixed`, and a `filter` / `backdrop-filter` / `transform` ancestor becomes their containing block; on the "glass" themes `index.css` gives every bordered/rounded `.bg-port-card` a `backdrop-filter`, so an inline drawer nested under a card was sized to the *card*, not the viewport (issue #4150). Portaling is unconditional rather than an opt-in flag, so no call site has to remember it — React still routes events and context through the React tree. The one thing the portal leaves behind is a **page-scoped CSS theming root written as descendant selectors** (`.openworld-themed` in `index.css`): a caller inside one must pass that class as `portalClassName` (see `OpenWorldSettingsDrawer.jsx`). Same trap, same fix, for any new hand-rolled `fixed inset-0` overlay — portal it (`Modal`'s `usePortal`, `GalleryImagePicker.jsx`).
- **Worked examples:** `client/src/components/apps/EditAppDrawer.jsx` (built-in `tabs` layout, `size="lg"`, `useDrawerTab('appTab', …)`) and `client/src/components/settings/ImageGenTab.jsx` (internal `TabPills variant="pills"` sub-tabs, `useDrawerTab('mediaTab', …)`). The primitive is `Drawer.jsx`; the design record is `docs/plans/2026-07-01-drawer-ux-redesign.md`.
+## Large collections and incremental loading
+
+Follow [the collection-loading contract](../../docs/UX_DESIGN_GUIDE.md#large-collections-and-incremental-loading) for every potentially growing list (including Brain inbox/memory, agent history, and image history). Fetch only the active route's data, start with a bounded server page, and hydrate large details on demand. Use `usePagedCollection` and `InfiniteScrollFooter` for new infinite lists; do not copy observer/request/race logic into each feature. Client-side slicing of an unbounded response is not pagination. Stable collections (apps, providers, histories) load on demand and refresh through targeted websocket invalidations and reconnect recovery, not recurring whole-list polls. Any telemetry polling must be justified, bounded, visibility-gated, and limited to an open consumer. Keep query-wide search/counts and selection URLs correct; do not silently search only loaded rows. Existing exceptions are migrated incrementally with tracker coverage.
+
## Socket-driven UI
Socket lifecycle conventions (event-driven state swaps, single-subscriber resources, pending-request tracking, deferred-work guards) are in the `portos-socket-ui` skill — invoke it before wiring a new socket-driven view.
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 4685682261..c31b68f2ef 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -295,6 +295,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
// bare `#7640` against the run's tracker through the one resolver.
const linkifyIssues = useMemo(() => agentIssueLinkifier(agent), [agent]);
const [fullOutput, setFullOutput] = useState(null);
+ const [fullMetadata, setFullMetadata] = useState(null);
const [loadingOutput, setLoadingOutput] = useState(false);
// Pipeline stage output: track which stage tab is active and cached outputs per stage agentId
const [activeStageTab, setActiveStageTab] = useState(null);
@@ -414,7 +415,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
}
}, [agent.id]);
- useAutoRefetch(fetchStats, 5000, { enabled: !inactive && !remote, pollOnly: true });
+ useAutoRefetch(fetchStats, 5000, { enabled: expanded && !inactive && !remote, pollOnly: true });
const handlePause = async () => {
if (!onPause) return;
@@ -451,7 +452,10 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
setLoadingOutput(true);
api.getCosAgent(agent.id)
.then(data => {
- if (current()) setFullOutput(toTranscript(data));
+ if (current()) {
+ setFullOutput(toTranscript(data));
+ setFullMetadata(data.metadata || null);
+ }
})
.catch(() => {
// Fall back to agent's stored output
@@ -717,7 +721,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
</div>
{/* Actions - right side */}
<div className="flex items-center gap-2 shrink-0 ml-0 sm:ml-auto">
- {(output.length > 0 || inactive) && (
+ {(output.length > 0 || inactive || !remote) && (
<button
onClick={() => setExpanded(!expanded)}
className="text-gray-500 hover:text-white transition-colors text-xs whitespace-nowrap"
@@ -1060,7 +1064,13 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
<Sparkles size={10} aria-hidden="true" className="text-emerald-400" />
Task Summary
</div>
- {agent.metadata?.taskSummary && <MarkdownOutput content={agent.metadata.taskSummary} linkifyText={linkifyIssues} />}
+ {agent.metadata?.taskSummary && <MarkdownOutput content={fullMetadata?.taskSummary ?? agent.metadata.taskSummary} linkifyText={linkifyIssues} />}
+ {agent.metadata?.taskSummaryTruncated && !fullMetadata?.taskSummary && (
+ <p className="mt-1 text-xs text-port-text-muted">
+ Summary preview. {!remote && <button type="button" className="text-port-accent hover:underline" disabled={loadingOutput}
+ onClick={() => { setFullOutput(null); setExpanded(true); }}>Load full summary</button>}
+ </p>
+ )}
{agent.metadata?.malwareScan?.reportUrl && (
<a
href={api.normalizeBrainScanReportPath(agent.metadata.malwareScan.reportUrl)}
diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsx
index 86df3745f9..de1ac23cc1 100644
--- a/client/src/components/cos/tabs/AgentCard.test.jsx
+++ b/client/src/components/cos/tabs/AgentCard.test.jsx
@@ -173,19 +173,19 @@ describe('AgentCard runtime presentation', () => {
it('distinguishes a live process, a zombie, and missing process stats', async () => {
const runningAgent = { ...runningAt(30_000), pid: 4242 };
api.getCosAgentStats.mockResolvedValueOnce({ active: true, pid: 4242, state: 'running', cpu: 12.3, memoryMb: 64 });
- const { unmount } = render(<MemoryRouter><AgentCard agent={runningAgent} /></MemoryRouter>);
+ const { unmount } = render(<MemoryRouter><AgentCard agent={runningAgent} initiallyExpanded /></MemoryRouter>);
expect(await screen.findByText('12.3%')).toBeInTheDocument();
expect(screen.getByText('64MB')).toBeInTheDocument();
expect(screen.queryByText('ZOMBIE')).not.toBeInTheDocument();
unmount();
api.getCosAgentStats.mockResolvedValueOnce({ active: false, pid: 4242 });
- const zombie = render(<MemoryRouter><AgentCard agent={runningAgent} /></MemoryRouter>);
+ const zombie = render(<MemoryRouter><AgentCard agent={runningAgent} initiallyExpanded /></MemoryRouter>);
expect(await screen.findByText('ZOMBIE')).toBeInTheDocument();
zombie.unmount();
api.getCosAgentStats.mockResolvedValueOnce(null);
- render(<MemoryRouter><AgentCard agent={runningAgent} /></MemoryRouter>);
+ render(<MemoryRouter><AgentCard agent={runningAgent} initiallyExpanded /></MemoryRouter>);
await waitFor(() => expect(api.getCosAgentStats).toHaveBeenCalledTimes(3));
expect(screen.queryByText('ZOMBIE')).not.toBeInTheDocument();
expect(screen.queryByText(/PID 4242/)).not.toBeInTheDocument();
@@ -1074,3 +1074,23 @@ it('links a task-summary issue reference at the tracker the run was stamped with
expect(screen.getByRole('link', { name: '#7640' }))
.toHaveAttribute('href', 'https://github.com/atomantic/PortOS/issues/7640');
});
+
+
+it('loads process stats only after opening an active agent with no output', async () => {
+ api.getCosAgentStats.mockResolvedValue({ active: true, pid: 4242, state: 'running', cpu: 12.3, memoryMb: 64 });
+ render(<MemoryRouter><AgentCard agent={{ ...agent, status: 'running', completedAt: null, result: null, output: [] }} /></MemoryRouter>);
+ expect(api.getCosAgentStats).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole('button', { name: 'Show', exact: true }));
+ expect(await screen.findByText('12.3%')).toBeInTheDocument();
+});
+
+
+it('loads a clipped summary only when the reader asks for the detail', async () => {
+ api.getCosAgent.mockResolvedValue({ ...agent, metadata: { ...agent.metadata, taskSummary: 'The full summary with its conclusion.' }, output: [] });
+ render(<MemoryRouter><AgentCard agent={{ ...agent, metadata: { ...agent.metadata, taskSummary: 'The preview', taskSummaryTruncated: true } }} completed /></MemoryRouter>);
+ expect(screen.getByText('The preview')).toBeInTheDocument();
+ expect(api.getCosAgent).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole('button', { name: 'Load full summary' }));
+ expect(await screen.findByText('The full summary with its conclusion.')).toBeInTheDocument();
+ expect(screen.queryByText('Summary preview.')).not.toBeInTheDocument();
+});
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index bb910b8952..fdded3f015 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -1,12 +1,13 @@
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useParams, useSearchParams } from 'react-router';
-import { Trash2, Search, X, ChevronDown, MessageSquare } from 'lucide-react';
+import { Trash2, Search, X, MessageSquare } from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import AgentCard from './AgentCard';
import ResumeAgentModal from './ResumeAgentModal';
import RelaunchAgentModal from './RelaunchAgentModal';
-import BrailleSpinner from '../../BrailleSpinner';
+import InfiniteScrollFooter from '../../ui/InfiniteScrollFooter';
+import { usePagedCollection } from '../../../hooks/usePagedCollection';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import { agentResumeMessage } from '../../../lib/agentResumeOutcome';
import { isAgentFeedbackEligible } from '../../../lib/cosAgentFeedback';
@@ -34,7 +35,7 @@ const RESUME_MESSAGES = {
const needsAgentFeedback = isAgentFeedbackEligible;
-export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, providersLoaded, apps }) {
+export default function AgentsTab({ completedRevision = 0, agents, onRefresh, liveOutputs, providers, providersLoaded, apps }) {
const { agentId } = useParams();
const [focusedAgent, setFocusedAgent] = useState(null);
const [focusLoading, setFocusLoading] = useState(false);
@@ -53,16 +54,10 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
const [durations, setDurations] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
const [feedbackUpdates, setFeedbackUpdates] = useState({});
- const [pendingFeedbackAgents, setPendingFeedbackAgents] = useState([]);
+
const [pendingFeedbackCount, setPendingFeedbackCount] = useState(null);
const [confirmingClear, setConfirmingClear] = useState(false);
- // Date-based lazy loading for completed agents
- const [dateBuckets, setDateBuckets] = useState([]); // [{ date, count }, ...]
- const [loadedAgents, setLoadedAgents] = useState([]); // agents loaded so far
- const [loadedDates, setLoadedDates] = useState(new Set()); // dates already fetched
- const [loadingMore, setLoadingMore] = useState(false);
-
// Filter selection is URL-backed so actionable insights can open the exact
// review queue and the filtered state remains bookmarkable/shareable.
const feedbackFilter = searchParams.get('feedback') === 'needs-feedback' ? 'needs-feedback' : 'all';
@@ -73,6 +68,14 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
setSearchParams(next, { replace: true });
}, [searchParams, setSearchParams]);
+ const fetchCompletedPage = useCallback(({ cursor, signal }) => api.getCosCompletedAgents({
+ cursor, signal, limit: 25, feedback: feedbackFilter === 'needs-feedback', silent: true,
+ }), [feedbackFilter]);
+ const history = usePagedCollection(fetchCompletedPage);
+ useEffect(() => { if (completedRevision) history.refreshFirst(); }, [completedRevision, history.refreshFirst]);
+ const loadedAgents = history.items;
+ const refresh = useCallback(() => { history.reload(); onRefresh(); }, [history.reload, onRefresh]);
+
// Fetch duration estimates for progress indicators
useEffect(() => {
api.getCosLearningDurations().then(setDurations).catch(() => {});
@@ -84,76 +87,35 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
// queue and supplies a count even when those cards are not otherwise loaded.
useEffect(() => {
let cancelled = false;
- api.getCosPendingAgentFeedback({ silent: true })
+ api.getCosPendingAgentFeedback({ countOnly: true, silent: true })
.then((result) => {
if (cancelled) return;
- setPendingFeedbackAgents(Array.isArray(result?.agents) ? result.agents : []);
setPendingFeedbackCount(Number.isFinite(result?.count) ? result.count : null);
})
.catch(() => {});
return () => { cancelled = true; };
}, []);
- // Fetch date buckets on mount, with the most recent one hydrated in the SAME
- // response. The tab always wants that bucket but can't name its date until the
- // bucket list arrives, so asking separately costs a second serial round trip
- // before any archived card can paint — the whole visible delay on a slow link.
- useEffect(() => {
- let cancelled = false;
- (async () => {
- const result = await api.getCosAgentDates({ hydrate: true }).catch(() => ({ dates: [] }));
- if (cancelled) return;
- const dates = result.dates || [];
- setDateBuckets(dates);
- if (!result.latest) return;
- setLoadedAgents(result.latest.agents || []);
- setLoadedDates(new Set([result.latest.date]));
- })();
- return () => { cancelled = true; };
- }, []);
-
- const handleLoadMore = useCallback(async () => {
- // Find next unloaded date
- const nextDate = dateBuckets.find(d => !loadedDates.has(d.date));
- if (!nextDate) return;
-
- setLoadingMore(true);
- const agents = await api.getCosAgentsByDate(nextDate.date).catch(() => []);
- setLoadedAgents(prev => [...prev, ...agents]);
- setLoadedDates(prev => new Set([...prev, nextDate.date]));
- setLoadingMore(false);
- }, [dateBuckets, loadedDates]);
-
const handleKill = async (agentId) => {
const result = await api.killCosAgent(agentId, { silent: true }).catch(err => { toast.error(err.message); return null; });
if (!result) return;
toast.success('Agent force killed');
- onRefresh();
+ refresh();
};
const handlePause = async (agentId) => {
const result = await api.pauseCosAgent(agentId, 'Paused from CoS agent list', { silent: true }).catch(err => { toast.error(err.message); return null; });
if (!result) return;
toast.success('Agent paused');
- onRefresh();
+ refresh();
};
const handleDelete = useCallback(async (agentId) => {
const result = await api.deleteCosAgent(agentId, { silent: true }).catch(err => { toast.error(err.message); return null; });
if (!result) return;
- setLoadedAgents(prev => {
- const deleted = prev.find(a => a.id === agentId);
- if (deleted?.completedAt) {
- const dateStr = deleted.completedAt.slice(0, 10);
- setDateBuckets(buckets => buckets.map(d =>
- d.date === dateStr ? { ...d, count: Math.max(0, d.count - 1) } : d
- ).filter(d => d.count > 0));
- }
- return prev.filter(a => a.id !== agentId);
- });
toast.success('Agent removed');
- onRefresh();
- }, [onRefresh]);
+ refresh();
+ }, [refresh]);
// ResumeAgentModal builds a NEW task prompt out of `metadata.taskDescription`,
// and the listing carries a bounded copy of it (server/lib/cosAgentListProjection.js).
@@ -177,21 +139,10 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
const handleFeedbackChange = useCallback((updatedAgent) => {
if (updatedAgent?.id && updatedAgent.feedback) {
setFeedbackUpdates(prev => ({ ...prev, [updatedAgent.id]: updatedAgent.feedback }));
- setLoadedAgents(prev => prev.map(agent =>
- agent.id === updatedAgent.id ? { ...agent, feedback: updatedAgent.feedback } : agent
- ));
}
- setPendingFeedbackAgents(prev => {
- const wasPending = prev.some(agent => agent.id === updatedAgent?.id);
- if (wasPending && !needsAgentFeedback(updatedAgent)) {
- setPendingFeedbackCount(count => (typeof count === 'number' ? Math.max(0, count - 1) : count));
- }
- return needsAgentFeedback(updatedAgent)
- ? prev.map(agent => agent.id === updatedAgent.id ? updatedAgent : agent)
- : prev.filter(agent => agent.id !== updatedAgent?.id);
- });
- onRefresh();
- }, [onRefresh]);
+ if (!needsAgentFeedback(updatedAgent)) setPendingFeedbackCount(count => count == null ? count : Math.max(0, count - 1));
+ refresh();
+ }, [refresh]);
// A PAUSED agent resumes IN PLACE (see `resumeAgent` in agentManagement.js):
// the server requeues that agent's own task on the worktree its run left behind.
@@ -219,18 +170,15 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
toast.success(agentResumeMessage(result, RESUME_MESSAGES,
result.created === false ? 'Resumed — nothing new was queued' : `Created ${type === 'internal' ? 'system ' : ''}resume task`));
setResumingAgent(null);
- onRefresh();
+ refresh();
};
const handleClearCompleted = async () => {
setConfirmingClear(false);
const result = await api.clearCompletedCosAgents({ silent: true }).catch(err => { toast.error(err.message); return null; });
if (!result) return;
- setLoadedAgents([]);
- setLoadedDates(new Set());
- setDateBuckets([]);
toast.success('Cleared completed agents');
- onRefresh();
+ refresh();
};
// Running agents come from props (real-time via parent socket updates)
@@ -252,20 +200,11 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
for (const agent of recentCompleted) addAgent(agent);
// Then disk-loaded agents
for (const agent of loadedAgents) addAgent(agent);
- // Finally the durable pending index, which may contain an older archived
- // run that has not been loaded through the date-bucket pager yet.
- for (const agent of pendingFeedbackAgents) addAgent(agent);
+
return merged.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
- }, [recentCompleted, loadedAgents, pendingFeedbackAgents, feedbackUpdates]);
+ }, [recentCompleted, loadedAgents, feedbackUpdates]);
- const totalCount = useMemo(() => {
- const indexTotal = dateBuckets.reduce((sum, d) => sum + d.count, 0);
- // Add any recent completed agents from state that may not yet be indexed
- const stateOnlyCount = recentCompleted.filter(a =>
- !loadedAgents.some(la => la.id === a.id)
- ).length;
- return indexTotal + stateOnlyCount;
- }, [dateBuckets, recentCompleted, loadedAgents]);
+ const totalCount = history.total ?? allCompleted.length;
// Search runs over what the listing carries. `metadata.taskDescription` is
// bounded at AGENT_LIST_DESCRIPTION_CHARS server-side, which leaves over 90% of
@@ -294,10 +233,6 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
: Math.max(pendingFeedbackCount, locallyVisibleNeedsFeedback);
const selectedAgent = agents.find(agent => agent.id === agentId) || (focusedAgent?.id === agentId ? focusedAgent : null);
- const hasMoreDates = dateBuckets.some(d => !loadedDates.has(d.date));
- const remainingCount = dateBuckets
- .filter(d => !loadedDates.has(d.date))
- .reduce((sum, d) => sum + d.count, 0);
return (
<div className="space-y-6">
@@ -363,13 +298,13 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
)}
{/* Completed Agents */}
- {(totalCount > 0 || recentCompleted.length > 0 || pendingFeedbackAgents.length > 0) && (
+ {(totalCount > 0 || !history.loaded || history.error || history.hasMore || allCompleted.length > 0 || feedbackFilter !== 'all' || pendingFeedbackCount > 0) && (
<div>
<div className="flex items-center justify-between mb-3">
<h3 className="text-lg font-semibold text-white">
Completed Agents
<span className="text-sm text-gray-500 font-normal ml-2">
- ({formatCount(totalCount)} total)
+ ({formatCount(totalCount)} {history.total == null ? 'loaded' : 'total'})
</span>
</h3>
<button
@@ -384,9 +319,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
{confirmingClear && (
<InlineConfirmRow
className="mb-3"
- question={totalCount > 0
- ? `Clear ALL completed agents? This removes ${formatCount(totalCount)} agent record${totalCount === 1 ? '' : 's'} and cannot be undone.`
- : 'Clear ALL completed agents? This cannot be undone.'}
+ question="Clear ALL completed agents, including records outside the current filter and unloaded pages? This cannot be undone."
confirmText="Clear all"
confirmTitle="Confirm clear all completed agents"
cancelTitle="Cancel clear"
@@ -410,7 +343,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
<button
type="button"
onClick={() => setFeedbackFilter('needs-feedback')}
- disabled={needsFeedbackCount === 0 && feedbackFilter !== 'needs-feedback'}
+
aria-label={`Needs feedback: ${needsFeedbackCount}`}
aria-pressed={feedbackFilter === 'needs-feedback'}
className={`flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] rounded-lg text-xs transition-colors disabled:opacity-50 ${
@@ -464,29 +397,11 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
{feedbackFilter === 'needs-feedback' && !searchQuery
? 'All loaded agent runs have feedback.'
: `No loaded agents match "${searchQuery}"`}
- {hasMoreDates && (
- <div className="mt-2 text-xs">
- {formatCount(remainingCount)} agents in older dates not yet loaded
- </div>
- )}
+
</div>
)}
- {!searchQuery && hasMoreDates && (
- <button
- onClick={handleLoadMore}
- disabled={loadingMore}
- className="col-span-full w-full py-2 text-sm text-port-accent hover:text-white bg-port-card border border-port-border rounded-lg transition-colors flex items-center justify-center gap-1 disabled:opacity-50"
- >
- {loadingMore ? (
- <BrailleSpinner text="Loading" />
- ) : (
- <>
- <ChevronDown size={14} />
- Load older agents ({formatCount(remainingCount)} remaining)
- </>
- )}
- </button>
- )}
+ <InfiniteScrollFooter hasMore={history.hasMore} loading={history.loading} error={history.error}
+ onLoadMore={history.loadMore} autoLoad={!searchQuery} label="Load older agents" />
</div>
</div>
)}
@@ -498,7 +413,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
providers={providers}
providersLoaded={providersLoaded}
apps={apps}
- onDone={onRefresh}
+ onDone={refresh}
onClose={() => setRelaunchingAgent(null)}
/>
)}
diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsx
index a8da218dcc..9e8ff52b28 100644
--- a/client/src/components/cos/tabs/AgentsTab.test.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx
@@ -7,8 +7,7 @@ import { MemoryRouter, Routes, Route } from 'react-router';
vi.mock('../../../services/api', () => ({
getCosLearningDurations: vi.fn(),
getCosAgent: vi.fn(),
- getCosAgentDates: vi.fn(),
- getCosAgentsByDate: vi.fn(),
+ getCosCompletedAgents: vi.fn(),
getCosPendingAgentFeedback: vi.fn(),
hydrateCosAgentDescription: vi.fn(async (agent) => agent),
clearCompletedCosAgents: vi.fn(),
@@ -75,7 +74,7 @@ vi.mock('./RelaunchAgentModal', () => ({
</button>
),
}));
-vi.mock('../../ui/InlineConfirmRow', () => ({ default: () => null }));
+vi.mock('../../ui/InlineConfirmRow', () => ({ default: ({ question }) => <p>{question}</p> }));
import * as api from '../../../services/api';
import toast from '../../ui/Toast';
@@ -106,8 +105,7 @@ const renderTab = (agents, onRefresh = vi.fn(), initialEntry = '/cos/agents') =>
beforeEach(() => {
vi.clearAllMocks();
api.getCosLearningDurations.mockResolvedValue({});
- api.getCosAgentDates.mockResolvedValue({ dates: [], latest: null });
- api.getCosAgentsByDate.mockResolvedValue([]);
+ api.getCosCompletedAgents.mockResolvedValue({ items: [], total: 0, nextCursor: null });
api.getCosPendingAgentFeedback.mockResolvedValue({ agents: [], count: null });
api.hydrateCosAgentDescription.mockImplementation(async (agent) => agent);
});
@@ -280,7 +278,8 @@ describe('AgentsTab feedback review queue', () => {
const archived = completedAgent('agent-archived', 'An older pending run');
api.getCosPendingAgentFeedback.mockResolvedValue({ agents: [archived], count: 1 });
- renderTab([]);
+ api.getCosCompletedAgents.mockResolvedValue({ items: [archived], total: 1, nextCursor: null });
+ renderTab([], vi.fn(), '/cos/agents?feedback=needs-feedback');
await waitFor(() => expect(screen.getByRole('button', { name: 'Needs feedback: 1' })).toBeInTheDocument());
expect(screen.getByText('An older pending run')).toBeInTheDocument();
});
@@ -335,10 +334,7 @@ describe('AgentsTab feedback review queue', () => {
it('removes an archived run from the queue immediately after feedback', async () => {
const user = userEvent.setup();
const onRefresh = vi.fn();
- api.getCosAgentDates.mockResolvedValue({
- dates: [{ date: '2026-07-13', count: 1 }],
- latest: { date: '2026-07-13', agents: [completedAgent('archived', 'Archived task')] },
- });
+ api.getCosCompletedAgents.mockResolvedValue({ items: [completedAgent('archived', 'Archived task')], total: 1, nextCursor: null });
renderTab([], onRefresh);
await act(async () => {});
@@ -363,37 +359,22 @@ it('opens an agent deep link even after it has left the recent agent list', asyn
expect(api.getCosAgent).toHaveBeenCalledWith('archived-example', { silent: true });
});
-// The archive list and its newest bucket arrive together: the tab cannot name the
-// date it needs until the bucket list answers, so asking separately costs a
-// second serial round trip before any archived card can paint.
-describe('AgentsTab archive loading', () => {
- it('paints the newest bucket from the bucket-list response, with no follow-up request', async () => {
- api.getCosAgentDates.mockResolvedValue({
- dates: [{ date: '2026-07-13', count: 1 }, { date: '2026-07-12', count: 4 }],
- latest: { date: '2026-07-13', agents: [completedAgent('archived', 'Archived task')] },
- });
-
- renderTab([]);
-
- await screen.findByText('Archived task');
- expect(api.getCosAgentDates).toHaveBeenCalledWith({ hydrate: true });
- expect(api.getCosAgentsByDate).not.toHaveBeenCalled();
- });
-
- it('loads an older bucket on demand, one request per date', async () => {
+describe('AgentsTab bounded archive loading', () => {
+ it('loads a bounded first page and preserves rows and cursor after a failed next page', async () => {
const user = userEvent.setup();
- api.getCosAgentDates.mockResolvedValue({
- dates: [{ date: '2026-07-13', count: 1 }, { date: '2026-07-12', count: 1 }],
- latest: { date: '2026-07-13', agents: [completedAgent('archived', 'Archived task')] },
- });
- api.getCosAgentsByDate.mockResolvedValue([completedAgent('older', 'Older task')]);
-
+ api.getCosCompletedAgents.mockResolvedValueOnce({ items: [completedAgent('archived', 'Archived task')], total: 2, nextCursor: 'next' })
+ .mockRejectedValueOnce(new Error('Temporary failure'))
+ .mockResolvedValueOnce({ items: [completedAgent('older', 'Older task')], total: 2, nextCursor: null });
renderTab([]);
await screen.findByText('Archived task');
- await user.click(screen.getByRole('button', { name: /Load/ }));
-
+ expect(api.getCosCompletedAgents).toHaveBeenCalledWith(expect.objectContaining({ limit: 25, cursor: null }));
+ await user.click(screen.getByRole('button', { name: 'Load older agents' }));
+ await screen.findByRole('alert');
+ expect(screen.getByText('Archived task')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Retry loading' }));
await screen.findByText('Older task');
- expect(api.getCosAgentsByDate).toHaveBeenCalledWith('2026-07-12');
+ expect(api.getCosCompletedAgents.mock.calls.slice(1).map(([args]) => args.cursor)).toEqual(['next', 'next']);
+ expect(screen.getByText('All results loaded')).toBeInTheDocument();
});
});
@@ -426,3 +407,13 @@ describe('AgentsTab hydrates a clipped description before reusing it', () => {
expect(api.resumeCosAgent.mock.calls[0][1].description).toBe('[Resume] Half-finished work, in full');
});
});
+
+
+it('makes the clear scope explicit when the feedback filter hides completed records', async () => {
+ api.getCosCompletedAgents.mockResolvedValue({ items: [completedAgent('filtered', 'Pending feedback')], total: 1, nextCursor: null });
+ renderTab([], vi.fn(), '/cos/agents?feedback=needs-feedback');
+ await screen.findByText('Pending feedback');
+ await userEvent.click(screen.getByRole('button', { name: 'Clear all completed agents' }));
+ expect(screen.getByText(/including records outside the current filter and unloaded pages/)).toBeInTheDocument();
+ expect(screen.queryByText(/removes 1 agent record/)).not.toBeInTheDocument();
+});
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index fdd1fd94a3..a62a9c778c 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -1,3 +1,5 @@
+import { usePagedCollection } from '../../../hooks/usePagedCollection';
+import InfiniteScrollFooter from '../../ui/InfiniteScrollFooter';
import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import { Play, ChevronDown, ChevronRight } from 'lucide-react';
@@ -40,12 +42,26 @@ function SectionGlyph({ status }) {
return <MicroGlyph variant={spec.variant} state={spec.state} animated={spec.animated} size={13} />;
}
-export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefresh, onTaskAdded, onTaskUnblocked, providers, providersLoaded, apps }) {
+export default function TasksTab({ completedRevision = 0, tasks, agents = [], liveOutputs = {}, onRefresh, onTaskAdded, onTaskUnblocked, providers, providersLoaded, apps }) {
const [searchParams] = useSearchParams();
const [userTasksLocal, setUserTasksLocal] = useState([]);
const [durations, setDurations] = useState(null);
const [showCompletedUserTasks, setShowCompletedUserTasks] = useState(false);
const [showCompletedSystemTasks, setShowCompletedSystemTasks] = useState(false);
+ const fetchUserHistory = useCallback(({ cursor, signal }) => api.getCosTasks({ view: 'completed', source: 'user', limit: 25, cursor, signal, silent: true }), []);
+ const fetchSystemHistory = useCallback(({ cursor, signal }) => api.getCosTasks({ view: 'completed', source: 'internal', limit: 25, cursor, signal, silent: true }), []);
+ const userHistory = usePagedCollection(fetchUserHistory, { enabled: showCompletedUserTasks && tasks.user?.completedCount != null });
+ const systemHistory = usePagedCollection(fetchSystemHistory, { enabled: showCompletedSystemTasks && tasks.cos?.completedCount != null });
+ const refreshHistory = () => { userHistory.reload(); systemHistory.reload(); onRefresh(); };
+ const historyVersion = useRef({ user: tasks.user?.completedCount, internal: tasks.cos?.completedCount, revision: completedRevision });
+ useEffect(() => {
+ const previous = historyVersion.current;
+ const revisionChanged = previous.revision !== completedRevision;
+ if (revisionChanged || previous.user !== tasks.user?.completedCount) userHistory.reload();
+ if (revisionChanged || previous.internal !== tasks.cos?.completedCount) systemHistory.reload();
+ historyVersion.current = { user: tasks.user?.completedCount, internal: tasks.cos?.completedCount, revision: completedRevision };
+ }, [completedRevision, tasks.user?.completedCount, tasks.cos?.completedCount, userHistory.reload, systemHistory.reload]);
+
// Fetched once for the whole list (#4520) — every row renders its instance pin
// from this, so a long backlog never issues one request per task.
const { instances: assignableInstances } = useAssignableInstances();
@@ -58,8 +74,8 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
}, []);
// Memoize task arrays to prevent unnecessary re-renders
- const userTasks = useMemo(() => tasks.user?.tasks || [], [tasks.user?.tasks]);
- const cosTasks = useMemo(() => tasks.cos?.tasks || [], [tasks.cos?.tasks]);
+ const userTasks = useMemo(() => [...new Map([...userHistory.items, ...(tasks.user?.tasks || [])].map(task => [task.id, task])).values()], [tasks.user?.tasks, userHistory.items]);
+ const cosTasks = useMemo(() => [...new Map([...systemHistory.items, ...(tasks.cos?.tasks || [])].map(task => [task.id, task])).values()], [tasks.cos?.tasks, systemHistory.items]);
const selectedTaskId = searchParams.get('task');
const requestedSource = searchParams.get('source');
const selectedTaskSource = useMemo(() => {
@@ -240,7 +256,7 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
<TaskAddForm queueFirst providers={providers} providersLoaded={providersLoaded} apps={apps} onTaskAdded={handleTaskAdded} />
{/* User Tasks Sections */}
- {pendingUserTasksLocal.length === 0 && activeUserTasksLocal.length === 0 && blockedUserTasksLocal.length === 0 && completedUserTasksLocal.length === 0 ? (
+ {pendingUserTasksLocal.length === 0 && activeUserTasksLocal.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 or edit TASKS.md directly.
@@ -312,7 +328,7 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
)}
{/* Completed Section - Collapsible */}
- {completedUserTasksLocal.length > 0 && (
+ {(tasks.user?.completedCount ?? completedUserTasksLocal.length) > 0 && (
<div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
<button
onClick={() => setShowCompletedUserTasks(!showCompletedUserTasks)}
@@ -322,14 +338,15 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
<span className="text-sm font-medium text-port-success flex items-center gap-2">
{showCompletedUserTasks ? <ChevronDown size={14} aria-hidden="true" /> : <ChevronRight size={14} aria-hidden="true" />}
<SectionGlyph status="completed" />
- Completed ({completedUserTasksLocal.length})
+ Completed ({tasks.user?.completedCount ?? completedUserTasksLocal.length})
</span>
</button>
{showCompletedUserTasks && (
<div className="p-2 space-y-1.5">
{completedUserTasksLocal.map(task => (
- <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} providersLoaded={providersLoaded} durations={durations} apps={apps} instances={assignableInstances} />
+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={refreshHistory} onTaskUnblocked={onTaskUnblocked} providers={providers} providersLoaded={providersLoaded} durations={durations} apps={apps} instances={assignableInstances} />
))}
+ {tasks.user?.completedCount != null && <InfiniteScrollFooter hasMore={userHistory.hasMore} loading={userHistory.loading} error={userHistory.error} onLoadMore={userHistory.loadMore} />}
</div>
)}
</div>
@@ -343,7 +360,7 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
<h3 className="text-lg font-semibold text-white mb-3">System Tasks (COS-TASKS.md)</h3>
{/* System Tasks Sections */}
- {pendingSystemTasks.length === 0 && activeSystemTasks.length === 0 && blockedSystemTasks.length === 0 && completedSystemTasks.length === 0 ? (
+ {pendingSystemTasks.length === 0 && activeSystemTasks.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.
@@ -402,7 +419,7 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
)}
{/* Completed Section - Collapsible */}
- {completedSystemTasks.length > 0 && (
+ {(tasks.cos?.completedCount ?? completedSystemTasks.length) > 0 && (
<div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
<button
onClick={() => setShowCompletedSystemTasks(!showCompletedSystemTasks)}
@@ -412,14 +429,15 @@ export default function TasksTab({ tasks, agents = [], liveOutputs = {}, onRefre
<span className="text-sm font-medium text-port-success flex items-center gap-2">
{showCompletedSystemTasks ? <ChevronDown size={14} aria-hidden="true" /> : <ChevronRight size={14} aria-hidden="true" />}
<SectionGlyph status="completed" />
- Completed ({completedSystemTasks.length})
+ Completed ({tasks.cos?.completedCount ?? completedSystemTasks.length})
</span>
</button>
{showCompletedSystemTasks && (
<div className="p-2 space-y-1.5">
{completedSystemTasks.map(task => (
- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} providersLoaded={providersLoaded} durations={durations} apps={apps} instances={assignableInstances} />
+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={refreshHistory} onTaskUnblocked={onTaskUnblocked} providers={providers} providersLoaded={providersLoaded} durations={durations} apps={apps} instances={assignableInstances} />
))}
+ {tasks.cos?.completedCount != null && <InfiniteScrollFooter hasMore={systemHistory.hasMore} loading={systemHistory.loading} error={systemHistory.error} onLoadMore={systemHistory.loadMore} />}
</div>
)}
</div>
diff --git a/client/src/components/cos/tabs/TasksTab.test.jsx b/client/src/components/cos/tabs/TasksTab.test.jsx
index 186c1e4904..50f7f19afd 100644
--- a/client/src/components/cos/tabs/TasksTab.test.jsx
+++ b/client/src/components/cos/tabs/TasksTab.test.jsx
@@ -7,6 +7,7 @@ import { MemoryRouter } from 'react-router';
vi.mock('../../../hooks/useAssignableInstances', () => ({ default: () => ({ instances: [], isFederated: false }) }));
const api = vi.hoisted(() => ({
forceCosEvaluate: vi.fn(),
+ getCosTasks: vi.fn(),
getCosLearningDurations: vi.fn(),
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
@@ -155,3 +156,24 @@ it('focuses a deep link when its task arrives, then preserves user focus on refr
await waitFor(() => expect(draft).toHaveFocus());
expect(scroll).not.toHaveBeenCalled();
});
+
+
+it('refreshes expanded history on completed changes without fetching it for queue heartbeats', async () => {
+ const completed = id => ({ id, description: `Completed ${id}`, status: 'completed', metadata: {} });
+ api.getCosTasks.mockResolvedValueOnce({ items: [completed('old')], total: 1, nextCursor: null })
+ .mockResolvedValueOnce({ items: [completed('new'), completed('old')], total: 2, nextCursor: null })
+ .mockResolvedValueOnce({ items: [completed('replacement')], total: 1, nextCursor: null });
+ const view = (count, revision = 0) => <MemoryRouter><TasksTab tasks={{ user: { tasks: [], completedCount: count }, cos: { tasks: [], completedCount: 0 } }} completedRevision={revision} onRefresh={vi.fn()} providers={[]} apps={[]} /></MemoryRouter>;
+ const { rerender } = render(view(1));
+ expect(api.getCosTasks).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Completed (1)' }));
+ await screen.findByText('Completed old');
+ rerender(view(1));
+ expect(api.getCosTasks).toHaveBeenCalledTimes(1);
+ rerender(view(2));
+ await screen.findByText('Completed new');
+ rerender(view(1, 1));
+ await screen.findByText('Completed replacement');
+ expect(screen.queryByText('Completed old')).not.toBeInTheDocument();
+ expect(api.getCosTasks).toHaveBeenCalledTimes(3);
+});
diff --git a/client/src/components/ui/InfiniteScrollFooter.jsx b/client/src/components/ui/InfiniteScrollFooter.jsx
new file mode 100644
index 0000000000..f79325be18
--- /dev/null
+++ b/client/src/components/ui/InfiniteScrollFooter.jsx
@@ -0,0 +1,24 @@
+import { useEffect, useRef } from 'react';
+import BrailleSpinner from '../BrailleSpinner';
+
+// The observer respects ancestor scroll containers. A real button remains for
+// keyboard users, unavailable observers, and retries (never auto-retry errors).
+export default function InfiniteScrollFooter({ hasMore, loading, error, onLoadMore, autoLoad = true, label = 'Load more', endLabel = 'All results loaded' }) {
+ const sentinel = useRef(null);
+ useEffect(() => {
+ if (!autoLoad || !hasMore || loading || error || typeof IntersectionObserver === 'undefined') return;
+ const observer = new IntersectionObserver(entries => {
+ if (entries.some(entry => entry.isIntersecting)) onLoadMore();
+ }, { rootMargin: '200px' });
+ if (sentinel.current) observer.observe(sentinel.current);
+ return () => observer.disconnect();
+ }, [autoLoad, hasMore, loading, error, onLoadMore]);
+ return <div ref={sentinel} className="col-span-full py-3 text-center">
+ {error && <p role="alert" className="mb-2 text-sm text-port-error">{(typeof error === 'string' ? error : error.message) || 'Unable to load results'}</p>}
+ {loading ? <div role="status"><BrailleSpinner text="Loading" /></div>
+ : hasMore || error ? <button type="button" onClick={onLoadMore}
+ className="min-h-[44px] rounded-lg border border-port-border px-4 py-2 text-sm text-port-accent hover:text-port-text">
+ {error ? 'Retry loading' : label}
+ </button> : <p role="status" className="text-xs text-port-text-muted">{endLabel}</p>}
+ </div>;
+}
diff --git a/client/src/components/ui/InfiniteScrollFooter.test.jsx b/client/src/components/ui/InfiniteScrollFooter.test.jsx
new file mode 100644
index 0000000000..6e5289e12c
--- /dev/null
+++ b/client/src/components/ui/InfiniteScrollFooter.test.jsx
@@ -0,0 +1,72 @@
+import { useCallback } from 'react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { usePagedCollection } from '../../hooks/usePagedCollection';
+import InfiniteScrollFooter from './InfiniteScrollFooter';
+
+function Collection({ query, fetchPage }) {
+ const readPage = useCallback(args => fetchPage(query, args), [query, fetchPage]);
+ const page = usePagedCollection(readPage);
+ return <><button onClick={page.refreshFirst}>Refresh</button><ul>{page.items.map(item => <li key={item.id}>{item.id}</li>)}</ul>
+ <InfiniteScrollFooter {...page} onLoadMore={page.loadMore} /></>;
+}
+afterEach(() => vi.unstubAllGlobals());
+
+it('coalesces intersections, rejects obsolete query results, and retries the same cursor', async () => {
+ let intersect;
+ vi.stubGlobal('IntersectionObserver', class {
+ constructor(callback) { intersect = callback; }
+ observe() {}
+ disconnect() {}
+ });
+ let resolveOld, resolveNext;
+ const fetchPage = vi.fn()
+ .mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }))
+ .mockResolvedValueOnce({ items: [{ id: 'current' }], nextCursor: 'page-two' })
+ .mockRejectedValueOnce(new Error('Offline'))
+ .mockImplementationOnce(() => new Promise(resolve => { resolveNext = resolve; }));
+ const view = render(<Collection query="old" fetchPage={fetchPage} />);
+ view.rerender(<Collection query="current" fetchPage={fetchPage} />);
+ await screen.findByText('current');
+ await act(async () => resolveOld({ items: [{ id: 'obsolete' }], nextCursor: null }));
+ expect(screen.queryByText('obsolete')).toBeNull();
+ await act(async () => { intersect([{ isIntersecting: true }]); intersect([{ isIntersecting: true }]); });
+ expect(fetchPage).toHaveBeenCalledTimes(3);
+ expect(await screen.findByRole('alert')).toHaveTextContent('Offline');
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
+ expect(fetchPage.mock.calls.at(-1)[1].cursor).toBe('page-two');
+ await act(async () => resolveNext({ items: [{ id: 'current' }, { id: 'older' }], nextCursor: null }));
+ await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(2));
+ expect(screen.getByRole('status')).toHaveTextContent('All results loaded');
+});
+
+
+it('backfills the gap after reconnect when new records fill an entire first page', async () => {
+ const fetchPage = vi.fn()
+ .mockResolvedValueOnce({ items: [{ id: 'old' }], nextCursor: 'older' })
+ .mockResolvedValueOnce({ items: [{ id: 'new' }], nextCursor: 'gap' })
+ .mockResolvedValueOnce({ items: [{ id: 'between' }, { id: 'old' }], nextCursor: 'older' });
+ render(<Collection query="history" fetchPage={fetchPage} />);
+ await screen.findByText('old');
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
+ await screen.findByText('new');
+ fireEvent.click(screen.getByRole('button', { name: 'Load more' }));
+ await screen.findByText('between');
+ expect(fetchPage.mock.calls.at(-1)[1].cursor).toBe('gap');
+ expect(screen.getAllByText('old')).toHaveLength(1);
+});
+
+
+it('retries a failed head refresh rather than skipping to an older page', async () => {
+ const fetchPage = vi.fn()
+ .mockResolvedValueOnce({ items: [{ id: 'old' }], nextCursor: 'older' })
+ .mockRejectedValueOnce(new Error('Refresh failed'))
+ .mockResolvedValueOnce({ items: [{ id: 'new' }, { id: 'old' }], nextCursor: 'older' });
+ render(<Collection query="history" fetchPage={fetchPage} />);
+ await screen.findByText('old');
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
+ await screen.findByRole('alert');
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
+ await screen.findByText('new');
+ expect(fetchPage.mock.calls.at(-1)[1].cursor).toBeNull();
+});
diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.md
index 28f5343aa9..e775eb8fb3 100644
--- a/client/src/components/ui/README.md
+++ b/client/src/components/ui/README.md
@@ -22,6 +22,7 @@ accessibility). Feature-specific components live under their own feature directo
| `FormField` | Accessible config-field wrapper — generates an id and wires `<label htmlFor>` to the input; `compact` preserves dense editor-label styling. |
| `HunkDiff` | Hunked side-by-side diff for long texts, with unchanged runs collapsed. |
| `ImageThumb` | List-card thumbnail with an icon fallback when the ref is missing or 404s. |
+| `InfiniteScrollFooter` | Shared scroll sentinel with loading, retry, end state and accessible manual Load more; pair with `usePagedCollection`. |
| `InfoTooltip` | Focusable info/help tooltip — hover, keyboard focus, or tap; Esc to dismiss. |
| `InlineConfirmRow` | Inline "question + confirm + cancel" row — PortOS's preferred alternative to `window.confirm`. |
| `InlineDiff` | Stacked word-level diff — old row (red removals) over new row (green additions). |
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 56909e9ae4..4b05c81f35 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -254,3 +254,4 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useGalleryPreviewResolver` | Builds the stable `resolveItem` callback that resolves a `?preview=` param the host's own items list does not contain, by looking the record up in the gallery and normalizing it. `usePreviewRoute` uses it as its DEFAULT. | Call it directly only to narrow the lookup — `collectionId` scopes it to one collection. |
| `useImageVariants` | Fetches the original-vs-cleaned variant set for the one open image (`GET /api/image-gen/:filename/variants`), normalized; reuses the held group across toggle clicks and aborts a superseded lookup. `null` while unfetched or failed, `[]` when the image is not indexed. | `MediaPreview` calls it for every image preview; neither a page-owned ref list nor a 60-row gallery window is a complete source of variant lineage. |
| `useGalleryPage` | Bounded image or mixed-media browsing with debounced server search, scopes, totals, stale-response cancellation and retryable next pages. | Gallery grids and pickers; `getGalleryImages` hydrates known references separately. |
+| `usePagedCollection` | `usePagedCollection(fetchPage, { enabled })` — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry and reset. | Growing cursor-based collections; pair with `InfiniteScrollFooter`. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 4acdf3e022..1471df6e2d 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -233,3 +233,5 @@ export { default as useEidoverseFrame } from './useEidoverseFrame.js';
export * from './useGalleryPage.js';
export * from './useAccountSyncStatus.js';
export * from './useActionQueue.js';
+
+export * from './usePagedCollection.js';
diff --git a/client/src/hooks/usePagedCollection.js b/client/src/hooks/usePagedCollection.js
new file mode 100644
index 0000000000..9b3bda46a4
--- /dev/null
+++ b/client/src/hooks/usePagedCollection.js
@@ -0,0 +1,68 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+const emptyPage = () => ({ items: [], total: null, nextCursor: null, loaded: false, loading: false, error: null });
+
+// fetchPage({ cursor, signal }) returns { items, total?, nextCursor }.
+// Its identity is the query key: memoize it over the collection's filters.
+export function usePagedCollection(fetchPage, { enabled = true } = {}) {
+ const [page, setPage] = useState(emptyPage);
+ const state = useRef(page);
+ const generation = useRef(0);
+ const pending = useRef(null);
+ const refreshQueued = useRef(false);
+ const retryRefresh = useRef(false);
+ const commit = useCallback(next => { state.current = next; setPage(next); }, []);
+
+ const read = useCallback(async function readPage(refresh = false) {
+ if (!enabled || (!refresh && state.current.loaded && state.current.nextCursor == null)) return;
+ if (pending.current) { if (refresh) refreshQueued.current = true; return; }
+ const epoch = generation.current;
+ const controller = new AbortController();
+ pending.current = controller;
+ commit({ ...state.current, loading: true, error: null });
+ try {
+ const result = await fetchPage({ cursor: refresh ? null : state.current.nextCursor, signal: controller.signal });
+ if (generation.current !== epoch) return;
+ const existingIds = new Set(state.current.items.map(item => item.id));
+ const overlaps = result.items.some(item => existingIds.has(item.id));
+ // Preserve encounter order; domains with a chronological display sort
+ // their records after merging, including gaps backfilled after reconnect.
+ const items = new Map((refresh ? result.items : state.current.items).map(item => [item.id, item]));
+ for (const item of refresh ? state.current.items : result.items) if (!refresh || !items.has(item.id)) items.set(item.id, item);
+ commit({ items: [...items.values()], total: result.total ?? state.current.total,
+ nextCursor: refresh && overlaps ? state.current.nextCursor : result.nextCursor ?? null, loaded: true, loading: false, error: null });
+ } catch (error) {
+ if (generation.current === epoch) {
+ retryRefresh.current = refresh;
+ commit({ ...state.current, loading: false, error });
+ }
+ } finally {
+ if (pending.current === controller) {
+ pending.current = null;
+ if (refreshQueued.current && generation.current === epoch) {
+ refreshQueued.current = false;
+ readPage(true);
+ }
+ }
+ }
+ }, [enabled, fetchPage, commit]);
+
+ const loadMore = useCallback(() => read(Boolean(state.current.error && retryRefresh.current)), [read]);
+ const refreshFirst = useCallback(() => read(true), [read]);
+
+ const reset = useCallback(() => {
+ generation.current += 1;
+ refreshQueued.current = false;
+ retryRefresh.current = false;
+ pending.current?.abort();
+ pending.current = null;
+ commit(emptyPage());
+ }, [commit]);
+ const reload = useCallback(() => { reset(); return loadMore(); }, [reset, loadMore]);
+ useEffect(() => {
+ reload();
+ return () => { generation.current += 1; refreshQueued.current = false; pending.current?.abort(); pending.current = null; };
+ }, [reload]);
+
+ return { ...page, hasMore: !page.loaded || page.nextCursor != null, loadMore, reload, refreshFirst };
+}
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 852c8ef447..f19eebaeb1 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -1,8 +1,7 @@
import { useState, useEffect, useCallback, useMemo, useRef, lazy, Suspense } from 'react';
-import { useParams, useNavigate } from 'react-router';
+import { useParams, useNavigate, useSearchParams } from 'react-router';
import { useSocket } from '../hooks/useSocket';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { useValidTab } from '../hooks/useValidTab';
import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';
import { filterNavByFeatures } from '../lib/navFeatures.js';
@@ -36,7 +35,7 @@ import StatCard from '../components/cos/StatCard';
import StatusBubble from '../components/cos/StatusBubble';
import EventLog from '../components/cos/EventLog';
import ActionableInsightsBanner from '../components/cos/ActionableInsightsBanner';
-import AgentsTab from '../components/cos/tabs/AgentsTab';
+const AgentsTab = lazy(() => import('../components/cos/tabs/AgentsTab'));
// Task editing is not needed to view agents, so keep its forms and drag/drop
// dependencies out of the agents page's initial download.
@@ -51,7 +50,7 @@ const RunsTab = lazy(() => import('../components/cos/tabs/RunsTab'));
// ledger read path with it.
const RunEventsTab = lazy(() => import('../components/cos/tabs/RunEventsTab'));
const MindTab = lazy(() => import('../components/cos/tabs/MindTab'));
-// Keep the agents landing surface eager; task editing loads only on its tab.
+// Collection views and editors load only on their selected tab.
// Every other tab is loaded only when selected so the common queue view does
// not pay for charts, memory graphs, briefing readers, or configuration forms.
const JobsTab = lazy(() => import('../components/cos/tabs/JobsTab'));
@@ -109,16 +108,46 @@ function TabLoadFallback({ label }) {
return <div className="flex items-center justify-center py-12"><BrailleSpinner text={`Loading ${label}`} /></div>;
}
+// Keep stable reference data until an explicit invalidation. A replaced read
+// cannot overwrite the newer cache or clear it when the old request fails.
+function readReference(cache, read, apply) {
+ if (cache.current) return cache.current;
+ const pending = read().then(data => {
+ if (cache.current === pending) apply(data);
+ return data;
+ }).catch(() => { if (cache.current === pending) cache.current = null; });
+ cache.current = pending;
+ return pending;
+}
+
export default function ChiefOfStaff() {
const { tab } = useParams();
+ const [searchParams] = useSearchParams();
+ const selectedTask = searchParams.get('task') || undefined;
const navigate = useNavigate();
const activeTab = useValidTab(TABS, 'tasks');
const { isFeatureEnabled } = useInstanceFeatures();
const visibleTabs = filterNavByFeatures(TABS, isFeatureEnabled);
+ const needsTasks = activeTab === 'tasks';
+ const needsAgents = needsTasks || activeTab === 'agents';
+ const needsProviders = ['tasks', 'agents', 'schedule', 'workflow'].includes(activeTab);
+ const needsApps = needsProviders || activeTab === 'memory';
+ const routeRef = useRef(activeTab);
+ routeRef.current = activeTab;
+ const queryKey = `${activeTab}:${selectedTask || ''}`;
+ const queryRef = useRef(queryKey);
+ queryRef.current = queryKey;
+ const inFlight = useRef(null);
+ const queuePending = useRef(null);
+ const providersReadRef = useRef(null);
+ const appsReadRef = useRef(null);
+
const [status, setStatus] = useState(null);
const [tasks, setTasks] = useState({ user: null, cos: null });
const [agents, setAgents] = useState([]);
+ const [completedRevision, setCompletedRevision] = useState(0);
+ const [taskHistoryRevision, setTaskHistoryRevision] = useState(0);
const [health, setHealth] = useState(null);
const [healthLoaded, setHealthLoaded] = useState(false);
const [providers, setProviders] = useState([]);
@@ -154,7 +183,7 @@ export default function ChiefOfStaff() {
// Actionable insights (blocked/approval/health counts) are fetched here in
// fetchData and passed to ActionableInsightsBanner as a prop, so every trigger
// that refetches CoS data — task mutations, socket-driven changes, health
- // checks, the 30s poll — refreshes the banner without a separate signal. null
+ // checks, explicit refresh or reconnect — refreshes the banner without a separate signal. null
// until the first fetch resolves; preserved across transient fetch failures.
const [insights, setInsights] = useState(null);
// Monotonic counter for queue/insight-state writes, so a slow fetchData cannot
@@ -201,7 +230,7 @@ export default function ChiefOfStaff() {
// The single write path for the provider list, mirroring `applyHealth` above:
// stamping the settle flag anywhere else could set `providers` without it.
// `sameJsonShape` keeps the array identity stable when the payload is
- // unchanged — which it is on essentially every 30s poll — so the early commit
+ // unchanged — which it is on essentially every refresh — so the early commit
// that fixes first-paint latency doesn't cost a full-tree re-render each tick
// (`providers` is an unmemoized prop down through every schedule card).
const applyProviders = useCallback((data) => {
@@ -216,7 +245,7 @@ export default function ChiefOfStaff() {
// `secondaryRead`'s Promise.all held it hostage to `getCosActionableInsights`
// (a server-side health check) and left those pickers showing an empty list
// for seconds. `sameJsonShape` keeps the array identity stable on an unchanged
- // 30s poll payload so this doesn't cost a full-tree re-render each tick.
+ // refresh payload so this doesn't cost a full-tree re-render each tick.
const applyApps = useCallback((data) => {
const filtered = (Array.isArray(data) ? data : []).filter(a => a.id !== 'portos-autofixer');
setApps(prev => (sameJsonShape(prev, filtered) ? prev : filtered));
@@ -229,7 +258,7 @@ export default function ChiefOfStaff() {
if (statusData.paused) return 'sleeping';
const activeAgents = agentsData.filter(a => a.status === 'running');
- if (activeAgents.length > 0) return 'coding';
+ if (activeAgents.length > 0 || statusData.activeAgents > 0) return 'coding';
if (healthData?.issues?.length > 0) return 'investigating';
@@ -237,129 +266,134 @@ export default function ChiefOfStaff() {
return 'thinking';
}, []);
- const fetchData = useCallback(async () => {
- const queueSeq = queueSeqRef.current;
- // The queue is the critical path for both the Tasks and Agents tabs. Start
- // the secondary reads at the same time, but do not make the first paint
- // wait for them: actionable insights runs a server-side PM2/memory health
- // check, and provider/app/learning data can be hydrated after the queue is
- // already usable.
- const coreRead = Promise.all([
- api.getCosStatus().catch(() => null),
- api.getCosTasks().catch(() => ({ user: null, cos: null })),
- api.getCosAgents().catch(() => []),
- ]);
- const healthRead = api.getCosHealth().catch(() => null).then((data) => {
- // Health is independently useful to the Health tab. Commit it as soon
- // as its own read settles instead of making that tab wait for the slower
- // actionable-insights request in the same batch.
- applyHealth(data, { merge: true });
- return data;
- });
- // `/providers` is a cache-only read that returns in milliseconds, but bundling
- // it into the Promise.all below held it until the SLOWEST sibling settled —
- // and `getCosActionableInsights` runs a server-side PM2/memory health check.
- // That left the Schedule tab's provider pickers empty for seconds, rendering
- // a lone "Default (active provider)" option that reads as broken. Same fix as
- // `healthRead`: commit on its own settle.
- const providersRead = api.getProviders()
- .catch(() => ({ providers: [] }))
- .then(applyProviders);
- // Same rationale as providersRead above: apps commits on its own settle
- // instead of waiting on the slower siblings in secondaryRead.
- const appsRead = api.getApps().catch(() => []).then(applyApps);
- const secondaryRead = Promise.all([
- api.getCosLearningSummary().catch(() => null),
- // `silent: true` keeps transient poll blips quiet, matching the banner's
- // retired 60s poll; `.catch(() => null)` → preserve last-good below.
- api.getCosActionableInsights({ silent: true }).catch(() => null)
- ]);
-
- const [statusData, tasksData, agentsData] = await coreRead;
- setStatus(statusData);
- // A queue refresh started later can still resolve first. Its task payload
- // must not be clobbered by this older, pre-flip read — otherwise the row
- // returns to the pending-AND-active state this guard exists to remove.
- if (queueSeqRef.current === queueSeq) {
- setTasks(tasksData);
- setAgents(agentsData);
+ const fetchData = useCallback(async function refreshPageData() {
+ const route = activeTab;
+ if (inFlight.current?.key === queryKey && !inFlight.current.controller.signal.aborted) {
+ inFlight.current.dirty = true;
+ return inFlight.current.promise;
}
+ inFlight.current?.controller.abort();
+ const controller = new AbortController();
+ const read = async () => {
+ const queueSeq = queueSeqRef.current;
+ // Paint the visible queue before ancillary summaries and references settle.
+ 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([]),
+ ]);
+ const healthRead = api.getCosHealth().catch(() => null).then((data) => {
+ // Health is independently useful to the Health tab. Commit it as soon
+ // as its own read settles instead of making that tab wait for the slower
+ // actionable-insights request in the same batch.
+ applyHealth(data, { merge: true });
+ return data;
+ });
+ // Reference data commits independently and remains cached until invalidated.
+ const providersRead = needsProviders ? readReference(providersReadRef, api.getProviders, applyProviders) : Promise.resolve();
+ // Same rationale as providersRead above: apps commits on its own settle
+ // instead of waiting on the slower siblings in secondaryRead.
+ const appsRead = needsApps ? readReference(appsReadRef, api.getApps, applyApps) : Promise.resolve();
+ const secondaryRead = Promise.all([
+ api.getCosLearningSummary().catch(() => null),
+ // Preserve the last good insights on a transient refresh failure.
+ needsTasks ? api.getCosActionableInsights({ cachedHealth: true, silent: true }).catch(() => null) : Promise.resolve(null)
+ ]);
+
+ const [statusData, tasksData, agentResult] = await coreRead;
+ if (controller.signal.aborted || queryRef.current !== queryKey) return;
+ const agentsData = agentResult || [];
+ setStatus(statusData);
+ // A queue refresh started later can still resolve first. Its task payload
+ // must not be clobbered by this older, pre-flip read — otherwise the row
+ // 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);
-
- // Paint the shell and queue before waiting for health, providers, apps,
- // learning, and insights. Those values fill in below without delaying the
- // tab the user asked to open.
- const initialHealth = healthRef.current;
- const initialState = deriveAgentState(statusData, agentsData, initialHealth);
- setAgentState(initialState);
- setStatusMessage(statusData?.paused
- ? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`
- : (initialState === 'investigating' && summarizeHealthIssues(initialHealth?.issues)) || STATE_MESSAGES[initialState]);
- const runningAgent = agentsData.find(a => a.status === 'running');
- setActiveAgentMeta(runningAgent?.metadata || null);
-
- const [learningSummaryData, insightsData] = await secondaryRead;
- // All three self-committing reads are barriers, not values: `mergedHealth`
- // below reads what `healthRead` wrote, so it must not run before they settle.
- await Promise.all([healthRead, providersRead, appsRead]);
- // `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
- // socket handler's health write can land before this runs. `fresherHealth`
- // keeps whichever check is newer (and keeps the last-good one when this read
- // failed); everything below derives from what it returned, never from the
- // raw read, so the bubble can't name an older issue than the tile shows.
- const mergedHealth = healthRef.current;
- setLearningSummary(learningSummaryData);
- // Apply a real insights payload (including a legitimately-empty []); a null
- // from a failed/transient fetch preserves the last-good array so the banner
- // doesn't flicker empty on a blip.
- if (insightsData?.insights && queueSeqRef.current === queueSeq) setInsights(insightsData.insights);
-
- const newState = deriveAgentState(statusData, agentsData, mergedHealth);
- setAgentState(newState);
- // Default state message — richer messages come from socket events. The one
- // state whose default is useless is `investigating`: only a health issue
- // gets us here, so name it rather than saying "Investigating issue..." next
- // to an Active count of 0 with no agent to inspect.
- setStatusMessage(statusData?.paused
- ? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`
- : (newState === 'investigating' && summarizeHealthIssues(mergedHealth?.issues)) || STATE_MESSAGES[newState]);
-
- }, [deriveAgentState, applyHealth]);
-
- // 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 queueSeq = queueSeqRef.current;
- const [tasksData, agentsData] = await Promise.all([
- api.getCosTasks({ silent: true }).catch(() => null),
- api.getCosAgents({ silent: true }).catch(() => null)
- ]);
- // A confirmed local mutation can supersede this read while it is in flight;
- // never let its older task snapshot undo the optimistic state.
- if (queueSeqRef.current !== queueSeq) return;
- 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;
- }, []);
+ setLoading(false);
+
+ // Paint the shell and queue before waiting for health, providers, apps,
+ // learning, and insights. Those values fill in below without delaying the
+ // tab the user asked to open.
+ const initialHealth = healthRef.current;
+ const initialState = deriveAgentState(statusData, agentsData, initialHealth);
+ setAgentState(initialState);
+ setStatusMessage(statusData?.paused
+ ? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`
+ : (initialState === 'investigating' && summarizeHealthIssues(initialHealth?.issues)) || STATE_MESSAGES[initialState]);
+ const runningAgent = agentsData.find(a => a.status === 'running');
+ setActiveAgentMeta(runningAgent?.metadata || null);
+
+ const [learningSummaryData, insightsData] = await secondaryRead;
+ // All three self-committing reads are barriers, not values: `mergedHealth`
+ // below reads what `healthRead` wrote, so it must not run before they settle.
+ await Promise.all([healthRead, providersRead, appsRead]);
+ // Health events may have delivered a newer snapshot while these reads settled.
+ if (controller.signal.aborted || queryRef.current !== queryKey) return;
+ const mergedHealth = healthRef.current;
+ setLearningSummary(learningSummaryData);
+ // Apply a real insights payload (including a legitimately-empty []); a null
+ // from a failed/transient fetch preserves the last-good array so the banner
+ // doesn't flicker empty on a blip.
+ if (insightsData?.insights && queueSeqRef.current === queueSeq) setInsights(insightsData.insights);
+
+ const newState = deriveAgentState(statusData, agentsData, mergedHealth);
+ setAgentState(newState);
+ // Default state message — richer messages come from socket events. The one
+ // state whose default is useless is `investigating`: only a health issue
+ // gets us here, so name it rather than saying "Investigating issue..." next
+ // to an Active count of 0 with no agent to inspect.
+ setStatusMessage(statusData?.paused
+ ? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`
+ : (newState === 'investigating' && summarizeHealthIssues(mergedHealth?.issues)) || STATE_MESSAGES[newState]);
+
+ };
+ const pending = { route, key: queryKey, promise: null, controller, dirty: false };
+ inFlight.current = pending;
+ pending.promise = read().finally(() => {
+ if (inFlight.current === pending) inFlight.current = null;
+ if (pending.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshPageData();
+ });
+ return pending.promise;
+ }, [activeTab, queryKey, selectedTask, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, applyProviders, applyApps]);
+
+ // Coalesce event bursts into a read of the visible queue and scalar shell
+ // status. Insights use persisted health; invalidation never runs PM2 repair.
+ const fetchQueue = useCallback(async function refreshQueueData() {
+ if (queuePending.current?.key === queryKey && !queuePending.current.controller.signal.aborted) {
+ queuePending.current.dirty = true;
+ return queuePending.current.promise;
+ }
+ queuePending.current?.controller.abort();
+ const controller = new AbortController();
+ const request = { key: queryKey, controller, dirty: false, promise: null };
+ queuePending.current = request;
+ const queueSeq = ++queueSeqRef.current;
+ const insightsRead = needsTasks
+ ? api.getCosActionableInsights({ cachedHealth: true, silent: true }).catch(() => null)
+ : Promise.resolve(null);
+ 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]) => {
+ 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(() => {
+ if (queuePending.current === request) queuePending.current = null;
+ if (request.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshQueueData();
+ });
+ return request.promise;
+ }, [queryKey, needsTasks, needsAgents, selectedTask]);
- // 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)
- // and re-emits `cos:health:check`. So an on-demand refresh — whether from the
- // `cos:health:check` socket handler or the manual "Run Check" button — would
- // either loop (socket) or fire a second, redundant process-restart ~1s after
- // the button's own check. The banner's server-derived counts refresh only
- // through fetchData: the 30s poll, task mutations (TasksTab onRefresh), the
- // unblock-up path, and agent spawn/completion (which already call fetchData).
+ // All page insight reads use cached health. Explicit Run Check owns repairs;
+ // task invalidations must never trigger a health-check/socket feedback loop.
// Redirect unknown tab IDs to the default tab — `activeTab !== tab` only
// when the param failed validation and fell back.
@@ -369,8 +403,11 @@ export default function ChiefOfStaff() {
}
}, [tab, activeTab, navigate]);
- // Reduced polling since most updates come via socket events
- useAutoRefetch(fetchData, 30_000, { pollOnly: true });
+ // Initial route load only. Socket invalidations and reconnect recover updates.
+ useEffect(() => {
+ fetchData();
+ return () => { inFlight.current?.controller.abort(); queuePending.current?.controller.abort(); };
+ }, [fetchData]);
useEffect(() => {
@@ -378,7 +415,7 @@ export default function ChiefOfStaff() {
// Subscribe when socket is connected (or already connected)
const subscribe = () => {
- socket.emit('cos:subscribe');
+ socket.emit('cos:subscribe', { taskLists: 'invalidate' });
};
// Subscribe now if already connected, AND always re-subscribe on every
@@ -387,10 +424,19 @@ export default function ChiefOfStaff() {
// cos:* events dead after a reconnect when the socket was already connected
// at mount. Cleanup below offs this listener.
if (socket.connected) subscribe();
- socket.on('connect', subscribe);
+ const reconnect = () => {
+ subscribe();
+ providersReadRef.current = null;
+ appsReadRef.current = null;
+ fetchData();
+ setCompletedRevision(value => value + 1);
+ setTaskHistoryRevision(value => value + 1);
+ };
+ socket.on('connect', reconnect);
const handleCosStatus = (data) => {
setStatus(prev => ({ ...prev, running: data.running }));
+ fetchQueue();
if (!data.running) {
setAgentState('sleeping');
setStatusMessage("Stopped - daemon not running");
@@ -400,16 +446,20 @@ export default function ChiefOfStaff() {
socket.on('cos:status', handleCosStatus);
const handleTasksUserChanged = (data) => {
- setTasks(prev => ({ ...prev, user: data }));
+ if (!needsTasks) return;
+ if (data?.tasks) setTasks(prev => ({ ...prev, user: { ...data, tasks: data.tasks.filter(task => task.status !== 'completed' || task.id === selectedTask), completedCount: data.tasks.filter(task => task.status === 'completed').length } }));
+ else refreshQueue();
};
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
+ // a freshly queued scheduled task only appeared once explicit refresh or reconnect came
// around. Same full-list payload as the user event, so swap it in directly.
const handleTasksCosChanged = (data) => {
- setTasks(prev => ({ ...prev, cos: data }));
+ if (!needsTasks) return;
+ if (data?.tasks) setTasks(prev => ({ ...prev, cos: { ...data, tasks: data.tasks.filter(task => task.status !== 'completed' || task.id === selectedTask), completedCount: data.tasks.filter(task => task.status === 'completed').length } }));
+ else refreshQueue();
};
socket.on('cos:tasks:cos:changed', handleTasksCosChanged);
@@ -422,9 +472,19 @@ export default function ChiefOfStaff() {
// 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 handleTaskMutation = data => {
+ if (data?.completedChanged || data?.task?.status === 'completed' || data?.previousStatus === 'completed' || ['deleted', 'peer-merged'].includes(data?.action)) {
+ setTaskHistoryRevision(value => value + 1);
+ }
+ refreshQueue();
+ };
+ socket.on('cos:tasks:changed', handleTaskMutation);
const handleAgentSpawned = (data) => {
+ if (needsAgents && data?.id) {
+ queueSeqRef.current += 1;
+ setAgents(prev => [...prev.filter(agent => agent.id !== data.id), data]);
+ }
setAgentState('coding');
// Show actual task description if available
const taskDesc = data?.metadata?.taskDescription;
@@ -438,20 +498,21 @@ export default function ChiefOfStaff() {
if (data?.agentId || data?.id) {
setLiveOutputs(prev => ({ ...prev, [data.agentId || data.id]: [] }));
}
- fetchData();
+ fetchQueue();
};
socket.on('cos:agent:spawned', handleAgentSpawned);
const handleAgentUpdated = (updatedAgent) => {
+ if (!needsAgents) return;
// Update the specific agent in the agents list without fetching all data
setAgents(prev => prev.map(agent =>
agent.id === updatedAgent.id ? updatedAgent : agent
- ));
+ ).filter(agent => agent.status !== 'completed'));
};
socket.on('cos:agent:updated', handleAgentUpdated);
const handleAgentOutput = (data) => {
- if (data?.agentId && data?.line) {
+ if (needsAgents && data?.agentId && data?.line) {
setLiveOutputs(prev => {
const existing = prev[data.agentId] || [];
const updated = [...existing, { line: data.line, timestamp: Date.now() }];
@@ -462,6 +523,7 @@ export default function ChiefOfStaff() {
socket.on('cos:agent:output', handleAgentOutput);
const handleAgentCompleted = (data) => {
+ setCompletedRevision(value => value + 1);
setAgentState('reviewing');
// Three outcomes, not two: a run retired by Resume/Relaunch never reached a
// verdict, so announcing "Task failed" for it tells the user their own
@@ -482,15 +544,13 @@ export default function ChiefOfStaff() {
return rest;
});
}
- fetchData();
+ fetchQueue();
};
socket.on('cos:agent:completed', handleAgentCompleted);
const handleHealthCheck = (data) => {
applyHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });
- // Do NOT refresh banner insights here — /cos/actionable-insights runs a
- // health check that re-emits this very socket event, which would loop
- // (see the note by the redirect effect). Banner refreshes on the next poll.
+ // The health snapshot is already in this event; no HTTP health read is needed.
if (data.issues?.length > 0) {
setAgentState('investigating');
setStatusMessage(summarizeHealthIssues(data.issues));
@@ -517,10 +577,20 @@ export default function ChiefOfStaff() {
};
socket.on('cos:log', handleCosLog);
- // Listen for apps changes (start/stop/restart)
- const handleAppsChanged = () => {
- fetchData();
- };
+ // Stable reference data has its own invalidation path, independent of the queue.
+ const handleAppsChanged = coalesce(() => {
+ appsReadRef.current = null;
+ if (needsApps) readReference(appsReadRef, api.getApps, applyApps);
+ }, 400);
+ const handleProvidersChanged = coalesce(() => {
+ providersReadRef.current = null;
+ if (needsProviders) readReference(providersReadRef, api.getProviders, applyProviders);
+ }, 400);
+ const handleConfigChanged = () => fetchData();
+ socket.on('providers:changed', handleProvidersChanged);
+ socket.on('cos:config:changed', handleConfigChanged);
+ socket.on('cos:status:paused', handleConfigChanged);
+ socket.on('cos:status:resumed', handleConfigChanged);
socket.on('apps:changed', handleAppsChanged);
// Don't emit cos:unsubscribe — the cos:* namespace is shared with
@@ -528,11 +598,18 @@ export default function ChiefOfStaff() {
// consumers; the server's per-socket subscriber Set has no ref count.
// Unsubscribing here would yank events out from under them.
return () => {
- socket.off('connect', subscribe);
+ socket.emit('cos:subscribe', { taskLists: 'full' });
+ socket.off('connect', reconnect);
+ socket.off('providers:changed', handleProvidersChanged);
+ socket.off('cos:config:changed', handleConfigChanged);
+ socket.off('cos:status:paused', handleConfigChanged);
+ socket.off('cos:status:resumed', handleConfigChanged);
+ handleAppsChanged.cancel();
+ handleProvidersChanged.cancel();
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:tasks:changed', handleTaskMutation);
socket.off('cos:agent:spawned', handleAgentSpawned);
socket.off('cos:agent:updated', handleAgentUpdated);
socket.off('cos:agent:output', handleAgentOutput);
@@ -542,7 +619,7 @@ export default function ChiefOfStaff() {
socket.off('apps:changed', handleAppsChanged);
refreshQueue.cancel();
};
- }, [socket, fetchData, fetchQueue]);
+ }, [socket, fetchData, fetchQueue, needsAgents, needsTasks, selectedTask, needsApps, needsProviders, applyApps, applyProviders]);
const handleStart = async () => {
const result = await api.startCos({ silent: true }).catch(err => {
@@ -710,10 +787,7 @@ export default function ChiefOfStaff() {
setSpeaking(false);
if (result) {
applyHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });
- // Do NOT refresh the banner insights here — /cos/actionable-insights runs
- // a process-restarting health check, so an on-demand refresh would fire a
- // second restart ~1s after forceHealthCheck's own. The banner's health
- // count refreshes on the next fetchData poll instead (see the note above).
+ // The Health route does not load the Tasks-only insights banner.
toast.success('Health check complete');
if (result.issues?.length > 0) {
setStatusMessage(summarizeHealthIssues(result.issues));
@@ -727,8 +801,8 @@ export default function ChiefOfStaff() {
// Memoize expensive derived state to prevent recalculation on every render
// Note: These must be before any early returns to follow React's Rules of Hooks
const activeAgentCount = useMemo(() =>
- agents.filter(a => a.status === 'running').length,
- [agents]
+ needsAgents ? agents.filter(a => a.status === 'running').length : status?.activeAgents || 0,
+ [agents, needsAgents, status?.activeAgents]
);
// Memoize pending task count, settled against the live agent list.
@@ -742,9 +816,9 @@ export default function ChiefOfStaff() {
// and the task list below them cannot disagree. See lib/cosSpawnWindow.js.
const runningAgentByTaskId = useMemo(() => runningAgentsByTaskId(agents), [agents]);
const pendingTaskCount = useMemo(() =>
- withoutSpawningTasks(tasks.user?.grouped?.pending, runningAgentByTaskId).length
- + withoutSpawningTasks(tasks.cos?.grouped?.pending, runningAgentByTaskId).length,
- [tasks.user?.grouped?.pending, tasks.cos?.grouped?.pending, runningAgentByTaskId]
+ needsTasks ? withoutSpawningTasks(tasks.user?.grouped?.pending, runningAgentByTaskId).length
+ + withoutSpawningTasks(tasks.cos?.grouped?.pending, runningAgentByTaskId).length : status?.pendingTasks || 0,
+ [tasks.user?.grouped?.pending, tasks.cos?.grouped?.pending, runningAgentByTaskId, needsTasks, status?.pendingTasks]
);
const hasCanvasAvatar = CANVAS_AVATAR_STYLES.has(avatarStyle) || isRiggedAvatarStyle(avatarStyle);
@@ -1207,13 +1281,15 @@ export default function ChiefOfStaff() {
<div role="tabpanel" id="tabpanel-tasks" aria-labelledby="tab-tasks">
<ActionableInsightsBanner insights={insights} onTaskUnblocked={handleTaskUnblocked} onRefresh={fetchData} />
<Suspense fallback={<TabLoadFallback label="tasks" />}>
- <TasksTab tasks={tasks} agents={agents} liveOutputs={liveOutputs} onRefresh={fetchData} onTaskAdded={handleUserTaskAdded} onTaskUnblocked={handleTaskUnblocked} providers={providers} providersLoaded={providersLoaded} apps={apps} />
+ <TasksTab completedRevision={taskHistoryRevision} tasks={tasks} agents={agents} liveOutputs={liveOutputs} onRefresh={fetchData} onTaskAdded={handleUserTaskAdded} onTaskUnblocked={handleTaskUnblocked} providers={providers} providersLoaded={providersLoaded} apps={apps} />
</Suspense>
</div>
)}
{activeTab === 'agents' && (
<div role="tabpanel" id="tabpanel-agents" aria-labelledby="tab-agents">
- <AgentsTab agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} providers={providers} providersLoaded={providersLoaded} apps={apps} />
+ <Suspense fallback={<TabLoadFallback label="agents" />}>
+ <AgentsTab completedRevision={completedRevision} agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} providers={providers} providersLoaded={providersLoaded} apps={apps} />
+ </Suspense>
</div>
)}
{activeTab === 'jobs' && (
diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsx
index cff4f72d31..c1b46fe8df 100644
--- a/client/src/pages/ChiefOfStaff.test.jsx
+++ b/client/src/pages/ChiefOfStaff.test.jsx
@@ -33,8 +33,7 @@ const api = vi.hoisted(() => ({
getCodeReviewDefaults: vi.fn(),
getRiggedAvatars: vi.fn(),
// AgentsTab, reached by the mobile-select navigation test below.
- getCosAgentDates: vi.fn(),
- getCosAgentsByDate: vi.fn(),
+ getCosCompletedAgents: vi.fn(),
getCosPendingAgentFeedback: vi.fn(),
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
@@ -122,8 +121,7 @@ beforeEach(() => {
api.getCosPopularTemplates.mockResolvedValue([]);
api.getCodeReviewDefaults.mockResolvedValue({});
api.getRiggedAvatars.mockResolvedValue({ records: [] });
- api.getCosAgentDates.mockResolvedValue({ dates: [] });
- api.getCosAgentsByDate.mockResolvedValue([]);
+ api.getCosCompletedAgents.mockResolvedValue({ items: [], total: 0, nextCursor: null });
api.getCosPendingAgentFeedback.mockResolvedValue({ agents: [], count: null });
localLlm.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });
localLlm.getToolUseModels.mockResolvedValue({ models: [] });
@@ -451,13 +449,7 @@ describe('ChiefOfStaff Learning card skipped label', () => {
});
});
-// #2654: the banner is now prop-driven, refreshed only through fetchData. There
-// is deliberately no on-demand insights refresh: /cos/actionable-insights runs a
-// health check that AUTO-RESTARTS errored processes and re-emits cos:health:check,
-// so an on-demand refresh would either loop (from the socket handler) or fire a
-// second process-restart (from the manual "Run Check" button). These guards pin
-// that neither the socket handler nor the manual button re-fetches insights, plus
-// the lastCheck guard that stops a stale fetchData read clobbering fresher health.
+// Health routes consume health directly without loading the Tasks-only insights.
describe('ChiefOfStaff insight freshness (#2654)', () => {
const getSocketHandler = (event) => {
const entry = socketStub.on.mock.calls.find(([evt]) => evt === event);
@@ -467,7 +459,7 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
it('does NOT re-fetch insights on a socket health-check (no feedback loop)', async () => {
await renderSettledConfigTab();
// The initial fetchData pulls insights once; wait for it before firing.
- await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());
+ await waitFor(() => expect(api.getCosHealth).toHaveBeenCalled());
const before = api.getCosActionableInsights.mock.calls.length;
const handleHealthCheck = getSocketHandler('cos:health:check');
@@ -481,13 +473,13 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
await act(async () => { await Promise.resolve(); });
// A socket-driven re-fetch here would loop against the health-checking
- // endpoint — the count must stay put; the poll refreshes the banner instead.
+ // endpoint — the count must stay put; the Tasks route refreshes its own banner.
expect(api.getCosActionableInsights.mock.calls.length).toBe(before);
});
it('does NOT re-fetch insights on the manual "Run Check" button (no second process-restart)', async () => {
await renderSettledAt('health');
- await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());
+ await waitFor(() => expect(api.getCosHealth).toHaveBeenCalled());
const before = api.getCosActionableInsights.mock.calls.length;
const button = await screen.findByRole('button', { name: /Run Check/i });
@@ -495,7 +487,7 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
// The button runs its own health check via forceHealthCheck and shows the
// result — but must NOT also hit the insights endpoint, which would run a
- // second process-restarting health check ~1s later. Banner refreshes on poll.
+ // second process-restarting health check ~1s later. The Tasks route refreshes its own banner.
await waitFor(() => expect(api.forceHealthCheck).toHaveBeenCalledWith({ silent: true }));
await act(async () => { await Promise.resolve(); });
expect(api.getCosActionableInsights.mock.calls.length).toBe(before);
@@ -530,7 +522,7 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
// Next fetchData (apps:changed) reads a STALE, older, issue-free health.
api.getCosHealth.mockResolvedValue({ lastCheck: '2026-01-01T00:00:01Z', issues: [] });
- const handleAppsChanged = getSocketHandler('apps:changed');
+ const handleAppsChanged = getSocketHandler('cos:config:changed');
expect(handleAppsChanged).toBeTypeOf('function');
await act(async () => {
handleAppsChanged();
@@ -538,7 +530,7 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
});
// The guard keeps the fresher health — the issue must NOT disappear.
- await waitFor(() => expect(api.getApps.mock.calls.length).toBeGreaterThan(1));
+ await waitFor(() => expect(api.getCosHealth.mock.calls.length).toBeGreaterThan(1));
expect(screen.getByText('FRESH_ISSUE')).toBeInTheDocument();
expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();
});
@@ -554,13 +546,13 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
// A read with no (parseable) lastCheck must not overwrite the timestamped,
// fresher health — Date.parse('') is NaN, which must NOT win the guard.
api.getCosHealth.mockResolvedValue({ issues: [] });
- const handleAppsChanged = getSocketHandler('apps:changed');
+ const handleAppsChanged = getSocketHandler('cos:config:changed');
await act(async () => {
handleAppsChanged();
await Promise.resolve();
});
- await waitFor(() => expect(api.getApps.mock.calls.length).toBeGreaterThan(1));
+ await waitFor(() => expect(api.getCosHealth.mock.calls.length).toBeGreaterThan(1));
expect(screen.getByText('FRESH_ISSUE')).toBeInTheDocument();
expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();
});
@@ -575,13 +567,13 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
// A failed health read (rejects → .catch → null) must not blank the banner.
api.getCosHealth.mockRejectedValue(new Error('boom'));
- const handleAppsChanged = getSocketHandler('apps:changed');
+ const handleAppsChanged = getSocketHandler('cos:config:changed');
await act(async () => {
handleAppsChanged();
await Promise.resolve();
});
- await waitFor(() => expect(api.getApps.mock.calls.length).toBeGreaterThan(1));
+ await waitFor(() => expect(api.getCosHealth.mock.calls.length).toBeGreaterThan(1));
expect(screen.getByText('FRESH_ISSUE')).toBeInTheDocument();
expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();
});
@@ -653,16 +645,15 @@ describe('ChiefOfStaff task-change subscriptions', () => {
it('refreshes the queue without re-running the health-checking insights read', async () => {
await renderSettledTasksTab();
- await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());
+ await waitFor(() => expect(api.getCosHealth).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);
+ // Invalidation must request persisted health, never the legacy repair path.
+ expect(api.getCosActionableInsights.mock.calls.length).toBe(insightsBefore + 1);
+ expect(api.getCosActionableInsights).toHaveBeenLastCalledWith({ cachedHealth: true, silent: true });
});
});
@@ -735,7 +726,7 @@ describe('ChiefOfStaff task unblock freshness', () => {
});
});
-// fetchData reads 8 endpoints, one of which runs a server-side health check, so a
+// Ancillary reads can settle after the visible queue, 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.
@@ -751,14 +742,15 @@ describe('ChiefOfStaff stale queue-read guard', () => {
await renderSettledAt('tasks');
expect(await screen.findByText('STALE pending copy')).toBeInTheDocument();
- // A spawn kicks off the slow full fetch, whose insights read we hold open so
+ // A config change 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: {} }); });
+ await act(async () => { getSocketHandler('cos:config:changed')({}); });
// The store event's queue refresh resolves first, with the post-flip truth.
api.getCosTasks.mockResolvedValue(fresh);
+ api.getCosActionableInsights.mockResolvedValue({ insights: [] });
await act(async () => { getSocketHandler('cos:tasks:changed')({ type: 'user', action: 'updated' }); });
expect(await screen.findByText('FRESH in-progress copy')).toBeInTheDocument();
@@ -784,7 +776,7 @@ describe('ChiefOfStaff stale queue-read guard', () => {
user: { tasks: [pendingTask], grouped: { pending: [pendingTask], in_progress: [] } },
cos: { tasks: [], grouped: { pending: [], in_progress: [] } },
});
- await renderSettledAt('config');
+ await renderSettledAt('tasks');
const statValue = (label) => screen.getAllByText(label)
.map((node) => node.parentElement?.parentElement?.textContent)
@@ -1065,3 +1057,70 @@ describe('avatar-style registry coverage', () => {
}
});
});
+
+
+describe('ChiefOfStaff route-scoped data', () => {
+ it.each(['config', 'health', 'mind'])('does not fetch task or agent collections on %s, including refresh events', async tab => {
+ withFakeTimers();
+ await renderSettledAt(tab);
+ await act(async () => {
+ for (const event of ['apps:changed', 'cos:tasks:changed', 'cos:agent:spawned', 'cos:agent:completed']) {
+ socketStub.on.mock.calls.find(([name]) => name === event)?.[1]({});
+ }
+ await vi.advanceTimersByTimeAsync(31_000);
+ });
+ expect(api.getCosTasks).not.toHaveBeenCalled();
+ expect(api.getCosAgents).not.toHaveBeenCalled();
+ if (tab !== 'health') expect(api.getProviders).not.toHaveBeenCalled();
+ expect(api.getApps).not.toHaveBeenCalled();
+ expect(api.getCosActionableInsights).not.toHaveBeenCalled();
+ });
+
+ it('stays idle without polling and invalidates apps/providers independently', async () => {
+ withFakeTimers();
+ await renderSettledAt('agents');
+ await waitFor(() => expect(api.getCosCompletedAgents).toHaveBeenCalledTimes(1));
+ const reads = [api.getCosAgents, api.getProviders, api.getApps, api.getCosCompletedAgents];
+ const before = reads.map(read => read.mock.calls.length);
+ await act(async () => { await vi.advanceTimersByTimeAsync(65_000); });
+ expect(reads.map(read => read.mock.calls.length)).toEqual(before);
+ const latestHandler = name => socketStub.on.mock.calls.filter(([event]) => event === name).at(-1)[1];
+ await act(async () => {
+ latestHandler('apps:changed')(); latestHandler('apps:changed')();
+ await vi.advanceTimersByTimeAsync(450);
+ });
+ expect(api.getApps).toHaveBeenCalledTimes(before[2] + 1);
+ expect(api.getProviders).toHaveBeenCalledTimes(before[1]);
+ expect(api.getCosAgents).toHaveBeenCalledTimes(before[0]);
+ await act(async () => {
+ latestHandler('providers:changed')();
+ await vi.advanceTimersByTimeAsync(450);
+ });
+ expect(api.getProviders).toHaveBeenCalledTimes(before[1] + 1);
+ await act(async () => { latestHandler('connect')(); });
+ expect(api.getCosAgents).toHaveBeenCalledTimes(before[0] + 1);
+ expect(api.getCosTasks).not.toHaveBeenCalled();
+ });
+
+ it('recovers a config invalidation received during an in-flight initial read', async () => {
+ let releaseStatus;
+ api.getCosStatus.mockReturnValueOnce(new Promise(resolve => { releaseStatus = resolve; }));
+ renderPageAt('config');
+ await waitFor(() => expect(api.getCosStatus).toHaveBeenCalledTimes(1));
+ api.getCosStatus.mockResolvedValue({ running: true, paused: true, config, stats: {} });
+ await act(async () => {
+ socketStub.on.mock.calls.find(([event]) => event === 'cos:config:changed')[1]();
+ releaseStatus({ running: false, config, stats: {} });
+ });
+ await waitFor(() => expect(api.getCosStatus).toHaveBeenCalledTimes(2));
+ expect((await screen.findAllByRole('button', { name: /Resume Chief of Staff scheduling/i })).length).toBeGreaterThan(0);
+ });
+
+ it('loads agents when navigating from another CoS tab without waiting for the poll', async () => {
+ await renderSettledAt('mind');
+ expect(api.getCosAgents).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('tab', { name: 'Agents' }));
+ await waitFor(() => expect(api.getCosAgents).toHaveBeenCalledWith(expect.objectContaining({ active: true })));
+ expect(api.getCosTasks).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index a7e4e72ede..458b2bf05a 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -1,3 +1,4 @@
+import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';
/**
* Media History — unified timeline of generated images + videos with filter
* chips, ffmpeg stitching (videos only), Remix for images and videos,
@@ -203,7 +204,7 @@ export default function MediaHistory() {
</div>
</div>
- {page.error && <p role="alert" className="text-port-error">{page.error} <button type="button" onClick={page.retry}>Retry</button></p>}
+ {page.error && items.length === 0 && <p role="alert" className="text-port-error">{page.error} <button type="button" onClick={page.retry}>Retry</button></p>}
{loading && items.length === 0 ? (
<PageSkeleton header="none" label="Loading media history" layout="grid" cards={10} gridColsClass="grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5" />
) : filtered.length === 0 ? (
@@ -246,16 +247,9 @@ export default function MediaHistory() {
);
})}
</div>
- {page.hasMore && (
- <button
- type="button"
- onClick={page.loadMore}
- disabled={loading}
- className="w-full py-2.5 text-xs text-port-accent hover:text-white bg-port-border/30 hover:bg-port-border/50 rounded-lg transition-colors min-h-[44px]"
- >
- {loading ? 'Loading…' : `Show more (${page.total - items.length} remaining)`}
- </button>
- )}
+ <InfiniteScrollFooter hasMore={page.hasMore} loading={loading} error={page.error}
+ onLoadMore={page.error ? page.retry : page.loadMore} autoLoad={!stitchMode}
+ label={`Show more (${page.total - items.length} remaining)`} />
</>
)}
diff --git a/client/src/pages/MediaHistory.test.jsx b/client/src/pages/MediaHistory.test.jsx
index 5fa2e55954..7d3065fdad 100644
--- a/client/src/pages/MediaHistory.test.jsx
+++ b/client/src/pages/MediaHistory.test.jsx
@@ -36,7 +36,7 @@ describe('bounded media history', () => {
fireEvent.click(screen.getByRole('button', { name: /Show more/ }));
await screen.findByRole('alert');
expect(screen.getByText('Picture 0')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
await screen.findByText('Picture 60');
expect(fetchPage).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 60 }), { silent: true });
fireEvent.change(screen.getByLabelText('Search media history'), { target: { value: 'Picture 60' } });
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 304f057295..d1e2313e26 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -167,7 +167,7 @@ export const updateCosConfig = (config, options = {}) => request('/cos/config',
});
// Today's per-domain autonomy usage (#711) for the Domain Budgets panel.
export const getCosBudgetUsage = (options = {}) => request('/cos/budget-usage', options);
-export const getCosTasks = (options) => request('/cos/tasks', options);
+export const getCosTasks = ({ view, source, cursor, limit, selected, ...options } = {}) => request(`/cos/tasks${runEventQuery({ view, source, cursor, limit, selected })}`, options);
export const addCosTask = (task, options = {}) => request('/cos/tasks', {
method: 'POST',
body: JSON.stringify(task),
@@ -232,14 +232,10 @@ export const deleteOrchestrationProfile = (id, options = {}) => request(`/settin
});
export const getCosHealth = () => request('/cos/health');
export const forceHealthCheck = (options = {}) => request('/cos/health/check', { method: 'POST', ...options });
-export const getCosAgents = (options) => request('/cos/agents', options);
-// `hydrate` also returns the newest bucket as `latest: { date, agents }`, so the
-// Agents tab reaches its first archived card in ONE round trip instead of
-// waiting for this response to name the date it must then ask for.
-export const getCosAgentDates = ({ hydrate = false } = {}) =>
- request(`/cos/agents/history${hydrate ? '?hydrate=1' : ''}`);
-export const getCosAgentsByDate = (date) => request(`/cos/agents/history/${date}`);
-export const getCosPendingAgentFeedback = (options = {}) => request('/cos/agents/feedback/pending', options);
+export const getCosAgents = ({ active = false, ...options } = {}) => request(`/cos/agents${active ? '?active=1' : ''}`, options);
+export const getCosCompletedAgents = ({ cursor, limit = 25, feedback = false, ...options } = {}) =>
+ request(`/cos/agents/${feedback ? 'feedback/pending' : 'completed'}${runEventQuery({ limit, cursor })}`, options);
+export const getCosPendingAgentFeedback = ({ countOnly, ...options } = {}) => request(`/cos/agents/feedback/pending${countOnly ? '?countOnly=1' : ''}`, options);
// `lines` caps the transcript TAIL the server hydrates (server default: 1000
// lines / 512 KB). Pass it when the record is wanted for its metadata rather
// than its log.
@@ -366,7 +362,7 @@ export const generateCosDigest = (weekId = null) => request('/cos/digest/generat
export const getCosActivityCalendar = (weeks = 12, options) => request(`/cos/activity-calendar?weeks=${weeks}`, options);
export const getCosQuickSummary = (options) => request('/cos/quick-summary', options);
export const getCosRecentTasks = (limit = 10, options) => request(`/cos/recent-tasks?limit=${limit}`, options);
-export const getCosActionableInsights = (options) => request('/cos/actionable-insights', options);
+export const getCosActionableInsights = ({ cachedHealth = false, ...options } = {}) => request(`/cos/actionable-insights${cachedHealth ? '?cachedHealth=1' : ''}`, options);
export const getCosGoalProgressSummary = (options) => request('/cos/goal-progress/summary', options);
// Auto-Fix Telemetry (issue #2328) — aggregated from persisted metadata.diagnostics
diff --git a/client/src/services/apiAgents.test.js b/client/src/services/apiAgents.test.js
index b922892334..7a6d672228 100644
--- a/client/src/services/apiAgents.test.js
+++ b/client/src/services/apiAgents.test.js
@@ -1,5 +1,5 @@
import { afterEach, expect, it, vi } from 'vitest';
-import { startMaintenanceRun, getCosAgentDates, hydrateCosAgentDescription, triggerCosJob } from './apiAgents';
+import { startMaintenanceRun, hydrateCosAgentDescription, triggerCosJob } from './apiAgents';
// Exercise the real API wrapper through HTTP serialization: mocking the wrapper
// in the form test cannot catch a selected mode being dropped before POST.
@@ -56,17 +56,6 @@ it('falls back to the clipped record when the hydration read fails', async () =>
expect(await hydrateCosAgentDescription(agent)).toBe(agent);
});
-it('asks for the newest bucket alongside the bucket list when hydrating', async () => {
- const fetchMock = okJson({ dates: [], latest: null });
- vi.stubGlobal('fetch', fetchMock);
-
- await getCosAgentDates({ hydrate: true });
- expect(fetchMock.mock.calls[0][0]).toContain('/cos/agents/history?hydrate=1');
-
- await getCosAgentDates();
- expect(fetchMock.mock.calls[1][0]).not.toContain('hydrate');
-});
-
// The one place a card's ad-hoc values become a request body. Every component
// suite mocks this module, so a regression that let `formValues` fall through
// into the fetch init instead of the body would leave all of those green while
diff --git a/docs/UX_DESIGN_GUIDE.md b/docs/UX_DESIGN_GUIDE.md
index 28658971a7..1525e02a04 100644
--- a/docs/UX_DESIGN_GUIDE.md
+++ b/docs/UX_DESIGN_GUIDE.md
@@ -252,3 +252,19 @@ The page families, spacing, navigation grouping, and pilot choices are PortOS de
## List deletion and reading position
Deleting an item keeps the populated list and its scroll container mounted. After server success, use `CollapsibleListItem` to fade and collapse the row, including its spacing, so following content slides up; remove the record locally on exit. Preserve search, filters, pagination and unrelated selection. Refresh summary counts separately. Keep failed deletions visible and actionable, prevent duplicate pending requests, honor reduced motion, and transfer keyboard focus without scrolling. Never show a whole-list loading placeholder as deletion feedback. Brain MemoryTab is the reference implementation across Memories, People, Projects, Ideas and Admin.
+
+
+## Large collections and incremental loading
+
+A growing collection must remain usable with hundreds, thousands, or more records. This applies to Brain inbox and memory, CoS tasks/agents, media and image history, and any new collection surface.
+
+- Use event-driven invalidation for stable collections and reference data. Fetch once when needed, update the affected resource on websocket notification, and recover missed updates on reconnect. Do not attach a recurring whole-page fetch to agents, apps, providers, or history. Poll live telemetry only when its visible inspector needs it; pause when hidden and document any fallback cadence.
+- Fetch only data used by the active route/tab. Shared shells use scalar summaries; inactive panels do not fetch, poll, or refresh collections on socket events. Deduplicate in-flight reads and retire responses after navigation or filter changes.
+- Start with a bounded server page (normally 25–50 records, with a server-enforced ceiling). Send card/row projections, never full transcripts, prompts, binary assets, or duplicated history. Load record details when opened and full editable values before editing. Use thumbnails and lazy image decoding/loading for media lists.
+- Use stable cursor pagination for changing histories (timestamp plus unique id as a tie-breaker); deduplicate appended records by id. Apply filters/search/order on the server before pagination. If search is intentionally local, label it “Search loaded results.” Counts describe their scope; do not equate loaded rows with the total.
+- Reuse `client/src/hooks/usePagedCollection.js` for request state and `client/src/components/ui/InfiniteScrollFooter.jsx` for scrolling. The footer observes the actual visible area, keeps a keyboard-accessible Load more button, announces loading/end states, and pauses automatic fetching on error until an explicit retry. Preserve already loaded rows on a failed next page. Disabled/collapsed collections do not fetch.
+- Filter changes reset the cursor and cancel obsolete requests. Mutation handling must preserve stable identity and prevent deleted records returning from stale requests. Keep deep links to records outside the loaded pages; fetch the selected record directly. Background updates must not restart a growing history on every event or jump the reader's scroll position.
+- Infinite fetching does not bound the DOM: for sessions retaining thousands of rows, use measured virtualization or an explicit bounded page/window with preserved selection and scroll. Do not virtualize small bounded lists without evidence.
+- Verify the public behavior: initial and next-page request limits, unrelated-tab silence, no duplicate concurrent loads, stale-response rejection, retry without skipped pages, end-of-results, deep links, and keyboard/mobile access. Measure transfer and rendered-row count using synthetic large fixtures; never put private records into tests or reports.
+
+Adoption is incremental. CoS uses the shared request and footer primitives; Media History reuses the footer with its existing `useGalleryPage` server-filtered adapter; existing collection surfaces require scoped migrations rather than a claim that this document alone makes them conform.
diff --git a/server/lib/cosAgentListProjection.js b/server/lib/cosAgentListProjection.js
index e918215364..8a702aa4cb 100644
--- a/server/lib/cosAgentListProjection.js
+++ b/server/lib/cosAgentListProjection.js
@@ -1,51 +1,28 @@
-// What a CoS agent LIST response is allowed to carry.
-//
-// The Agents tab renders every card from two list reads — `GET /api/cos/agents`
-// (state-resident runs, on the first-paint critical path of EVERY /cos/* tab and
-// re-read by the 30s poll) and `GET /api/cos/agents/history/:date` (one archived
-// date bucket). Both used to ship each agent's `metadata.taskDescription` whole,
-// and that one field is the payload: measured over a real install's five most
-// recent buckets it was 1.7 MB of a 2.35 MB response — 68% — while the state
-// listing alone was 570 KB for 56 runs. The distribution is why: p50 is 75
-// characters and p75 is 447, but the tail runs past 50 KB, because a CoS task
-// description can be a whole pasted prompt. A handful of records pay for
-// everyone, on every poll, over whatever link the user is on.
-//
-// The card never shows that text in full anyway — it renders through
-// `CollapsibleText`, clamped to a few lines until the reader asks for more. So
-// the listing carries a preview and stamps `taskDescriptionTruncated`; the
-// client hydrates the full text from `GET /api/cos/agents/:id` at the two places
-// it actually matters (expanding the description, and opening Resume/Relaunch,
-// which build a new task prompt out of it).
-//
-// The cap is deliberately generous rather than tight. At 2000 characters over
-// 90% of records are untouched, so the tab's client-side search and the
-// task-type classifier behind the duration estimate keep seeing whole
-// descriptions for every normal run, and the response still shrinks by ~65%.
-//
-// This is a ROUTE projection, not a service one: `getAgents` / `getAgentsByDate`
-// also feed the weekly digest and CoS reports, which need the whole text.
+// CoS HTTP list responses and websocket agent rows carry bounded previews.
+// Descriptions can contain pasted prompts; legacy task/simplify summaries can
+// contain entire transcripts. Details remain available from GET /agents/:id
+// when the reader expands a card or opens Resume/Relaunch. Project only at the
+// transport boundary: reports and other service callers need the full records.
import { clampToCharLimit } from './textUtils.js';
export const AGENT_LIST_DESCRIPTION_CHARS = 2000;
/**
* Project one agent record into its list shape: no transcript, and a bounded
- * task description that says so when it was clipped.
+ * description and summaries that say when they were clipped.
*/
export function toAgentListItem(agent) {
const { output, ...rest } = agent;
- const description = rest.metadata?.taskDescription;
- const { text, truncated } = clampToCharLimit(description, AGENT_LIST_DESCRIPTION_CHARS);
- if (!truncated) return rest;
- return {
- ...rest,
- metadata: {
- ...rest.metadata,
- taskDescription: text,
- taskDescriptionTruncated: true
+ if (!rest.metadata) return rest;
+ const metadata = { ...rest.metadata };
+ for (const field of ['taskDescription', 'taskSummary', 'simplifySummary']) {
+ const { text, truncated } = clampToCharLimit(metadata[field], AGENT_LIST_DESCRIPTION_CHARS);
+ if (truncated) {
+ metadata[field] = text;
+ metadata[`${field}Truncated`] = true;
}
- };
+ }
+ return { ...rest, metadata };
}
export const toAgentListItems = (agents) => agents.map(toAgentListItem);
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index be58c4c207..4da90275de 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -52,6 +52,7 @@ vi.mock('../services/cos.js', () => ({
getAgents: vi.fn(),
getAgentDates: vi.fn(),
getAgentsByDate: vi.fn(),
+ getCompletedAgentPage: vi.fn(),
getPendingAgentFeedback: vi.fn(),
getAgent: vi.fn(),
deleteAgent: vi.fn(),
@@ -2009,4 +2010,38 @@ describe('CoS Routes', () => {
expect(cos.getWhileAwayActivity).toHaveBeenCalledWith(undefined);
});
});
+describe('CoS scoped collections', () => {
+ it('omits completed task history and every derived copy from the initial queue', async () => {
+ const active = { id: 'active', status: 'pending', description: 'Queued work' };
+ const history = Array.from({ length: 1000 }, (_, i) => ({ id: `done-${i}`, status: 'completed', metadata: { prompt: 'x'.repeat(1000) } }));
+ cos.getAllTasks.mockResolvedValue({ user: { tasks: [active, ...history], grouped: { pending: [active], completed: history } }, cos: null });
+ cos.getAgents.mockResolvedValue([]);
+ const response = await request(app).get('/api/cos/tasks?view=queue');
+ expect(response.status).toBe(200);
+ expect(response.body.user).toMatchObject({ tasks: [active], completedCount: 1000, grouped: { completed: [] } });
+ expect(JSON.stringify(response.body).length).toBeLessThan(1000);
+ const selected = await request(app).get('/api/cos/tasks?view=queue&selected=done-7');
+ expect(selected.body.user.tasks.map(task => task.id)).toEqual(['active', 'done-7']);
+ const page = await request(app).get('/api/cos/tasks?view=completed&limit=25');
+ expect(page.body.items).toHaveLength(25);
+ expect(page.body.total).toBe(1000);
+ const next = await request(app).get(`/api/cos/tasks?view=completed&limit=25&cursor=${page.body.nextCursor}`);
+ expect(next.body.items).toHaveLength(25);
+ expect(new Set([...page.body.items, ...next.body.items].map(task => task.id)).size).toBe(50);
+ });
+
+ it('scopes live agents and validates completed page bounds without changing legacy lists', async () => {
+ cos.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']);
+ expect((await request(app).get('/api/cos/agents')).body).toHaveLength(2);
+ cos.getCompletedAgentPage.mockResolvedValue({ items: [{ id: 'done', output: ['private transcript'], metadata: { taskSummary: 'x'.repeat(100000), simplifySummary: 'y'.repeat(100000) } }], total: 1, nextCursor: null });
+ const page = await request(app).get('/api/cos/agents/completed?limit=25');
+ expect(page.body).toMatchObject({ items: [{ id: 'done', metadata: { taskSummaryTruncated: true, simplifySummaryTruncated: true } }], total: 1, nextCursor: null });
+ expect(page.body.items[0]).not.toHaveProperty('output');
+ expect(JSON.stringify(page.body).length).toBeLessThan(5000);
+ expect((await request(app).get('/api/cos/agents/completed?limit=1000')).status).toBe(400);
+ expect((await request(app).get('/api/cos/agents/completed?cursor=invalid')).status).toBe(400);
+ });
+});
+
});
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 1a07b46c8c..3a8d5fd248 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -48,8 +48,20 @@ router.get('/agents', asyncHandler(async (req, res) => {
void cos.cleanupZombieAgents().catch((err) => {
console.error(`🧹 Background zombie cleanup failed: ${err.message}`);
});
+ const { active } = validateRequest(z.object({ active: z.literal('1').optional() }), req.query);
const agents = await cos.getAgents();
- res.json(toAgentListItems(agents));
+ res.json(toAgentListItems(active ? agents.filter(agent => agent.status !== 'completed') : agents));
+}));
+
+// Bounded completed history, including state records not yet archived.
+const completedQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(100).default(25),
+ cursor: z.string().max(512).regex(/^\d{4}-\d{2}-\d{2}\|[^|]*\|[^|]+$/).optional(),
+});
+router.get('/agents/completed', asyncHandler(async (req, res) => {
+ const query = validateRequest(completedQuerySchema, req.query);
+ const page = await cos.getCompletedAgentPage({ ...query, liveAgents: await cos.getAgents() });
+ res.json({ ...page, items: toAgentListItems(page.items) });
}));
// GET /api/cos/agents/history - Get available date buckets with counts
@@ -90,7 +102,19 @@ router.get('/agents/history/:date', asyncHandler(async (req, res) => {
// The queue owns the action mutation; this endpoint feeds the Agents tab with
// the same live/archive predicate and count without loading every date bucket.
router.get('/agents/feedback/pending', asyncHandler(async (req, res) => {
+ const { limit, cursor, countOnly } = validateRequest(z.object({
+ countOnly: z.literal('1').optional(),
+ limit: z.coerce.number().int().min(1).max(100).optional(),
+ cursor: z.string().max(512).optional(),
+ }), req.query);
const pending = await cos.getPendingAgentFeedback({ includeUnavailable: true });
+ if (countOnly) return res.json({ count: pending.count });
+ if (limit) {
+ const ordered = pending.agents.sort((a, b) => a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
+ const remaining = ordered.filter(agent => !cursor || agent.id < cursor);
+ return res.json({ items: toAgentListItems(remaining.slice(0, limit)), total: pending.count,
+ nextCursor: remaining.length > limit ? remaining[limit - 1].id : null });
+ }
res.json({
count: pending.count,
agents: toAgentListItems(pending.agents),
diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.js
index f4c940ecc5..ed8735faab 100644
--- a/server/routes/cosInsightRoutes.js
+++ b/server/routes/cosInsightRoutes.js
@@ -3,13 +3,14 @@
*/
import { Router } from 'express';
+import { z } from 'zod';
import * as cos from '../services/cos.js';
import * as taskLearning from '../services/taskLearning.js';
import { getActivityCalendar } from '../services/cosActivityCalendar.js';
import * as goalProgress from '../services/goalProgress.js';
import * as decisionLog from '../services/decisionLog.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { parsePagination } from '../lib/validation.js';
+import { parsePagination, validateRequest } from '../lib/validation.js';
import { runningAgentsByTaskId, withoutSpawningTasks } from '../lib/cosSpawnWindow.js';
import { detectIdleLeftoverBranches } from '../services/userActionDetectors.js';
@@ -27,10 +28,11 @@ router.get('/activity-calendar', asyncHandler(async (req, res) => {
// GET /api/cos/actionable-insights - Get prioritized action items requiring user attention
// Surfaces the most important things to address right now across all CoS subsystems
router.get('/actionable-insights', asyncHandler(async (req, res) => {
+ const { cachedHealth } = validateRequest(z.object({ cachedHealth: z.literal('1').optional() }), req.query);
const [tasksData, learningSummary, healthCheck, notificationsModule, pendingFeedbackCount, leftoverFindings, agents] = await Promise.all([
cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),
taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),
- cos.runHealthCheck().catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),
+ (cachedHealth ? cos.getHealthStatus() : cos.runHealthCheck()).catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),
import('../services/notifications.js').catch(err => { console.error(`❌ Failed to load notifications: ${err.message}`); return null; }),
cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; }),
detectIdleLeftoverBranches().catch(err => { console.error(`❌ Failed to detect leftover branches: ${err.message}`); return []; }),
diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.js
index 30fcc0124b..0c114197b1 100644
--- a/server/routes/cosInsightRoutes.test.js
+++ b/server/routes/cosInsightRoutes.test.js
@@ -7,6 +7,7 @@ vi.mock('../services/cos.js', () => ({
getAllTasks: vi.fn(),
getAgents: vi.fn(async () => []),
runHealthCheck: vi.fn(),
+ getHealthStatus: vi.fn(),
getPendingAgentFeedbackCount: vi.fn(),
getTodayActivity: vi.fn(),
getRecentTasks: vi.fn()
@@ -94,6 +95,17 @@ describe('CoS Insight Routes', () => {
});
describe('GET /api/cos/actionable-insights', () => {
+ it('refreshes event-driven insights from persisted health without running process repair', async () => {
+ cos.getAllTasks.mockResolvedValue({ user: null, cos: null });
+ taskLearning.getLearningInsights.mockResolvedValue(null);
+ cos.getHealthStatus.mockResolvedValue({ issues: [] });
+ const response = await request(app).get('/api/cos/actionable-insights?cachedHealth=1');
+ expect(response.status).toBe(200);
+ expect(cos.getHealthStatus).toHaveBeenCalledTimes(1);
+ expect(cos.runHealthCheck).not.toHaveBeenCalled();
+ expect(Array.isArray(response.body.insights)).toBe(true);
+ });
+
it('should return actionable insights sorted by priority', async () => {
cos.getAllTasks.mockResolvedValue({
user: { grouped: { pending: [{ id: 't1', description: 'Task' }], blocked: [] } },
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 6f60231024..6d55016aea 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -153,6 +153,12 @@ const router = Router();
// caller asked to page through, defeating the bound. A `pagination` block with
// the true per-source totals is added so the caller can page.
router.get('/tasks', asyncHandler(async (req, res) => {
+ const query = validateRequest(z.object({
+ view: z.enum(['queue', 'completed']).optional(),
+ source: z.enum(['user', 'internal']).default('user'),
+ selected: z.string().max(512).optional(),
+ cursor: z.string().max(512).optional(),
+ }), req.query);
const [allTasks, agents] = await Promise.all([
cos.getAllTasks(),
cos.getAgents().catch(() => []),
@@ -163,6 +169,26 @@ router.get('/tasks', asyncHandler(async (req, res) => {
user: settleTaskSourceSpawnWindow(allTasks?.user, runningAgents),
cos: settleTaskSourceSpawnWindow(allTasks?.cos, runningAgents),
};
+ if (query.view === 'completed') {
+ const source = query.source === 'internal' ? tasks.cos : tasks.user;
+ const completed = (source?.tasks || []).filter(task => task.status === 'completed')
+ .sort((a, b) => a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
+ const remaining = completed.filter(task => !query.cursor || task.id < query.cursor);
+ const { limit } = validateRequest(z.object({ limit: z.coerce.number().int().min(1).max(100).default(25) }), req.query);
+ return res.json({ items: remaining.slice(0, limit), total: completed.length,
+ nextCursor: remaining.length > limit ? remaining[limit - 1].id : null });
+ }
+ if (query.view === 'queue') {
+ const queueSource = source => {
+ if (!source) return source;
+ const keep = task => task.status !== 'completed' || task.id === query.selected;
+ return { ...source, tasks: (source.tasks || []).filter(keep),
+ completedCount: (source.tasks || []).filter(task => task.status === 'completed').length,
+ grouped: Object.fromEntries(Object.entries(source.grouped || {}).map(([key, rows]) => [key, rows.filter(keep).map(task => ({ id: task.id, status: task.status, spawning: task.spawning }))])),
+ autoApproved: source.autoApproved?.filter(keep).map(task => ({ id: task.id })), awaitingApproval: source.awaitingApproval?.filter(keep).map(task => ({ id: task.id })) };
+ };
+ return res.json({ user: queueSource(tasks.user), cos: queueSource(tasks.cos) });
+ }
if (!isPaginationRequested(req.query)) {
return res.json(tasks);
}
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 3d0c788261..8af9689791 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -255,6 +255,14 @@ const withResolvedModelAccess = (provider, resolved) => (
*/
export function createPortOSProviderRoutes(aiToolkit) {
const router = Router();
+ router.use((req, res, next) => {
+ if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
+ res.once('finish', () => {
+ if (res.statusCode < 400) req.app.get('io')?.emit('providers:changed');
+ });
+ }
+ next();
+ });
router.get('/fleet-host', asyncHandler(async (req, res) => {
const { getFleetLlmHostStatus } = await import('../services/fleetLlmHost.js');
diff --git a/server/routes/providers.management.test.js b/server/routes/providers.management.test.js
index 2d2aa63942..3856819b31 100644
--- a/server/routes/providers.management.test.js
+++ b/server/routes/providers.management.test.js
@@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import express, { Router } from 'express';
import { request } from '../lib/testHelper.js';
-import { errorMiddleware } from '../lib/errorHandler.js';
+import { errorMiddleware, errorEvents } from '../lib/errorHandler.js';
import { staticImportClosure, specifierMatchesPackage } from '../lib/staticImportGraph.js';
import { createPortOSProviderRoutes } from './providers.js';
@@ -194,3 +194,23 @@ describe('POST /api/providers — creating both execution modes at once', () =>
expect(updateProvider.mock.calls[0][1]).not.toHaveProperty('modes');
});
});
+
+
+describe('provider configuration invalidation', () => {
+ const handleExpectedError = () => {};
+ beforeEach(() => errorEvents.on('error', handleExpectedError));
+ afterEach(() => errorEvents.off('error', handleExpectedError));
+ it('notifies websocket clients after successful writes, but not reads or rejected writes', async () => {
+ const setActiveProvider = vi.fn().mockResolvedValue(CLAUDE_OLLAMA);
+ const app = appWith({ setActiveProvider, getAllProviders: vi.fn().mockResolvedValue(providersFixture()) });
+ const emit = vi.fn();
+ app.set('io', { emit });
+ expect((await request(app).get('/api/providers')).status).toBe(200);
+ expect(emit).not.toHaveBeenCalledWith('providers:changed');
+ expect((await request(app).put('/api/providers/active').send({ id: 'claude-ollama' })).status).toBe(200);
+ expect(emit).toHaveBeenCalledWith('providers:changed');
+ emit.mockClear();
+ expect((await request(app).put('/api/providers/active').send({})).status).toBe(400);
+ expect(emit).not.toHaveBeenCalledWith('providers:changed');
+ });
+});
diff --git a/server/services/cos.js b/server/services/cos.js
index 4c80c4c6ea..abb27be6db 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1,3 +1,4 @@
+import { getPendingTaskIds as readPendingTaskIds } from './cosTaskStore.js';
import { mergePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';
/**
* Chief of Staff (CoS) Service
@@ -21,7 +22,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { getActiveProvider } from './providers.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { runningAgentsByTaskId, spawningAgentForTask, spawnClaimAgeMs } from '../lib/cosSpawnWindow.js';
+import { unclaimedTaskIds, runningAgentsByTaskId, spawningAgentForTask, spawnClaimAgeMs } from '../lib/cosSpawnWindow.js';
import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';
import { clearStaleActiveAgents } from './appActivity.js';
// The single Priority-0 on-demand loop body, shared with the evaluateTasks
@@ -67,7 +68,7 @@ export { cosEvents, emitLog };
// is what forced the `await import()` forwarders in `cosAgentLifecycle.js`.
// Callers ask `agentOrchestrator.js` for those (#3450).
export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgent, getAgentRecord, getAgentPrompt, terminateAgent, sendBtwToAgent, cleanupZombieAgents, deleteAgent } from './cosAgentLifecycle.js';
-export { getAgentDates, getAgentsByDate, pruneOldAgentArchives } from './cosAgentIndex.js';
+export { getAgentDates, getAgentsByDate, getCompletedAgentPage, pruneOldAgentArchives } from './cosAgentIndex.js';
export {
submitAgentFeedback,
getFeedbackStats,
@@ -219,6 +220,7 @@ export async function getStatus() {
config: state.config,
stats: { ...state.stats, tasksCompleted },
activeAgents,
+ pendingTasks: unclaimedTaskIds(await readPendingTaskIds(), runningAgentsByTaskId(Object.values(state.agents))).length,
pausedAgents,
provider: provider ? { id: provider.id, name: provider.name } : null
};
diff --git a/server/services/cosAgentIndex.js b/server/services/cosAgentIndex.js
index 0aa580180b..a6984e29c8 100644
--- a/server/services/cosAgentIndex.js
+++ b/server/services/cosAgentIndex.js
@@ -287,7 +287,7 @@ export async function getAgentIdsForDates(dates) {
}
// Get completed agents for a specific date bucket
-export async function getAgentsByDate(date) {
+export async function getAgentsByDate(date, { repairSummaries = true } = {}) {
const dateDir = join(AGENTS_DIR, date);
if (!existsSync(dateDir)) return [];
@@ -308,7 +308,7 @@ export async function getAgentsByDate(date) {
const id = raw.id || raw.agentId || entry.name;
const { output, ...rest } = raw;
const agent = { ...rest, id, status: raw.status || 'completed' };
- const repaired = await repairCodexTaskSummary(join(dateDir, entry.name), agent);
+ const repaired = repairSummaries && await repairCodexTaskSummary(join(dateDir, entry.name), agent);
if (repaired) agent.metadata = { ...agent.metadata, taskSummary: repaired };
agents.push(agent);
});
@@ -317,3 +317,31 @@ export async function getAgentsByDate(date) {
return agents.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
}
+
+
+// Cursor order is archive day, completion timestamp, then id. Only visit the
+// cursor's day and older days until one extra record proves another page exists.
+// Legacy archives store ordering metadata per record, so one visited day must
+// still be read to sort it; no transcript or unrelated older day is hydrated.
+export async function getCompletedAgentPage({ liveAgents = [], limit = 25, cursor } = {}) {
+ const idx = await loadAgentIndex();
+ const live = liveAgents.filter(agent => agent.status === 'completed');
+ const dayOf = agent => (agent.completedAt || agent.startedAt || '1970-01-01').slice(0, 10);
+ const keyOf = (agent, day) => `${day}|${agent.completedAt || ''}|${agent.id}`;
+ const days = [...new Set([...idx.values(), ...live.map(dayOf)])].sort().reverse();
+ const total = new Set([...idx.keys(), ...live.map(agent => agent.id)]).size;
+ const items = [];
+ for (const day of days) {
+ if (cursor && day > cursor.slice(0, 10)) continue;
+ const records = new Map((await getAgentsByDate(day, { repairSummaries: false })).map(agent => [agent.id, agent]));
+ for (const agent of live) if ((idx.get(agent.id) || dayOf(agent)) === day) records.set(agent.id, agent);
+ const candidates = [...records.values()].filter(agent => agent.status === 'completed')
+ .map(agent => ({ agent, key: keyOf(agent, day) }))
+ .filter(entry => !cursor || entry.key < cursor)
+ .sort((a, b) => a.key < b.key ? 1 : a.key > b.key ? -1 : 0);
+ items.push(...candidates.slice(0, limit + 1 - items.length));
+ if (items.length > limit) break;
+ }
+ return { items: items.slice(0, limit).map(entry => entry.agent), total,
+ nextCursor: items.length > limit ? items[limit - 1].key : null };
+}
diff --git a/server/services/cosAgentIndex.pagination.test.js b/server/services/cosAgentIndex.pagination.test.js
new file mode 100644
index 0000000000..a36781e55b
--- /dev/null
+++ b/server/services/cosAgentIndex.pagination.test.js
@@ -0,0 +1,44 @@
+import { afterAll, expect, it, vi } from 'vitest';
+import { mkdir, writeFile, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+const fixture = await vi.hoisted(async () => {
+ const { mkdtemp } = await import('node:fs/promises');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ return await mkdtemp(join(tmpdir(), 'cos-history-page-'));
+});
+vi.mock('./cosState.js', () => ({ AGENTS_DIR: fixture }));
+vi.mock('./codexSummaryRepair.js', () => ({ repairCodexTaskSummary: vi.fn(async () => null) }));
+import { repairCodexTaskSummary } from './codexSummaryRepair.js';
+import { getCompletedAgentPage, loadAgentIndex } from './cosAgentIndex.js';
+afterAll(() => rm(fixture, { recursive: true, force: true }));
+
+it('pages busy days with stable ties, live/archive deduplication and additions between reads', async () => {
+ const date = '2026-01-02';
+ const records = Array.from({ length: 65 }, (_, i) => ({ id: `agent-${String(i).padStart(3, '0')}`, status: 'completed', completedAt: `${date}T12:00:00.000Z`, metadata: {} }));
+ await writeFile(join(fixture, 'index.json'), JSON.stringify(Object.fromEntries(records.map(agent => [agent.id, date]))));
+ for (const agent of records) {
+ const dir = join(fixture, date, agent.id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'metadata.json'), JSON.stringify(agent));
+ }
+ const liveAgents = [{ ...records[64], metadata: { taskSummary: 'Fresh live summary' } }];
+ const first = await getCompletedAgentPage({ liveAgents, limit: 25 });
+ expect(first.items).toHaveLength(25);
+ expect(first.items[0].metadata.taskSummary).toBe('Fresh live summary');
+ expect(first.total).toBe(65);
+ expect(repairCodexTaskSummary).not.toHaveBeenCalled();
+ // Newer completions must not shift the stable cursor or duplicate a row.
+ liveAgents.push({ id: 'agent-new', status: 'completed', completedAt: '2026-01-03T12:00:00.000Z' });
+ const second = await getCompletedAgentPage({ liveAgents, limit: 25, cursor: first.nextCursor });
+ const third = await getCompletedAgentPage({ liveAgents, limit: 25, cursor: second.nextCursor });
+ expect(second.items).toHaveLength(25);
+ expect(third.items).toHaveLength(15);
+ expect(third.nextCursor).toBeNull();
+ expect(new Set([...first.items, ...second.items, ...third.items].map(agent => agent.id)).size).toBe(65);
+ // A removed cursor record is still a valid boundary.
+ const index = await loadAgentIndex();
+ index.delete(first.items.at(-1).id);
+ await rm(join(fixture, date, first.items.at(-1).id), { recursive: true });
+ expect((await getCompletedAgentPage({ limit: 25, cursor: first.nextCursor })).items).toEqual(second.items);
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index 66619f003b..33fbf20309 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -82,7 +82,8 @@ function broadcastToSet(set, event, data) {
}
function registerSubscriber(socket, namespace, set) {
- socket.on(`${namespace}:subscribe`, () => {
+ socket.on(`${namespace}:subscribe`, (options) => {
+ if (namespace === 'cos' && ['invalidate', 'full'].includes(options?.taskLists)) socket.cosTaskLists = options.taskLists;
set.add(socket);
socket.emit(`${namespace}:subscribed`);
});
@@ -329,7 +330,19 @@ export function broadcast(io, event, data) {
}
// Broadcast to CoS subscribers only
-function broadcastToCos(event, data) { broadcastToSet(cosSubscribers, event, data); }
+function broadcastToCos(event, data) {
+ if (!['cos:tasks:user:changed', 'cos:tasks:cos:changed', 'cos:tasks:changed'].includes(event)) {
+ broadcastToSet(cosSubscribers, event, data);
+ return;
+ }
+ for (const socket of cosSubscribers) {
+ if (!socket.connected) { cosSubscribers.delete(socket); continue; }
+ const completedChanged = event === 'cos:tasks:changed' && (data?.task?.status === 'completed'
+ || data?.previousStatus === 'completed' || ['deleted', 'peer-merged'].includes(data?.action));
+ socket.emit(event, socket.cosTaskLists === 'invalidate'
+ ? { invalidated: true, ...(completedChanged ? { completedChanged: true } : {}) } : data);
+ }
+}
// Broadcast to error subscribers only
function broadcastToErrors(event, data) { broadcastToSet(errorSubscribers, event, data); }
@@ -338,6 +351,9 @@ function broadcastToErrors(event, data) { broadcastToSet(errorSubscribers, event
function setupCosEventForwarding() {
// Status events
cosEvents.on('status', (data) => broadcastToCos('cos:status', data));
+ for (const event of ['config:changed', 'status:paused', 'status:resumed']) {
+ cosEvents.on(event, data => broadcastToCos(`cos:${event}`, data));
+ }
// Log events for real-time UI feedback
cosEvents.on('log', (data) => broadcastToCos('cos:log', data));
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 5c1b9f9548..480bf96cdb 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -1,3 +1,4 @@
+import { authEvents } from './auth.js';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Preserve installed once-only listeners across Vitest's per-test mock-call
@@ -139,6 +140,7 @@ describe('socket.js — initSocket', () => {
if (s.handlers['disconnect']) s.handlers['disconnect']();
}
createdSockets.length = 0;
+ authEvents.removeAllListeners('sessions:revoked-all');
});
beforeEach(() => {
@@ -148,6 +150,26 @@ describe('socket.js — initSocket', () => {
initSocket(io);
});
+ it('sends compact task invalidations to opted-in pages while preserving legacy subscribers', () => {
+ const compact = makeSocket('compact-cos');
+ const legacy = makeSocket('legacy-cos');
+ createdSockets.push(compact, legacy);
+ io.connect(compact); io.connect(legacy);
+ compact.handlers['cos:subscribe']({ taskLists: 'invalidate' });
+ compact.handlers['cos:subscribe'](); // another shared consumer must not widen it
+ legacy.handlers['cos:subscribe']();
+ const payload = { tasks: [{ id: 'example', metadata: { prompt: 'large private prompt' } }] };
+ const forward = queueListeners.cos.find(([event]) => event === 'tasks:user:changed')[1];
+ forward(payload);
+ expect(compact.emitted).toContainEqual(['cos:tasks:user:changed', { invalidated: true }]);
+ expect(legacy.emitted).toContainEqual(['cos:tasks:user:changed', payload]);
+ const forwardChange = queueListeners.cos.find(([event]) => event === 'tasks:changed')[1];
+ forwardChange({ task: { id: 'done', status: 'completed' } });
+ expect(compact.emitted).toContainEqual(['cos:tasks:changed', { invalidated: true, completedChanged: true }]);
+ forwardChange({ task: { id: 'live', status: 'in_progress' } });
+ expect(compact.emitted.at(-1)).toEqual(['cos:tasks:changed', { invalidated: true }]);
+ });
+
it('composes every per-feature handler registrar for a connected socket', () => {
const socket = makeSocket('registrars');
createdSockets.push(socket);
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index ac8f08d09b..7de8fad884 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -31,7 +31,7 @@
"model-comparison-refresh": "dc1702b07c7fb8be6165feb776d5acb6",
"module-hygiene": "3b7671cd44f719d4b2116b96a279e6d0",
"observability": "fdb4d77df5891cfb653a5da2553ecf8a",
- "performance": "d7e3a80f42903fbf90be0efc9b559c0b",
+ "performance": "b69bf4cbd2b3c272b5650608c62cede3",
"plan-feature": "87f71a894757f89354da4e2119e07118",
"plan-task": "8a53a518714cc4029d751fdad92f9b05",
"plan-task-claim": "ff9ef899c1b0d13ae2f6d7e31c13a10f",
@@ -85,7 +85,7 @@
"model-comparison-refresh": 1,
"module-hygiene": 1,
"observability": 1,
- "performance": 3,
+ "performance": 4,
"plan-feature": 5,
"plan-task": 19,
"pr-reviewer": 5,
@@ -274,7 +274,8 @@
"performance": [
"c8224243c15f6897ee04be25d172f021",
"4fea5eb3585bdc150980934b289016bc",
- "672bd3958b12afb0f382bcebb6dc3b33"
+ "672bd3958b12afb0f382bcebb6dc3b33",
+ "d7e3a80f42903fbf90be0efc9b559c0b"
],
"plan-feature": [
"9fbc2a2ded8f4533d1f0f6b9cb780b34",
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 10626f09ef..e0672b5e92 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -308,6 +308,32 @@ scale the code actually sees. Say which one you have.
- **Cache misuse** — a cache that never invalidates, one that never hits because
its key varies, or an unbounded one that is really a leak.
+## Required UI load and idle-network coverage
+
+For apps with a UI, inspect the shared shell and at least one high-volume
+collection route, plus a sibling tab that does not use that collection. Trace
+initial reads, mounted hidden panels, polling timers, websocket invalidations,
+and reconnect recovery. Include Brain inbox/memory, CoS history, and media
+history when those surfaces exist; follow the app's collection-loading standard.
+
+When browser tooling is available, capture a cold route load, navigation to the
+sibling tab, and at least 60 seconds of idle network activity. Report request
+counts and transferred/decoded bytes by endpoint, duplicate or overlapping
+requests, time until useful content renders, and idle bytes per minute. Include
+websocket payloads, not only fetch/XHR. Check apps/providers and other stable
+reference data are invalidated by events rather than repeatedly downloaded.
+Distinguish expected live telemetry from whole-list polling; telemetry should
+be scoped to visible consumers. Use synthetic large collections to verify
+server page limits, compact list projections, lazy details, bounded rendered
+rows, and no full history hydration hidden behind client-side slicing.
+
+Do not claim UI performance passed from source inspection or a small/empty
+fixture alone. If browser access, an authorized session, or usable large-fixture
+evidence is unavailable, explicitly mark UI load/idle transfer UNVERIFIED and
+file a deduplicated coverage-gap issue with the missing check and next step.
+Never copy live personal records, hostnames, tokens, or raw private HAR bodies
+into reports; report redacted endpoint patterns and aggregate measurements.
+
## Do not trade correctness or clarity for a gain you cannot measure
Reject micro-optimizations with no measured effect, and any change that makes
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index acd0744d7a..f165310d21 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -36,7 +36,7 @@ export const PROMPT_VERSIONS = {
'security': 3, // v3: carries {modeInstructions} (the pre-v3 body had no placeholder, so its own "fix and commit" steps fought a file-issues dispatch) and defers to the project's documented threat model, requiring an attacker-or-accident story per finding instead of a generic OWASP checklist walk. Previously v2: generic {appName} body (older default hardcoded "PortOS"/"server/routes" paths)
'code-quality': 4, // v4: hands generated-artifact/hand-synced-registry/layout-coupling drift to the better-structural-drift lane and counted branching + reader cost to better-complexity / better-cognitive-load, keeping conventional maintainability defects — the split the sibling do:better lenses made possible. Previously v3: inventory structural drift, duplicate sources of truth, volatile generated artifacts, and incidental-layout coupling before conventional maintainability checks. v2: generic {appName} body (older default hardcoded "PortOS")
'test-coverage': 3, // v3: carries {modeInstructions}, ranks gaps by consequence rather than percentage, tests at the highest practical public boundary, requires naming the regression a new test uniquely catches, and hands existing-test quality to better-test-quality. Previously v2: generic {appName} body (older default hardcoded "PortOS")
- 'performance': 3, // v3: carries {modeInstructions} and requires a quantity (frequency x size, or a stated growth term) per finding — the pre-v3 body invited unmeasured micro-optimization. Previously v2: generic {appName} body (older default hardcoded "PortOS")
+ 'performance': 4, // v4: requires UI route-load, idle-network and large-collection evidence; missing measurements are explicitly unverified.
'accessibility': 3, // v3: carries {modeInstructions}, names who is blocked and how far they get, and prefers a native element over a custom control with patched attributes. Previously v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)
'console-errors': 4, // v4: refer to framework-neutral UI lifecycle audit. v3: carries {modeInstructions}, collects real emitted output before diagnosing, groups duplicates by cause, and forbids "fixing" an error by suppressing it. Previously v2: unified `[Improvement: {appName}]` body (pre-unification defaults shipped separate self- and app-improvement bodies)
'error-handling': 3, // v3: carries {modeInstructions} and covers resilience (timeouts, retry ceilings, degraded-dependency fallback, cleanup on the error path, actionable user-facing text) while handing swallowed errors and log context to observability. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)