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

fix: log PM2 read failures only on state change, add probe-unavailable warning (#8431)

[._.]/ Adam Eivyada255f2562e
diff --git a/client/src/components/SystemHealthWidget.jsx b/client/src/components/SystemHealthWidget.jsx
index f5753b1bff..c6c0b171d1 100644
--- a/client/src/components/SystemHealthWidget.jsx
+++ b/client/src/components/SystemHealthWidget.jsx
@@ -50,7 +50,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })
const norm = (pct) => Math.max(0.18, Math.min(1, (pct ?? 0) / 100));
cells[0] = norm(memPct);
cells[1] = norm(cpuPct);
- cells[2] = procTotal ? Math.max(0.25, procOnline / procTotal) : 0.25;
+ cells[2] = processes && procTotal ? Math.max(0.25, procOnline / procTotal) : 0.25;
cells[3] = appTotal ? Math.max(0.25, appOnline / appTotal) : 0.25;
cells[4] = norm(diskPct);
for (let row = 1; row < 5; row++) {
@@ -60,7 +60,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })
}
}
return cells;
- }, [memPct, cpuPct, diskPct, procOnline, procTotal, appOnline, appTotal]);
+ }, [memPct, cpuPct, diskPct, procOnline, procTotal, appOnline, appTotal, processes]);
// Don't render if no data
if (!health) {
@@ -70,6 +70,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })
const { overallHealth, warnings, system, processes, apps, cos } = health;
const diskProbeUnavailable = warnings.some(warning => warning.type === 'probe-unavailable' && warning.source === 'disk');
const cosProbeUnavailable = warnings.some(warning => warning.type === 'probe-unavailable' && warning.source === 'cos');
+ const pm2ProbeUnavailable = warnings.some(warning => warning.type === 'probe-unavailable' && warning.source === 'pm2');
const healthStyle = HEALTH_STYLE[overallHealth] || { color: 'text-gray-400', bg: 'bg-gray-400/10', icon: Activity };
const HealthIcon = healthStyle.icon;
@@ -193,25 +194,32 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })
</div>
{/* Processes */}
- <div className="bg-port-bg/50 rounded-lg p-3">
- <div className="flex min-w-0 items-center gap-2 mb-1">
- <Activity size={14} className="hidden shrink-0 text-emerald-400 @2xs:block" />
- <span className="truncate text-xs text-gray-500">Processes</span>
- </div>
- <div className="text-lg @sm:text-xl font-bold text-white">
- {processes.online}
- <span className="text-sm font-normal text-gray-500">/{processes.total}</span>
+ {processes ? (
+ <div className="bg-port-bg/50 rounded-lg p-3">
+ <div className="flex min-w-0 items-center gap-2 mb-1">
+ <Activity size={14} className="hidden shrink-0 text-emerald-400 @2xs:block" />
+ <span className="truncate text-xs text-gray-500">Processes</span>
+ </div>
+ <div className="text-lg @sm:text-xl font-bold text-white">
+ {processes.online}
+ <span className="text-sm font-normal text-gray-500">/{processes.total}</span>
+ </div>
+ <div className="flex items-center gap-1 text-xs text-gray-500">
+ {processes.errored > 0 ? (
+ <span className="text-port-error">{processes.errored} errored</span>
+ ) : processes.stopped > 0 ? (
+ <span>{processes.stopped} stopped</span>
+ ) : (
+ <span className="text-port-success">All running</span>
+ )}
+ </div>
</div>
- <div className="flex items-center gap-1 text-xs text-gray-500">
- {processes.errored > 0 ? (
- <span className="text-port-error">{processes.errored} errored</span>
- ) : processes.stopped > 0 ? (
- <span>{processes.stopped} stopped</span>
- ) : (
- <span className="text-port-success">All running</span>
- )}
+ ) : pm2ProbeUnavailable ? (
+ <div className="rounded-lg bg-port-bg/50 p-3" aria-label="Process manager status unavailable">
+ <div className="text-xs text-gray-500">Processes</div>
+ <div className="text-lg font-bold text-port-warning">Unavailable</div>
</div>
- </div>
+ ) : null}
{/* Services — PM2-managed apps; native (Xcode/iOS) projects shown as "+N native" */}
<div
diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsx
index aeadf58d3b..50b921b1ed 100644
--- a/client/src/pages/SystemHealthPage.jsx
+++ b/client/src/pages/SystemHealthPage.jsx
@@ -297,7 +297,11 @@ function SystemHealthOverview() {
<Activity size={16} />
Top processes by memory
</h3>
- {health.topProcesses && health.topProcesses.length > 0 ? (
+ {health.topProcesses === null ? (
+ <p role="status" className="text-gray-400 text-sm">
+ Process manager (PM2) status unavailable. <Link to="/system-resources/overview" className="text-port-accent hover:text-port-accent/80">Check health →</Link>
+ </p>
+ ) : health.topProcesses && health.topProcesses.length > 0 ? (
<div className="space-y-1">
{health.topProcesses.map((p) => (
<div key={p.name} className="flex items-center gap-3 px-3 py-2 rounded-lg bg-port-bg/40 hover:bg-port-bg/60 text-sm">
diff --git a/server/lib/validation.js b/server/lib/validation.js
index da316679ff..1b53bfe29e 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1654,8 +1654,10 @@ export const databaseExportSchema = z.object({
});
// Dismissible system health warnings — see server/routes/systemHealth.js.
-// Probe failures are intentionally excluded: a missing measurement cannot be dismissed.
-export const SYSTEM_HEALTH_WARNING_TYPES = ['memory', 'cpu', 'disk', 'process', 'restarts', 'apps', 'database', 'forge', 'code-review', 'health-settings'];
+// Probe failures ('probe-unavailable') are intentionally marked dismissible: false,
+// so they cannot be suppressed by the dismiss endpoint; 'probe-unavailable' is listed
+// here so it passes schema validation for requests that might include it.
+export const SYSTEM_HEALTH_WARNING_TYPES = ['memory', 'cpu', 'disk', 'process', 'restarts', 'apps', 'database', 'forge', 'code-review', 'health-settings', 'probe-unavailable'];
export const systemHealthWarningParamsSchema = z.object({ type: z.enum(SYSTEM_HEALTH_WARNING_TYPES) });
export const systemHealthWarningDismissSchema = z.object({ message: z.string().trim().min(1).max(500) });
diff --git a/server/routes/health.test.js b/server/routes/health.test.js
index 6c5b8e6a57..9b839e9ec7 100644
--- a/server/routes/health.test.js
+++ b/server/routes/health.test.js
@@ -5,7 +5,7 @@ import { getMemoryStats } from '../lib/memoryStats.js';
import express from 'express';
import { request } from '../lib/testHelper.js';
import systemHealthRoutes from './systemHealth.js';
-import { listProcesses } from '../services/pm2.js';
+import { listProcesses, listProcessesStrict } from '../services/pm2.js';
import { getStatus, getPendingTaskIds, getAgents } from '../services/cos.js';
import { getSelf } from '../services/instanceIdentity.js';
import { isAuthEnabled } from '../services/auth.js';
@@ -15,7 +15,8 @@ import { getSettingsWithStatus, updateSettingsWith } from '../services/settings.
import { statfs } from 'fs/promises';
vi.mock('../services/pm2.js', () => ({
- listProcesses: vi.fn().mockResolvedValue([])
+ listProcesses: vi.fn().mockResolvedValue([]),
+ listProcessesStrict: vi.fn().mockResolvedValue([])
}));
// Health assertions must not inherit the developer machine's disk or memory
@@ -239,7 +240,7 @@ describe('System Health Routes', () => {
});
it('does not warn on cumulative restart_time (developer-driven restarts)', async () => {
- listProcesses.mockResolvedValueOnce([
+ listProcessesStrict.mockResolvedValueOnce([
{ name: 'portos', status: 'online', restarts: 97, unstableRestarts: 0, cpu: 0, memory: 0 }
]);
const response = await request(app).get('/api/system/health/details');
@@ -248,7 +249,7 @@ describe('System Health Routes', () => {
});
it('warns when a process has unstable_restarts (real crash loop)', async () => {
- listProcesses.mockResolvedValueOnce([
+ listProcessesStrict.mockResolvedValueOnce([
{ name: 'flaky-svc', status: 'online', restarts: 5, unstableRestarts: 3, cpu: 0, memory: 0 }
]);
const response = await request(app).get('/api/system/health/details');
@@ -259,7 +260,7 @@ describe('System Health Routes', () => {
});
it('exposes thresholds and topProcesses (sorted by memory desc)', async () => {
- listProcesses.mockResolvedValueOnce([
+ listProcessesStrict.mockResolvedValueOnce([
{ name: 'small', status: 'online', memory: 100, cpu: 1, restarts: 0, unstableRestarts: 0 },
{ name: 'big', status: 'online', memory: 5_000_000, cpu: 50, restarts: 0, unstableRestarts: 0 },
{ name: 'mid', status: 'online', memory: 2_000_000, cpu: 5, restarts: 0, unstableRestarts: 0 }
@@ -322,7 +323,7 @@ describe('System Health Routes', () => {
});
it('does not downgrade an already-critical verdict to warning', async () => {
- listProcesses.mockResolvedValueOnce([
+ listProcessesStrict.mockResolvedValueOnce([
{ name: 'broken', status: 'errored', restarts: 1, unstableRestarts: 0, cpu: 0, memory: 0 }
]);
checkGhHealth.mockResolvedValueOnce({
@@ -421,12 +422,12 @@ describe('System Health Routes', () => {
describe('GET /health/details — desktop (GUI) process exemption', () => {
beforeEach(() => {
mock.desktopProcessNames = new Set();
- vi.mocked(listProcesses).mockResolvedValue([]);
+ vi.mocked(listProcessesStrict).mockResolvedValue([]);
});
it('stays healthy when the only errored process is a quit game window', async () => {
mock.desktopProcessNames = new Set(['game']);
- vi.mocked(listProcesses).mockResolvedValue([{ name: 'game', status: 'errored' }]);
+ vi.mocked(listProcessesStrict).mockResolvedValue([{ name: 'game', status: 'errored' }]);
const { body } = await request(app).get('/api/system/health/details');
@@ -437,7 +438,7 @@ describe('System Health Routes', () => {
});
it('still goes critical for a genuinely errored web process', async () => {
- vi.mocked(listProcesses).mockResolvedValue([{ name: 'web', status: 'errored' }]);
+ vi.mocked(listProcessesStrict).mockResolvedValue([{ name: 'web', status: 'errored' }]);
const { body } = await request(app).get('/api/system/health/details');
@@ -447,7 +448,7 @@ describe('System Health Routes', () => {
it('does not report a quit game as a crash loop', async () => {
mock.desktopProcessNames = new Set(['game']);
- vi.mocked(listProcesses).mockResolvedValue([
+ vi.mocked(listProcessesStrict).mockResolvedValue([
{ name: 'game', status: 'errored', unstableRestarts: 5 }
]);
@@ -459,7 +460,7 @@ describe('System Health Routes', () => {
it('counts a cleanly stopped desktop app as exited, not stopped', async () => {
mock.desktopProcessNames = new Set(['game']);
- vi.mocked(listProcesses).mockResolvedValue([{ name: 'game', status: 'stopped' }]);
+ vi.mocked(listProcessesStrict).mockResolvedValue([{ name: 'game', status: 'stopped' }]);
const { body } = await request(app).get('/api/system/health/details');
@@ -474,7 +475,7 @@ describe('System Health Routes', () => {
// `online` too would render "1 of 2 running · all healthy" with both up,
// and read identically whether the game is running or quit.
mock.desktopProcessNames = new Set(['game']);
- vi.mocked(listProcesses).mockResolvedValue([
+ vi.mocked(listProcessesStrict).mockResolvedValue([
{ name: 'game', status: 'online' },
{ name: 'web', status: 'online' }
]);
@@ -488,7 +489,7 @@ describe('System Health Routes', () => {
it('keeps resource totals covering every process, exempt or not', async () => {
mock.desktopProcessNames = new Set(['game']);
- vi.mocked(listProcesses).mockResolvedValue([
+ vi.mocked(listProcessesStrict).mockResolvedValue([
{ name: 'game', status: 'errored', memory: 100, cpu: 5, restarts: 2 },
{ name: 'web', status: 'online', memory: 50, cpu: 3, restarts: 1 }
]);
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index 34b33908a7..abd2ce68dc 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -1,7 +1,7 @@
import { Router } from 'express';
import os from 'os';
import { statfs } from 'fs/promises';
-import { listProcesses } from '../services/pm2.js';
+import { listProcesses, 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';
@@ -159,7 +159,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {
// Gather data in parallel
const [pm2Processes, appStatusSummary, cosStatus, cosPendingTaskIds, cosAgents, self, dbHealth, version, diskStats, memStats, healthSettings, forgeHealth, mediaCapacity, reviewerConfigHealth] = await Promise.all([
- listProcesses().catch(() => []),
+ 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);
@@ -216,23 +216,30 @@ router.get('/health/details', asyncHandler(async (req, res) => {
// 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.
- const annotated = await annotateExpectedExit(pm2Processes);
- const supervised = annotated.filter(p => !p.expectedExit);
- const 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)
- };
+ // 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`
@@ -263,6 +270,9 @@ router.get('/health/details', asyncHandler(async (req, res) => {
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) {
@@ -272,18 +282,20 @@ router.get('/health/details', asyncHandler(async (req, res) => {
}
}
- if (processStats.errored > 0) {
- rawWarnings.push({ type: 'process', severity: 'critical', message: `${processStats.errored} process(es) errored` });
- }
+ 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(', ')})`
- });
+ 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
@@ -450,7 +462,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {
codeReview: reviewerConfigHealth,
thresholds: thresholdsAvailable ? thresholds : undefined,
thresholdsAvailable,
- topProcesses: [...pm2Processes]
+ topProcesses: pm2Processes === null ? null : [...pm2Processes]
.sort((a, b) => (b.memory || 0) - (a.memory || 0))
.slice(0, 10)
.map(p => ({
diff --git a/server/services/pm2.js b/server/services/pm2.js
index dbe84cdbc3..b5f7314b05 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -18,6 +18,9 @@ const jlistCache = new Map();
const jlistInflight = new Map();
const cacheKey = (pm2Home) => pm2Home || '_default';
+// Track PM2 read failures per home so we log only on state change or reason change
+const jlistFailureState = new Map(); // home -> { lastError: string, lastLogged: number }
+
/**
* Invalidate the jlist TTL cache (e.g. after mutations like start/stop/delete).
* @param {string|null} [pm2Home=null]
@@ -30,6 +33,40 @@ export function clearJlistCache(pm2Home = null) {
}
}
+/**
+ * Record a PM2 read failure and log it only on state change or reason change.
+ * @param {string|null} pm2Home The PM2 home being read
+ * @param {string} errorReason Formatted error description
+ * @private
+ */
+function logJlistFailure(pm2Home, errorReason) {
+ const key = cacheKey(pm2Home);
+ const state = jlistFailureState.get(key);
+ const homeDesc = pm2Home ? 'custom' : 'default';
+
+ // Log only if no prior state, or if the reason changed
+ if (!state || state.lastError !== errorReason) {
+ console.error(`❌ PM2 read failed (home=${homeDesc}): ${errorReason}`);
+ jlistFailureState.set(key, { lastError: errorReason, lastLogged: Date.now() });
+ }
+}
+
+/**
+ * Record recovery from a PM2 read failure.
+ * @param {string|null} pm2Home The PM2 home that recovered
+ * @private
+ */
+function logJlistRecovery(pm2Home) {
+ const key = cacheKey(pm2Home);
+ const state = jlistFailureState.get(key);
+
+ if (state) {
+ const homeDesc = pm2Home ? 'custom' : 'default';
+ console.log(`✅ PM2 read recovered (home=${homeDesc})`);
+ jlistFailureState.delete(key);
+ }
+}
+
// Resolve PM2 CLI binary path from our local dependency using require.resolve
// to handle hoisted node_modules correctly.
const require = createRequire(import.meta.url);
@@ -391,16 +428,24 @@ function fetchJlist(pm2Home = null) {
pm2.connect((err) => {
if (err) {
jlistInflight.delete(key);
+ logJlistFailure(pm2Home, err.message || String(err));
resolve(null);
return;
}
pm2.list((err, list) => {
pm2.disconnect();
jlistInflight.delete(key);
- if (err || !Array.isArray(list)) {
+ if (err) {
+ logJlistFailure(pm2Home, err.message || String(err));
resolve(null);
return;
}
+ if (!Array.isArray(list)) {
+ logJlistFailure(pm2Home, 'Invalid response from pm2.list (not an array)');
+ resolve(null);
+ return;
+ }
+ logJlistRecovery(pm2Home);
jlistCache.set(key, { data: list, ts: Date.now() });
resolve(list);
});
@@ -413,28 +458,39 @@ function fetchJlist(pm2Home = null) {
env: buildEnv(pm2Home)
});
let stdout = '';
+ let stderr = '';
child.stdout.on('data', (data) => {
stdout += data.toString();
});
+ child.stderr.on('data', (data) => {
+ stderr += data.toString();
+ });
+
child.on('close', (code) => {
jlistInflight.delete(key);
if (code !== 0) {
+ const stderrTail = stderr.length > 200 ? stderr.slice(-200) : stderr;
+ const errMsg = stderrTail.trim() || `exit ${code}`;
+ logJlistFailure(pm2Home, errMsg);
resolve(null);
return;
}
const list = parseJlistStdout(stdout);
if (list === null) {
+ logJlistFailure(pm2Home, 'Failed to parse pm2 jlist output (invalid JSON)');
resolve(null);
return;
}
+ logJlistRecovery(pm2Home);
jlistCache.set(key, { data: list, ts: Date.now() });
resolve(list);
});
- child.on('error', () => {
+ child.on('error', (err) => {
jlistInflight.delete(key);
+ logJlistFailure(pm2Home, err.message || String(err));
resolve(null);
});
});