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
fix: show unavailable CoS health and stale results (#9745)
Adam Eivy3ac8ca33f3e2
diff --git a/client/src/components/cos/ActionableInsightsBanner.jsx b/client/src/components/cos/ActionableInsightsBanner.jsxindex edc1b1192a..5eea7221ee 100644--- a/client/src/components/cos/ActionableInsightsBanner.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.jsx@@ -247,7 +247,9 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, onUrgent</span>)}- <ProvenanceChip {...insightProvenance(primaryInsight.type)} />+ {primaryInsight.type === 'health-unavailable' ? (+ <span className="text-xs text-port-warning">Observation failed</span>+ ) : <ProvenanceChip {...insightProvenance(primaryInsight.type)} />}</div>{primaryInsight.description && !isExpanded && (<p className="text-xs text-gray-400 mt-0.5 line-clamp-1">diff --git a/client/src/components/cos/ActionableInsightsBanner.test.jsx b/client/src/components/cos/ActionableInsightsBanner.test.jsxindex 3d20be35c3..262bd91b28 100644--- a/client/src/components/cos/ActionableInsightsBanner.test.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.test.jsx@@ -92,6 +92,17 @@ describe('ActionableInsightsBanner (presentational)', () => {expect(screen.getByTestId('location')).toHaveTextContent('/cos/agents?feedback=needs-feedback');});+ it('renders unavailable health as an observation failure with a Health retry link', () => {+ renderBanner({ insights: [{+ type: 'health-unavailable', priority: 'high', icon: 'AlertTriangle', title: 'CoS health unavailable',+ description: 'Could not observe system health.', action: { label: 'Check Health', route: '/cos/health' },+ }] }, { withLocation: true });+ expect(screen.getByText('Observation failed')).toBeInTheDocument();+ expect(screen.queryByText('Data-backed')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Check Health' }));+ expect(screen.getByTestId('location')).toHaveTextContent('/cos/health');+ });+it('hides insights the user dismisses', () => {renderBanner({insights: [diff --git a/client/src/components/cos/tabs/HealthTab.jsx b/client/src/components/cos/tabs/HealthTab.jsxindex 5e2f6c9042..b6482ff24d 100644--- a/client/src/components/cos/tabs/HealthTab.jsx+++ b/client/src/components/cos/tabs/HealthTab.jsx@@ -4,7 +4,7 @@ import * as api from '../../../services/api';import { formatDateTime } from '../../../utils/formatters';import ProviderStatusCard from './ProviderStatusCard';-export default function HealthTab({ health, healthLoading = false, onCheck }) {+export default function HealthTab({ health, healthLoading = false, healthError = null, onCheck }) {const [learning, setLearning] = useState(null);const [loadingLearning, setLoadingLearning] = useState(true);const [backfilling, setBackfilling] = useState(false);@@ -145,12 +145,22 @@ export default function HealthTab({ health, healthLoading = false, onCheck }) {</button></div>+ {healthError && (+ <div role="alert" className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-3 mb-2 text-port-warning text-sm">+ <p className="font-medium">{health ? 'Health results stale' : 'CoS health unavailable'}</p>+ <p className="text-xs mt-1">{healthError}</p>+ </div>+ )}{healthLoading ? (<div className="text-center py-4 text-gray-500"><RefreshCw size={16} className="animate-spin mx-auto mb-2" />Loading health...</div>- ) : !health?.issues || health.issues.length === 0 ? (+ ) : !Array.isArray(health?.issues) ? (+ !healthError && <p className="text-port-warning text-sm">Health has not been observed. Run Check to retry.</p>+ ) : healthError && health.issues.length === 0 ? (+ <p className="text-gray-400 text-sm">The last successful check found no issues. Current health is unknown.</p>+ ) : health.issues.length === 0 ? (<div className="bg-port-success/10 border border-port-success/30 rounded-lg p-4 text-center"><CheckCircle className="w-8 h-8 text-port-success mx-auto mb-2" /><p className="text-port-success font-medium text-sm">All Systems Healthy</p>diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex db33586187..1dbfe6238d 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -152,6 +152,7 @@ export default function ChiefOfStaff() {const [taskHistoryRevision, setTaskHistoryRevision] = useState(0);const [health, setHealth] = useState(null);const [healthLoaded, setHealthLoaded] = useState(false);+ const [healthError, setHealthError] = useState(null);const [providers, setProviders] = useState([]);// Which provider an unpinned task actually runs on — the Schedule tab names it// on the "Default" option and resolves model/effort choices against it.@@ -251,16 +252,32 @@ export default function ChiefOfStaff() {// 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.+ // null) read. HTTP responses merge by check time; socket events deliver the+ // completed check directly. Only a valid accepted observation clears errors.const healthRef = useRef(null);+ // A read started before a successful socket/manual observation cannot mark+ // that newer result unavailable when its own transport later fails.+ const healthObservationRef = useRef(0);+ const markHealthUnavailable = useCallback((observation = healthObservationRef.current) => {+ if (observation !== healthObservationRef.current) return;+ setHealthLoaded(true);+ setHealthError('Could not observe system health. Run Check to retry.');+ }, []);const applyHealth = useCallback((next, { merge = false } = {}) => {+ if (!Array.isArray(next?.issues)) {+ markHealthUnavailable();+ return healthRef.current;+ }const resolved = merge ? fresherHealth(healthRef.current, next) : next;+ if (resolved === next) {+ healthObservationRef.current += 1;+ setHealthError(null);+ }healthRef.current = resolved;setHealth(resolved);setHealthLoaded(true);return resolved;- }, []);+ }, [markHealthUnavailable]);// The single write path for the provider list, mirroring `applyHealth` above:// stamping the settle flag anywhere else could set `providers` without it.@@ -341,7 +358,13 @@ export default function ChiefOfStaff() {needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTask, signal: controller.signal, silent: true }).catch(() => null) : Promise.resolve(null),readAgents(controller),]);- const healthRead = api.getCosHealth().catch(() => null).then((data) => {+ const healthObservation = healthObservationRef.current;+ const healthRead = api.getCosHealth({ signal: controller.signal, silent: true }).catch(() => null).then((data) => {+ if (controller.signal.aborted || queryRef.current !== queryKey) return null;+ if (!Array.isArray(data?.issues)) {+ markHealthUnavailable(healthObservation);+ return null;+ }// Health is independently useful to the Health tab. Commit it as soon// as its own read settles instead of making that tab wait for the slower// actionable-insights request in the same batch.@@ -416,7 +439,7 @@ export default function ChiefOfStaff() {if (pending.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshPageData();});return pending.promise;- }, [activeTab, queryKey, selectedTask, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, applyProviders, applyApps, readAgents]);+ }, [activeTab, queryKey, selectedTask, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, markHealthUnavailable, applyProviders, applyApps, readAgents]);// Coalesce event bursts into a read of the visible queue and scalar shell// status. Insights use persisted health; invalidation never runs PM2 repair.@@ -883,21 +906,25 @@ export default function ChiefOfStaff() {setAgentState('investigating');setStatusMessage("Running system health check...");const speakingGeneration = setSpeakingFor();+ const healthObservation = healthObservationRef.current;const result = await api.forceHealthCheck({ silent: true }).catch(err => {toast.error(err.message);return null;});setSpeakingFor(0, speakingGeneration);- if (result) {- applyHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });+ if (Array.isArray(result?.issues)) {+ const checkedHealth = applyHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues }, { merge: true });// The Health route does not load the Tasks-only insights banner.toast.success('Health check complete');- if (result.issues?.length > 0) {- setStatusMessage(summarizeHealthIssues(result.issues));+ if (checkedHealth.issues.length > 0) {+ setStatusMessage(summarizeHealthIssues(checkedHealth.issues));} else {setAgentState('sleeping');setStatusMessage("Health check passed - all systems OK");}+ } else {+ markHealthUnavailable(healthObservation);+ if (healthObservation === healthObservationRef.current) setStatusMessage('System health unavailable');}};@@ -954,9 +981,11 @@ export default function ChiefOfStaff() {const healthIssues = health?.issues || [];const issuesStatProps = {label: 'Issues',- value: healthIssues.length,- tone: healthIssueTone(healthIssues),- title: summarizeHealthIssues(healthIssues) || 'No issues detected — view system health',+ value: healthError || !healthLoaded ? '—' : healthIssues.length,+ tone: healthError ? 'warning' : healthIssueTone(healthIssues),+ title: healthError ? 'Health unavailable — view last results and retry'+ : !healthLoaded ? 'Health not observed yet — view system health'+ : summarizeHealthIssues(healthIssues) || 'No issues detected — view system health',onClick: () => navigate('/cos/health'),};@@ -1486,7 +1515,7 @@ export default function ChiefOfStaff() {{activeTab === 'health' && (<div role="tabpanel" id="tabpanel-health" aria-labelledby="tab-health"><Suspense fallback={<TabLoadFallback label="health" />}>- <HealthTab health={health} healthLoading={!healthLoaded} onCheck={handleHealthCheck} />+ <HealthTab health={health} healthLoading={!healthLoaded} healthError={healthError} onCheck={handleHealthCheck} /></Suspense></div>)}diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 829b56d328..1b74d75027 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -100,7 +100,7 @@ beforeEach(() => {api.getCosStatus.mockResolvedValue({ running: false, config, stats: {} });api.getCosTasks.mockResolvedValue({ user: null, cos: null });api.getCosAgents.mockResolvedValue([]);- api.getCosHealth.mockResolvedValue(null);+ api.getCosHealth.mockResolvedValue({ issues: [] });api.getProviders.mockResolvedValue({ providers: [] });api.getApps.mockResolvedValue([]);api.getCosLearningSummary.mockResolvedValue(null);@@ -170,7 +170,13 @@ const renderSettledAt = async (tab) => {return result;};-const renderSettledConfigTab = () => renderSettledAt('config');+const renderSettledConfigTab = async () => {+ // The page shell settles before this lazy tab's import. Resolve that import+ // outside DOM-query deadlines so contended transforms cannot time out the+ // Force Evaluate tests before their action even exists.+ await act(async () => { await import('../components/cos/tabs/ConfigTab'); });+ return renderSettledAt('config');+};// #4144 — `/cos` is an `isFullWidth` route, so its `<main>` is a bare// `relative overflow-hidden`. The old centered `h-64` BrailleSpinner reserved@@ -583,7 +589,7 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();});- it('preserves last-good health when a fetchData health read fails (null)', async () => {+ it('marks retained results stale after a failed read and clears failure on a socket observation', async () => {api.getCosHealth.mockResolvedValue({lastCheck: '2026-01-01T00:00:02Z',issues: [{ type: 'error', category: 'memory', message: 'FRESH_ISSUE' }],@@ -602,6 +608,54 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {await waitFor(() => expect(api.getCosHealth.mock.calls.length).toBeGreaterThan(1));expect(screen.getByText('FRESH_ISSUE')).toBeInTheDocument();expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();+ expect(await screen.findByRole('alert')).toHaveTextContent('Health results stale');+ await act(async () => {+ getSocketHandler('cos:health:check')({ metrics: { timestamp: '2026-01-01T00:00:03Z' }, issues: [] });+ });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText('All Systems Healthy')).toBeInTheDocument();+ });++ it('shows first-load failure as unavailable and recovers after a successful HTTP read', async () => {+ api.getCosHealth.mockRejectedValue(new Error('private failure detail'));+ await renderSettledAt('health');+ expect(await screen.findByRole('alert')).toHaveTextContent('CoS health unavailable');+ expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();+ expect(screen.queryByText('No issues detected')).not.toBeInTheDocument();+ expect(screen.queryByText('private failure detail')).not.toBeInTheDocument();+ expect(api.getCosHealth).toHaveBeenCalledWith(expect.objectContaining({ silent: true, signal: expect.any(AbortSignal) }));++ api.getCosHealth.mockResolvedValue({ issues: [] });+ await act(async () => { getSocketHandler('cos:config:changed')(); });+ expect(await screen.findByText('All Systems Healthy')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });++ it('does not present last-good empty results as healthy after a manual check fails', async () => {+ await renderSettledAt('health');+ expect(await screen.findByText('All Systems Healthy')).toBeInTheDocument();+ api.forceHealthCheck.mockRejectedValueOnce(new Error('failed check'));+ fireEvent.click(screen.getByRole('button', { name: 'Run Check' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Health results stale');+ expect(screen.getByText(/Current health is unknown/)).toBeInTheDocument();+ expect(screen.queryByText('All Systems Healthy')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Run Check' }));+ expect(await screen.findByText('All Systems Healthy')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });++ it('ignores a failed HTTP read superseded by a successful socket observation', async () => {+ let rejectHealth;+ api.getCosHealth.mockReturnValue(new Promise((resolve, reject) => { rejectHealth = reject; }));+ await renderSettledAt('health');+ expect(await screen.findByText('Loading health...')).toBeInTheDocument();+ await act(async () => {+ getSocketHandler('cos:health:check')({ metrics: { timestamp: '2026-01-01T00:00:03Z' }, issues: [] });+ rejectHealth(new Error('late transport failure'));+ });+ expect(screen.getByText('All Systems Healthy')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();});});diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 93a988707c..d444a0c5b4 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -230,7 +230,7 @@ export const deleteOrchestrationProfile = (id, options = {}) => request(`/settinmethod: 'DELETE',...options,});-export const getCosHealth = () => request('/cos/health');+export const getCosHealth = (options = {}) => request('/cos/health', options);export const forceHealthCheck = (options = {}) => request('/cos/health/check', { method: 'POST', ...options });export const getCosAgents = ({ active = false, ...options } = {}) => request(`/cos/agents${active ? '?active=1' : ''}`, options);export const getCosCompletedAgents = ({ cursor, limit = 25, feedback = false, ...options } = {}) =>diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.jsindex ed8735faab..ff6e7d794a 100644--- a/server/routes/cosInsightRoutes.js+++ b/server/routes/cosInsightRoutes.js@@ -32,7 +32,7 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {const [tasksData, learningSummary, healthCheck, notificationsModule, pendingFeedbackCount, leftoverFindings, agents] = await Promise.all([cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),- (cachedHealth ? cos.getHealthStatus() : cos.runHealthCheck()).catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),+ (cachedHealth ? cos.getHealthStatus() : cos.runHealthCheck()).catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return null; }),import('../services/notifications.js').catch(err => { console.error(`❌ Failed to load notifications: ${err.message}`); return null; }),cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; }),detectIdleLeftoverBranches().catch(err => { console.error(`❌ Failed to detect leftover branches: ${err.message}`); return []; }),@@ -81,8 +81,18 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {}// 3. Health issues- const healthIssues = healthCheck?.issues || [];- if (healthIssues.length > 0) {+ const healthUnavailable = !Array.isArray(healthCheck?.issues);+ const healthIssues = healthUnavailable ? [] : healthCheck.issues;+ if (healthUnavailable) {+ insights.push({+ type: 'health-unavailable',+ priority: 'high',+ icon: 'AlertTriangle',+ title: 'CoS health unavailable',+ description: 'Could not observe system health. Open Health and run a check to retry.',+ action: { label: 'Check Health', route: '/cos/health' }+ });+ } else if (healthIssues.length > 0) {// `type`, not `severity` — runHealthCheck stamps issues `error`/`warning`// and never writes a `severity` field, so the old check matched nothing and// a process that failed to auto-restart banner'd at `medium` alongside a@@ -203,7 +213,8 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {res.json({insights: insights.slice(0, 5), // Max 5 insightshasActionableItems: insights.some(i => ['critical', 'high'].includes(i.priority)),- totalCount: insights.length+ totalCount: insights.length,+ unavailableSources: healthUnavailable ? [{ source: 'health', code: 'HEALTH_UNAVAILABLE' }] : []});}));diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.jsindex 0c114197b1..6ef0426e0e 100644--- a/server/routes/cosInsightRoutes.test.js+++ b/server/routes/cosInsightRoutes.test.js@@ -103,7 +103,8 @@ describe('CoS Insight Routes', () => {expect(response.status).toBe(200);expect(cos.getHealthStatus).toHaveBeenCalledTimes(1);expect(cos.runHealthCheck).not.toHaveBeenCalled();- expect(Array.isArray(response.body.insights)).toBe(true);+ expect(response.body.insights).toEqual([]);+ expect(response.body.unavailableSources).toEqual([]);});it('should return actionable insights sorted by priority', async () => {@@ -258,7 +259,7 @@ describe('CoS Insight Routes', () => {expect(response.body.insights.map(i => i.priority)).toEqual(['critical', 'high', 'high', 'medium', 'low']);});- it('should handle errors gracefully in parallel calls', async () => {+ it('keeps health observation failure visible when parallel calls fail', async () => {cos.getAllTasks.mockRejectedValue(new Error('fail'));taskLearning.getLearningInsights.mockRejectedValue(new Error('fail'));cos.runHealthCheck.mockRejectedValue(new Error('fail'));@@ -266,7 +267,25 @@ describe('CoS Insight Routes', () => {const response = await request(app).get('/api/cos/actionable-insights');expect(response.status).toBe(200);- expect(response.body.insights).toEqual([]);+ expect(response.body.insights).toEqual([expect.objectContaining({ type: 'health-unavailable', priority: 'high' })]);+ expect(response.body.hasActionableItems).toBe(true);+ expect(response.body.totalCount).toBe(1);+ expect(response.body.unavailableSources).toEqual([{ source: 'health', code: 'HEALTH_UNAVAILABLE' }]);+ });++ it.each(['', '?cachedHealth=1'])('retains other insights while health is unavailable on %s', async query => {+ cos.getAllTasks.mockResolvedValue({ user: null, cos: { awaitingApproval: [{ id: 'a1', description: 'Example approval' }] } });+ taskLearning.getLearningInsights.mockResolvedValue(null);+ cos.runHealthCheck.mockRejectedValue(new Error('private failure details'));+ cos.getHealthStatus.mockRejectedValue(new Error('private failure details'));++ const response = await request(app).get(`/api/cos/actionable-insights${query}`);++ expect(response.status).toBe(200);+ expect(response.body.insights.map(i => i.type)).toEqual(['approval', 'health-unavailable']);+ expect(response.body.unavailableSources).toEqual([{ source: 'health', code: 'HEALTH_UNAVAILABLE' }]);+ expect(JSON.stringify(response.body)).not.toContain('private failure details');+ if (query) expect(cos.runHealthCheck).not.toHaveBeenCalled();});});