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): drop on-demand insights refresh; harden fetchData health guard
[._.]/ Adam Eivye52634ab0ebc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c0fb75bcd8..ae87cf1311 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. 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.+- **[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()`. The banner's counts refresh **only** through `fetchData`: the 30s poll, task mutations (TasksTab `onRefresh`), the unblock-up path, and agent spawn/completion (which already call `fetchData`). There is deliberately no on-demand "refresh just the insights" path, because `/cos/actionable-insights` runs a health check that **auto-restarts errored PM2 processes** (`server/services/cosHealthMonitor.js`) and re-emits `cos:health:check` — so refreshing from the `cos:health:check` socket handler would loop, and refreshing from the manual "Run Check" button would fire a second process-restart ~1s after the button's own check. Daemon/manual health changes therefore refresh the banner on the next `fetchData` poll (a 2× improvement over the retired 60s self-poll, and the cadence skew is gone). A failed/transient insights fetch (`null`) preserves the last-good array; 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` keeps whichever health check is newer by `lastCheck` (`Date.parse`-normalized), and preserves the last-good health when its own read fails — instead of blanking a fresher socket-delivered result. 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, guards asserting neither the `cos:health:check` socket handler nor the manual button re-fetches insights (no loop, no second restart), and the stale/failed-read health-overwrite guards.diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex ae748f6f8e..4b99f0b33c 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -146,13 +146,15 @@ export default function ChiefOfStaff() {// 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,- );+ // check is newer by lastCheck (Date.parse normalizes the ISO timestamps so+ // the compare never goes lexicographic). A failed read (null) keeps the+ // last-good health rather than blanking a fresher socket-delivered one.+ setHealth(prev => {+ if (!healthData) return prev ?? null;+ const prevT = Date.parse(prev?.lastCheck ?? '');+ const newT = Date.parse(healthData.lastCheck ?? '');+ return (!Number.isNaN(prevT) && !Number.isNaN(newT) && newT < prevT) ? prev : healthData;+ });setProviders(providersData.providers || []);// Filter out PortOS Autofixer (it's part of PortOS project)setApps(appsData.filter(a => a.id !== 'portos-autofixer'));@@ -173,22 +175,15 @@ export default function ChiefOfStaff() {setActiveAgentMeta(runningAgent?.metadata || null);}, [deriveAgentState]);- // 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);- }, []);+ // 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).// Redirect unknown tab IDs to the default tab — `activeTab !== tab` only// when the param failed validation and fell back.@@ -290,9 +285,9 @@ export default function ChiefOfStaff() {const handleHealthCheck = (data) => {setHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });- // 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.+ // 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.if (data.issues?.length > 0) {setAgentState('investigating');setStatusMessage(`Health check: ${data.issues.length} issue${data.issues.length > 1 ? 's' : ''} found`);@@ -426,15 +421,10 @@ export default function ChiefOfStaff() {setSpeaking(false);if (result) {setHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });- // 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();+ // 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).toast.success('Health check complete');if (result.issues?.length > 0) {setStatusMessage(`Health: ${result.issues.length} issue${result.issues.length > 1 ? 's' : ''} detected`);diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 2a86c3505f..c4c122f388 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -113,12 +113,13 @@ describe('ChiefOfStaff handleForceEvaluate', () => {});});-// #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).+// #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.describe('ChiefOfStaff insight freshness (#2654)', () => {const getSocketHandler = (event) => {const entry = socketStub.on.mock.calls.find(([evt]) => evt === event);@@ -154,7 +155,7 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {expect(api.getCosActionableInsights.mock.calls.length).toBe(before);});- it('re-fetches insights when the manual "Run Check" button runs a health check', async () => {+ it('does NOT re-fetch insights on the manual "Run Check" button (no second process-restart)', async () => {renderAt('health');await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());const before = api.getCosActionableInsights.mock.calls.length;@@ -162,12 +163,12 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {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.+ // 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.await waitFor(() => expect(api.forceHealthCheck).toHaveBeenCalledWith({ silent: true }));- await waitFor(() =>- expect(api.getCosActionableInsights.mock.calls.length).toBeGreaterThan(before),- );+ await act(async () => { await Promise.resolve(); });+ expect(api.getCosActionableInsights.mock.calls.length).toBe(before);});it('does not let a stale fetchData health read clobber a fresher one', async () => {@@ -197,4 +198,25 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {expect(screen.getByText('FRESH_ISSUE')).toBeInTheDocument();expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();});++ it('preserves last-good health when a fetchData health read fails (null)', async () => {+ api.getCosHealth.mockResolvedValue({+ lastCheck: '2026-01-01T00:00:02Z',+ issues: [{ type: 'error', category: 'memory', message: 'FRESH_ISSUE' }],+ });+ renderAt('health');+ expect(await screen.findByText('FRESH_ISSUE')).toBeInTheDocument();++ // A failed health read (rejects → .catch → null) must not blank the banner.+ api.getCosHealth.mockRejectedValue(new Error('boom'));+ const handleAppsChanged = getSocketHandler('apps:changed');+ await act(async () => {+ handleAppsChanged();+ await Promise.resolve();+ });++ await waitFor(() => expect(api.getApps.mock.calls.length).toBeGreaterThan(1));+ expect(screen.getByText('FRESH_ISSUE')).toBeInTheDocument();+ expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();+ });});