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

feat: push health and capability readiness updates (#8553)

[._.]/ Adam Eivye5d5eb61f11f
diff --git a/client/src/pages/CapabilityMap.jsx b/client/src/pages/CapabilityMap.jsx
index 68d9180317..e2f34c0d07 100644
--- a/client/src/pages/CapabilityMap.jsx
+++ b/client/src/pages/CapabilityMap.jsx
@@ -7,7 +7,10 @@ import {
import * as api from '../services/api';
import PageSkeleton from '../components/ui/PageSkeleton';
import NetworkSetupGuide from '../components/NetworkSetupGuide.jsx';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
+
+const READINESS_EVENTS = ['capabilities:changed', 'localLlm:progress'];
+const matchesReadinessEvent = (payload, event) => event !== 'localLlm:progress' || ['complete', 'error'].includes(payload?.event);
// Status presentation. Mirrors the server's CAPABILITY_STATUS tiers.
const STATUS_STYLE = {
@@ -50,9 +53,9 @@ function CapabilityRow({ cap }) {
export default function CapabilityMap() {
const [savedPreference, setSavedPreference] = useState(null);
const [saving, setSaving] = useState(false);
- const { data, loading } = useAutoRefetch(
+ const { data, loading, error } = useSocketResource(
() => api.getCapabilities({ silent: true }),
- 20_000,
+ { namespace: 'readiness', events: READINESS_EVENTS, matchesEvent: matchesReadinessEvent },
);
if (loading) {
@@ -91,6 +94,7 @@ export default function CapabilityMap() {
return (
<div className="space-y-4">
+ {error && <p role="status" className="text-port-warning">Capability refresh failed. Showing the last available reading.</p>}
<div className="flex items-center justify-between gap-3 flex-wrap">
<h2 className="text-xl font-bold text-white flex items-center gap-2">
<ListChecks size={20} />
diff --git a/client/src/pages/CapabilityMap.test.jsx b/client/src/pages/CapabilityMap.test.jsx
index 9813d7213a..aa7c9866da 100644
--- a/client/src/pages/CapabilityMap.test.jsx
+++ b/client/src/pages/CapabilityMap.test.jsx
@@ -3,8 +3,8 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { awaitEnabled } from '../test/enabledBarrier.js';
-vi.mock('../hooks/useAutoRefetch', () => ({
- useAutoRefetch: () => ({
+vi.mock('../hooks/useSocketResource', () => ({
+ useSocketResource: () => ({
loading: false,
data: {
networkSetupPreference: 'tailscale',
diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsx
index c8946221eb..a17211fc90 100644
--- a/client/src/pages/SystemHealthPage.jsx
+++ b/client/src/pages/SystemHealthPage.jsx
@@ -5,7 +5,8 @@ import * as api from '../services/api';
import toast from '../components/ui/Toast';
import PageSkeleton from '../components/ui/PageSkeleton';
import Banner from '../components/ui/Banner';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
+
import { useHealthWarningDismiss } from '../hooks/useHealthWarningDismiss.jsx';
import { useSystemResourceReport } from '../hooks/useSystemResourceReport.js';
import StoragePanel from '../components/system-resources/StoragePanel.jsx';
@@ -17,6 +18,8 @@ import { buildPageNavTabs } from '../lib/pageNavTabs.js';
import RouteTabsHeader from '../components/ui/RouteTabsHeader';
import { HEALTH_STYLE, pctTone, barTone, resolveHealthThresholds } from '../lib/healthStyle.js';
+const READINESS_EVENTS = ['system:health:changed'];
+
// Every alert names its own next step. The server tags each warning with a
// `type` (server/routes/systemHealth.js), so the banner can carry the link that
// actually resolves it instead of leaving the user to hunt for the right page.
@@ -113,9 +116,9 @@ function SystemHealthOverview() {
// successful save so the next refetch re-seeds with the persisted thresholds.
const draftSeededRef = useRef(false);
- const { data: health, loading, refetch } = useAutoRefetch(
+ const { data: health, loading, error, refetch } = useSocketResource(
() => api.getSystemHealth({ silent: true }),
- 15_000,
+ { namespace: 'readiness', events: READINESS_EVENTS },
);
const { dismissingType, handleDismissWarning } = useHealthWarningDismiss(refetch);
@@ -288,6 +291,8 @@ function SystemHealthOverview() {
) : null}
</section>
+ {error && <p role="status" className="text-port-warning">Health refresh failed. Showing the last available reading.</p>}
+
<MediaCapacityPanel media={health.media} />
<BuildStampPanel uptimeFormatted={health.system.uptimeFormatted} />
diff --git a/client/src/pages/readinessViews.test.jsx b/client/src/pages/readinessViews.test.jsx
new file mode 100644
index 0000000000..0dd3b4ab38
--- /dev/null
+++ b/client/src/pages/readinessViews.test.jsx
@@ -0,0 +1,129 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+const { handlers, socket, getSystemHealth, getCapabilities } = vi.hoisted(() => {
+ const handlers = new Map();
+ return {
+ handlers,
+ socket: {
+ on: vi.fn((event, fn) => {
+ if (!handlers.has(event)) handlers.set(event, new Set());
+ handlers.get(event).add(fn);
+ }),
+ off: vi.fn((event, fn) => handlers.get(event)?.delete(fn)),
+ emit: vi.fn(),
+ },
+ getSystemHealth: vi.fn(),
+ getCapabilities: vi.fn(),
+ };
+});
+vi.mock('../services/socket', () => ({ default: socket }));
+vi.mock('../services/api', () => ({ getSystemHealth, getCapabilities }));
+vi.mock('../hooks/useSystemResourceReport.js', () => ({
+ useSystemResourceReport: () => ({ report: null, cleanup: {} }),
+}));
+vi.mock('../components/system-resources/MediaCapacityPanel.jsx', () => ({ default: () => null }));
+vi.mock('../components/system-resources/BuildStampPanel.jsx', () => ({ default: () => null }));
+import SystemHealthPage from './SystemHealthPage';
+import CapabilityMap from './CapabilityMap';
+
+const health = message => ({
+ overallHealth: 'warning',
+ warnings: [{ type: 'process', message }],
+ system: {
+ uptimeFormatted: '1h',
+ memory: { usagePercent: 30, usedFormatted: '3 GB', totalFormatted: '10 GB' },
+ cpu: { usagePercent: 5, cores: 4, loadAvg1m: 0.2 },
+ disk: null,
+ },
+ topProcesses: [],
+});
+const capabilities = message => ({
+ capabilities: [{ id: 'calendar', label: 'Calendar', status: 'warn', summary: message, settingsPath: '/calendar' }],
+});
+const emit = event => act(async () => {
+ for (const fn of handlers.get(event) || []) fn({});
+});
+const visibility = state => act(async () => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: state });
+ document.dispatchEvent(new Event('visibilitychange'));
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+});
+afterEach(() => {
+ cleanup();
+ handlers.clear();
+ vi.useRealTimers();
+});
+
+describe.each([
+ ['health', SystemHealthPage, getSystemHealth, health, 'system:health:changed'],
+ ['capabilities', CapabilityMap, getCapabilities, capabilities, 'capabilities:changed'],
+])('%s readiness view', (_name, Page, read, snapshot, event) => {
+ it('renders service changes without polling, reconciles once on reconnect/reshow and releases listeners', async () => {
+ read.mockResolvedValue(snapshot('Initial reading'));
+ let view;
+ await act(async () => { view = render(<MemoryRouter><Page /></MemoryRouter>); });
+ expect(screen.getByText('Initial reading')).toBeInTheDocument();
+ expect(read).toHaveBeenCalledTimes(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(read).toHaveBeenCalledTimes(1);
+
+ read.mockResolvedValue(snapshot('Changed reading'));
+ await emit(event);
+ expect(screen.getByText('Changed reading')).toBeInTheDocument();
+ expect(read).toHaveBeenCalledTimes(2);
+ await emit('connect');
+ expect(read).toHaveBeenCalledTimes(3);
+ await visibility('hidden');
+ await emit(event);
+ expect(read).toHaveBeenCalledTimes(3);
+ await visibility('visible');
+ expect(read).toHaveBeenCalledTimes(4);
+ await visibility('visible');
+ expect(read).toHaveBeenCalledTimes(4);
+
+ view.unmount();
+ expect(socket.emit).toHaveBeenCalledWith('readiness:unsubscribe');
+ expect(handlers.get(event)?.size).toBe(0);
+ expect(handlers.get('connect')?.size).toBe(0);
+ await emit(event);
+ await visibility('hidden');
+ await visibility('visible');
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(read).toHaveBeenCalledTimes(4);
+ });
+
+ it('recovers an initial failure and marks a failed later read stale until a successful event', async () => {
+ read.mockRejectedValueOnce(new Error('Unavailable'));
+ await act(async () => { render(<MemoryRouter><Page /></MemoryRouter>); });
+ expect(screen.getByText(/unavailable\./i)).toBeInTheDocument();
+ read.mockResolvedValue(snapshot('Recovered reading'));
+ await emit('connect');
+ expect(screen.getByText('Recovered reading')).toBeInTheDocument();
+ read.mockRejectedValueOnce(new Error('Unavailable'));
+ await emit(event);
+ expect(screen.getByText(/Showing the last available reading/)).toBeInTheDocument();
+ expect(screen.getByText('Recovered reading')).toBeInTheDocument();
+ await emit(event);
+ expect(screen.queryByText(/Showing the last available reading/)).not.toBeInTheDocument();
+ });
+
+ it('coalesces invalidations during an in-flight read into one trailing reconciliation', async () => {
+ let resolve;
+ read.mockReturnValueOnce(new Promise(done => { resolve = done; }));
+ await act(async () => { render(<MemoryRouter><Page /></MemoryRouter>); });
+ await emit(event);
+ await emit(event);
+ expect(read).toHaveBeenCalledTimes(1);
+ read.mockResolvedValue(snapshot('Latest reading'));
+ await act(async () => { resolve(snapshot('Old reading')); });
+ expect(read).toHaveBeenCalledTimes(2);
+ expect(screen.getByText('Latest reading')).toBeInTheDocument();
+ });
+});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index bf7a4b54d7..42a9a9c57b 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -49,6 +49,26 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
summary: 'Invalidate updater status after runtime, configuration or external git ref changes.',
payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
},
+ 'system:health:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate health after a service change or changed shared readiness sample.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'capabilities:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate capabilities after a persisted change or changed readiness sample.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'readiness:subscribe': {
+ direction: 'client-to-server',
+ summary: 'Observe health and capability readiness while a view is mounted.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'readiness:unsubscribe': {
+ direction: 'client-to-server',
+ summary: 'Release readiness observation; the last subscriber stops the observer.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
'brain:changed': {
direction: 'server-to-client',
summary: 'Invalidate Brain summary/settings after a persisted change.',
diff --git a/server/routes/capabilities.js b/server/routes/capabilities.js
index 6f7ac3fac2..33b8c489f6 100644
--- a/server/routes/capabilities.js
+++ b/server/routes/capabilities.js
@@ -1,129 +1,9 @@
import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
-import {
- buildCapabilityRows,
- summarizeCapabilities,
- summarizeSetupCapabilities,
-} from '../lib/capabilityMap.js';
-import { getAllProviders, getProviderById } from '../services/providers.js';
-import { getProviderPrerequisiteReadinessMap } from '../services/providerPrerequisites.js';
-import { getProviderReadinessMap } from '../services/providerReadiness.js';
-import { getAllProviderStatuses } from '../services/providerStatus.js';
-import { listAccounts as listCalendarAccounts } from '../services/calendarAccounts.js';
-import { listAccounts as listMessageAccounts } from '../services/messageAccounts.js';
-import { countMemories } from '../services/memoryBackend.js';
-import { getConfig as getCosConfig } from '../services/cos.js';
-import { getVoiceConfig } from '../services/voice/config.js';
-import { getNetworkExposureSetupStatus } from '../lib/networkExposure.js';
-import { getGenomeSummary } from '../services/genome.js';
-import { getSettings } from '../services/settings.js';
-import * as telegram from '../services/telegram.js';
-import * as telegramBridge from '../services/telegramBridge.js';
-import { getAppStatusSummary } from '../services/appProcessStatus.js';
+import { getCapabilitiesSnapshot } from '../services/capabilitiesSnapshot.js';
const router = Router();
-
-// Resolve whether a memory-embedding provider is actually reachable-by-config
-// (mirrors memoryEmbeddings.initConfig) without firing the live LM Studio probe
-// — the probe auto-loads a model as a side effect, which a read-only status
-// page must not trigger.
-async function resolveEmbeddingProviderConfigured() {
- const cosConfig = await getCosConfig().catch(() => ({}));
- const providerId = cosConfig?.embeddingProviderId || 'lmstudio';
- const provider = await getProviderById(providerId).catch(() => null);
- // Mirror memoryEmbeddings.initConfig exactly: it keys off `endpoint` alone and
- // does NOT gate on `enabled`, so embeddings still generate from a disabled-but-
- // endpoint'd provider. Checking `enabled` here would misreport that as "off".
- return !!provider?.endpoint;
-}
-
-async function resolveTelegram() {
- const settings = await getSettings().catch(() => ({}));
- const method = settings?.telegram?.method || 'manual';
- if (method === 'mcp-bridge') {
- const status = telegramBridge.getStatus();
- return { method, hasToken: status.hasBotToken, hasChatId: status.hasChatId, connected: status.connected };
- }
- const status = telegram.getStatus();
- return {
- method,
- hasToken: !!settings?.secrets?.telegram?.token,
- hasChatId: !!settings?.telegram?.chatId,
- connected: status.connected,
- };
-}
-
-// GET /api/capabilities — capability map of every connected system.
router.get('/', asyncHandler(async (req, res) => {
- const providersPromise = getAllProviders().catch(() => ({ providers: [] }));
- const providerPrerequisiteReadinessPromise = providersPromise.then((data) => {
- const providers = Array.isArray(data?.providers) ? data.providers : [];
- const enabled = providers.filter((provider) => provider?.enabled !== false);
- return getProviderPrerequisiteReadinessMap(providers, { candidates: enabled });
- }).catch(() => null);
- const providerLocalReadinessPromise = providersPromise.then((data) => {
- const providers = Array.isArray(data?.providers) ? data.providers : [];
- const enabled = providers.filter((provider) => provider?.enabled !== false);
- return getProviderReadinessMap(enabled);
- }).catch(() => null);
-
- const [
- providersData,
- providerPrerequisiteReadiness,
- providerLocalReadiness,
- providerStatuses,
- calendarAccounts,
- messageAccounts,
- memoryCount,
- embeddingProviderConfigured,
- voiceConfig,
- genome,
- telegramStatus,
- appSummary,
- network,
- settings,
- ] = await Promise.all([
- providersPromise,
- providerPrerequisiteReadinessPromise,
- providerLocalReadinessPromise,
- Promise.resolve().then(() => getAllProviderStatuses()).catch(() => ({})),
- listCalendarAccounts().catch(() => []),
- listMessageAccounts().catch(() => []),
- countMemories({ status: 'active' }).catch(() => 0),
- resolveEmbeddingProviderConfigured().catch(() => false),
- getVoiceConfig().catch(() => ({})),
- getGenomeSummary().catch(() => ({ uploaded: false })),
- resolveTelegram().catch(() => ({})),
- getAppStatusSummary().catch(() => ({ total: 0 })),
- getNetworkExposureSetupStatus().catch(() => ({})),
- getSettings(),
- ]);
-
- const rows = buildCapabilityRows({
- providers: providersData?.providers ?? [],
- providerPrerequisiteReadiness,
- providerLocalReadiness,
- providerStatuses,
- calendarAccounts,
- messageAccounts,
- memoryCount: Number(memoryCount) || 0,
- embeddingProviderConfigured,
- voiceConfig,
- network,
- genome,
- telegram: telegramStatus,
- appSummary,
- });
-
- res.json({
- timestamp: new Date().toISOString(),
- summary: summarizeCapabilities(rows),
- optionalSummary: summarizeCapabilities(rows.filter((row) => row.setupRequired !== true && row.id !== 'network')),
- setup: summarizeSetupCapabilities(rows),
- capabilities: rows,
- network,
- networkSetupPreference: settings.networkSetupPreference || null,
- });
+ res.json(await getCapabilitiesSnapshot());
}));
-
export default router;
diff --git a/server/routes/capabilities.test.js b/server/routes/capabilities.test.js
index 4fbde8f74c..57569ae83d 100644
--- a/server/routes/capabilities.test.js
+++ b/server/routes/capabilities.test.js
@@ -114,8 +114,8 @@ describe('GET /api/capabilities', () => {
getGenomeSummary.mockRejectedValueOnce(new Error('disk gone'));
const res = await request(makeApp()).get('/api/capabilities');
expect(res.status).toBe(200);
- // the failed source falls back to "not set up" rather than 500-ing the page
- expect(byId(res.body, 'genome').status).toBe('unconfigured');
+ // A failed probe is unavailable, not proof that the integration is absent.
+ expect(byId(res.body, 'genome')).toMatchObject({ status: 'warn', summary: 'Readiness unavailable — probe failed' });
// unrelated rows are unaffected
expect(byId(res.body, 'providers').configured).toBe(true);
});
@@ -124,7 +124,7 @@ describe('GET /api/capabilities', () => {
countMemories.mockRejectedValueOnce(new Error('boom'));
const res = await request(makeApp()).get('/api/capabilities');
expect(res.status).toBe(200);
- expect(byId(res.body, 'brain').detail.memoryCount).toBe(0);
+ expect(byId(res.body, 'brain')).toMatchObject({ status: 'warn', summary: 'Readiness unavailable — probe failed' });
});
it('keeps provider setup incomplete when strict prerequisite probing fails', async () => {
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index 355d453fea..c05ce9c50f 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -1,78 +1,20 @@
+import { getSystemHealthSnapshot } from '../services/systemHealthSnapshot.js';
import { Router } from 'express';
import os from 'os';
-import { statfs } from 'fs/promises';
-import { listProcessesStrict } from '../services/pm2.js';
-import { getAppStatusSummary, annotateExpectedExit } from '../services/appProcessStatus.js';
-import * as cos from '../services/cos.js';
+
import { getSelf } from '../services/instanceIdentity.js';
-import { checkHealth } from '../lib/db.js';
+
import { getCurrentVersion } from '../services/updateChecker.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { getMemoryStats } from '../lib/memoryStats.js';
-import { formatBytes, formatDuration } from '../lib/fileUtils.js';
-import { parseFilesystemStats } from '../lib/fileCore.js';
+
import { validateRequest, systemHealthWarningParamsSchema, systemHealthWarningDismissSchema } from '../lib/validation.js';
import { getSettingsWithStatus, updateSettingsWith } from '../services/settings.js';
-import { checkGhHealth } from '../services/github.js';
+
import { isAuthEnabled } from '../services/auth.js';
import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';
import { getActiveProcessing } from '../services/activeProcessing.js';
-import { getMediaCapacity } from '../services/mediaCapacity.js';
-import { runningAgentsByTaskId, unclaimedTaskIds } from '../lib/cosSpawnWindow.js';
-import { getBuildIdentity } from '../lib/buildIdentity.js';
-import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
-
-// Disk capacity remains actionable. Memory thresholds are retained on the wire
-// for older clients, but no longer generate warnings or degrade health.
-const DEFAULT_THRESHOLDS = {
- memoryWarn: 85,
- memoryCritical: 95,
- diskWarn: 90,
- diskCritical: 98
-};
-
-// When a stale dismissal cannot be removed, remember the exact record that
-// needs pruning. A matching recurrence remains visible until a later health
-// read successfully removes that same persisted value.
-const pendingDismissalPrunes = new Map();
-const sameDismissal = (left, right) => JSON.stringify(left) === JSON.stringify(right);
-// Dashboard warnings are recomputed fresh on every read (nothing about them is
-// persisted), so "dismiss" can't delete a row — it has to remember, per warning
-// TYPE, the exact message that was dismissed. A later read matching that same
-// (type, message) pair stays suppressed; a DIFFERENT message for the same type
-// (severity escalated, a different process started crash-looping) is a new
-// occurrence and is shown again automatically. Keyed by type rather than a
-// generated id because each health check emits at most one warning per type.
-//
-// Thresholds and dismissals both live under settings.health, so one read
-// covers both — GET /health/details used to call getSettings() twice (once
-// per concern), paying for two deep-clones of the settings cache on every
-// dashboard poll.
-async function loadHealthSettings() {
- const status = await getSettingsWithStatus().catch(() => {
- console.error('❌ Failed to read system health settings; default thresholds will be used');
- return { corrupt: true, settings: {} };
- });
- const settingsAvailable = status?.corrupt === false
- && status.settings
- && typeof status.settings === 'object'
- && !Array.isArray(status.settings);
- const h = settingsAvailable ? (status.settings.health || {}) : {};
- const dismissedWarnings = h.dismissedWarnings;
- return {
- thresholdsAvailable: Boolean(settingsAvailable),
- thresholds: {
- memoryWarn: Number(h.memoryWarn) || DEFAULT_THRESHOLDS.memoryWarn,
- memoryCritical: Number(h.memoryCritical) || DEFAULT_THRESHOLDS.memoryCritical,
- diskWarn: Number(h.diskWarn) || DEFAULT_THRESHOLDS.diskWarn,
- diskCritical: Number(h.diskCritical) || DEFAULT_THRESHOLDS.diskCritical
- },
- dismissedWarnings: dismissedWarnings && typeof dismissedWarnings === 'object' && !Array.isArray(dismissedWarnings)
- ? dismissedWarnings
- : {}
- };
-}
+import { getBuildIdentity } from '../lib/buildIdentity.js';
async function assertHealthSettingsWritable() {
const status = await getSettingsWithStatus().catch(() => ({ corrupt: true }));
@@ -154,327 +96,9 @@ router.get('/health', asyncHandler(async (req, res) => {
* Returns system metrics, app status, and CoS status for dashboard display
*/
router.get('/health/details', asyncHandler(async (req, res) => {
- const startTime = Date.now();
- const failedProbe = Symbol('failed health probe');
-
- // Gather data in parallel
- const [pm2Processes, appStatusSummary, cosStatus, cosPendingTaskIds, cosAgents, self, dbHealth, version, diskStats, memStats, healthSettings, forgeHealth, mediaCapacity, reviewerConfigHealth] = await Promise.all([
- listProcessesStrict().catch(() => null),
- getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),
- cos.getStatus().catch((error) => {
- console.error('Chief of Staff health probe failed', error);
- return failedProbe;
- }),
- // Queue depth is read here rather than taken off `getStatus()`, which has no
- // such field — `cosStatus.queueLength` never existed, so the widget's
- // "N queued" was dead and always rendered 0. Both reads ride the same
- // `loadState()`/parse caches `getStatus()` above already warmed.
- cos.getPendingTaskIds().catch(() => null),
- cos.getAgents().catch(() => null),
- getSelf().catch(() => null),
- checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),
- getCurrentVersion().catch(() => null),
- statfs('/').catch((error) => {
- console.error('Root filesystem health probe failed', error);
- return failedProbe;
- }),
- getMemoryStats(),
- loadHealthSettings(),
- checkGhHealth().catch(() => ({ status: 'error', ok: false, detail: 'Health check failed', remedy: null, checkedAt: null })),
- // Media-lane capacity never fails the health report: an unreadable GPU probe
- // degrades to `null`, which the UI renders as unknown rather than as idle.
- getMediaCapacity().catch(() => null),
- import('../services/codeReview.js')
- .then(({ getReviewerConfigHealth }) => getReviewerConfigHealth())
- .catch(() => ({ status: 'unknown', configFaults: {} }))
- ]);
- const { thresholds, dismissedWarnings, thresholdsAvailable } = healthSettings;
-
- const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);
- const cpuLoad = os.loadavg()[0]; // 1-minute load average
- const cpuCount = os.cpus().length;
- const cpuUsagePercent = Math.round((cpuLoad / cpuCount) * 100);
-
- // Disk usage (root filesystem).
- // bavail = blocks available to unprivileged users (what the user can actually fill).
- // Derive used/usagePercent from the same figure so `used + free === total` and
- // the UI's percent corresponds to the displayed `free`.
- const parsedDisk = diskStats === failedProbe ? null : parseFilesystemStats(diskStats);
- const disk = parsedDisk && {
- total: parsedDisk.total,
- used: parsedDisk.used,
- free: parsedDisk.free,
- usagePercent: parsedDisk.usagePercent,
- };
-
- // Process status summary from PM2. Processes whose exit is expected (a desktop
- // app the user closed) are excluded from the FAILURE-bearing counts: a quit game
- // window would otherwise force overallHealth to 'critical' below and light up
- // the dashboard widget and the OpenWorld HUD until the PM2 entry is manually
- // cleared. `expectedExit` describes a process's exit *semantics*, not its
- // liveness — so `online` counts every process, exempt or not, or a *running*
- // desktop app would sit in `total` and in no status bucket at all and the
- // dashboard would read "5/6 · all running" with all six up. Resource totals
- // likewise cover every process. See issue #2991.
- // When PM2 read fails, pm2Processes is null and we set processStats to null
- // to signal unavailable rather than zero.
- let processStats = null;
- let annotated = [];
- let supervised = [];
- if (pm2Processes !== null) {
- annotated = await annotateExpectedExit(pm2Processes);
- supervised = annotated.filter(p => !p.expectedExit);
- processStats = {
- total: pm2Processes.length,
- online: annotated.filter(p => p.status === 'online').length,
- stopped: supervised.filter(p => p.status === 'stopped').length,
- errored: supervised.filter(p => p.status === 'errored').length,
- // A desktop app that exited (cleanly as `stopped`, or `errored` on a
- // force-quit) — reported on its own rather than as a failure.
- desktopExited: annotated.filter(
- p => p.expectedExit && ['errored', 'stopped'].includes(p.status)
- ).length,
- totalMemory: pm2Processes.reduce((sum, p) => sum + (p.memory || 0), 0),
- totalCpu: pm2Processes.reduce((sum, p) => sum + (p.cpu || 0), 0),
- totalRestarts: pm2Processes.reduce((sum, p) => sum + (p.restarts || 0), 0),
- unstableRestarts: supervised.reduce((sum, p) => sum + (p.unstableRestarts || 0), 0)
- };
- }
-
- // App status summary — PM2-managed apps only (Xcode/iOS-native projects
- // have no detectable runtime state, so they're tracked under `unmanaged`
- // and excluded from the running denominator)
- const appStats = appStatusSummary;
-
- // Determine overall health status. Each condition below records its
- // severity on the warning itself rather than mutating `overallHealth`
- // inline, because a dismissed warning (see loadDismissedWarnings above)
- // must not count toward the badge — overallHealth is derived once, after
- // dismissals are filtered out, from whatever warnings remain visible.
- const rawWarnings = [];
-
- // Memory occupancy and CPU load describe work, not a health failure.
-
- if (!thresholdsAvailable) {
- rawWarnings.push({
- type: 'health-settings',
- severity: 'warning',
- message: 'System health settings are unavailable; default thresholds are being used and saved warning dismissals were ignored.',
- dismissible: false
- });
- }
-
- if (diskStats === failedProbe) {
- rawWarnings.push({ type: 'probe-unavailable', source: 'disk', status: 'unavailable', severity: 'warning', message: 'Disk status unavailable', dismissible: false });
- }
- if (cosStatus === failedProbe) {
- rawWarnings.push({ type: 'probe-unavailable', source: 'cos', status: 'unavailable', severity: 'warning', message: 'Chief of Staff status unavailable', dismissible: false });
- }
- if (pm2Processes === null) {
- rawWarnings.push({ type: 'probe-unavailable', source: 'pm2', status: 'unavailable', severity: 'warning', message: 'Process manager (PM2) status unavailable', dismissible: false });
- }
-
- if (disk) {
- if (disk.usagePercent >= thresholds.diskCritical) {
- rawWarnings.push({ type: 'disk', severity: 'critical', message: `Disk usage at or above ${thresholds.diskCritical}%` });
- } else if (disk.usagePercent >= thresholds.diskWarn) {
- rawWarnings.push({ type: 'disk', severity: 'warning', message: `Disk usage at or above ${thresholds.diskWarn}%` });
- }
- }
-
- if (processStats) {
- if (processStats.errored > 0) {
- rawWarnings.push({ type: 'process', severity: 'critical', message: `${processStats.errored} process(es) errored` });
- }
-
- if (processStats.unstableRestarts > 0) {
- const crashing = supervised.filter(p => (p.unstableRestarts || 0) > 0).map(p => p.name);
- const plural = processStats.unstableRestarts === 1 ? '' : 's';
- rawWarnings.push({
- type: 'restarts',
- severity: 'warning',
- message: `${processStats.unstableRestarts} crash-loop restart${plural} (${crashing.join(', ')})`
- });
- }
- }
-
- // A degraded app summary means PM2 couldn't be read for one or more homes, so
- // those apps' online/stopped status is unknown — surface it rather than letting
- // the counts silently read as "everything not started."
- if (appStats.degraded) {
- const unknown = appStats.unknown || 0;
- rawWarnings.push({ type: 'apps', severity: 'warning', message: `App status unavailable for ${unknown} app(s) — PM2 read failed` });
- }
-
- if (!dbHealth.connected) {
- rawWarnings.push({ type: 'database', severity: 'warning', message: `PostgreSQL disconnected${dbHealth.error ? `: ${dbHealth.error}` : ''}` });
- } else if (!dbHealth.hasSchema) {
- rawWarnings.push({ type: 'database', severity: 'warning', message: 'PostgreSQL connected but schema missing' });
- }
-
- // A `gh` that cannot reach the forge does not fail loudly anywhere else: the
- // call sites that read pull requests and issues swallow the error into an
- // empty list, so a blocked or unauthenticated CLI looks exactly like a repo
- // with nothing open — and an agent asked to file a PR reports success having
- // filed none. Warn only when gh is present but unusable; an install that
- // never had gh has opted out of those features rather than broken them.
- if (!forgeHealth.ok && forgeHealth.status !== 'not-installed') {
- rawWarnings.push({
- type: 'forge',
- severity: 'warning',
- message: `GitHub CLI unusable (${forgeHealth.status})${forgeHealth.remedy ? ` — ${forgeHealth.remedy}` : ''}`
- });
- }
-
- const reviewerConfigFaults = reviewerConfigHealth.configFaults || {};
- if (Object.keys(reviewerConfigFaults).length) {
- rawWarnings.push({
- type: 'code-review',
- severity: 'warning',
- message: `Code review configuration needs attention for ${Object.keys(reviewerConfigFaults).join(', ')} — open Settings → Code Reviewers`
- });
- }
-
- if (!thresholdsAvailable) rawWarnings.forEach((warning) => { warning.dismissible = false; });
-
- // A dismissal only stays applied while the warning it was recorded against
- // is still current (same type AND same message) — see loadHealthSettings.
- // Anything else (the condition cleared, or recurred with a different
- // message) drops out of `dismissedWarnings` here so a genuinely new
- // occurrence is never silently hidden by a stale record.
- const nextDismissedWarnings = {};
- const warnings = [];
- for (const warning of rawWarnings) {
- const dismissal = dismissedWarnings[warning.type];
- const pendingPrune = pendingDismissalPrunes.get(warning.type);
- if (warning.dismissible !== false && dismissal?.message === warning.message && !sameDismissal(pendingPrune, dismissal)) {
- nextDismissedWarnings[warning.type] = dismissal;
- continue;
- }
- warnings.push(warning);
- }
-
- if (thresholdsAvailable) {
- for (const [type, pending] of pendingDismissalPrunes) {
- if (!Object.hasOwn(dismissedWarnings, type) || !sameDismissal(dismissedWarnings[type], pending)) {
- pendingDismissalPrunes.delete(type);
- }
- }
-
- const staleDismissals = Object.entries(dismissedWarnings)
- .filter(([type]) => !Object.hasOwn(nextDismissedWarnings, type));
- if (staleDismissals.length) {
- for (const [type, dismissal] of staleDismissals) pendingDismissalPrunes.set(type, dismissal);
- try {
- const saved = await updateSettingsWith((current) => {
- const next = { ...(current.health?.dismissedWarnings || {}) };
- for (const [type, dismissal] of staleDismissals) {
- if (sameDismissal(next[type], dismissal)) delete next[type];
- }
- return patchHealth(current, { dismissedWarnings: next });
- });
- for (const [type, dismissal] of staleDismissals) {
- if (sameDismissal(pendingDismissalPrunes.get(type), dismissal)
- && !sameDismissal(saved?.health?.dismissedWarnings?.[type], dismissal)) {
- pendingDismissalPrunes.delete(type);
- }
- }
- } catch (error) {
- for (const [type] of staleDismissals) {
- console.error(`❌ Failed to prune stale system health warning dismissal (type=${type}, error=${error?.code || 'write-failed'})`);
- }
- }
- }
- }
-
- const overallHealth = warnings.some(w => w.severity === 'critical')
- ? 'critical'
- : warnings.length > 0 ? 'warning' : 'healthy';
-
- // CoS status. Active and queued BOTH come off the one agent read when it is
- // readable — mixing `getStatus()`'s tally with a separately-read queue lets the
- // two skew, which is the defect one layer down (services/activeProcessing.js).
- // A task a live agent already holds is active, not queued (lib/cosSpawnWindow.js).
- // An unreadable list degrades to null — unknown, which the widget hides —
- // rather than to a manufactured zero.
- const heldByRunningAgent = runningAgentsByTaskId(cosAgents);
- const cosInfo = cosStatus && cosStatus !== failedProbe ? {
- running: cosStatus.running,
- paused: cosStatus.paused,
- activeAgents: cosAgents
- ? cosAgents.filter((agent) => agent?.status === 'running').length
- : (cosStatus.activeAgents || 0),
- queuedTasks: cosPendingTaskIds ? unclaimedTaskIds(cosPendingTaskIds, heldByRunningAgent).length : null
- } : null;
-
- const uptime = process.uptime();
- const uptimeFormatted = formatDuration(uptime * 1000);
-
- const responseTime = Date.now() - startTime;
-
- res.json({
- timestamp: new Date().toISOString(),
- hostname: os.hostname(),
- instanceId: self?.instanceId ?? null,
- version,
- overallHealth,
- // Peer credential handshake (#8356): `accepted` tells the probing peer that
- // THIS request authenticated with its pair token, so it can stop sending
- // the instance password. Older receivers omit the field; senders keep Basic.
- peerAuth: {
- version: PORTOS_SCHEMA_VERSIONS.peerAuth,
- accepted: req.portosAuthContext?.method === 'peer',
- },
- warnings,
- system: {
- uptime,
- uptimeFormatted,
- memory: {
- total: memStats.total,
- used: memStats.used,
- free: memStats.free,
- usagePercent: memUsagePercent,
- totalFormatted: formatBytes(memStats.total),
- usedFormatted: formatBytes(memStats.used),
- freeFormatted: formatBytes(memStats.free)
- },
- cpu: {
- cores: cpuCount,
- loadAvg1m: cpuLoad,
- usagePercent: cpuUsagePercent
- },
- disk: disk ? {
- total: disk.total,
- used: disk.used,
- free: disk.free,
- usagePercent: disk.usagePercent,
- totalFormatted: formatBytes(disk.total),
- usedFormatted: formatBytes(disk.used),
- freeFormatted: formatBytes(disk.free)
- } : null
- },
- processes: processStats,
- apps: appStats,
- cos: cosInfo,
- media: mediaCapacity,
- database: dbHealth,
- forge: forgeHealth,
- codeReview: reviewerConfigHealth,
- thresholds: thresholdsAvailable ? thresholds : undefined,
- thresholdsAvailable,
- topProcesses: pm2Processes === null ? null : [...pm2Processes]
- .sort((a, b) => (b.memory || 0) - (a.memory || 0))
- .slice(0, 10)
- .map(p => ({
- name: p.name,
- status: p.status,
- memory: p.memory || 0,
- memoryFormatted: formatBytes(p.memory || 0),
- cpu: p.cpu || 0,
- restarts: p.restarts || 0,
- unstableRestarts: p.unstableRestarts || 0
- }))
- });
+ const snapshot = await getSystemHealthSnapshot();
+ snapshot.peerAuth.accepted = req.portosAuthContext?.method === 'peer';
+ res.json(snapshot);
}));
/**
diff --git a/server/services/calendarAccounts.js b/server/services/calendarAccounts.js
index 1f2e5c96aa..e9c728534b 100644
--- a/server/services/calendarAccounts.js
+++ b/server/services/calendarAccounts.js
@@ -1,3 +1,4 @@
+import { noteReadinessChanged } from './readinessNotify.js';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';
@@ -19,6 +20,7 @@ async function loadAccounts() {
async function saveAccounts(accounts) {
await ensureDir(PATHS.calendar);
await atomicWrite(ACCOUNTS_FILE, accounts);
+ noteReadinessChanged();
}
export async function listAccounts() {
diff --git a/server/services/capabilitiesSnapshot.js b/server/services/capabilitiesSnapshot.js
new file mode 100644
index 0000000000..c7c0b8499e
--- /dev/null
+++ b/server/services/capabilitiesSnapshot.js
@@ -0,0 +1,132 @@
+import {
+ buildCapabilityRows,
+ summarizeCapabilities,
+ summarizeSetupCapabilities,
+} from '../lib/capabilityMap.js';
+import { getAllProviders, getProviderById } from './providers.js';
+import { getProviderPrerequisiteReadinessMap } from './providerPrerequisites.js';
+import { getProviderReadinessMap } from './providerReadiness.js';
+import { getAllProviderStatuses } from './providerStatus.js';
+import { listAccounts as listCalendarAccounts } from './calendarAccounts.js';
+import { listAccounts as listMessageAccounts } from './messageAccounts.js';
+import { countMemories } from './memoryBackend.js';
+import { getConfig as getCosConfig } from './cos.js';
+import { getVoiceConfig } from './voice/config.js';
+import { getNetworkExposureSetupStatus } from '../lib/networkExposure.js';
+import { getGenomeSummary } from './genome.js';
+import { getSettings } from './settings.js';
+import * as telegram from './telegram.js';
+import * as telegramBridge from './telegramBridge.js';
+import { getAppStatusSummary } from './appProcessStatus.js';
+
+
+// Resolve whether a memory-embedding provider is actually reachable-by-config
+// (mirrors memoryEmbeddings.initConfig) without firing the live LM Studio probe
+// — the probe auto-loads a model as a side effect, which a read-only status
+// page must not trigger.
+async function resolveEmbeddingProviderConfigured() {
+ const cosConfig = await getCosConfig();
+ const providerId = cosConfig?.embeddingProviderId || 'lmstudio';
+ const provider = await getProviderById(providerId);
+ // Mirror memoryEmbeddings.initConfig exactly: it keys off `endpoint` alone and
+ // does NOT gate on `enabled`, so embeddings still generate from a disabled-but-
+ // endpoint'd provider. Checking `enabled` here would misreport that as "off".
+ return !!provider?.endpoint;
+}
+
+async function resolveTelegram() {
+ const settings = await getSettings();
+ const method = settings?.telegram?.method || 'manual';
+ if (method === 'mcp-bridge') {
+ const status = telegramBridge.getStatus();
+ return { method, hasToken: status.hasBotToken, hasChatId: status.hasChatId, connected: status.connected };
+ }
+ const status = telegram.getStatus();
+ return {
+ method,
+ hasToken: !!settings?.secrets?.telegram?.token,
+ hasChatId: !!settings?.telegram?.chatId,
+ connected: status.connected,
+ };
+}
+
+// GET /api/capabilities — capability map of every connected system.
+export async function getCapabilitiesSnapshot() {
+ const unavailable = new Set();
+ const failed = (id, fallback) => () => {
+ unavailable.add(id);
+ return fallback;
+ };
+ const providersPromise = getAllProviders().catch(failed('providers', { providers: [] }));
+ const providerPrerequisiteReadinessPromise = providersPromise.then((data) => {
+ const providers = Array.isArray(data?.providers) ? data.providers : [];
+ const enabled = providers.filter((provider) => provider?.enabled !== false);
+ return getProviderPrerequisiteReadinessMap(providers, { candidates: enabled });
+ }).catch(failed('providers', null));
+ const providerLocalReadinessPromise = providersPromise.then((data) => {
+ const providers = Array.isArray(data?.providers) ? data.providers : [];
+ const enabled = providers.filter((provider) => provider?.enabled !== false);
+ return getProviderReadinessMap(enabled);
+ }).catch(() => null);
+
+ const [
+ providersData,
+ providerPrerequisiteReadiness,
+ providerLocalReadiness,
+ providerStatuses,
+ calendarAccounts,
+ messageAccounts,
+ memoryCount,
+ embeddingProviderConfigured,
+ voiceConfig,
+ genome,
+ telegramStatus,
+ appSummary,
+ network,
+ settings,
+ ] = await Promise.all([
+ providersPromise,
+ providerPrerequisiteReadinessPromise,
+ providerLocalReadinessPromise,
+ Promise.resolve().then(() => getAllProviderStatuses()).catch(failed('providers', {})),
+ listCalendarAccounts().catch(failed('calendar', [])),
+ listMessageAccounts().catch(failed('messages', [])),
+ countMemories({ status: 'active' }).catch(failed('brain', 0)),
+ resolveEmbeddingProviderConfigured().catch(failed('brain', false)),
+ getVoiceConfig().catch(failed('voice', {})),
+ getGenomeSummary().catch(failed('genome', { uploaded: false })),
+ resolveTelegram().catch(failed('telegram', {})),
+ getAppStatusSummary().catch(failed('apps', { total: 0 })),
+ getNetworkExposureSetupStatus().catch(failed('network', {})),
+ getSettings(),
+ ]);
+
+ const rows = buildCapabilityRows({
+ providers: providersData?.providers ?? [],
+ providerPrerequisiteReadiness,
+ providerLocalReadiness,
+ providerStatuses,
+ calendarAccounts,
+ messageAccounts,
+ memoryCount: Number(memoryCount) || 0,
+ embeddingProviderConfigured,
+ voiceConfig,
+ network,
+ genome,
+ telegram: telegramStatus,
+ appSummary,
+ }).map(row => unavailable.has(row.id)
+ ? { ...row, status: 'warn', summary: 'Readiness unavailable — probe failed', setupComplete: false }
+ : row);
+
+ return {
+ timestamp: new Date().toISOString(),
+ summary: summarizeCapabilities(rows),
+ optionalSummary: summarizeCapabilities(rows.filter((row) => row.setupRequired !== true && row.id !== 'network')),
+ setup: summarizeSetupCapabilities(rows),
+ capabilities: rows,
+ network,
+ networkSetupPreference: settings.networkSetupPreference || null,
+ };
+}
+
diff --git a/server/services/genome.js b/server/services/genome.js
index 3fcd1d7225..1e9fad8a09 100644
--- a/server/services/genome.js
+++ b/server/services/genome.js
@@ -1,3 +1,4 @@
+import { noteReadinessChanged } from './readinessNotify.js';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { atomicWrite, PATHS, ensureDir, safeJSONParse, tryReadFile, unlinkGuarded } from '../lib/fileUtils.js';
@@ -36,6 +37,7 @@ async function loadMeta() {
async function saveMeta(meta) {
await ensureGenomeDir();
await atomicWrite(META_FILE, meta);
+ noteReadinessChanged();
}
/**
@@ -372,6 +374,7 @@ export async function deleteGenome() {
await unlinkGuarded(META_FILE).catch(() => {});
snpIndex = null;
indexBuiltAt = 0;
+ noteReadinessChanged();
console.log('🧬 Genome data deleted');
return { success: true };
diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.js
index 0310417a1f..c3fbdfb0ab 100644
--- a/server/services/messageAccounts.js
+++ b/server/services/messageAccounts.js
@@ -1,3 +1,4 @@
+import { noteReadinessChanged } from './readinessNotify.js';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureDir, PATHS, safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';
@@ -16,6 +17,7 @@ async function loadAccounts() {
async function saveAccounts(accounts) {
await ensureDir(PATHS.messages);
await atomicWrite(ACCOUNTS_FILE, accounts);
+ noteReadinessChanged();
}
export async function listAccounts() {
diff --git a/server/services/pm2.js b/server/services/pm2.js
index f46e6de2d1..ddeef315e6 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -1,3 +1,4 @@
+import { noteReadinessChanged } from './readinessNotify.js';
import pm2 from 'pm2';
import { spawn } from '../lib/childProcess.js';
import { existsSync } from 'fs';
@@ -26,6 +27,8 @@ const jlistFailureState = new Map(); // home -> { lastError: string }
* @param {string|null} [pm2Home=null]
*/
export function clearJlistCache(pm2Home = null) {
+ noteReadinessChanged('health');
+ noteReadinessChanged('capabilities');
if (pm2Home !== undefined && pm2Home !== null) {
jlistCache.delete(cacheKey(pm2Home));
} else {
@@ -212,6 +215,7 @@ function spawnPm2Cli(action, name, pm2Home) {
child.stderr.on('data', (data) => { stderr += data.toString(); });
child.on('close', (code) => {
if (code !== 0) return reject(new Error(stderr || `pm2 ${action} exited with code ${code}`));
+ clearJlistCache();
resolve({ success: true });
});
child.on('error', reject);
@@ -272,6 +276,7 @@ export async function startApp(name, options = {}) {
pm2.start(startOptions, (err, proc) => {
if (err) return reject(err);
+ clearJlistCache();
resolve({ success: true, process: proc });
});
});
@@ -293,6 +298,7 @@ export async function stopApp(name, pm2Home = null) {
return new Promise((resolve, reject) => {
pm2.stop(name, (err) => {
if (err) return reject(err);
+ clearJlistCache();
resolve({ success: true });
});
});
@@ -331,6 +337,7 @@ export async function deleteApp(name, pm2Home = null) {
return new Promise((resolve, reject) => {
pm2.delete(name, (err) => {
if (err) return reject(err);
+ clearJlistCache();
resolve({ success: true });
});
});
@@ -652,6 +659,7 @@ export async function startWithCommand(name, cwd, command, options = {}) {
pm2.start(opts, (err, proc) => {
if (err) return reject(err);
+ clearJlistCache();
resolve({ success: true, process: proc });
});
});
@@ -685,6 +693,7 @@ function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestart
child.stderr.on('data', (data) => { stderr += data.toString(); });
child.on('close', (code) => {
if (code !== 0) return reject(new Error(stderr || `pm2 start exited with code ${code}`));
+ clearJlistCache();
resolve({ success: true });
});
child.on('error', reject);
@@ -724,6 +733,7 @@ function spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home) {
if (code !== 0) {
return reject(new Error(stderr || `pm2 start exited with code ${code}`));
}
+ clearJlistCache();
resolve({ success: true, output: stdout });
});
diff --git a/server/services/providers.js b/server/services/providers.js
index dbf4f01d4e..2988b97887 100644
--- a/server/services/providers.js
+++ b/server/services/providers.js
@@ -1,3 +1,4 @@
+import { noteReadinessChanged } from './readinessNotify.js';
/**
* Compatibility shim for PortOS services that import from providers.js
* Re-exports toolkit provider service functions
@@ -96,19 +97,27 @@ export async function getActiveProvider() {
}
export async function setActiveProvider(id) {
- return requireToolkit().services.providers.setActiveProvider(id);
+ const result = await requireToolkit().services.providers.setActiveProvider(id);
+ noteReadinessChanged();
+ return result;
}
export async function createProvider(data) {
- return requireToolkit().services.providers.createProvider(data);
+ const result = await requireToolkit().services.providers.createProvider(data);
+ noteReadinessChanged();
+ return result;
}
export async function updateProvider(id, data) {
- return requireToolkit().services.providers.updateProvider(id, data);
+ const result = await requireToolkit().services.providers.updateProvider(id, data);
+ noteReadinessChanged();
+ return result;
}
export async function deleteProvider(id) {
- return requireToolkit().services.providers.deleteProvider(id);
+ const result = await requireToolkit().services.providers.deleteProvider(id);
+ noteReadinessChanged();
+ return result;
}
export async function testProvider(id) {
@@ -116,7 +125,9 @@ export async function testProvider(id) {
}
export async function refreshProviderModels(id) {
- return requireToolkit().services.providers.refreshProviderModels(id);
+ const result = await requireToolkit().services.providers.refreshProviderModels(id);
+ noteReadinessChanged();
+ return result;
}
/**
@@ -135,5 +146,7 @@ export async function fetchProviderModels(id) {
* the caller logs group-level context instead of one line per member.
*/
export async function refreshProviderModelsBatch(ids) {
- return requireToolkit().services.providers.refreshProviderModelsBatch(ids);
+ const result = await requireToolkit().services.providers.refreshProviderModelsBatch(ids);
+ noteReadinessChanged();
+ return result;
}
diff --git a/server/services/readinessNotify.js b/server/services/readinessNotify.js
new file mode 100644
index 0000000000..6e8bad5b10
--- /dev/null
+++ b/server/services/readinessNotify.js
@@ -0,0 +1,145 @@
+/**
+ * Bounded readiness invalidations. No snapshot, credentials or record content
+ * goes onto the socket. One observer serves all open readiness views; it stops
+ * with the last subscriber. Snapshot readers only inspect readiness (never
+ * generate, warm a model, restart a process, or run CoS's repairing health check).
+ *
+ * Internal inputs: settings (health/voice/network/reviewer config), app and PM2
+ * mutations, CoS lifecycle/config/memory, media queues, providers/status,
+ * calendar/message accounts, genome and Telegram lifecycle.
+ * External inputs: filesystem and OS telemetry, DB/forge reachability, PM2
+ * changes outside PortOS, CUDA, provider binaries/local daemon readiness and
+ * Tailscale/cert state. Shared snapshot readers keep observer and HTTP failure
+ * semantics identical; timestamps alone never trigger an invalidation.
+ */
+const subscribers = new Set();
+const previous = new Map();
+const pendingDomains = new Set();
+let flushTimer = null;
+let observerTimer = null;
+let observing = false;
+let generation = 0;
+let stopWatchers = null;
+
+const READERS = {
+ health: () => import('./systemHealthSnapshot.js').then(m => m.getSystemHealthSnapshot()),
+ capabilities: () => import('./capabilitiesSnapshot.js').then(m => m.getCapabilitiesSnapshot()),
+};
+const EVENTS = { health: 'system:health:changed', capabilities: 'capabilities:changed' };
+export const READINESS_OBSERVE_MS = 20_000;
+export const READINESS_COALESCE_MS = 100;
+
+// Clock fields must not turn an unchanged observer sample into an invalidation.
+// Resource usage is real telemetry and remains part of health change detection.
+function signature(snapshot) {
+ return JSON.stringify(snapshot, (key, value) =>
+ ['timestamp', 'checkedAt', 'responseTime', 'uptime', 'uptimeFormatted'].includes(key) ? undefined : value);
+}
+
+export function noteReadinessChanged(domain = 'capabilities') {
+ if (!EVENTS[domain] || !subscribers.size) return;
+ pendingDomains.add(domain);
+ if (flushTimer) return;
+ flushTimer = setTimeout(() => {
+ flushTimer = null;
+ const domains = [...pendingDomains];
+ pendingDomains.clear();
+ for (const socket of subscribers) {
+ if (!socket.connected) continue;
+ try {
+ for (const name of domains) socket.emit(EVENTS[name], {});
+ } catch (err) {
+ console.error(`❌ Readiness notification failed: ${err.message}`);
+ }
+ }
+ }, READINESS_COALESCE_MS);
+ flushTimer.unref?.();
+}
+
+async function observe() {
+ if (observing || !subscribers.size) return;
+ observing = true;
+ const started = generation;
+ try {
+ await Promise.all(Object.entries(READERS).map(async ([domain, read]) => {
+ // Failure is a distinct state, never an empty or healthy snapshot.
+ const value = await read().then(signature, () => 'probe-unavailable');
+ if (started !== generation || !subscribers.size) return;
+ if (previous.has(domain) && previous.get(domain) !== value) noteReadinessChanged(domain);
+ previous.set(domain, value);
+ }));
+ } finally {
+ observing = false;
+ // A new subscriber may have arrived while an old generation was draining.
+ if (subscribers.size && !observerTimer) scheduleObservation();
+ }
+}
+
+function scheduleObservation() {
+ observerTimer = setTimeout(() => {
+ observerTimer = null;
+ observe().catch(err => console.error(`❌ Readiness observation failed: ${err.message}`));
+ }, READINESS_OBSERVE_MS);
+ observerTimer.unref?.();
+}
+
+function stopObservation() {
+ generation += 1;
+ clearTimeout(observerTimer);
+ clearTimeout(flushTimer);
+ observerTimer = null;
+ flushTimer = null;
+ pendingDomains.clear();
+ previous.clear();
+}
+
+export function registerReadinessSocket(socket) {
+ const release = () => {
+ subscribers.delete(socket);
+ if (!subscribers.size) stopObservation();
+ };
+ socket.on('readiness:subscribe', () => {
+ const first = subscribers.size === 0;
+ subscribers.add(socket);
+ if (first) observe().catch(err => console.error(`❌ Readiness observation failed: ${err.message}`));
+ });
+ socket.on('readiness:unsubscribe', release);
+ socket.on('disconnect', release);
+}
+
+/** Forward existing service buses without their private payloads. */
+export async function armReadinessWatchers() {
+ if (stopWatchers) return;
+ const offs = [];
+ // Set synchronously to make concurrent initialization idempotent.
+ stopWatchers = () => offs.splice(0).forEach(off => off());
+ try {
+ const [{ cosEvents }, { settingsEvents }, { appsEvents }, { providerStatusEvents }, { mediaJobEvents }] = await Promise.all([
+ import('./cosEvents.js'), import('./settings.js'), import('./apps.js'), import('./providerStatus.js'), import('./mediaJobQueue/index.js'),
+ ]);
+ const listen = (bus, events, domains) => {
+ for (const event of events) {
+ const handler = () => domains.forEach(noteReadinessChanged);
+ bus.on(event, handler);
+ offs.push(() => bus.off(event, handler));
+ }
+ };
+ listen(settingsEvents, ['settings:updated', 'settings:invalidated'], ['health', 'capabilities']);
+ listen(appsEvents, ['changed'], ['health', 'capabilities']);
+ listen(mediaJobEvents, ['enqueued', 'started', 'completed', 'failed', 'canceled'], ['health']);
+ listen(providerStatusEvents, ['status:changed'], ['capabilities']);
+ listen(cosEvents, ['health:check', 'health:critical', 'agent:spawned', 'agent:completed', 'agent:terminate', 'tasks:changed', 'status', 'status:paused', 'status:resumed'], ['health']);
+ listen(cosEvents, ['config:changed', 'memory:created', 'memory:updated', 'memory:deleted', 'memory:approved', 'memory:rejected'], ['capabilities']);
+ } catch (err) {
+ stopWatchers();
+ stopWatchers = null;
+ throw err;
+ }
+}
+
+export function resetReadinessForTests() {
+ subscribers.clear();
+ stopObservation();
+ stopWatchers?.();
+ stopWatchers = null;
+}
diff --git a/server/services/readinessNotify.test.js b/server/services/readinessNotify.test.js
new file mode 100644
index 0000000000..e610366857
--- /dev/null
+++ b/server/services/readinessNotify.test.js
@@ -0,0 +1,102 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./systemHealthSnapshot.js', () => ({ getSystemHealthSnapshot: vi.fn() }));
+vi.mock('./capabilitiesSnapshot.js', () => ({ getCapabilitiesSnapshot: vi.fn() }));
+vi.mock('./settings.js', () => ({ settingsEvents: new EventEmitter() }));
+vi.mock('./apps.js', () => ({ appsEvents: new EventEmitter() }));
+vi.mock('./providerStatus.js', () => ({ providerStatusEvents: new EventEmitter() }));
+vi.mock('./cosEvents.js', () => ({ cosEvents: new EventEmitter() }));
+vi.mock('./mediaJobQueue/index.js', () => ({ mediaJobEvents: new EventEmitter() }));
+import { getSystemHealthSnapshot } from './systemHealthSnapshot.js';
+import { getCapabilitiesSnapshot } from './capabilitiesSnapshot.js';
+import { settingsEvents } from './settings.js';
+import { cosEvents } from './cosEvents.js';
+import {
+ armReadinessWatchers, registerReadinessSocket, resetReadinessForTests,
+ READINESS_OBSERVE_MS, READINESS_COALESCE_MS,
+} from './readinessNotify.js';
+
+function connect() {
+ const handlers = new Map();
+ const socket = { connected: true, on: (event, fn) => handlers.set(event, fn), emit: vi.fn() };
+ registerReadinessSocket(socket);
+ handlers.get('readiness:subscribe')();
+ return { socket, send: event => handlers.get(event)() };
+}
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ getSystemHealthSnapshot.mockResolvedValue({ overallHealth: 'healthy', timestamp: 'one', system: { uptime: 1 } });
+ getCapabilitiesSnapshot.mockResolvedValue({ summary: { overall: 'ok' }, timestamp: 'one' });
+});
+afterEach(() => { resetReadinessForTests(); vi.useRealTimers(); });
+
+describe('shared readiness subscription', () => {
+ it('shares one observer, ignores clock-only changes and stops after the last unsubscribe', async () => {
+ const a = connect();
+ const b = connect();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getCapabilitiesSnapshot).toHaveBeenCalledTimes(1);
+ expect(getSystemHealthSnapshot).toHaveBeenCalledTimes(1);
+ getCapabilitiesSnapshot.mockResolvedValue({ summary: { overall: 'ok' }, timestamp: 'two' });
+ getSystemHealthSnapshot.mockResolvedValue({ overallHealth: 'healthy', timestamp: 'two', system: { uptime: 2 } });
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS + READINESS_COALESCE_MS);
+ expect(a.socket.emit).not.toHaveBeenCalled();
+
+ getCapabilitiesSnapshot.mockResolvedValue({ summary: { overall: 'warn' } });
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS);
+ expect(a.socket.emit).toHaveBeenCalledExactlyOnceWith('capabilities:changed', {});
+ expect(b.socket.emit).toHaveBeenCalledExactlyOnceWith('capabilities:changed', {});
+ a.send('readiness:unsubscribe');
+ const reads = getCapabilitiesSnapshot.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS);
+ expect(getCapabilitiesSnapshot).toHaveBeenCalledTimes(reads + 1);
+ b.send('disconnect');
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS * 3);
+ expect(getCapabilitiesSnapshot).toHaveBeenCalledTimes(reads + 1);
+ });
+
+ it('coalesces service events without forwarding private payloads, and distinguishes probe failure/recovery', async () => {
+ await armReadinessWatchers();
+ await armReadinessWatchers();
+ const a = connect();
+ await vi.advanceTimersByTimeAsync(0);
+ settingsEvents.emit('settings:updated', { secrets: 'not a socket payload' });
+ cosEvents.emit('health:check', { private: 'not a socket payload' });
+ await vi.advanceTimersByTimeAsync(READINESS_COALESCE_MS);
+ expect(a.socket.emit.mock.calls).toEqual([
+ ['system:health:changed', {}], ['capabilities:changed', {}],
+ ]);
+ a.socket.emit.mockClear();
+ getCapabilitiesSnapshot.mockRejectedValue(new Error('Probe failed'));
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS);
+ expect(a.socket.emit).toHaveBeenCalledExactlyOnceWith('capabilities:changed', {});
+ a.socket.emit.mockClear();
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS);
+ expect(a.socket.emit).not.toHaveBeenCalled();
+ getCapabilitiesSnapshot.mockResolvedValue({ summary: { overall: 'ok' } });
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS);
+ expect(a.socket.emit).toHaveBeenCalledExactlyOnceWith('capabilities:changed', {});
+ resetReadinessForTests();
+ expect(settingsEvents.listenerCount('settings:updated')).toBe(0);
+ expect(cosEvents.listenerCount('health:check')).toBe(0);
+ });
+ it('never overlaps a slow sample and discards its result after the last consumer leaves', async () => {
+ let finish;
+ getCapabilitiesSnapshot.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));
+ const a = connect();
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS * 3);
+ expect(getCapabilitiesSnapshot).toHaveBeenCalledTimes(1);
+ a.send('disconnect');
+ finish({ summary: { overall: 'warn' } });
+ await vi.advanceTimersByTimeAsync(READINESS_OBSERVE_MS);
+ expect(a.socket.emit).not.toHaveBeenCalled();
+ expect(getCapabilitiesSnapshot).toHaveBeenCalledTimes(1);
+ connect();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getCapabilitiesSnapshot).toHaveBeenCalledTimes(2);
+ });
+
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index 4010619c92..702a91570d 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -46,6 +46,7 @@ import { getBuildId } from '../lib/buildId.js';
import { authEvents, isAuthEnabled, verifyRequestSession } from './auth.js';
import { runEventLogEvents } from './agentRunEventLog.js';
import { armSystemActivityWatchers, bindSystemActivityIo } from './systemActivityNotify.js';
+import { armReadinessWatchers, registerReadinessSocket } from './readinessNotify.js';
// Store CoS subscribers
const cosSubscribers = new Set();
@@ -196,6 +197,7 @@ function registerLifecycleHandlers(socket, _io) {
const SOCKET_HANDLER_REGISTRARS = [
registerAuthHandlers,
+ registerReadinessSocket,
registerVoiceHandlers,
registerBuildHandlers,
registerImporterHandlers,
@@ -301,6 +303,9 @@ export function initSocket(io) {
// Invalidation only. Clients coalesce the frame into one bounded activity
// read; a missed frame is repaired by the reconnect read, not by polling.
bindSystemActivityIo(io);
+ armReadinessWatchers().catch((err) => {
+ console.error(`❌ Readiness watchers failed: ${err.message}`);
+ });
armSystemActivityWatchers().catch((err) => {
console.error(`❌ system activity watchers failed: ${err.message}`);
});
diff --git a/server/services/systemHealthSnapshot.js b/server/services/systemHealthSnapshot.js
new file mode 100644
index 0000000000..86c59e2c2c
--- /dev/null
+++ b/server/services/systemHealthSnapshot.js
@@ -0,0 +1,394 @@
+import os from 'os';
+import { statfs } from 'fs/promises';
+import { listProcessesStrict } from './pm2.js';
+import { getAppStatusSummary, annotateExpectedExit } from './appProcessStatus.js';
+import * as cos from './cos.js';
+import { getSelf } from './instanceIdentity.js';
+import { checkHealth } from '../lib/db.js';
+import { getCurrentVersion } from './updateChecker.js';
+import { getMemoryStats } from '../lib/memoryStats.js';
+import { formatBytes, formatDuration } from '../lib/fileUtils.js';
+import { parseFilesystemStats } from '../lib/fileCore.js';
+import { getSettingsWithStatus, updateSettingsWith } from './settings.js';
+import { checkGhHealth } from './github.js';
+import { getMediaCapacity } from './mediaCapacity.js';
+import { runningAgentsByTaskId, unclaimedTaskIds } from '../lib/cosSpawnWindow.js';
+import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
+
+// Disk capacity remains actionable. Memory thresholds are retained on the wire
+// for older clients, but no longer generate warnings or degrade health.
+const DEFAULT_THRESHOLDS = {
+ memoryWarn: 85,
+ memoryCritical: 95,
+ diskWarn: 90,
+ diskCritical: 98
+};
+
+// When a stale dismissal cannot be removed, remember the exact record that
+// needs pruning. A matching recurrence remains visible until a later health
+// read successfully removes that same persisted value.
+const pendingDismissalPrunes = new Map();
+const sameDismissal = (left, right) => JSON.stringify(left) === JSON.stringify(right);
+
+// Dashboard warnings are recomputed fresh on every read (nothing about them is
+// persisted), so "dismiss" can't delete a row — it has to remember, per warning
+// TYPE, the exact message that was dismissed. A later read matching that same
+// (type, message) pair stays suppressed; a DIFFERENT message for the same type
+// (severity escalated, a different process started crash-looping) is a new
+// occurrence and is shown again automatically. Keyed by type rather than a
+// generated id because each health check emits at most one warning per type.
+//
+// Thresholds and dismissals both live under settings.health, so one read
+// covers both — GET /health/details used to call getSettings() twice (once
+// per concern), paying for two deep-clones of the settings cache on every
+// dashboard poll.
+async function loadHealthSettings() {
+ const status = await getSettingsWithStatus().catch(() => {
+ console.error('❌ Failed to read system health settings; default thresholds will be used');
+ return { corrupt: true, settings: {} };
+ });
+ const settingsAvailable = status?.corrupt === false
+ && status.settings
+ && typeof status.settings === 'object'
+ && !Array.isArray(status.settings);
+ const h = settingsAvailable ? (status.settings.health || {}) : {};
+ const dismissedWarnings = h.dismissedWarnings;
+ return {
+ thresholdsAvailable: Boolean(settingsAvailable),
+ thresholds: {
+ memoryWarn: Number(h.memoryWarn) || DEFAULT_THRESHOLDS.memoryWarn,
+ memoryCritical: Number(h.memoryCritical) || DEFAULT_THRESHOLDS.memoryCritical,
+ diskWarn: Number(h.diskWarn) || DEFAULT_THRESHOLDS.diskWarn,
+ diskCritical: Number(h.diskCritical) || DEFAULT_THRESHOLDS.diskCritical
+ },
+ dismissedWarnings: dismissedWarnings && typeof dismissedWarnings === 'object' && !Array.isArray(dismissedWarnings)
+ ? dismissedWarnings
+ : {}
+ };
+}
+
+const patchHealth = (current, patch) => ({ ...current, health: { ...(current.health || {}), ...patch } });
+
+export async function getSystemHealthSnapshot() {
+ const startTime = Date.now();
+ const failedProbe = Symbol('failed health probe');
+
+ // Gather data in parallel
+ const [pm2Processes, appStatusSummary, cosStatus, cosPendingTaskIds, cosAgents, self, dbHealth, version, diskStats, memStats, healthSettings, forgeHealth, mediaCapacity, reviewerConfigHealth] = await Promise.all([
+ listProcessesStrict().catch(() => null),
+ getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),
+ cos.getStatus().catch((error) => {
+ console.error('Chief of Staff health probe failed', error);
+ return failedProbe;
+ }),
+ // Queue depth is read here rather than taken off `getStatus()`, which has no
+ // such field — `cosStatus.queueLength` never existed, so the widget's
+ // "N queued" was dead and always rendered 0. Both reads ride the same
+ // `loadState()`/parse caches `getStatus()` above already warmed.
+ cos.getPendingTaskIds().catch(() => null),
+ cos.getAgents().catch(() => null),
+ getSelf().catch(() => null),
+ checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),
+ getCurrentVersion().catch(() => null),
+ statfs('/').catch((error) => {
+ console.error('Root filesystem health probe failed', error);
+ return failedProbe;
+ }),
+ getMemoryStats(),
+ loadHealthSettings(),
+ checkGhHealth().catch(() => ({ status: 'error', ok: false, detail: 'Health check failed', remedy: null, checkedAt: null })),
+ // Media-lane capacity never fails the health report: an unreadable GPU probe
+ // degrades to `null`, which the UI renders as unknown rather than as idle.
+ getMediaCapacity().catch(() => null),
+ import('../services/codeReview.js')
+ .then(({ getReviewerConfigHealth }) => getReviewerConfigHealth())
+ .catch(() => ({ status: 'unknown', configFaults: {} }))
+ ]);
+ const { thresholds, dismissedWarnings, thresholdsAvailable } = healthSettings;
+
+ const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);
+ const cpuLoad = os.loadavg()[0]; // 1-minute load average
+ const cpuCount = os.cpus().length;
+ const cpuUsagePercent = Math.round((cpuLoad / cpuCount) * 100);
+
+ // Disk usage (root filesystem).
+ // bavail = blocks available to unprivileged users (what the user can actually fill).
+ // Derive used/usagePercent from the same figure so `used + free === total` and
+ // the UI's percent corresponds to the displayed `free`.
+ const parsedDisk = diskStats === failedProbe ? null : parseFilesystemStats(diskStats);
+ const disk = parsedDisk && {
+ total: parsedDisk.total,
+ used: parsedDisk.used,
+ free: parsedDisk.free,
+ usagePercent: parsedDisk.usagePercent,
+ };
+
+ // Process status summary from PM2. Processes whose exit is expected (a desktop
+ // app the user closed) are excluded from the FAILURE-bearing counts: a quit game
+ // window would otherwise force overallHealth to 'critical' below and light up
+ // the dashboard widget and the OpenWorld HUD until the PM2 entry is manually
+ // cleared. `expectedExit` describes a process's exit *semantics*, not its
+ // liveness — so `online` counts every process, exempt or not, or a *running*
+ // desktop app would sit in `total` and in no status bucket at all and the
+ // dashboard would read "5/6 · all running" with all six up. Resource totals
+ // likewise cover every process. See issue #2991.
+ // When PM2 read fails, pm2Processes is null and we set processStats to null
+ // to signal unavailable rather than zero.
+ let processStats = null;
+ let annotated = [];
+ let supervised = [];
+ if (pm2Processes !== null) {
+ annotated = await annotateExpectedExit(pm2Processes);
+ supervised = annotated.filter(p => !p.expectedExit);
+ processStats = {
+ total: pm2Processes.length,
+ online: annotated.filter(p => p.status === 'online').length,
+ stopped: supervised.filter(p => p.status === 'stopped').length,
+ errored: supervised.filter(p => p.status === 'errored').length,
+ // A desktop app that exited (cleanly as `stopped`, or `errored` on a
+ // force-quit) — reported on its own rather than as a failure.
+ desktopExited: annotated.filter(
+ p => p.expectedExit && ['errored', 'stopped'].includes(p.status)
+ ).length,
+ totalMemory: pm2Processes.reduce((sum, p) => sum + (p.memory || 0), 0),
+ totalCpu: pm2Processes.reduce((sum, p) => sum + (p.cpu || 0), 0),
+ totalRestarts: pm2Processes.reduce((sum, p) => sum + (p.restarts || 0), 0),
+ unstableRestarts: supervised.reduce((sum, p) => sum + (p.unstableRestarts || 0), 0)
+ };
+ }
+
+ // App status summary — PM2-managed apps only (Xcode/iOS-native projects
+ // have no detectable runtime state, so they're tracked under `unmanaged`
+ // and excluded from the running denominator)
+ const appStats = appStatusSummary;
+
+ // Determine overall health status. Each condition below records its
+ // severity on the warning itself rather than mutating `overallHealth`
+ // inline, because a dismissed warning (see loadDismissedWarnings above)
+ // must not count toward the badge — overallHealth is derived once, after
+ // dismissals are filtered out, from whatever warnings remain visible.
+ const rawWarnings = [];
+
+ // Memory occupancy and CPU load describe work, not a health failure.
+
+ if (!thresholdsAvailable) {
+ rawWarnings.push({
+ type: 'health-settings',
+ severity: 'warning',
+ message: 'System health settings are unavailable; default thresholds are being used and saved warning dismissals were ignored.',
+ dismissible: false
+ });
+ }
+
+ if (diskStats === failedProbe) {
+ rawWarnings.push({ type: 'probe-unavailable', source: 'disk', status: 'unavailable', severity: 'warning', message: 'Disk status unavailable', dismissible: false });
+ }
+ if (cosStatus === failedProbe) {
+ rawWarnings.push({ type: 'probe-unavailable', source: 'cos', status: 'unavailable', severity: 'warning', message: 'Chief of Staff status unavailable', dismissible: false });
+ }
+ if (pm2Processes === null) {
+ rawWarnings.push({ type: 'probe-unavailable', source: 'pm2', status: 'unavailable', severity: 'warning', message: 'Process manager (PM2) status unavailable', dismissible: false });
+ }
+
+ if (disk) {
+ if (disk.usagePercent >= thresholds.diskCritical) {
+ rawWarnings.push({ type: 'disk', severity: 'critical', message: `Disk usage at or above ${thresholds.diskCritical}%` });
+ } else if (disk.usagePercent >= thresholds.diskWarn) {
+ rawWarnings.push({ type: 'disk', severity: 'warning', message: `Disk usage at or above ${thresholds.diskWarn}%` });
+ }
+ }
+
+ if (processStats) {
+ if (processStats.errored > 0) {
+ rawWarnings.push({ type: 'process', severity: 'critical', message: `${processStats.errored} process(es) errored` });
+ }
+
+ if (processStats.unstableRestarts > 0) {
+ const crashing = supervised.filter(p => (p.unstableRestarts || 0) > 0).map(p => p.name);
+ const plural = processStats.unstableRestarts === 1 ? '' : 's';
+ rawWarnings.push({
+ type: 'restarts',
+ severity: 'warning',
+ message: `${processStats.unstableRestarts} crash-loop restart${plural} (${crashing.join(', ')})`
+ });
+ }
+ }
+
+ // A degraded app summary means PM2 couldn't be read for one or more homes, so
+ // those apps' online/stopped status is unknown — surface it rather than letting
+ // the counts silently read as "everything not started."
+ if (appStats.degraded) {
+ const unknown = appStats.unknown || 0;
+ rawWarnings.push({ type: 'apps', severity: 'warning', message: `App status unavailable for ${unknown} app(s) — PM2 read failed` });
+ }
+
+ if (!dbHealth.connected) {
+ rawWarnings.push({ type: 'database', severity: 'warning', message: `PostgreSQL disconnected${dbHealth.error ? `: ${dbHealth.error}` : ''}` });
+ } else if (!dbHealth.hasSchema) {
+ rawWarnings.push({ type: 'database', severity: 'warning', message: 'PostgreSQL connected but schema missing' });
+ }
+
+ // A `gh` that cannot reach the forge does not fail loudly anywhere else: the
+ // call sites that read pull requests and issues swallow the error into an
+ // empty list, so a blocked or unauthenticated CLI looks exactly like a repo
+ // with nothing open — and an agent asked to file a PR reports success having
+ // filed none. Warn only when gh is present but unusable; an install that
+ // never had gh has opted out of those features rather than broken them.
+ if (!forgeHealth.ok && forgeHealth.status !== 'not-installed') {
+ rawWarnings.push({
+ type: 'forge',
+ severity: 'warning',
+ message: `GitHub CLI unusable (${forgeHealth.status})${forgeHealth.remedy ? ` — ${forgeHealth.remedy}` : ''}`
+ });
+ }
+
+ const reviewerConfigFaults = reviewerConfigHealth.configFaults || {};
+ if (Object.keys(reviewerConfigFaults).length) {
+ rawWarnings.push({
+ type: 'code-review',
+ severity: 'warning',
+ message: `Code review configuration needs attention for ${Object.keys(reviewerConfigFaults).join(', ')} — open Settings → Code Reviewers`
+ });
+ }
+
+ if (!thresholdsAvailable) rawWarnings.forEach((warning) => { warning.dismissible = false; });
+
+ // A dismissal only stays applied while the warning it was recorded against
+ // is still current (same type AND same message) — see loadHealthSettings.
+ // Anything else (the condition cleared, or recurred with a different
+ // message) drops out of `dismissedWarnings` here so a genuinely new
+ // occurrence is never silently hidden by a stale record.
+ const nextDismissedWarnings = {};
+ const warnings = [];
+ for (const warning of rawWarnings) {
+ const dismissal = dismissedWarnings[warning.type];
+ const pendingPrune = pendingDismissalPrunes.get(warning.type);
+ if (warning.dismissible !== false && dismissal?.message === warning.message && !sameDismissal(pendingPrune, dismissal)) {
+ nextDismissedWarnings[warning.type] = dismissal;
+ continue;
+ }
+ warnings.push(warning);
+ }
+
+ if (thresholdsAvailable) {
+ for (const [type, pending] of pendingDismissalPrunes) {
+ if (!Object.hasOwn(dismissedWarnings, type) || !sameDismissal(dismissedWarnings[type], pending)) {
+ pendingDismissalPrunes.delete(type);
+ }
+ }
+
+ const staleDismissals = Object.entries(dismissedWarnings)
+ .filter(([type]) => !Object.hasOwn(nextDismissedWarnings, type));
+ if (staleDismissals.length) {
+ for (const [type, dismissal] of staleDismissals) pendingDismissalPrunes.set(type, dismissal);
+ try {
+ const saved = await updateSettingsWith((current) => {
+ const next = { ...(current.health?.dismissedWarnings || {}) };
+ for (const [type, dismissal] of staleDismissals) {
+ if (sameDismissal(next[type], dismissal)) delete next[type];
+ }
+ return patchHealth(current, { dismissedWarnings: next });
+ });
+ for (const [type, dismissal] of staleDismissals) {
+ if (sameDismissal(pendingDismissalPrunes.get(type), dismissal)
+ && !sameDismissal(saved?.health?.dismissedWarnings?.[type], dismissal)) {
+ pendingDismissalPrunes.delete(type);
+ }
+ }
+ } catch (error) {
+ for (const [type] of staleDismissals) {
+ console.error(`❌ Failed to prune stale system health warning dismissal (type=${type}, error=${error?.code || 'write-failed'})`);
+ }
+ }
+ }
+ }
+
+ const overallHealth = warnings.some(w => w.severity === 'critical')
+ ? 'critical'
+ : warnings.length > 0 ? 'warning' : 'healthy';
+
+ // CoS status. Active and queued BOTH come off the one agent read when it is
+ // readable — mixing `getStatus()`'s tally with a separately-read queue lets the
+ // two skew, which is the defect one layer down (services/activeProcessing.js).
+ // A task a live agent already holds is active, not queued (lib/cosSpawnWindow.js).
+ // An unreadable list degrades to null — unknown, which the widget hides —
+ // rather than to a manufactured zero.
+ const heldByRunningAgent = runningAgentsByTaskId(cosAgents);
+ const cosInfo = cosStatus && cosStatus !== failedProbe ? {
+ running: cosStatus.running,
+ paused: cosStatus.paused,
+ activeAgents: cosAgents
+ ? cosAgents.filter((agent) => agent?.status === 'running').length
+ : (cosStatus.activeAgents || 0),
+ queuedTasks: cosPendingTaskIds ? unclaimedTaskIds(cosPendingTaskIds, heldByRunningAgent).length : null
+ } : null;
+
+ const uptime = process.uptime();
+ const uptimeFormatted = formatDuration(uptime * 1000);
+
+ const responseTime = Date.now() - startTime;
+
+ return {
+ timestamp: new Date().toISOString(),
+ hostname: os.hostname(),
+ instanceId: self?.instanceId ?? null,
+ version,
+ overallHealth,
+ // Peer credential handshake (#8356): `accepted` tells the probing peer that
+ // THIS request authenticated with its pair token, so it can stop sending
+ // the instance password. Older receivers omit the field; senders keep Basic.
+ peerAuth: {
+ version: PORTOS_SCHEMA_VERSIONS.peerAuth,
+ accepted: false,
+ },
+ warnings,
+ system: {
+ uptime,
+ uptimeFormatted,
+ memory: {
+ total: memStats.total,
+ used: memStats.used,
+ free: memStats.free,
+ usagePercent: memUsagePercent,
+ totalFormatted: formatBytes(memStats.total),
+ usedFormatted: formatBytes(memStats.used),
+ freeFormatted: formatBytes(memStats.free)
+ },
+ cpu: {
+ cores: cpuCount,
+ loadAvg1m: cpuLoad,
+ usagePercent: cpuUsagePercent
+ },
+ disk: disk ? {
+ total: disk.total,
+ used: disk.used,
+ free: disk.free,
+ usagePercent: disk.usagePercent,
+ totalFormatted: formatBytes(disk.total),
+ usedFormatted: formatBytes(disk.used),
+ freeFormatted: formatBytes(disk.free)
+ } : null
+ },
+ processes: processStats,
+ apps: appStats,
+ cos: cosInfo,
+ media: mediaCapacity,
+ database: dbHealth,
+ forge: forgeHealth,
+ codeReview: reviewerConfigHealth,
+ thresholds: thresholdsAvailable ? thresholds : undefined,
+ thresholdsAvailable,
+ topProcesses: pm2Processes === null ? null : [...pm2Processes]
+ .sort((a, b) => (b.memory || 0) - (a.memory || 0))
+ .slice(0, 10)
+ .map(p => ({
+ name: p.name,
+ status: p.status,
+ memory: p.memory || 0,
+ memoryFormatted: formatBytes(p.memory || 0),
+ cpu: p.cpu || 0,
+ restarts: p.restarts || 0,
+ unstableRestarts: p.unstableRestarts || 0
+ }))
+ };
+}
diff --git a/server/services/telegram.js b/server/services/telegram.js
index 67cc27d10d..62ea5c6ede 100644
--- a/server/services/telegram.js
+++ b/server/services/telegram.js
@@ -1,3 +1,4 @@
+import { noteReadinessChanged } from './readinessNotify.js';
/**
* Telegram Bot Service
*
@@ -90,6 +91,7 @@ export async function init(sendTestMessage = false) {
botUsername = me.username;
isConnected = true;
+ noteReadinessChanged();
console.log(`📱 Telegram: connected as @${botUsername}`);
// Register /start handler (always works, no auth required)
@@ -204,6 +206,7 @@ export async function cleanup() {
bot = null;
}
isConnected = false;
+ noteReadinessChanged();
botUsername = null;
authorizedChatId = null;
cachedForwardTypes = null;
@@ -239,6 +242,7 @@ async function healthCheck() {
await bot.getMe().catch(async (err) => {
console.error(`📱 Telegram: health check failed — ${err.message}`);
isConnected = false;
+ noteReadinessChanged();
await reconnect();
});
}
@@ -257,6 +261,7 @@ export async function sendMessage(text, opts = { parse_mode: 'HTML' }) {
const result = await bot.sendMessage(authorizedChatId, text, opts).catch(async (err) => {
console.error(`📱 Telegram: send failed — ${err.message}`);
isConnected = false;
+ noteReadinessChanged();
await reconnect();
return null;
});
diff --git a/server/services/telegramBridge.js b/server/services/telegramBridge.js
index 007ec94573..3784c3d69a 100644
--- a/server/services/telegramBridge.js
+++ b/server/services/telegramBridge.js
@@ -1,3 +1,4 @@
+import { noteReadinessChanged } from './readinessNotify.js';
/**
* Telegram MCP Bridge Service
*
@@ -100,6 +101,7 @@ export async function init() {
botUsername = me.username;
isActive = true;
+ noteReadinessChanged();
console.log(`📱 TG Bridge: active as @${botUsername} → chat ${chatId}`);
// Subscribe to notification events
@@ -116,6 +118,7 @@ export async function cleanup() {
notificationSubscription = null;
}
isActive = false;
+ noteReadinessChanged();
botToken = null;
chatId = null;
botUsername = null;