Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): guard fetchData against clobbering fresher socket health with a stale pre-check read
[._.]/ Adam Eivyd1159e674b22
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2c530c5585..c0fb75bcd8 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 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).+- **[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. Because that same insights call triggers a fresh server health check whose `cos:health:check` socket emit can land before `fetchData`'s own (pre-check) `getCosHealth` read resolves, `fetchData` now keeps whichever health check is newer by `lastCheck` instead of overwriting a fresher socket-delivered result with its stale read. 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, a regression guard asserting the `cos:health:check` socket handler does not re-fetch (no loop), and the stale-health-overwrite guard.diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 5153d694c6..ae748f6f8e 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -141,7 +141,18 @@ export default function ChiefOfStaff() {setStatus(statusData);setTasks(tasksData);setAgents(agentsData);- setHealth(healthData);+ // `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 setHealth can land in `prev` before this runs. Don't let+ // this fetch's older read clobber that fresher result; keep whichever health+ // check is newer by lastCheck (lexicographic on ISO / numeric both order by+ // time). A null read (fetch failed) still applies, matching prior behavior.+ setHealth(prev =>+ (prev?.lastCheck && healthData?.lastCheck && healthData.lastCheck < prev.lastCheck)+ ? prev+ : healthData,+ );setProviders(providersData.providers || []);// Filter out PortOS Autofixer (it's part of PortOS project)setApps(appsData.filter(a => a.id !== 'portos-autofixer'));@@ -415,8 +426,14 @@ export default function ChiefOfStaff() {setSpeaking(false);if (result) {setHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });- // Refresh the banner's health-issue count without a full fetchData (which- // would clobber the health-specific status message set below).+ // Refresh the banner's server-derived health-issue count without a full+ // fetchData (which would clobber the health-specific status message set+ // below). This deliberately runs a second health check inside the insights+ // endpoint — a small, user-initiated redundancy; on a single-user install+ // two back-to-back checks return identical issues, and the fresher one's+ // socket emit wins the lastCheck guard in fetchData, so health stays+ // consistent. The alternative (client-computing the insight) isn't viable:+ // insights aggregate approvals/learning, not just health.refreshInsights();toast.success('Health check complete');if (result.issues?.length > 0) {diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex d76b3eb852..2a86c3505f 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -169,4 +169,32 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {expect(api.getCosActionableInsights.mock.calls.length).toBeGreaterThan(before),);});++ it('does not let a stale fetchData health read clobber a fresher one', async () => {+ // The insights call inside fetchData triggers a fresh server health check+ // whose socket emit can update `health` before fetchData's own getCosHealth+ // read (which sees the pre-check state) resolves. fetchData must keep the+ // newer health by lastCheck instead of overwriting it with the stale read.+ api.getCosHealth.mockResolvedValue({+ lastCheck: '2026-01-01T00:00:02Z',+ issues: [{ type: 'error', category: 'memory', message: 'FRESH_ISSUE' }],+ });+ renderAt('health');+ // Initial fetchData paints the fresh issue.+ expect(await screen.findByText('FRESH_ISSUE')).toBeInTheDocument();++ // 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');+ expect(handleAppsChanged).toBeTypeOf('function');+ await act(async () => {+ handleAppsChanged();+ await Promise.resolve();+ });++ // The guard keeps the fresher health — the issue must NOT disappear.+ await waitFor(() => expect(api.getApps.mock.calls.length).toBeGreaterThan(1));+ expect(screen.getByText('FRESH_ISSUE')).toBeInTheDocument();+ expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();+ });});