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([issue-968]): make the failed-read sentinel actually fire in production (review: codex, claude)

Adam Eivyca4e9c2f5619
diff --git a/client/src/components/AppTile.jsx b/client/src/components/AppTile.jsx
index 6803eed45e..616ca385ed 100644
--- a/client/src/components/AppTile.jsx
+++ b/client/src/components/AppTile.jsx
@@ -30,6 +30,8 @@ const AppTile = memo(function AppTile({ app, onUpdate }) {
};
const isOnline = app.overallStatus === 'online';
+ // PM2 read failed — status is genuinely unknown, so don't offer Start/Stop.
+ const isDegraded = app.degraded || app.overallStatus === 'unknown';
return (
<article className={`border rounded-lg p-3 transition-colors ${
@@ -95,7 +97,18 @@ const AppTile = memo(function AppTile({ app, onUpdate }) {
</a>
)}
- {!isOnline && (
+ {!isOnline && isDegraded && (
+ <button
+ onClick={() => onUpdate?.()}
+ className="px-2.5 py-1 text-xs rounded bg-port-warning hover:bg-port-warning/80 text-white transition-colors"
+ aria-label={`${app.name} status unavailable — refresh`}
+ title="PM2 status could not be read — refresh to retry"
+ >
+ Status unavailable
+ </button>
+ )}
+
+ {!isOnline && !isDegraded && (
<button
onClick={() => handleAction('start')}
disabled={loading === 'start'}
diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsx
index 5ce257ffa2..49675858f8 100644
--- a/client/src/components/apps/tabs/OverviewTab.jsx
+++ b/client/src/components/apps/tabs/OverviewTab.jsx
@@ -201,7 +201,8 @@ export default function OverviewTab({ app, onRefresh }) {
>
<span className={`w-2 h-2 rounded-full shrink-0 ${
proc.status === 'online' ? 'bg-port-success' :
- proc.status === 'stopped' ? 'bg-gray-500' : 'bg-port-error'
+ proc.status === 'stopped' ? 'bg-gray-500' :
+ proc.status === 'unknown' ? 'bg-port-warning' : 'bg-port-error'
}`} />
<span className="text-sm text-white font-mono">{proc.name}</span>
{processConfig?.ports && Object.keys(processConfig.ports).length > 0 && (
diff --git a/client/src/components/city/HolographicPanel.jsx b/client/src/components/city/HolographicPanel.jsx
index e14c13dccb..a7f34b59cf 100644
--- a/client/src/components/city/HolographicPanel.jsx
+++ b/client/src/components/city/HolographicPanel.jsx
@@ -5,6 +5,7 @@ const STATUS_ICONS = {
stopped: '\u25A0',
not_started: '\u25CB',
not_found: '\u25CB',
+ unknown: '\u25CB',
};
export default function HolographicPanel({ app, agentCount, position, expanded = false }) {
@@ -13,6 +14,8 @@ export default function HolographicPanel({ app, agentCount, position, expanded =
stopped: 'border-red-500/50 text-red-400',
not_started: 'border-violet-500/50 text-violet-400',
not_found: 'border-violet-500/50 text-violet-400',
+ // PM2 read failed \u2014 gray, matching the city building, distinct from violet.
+ unknown: 'border-gray-400/50 text-gray-400',
};
const statusDotColors = {
@@ -20,6 +23,7 @@ export default function HolographicPanel({ app, agentCount, position, expanded =
stopped: 'text-red-400',
not_started: 'text-violet-400',
not_found: 'text-violet-400',
+ unknown: 'text-gray-400',
};
const colorClass = app.archived
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index 8dac9dafdd..9c82772b22 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -447,7 +447,8 @@ export default function Apps() {
>
<span className={`w-2 h-2 rounded-full shrink-0 ${
proc.status === 'online' ? 'bg-port-success' :
- proc.status === 'stopped' ? 'bg-gray-500' : 'bg-port-error'
+ proc.status === 'stopped' ? 'bg-gray-500' :
+ proc.status === 'unknown' ? 'bg-port-warning' : 'bg-port-error'
}`} />
<span className="text-sm text-white font-mono">{proc.name}</span>
{processConfig?.ports && Object.keys(processConfig.ports).length > 0 && (
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 484e3320d1..bdab6cf1c9 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -68,14 +68,15 @@ router.get('/', asyncHandler(async (req, res) => {
}
// Fetch PM2 processes for each unique PM2_HOME.
- // A thrown listProcesses is a failed read, not an empty list — track those
- // homes so we report `unknown` (status unavailable) instead of `not_started`
- // (confidently not running) for their apps. See getAppStatuses() in the
- // service for the same absent-vs-empty distinction.
+ // listProcessesStrict returns `null` on a failed read (vs `[]` for a
+ // successful read with no processes) — track those homes so we report
+ // `unknown` (status unavailable) instead of `not_started` (confidently not
+ // running) for their apps. See getAppStatuses() in the service for the same
+ // absent-vs-empty distinction.
const pm2Maps = new Map();
const failedHomes = new Set();
for (const pm2Home of pm2HomeGroups.keys()) {
- const processes = await pm2Service.listProcesses(pm2Home).catch(() => null);
+ const processes = await pm2Service.listProcessesStrict(pm2Home);
if (processes === null) {
failedHomes.add(pm2Home);
pm2Maps.set(pm2Home, new Map());
@@ -168,22 +169,27 @@ router.get('/:id', loadApp, asyncHandler(async (req, res) => {
let degraded = false;
if (usesPm2(app.type)) {
- // Get PM2 status for each process (using app's custom PM2_HOME if set).
- // A thrown getAppStatus is a failed read, not a confident "not running" —
- // mark `degraded` so the detail UI can disable lifecycle controls rather
- // than offer a misleading Start. Mirrors the list endpoint's `degraded`.
+ // getAppStatusStrict returns `null` when the PM2 read failed (vs a real
+ // status object). A failed read is genuinely unknown, not "not running" —
+ // mark `degraded` so the detail UI can offer refresh-to-retry rather than a
+ // misleading Start. Mirrors the list endpoint's `degraded`.
for (const processName of app.pm2ProcessNames || []) {
- const status = await pm2Service.getAppStatus(processName, app.pm2Home).catch(() => {
+ const status = await pm2Service.getAppStatusStrict(processName, app.pm2Home);
+ if (status === null) {
degraded = true;
- return { status: 'unknown' };
- });
- statuses[processName] = status;
+ statuses[processName] = { name: processName, status: 'unknown', pm2_env: null };
+ } else {
+ statuses[processName] = status;
+ }
}
- // Compute overall status (same logic as list endpoint)
+ // Compute overall status (same logic as list endpoint). A degraded read
+ // short-circuits to `unknown` rather than collapsing to `not_started`.
const statusValues = Object.values(statuses);
overallStatus = 'unknown';
- if (statusValues.some(s => s.status === 'online')) {
+ if (degraded) {
+ overallStatus = 'unknown';
+ } else if (statusValues.some(s => s.status === 'online')) {
overallStatus = 'online';
} else if (statusValues.some(s => s.status === 'stopped')) {
overallStatus = 'stopped';
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index bb1efa5382..5aeb5759ed 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -20,7 +20,9 @@ vi.mock('../services/apps.js', () => ({
vi.mock('../services/pm2.js', () => ({
listProcesses: vi.fn(),
+ listProcessesStrict: vi.fn(),
getAppStatus: vi.fn(),
+ getAppStatusStrict: vi.fn(),
startWithCommand: vi.fn(),
stopApp: vi.fn(),
restartApp: vi.fn(),
@@ -105,7 +107,7 @@ describe('Apps Routes', () => {
];
appsService.getAllApps.mockResolvedValue(mockApps);
- pm2Service.listProcesses.mockResolvedValue(mockPm2Processes);
+ pm2Service.listProcessesStrict.mockResolvedValue(mockPm2Processes);
streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);
const response = await request(app).get('/api/apps');
@@ -121,7 +123,7 @@ describe('Apps Routes', () => {
];
appsService.getAllApps.mockResolvedValue(mockApps);
- pm2Service.listProcesses.mockResolvedValue([]);
+ pm2Service.listProcessesStrict.mockResolvedValue([]);
streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);
const response = await request(app).get('/api/apps');
@@ -136,8 +138,9 @@ describe('Apps Routes', () => {
];
appsService.getAllApps.mockResolvedValue(mockApps);
- // A failed PM2 read must not collapse into a confident "not started."
- pm2Service.listProcesses.mockRejectedValue(new Error('pm2 daemon unreachable'));
+ // Strict read returns null on a failed PM2 read — must not collapse into
+ // a confident "not started."
+ pm2Service.listProcessesStrict.mockResolvedValue(null);
streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);
const response = await request(app).get('/api/apps');
@@ -150,7 +153,7 @@ describe('Apps Routes', () => {
it('should return empty array when no apps exist', async () => {
appsService.getAllApps.mockResolvedValue([]);
- pm2Service.listProcesses.mockResolvedValue([]);
+ pm2Service.listProcessesStrict.mockResolvedValue([]);
const response = await request(app).get('/api/apps');
@@ -167,7 +170,7 @@ describe('Apps Routes', () => {
pm2ProcessNames: ['test-app']
};
appsService.getAppById.mockResolvedValue(mockApp);
- pm2Service.getAppStatus.mockResolvedValue({ status: 'online' });
+ pm2Service.getAppStatusStrict.mockResolvedValue({ name: 'test-app', status: 'online' });
const response = await request(app).get('/api/apps/app-001');
@@ -183,9 +186,10 @@ describe('Apps Routes', () => {
pm2ProcessNames: ['test-app']
};
appsService.getAppById.mockResolvedValue(mockApp);
- // Detail endpoint reads per-process status; a thrown read must surface
- // as degraded, not collapse into a confident not_started.
- pm2Service.getAppStatus.mockRejectedValue(new Error('pm2 daemon unreachable'));
+ // Detail endpoint reads per-process status via the strict variant, which
+ // returns null on a failed read — must surface as degraded, not collapse
+ // into a confident not_started.
+ pm2Service.getAppStatusStrict.mockResolvedValue(null);
const response = await request(app).get('/api/apps/app-001');
@@ -383,7 +387,7 @@ describe('Apps Routes', () => {
processes: [{ name: 'test-app', ports: { devUi: 5554 } }]
}];
appsService.getAllApps.mockResolvedValue(mockApps);
- pm2Service.listProcesses.mockResolvedValue([]);
+ pm2Service.listProcessesStrict.mockResolvedValue([]);
const response = await request(app).get('/api/apps');
@@ -403,7 +407,7 @@ describe('Apps Routes', () => {
]
}];
appsService.getAllApps.mockResolvedValue(mockApps);
- pm2Service.listProcesses.mockResolvedValue([]);
+ pm2Service.listProcessesStrict.mockResolvedValue([]);
const response = await request(app).get('/api/apps');
@@ -423,7 +427,7 @@ describe('Apps Routes', () => {
processes: [{ name: 'test-app', ports: { devUi: 5554 } }]
}];
appsService.getAllApps.mockResolvedValue(mockApps);
- pm2Service.listProcesses.mockResolvedValue([]);
+ pm2Service.listProcessesStrict.mockResolvedValue([]);
const response = await request(app).get('/api/apps');
diff --git a/server/services/apps.js b/server/services/apps.js
index d8ace33f85..bcb4657e34 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -3,7 +3,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import EventEmitter from 'events';
import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
import { NON_PM2_TYPES, usesPm2 } from './streamingDetect.js';
-import { listProcesses } from './pm2.js';
+import { listProcessesStrict } from './pm2.js';
import { SELF_IMPROVEMENT_TASK_TYPES } from './taskSchedule.js';
import { sanitizeTaskMetadata } from '../lib/validation.js';
import { PORTS } from '../lib/ports.js';
@@ -193,8 +193,9 @@ export async function getActiveApps() {
* primitive behind both `getAppStatusSummary()` (counts) and the CyberCity
* snapshot pipeline (per-building status), so the two never drift.
*
- * Absent-vs-empty rule (CLAUDE.md): a `listProcesses(home)` that *throws* is a
- * failed read, NOT a successful "no processes." Folding it into `[]` would
+ * Absent-vs-empty rule (CLAUDE.md): `listProcessesStrict(home)` returns `null`
+ * when the PM2 read FAILED (vs `[]` for a successful read with no processes).
+ * The generic `listProcesses` flattens a failed read into `[]`, which would
* record every app in that home as `not_started` (status known: never launched)
* when the truth is `unknown` (status unavailable: PM2 unreachable). We track
* failed homes explicitly and mark their apps `overallStatus: 'unknown'` +
@@ -217,8 +218,8 @@ export async function getAppStatuses() {
const procMaps = new Map();
const failedHomes = new Set();
for (const home of homeGroups.keys()) {
- // `null` sentinel on throw distinguishes a failed read from an empty list.
- const procs = await listProcesses(home).catch(() => null);
+ // `null` = PM2 read failed (vs `[]` = read OK, no processes).
+ const procs = await listProcessesStrict(home);
if (procs === null) {
failedHomes.add(home);
procMaps.set(home, new Map());
diff --git a/server/services/apps.test.js b/server/services/apps.test.js
index 6d8489255c..0c477d4f2b 100644
--- a/server/services/apps.test.js
+++ b/server/services/apps.test.js
@@ -25,11 +25,13 @@ vi.mock('./taskSchedule.js', () => ({
}));
vi.mock('./pm2.js', () => ({
- listProcesses: vi.fn().mockResolvedValue([]),
+ // Strict variant: resolves an array on success (incl. []), or null on a
+ // failed PM2 read. The status getters use this, not the forgiving listProcesses.
+ listProcessesStrict: vi.fn().mockResolvedValue([]),
}));
import { readJSONFile } from '../lib/fileUtils.js';
-import { listProcesses } from './pm2.js';
+import { listProcessesStrict } from './pm2.js';
import { getAppStatuses, getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID } from './apps.js';
describe('getReservedPorts', () => {
@@ -157,7 +159,7 @@ describe('getAppStatusSummary', () => {
}
}
});
- listProcesses.mockResolvedValue([
+ listProcessesStrict.mockResolvedValue([
{ name: 'portos-server', status: 'online' },
{ name: 'svc-a', status: 'stopped' }
// svc-b is missing → not_found → notStarted
@@ -185,7 +187,7 @@ describe('getAppStatusSummary', () => {
}
}
});
- listProcesses.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);
+ listProcessesStrict.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);
const summary = await getAppStatusSummary();
expect(summary).toEqual({
@@ -225,7 +227,7 @@ describe('getAppStatusSummary', () => {
}
}
});
- listProcesses.mockImplementation(async (home) => {
+ listProcessesStrict.mockImplementation(async (home) => {
if (home === '/tmp/other-pm2') return [{ name: 'c', status: 'online' }];
return [
{ name: 'portos-server', status: 'online' },
@@ -235,7 +237,7 @@ describe('getAppStatusSummary', () => {
});
const summary = await getAppStatusSummary();
- expect(listProcesses).toHaveBeenCalledTimes(2);
+ expect(listProcessesStrict).toHaveBeenCalledTimes(2);
expect(summary).toMatchObject({ total: 4, online: 3, stopped: 1, notStarted: 0, unmanaged: 0 });
});
@@ -255,7 +257,7 @@ describe('getAppStatusSummary', () => {
}
}
});
- listProcesses.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);
+ listProcessesStrict.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);
const summary = await getAppStatusSummary();
expect(summary.total).toBe(1);
@@ -268,8 +270,8 @@ describe('getAppStatusSummary', () => {
'svc-a': { name: 'svc-a', type: 'express', pm2ProcessNames: ['svc-a'] }
}
});
- // The default PM2 home throws — a transient read failure, NOT an empty list.
- listProcesses.mockRejectedValue(new Error('pm2 daemon unreachable'));
+ // Strict read returns null on a transient PM2 failure (NOT an empty list).
+ listProcessesStrict.mockResolvedValue(null);
const summary = await getAppStatusSummary();
expect(summary).toEqual({
@@ -290,8 +292,8 @@ describe('getAppStatusSummary', () => {
'custom-home': { name: 'c', type: 'express', pm2Home: '/tmp/other-pm2', pm2ProcessNames: ['c'] }
}
});
- listProcesses.mockImplementation(async (home) => {
- if (home === '/tmp/other-pm2') throw new Error('this home is down');
+ listProcessesStrict.mockImplementation(async (home) => {
+ if (home === '/tmp/other-pm2') return null; // this home's read failed
return [{ name: 'portos-server', status: 'online' }];
});
@@ -312,7 +314,7 @@ describe('getAppStatuses', () => {
[PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] }
}
});
- listProcesses.mockRejectedValue(new Error('pm2 daemon unreachable'));
+ listProcessesStrict.mockResolvedValue(null);
const statuses = await getAppStatuses();
const portos = statuses.find(s => s.id === PORTOS_APP_ID);
@@ -327,7 +329,7 @@ describe('getAppStatuses', () => {
}
});
// Successful read, genuinely no processes → not_started, NOT unknown.
- listProcesses.mockResolvedValue([]);
+ listProcessesStrict.mockResolvedValue([]);
const statuses = await getAppStatuses();
const portos = statuses.find(s => s.id === PORTOS_APP_ID);
diff --git a/server/services/pm2.js b/server/services/pm2.js
index a686b17161..ad52327565 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -233,6 +233,9 @@ export async function deleteApp(name, pm2Home = null) {
*/
export async function getAppStatus(name, pm2Home = null) {
const processes = await fetchJlist(pm2Home);
+ // `error` here means "PM2 read failed", but it's the same forgiving shape the
+ // generic callers expect. App-status callers that must distinguish a failed
+ // read from a genuine state use getAppStatusStrict (null sentinel) instead.
if (!processes) return { name, status: 'error', pm2_env: null };
const proc = processes.find(p => p.name === name);
@@ -240,6 +243,28 @@ export async function getAppStatus(name, pm2Home = null) {
return { name, status: 'not_found', pm2_env: null };
}
+ return shapeProcStatus(proc);
+}
+
+/**
+ * Strict variant of {@link getAppStatus}: returns `null` when the PM2 read
+ * FAILED, distinct from a `{ status: 'not_found' }` for a read that succeeded
+ * but found no matching process. The detail endpoint uses this so a daemon
+ * blip surfaces as `degraded` rather than a confident `not_started`.
+ *
+ * @returns {Promise<object|null>} Process status, `{ status: 'not_found' }`, or
+ * `null` on read failure.
+ */
+export async function getAppStatusStrict(name, pm2Home = null) {
+ const processes = await fetchJlist(pm2Home);
+ if (!processes) return null;
+ const proc = processes.find(p => p.name === name);
+ if (!proc) return { name, status: 'not_found', pm2_env: null };
+ return shapeProcStatus(proc);
+}
+
+// Shared shaping for getAppStatus / getAppStatusStrict so the two never drift.
+function shapeProcStatus(proc) {
return {
name: proc.name,
status: proc.pm2_env?.status || 'unknown',
@@ -333,7 +358,32 @@ function fetchJlist(pm2Home = null) {
export async function listProcesses(pm2Home = null) {
const list = await fetchJlist(pm2Home);
if (!list) return [];
- return list.map(proc => ({
+ return list.map(mapProcess);
+}
+
+/**
+ * Strict variant of {@link listProcesses}: returns `null` when the PM2 read
+ * FAILED (daemon unreachable / non-zero exit) and the mapped array otherwise —
+ * including `[]` for a successful read with no processes.
+ *
+ * `listProcesses()` flattens a failed read into `[]`, which is the right
+ * forgiving behavior for log/command/voice callers that just want "whatever is
+ * running." But app-status getters MUST distinguish "PM2 unreachable" from
+ * "nothing running" (CLAUDE.md absent-vs-empty rule) — collapsing them records
+ * a transient blip as every app `not_started`. Those callers use this instead.
+ *
+ * @param {string} pm2Home Optional custom PM2_HOME path
+ * @returns {Promise<Array|null>} Mapped process list, or `null` on read failure.
+ */
+export async function listProcessesStrict(pm2Home = null) {
+ const list = await fetchJlist(pm2Home);
+ if (!list) return null;
+ return list.map(mapProcess);
+}
+
+// Shared shaping for listProcesses / listProcessesStrict so the two never drift.
+function mapProcess(proc) {
+ return {
name: proc.name,
status: proc.pm2_env?.status || 'unknown',
pid: proc.pid,
@@ -343,7 +393,7 @@ export async function listProcesses(pm2Home = null) {
uptime: proc.pm2_env?.pm_uptime ? Date.now() - proc.pm2_env.pm_uptime : null,
restarts: proc.pm2_env?.restart_time || 0,
unstableRestarts: proc.pm2_env?.unstable_restarts || 0
- }));
+ };
}
/**