Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: refresh CoS briefings and expanded agent stats from socket events (#8604)

[._.]/ Adam Eivy1ce468fa0289
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index d2cc7caacb..b96ae37c08 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -35,13 +35,16 @@ import { isAgentFeedbackUpdateTarget, isSystemAgent as isSystemAgentRecord } fro
import AgentResultLine from '../AgentResultLine';
import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';
import { formatBytes, formatCount, formatDurationMs, formatDateTime, formatTimeOfDay } from '../../../utils/formatters';
-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { useSocketResource } from '../../../hooks/useSocketResource';
+
import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import { AgentProgress, AgentRuntimeStatus } from './AgentRuntimeStatus';
import { agentIssueLinkifier } from '../../../lib/issueRefs';
import { harnessLabel, providerHarnessId } from '../../../utils/providerHarnesses';
+const STATS_EVENTS = ['cos:agent:updated', 'cos:agent:output'];
+
// Pre-compiled regexes for normalizeDescriptionToMarkdown
// Avoid lookbehind to support older Safari/iOS runtimes
const RE_NUMBERED_LIST = /([.!?:]) (\d+)\. /g;
@@ -411,7 +414,6 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
const [activeStageTab, setActiveStageTab] = useState(null);
const [stageOutputs, setStageOutputs] = useState({});
const [loadingStageId, setLoadingStageId] = useState(null);
- const [processStats, setProcessStats] = useState(null);
const [pausing, setPausing] = useState(false);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
const [killing, setKilling] = useState(false);
@@ -514,19 +516,19 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
return () => clearInterval(interval);
}, [inactive]);
- // Fetch process stats for running agents (skip for remote peers).
- // Only overwrite prior stats on a successful response so a transient
- // error doesn't blank out the previously displayed CPU/mem/PID.
- const fetchStats = useCallback(async () => {
- try {
- const stats = await api.getCosAgentStats(agent.id, { silent: true });
- setProcessStats(stats);
- } catch {
- // preserve last-good stats on transient blip
- }
- }, [agent.id]);
-
- useAutoRefetch(fetchStats, 5000, { enabled: expanded && !inactive && !remote, pollOnly: true });
+ // Read only for an expanded, active local agent. The resource key discards
+ // in-flight responses after collapsing, switching agents, or going inactive.
+ const statsEnabled = expanded && !inactive && !remote;
+ const { data: processStats } = useSocketResource(
+ () => statsEnabled ? api.getCosAgentStats(agent.id, { silent: true }) : null,
+ {
+ namespace: 'cos',
+ enabled: statsEnabled,
+ events: STATS_EVENTS,
+ resourceKey: statsEnabled ? agent.id : null,
+ matchesEvent: payload => statsEnabled && (payload?.agentId ?? payload?.id) === agent.id,
+ },
+ );
const handlePause = async () => {
if (!onPause) return;
diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsx
index 8b34b868f2..b7cec93350 100644
--- a/client/src/components/cos/tabs/AgentCard.test.jsx
+++ b/client/src/components/cos/tabs/AgentCard.test.jsx
@@ -1,9 +1,23 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router';
import { typeSettled } from '../../../test/settledInput';
+const socket = vi.hoisted(() => {
+ const handlers = new Map();
+ return {
+ on: (event, handler) => {
+ if (!handlers.has(event)) handlers.set(event, new Set());
+ handlers.get(event).add(handler);
+ },
+ off: (event, handler) => handlers.get(event)?.delete(handler),
+ emit: vi.fn(),
+ receive: (event, payload) => handlers.get(event)?.forEach(handler => handler(payload)),
+ };
+});
+vi.mock('../../../services/socket', () => ({ default: socket }));
+
vi.mock('../../../services/api', () => ({
submitCosAgentFeedback: vi.fn(),
sendCosAgentBtw: vi.fn(),
@@ -1196,3 +1210,64 @@ it('loads a clipped summary only when the reader asks for the detail', async ()
expect(await screen.findByText('The full summary with its conclusion.')).toBeInTheDocument();
expect(screen.queryByText('Summary preview.')).not.toBeInTheDocument();
});
+
+it('refreshes expanded local stats on matching events without polling and reconciles missed events', async () => {
+ vi.useFakeTimers();
+ const running = { ...agent, status: 'running', completedAt: null, result: null };
+ api.getCosAgentStats.mockResolvedValue({ active: true, cpu: 12.3, memoryMb: 64 });
+ const view = render(<MemoryRouter><AgentCard agent={running} initiallyExpanded /></MemoryRouter>);
+ await act(async () => {});
+ expect(screen.getByText('12.3%')).toBeInTheDocument();
+ await act(async () => { await vi.advanceTimersByTimeAsync(15000); });
+ expect(api.getCosAgentStats).toHaveBeenCalledTimes(1);
+ await act(async () => socket.receive('cos:agent:output', { agentId: 'another-agent' }));
+ expect(api.getCosAgentStats).toHaveBeenCalledTimes(1);
+ api.getCosAgentStats.mockResolvedValue({ active: true, cpu: 24.6, memoryMb: 128 });
+ await act(async () => socket.receive('cos:agent:output', { agentId: agent.id }));
+ expect(screen.getByText('24.6%')).toBeInTheDocument();
+ await act(async () => socket.receive('cos:agent:updated', { id: agent.id }));
+ expect(api.getCosAgentStats).toHaveBeenCalledTimes(3);
+ await act(async () => socket.receive('connect'));
+ expect(api.getCosAgentStats).toHaveBeenCalledTimes(4);
+ await act(async () => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await act(async () => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ document.dispatchEvent(new Event('visibilitychange'));
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ expect(api.getCosAgentStats).toHaveBeenCalledTimes(5);
+ view.unmount();
+ await act(async () => socket.receive('connect'));
+ await act(async () => socket.receive('cos:agent:output', { agentId: agent.id }));
+ expect(api.getCosAgentStats).toHaveBeenCalledTimes(5);
+ api.getCosAgentStats.mockImplementation(() => new Promise(() => {}));
+});
+
+it.each([{ remote: true }, { completed: true }, { paused: true }])('does not read stats for an ineligible expanded card %j', async props => {
+ render(<MemoryRouter><AgentCard agent={agent} initiallyExpanded {...props} /></MemoryRouter>);
+ await act(async () => socket.receive('cos:agent:output', { agentId: agent.id }));
+ await act(async () => socket.receive('connect'));
+ expect(api.getCosAgentStats).not.toHaveBeenCalled();
+});
+
+it('drops an outstanding stats response when collapsed and reads afresh on reopening', async () => {
+ let resolveStats;
+ api.getCosAgentStats.mockReturnValueOnce(new Promise(resolve => { resolveStats = resolve; }));
+ const running = { ...agent, status: 'running', completedAt: null, result: null };
+ render(<MemoryRouter><AgentCard agent={running} initiallyExpanded /></MemoryRouter>);
+ await act(async () => {});
+ fireEvent.click(screen.getByRole('button', { name: 'Hide', exact: true }));
+ await act(async () => resolveStats({ active: true, cpu: 99.9 }));
+ await act(async () => socket.receive('cos:agent:output', { agentId: agent.id }));
+ expect(api.getCosAgentStats).toHaveBeenCalledTimes(1);
+ api.getCosAgentStats.mockResolvedValueOnce({ active: true, cpu: 11.1 });
+ fireEvent.click(screen.getByRole('button', { name: 'Show', exact: true }));
+ expect(await screen.findByText('11.1%')).toBeInTheDocument();
+ expect(screen.queryByText('99.9%')).not.toBeInTheDocument();
+ api.getCosAgentStats.mockRejectedValueOnce(new Error('Temporary failure'));
+ await act(async () => socket.receive('cos:agent:updated', { id: agent.id }));
+ expect(screen.getByText('11.1%')).toBeInTheDocument();
+});
diff --git a/client/src/components/cos/tabs/BriefingTab.jsx b/client/src/components/cos/tabs/BriefingTab.jsx
index 27e9316efc..82abc94444 100644
--- a/client/src/components/cos/tabs/BriefingTab.jsx
+++ b/client/src/components/cos/tabs/BriefingTab.jsx
@@ -19,7 +19,9 @@ import BrailleSpinner from '../../BrailleSpinner';
import { formatWeekdayDate } from '../../../utils/formatters';
import EmptyState from '../../EmptyState';
import { useAsyncAction } from '../../../hooks/useAsyncAction';
-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { useSocketResource } from '../../../hooks/useSocketResource';
+
+const BRIEFING_EVENTS = ['cos:agent:completed'];
const SECTION_ICONS = {
'Task Queue': CheckCircle,
@@ -157,10 +159,7 @@ const renderInlineFormatting = (text) => {
};
export default function BriefingTab() {
- const [briefings, setBriefings] = useState([]);
- const [currentBriefing, setCurrentBriefing] = useState(null);
const [selectedDate, setSelectedDate] = useState(null);
- const [loading, setLoading] = useState(true);
const [expandedSections, setExpandedSections] = useState({});
const [generationPending, setGenerationPending] = useState(false);
const generationInFlightRef = useRef(false);
@@ -174,8 +173,7 @@ export default function BriefingTab() {
throw new Error(result?.reason || 'The briefing could not be generated');
}
setGenerationPending(true);
- const latest = await loadData({ showLoading: false });
- if (latest) setGenerationPending(false);
+ await refetch();
} finally {
generationInFlightRef.current = false;
}
@@ -186,53 +184,28 @@ export default function BriefingTab() {
generateBriefing();
};
- useEffect(() => {
- loadData();
- }, []);
-
- const loadData = async ({ showLoading = true } = {}) => {
- if (showLoading) setLoading(true);
- const [listResult, latest] = await Promise.all([
- api.getCosBriefings().catch(() => ({ briefings: [] })),
- api.getCosLatestBriefing().catch(() => null)
+ const { data, loading, refetch } = useSocketResource(async () => {
+ const [listResult, briefing] = await Promise.all([
+ api.getCosBriefings(),
+ selectedDate ? api.getCosBriefing(selectedDate) : api.getCosLatestBriefing(),
]);
- setBriefings(listResult.briefings || []);
- if (latest) {
- setCurrentBriefing(latest);
- setSelectedDate(latest.date);
- // Expand all sections by default
- const parsed = parseBriefingMarkdown(latest.content);
- const expanded = {};
- parsed.sections.forEach((_s, i) => { expanded[i] = true; });
- setExpandedSections(expanded);
- }
- if (showLoading) setLoading(false);
- return latest;
- };
-
- useAutoRefetch(
- async () => {
- const latest = await loadData({ showLoading: false });
- if (latest) setGenerationPending(false);
- return latest;
- },
- 5000,
- { enabled: generationPending, immediate: false, pollOnly: true },
- );
+ return { briefings: listResult.briefings || [], briefing };
+ }, {
+ namespace: 'cos',
+ events: BRIEFING_EVENTS,
+ resourceKey: selectedDate,
+ // Daily briefings are persisted by this job's agent, not the weekly digest.
+ matchesEvent: agent => agent?.metadata?.jobId === 'job-daily-briefing',
+ });
+ const briefings = data?.briefings || [];
+ const currentBriefing = data?.briefing;
- const loadBriefing = async (date) => {
- setLoading(true);
- setSelectedDate(date);
- const briefing = await api.getCosBriefing(date).catch(() => null);
- if (briefing) {
- setCurrentBriefing(briefing);
- const parsed = parseBriefingMarkdown(briefing.content);
- const expanded = {};
- parsed.sections.forEach((_s, i) => { expanded[i] = true; });
- setExpandedSections(expanded);
- }
- setLoading(false);
- };
+ useEffect(() => {
+ if (!currentBriefing) return;
+ setGenerationPending(false);
+ const parsed = parseBriefingMarkdown(currentBriefing.content);
+ setExpandedSections(Object.fromEntries(parsed.sections.map((_section, i) => [i, true])));
+ }, [currentBriefing]);
const toggleSection = (idx) => {
setExpandedSections(prev => ({ ...prev, [idx]: !prev[idx] }));
@@ -258,8 +231,8 @@ export default function BriefingTab() {
{briefings.length > 0 && (
<select
aria-label="Date"
- value={selectedDate || ''}
- onChange={(e) => loadBriefing(e.target.value)}
+ value={selectedDate || currentBriefing?.date || ''}
+ onChange={(e) => setSelectedDate(e.target.value)}
className="bg-port-card border border-port-border rounded px-2 py-1 text-sm text-gray-300"
>
{briefings.map(b => (
@@ -279,9 +252,7 @@ export default function BriefingTab() {
/>
)}
<button
- onClick={() => loadData({ showLoading: false }).then((latest) => {
- if (latest) setGenerationPending(false);
- })}
+ onClick={() => refetch()}
className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-card border border-port-border hover:border-port-accent/50 text-gray-300 rounded-lg transition-colors"
>
<RefreshCw size={14} />
diff --git a/client/src/components/cos/tabs/BriefingTab.test.jsx b/client/src/components/cos/tabs/BriefingTab.test.jsx
index c776a54c75..5c3e1c907f 100644
--- a/client/src/components/cos/tabs/BriefingTab.test.jsx
+++ b/client/src/components/cos/tabs/BriefingTab.test.jsx
@@ -7,10 +7,25 @@ import BriefingTab from './BriefingTab';
const api = vi.hoisted(() => ({
getCosBriefings: vi.fn(),
getCosLatestBriefing: vi.fn(),
+ getCosBriefing: vi.fn(),
triggerCosJob: vi.fn(),
}));
const toast = vi.hoisted(() => ({ error: vi.fn() }));
+const socket = vi.hoisted(() => {
+ const handlers = new Map();
+ return {
+ on: (event, handler) => {
+ if (!handlers.has(event)) handlers.set(event, new Set());
+ handlers.get(event).add(handler);
+ },
+ off: (event, handler) => handlers.get(event)?.delete(handler),
+ emit: vi.fn(),
+ receive: (event, payload) => handlers.get(event)?.forEach(handler => handler(payload)),
+ };
+});
+vi.mock('../../../services/socket', () => ({ default: socket }));
+
vi.mock('../../../services/api', () => api);
vi.mock('../../ui/Toast', () => ({ default: toast }));
@@ -66,7 +81,11 @@ describe('BriefingTab empty state', () => {
await act(async () => {});
expect(screen.getByRole('button', { name: 'Generating today’s briefing…' })).toBeDisabled();
- await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(15000); });
+ expect(api.getCosLatestBriefing).toHaveBeenCalledTimes(2);
+ await act(async () => socket.receive('cos:agent:completed', { metadata: { jobId: 'other-job' } }));
+ expect(api.getCosLatestBriefing).toHaveBeenCalledTimes(2);
+ await act(async () => socket.receive('cos:agent:completed', { metadata: { jobId: 'job-daily-briefing' } }));
expect(screen.getByText('Today')).toBeInTheDocument();
});
@@ -97,3 +116,43 @@ describe('BriefingTab empty state', () => {
expect(toast.error).toHaveBeenCalledTimes(1);
});
});
+
+it('reconciles once on reconnect and tab show, and stops reading after unmount', async () => {
+ const view = renderTab();
+ await act(async () => {});
+ expect(api.getCosLatestBriefing).toHaveBeenCalledTimes(1);
+ await act(async () => socket.receive('connect'));
+ expect(api.getCosLatestBriefing).toHaveBeenCalledTimes(2);
+ await act(async () => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await act(async () => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+ document.dispatchEvent(new Event('visibilitychange'));
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ expect(api.getCosLatestBriefing).toHaveBeenCalledTimes(3);
+ view.unmount();
+ await act(async () => socket.receive('cos:agent:completed', { metadata: { jobId: 'job-daily-briefing' } }));
+ await act(async () => socket.receive('connect'));
+ expect(api.getCosLatestBriefing).toHaveBeenCalledTimes(3);
+});
+
+it('keeps the selected historical briefing when a daily job completes', async () => {
+ api.getCosBriefings.mockResolvedValue({ briefings: [{ date: '2026-09-12' }, { date: '2026-09-11' }] });
+ api.getCosLatestBriefing.mockResolvedValue({ date: '2026-09-12', content: '# Latest' });
+ renderTab();
+ await act(async () => {});
+ let resolveOld;
+ api.getCosBriefing.mockReturnValueOnce(new Promise(resolve => { resolveOld = resolve; }));
+ fireEvent.change(screen.getByRole('combobox', { name: 'Date' }), { target: { value: '2026-09-11' } });
+ await act(async () => {});
+ // The route remains mounted while the first historical read is pending.
+ api.getCosBriefing.mockResolvedValue({ date: '2026-09-11', content: '# Historical' });
+ await act(async () => resolveOld({ date: '2026-09-11', content: '# Historical' }));
+ await act(async () => socket.receive('cos:agent:completed', { metadata: { jobId: 'job-daily-briefing' } }));
+ expect(screen.getByText('Historical')).toBeInTheDocument();
+ expect(api.getCosLatestBriefing).toHaveBeenCalledTimes(1);
+ expect(api.getCosBriefing).toHaveBeenLastCalledWith('2026-09-11');
+});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 35fc247f32..3eb4028df0 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -89,7 +89,7 @@ grep -i "what you want to do" client/src/hooks/README.md
|---|---|---|
| `useProcessSnapshot` | PM2 snapshots from entry reads and server pushes, with reconnect/reshow recovery and stale-read protection. | Process lists and native-launch panels; pass an app id for custom PM2 homes. |
| `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. |
-| `useSocketResource` | Initial resource read plus global/room-event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |
+| `useSocketResource` | Initial resource read plus global/room-event, reconnect and tab-show reconciliation; single-flight reads, identity guards, an enabled gate and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |
| `useFableLoomRun` | Revisioned editorial/production snapshots, identity-safe mutation replies and entry/reconnect/reshow recovery. | FableLoom run views. |
| `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. |
| `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. |
diff --git a/client/src/hooks/useSocketResource.js b/client/src/hooks/useSocketResource.js
index fdee28c054..c6b4255f7c 100644
--- a/client/src/hooks/useSocketResource.js
+++ b/client/src/hooks/useSocketResource.js
@@ -11,9 +11,10 @@ const visible = () => document.visibilityState !== 'hidden';
* { reconcile, events: [{ event, payload }] } for targeted invalidation reads.
* Keep events stable (module-level). fetchFn returns data without setting state.
* resourceKey cancels old reads; updateData applies mutation responses and
- * prevents an older in-flight read from overwriting them.
+ * prevents an older in-flight read from overwriting them. enabled=false releases
+ * subscriptions and cancels reads for closed or otherwise inactive consumers.
*/
-export function useSocketResource(fetchFn, { namespace, events, resourceKey = null, matchesEvent = () => true, compare }) {
+export function useSocketResource(fetchFn, { namespace, events, resourceKey = null, matchesEvent = () => true, compare, enabled = true }) {
const [state, setState] = useState({ key: resourceKey, data: null, loading: true, error: null });
const fetchRef = useRef(fetchFn);
const matchesRef = useRef(matchesEvent);
@@ -24,11 +25,12 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nu
const controller = useRef(null);
const refetch = useCallback(() => controller.current?.read(), []);
- useSocketSubscription(namespace, { onResubscribe: () => {
+ useSocketSubscription(namespace, { enabled, onResubscribe: () => {
if (visible()) refetch();
} });
useEffect(() => {
+ if (!enabled) return;
let disposed = false;
let pending = null;
let dirty = false;
@@ -97,7 +99,7 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nu
for (const [event, handler] of handlers) socket.off(event, handler);
if (!namespace) socket.off('connect', reconnect);
};
- }, [namespace, events, resourceKey]);
+ }, [namespace, events, resourceKey, enabled]);
const lastVisibility = useRef(document.visibilityState);
useVisibilityEvent(state => {