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

address review (codex): don't refreshInsights from the cos:health:check socket handler (feedback loop)

[._.]/ Adam Eivya1f3fe4cdf12
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e13a2aa0f4..2c530c5585 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -117,4 +117,4 @@
- **Fix the app-manager Git tab's "Clean N merged" button counting worktree-locked branches, so cleanup deleted zero and toasted "No merged branches to clean up".** `getBranches` marked a local branch `merged: true` from `git branch --merged` alone, but `deleteMergedBranches` (correctly) skips branches checked out in a worktree — `git branch -d` can't delete them. On any install with active CoS-agent/claim worktrees, those merged-but-locked branches inflated the button's count while yielding no deletions. `getBranches` now also returns a `worktree` flag (branch checked out in another worktree), the Git tab's `localMergedCount` counts only `merged && !worktree` so the button reflects what the server will actually delete, and locked branches render a `worktree` badge next to `merged` so the user sees why they linger. Server + client tests cover the count and badge.
-- **[issue-2654] Lift the CoS actionable-insights fetch into `ChiefOfStaff.fetchData` so the banner refreshes for the whole staleness class.** `ActionableInsightsBanner` owned its own `/cos/actionable-insights` fetch on a 60s `useAutoRefetch` poll, decoupled from the parent's 30s task poll, so its server-derived counts (blocked, approvals, "N health issues") lagged any parent-owned data change until that poll. A prior fix bridged only the TasksTab mutation path via an `insightsRefreshKey` counter; socket-driven task changes, agent spawn/completion, and health checks stayed stale. Insights are now fetched inside `ChiefOfStaff.fetchData`'s `Promise.all` and passed down as an `insights` prop, making the banner presentational (it keeps only dismiss/expand/unblock UI state); its unblock path calls `onRefresh` up instead of owning a `refetch()`. Because agent spawn/completion already call `fetchData`, they refresh the banner for free; the two paths that intentionally do a targeted `setState` rather than a full refetch — the `cos:health:check`/manual health-check handlers (to preserve their own status messaging) and the `cos:tasks:user:changed` socket handler — call a lightweight insights-only `refreshInsights()` so a newly-found or cleared health issue / daemon-driven task change reflects immediately. A failed/transient insights fetch (`null`) preserves the last-good array (matching the retired poll's behavior); a legitimately-empty `[]` clears the banner. Retires `insightsRefreshKey`, `refreshTasks`'s signal bump, the banner's `refreshKey` prop, its `didMountRef` skip-mount effect, and its `useAutoRefetch` self-poll. Tests cover the prop-driven render, null/empty gating, the unblock-up path, and the health/task socket refreshes.
+- **[issue-2654] Lift the CoS actionable-insights fetch into `ChiefOfStaff.fetchData` so the banner refreshes for the whole staleness class.** `ActionableInsightsBanner` owned its own `/cos/actionable-insights` fetch on a 60s `useAutoRefetch` poll, decoupled from the parent's 30s task poll, so its server-derived counts (blocked, approvals, "N health issues") lagged any parent-owned data change until that poll. A prior fix bridged only the TasksTab mutation path via an `insightsRefreshKey` counter; socket-driven task changes, agent spawn/completion, and health checks stayed stale. Insights are now fetched inside `ChiefOfStaff.fetchData`'s `Promise.all` and passed down as an `insights` prop, making the banner presentational (it keeps only dismiss/expand/unblock UI state); its unblock path calls `onRefresh` up instead of owning a `refetch()`. Because agent spawn/completion already call `fetchData`, they refresh the banner for free. The manual "Run health check" button updates `health` locally (to keep its own status messaging) rather than calling `fetchData`, so it also calls a lightweight insights-only `refreshInsights()` — a one-shot re-pull that keeps the banner's "N health issues" count fresh without waiting for the poll. The `cos:health:check` **socket** handler deliberately does NOT call `refreshInsights()`: the `/cos/actionable-insights` endpoint itself runs a health check (`cos.runHealthCheck` → `cosEvents 'health:check'` → socket `cos:health:check`), so a socket-driven refresh would re-emit the very event that triggered it — an unbounded health-check/request/socket feedback loop. Daemon-driven health/task changes refresh on the next `fetchData` poll (unchanged from before). A failed/transient insights fetch (`null`) preserves the last-good array (matching the retired poll's behavior); a legitimately-empty `[]` clears the banner. Retires `insightsRefreshKey`, `refreshTasks`'s signal bump, the banner's `refreshKey` prop, its `didMountRef` skip-mount effect, and its `useAutoRefetch` self-poll. Tests cover the prop-driven render, null/empty gating, the unblock-up path, the manual-health-button refresh, and a regression guard asserting the `cos:health:check` socket handler does not re-fetch (no loop).
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 71646bf5e7..5153d694c6 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -162,12 +162,18 @@ export default function ChiefOfStaff() {
setActiveAgentMeta(runningAgent?.metadata || null);
}, [deriveAgentState]);
- // Targeted insights-only refresh for parent state changes that DON'T route
- // through fetchData — health checks and socket-driven task changes update
- // `health`/`tasks` locally (to keep their own status messaging / avoid a full
- // refetch) rather than calling fetchData. The banner's server-derived counts
- // (blocked, health issues) would otherwise lag those until the 30s poll, so we
- // re-pull just insights here. Same last-good/silent semantics as fetchData.
+ // Targeted insights-only refresh for the manual "Run health check" button,
+ // which updates `health` locally (to keep its own status messaging) rather
+ // than calling fetchData — so the banner's server-derived "N health issues"
+ // count would otherwise lag until the 30s poll. Same last-good/silent
+ // semantics as fetchData.
+ //
+ // IMPORTANT: never wire this to the `cos:health:check` SOCKET handler. The
+ // /cos/actionable-insights endpoint itself runs a health check
+ // (cos.runHealthCheck → cosEvents 'health:check' → socket 'cos:health:check'),
+ // so a socket-driven refreshInsights would re-emit the very event that
+ // triggered it — an unbounded health-check/request/socket feedback loop.
+ // Daemon-driven health checks refresh the banner on the next fetchData poll.
const refreshInsights = useCallback(async () => {
const insightsData = await api.getCosActionableInsights({ silent: true }).catch(() => null);
if (insightsData?.insights) setInsights(insightsData.insights);
@@ -212,9 +218,6 @@ export default function ChiefOfStaff() {
const handleTasksUserChanged = (data) => {
setTasks(prev => ({ ...prev, user: data }));
- // Socket-driven task changes (daemon status flips, blocks/unblocks) don't
- // go through fetchData, so refresh the banner's blocked/approval counts.
- refreshInsights();
};
socket.on('cos:tasks:user:changed', handleTasksUserChanged);
@@ -276,9 +279,9 @@ export default function ChiefOfStaff() {
const handleHealthCheck = (data) => {
setHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });
- // Health feeds the banner's "N health issues" insight; refresh it so a
- // newly-found (or cleared) issue reflects immediately, not on the 30s poll.
- refreshInsights();
+ // Do NOT refreshInsights() here — the insights endpoint runs a health
+ // check that re-emits this very socket event (see refreshInsights above),
+ // which would loop. The banner's health count refreshes on the next poll.
if (data.issues?.length > 0) {
setAgentState('investigating');
setStatusMessage(`Health check: ${data.issues.length} issue${data.issues.length > 1 ? 's' : ''} found`);
@@ -327,7 +330,7 @@ export default function ChiefOfStaff() {
socket.off('cos:log', handleCosLog);
socket.off('apps:changed', handleAppsChanged);
};
- }, [socket, fetchData, refreshInsights]);
+ }, [socket, fetchData]);
const handleStart = async () => {
const result = await api.startCos({ silent: true }).catch(err => {
diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsx
index 493f593cb7..d76b3eb852 100644
--- a/client/src/pages/ChiefOfStaff.test.jsx
+++ b/client/src/pages/ChiefOfStaff.test.jsx
@@ -16,7 +16,12 @@ const api = vi.hoisted(() => ({
getCosActionableInsights: vi.fn(),
getCosBudgetUsage: vi.fn(),
forceCosEvaluate: vi.fn(),
+ forceHealthCheck: vi.fn(),
updateCosConfig: vi.fn(),
+ // HealthTab (rendered by the manual "Run Check" test) + its ProviderStatusCard.
+ getCosTodayActivity: vi.fn(),
+ getCosLearning: vi.fn(),
+ getProviderStatuses: vi.fn(),
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
const socketStub = vi.hoisted(() => ({ connected: false, on: vi.fn(), off: vi.fn(), emit: vi.fn() }));
@@ -61,6 +66,10 @@ beforeEach(() => {
api.getApps.mockResolvedValue([]);
api.getCosLearningSummary.mockResolvedValue(null);
api.getCosActionableInsights.mockResolvedValue({ insights: [] });
+ api.forceHealthCheck.mockResolvedValue({ metrics: { timestamp: 1 }, issues: [] });
+ api.getCosTodayActivity.mockResolvedValue({ isRunning: false, stats: { completed: 0 } });
+ api.getCosLearning.mockResolvedValue(null);
+ api.getProviderStatuses.mockResolvedValue({ providers: {} });
api.getCosBudgetUsage.mockResolvedValue({ usage: {} });
});
@@ -104,16 +113,27 @@ describe('ChiefOfStaff handleForceEvaluate', () => {
});
});
-// #2654: the banner is now prop-driven, and paths that don't go through
-// fetchData (socket-driven health checks / task changes) must still refresh the
-// server-derived insight counts so the banner doesn't lag until the 30s poll.
+// #2654: the banner is now prop-driven. The manual "Run Check" button updates
+// `health` locally (keeping its own status message), so it must re-pull insights
+// to refresh the banner's health-issue count. But the SOCKET `cos:health:check`
+// handler must NOT re-pull insights: the /cos/actionable-insights endpoint runs a
+// health check that re-emits that same socket event, so a socket-driven refresh
+// would be an unbounded feedback loop (regression guard for the review finding).
describe('ChiefOfStaff insight freshness (#2654)', () => {
const getSocketHandler = (event) => {
const entry = socketStub.on.mock.calls.find(([evt]) => evt === event);
return entry?.[1];
};
- it('refreshes actionable insights when a socket health-check arrives', async () => {
+ const renderAt = (tab) => render(
+ <MemoryRouter initialEntries={[`/cos/${tab}`]}>
+ <Routes>
+ <Route path="/cos/:tab" element={<ChiefOfStaff />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ it('does NOT re-fetch insights on a socket health-check (no feedback loop)', async () => {
renderConfigTab();
// The initial fetchData pulls insights once; wait for it before firing.
await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());
@@ -122,29 +142,29 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
const handleHealthCheck = getSocketHandler('cos:health:check');
expect(handleHealthCheck).toBeTypeOf('function');
// Empty issues avoids the >0 branch's setTimeout(setSpeaking) so no state
- // update escapes act; refreshInsights fires unconditionally either way.
+ // update escapes act.
await act(async () => {
handleHealthCheck({ metrics: { timestamp: 1 }, issues: [] });
});
+ // Give any (buggy) async refresh a tick to fire before asserting it didn't.
+ await act(async () => { await Promise.resolve(); });
- // Health doesn't call fetchData (that would clobber its status message) — it
- // re-pulls just insights, so the call count must advance past the initial.
- await waitFor(() =>
- expect(api.getCosActionableInsights.mock.calls.length).toBeGreaterThan(before),
- );
+ // A socket-driven re-fetch here would loop against the health-checking
+ // endpoint — the count must stay put; the poll refreshes the banner instead.
+ expect(api.getCosActionableInsights.mock.calls.length).toBe(before);
});
- it('refreshes actionable insights on a socket task change', async () => {
- renderConfigTab();
+ it('re-fetches insights when the manual "Run Check" button runs a health check', async () => {
+ renderAt('health');
await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());
const before = api.getCosActionableInsights.mock.calls.length;
- const handleTasksUserChanged = getSocketHandler('cos:tasks:user:changed');
- expect(handleTasksUserChanged).toBeTypeOf('function');
- await act(async () => {
- handleTasksUserChanged({ tasks: [], grouped: {} });
- });
+ const button = await screen.findByRole('button', { name: /Run Check/i });
+ fireEvent.click(button);
+ // The manual path awaits forceHealthCheck, sets health locally, then calls
+ // refreshInsights() — a one-shot, loop-free insights re-pull.
+ await waitFor(() => expect(api.forceHealthCheck).toHaveBeenCalledWith({ silent: true }));
await waitFor(() =>
expect(api.getCosActionableInsights.mock.calls.length).toBeGreaterThan(before),
);