Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-968]): distinguish failed PM2 read from empty process list in app status
Adam Eivy4566ccf41673
diff --git a/server/lib/capabilityMap.js b/server/lib/capabilityMap.jsindex 8512268741..21ae7788ee 100644--- a/server/lib/capabilityMap.js+++ b/server/lib/capabilityMap.js@@ -234,13 +234,18 @@ export function appsRow(summary = {}) {// setup gap this page exists to surface, so it degrades the row too. unmanaged// (Xcode/native projects with no runtime state) is intentionally NOT counted.const notStarted = Number(summary?.notStarted) || 0;+ // unknown = PM2 home read failed — runtime status unavailable, NOT a confident+ // "not running." Surfaced separately so a transient PM2 blip reads as+ // "status unavailable" rather than inflating the not-started/stopped count.+ const unknown = Number(summary?.unknown) || 0;return row('apps', 'Apps & Processes', '/apps', {- status: stopped > 0 || notStarted > 0 ? WARN : OK,+ status: stopped > 0 || notStarted > 0 || unknown > 0 ? WARN : OK,configured: true,summary: `${total} ${plural(total, 'app')} · ${online} online`+ (stopped > 0 ? ` · ${stopped} stopped` : '')- + (notStarted > 0 ? ` · ${notStarted} not started` : ''),- detail: { total, online, stopped, notStarted, unmanaged },+ + (notStarted > 0 ? ` · ${notStarted} not started` : '')+ + (unknown > 0 ? ` · ${unknown} status unavailable` : ''),+ detail: { total, online, stopped, notStarted, unknown, degraded: unknown > 0, unmanaged },});}diff --git a/server/lib/capabilityMap.test.js b/server/lib/capabilityMap.test.jsindex a5bfd375ca..f9232ab05f 100644--- a/server/lib/capabilityMap.test.js+++ b/server/lib/capabilityMap.test.js@@ -166,6 +166,14 @@ describe('appsRow', () => {expect(r.detail.notStarted).toBe(3);});+ it('warns and reports "status unavailable" when PM2 read degraded the summary', () => {+ const r = appsRow({ total: 3, online: 2, stopped: 0, notStarted: 0, unknown: 1, degraded: true });+ expect(r.status).toBe(WARN);+ expect(r.summary).toContain('1 status unavailable');+ expect(r.detail.unknown).toBe(1);+ expect(r.detail.degraded).toBe(true);+ });+it('reports native-only (unmanaged) apps as present, not "No apps"', () => {// getAppStatusSummary().total excludes unmanaged native/Xcode apps.const r = appsRow({ total: 0, online: 0, unmanaged: 2 });diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 1424244878..b967494eb3 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -67,11 +67,21 @@ router.get('/', asyncHandler(async (req, res) => {pm2HomeGroups.get(home).push(app);}- // Fetch PM2 processes for each unique PM2_HOME+ // 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.const pm2Maps = new Map();+ const failedHomes = new Set();for (const pm2Home of pm2HomeGroups.keys()) {- const processes = await pm2Service.listProcesses(pm2Home).catch(() => []);- pm2Maps.set(pm2Home, new Map(processes.map(p => [p.name, p])));+ const processes = await pm2Service.listProcesses(pm2Home).catch(() => null);+ if (processes === null) {+ failedHomes.add(pm2Home);+ pm2Maps.set(pm2Home, new Map());+ } else {+ pm2Maps.set(pm2Home, new Map(processes.map(p => [p.name, p])));+ }}// Enrich with PM2 status and auto-populate processes if needed@@ -83,17 +93,24 @@ router.get('/', asyncHandler(async (req, res) => {const pm2Home = app.pm2Home || null;const pm2Map = pm2Maps.get(pm2Home) || new Map();+ const homeFailed = failedHomes.has(pm2Home);const statuses = {};for (const processName of app.pm2ProcessNames || []) {const pm2Proc = pm2Map.get(processName);- statuses[processName] = pm2Proc ?? { name: processName, status: 'not_found', pm2_env: null };+ // A failed PM2 read leaves status genuinely unknown — don't claim+ // `not_found` (which the UI reads as "registered but never launched").+ statuses[processName] = pm2Proc+ ?? { name: processName, status: homeFailed ? 'unknown' : 'not_found', pm2_env: null };}- // Compute overall status+ // Compute overall status. A failed PM2 home short-circuits to `unknown`+ // with a `degraded` flag rather than collapsing to `not_started`.const statusValues = Object.values(statuses);let overallStatus = 'unknown';- if (statusValues.some(s => s.status === 'online')) {+ if (homeFailed) {+ overallStatus = 'unknown';+ } else if (statusValues.some(s => s.status === 'online')) {overallStatus = 'online';} else if (statusValues.some(s => s.status === 'stopped')) {overallStatus = 'stopped';@@ -132,6 +149,7 @@ router.get('/', asyncHandler(async (req, res) => {apiPort,pm2Status: statuses,overallStatus,+ degraded: homeFailed,hasDeployScript: hasDeployScript(app),xcodeScripts: checkScripts(app)};diff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsindex c310bd9027..817c02d115 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -130,6 +130,24 @@ describe('Apps Routes', () => {expect(response.body[0].overallStatus).toBe('not_started');});+ it('reports unknown + degraded (not not_started) when the PM2 read fails', async () => {+ const mockApps = [+ { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }+ ];++ appsService.getAllApps.mockResolvedValue(mockApps);+ // A failed PM2 read must not collapse into a confident "not started."+ pm2Service.listProcesses.mockRejectedValue(new Error('pm2 daemon unreachable'));+ streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body[0].overallStatus).toBe('unknown');+ expect(response.body[0].degraded).toBe(true);+ expect(response.body[0].pm2Status['test-app'].status).toBe('unknown');+ });+it('should return empty array when no apps exist', async () => {appsService.getAllApps.mockResolvedValue([]);pm2Service.listProcesses.mockResolvedValue([]);diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex f51da22ca8..7eb0e402fa 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -61,7 +61,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {// Gather data in parallelconst [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds] = await Promise.all([listProcesses().catch(() => []),- apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unmanaged: 0 })),+ apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),cos.getStatus().catch(() => null),getSelf().catch(() => null),checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),@@ -155,6 +155,15 @@ router.get('/health/details', asyncHandler(async (req, res) => {});}+ // 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) {+ if (overallHealth !== 'critical') overallHealth = 'warning';+ const unknown = appStats.unknown || 0;+ warnings.push({ type: 'apps', message: `App status unavailable for ${unknown} app(s) — PM2 read failed` });+ }+if (!dbHealth.connected) {if (overallHealth !== 'critical') overallHealth = 'warning';warnings.push({ type: 'database', message: `PostgreSQL disconnected${dbHealth.error ? `: ${dbHealth.error}` : ''}` });diff --git a/server/services/apps.js b/server/services/apps.jsindex 8efc56a841..d8ace33f85 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -187,13 +187,21 @@ export async function getActiveApps() {* Resolve each active app's overall PM2 status in one pass.** Returns one entry per active app — PM2-runnable apps carry a derived- * `overallStatus` of `online` / `stopped` / `not_started`; native projects- * (Xcode, iOS, macOS) report `n/a` since they have no detectable runtime.- * Each unique PM2_HOME is queried at most once. This is the shared primitive- * behind both `getAppStatusSummary()` (counts) and the CyberCity snapshot- * pipeline (per-building status), so the two never drift.+ * `overallStatus` of `online` / `stopped` / `not_started` / `unknown`; native+ * projects (Xcode, iOS, macOS) report `n/a` since they have no detectable+ * runtime. Each unique PM2_HOME is queried at most once. This is the shared+ * primitive behind both `getAppStatusSummary()` (counts) and the CyberCity+ * snapshot pipeline (per-building status), so the two never drift.*- * @returns {Promise<Array<{ id, name, type, repoPath, overallStatus, managed: boolean }>>}+ * Absent-vs-empty rule (CLAUDE.md): a `listProcesses(home)` that *throws* is a+ * failed read, NOT a successful "no processes." Folding it into `[]` 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'` ++ * `degraded: true`, so a transient PM2 blip can't masquerade as "all apps+ * offline." Homes that read fine still report accurate status alongside.+ *+ * @returns {Promise<Array<{ id, name, type, repoPath, overallStatus, managed: boolean, degraded?: boolean }>>}*/export async function getAppStatuses() {const apps = await getAllApps({ includeArchived: false });@@ -207,9 +215,16 @@ export async function getAppStatuses() {}const procMaps = new Map();+ const failedHomes = new Set();for (const home of homeGroups.keys()) {- const procs = await listProcesses(home).catch(() => []);- procMaps.set(home, new Map(procs.map(p => [p.name, p])));+ // `null` sentinel on throw distinguishes a failed read from an empty list.+ const procs = await listProcesses(home).catch(() => null);+ if (procs === null) {+ failedHomes.add(home);+ procMaps.set(home, new Map());+ } else {+ procMaps.set(home, new Map(procs.map(p => [p.name, p])));+ }}return apps.map(app => {@@ -221,7 +236,13 @@ export async function getAppStatuses() {if (!managed) {return { ...base, overallStatus: 'n/a', managed: false };}- const procMap = procMaps.get(app.pm2Home || null) || new Map();+ const home = app.pm2Home || null;+ if (failedHomes.has(home)) {+ // PM2 read for this home failed — runtime status is genuinely unknown,+ // NOT a confident `not_started`. `degraded` lets callers surface the gap.+ return { ...base, overallStatus: 'unknown', managed: true, degraded: true };+ }+ const procMap = procMaps.get(home) || new Map();const names = app.pm2ProcessNames || [];let overallStatus = 'not_started';if (names.length > 0) {@@ -237,12 +258,19 @@ export async function getAppStatuses() {export async function getAppStatusSummary() {const statuses = await getAppStatuses();const managed = statuses.filter(s => s.managed);+ // `unknown` = PM2 home read failed (status unavailable), distinct from+ // `notStarted` (read succeeded, app simply isn't running). `degraded` flags+ // that at least one managed app's runtime status couldn't be determined, so+ // consumers don't report a PM2 blip as a confident "everything offline."+ const unknown = managed.filter(s => s.overallStatus === 'unknown').length;return {total: managed.length,online: managed.filter(s => s.overallStatus === 'online').length,stopped: managed.filter(s => s.overallStatus === 'stopped').length,notStarted: managed.filter(s => s.overallStatus === 'not_started').length,+ unknown,+ degraded: unknown > 0,unmanaged: statuses.length - managed.length};}diff --git a/server/services/apps.test.js b/server/services/apps.test.jsindex 60cd7542c2..6d8489255c 100644--- a/server/services/apps.test.js+++ b/server/services/apps.test.js@@ -30,7 +30,7 @@ vi.mock('./pm2.js', () => ({import { readJSONFile } from '../lib/fileUtils.js';import { listProcesses } from './pm2.js';-import { getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID } from './apps.js';+import { getAppStatuses, getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID } from './apps.js';describe('getReservedPorts', () => {beforeEach(() => {@@ -169,6 +169,8 @@ describe('getAppStatusSummary', () => {online: 1,stopped: 1,notStarted: 1,+ unknown: 0,+ degraded: false,unmanaged: 2});});@@ -191,6 +193,8 @@ describe('getAppStatusSummary', () => {online: 1,stopped: 0,notStarted: 0,+ unknown: 0,+ degraded: false,unmanaged: 0});});@@ -256,4 +260,78 @@ describe('getAppStatusSummary', () => {const summary = await getAppStatusSummary();expect(summary.total).toBe(1);});++ it('marks the summary degraded (not all not-started) when a PM2 read fails', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },+ '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'));++ const summary = await getAppStatusSummary();+ expect(summary).toEqual({+ total: 2,+ online: 0,+ stopped: 0,+ notStarted: 0,+ unknown: 2,+ degraded: true,+ unmanaged: 0+ });+ });++ it('keeps accurate counts for healthy homes when only one home fails', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },+ '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');+ return [{ name: 'portos-server', status: 'online' }];+ });++ const summary = await getAppStatusSummary();+ expect(summary).toMatchObject({ total: 2, online: 1, unknown: 1, degraded: true });+ });+});++describe('getAppStatuses', () => {+ beforeEach(() => {+ invalidateCache();+ vi.clearAllMocks();+ });++ it('reports unknown + degraded for apps whose PM2 home read failed', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] }+ }+ });+ listProcesses.mockRejectedValue(new Error('pm2 daemon unreachable'));++ const statuses = await getAppStatuses();+ const portos = statuses.find(s => s.id === PORTOS_APP_ID);+ expect(portos.overallStatus).toBe('unknown');+ expect(portos.degraded).toBe(true);+ });++ it('does NOT mark apps unknown when the PM2 home reads an empty list', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] }+ }+ });+ // Successful read, genuinely no processes → not_started, NOT unknown.+ listProcesses.mockResolvedValue([]);++ const statuses = await getAppStatuses();+ const portos = statuses.find(s => s.id === PORTOS_APP_ID);+ expect(portos.overallStatus).toBe('not_started');+ expect(portos.degraded).toBeUndefined();+ });});