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): fix the critical-insight sort and the health-snapshot race
Adam Eivy5fae77424485
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex efdcd4324c..c2d762bd9c 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -203,12 +203,31 @@ export const STATE_MESSAGES = {export const summarizeHealthIssues = (issues) => {if (!Array.isArray(issues) || issues.length === 0) return null;const messages = issues.map((issue) => issue?.message).filter(Boolean);+ // Counts come from `issues`, never from `messages` — a mixed list like+ // [{message:'A'}, {}] has two problems and one description, and counting the+ // descriptions would under-report it as a single issue.+ const plural = issues.length > 1 ? 's' : '';// A message-less issue still has to read as an issue — `null` means "nothing// to report", so callers that already know the list is non-empty never need a// fallback of their own.- if (messages.length === 0) return `${issues.length} health issue${issues.length > 1 ? 's' : ''} detected`;- if (messages.length === 1) return messages[0];- return `${messages.length} health issues: ${messages.join(' · ')}`;+ if (messages.length === 0) return `${issues.length} health issue${plural} detected`;+ if (issues.length === 1) return messages[0];+ return `${issues.length} health issues: ${messages.join(' · ')}`;+};++// Which of two health snapshots to keep. `getCosHealth` reads the *pre-check*+// persisted health while the same fetch batch triggers a fresh server-side check+// whose `cos:health:check` socket event can land first — so the slow read must+// not clobber the fresher socket result. Keep whichever check is newer by+// `lastCheck` (Date.parse normalizes the ISO timestamps so the compare never+// goes lexicographic), keep `prev` when the incoming read has no comparable+// timestamp but `prev` does, and treat a failed read (null) as "keep prev".+export const fresherHealth = (prev, next) => {+ if (!next) return prev ?? null;+ const prevT = Date.parse(prev?.lastCheck ?? '');+ const nextT = Date.parse(next.lastCheck ?? '');+ if (!Number.isNaN(prevT) && (Number.isNaN(nextT) || nextT < prevT)) return prev;+ return next;};// StatCard tone for the Issues tile. `error`-type issues mean something isdiff --git a/client/src/components/cos/constants.test.js b/client/src/components/cos/constants.test.jsindex f9e0e99172..22ac1145ff 100644--- a/client/src/components/cos/constants.test.js+++ b/client/src/components/cos/constants.test.js@@ -15,7 +15,8 @@ import {MODEL_CAPABLE_CLI_REVIEWERS,reviewerLabel,summarizeHealthIssues,- healthIssueTone+ healthIssueTone,+ fresherHealth} from './constants';// These mirror the server's domainBudgets/domainAutonomy helpers so the UI's@@ -244,6 +245,44 @@ describe('summarizeHealthIssues', () => {expect(summarizeHealthIssues([{ type: 'error' }])).toBe('1 health issue detected');expect(summarizeHealthIssues([{ type: 'error' }, {}])).toBe('2 health issues detected');});++ // Counting the descriptions instead of the issues under-reported a mixed+ // list as a single issue, hiding the message-less one entirely.+ it('counts issues, not messages, when only some carry one', () => {+ expect(summarizeHealthIssues([{ message: 'A' }, {}])).toBe('2 health issues: A');+ expect(summarizeHealthIssues([{ message: 'A' }, {}, { message: 'B' }])).toBe('3 health issues: A \u00b7 B');+ });+});++// The slow `getCosHealth` read routinely resolves AFTER the socket event for the+// check that same fetch batch triggered, so "newest wins" is what keeps the+// Issues tile and the status bubble describing the same check.+describe('fresherHealth', () => {+ const older = { lastCheck: '2026-01-01T00:00:00.000Z', issues: [] };+ const newer = { lastCheck: '2026-01-02T00:00:00.000Z', issues: [{ type: 'warning' }] };++ it('takes the newer check', () => {+ expect(fresherHealth(older, newer)).toBe(newer);+ });++ it('keeps the newer previous check against a stale read', () => {+ expect(fresherHealth(newer, older)).toBe(newer);+ });++ it('keeps the last-good check when the read failed', () => {+ expect(fresherHealth(newer, null)).toBe(newer);+ expect(fresherHealth(null, null)).toBeNull();+ });++ it('keeps a timestamped previous check over an untimed read', () => {+ expect(fresherHealth(newer, { issues: [] })).toBe(newer);+ });++ it('accepts any read when there is no comparable previous check', () => {+ const untimed = { issues: [] };+ expect(fresherHealth(null, untimed)).toBe(untimed);+ expect(fresherHealth({ issues: [] }, untimed)).toBe(untimed);+ });});describe('healthIssueTone', () => {diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.jsindex f2f890ca50..0044a46673 100644--- a/client/src/components/cos/index.js+++ b/client/src/components/cos/index.js@@ -1,5 +1,5 @@// Constants-export { TABS, AGENT_STATES, STATE_MESSAGES, MEMORY_TYPES, MEMORY_TYPE_COLORS, summarizeHealthIssues, healthIssueTone } from './constants';+export { TABS, AGENT_STATES, STATE_MESSAGES, MEMORY_TYPES, MEMORY_TYPE_COLORS, summarizeHealthIssues, healthIssueTone, fresherHealth } from './constants';// Avatar/Character Components// The five three.js *CoSAvatar variants are intentionally NOT re-exported:diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex a2f7f28080..5c9181d722 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -18,6 +18,7 @@ import {STATE_MESSAGES,summarizeHealthIssues,healthIssueTone,+ fresherHealth,CoSCharacter,StateLabel,TerminalCoSPanel,@@ -131,6 +132,22 @@ export default function ChiefOfStaff() {setDesktopPanelCollapsed((prev) => !prev);}, [setDesktopPanelCollapsed]);+ // ONE writer for the health snapshot, so the Issues tile, the avatar state and+ // the status bubble can never describe different health checks. The ref is+ // written synchronously alongside the state, which is what lets fetchData run+ // the freshness rule and then derive from the value it actually committed —+ // with a functional updater the merged result was only visible inside the+ // updater, so the derivation below fell back to the raw (possibly older, or+ // null) read. `merge` runs the freshness rule; the socket and manual paths+ // deliver the newest check by definition and set it outright.+ const healthRef = useRef(null);+ const applyHealth = useCallback((next, { merge = false } = {}) => {+ const resolved = merge ? fresherHealth(healthRef.current, next) : next;+ healthRef.current = resolved;+ setHealth(resolved);+ return resolved;+ }, []);+// Derive agent state from system statusconst deriveAgentState = useCallback((statusData, agentsData, healthData) => {if (!statusData?.running) return 'sleeping';@@ -172,21 +189,11 @@ export default function ChiefOfStaff() {// `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 (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 ?? '');- // Keep prev when it is strictly newer, OR when this read has no comparable- // timestamp but prev does — a timestamped health check is fresher than an- // untimed read, so an absent/unparseable lastCheck must not clobber it.- if (!Number.isNaN(prevT) && (Number.isNaN(newT) || newT < prevT)) return prev;- return healthData;- });+ // 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 = applyHealth(healthData, { merge: true });setProviders(providersData.providers || []);setActiveProviderId(providersData.activeProvider || null);// Filter out PortOS Autofixer (it's part of PortOS project)@@ -198,7 +205,7 @@ export default function ChiefOfStaff() {if (insightsData?.insights) setInsights(insightsData.insights);setLoading(false);- const newState = deriveAgentState(statusData, agentsData, healthData);+ 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@@ -206,12 +213,12 @@ export default function ChiefOfStaff() {// to an Active count of 0 with no agent to inspect.setStatusMessage(statusData?.paused? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`- : (newState === 'investigating' && summarizeHealthIssues(healthData?.issues)) || STATE_MESSAGES[newState]);+ : (newState === 'investigating' && summarizeHealthIssues(mergedHealth?.issues)) || STATE_MESSAGES[newState]);// Set active agent metadata for dynamic avatar (use first running agent)const runningAgent = agentsData.find(a => a.status === 'running');setActiveAgentMeta(runningAgent?.metadata || null);- }, [deriveAgentState]);+ }, [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.@@ -361,7 +368,7 @@ export default function ChiefOfStaff() {socket.on('cos:agent:completed', handleAgentCompleted);const handleHealthCheck = (data) => {- setHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });+ 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.@@ -529,7 +536,7 @@ export default function ChiefOfStaff() {});setSpeaking(false);if (result) {- setHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });+ 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 healthdiff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 6dbf61ac55..75cd9707cd 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -668,12 +668,71 @@ describe('ChiefOfStaff Issues card', () => {await act(async () => { await new Promise((resolve) => setTimeout(resolve, 2100)); });});+ // Without these, deleting the `tone` prop would leave every tile neutral gray+ // while the helper's own unit tests stayed green.+ it('colors the tile amber for a warning-only check', async () => {+ renderWithIssues([memoryWarning]);++ for (const card of await issueCards()) {+ expect(card.className).toContain('border-port-warning');+ expect(card.className).not.toContain('border-port-error');+ }+ });++ it('escalates the tile to red when an issue is error-level', async () => {+ renderWithIssues([memoryWarning, { type: 'error', category: 'processes', message: 'example-app failed to auto-restart' }]);++ for (const card of await issueCards()) {+ expect(card.className).toContain('border-port-error');+ }+ });+it('stays a click-through to Health when there are no issues at all', async () => {renderWithIssues([]);for (const card of await issueCards()) {expect(card).toHaveAttribute('title', 'No issues detected — view system health');expect(within(card).getByText('0')).toBeInTheDocument();+ expect(card.className).not.toContain('border-port-warning');+ expect(card.className).not.toContain('border-port-error');+ }+ });++ // fetchData's health read is the SLOW one — it resolves after the socket event+ // for the check that same batch triggered. Everything the page derives from+ // health (tile, avatar state, status bubble) must come from the merged+ // snapshot, or the bubble names an older issue than the tile is counting.+ it('does not let a slow health read clobber a fresher socket-delivered check', async () => {+ const staleWarning = { type: 'warning', category: 'memory', message: 'Stale issue from the older read' };+ api.getCosStatus.mockResolvedValue({ running: true, config, stats: {} });+ // The slow read carries the OLDER timestamp; the socket event below is newer.+ api.getCosHealth.mockResolvedValue({ lastCheck: '2026-01-01T00:00:00.000Z', issues: [staleWarning] });+ render(+ <MemoryRouter initialEntries={['/cos/config']}>+ <Routes>+ <Route path="/cos/:tab" element={<ChiefOfStaff />} />+ </Routes>+ </MemoryRouter>,+ );+ expect(await screen.findByText(staleWarning.message)).toBeInTheDocument();++ const handleHealthCheck = socketStub.on.mock.calls.find(([evt]) => evt === 'cos:health:check')?.[1];+ await act(async () => {+ handleHealthCheck({ metrics: { timestamp: '2026-01-02T00:00:00.000Z' }, issues: [memoryWarning] });+ });+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 2100)); });++ // Now force the slow batch to run again with its stale payload — the merge+ // must keep the socket's newer check, for the tile AND the bubble.+ await act(async () => {+ socketStub.on.mock.calls.find(([evt]) => evt === 'apps:changed')?.[1]?.();+ await new Promise((resolve) => setTimeout(resolve, 50));+ });++ expect(screen.getByText(memoryWarning.message)).toBeInTheDocument();+ expect(screen.queryByText(staleWarning.message)).not.toBeInTheDocument();+ for (const card of await issueCards()) {+ expect(card).toHaveAttribute('title', memoryWarning.message);}});});diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.jsindex 81c5415326..d67e13adec 100644--- a/server/routes/cosInsightRoutes.js+++ b/server/routes/cosInsightRoutes.js@@ -189,9 +189,11 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {});}- // Sort by priority+ // Sort by priority. `??`, not `||` — `critical` ranks 0, and `0 || 5` demoted+ // it below every other priority, so the single most urgent insight sorted LAST+ // and fell off the `slice(0, 5)` below once six insights were open.const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3, info: 4 };- insights.sort((a, b) => (priorityOrder[a.priority] || 5) - (priorityOrder[b.priority] || 5));+ insights.sort((a, b) => (priorityOrder[a.priority] ?? 5) - (priorityOrder[b.priority] ?? 5));res.json({insights: insights.slice(0, 5), // Max 5 insightsdiff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.jsindex ae61478e9a..7feaf62122 100644--- a/server/routes/cosInsightRoutes.test.js+++ b/server/routes/cosInsightRoutes.test.js@@ -52,6 +52,7 @@ import * as autonomousJobs from '../services/autonomousJobs.js';import * as productivity from '../services/productivity.js';import * as goalProgress from '../services/goalProgress.js';import * as decisionLog from '../services/decisionLog.js';+import * as notifications from '../services/notifications.js';describe('CoS Insight Routes', () => {let app;@@ -62,6 +63,9 @@ describe('CoS Insight Routes', () => {app.use('/api/cos', insightRoutes);vi.clearAllMocks();cos.getPendingAgentFeedbackCount.mockResolvedValue(0);+ // clearAllMocks keeps implementations, so a per-test override would leak+ // into later tests — restore the default empty notification list here.+ notifications.getNotifications.mockResolvedValue([]);});describe('GET /api/cos/productivity', () => {@@ -203,6 +207,33 @@ describe('CoS Insight Routes', () => {}));});+ // The priority sort used `priorityOrder[p] || 5`, and `critical` ranks 0 —+ // so `0 || 5` demoted the single most urgent insight below every other+ // priority. It sorted LAST and, once six insights were open, fell off the+ // `slice(0, 5)` entirely. Only reachable now that a health issue can+ // actually be `critical`.+ it('sorts a critical insight first and keeps it within the top-5 slice', async () => {+ cos.getAllTasks.mockResolvedValue({+ user: { grouped: { pending: [], blocked: [{ id: 'b1', description: 'Blocked task' }] } },+ cos: { awaitingApproval: [{ id: 'a1', description: 'Approve me' }], grouped: { pending: [], blocked: [] } }+ });+ taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [{ type: 'flaky' }] });+ cos.getPendingAgentFeedbackCount.mockResolvedValue(2);+ productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });+ notifications.getNotifications.mockResolvedValue([{ type: 'briefing_ready' }]);+ cos.runHealthCheck.mockResolvedValue({+ issues: [{ type: 'error', category: 'processes', message: 'example-app failed to auto-restart' }]+ });++ const response = await request(app).get('/api/cos/actionable-insights');++ expect(response.status).toBe(200);+ // Six insights were built, so a demoted critical would have been sliced off.+ expect(response.body.totalCount).toBe(6);+ expect(response.body.insights[0]).toMatchObject({ type: 'health', priority: 'critical' });+ expect(response.body.insights.map(i => i.priority)).toEqual(['critical', 'high', 'high', 'medium', 'low']);+ });+it('should handle errors gracefully in parallel calls', async () => {cos.getAllTasks.mockRejectedValue(new Error('fail'));taskLearning.getLearningInsights.mockRejectedValue(new Error('fail'));