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
refactor: separate app process status projections (#8165)
[._.]/ Adam Eivycc4bb77f138a
diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.jsindex 404cd92908..f863229b4d 100644--- a/client/src/components/apps/constants.js+++ b/client/src/components/apps/constants.js@@ -1,5 +1,5 @@// From lib/, NOT services/apiCore.js: this file is imported by a node-env server-// test (streamingDetect's DESKTOP_TYPES parity check), where apiCore's React+// test (appProcessTypes' DESKTOP_TYPES parity check), where apiCore's React// dependency doesn't resolve.import { PORTOS_APP_ID } from '../../lib/appIdentity.js';import { APP_FEATURE_IDS, INSTANCE_FEATURES } from '../../../../server/lib/instanceFeatureRegistry.js';@@ -11,7 +11,7 @@ export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'sw// class string — Tailwind only sees classes it can read in source.export const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden';-// Mirrors DESKTOP_TYPES in server/services/streamingDetect.js — app types that run+// Mirrors DESKTOP_TYPES in server/services/appProcessTypes.js — app types that run// a GUI/desktop process with no HTTP port (a game binary). Kept in sync by hand// (a parity test asserts the two Sets match); the server stays the source of truth// for what the type MEANS (autorestart off, command-launched, exempt from@@ -46,7 +46,7 @@ export function resolveLaunchPanelProcess(app, result) {}// Mirrors NON_NODE_TYPES / NON_STANDARDIZABLE_TYPES in-// server/services/streamingDetect.js (parity tests assert the Sets match). The+// server/services/appProcessTypes.js (parity tests assert the Sets match). The// PM2 standardizer writes a NODE ecosystem config from a prompt that opens "You// are analyzing a Node.js application", so a Python/Go/Docker/static repo must// not be offered the flow. It's a DENY list, not an allowlist of Node types:diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex d8404148d9..fa694e52c6 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -102,6 +102,10 @@ const NARROWED = ['needs CUT_TYPES/SAFE_CUT_TYPES only'],['services/apps.js', 'lib/validation.js','needs sanitizeTaskMetadata, which cosValidation.js declares'],+ ['services/apps.js', 'services/pm2.js',+ 'keeps PM2 process projections out of the registry graph'],+ ['services/apps.js', 'services/streamingDetect.js',+ 'reads process-type vocabulary from the dependency-free leaf'],['services/memoryEmbeddings.js', 'services/memoryBackend.js','needs DEFAULT_MEMORY_CONFIG, which memoryConfig.js declares'],['lib/llmRoutePin.js', 'lib/storyBible.js',@@ -158,6 +162,10 @@ describe('narrowed imports stay narrow (#6009)', () => {expect(reaches('services/agentAppWorkspace.js', 'lib/fileUtils.js')).toBe(true);expect(reaches('lib/pipelineValidation.js', 'lib/editorial/checkInfra/taxonomy.js')).toBe(true);expect(reaches('services/apps.js', 'lib/cosValidation.js')).toBe(true);+ expect(reaches('services/appProcessTypes.js', 'services/appProcessTypes.js')).toBe(true);+ expect(reaches('services/streamingDetect.js', 'services/appProcessTypes.js')).toBe(true);+ expect(reaches('services/appProcessStatus.js', 'services/apps.js')).toBe(true);+ expect(reaches('services/appProcessStatus.js', 'services/pm2.js')).toBe(true);expect(reaches('services/memoryEmbeddings.js', 'services/memoryConfig.js')).toBe(true);expect(reaches('lib/llmRoutePin.js', 'lib/textUtils.js')).toBe(true);expect(reaches('lib/slashdoInvocation.js', 'lib/providerVendors.js')).toBe(true);@@ -166,6 +174,11 @@ describe('narrowed imports stay narrow (#6009)', () => {expect(reaches('lib/storyBible.js', 'lib/textUtils.js')).toBe(true);});+ it('keeps the process-type vocabulary dependency-free', () => {+ const entry = abs('services/appProcessTypes.js');+ expect([...staticImportClosure(entry).files]).toEqual([entry]);+ });+// And a control on the other side: the barrels themselves still reach what// they re-export, so "nobody reaches checkRegistry" is a statement about the// narrowed callers, not about a broken registry.diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.jsindex a7df43f962..68179f0a27 100644--- a/server/routes/apps/crud.js+++ b/server/routes/apps/crud.js@@ -23,7 +23,7 @@ import { notifyAppsChanged, PORTOS_APP_ID } from '../../services/apps.js';import * as pm2Service from '../../services/pm2.js';import { validateRequest, appSchema, appUpdateSchema } from '../../lib/validation.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';-import { usesPm2 } from '../../services/streamingDetect.js';+import { usesPm2 } from '../../services/appProcessTypes.js';import { detectAppIcon } from '../../services/appIconDetect.js';import { hasDeployScript } from '../../services/appDeployer.js';import { checkScripts } from '../../services/xcodeScripts.js';diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.jsindex 0a5cff4e93..f0490f3631 100644--- a/server/routes/apps/crud.test.js+++ b/server/routes/apps/crud.test.js@@ -32,6 +32,8 @@ vi.mock('../../services/pm2.js', () => ({vi.mock('../../services/streamingDetect.js', () => ({parseEcosystemFromPath: vi.fn(),writeEcosystemPortEdits: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true, remapApplied: true, applied: [], unapplied: [] }),+}));+vi.mock('../../services/appProcessTypes.js', () => ({usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift'])}));diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.jsindex 445654e62d..f83fd31355 100644--- a/server/routes/apps/lifecycle.js+++ b/server/routes/apps/lifecycle.js@@ -23,7 +23,8 @@ import * as pm2Service from '../../services/pm2.js';import * as appBuilder from '../../services/appBuilder.js';import { logAction } from '../../services/history.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';-import { parseEcosystemFromPath, usesPm2, isDesktopType } from '../../services/streamingDetect.js';+import { parseEcosystemFromPath } from '../../services/streamingDetect.js';+import { usesPm2, isDesktopType } from '../../services/appProcessTypes.js';import { detectAppIcon, isUsableSvg } from '../../services/appIconDetect.js';import { loadApp, pathExists, deriveUiPort } from './shared.js';diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.jsindex 01c3ecd7ca..8a414e9462 100644--- a/server/routes/apps/lifecycle.test.js+++ b/server/routes/apps/lifecycle.test.js@@ -36,8 +36,9 @@ vi.mock('../../services/history.js', () => ({vi.mock('../../services/streamingDetect.js', () => ({parseEcosystemFromPath: vi.fn(),+}));+vi.mock('../../services/appProcessTypes.js', () => ({usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),- NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift']),isDesktopType: vi.fn((type) => type === 'desktop')}));diff --git a/server/routes/capabilities.js b/server/routes/capabilities.jsindex b34472d2d8..6f7ac3fac2 100644--- a/server/routes/capabilities.js+++ b/server/routes/capabilities.js@@ -19,7 +19,7 @@ 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 * as apps from '../services/apps.js';+import { getAppStatusSummary } from '../services/appProcessStatus.js';const router = Router();@@ -94,7 +94,7 @@ router.get('/', asyncHandler(async (req, res) => {getVoiceConfig().catch(() => ({})),getGenomeSummary().catch(() => ({ uploaded: false })),resolveTelegram().catch(() => ({})),- apps.getAppStatusSummary().catch(() => ({ total: 0 })),+ getAppStatusSummary().catch(() => ({ total: 0 })),getNetworkExposureSetupStatus().catch(() => ({})),getSettings(),]);diff --git a/server/routes/capabilities.test.js b/server/routes/capabilities.test.jsindex b68e90225e..4fbde8f74c 100644--- a/server/routes/capabilities.test.js+++ b/server/routes/capabilities.test.js@@ -62,7 +62,7 @@ vi.mock('../services/telegram.js', () => ({vi.mock('../services/telegramBridge.js', () => ({getStatus: vi.fn(() => ({ connected: false, hasBotToken: false, hasChatId: false })),}));-vi.mock('../services/apps.js', () => ({+vi.mock('../services/appProcessStatus.js', () => ({getAppStatusSummary: vi.fn(async () => ({ total: 2, online: 2, stopped: 0, notStarted: 0, unmanaged: 0 })),}));diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 6d55016aea..6318cdf34b 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -15,7 +15,7 @@ import { resolveManagedAppIssueTarget } from '../services/managedAppRepositoriesimport { workTrackerLabel } from '../lib/workTracker.js';import { runningAgentsByTaskId, settleTaskSourceSpawnWindow } from '../lib/cosSpawnWindow.js';import { getSlashdoWorkflow, slashdoWorkflowAppliesTo, SLASHDO_COMMAND_NAMES } from '../lib/slashdoCatalog.js';-import { NON_PM2_TYPES } from '../services/streamingDetect.js';+import { NON_PM2_TYPES } from '../services/appProcessTypes.js';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { recordUserAction } from '../services/userActions.js';import { fileInvestigationTask } from '../services/investigationTaskProducer.js';diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.jsindex 54b184ef93..3045915326 100644--- a/server/routes/cosTaskRoutes.test.js+++ b/server/routes/cosTaskRoutes.test.js@@ -64,7 +64,7 @@ vi.mock('../services/cosTaskGenerator.js', () => ({buildJiraTicketTask: vi.fn(),}));vi.mock('../services/apps.js', () => ({ getAppById: vi.fn(), getAppWorkTracker: vi.fn(), PORTOS_APP_ID: 'portos-default' }));-vi.mock('../services/streamingDetect.js', () => ({ NON_PM2_TYPES: new Set() }));+vi.mock('../services/appProcessTypes.js', () => ({ NON_PM2_TYPES: new Set() }));vi.mock('../services/instances.js', () => ({ getAssignableInstances: vi.fn() }));vi.mock('../services/managedAppRepositories.js', () => ({ resolveManagedAppIssueTarget: vi.fn() }));vi.mock('../services/goalFidelityCalibration.js', () => ({ reportGoalFidelityFalsePositive: vi.fn() }));diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex 1d6e0da8f3..a367acc2e8 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -46,8 +46,7 @@ vi.mock('../services/auth.js', () => ({// exercise the desktop exemption set it, everything else leaves it empty.const mock = vi.hoisted(() => ({ desktopProcessNames: new Set() }));-vi.mock('../services/apps.js', () => ({- getAllApps: vi.fn().mockResolvedValue([]),+vi.mock('../services/appProcessStatus.js', () => ({getAppStatusSummary: vi.fn().mockResolvedValue({total: 0,online: 0,@@ -55,7 +54,6 @@ vi.mock('../services/apps.js', () => ({notStarted: 0,unmanaged: 0}),- // Mirrors the real helper: stamps expectedExit from the desktop-owned names.annotateExpectedExit: vi.fn(async (processes) =>processes.map(p => ({ ...p, expectedExit: mock.desktopProcessNames.has(p?.name) })))diff --git a/server/routes/logs.js b/server/routes/logs.jsindex 7f766017b8..1b3f471368 100644--- a/server/routes/logs.js+++ b/server/routes/logs.js@@ -1,5 +1,6 @@import { Router } from 'express';-import * as appsService from '../services/apps.js';+import { getAppById } from '../services/apps.js';+import { resolvePm2HomeForProcess } from '../services/appProcessStatus.js';import * as pm2Service from '../services/pm2.js';import { spawnPm2 } from '../services/pm2.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -42,7 +43,7 @@ router.get('/:processName', asyncHandler(async (req, res) => {throw new ServerError('Invalid process name', { status: 400, code: 'INVALID_PROCESS_NAME' });}- const pm2Home = await appsService.resolvePm2HomeForProcess(safeProcessName);+ const pm2Home = await resolvePm2HomeForProcess(safeProcessName);if (!follow) {// Static log fetch@@ -102,7 +103,7 @@ router.get('/:processName', asyncHandler(async (req, res) => {// GET /api/logs/app/:appId - Get logs for all processes of an approuter.get('/app/:appId', asyncHandler(async (req, res) => {- const app = await appsService.getAppById(req.params.appId);+ const app = await getAppById(req.params.appId);if (!app) {throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/routes/logs.test.js b/server/routes/logs.test.jsindex cb6b4e4a84..4b2027be14 100644--- a/server/routes/logs.test.js+++ b/server/routes/logs.test.js@@ -13,6 +13,8 @@ const makeLogProcess = () => {vi.mock('../services/apps.js', () => ({getAppById: vi.fn(),+}));+vi.mock('../services/appProcessStatus.js', () => ({resolvePm2HomeForProcess: vi.fn(),}));@@ -23,6 +25,7 @@ vi.mock('../services/pm2.js', () => ({}));import * as appsService from '../services/apps.js';+import * as appProcessStatus from '../services/appProcessStatus.js';import * as pm2Service from '../services/pm2.js';import logsRoutes from './logs.js';@@ -72,22 +75,22 @@ describe('log routes PM2_HOME resolution', () => {});it('fetches static logs for a process from its resolved custom PM2 home', async () => {- appsService.resolvePm2HomeForProcess.mockResolvedValue('/tmp/example-pm2');+ appProcessStatus.resolvePm2HomeForProcess.mockResolvedValue('/tmp/example-pm2');const response = await request(createApp()).get('/api/logs/example-api?lines=50');expect(response.status).toBe(200);- expect(appsService.resolvePm2HomeForProcess).toHaveBeenCalledWith('example-api');+ expect(appProcessStatus.resolvePm2HomeForProcess).toHaveBeenCalledWith('example-api');expect(pm2Service.getLogs).toHaveBeenCalledWith('example-api', 50, '/tmp/example-pm2');});it('follows a process from its resolved custom PM2 home', async () => {- appsService.resolvePm2HomeForProcess.mockResolvedValue('/tmp/example-pm2');+ appProcessStatus.resolvePm2HomeForProcess.mockResolvedValue('/tmp/example-pm2');const response = await request(createApp()).get('/api/logs/example-api?follow=true');expect(response.status).toBe(200);- expect(appsService.resolvePm2HomeForProcess).toHaveBeenCalledWith('example-api');+ expect(appProcessStatus.resolvePm2HomeForProcess).toHaveBeenCalledWith('example-api');expect(pm2Service.buildEnv).toHaveBeenCalledWith('/tmp/example-pm2');expect(pm2Service.spawnPm2).toHaveBeenCalledWith(['logs', 'example-api', '--raw', '--lines', '100'],@@ -96,7 +99,7 @@ describe('log routes PM2_HOME resolution', () => {});it('follows a process from the default PM2 home when no custom home resolves', async () => {- appsService.resolvePm2HomeForProcess.mockResolvedValue(null);+ appProcessStatus.resolvePm2HomeForProcess.mockResolvedValue(null);const response = await request(createApp()).get('/api/logs/example-api?follow=true&lines=25');diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex fd8c426287..dd37053602 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -2,7 +2,7 @@ import { Router } from 'express';import os from 'os';import { statfs } from 'fs/promises';import { listProcesses } from '../services/pm2.js';-import * as apps from '../services/apps.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';@@ -132,7 +132,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {// Gather data in parallelconst [pm2Processes, appStatusSummary, cosStatus, cosPendingTaskIds, cosAgents, self, dbHealth, version, diskStats, memStats, healthSettings, forgeHealth, mediaCapacity, reviewerConfigHealth] = await Promise.all([listProcesses().catch(() => []),- apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),+ getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),cos.getStatus().catch(() => null),// Queue depth is read here rather than taken off `getStatus()`, which has no// such field — `cosStatus.queueLength` never existed, so the widget's@@ -182,7 +182,7 @@ 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 apps.annotateExpectedExit(pm2Processes);+ const annotated = await annotateExpectedExit(pm2Processes);const supervised = annotated.filter(p => !p.expectedExit);const processStats = {total: pm2Processes.length,diff --git a/server/services/README.md b/server/services/README.mdindex 6cc29cfb81..c69c364bf6 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -16,3 +16,5 @@ image-generation paths below are useful entry points when tracing render jobs.| `sprites/reference.js` | Sprite reference candidate rendering and provenance. || `deckRender.js` | Deck card image render jobs. || `fableLoom/production.js` | FableLoom production render planning and enqueueing. |+| `appProcessTypes.js` | Dependency-free managed-app process-type vocabulary and PM2/desktop predicates. |+| `appProcessStatus.js` | PM2-backed managed-app status projections, expected-exit policy, and custom PM2 home resolution. |diff --git a/server/services/appDeployer.js b/server/services/appDeployer.jsindex b84b1357cb..a3b8a5b60f 100644--- a/server/services/appDeployer.js+++ b/server/services/appDeployer.js@@ -1,7 +1,7 @@import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';import { join } from 'path';-import { NON_PM2_TYPES } from './streamingDetect.js';+import { NON_PM2_TYPES } from './appProcessTypes.js';import { getAppById } from './apps.js';import { resolveBashBinary } from '../lib/bashResolver.js';import { DEPLOY_FLAGS } from '../lib/appDeployFlags.js';diff --git a/server/services/appListEnrichment.js b/server/services/appListEnrichment.jsindex 302261cb55..abc9bf1e32 100644--- a/server/services/appListEnrichment.js+++ b/server/services/appListEnrichment.js@@ -15,7 +15,8 @@* a single shared implementation without importing a service from a route.*/-import { usesPm2, parseEcosystemFromPath } from './streamingDetect.js';+import { usesPm2 } from './appProcessTypes.js';+import { parseEcosystemFromPath } from './streamingDetect.js';import { listProcessesStrict } from './pm2.js';import { hasDeployScript } from './appDeployer.js';import { checkScripts } from './xcodeScripts.js';@@ -72,7 +73,7 @@ export function computeOverallStatus(statusValues, degraded) {* successful read with no processes) — those homes are tracked so their apps* report `unknown` (status unavailable) + `degraded: true` instead of* `not_started` (confidently not running). See `getAppStatuses()` in- * `apps.js` for the same absent-vs-empty distinction.+ * `appProcessStatus.js` for the same absent-vs-empty distinction.** @param {Array<object>} apps - raw app records (e.g. from `getAllApps()`)* @returns {Promise<Array<object>>} PM2-status-enriched app recordsdiff --git a/server/services/appProcessStatus.js b/server/services/appProcessStatus.jsnew file mode 100644index 0000000000..a04ad7252d--- /dev/null+++ b/server/services/appProcessStatus.js@@ -0,0 +1,93 @@+import { getAllApps } from './apps.js';+import { isDesktopType, usesPm2 } from './appProcessTypes.js';+import { listProcessesStrict } from './pm2.js';++export async function getDesktopProcessNames() {+ const apps = await getAllApps();+ const names = new Set();+ for (const app of apps) {+ if (isDesktopType(app.type)) {+ for (const name of app.pm2ProcessNames || []) names.add(name);+ }+ if (app.nativeLaunch?.processName) names.add(app.nativeLaunch.processName);+ }+ return names;+}++export async function resolvePm2HomeForProcess(processName) {+ const apps = await getAllApps();+ const app = apps.find(candidate =>+ candidate.pm2ProcessNames?.includes(processName)+ || candidate.nativeLaunch?.processName === processName+ );+ return app?.pm2Home || null;+}++export async function annotateExpectedExit(processes) {+ const desktopNames = await getDesktopProcessNames().catch(err => {+ console.error(`❌ Could not read the app registry for process supervision: ${err.message}`);+ return new Set();+ });+ return processes.map(p => ({ ...p, expectedExit: desktopNames.has(p?.name) }));+}++export async function getAppStatuses() {+ const apps = await getAllApps({ includeArchived: false });++ const homeGroups = new Map();+ for (const app of apps) {+ if (!usesPm2(app.type)) continue;+ const home = app.pm2Home || null;+ if (!homeGroups.has(home)) homeGroups.set(home, true);+ }++ const procMaps = new Map();+ const failedHomes = new Set();+ for (const home of homeGroups.keys()) {+ const procs = await listProcessesStrict(home);+ 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 => {+ const managed = usesPm2(app.type);+ const base = { id: app.id, name: app.name, type: app.type, repoPath: app.repoPath };+ if (!managed) {+ return { ...base, overallStatus: 'n/a', managed: false };+ }+ const home = app.pm2Home || null;+ if (failedHomes.has(home)) {+ 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) {+ const statuses = names.map(n => procMap.get(n)?.status || 'not_found');+ if (statuses.some(s => s === 'online')) overallStatus = 'online';+ else if (statuses.some(s => s === 'stopped')) overallStatus = 'stopped';+ else overallStatus = 'not_started';+ }+ return { ...base, overallStatus, managed: true };+ });+}++export async function getAppStatusSummary() {+ const statuses = await getAppStatuses();+ const managed = statuses.filter(s => s.managed);+ 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/appProcessStatus.test.js b/server/services/appProcessStatus.test.jsnew file mode 100644index 0000000000..b77d12533f--- /dev/null+++ b/server/services/appProcessStatus.test.js@@ -0,0 +1,201 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ apps: [],+ appsError: null,+ processes: [],+}));++vi.mock('./apps.js', () => ({+ getAllApps: vi.fn(),+}));++vi.mock('./pm2.js', () => ({+ listProcessesStrict: vi.fn(),+}));++import { getAllApps } from './apps.js';+import { listProcessesStrict } from './pm2.js';+import {+ annotateExpectedExit,+ getAppStatuses,+ getAppStatusSummary,+ getDesktopProcessNames,+ resolvePm2HomeForProcess,+} from './appProcessStatus.js';++const setApps = (...apps) => {+ mocks.apps = apps;+ mocks.appsError = null;+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.apps = [];+ mocks.appsError = null;+ mocks.processes = [];+ getAllApps.mockImplementation(async ({ includeArchived = true } = {}) => {+ if (mocks.appsError) throw mocks.appsError;+ return includeArchived ? mocks.apps : mocks.apps.filter(app => !app.archived);+ });+ listProcessesStrict.mockImplementation(async () => mocks.processes);+});++describe('getDesktopProcessNames', () => {+ it('collects desktop process names and native launch targets, including archived apps', async () => {+ setApps(+ { id: 'web', type: 'express', pm2ProcessNames: ['web'] },+ { id: 'game', type: 'desktop', archived: true, pm2ProcessNames: ['game', 'game-alt'] },+ { id: 'mixed', type: 'express', nativeLaunch: { processName: 'mixed-game' } },+ );++ await expect(getDesktopProcessNames()).resolves.toEqual(new Set(['game', 'game-alt', 'mixed-game']));+ });++ it('returns an empty set when no matching app exists', async () => {+ setApps({ id: 'web', type: 'express', pm2ProcessNames: ['web'] });++ await expect(getDesktopProcessNames()).resolves.toEqual(new Set());+ });+});++describe('resolvePm2HomeForProcess', () => {+ it('resolves a custom home for a PM2 process', async () => {+ setApps({ id: 'custom', type: 'express', pm2Home: '/tmp/example-pm2', pm2ProcessNames: ['example-api'] });++ await expect(resolvePm2HomeForProcess('example-api')).resolves.toBe('/tmp/example-pm2');+ });++ it('resolves a custom home for a native launch process', async () => {+ setApps({+ id: 'mixed',+ type: 'express',+ pm2Home: '/tmp/example-pm2',+ nativeLaunch: { processName: 'mixed-game' },+ });++ await expect(resolvePm2HomeForProcess('mixed-game')).resolves.toBe('/tmp/example-pm2');+ });++ it('returns null for an app using the default home or an unknown process', async () => {+ setApps({ id: 'default', type: 'express', pm2ProcessNames: ['example-api'] });++ await expect(resolvePm2HomeForProcess('example-api')).resolves.toBeNull();+ await expect(resolvePm2HomeForProcess('missing')).resolves.toBeNull();+ });+});++describe('annotateExpectedExit', () => {+ it('marks desktop and native processes while preserving their input shape', async () => {+ setApps(+ { id: 'web', type: 'express', pm2ProcessNames: ['web'] },+ { id: 'game', type: 'desktop', pm2ProcessNames: ['game'] },+ );++ await expect(annotateExpectedExit([+ { name: 'web', status: 'errored' },+ { name: 'game', pm2_env: { status: 'errored' } },+ ])).resolves.toEqual([+ { name: 'web', status: 'errored', expectedExit: false },+ { name: 'game', pm2_env: { status: 'errored' }, expectedExit: true },+ ]);+ });++ it('fails open when the registry read fails', async () => {+ mocks.appsError = new Error('registry unreadable');+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(annotateExpectedExit([{ name: 'game', status: 'errored' }])).resolves.toEqual([+ { name: 'game', status: 'errored', expectedExit: false },+ ]);+ errorSpy.mockRestore();+ });+});++describe('getAppStatuses', () => {+ it('reports desktop lifecycle state from PM2 and excludes archived apps', async () => {+ setApps(+ { id: 'web', name: 'Web', type: 'express', repoPath: '/tmp/web', pm2ProcessNames: ['web'] },+ { id: 'game', name: 'Game', type: 'desktop', repoPath: '/tmp/game', pm2ProcessNames: ['game'] },+ { id: 'old', name: 'Old', type: 'express', archived: true, pm2ProcessNames: ['old'] },+ );+ mocks.processes = [+ { name: 'web', status: 'online' },+ { name: 'game', status: 'stopped' },+ ];++ const statuses = await getAppStatuses();++ expect(statuses).toEqual([+ { id: 'web', name: 'Web', type: 'express', repoPath: '/tmp/web', overallStatus: 'online', managed: true },+ { id: 'game', name: 'Game', type: 'desktop', repoPath: '/tmp/game', overallStatus: 'stopped', managed: true },+ ]);+ });++ it('distinguishes a failed PM2 read from a successful empty read', async () => {+ setApps({ id: 'web', name: 'Web', type: 'express', repoPath: '/tmp/web', pm2ProcessNames: ['web'] });++ mocks.processes = null;+ const failed = await getAppStatuses();+ expect(failed[0]).toMatchObject({ overallStatus: 'unknown', managed: true, degraded: true });++ mocks.processes = [];+ const empty = await getAppStatuses();+ expect(empty[0]).toMatchObject({ overallStatus: 'not_started', managed: true });+ expect(empty[0].degraded).toBeUndefined();+ });++ it('reports native projects as unmanaged and queries each PM2 home once', async () => {+ setApps(+ { id: 'a', name: 'A', type: 'express', pm2ProcessNames: ['a'] },+ { id: 'b', name: 'B', type: 'express', pm2Home: '/tmp/example-pm2', pm2ProcessNames: ['b'] },+ { id: 'native', name: 'Native', type: 'ios-native' },+ );+ listProcessesStrict.mockImplementation(async (home) => home === '/tmp/example-pm2'+ ? [{ name: 'b', status: 'online' }]+ : [{ name: 'a', status: 'stopped' }]);++ const statuses = await getAppStatuses();++ expect(listProcessesStrict).toHaveBeenCalledTimes(2);+ expect(statuses.find(status => status.id === 'native')).toMatchObject({ overallStatus: 'n/a', managed: false });+ expect(statuses.find(status => status.id === 'a')).toMatchObject({ overallStatus: 'stopped', managed: true });+ expect(statuses.find(status => status.id === 'b')).toMatchObject({ overallStatus: 'online', managed: true });+ });+});++describe('getAppStatusSummary', () => {+ it('counts managed, unmanaged, and unknown states without collapsing failures to not-started', async () => {+ setApps(+ { id: 'online', type: 'express', pm2ProcessNames: ['online'] },+ { id: 'stopped', type: 'express', pm2ProcessNames: ['stopped'] },+ { id: 'missing', type: 'express', pm2ProcessNames: ['missing'] },+ { id: 'native', type: 'xcode' },+ );+ mocks.processes = [+ { name: 'online', status: 'online' },+ { name: 'stopped', status: 'stopped' },+ ];++ await expect(getAppStatusSummary()).resolves.toEqual({+ total: 3,+ online: 1,+ stopped: 1,+ notStarted: 1,+ unknown: 0,+ degraded: false,+ unmanaged: 1,+ });++ mocks.processes = null;+ await expect(getAppStatusSummary()).resolves.toMatchObject({+ total: 3,+ online: 0,+ stopped: 0,+ notStarted: 0,+ unknown: 3,+ degraded: true,+ unmanaged: 1,+ });+ });+});diff --git a/server/services/appProcessTypes.js b/server/services/appProcessTypes.jsnew file mode 100644index 0000000000..d90a5f54c5--- /dev/null+++ b/server/services/appProcessTypes.js@@ -0,0 +1,4 @@+export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'swift']);+export const usesPm2 = (type) => !NON_PM2_TYPES.has(type);+export const DESKTOP_TYPES = new Set(['desktop']);+export const isDesktopType = (type) => DESKTOP_TYPES.has(type);diff --git a/server/services/apps.js b/server/services/apps.jsindex a143938a24..f128ea5db9 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -7,8 +7,7 @@ import {expandPortosRootInApp,} from '../lib/portosRootPlaceholder.js';import { PORTOS_APP_ID } from '../lib/appIdentity.js';-import { NON_PM2_TYPES, usesPm2, isDesktopType } from './streamingDetect.js';-import { listProcessesStrict } from './pm2.js';+import { NON_PM2_TYPES } from './appProcessTypes.js';import { SELF_IMPROVEMENT_TASK_TYPES } from './taskScheduleRegistry.js';import { sanitizeTaskMetadata } from '../lib/cosValidation.js';import { isPlainObject } from '../lib/objects.js';@@ -96,9 +95,8 @@ async function loadApps() {// STRICT (#4115): this reader WRITES — an empty `data.apps` makes the baseline// branch below rewrite apps.json with a lone PortOS entry, so a swallowed- // EACCES/EIO would delete every registered app. It also feeds displayed counts- // (`getAppStatusSummary`'s total/online/unmanaged), where a fake 0 reads as- // fact. Absent is still a legitimate first-run empty; unreadable is not.+ // EACCES/EIO would delete every registered app. Absent is still a legitimate+ // first-run empty; unreadable is not.const data = await readJSONFile(APPS_FILE, { apps: {} }, { strict: true });// Normalize: ensure data.apps is always an object@@ -214,193 +212,6 @@ export async function getActiveApps() {return getAllApps({ includeArchived: false });}-/**- * PM2 process names whose exit is expected: desktop apps and optional native- * launch targets attached to otherwise web-based apps.- *- * A desktop process is launched with `autorestart: false` because the user- * closing the window is a normal exit — but that alone does NOT stop every- * relaunch path. Anything that reacts to an `errored` PM2 status by restarting- * it (the CoS health monitor) would reopen the game window, and anything that- * alerts on `errored` (proactive alerts) would report a quit as a failure.- * A force-quit or a non-zero exit lands in exactly that state, so those- * supervisors consult this set and skip desktop processes. See issue #2991.- *- * Archived apps are included: their PM2 entries can outlive the archive, and a- * stale entry must not become auto-restartable just because the app was hidden.- *- * @returns {Promise<Set<string>>} Process names to exempt from auto-restart/alerts.- */-export async function getDesktopProcessNames() {- const apps = await getAllApps();- const names = new Set();- for (const app of apps) {- if (isDesktopType(app.type)) {- for (const name of app.pm2ProcessNames || []) names.add(name);- }- if (app.nativeLaunch?.processName) names.add(app.nativeLaunch.processName);- }- return names;-}--/**- * Resolve the custom PM2 home for a registered process name.- *- * Process-name-only log consumers use this as a backward-compatible fallback- * when they do not already have an app id. An app id remains the preferred- * disambiguator because process names may be reused across PM2 homes.- *- * @param {string} processName PM2 process name to look up- * @returns {Promise<string|null>} The owning app's custom PM2_HOME, if any- */-export async function resolvePm2HomeForProcess(processName) {- const apps = await getAllApps();- const app = apps.find(candidate =>- candidate.pm2ProcessNames?.includes(processName)- || candidate.nativeLaunch?.processName === processName- );- return app?.pm2Home || null;-}--/**- * Stamp `expectedExit` onto each PM2 process so supervisors can branch on the- * concept rather than each re-deriving it from a name set.- *- * `expectedExit: true` means "this process stopping is a normal outcome, not a- * failure" — today that covers desktop (GUI) app processes and the optional- * native launch targets attached to web apps. The user closing either window- * ends its process (cleanly as `stopped`, or as `errored` on a force-quit /- * non-zero exit). Consumers that auto-restart or alert on `errored` must skip- * these. Current consumers:- * - services/cosHealthMonitor.js — auto-restarts errored processes- * - services/proactiveAlerts.js — alerts on errored / crash-looping processes- * - routes/systemHealth.js — drives overallHealth + the dashboard/city HUD- * - services/voice/tools/system.js — `pm2_status` reads "issues" back aloud- * A further consumer that reacts to `errored` needs this too; naming the concept- * here is what makes that discoverable (see issue #2991).- *- * What NONE of them exempt is *liveness*. `expectedExit` says a process- * STOPPING is a normal outcome, so only the failure-bearing counts filter on- * it — an `online` count must still include an exempt process, or a *running*- * desktop app lands in `total` and in no status bucket at all.- *- * Fails open: if the registry can't be read, nothing is marked expected, so the- * pre-existing behavior stands rather than silently exempting every process.- * Accepts either shape of process object — raw `pm2 jlist` entries or `mapProcess`- * output — since both carry a top-level `name`.- *- * @param {Array<{name: string}>} processes- * @returns {Promise<Array<object>>} the same processes, each with `expectedExit`.- */-export async function annotateExpectedExit(processes) {- const desktopNames = await getDesktopProcessNames().catch(err => {- console.error(`❌ Could not read the app registry for process supervision: ${err.message}`);- return new Set();- });- return processes.map(p => ({ ...p, expectedExit: desktopNames.has(p?.name) }));-}--/**- * Summarize PM2-managed app status for dashboards.- *- * Only counts apps whose `type` is PM2-runnable (Express services, etc.).- * Native projects (Xcode, iOS, macOS) have no detectable runtime state and- * are reported separately under `unmanaged` so callers can show context- * without inflating the running denominator.- */-/**- * 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` / `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 OpenWorld- * snapshot pipeline (per-building status), so the two never drift.- *- * Absent-vs-empty rule (AGENTS.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'` +- * `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 });-- // Group PM2 apps by pm2Home so each unique home is queried at most once.- const homeGroups = new Map();- for (const app of apps) {- if (!usesPm2(app.type)) continue;- const home = app.pm2Home || null;- if (!homeGroups.has(home)) homeGroups.set(home, true);- }-- const procMaps = new Map();- const failedHomes = new Set();- for (const home of homeGroups.keys()) {- // `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());- } else {- procMaps.set(home, new Map(procs.map(p => [p.name, p])));- }- }-- return apps.map(app => {- const managed = usesPm2(app.type);- // repoPath is carried so callers can map an agent's workspacePath back to its- // app (the OpenWorld snapshot's agent-assignment mapping, mirroring the- // client's agentMap) without a second apps read.- const base = { id: app.id, name: app.name, type: app.type, repoPath: app.repoPath };- if (!managed) {- return { ...base, overallStatus: 'n/a', managed: false };- }- 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) {- const statuses = names.map(n => procMap.get(n)?.status || 'not_found');- if (statuses.some(s => s === 'online')) overallStatus = 'online';- else if (statuses.some(s => s === 'stopped')) overallStatus = 'stopped';- else overallStatus = 'not_started';- }- return { ...base, overallStatus, managed: true };- });-}--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- };-}-/*** Get app by ID (injects id from key)*/diff --git a/server/services/apps.test.js b/server/services/apps.test.jsindex d0c33ca46a..f77a89fa88 100644--- a/server/services/apps.test.js+++ b/server/services/apps.test.js@@ -28,16 +28,9 @@ vi.mock('./taskScheduleRegistry.js', () => ({SELF_IMPROVEMENT_TASK_TYPES: [],}));-vi.mock('./pm2.js', () => ({- // 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 { atomicWrite, readJSONFile } from '../lib/fileUtils.js';-import { listProcessesStrict } from './pm2.js';import { resetExecutionHistory } from './taskSchedule.js';-import { annotateExpectedExit, createApp, deleteApp, getAllApps, getAppStatuses, getAppStatusSummary, getDesktopProcessNames, getReservedPorts, invalidateCache, PORTOS_APP_ID, resolvePm2HomeForProcess, updateApp, updateAppTaskTypeOverride } from './apps.js';+import { createApp, deleteApp, getAllApps, getReservedPorts, invalidateCache, PORTOS_APP_ID, updateApp, updateAppTaskTypeOverride } from './apps.js';describe('pr-watcher cooldown reset', () => {beforeEach(() => {@@ -313,161 +306,6 @@ describe('portless / desktop apps (#2991)', () => {expect(atomicWrite.mock.calls.at(-1)?.[1].apps[created.id].nativeLaunch).toEqual(nativeLaunch);});- it('reports a portless desktop app from supervisor state alone (no HTTP probe)', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },- 'the-game': {- name: 'The Game',- type: 'desktop',- uiPort: null,- pm2ProcessNames: ['the-game'],- },- },- });- // A clean quit exits 0 → PM2 reports the process 'stopped', not 'errored'.- listProcessesStrict.mockResolvedValue([- { name: 'portos-server', status: 'online' },- { name: 'the-game', status: 'stopped' },- ]);-- const statuses = await getAppStatuses();- const game = statuses.find(s => s.name === 'The Game');- expect(game).toBeDefined();- expect(game.managed).toBe(true); // supervised, not 'n/a'- expect(game.overallStatus).toBe('stopped'); // reflects supervisor, never "unreachable"- });-- it('renders a running desktop app as online purely from the supervisor', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },- 'the-game': { name: 'The Game', type: 'desktop', uiPort: null, pm2ProcessNames: ['the-game'] },- },- });- listProcessesStrict.mockResolvedValue([- { name: 'portos-server', status: 'online' },- { name: 'the-game', status: 'online' },- ]);-- const statuses = await getAppStatuses();- const game = statuses.find(s => s.name === 'The Game');- expect(game.overallStatus).toBe('online');- });-- // The set the CoS health monitor and proactive alerts consult so a quit game- // window is never auto-restarted or reported as a failure.- describe('getDesktopProcessNames', () => {- it('collects every PM2 name owned by a desktop app', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },- 'the-game': { name: 'The Game', type: 'desktop', pm2ProcessNames: ['the-game', 'the-game-alt'] },- },- });-- const names = await getDesktopProcessNames();-- expect(names).toEqual(new Set(['the-game', 'the-game-alt']));- // Web processes stay auto-restartable.- expect(names.has('portos-server')).toBe(false);- });-- it('also exempts a native target attached to a web app', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },- mixed: {- name: 'Mixed App',- type: 'express',- pm2ProcessNames: ['mixed-web'],- nativeLaunch: { label: 'Godot', command: './scripts/game run', processName: 'mixed-game' }- },- },- });-- expect(await getDesktopProcessNames()).toEqual(new Set(['mixed-game']));- });-- it('is empty when no desktop app or native target is registered', async () => {- readJSONFile.mockResolvedValue({- apps: { [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] } },- });-- expect(await getDesktopProcessNames()).toEqual(new Set());- });-- it('tolerates a desktop app with no process names', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express' },- 'the-game': { name: 'The Game', type: 'desktop' },- },- });-- expect(await getDesktopProcessNames()).toEqual(new Set());- });-- it('annotates processes with expectedExit so supervisors branch on the concept', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },- 'the-game': { name: 'The Game', type: 'desktop', pm2ProcessNames: ['the-game'] },- },- });-- const annotated = await annotateExpectedExit([- { name: 'the-game', status: 'errored' },- { name: 'portos-server', status: 'errored' },- ]);-- expect(annotated).toEqual([- { name: 'the-game', status: 'errored', expectedExit: true },- { name: 'portos-server', status: 'errored', expectedExit: false },- ]);- });-- it('annotates raw pm2 jlist entries too (both shapes carry a top-level name)', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express' },- 'the-game': { name: 'The Game', type: 'desktop', pm2ProcessNames: ['the-game'] },- },- });-- const annotated = await annotateExpectedExit([- { name: 'the-game', pm2_env: { status: 'errored' } },- ]);-- expect(annotated[0].expectedExit).toBe(true);- expect(annotated[0].pm2_env).toEqual({ status: 'errored' });- });-- it('fails open — a registry read error exempts nothing', async () => {- readJSONFile.mockRejectedValue(new Error('registry unreadable'));- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});-- const annotated = await annotateExpectedExit([{ name: 'the-game', status: 'errored' }]);-- // Nothing marked expected → the pre-existing auto-restart/alert behavior- // stands rather than silently exempting every process.- expect(annotated[0].expectedExit).toBe(false);- errorSpy.mockRestore();- });-- it('still exempts an archived desktop app whose PM2 entry outlived the archive', async () => {- // Archiving hides the app from the UI but does not delete its PM2 process;- // a leftover entry must not become auto-restartable as a side effect.- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express' },- 'the-game': { name: 'The Game', type: 'desktop', archived: true, pm2ProcessNames: ['the-game'] },- },- });-- expect(await getDesktopProcessNames()).toEqual(new Set(['the-game']));- });- });});describe('managed app feature overrides', () => {@@ -498,50 +336,6 @@ describe('managed app feature overrides', () => {});});-describe('resolvePm2HomeForProcess', () => {- beforeEach(() => {- invalidateCache();- vi.clearAllMocks();- });-- it('returns the owning app custom home for a registered process', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },- 'custom-home': { name: 'Example App', pm2Home: '/tmp/example-pm2', pm2ProcessNames: ['example-api'] },- },- });-- await expect(resolvePm2HomeForProcess('example-api')).resolves.toBe('/tmp/example-pm2');- });-- it('resolves the custom home for an app native launch process', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express' },- mixed: {- name: 'Mixed App',- pm2Home: '/tmp/example-pm2',- nativeLaunch: { label: 'Godot', command: './scripts/game run', processName: 'mixed-game' }- },- },- });-- await expect(resolvePm2HomeForProcess('mixed-game')).resolves.toBe('/tmp/example-pm2');- });-- it('returns null when the matching app uses the default PM2 home', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },- 'default-home': { name: 'Example App', pm2ProcessNames: ['example-api'] },- },- });-- await expect(resolvePm2HomeForProcess('example-api')).resolves.toBeNull();- });-});-describe('deleteApp', () => {beforeEach(() => {invalidateCache();@@ -570,219 +364,6 @@ describe('deleteApp', () => {});});-describe('getAppStatusSummary', () => {- beforeEach(() => {- invalidateCache();- vi.clearAllMocks();- });-- it('counts only PM2-managed apps in total and tracks native projects separately', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: {- name: 'PortOS',- type: 'express',- pm2ProcessNames: ['portos-server']- },- 'svc-a': {- name: 'svc-a',- type: 'express',- pm2ProcessNames: ['svc-a']- },- 'svc-b': {- name: 'svc-b',- type: 'express',- pm2ProcessNames: ['svc-b']- },- 'ios-app': {- name: 'iOS App',- type: 'ios-native'- },- 'xcode-app': {- name: 'Xcode App',- type: 'xcode'- }- }- });- listProcessesStrict.mockResolvedValue([- { name: 'portos-server', status: 'online' },- { name: 'svc-a', status: 'stopped' }- // svc-b is missing → not_found → notStarted- ]);-- const summary = await getAppStatusSummary();- expect(summary).toEqual({- total: 3,- online: 1,- stopped: 1,- notStarted: 1,- unknown: 0,- degraded: false,- unmanaged: 2- });- });-- it('returns zero counts when no apps are registered (native or otherwise)', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: {- name: 'PortOS',- type: 'express',- pm2ProcessNames: ['portos-server']- }- }- });- listProcessesStrict.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);-- const summary = await getAppStatusSummary();- expect(summary).toEqual({- total: 1,- online: 1,- stopped: 0,- notStarted: 0,- unknown: 0,- degraded: false,- unmanaged: 0- });- });-- it('queries each unique pm2Home only once', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: {- name: 'PortOS',- type: 'express',- pm2ProcessNames: ['portos-server']- },- 'shared-home-a': {- name: 'a',- type: 'express',- pm2ProcessNames: ['a']- },- 'shared-home-b': {- name: 'b',- type: 'express',- pm2ProcessNames: ['b']- },- 'custom-home': {- name: 'c',- type: 'express',- pm2Home: '/tmp/other-pm2',- pm2ProcessNames: ['c']- }- }- });- listProcessesStrict.mockImplementation(async (home) => {- if (home === '/tmp/other-pm2') return [{ name: 'c', status: 'online' }];- return [- { name: 'portos-server', status: 'online' },- { name: 'a', status: 'online' },- { name: 'b', status: 'stopped' }- ];- });-- const summary = await getAppStatusSummary();- expect(listProcessesStrict).toHaveBeenCalledTimes(2);- expect(summary).toMatchObject({ total: 4, online: 3, stopped: 1, notStarted: 0, unmanaged: 0 });- });-- it('skips archived apps', async () => {- readJSONFile.mockResolvedValue({- apps: {- [PORTOS_APP_ID]: {- name: 'PortOS',- type: 'express',- pm2ProcessNames: ['portos-server']- },- 'old-app': {- name: 'old',- type: 'express',- pm2ProcessNames: ['old'],- archived: true- }- }- });- listProcessesStrict.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);-- 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'] }- }- });- // Strict read returns null on a transient PM2 failure (NOT an empty list).- listProcessesStrict.mockResolvedValue(null);-- 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'] }- }- });- listProcessesStrict.mockImplementation(async (home) => {- if (home === '/tmp/other-pm2') return null; // this home's read failed- 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'] }- }- });- listProcessesStrict.mockResolvedValue(null);-- 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.- listProcessesStrict.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();- });-});-describe('__PORTOS_ROOT__ placeholder expansion on load', () => {beforeEach(() => {invalidateCache();diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.jsindex ccbd9681f6..e8d7572961 100644--- a/server/services/cosHealthMonitor.js+++ b/server/services/cosHealthMonitor.js@@ -10,7 +10,7 @@ import { execPm2, listProcessesStrict } from './pm2.js';import { getMemoryStats } from '../lib/memoryStats.js';import { loadState, saveState, withStateLock, isDaemonRunning } from './cosState.js';import { cosEvents, emitLog } from './cosEvents.js';-import { annotateExpectedExit } from './apps.js';+import { annotateExpectedExit } from './appProcessStatus.js';/*** Run a daemon health check: inspect PM2 processes and memory, auto-restartdiff --git a/server/services/cosHealthMonitor.test.js b/server/services/cosHealthMonitor.test.jsindex f0c321ae6d..6c1057b234 100644--- a/server/services/cosHealthMonitor.test.js+++ b/server/services/cosHealthMonitor.test.js@@ -17,7 +17,7 @@ const mock = vi.hoisted(() => ({// Mocked so the health check never reads the real apps registry off disk.// Mirrors the real annotateExpectedExit, including its fail-open behavior: a// registry read failure marks nothing expected, so nothing is exempted.-vi.mock('./apps.js', () => ({+vi.mock('./appProcessStatus.js', () => ({annotateExpectedExit: vi.fn(async (processes) => {const names = mock.desktopLookupError ? new Set() : mock.desktopProcessNames;return processes.map(p => ({ ...p, expectedExit: names.has(p?.name) }));diff --git a/server/services/eidoverseWorld.runtime.test.js b/server/services/eidoverseWorld.runtime.test.jsindex 4e1567a2a9..4fd267a636 100644--- a/server/services/eidoverseWorld.runtime.test.js+++ b/server/services/eidoverseWorld.runtime.test.js@@ -65,6 +65,8 @@ vi.mock('./instanceIdentity.js', () => ({vi.mock('./apps.js', () => ({getAllApps: vi.fn(async () => []),+}));+vi.mock('./appProcessStatus.js', () => ({getAppStatuses: vi.fn(async () => {mocks.appStatusReads += 1;return mocks.appStatuses;diff --git a/server/services/eidoverseWorldSources.js b/server/services/eidoverseWorldSources.jsindex dd7a516129..7c5e3d646a 100644--- a/server/services/eidoverseWorldSources.js+++ b/server/services/eidoverseWorldSources.js@@ -8,7 +8,8 @@import { statfs } from 'node:fs/promises';import { parseFilesystemStats } from '../lib/fileCore.js';-import { getAllApps, getAppStatuses } from './apps.js';+import { getAllApps } from './apps.js';+import { getAppStatuses } from './appProcessStatus.js';import { getStatus as getCosStatus, getAgents, getCosTasks, getTodayActivity } from './cos.js';import { getPendingCounts } from './review.js';import { getPeers } from './instances.js';diff --git a/server/services/eidoverseWorldSources.test.js b/server/services/eidoverseWorldSources.test.jsindex 97c50602d7..2c57479488 100644--- a/server/services/eidoverseWorldSources.test.js+++ b/server/services/eidoverseWorldSources.test.js@@ -10,9 +10,11 @@ vi.mock('node:fs/promises', () => ({})),}));vi.mock('./apps.js', () => ({- getAppStatuses: vi.fn(async () => sources.apps),getAllApps: vi.fn(async () => sources.appConfig),}));+vi.mock('./appProcessStatus.js', () => ({+ getAppStatuses: vi.fn(async () => sources.apps),+}));vi.mock('./cos.js', () => ({getAgents: vi.fn(async () => sources.agents),getCosTasks: vi.fn(async () => sources.taskState),diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex e813380826..c8a231f9db 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -9,7 +9,8 @@ import { extractJson } from '../lib/jsonExtract.js';import { runPromptThroughProvider } from './promptRunner.js';import { getReservedPorts, getAllApps } from './apps.js';import { PORTOS_APP_ID } from '../lib/appIdentity.js';-import { usesPm2, isStandardizable } from './streamingDetect.js';+import { usesPm2 } from './appProcessTypes.js';+import { isStandardizable } from './streamingDetect.js';import { getListeningPorts } from '../lib/platform.js';const execAsync = promisify(exec);diff --git a/server/services/proactiveAlertSources.js b/server/services/proactiveAlertSources.jsindex ca400eef6b..f6e6e5faf2 100644--- a/server/services/proactiveAlertSources.js+++ b/server/services/proactiveAlertSources.js@@ -11,7 +11,7 @@ import { getHealthAlertResolutions, healthAlertEvidence, recordHealthAlertResoluimport { getGoals } from './identity.js';import { getPerformanceSummary } from './taskLearning.js';import { listProcesses } from './pm2.js';-import { annotateExpectedExit } from './apps.js';+import { annotateExpectedExit } from './appProcessStatus.js';import { getCareSummary } from './tribe.js';import { findUnansweredTribeThreads } from './tribeOutreach.js';diff --git a/server/services/proactiveAlerts.test.js b/server/services/proactiveAlerts.test.jsindex 91f46a5803..3903bbf3d3 100644--- a/server/services/proactiveAlerts.test.js+++ b/server/services/proactiveAlerts.test.js@@ -21,7 +21,7 @@ vi.mock('./taskLearning.js', () => ({vi.mock('./pm2.js', () => ({ listProcesses: vi.fn(async () => mock.processes) }));// Mirrors the real annotateExpectedExit, including its fail-open behavior: a// registry read failure marks nothing expected, so nothing is exempted.-vi.mock('./apps.js', () => ({+vi.mock('./appProcessStatus.js', () => ({annotateExpectedExit: vi.fn(async (processes) => {const names = mock.desktopLookupError ? new Set() : mock.desktopProcessNames;return processes.map(p => ({ ...p, expectedExit: names.has(p?.name) }));diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 480bf96cdb..ae1ad2550b 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -19,7 +19,8 @@ vi.mock('./pm2.js', () => ({}));vi.mock('./streamingDetect.js', () => ({ streamDetection: vi.fn() }));vi.mock('./cosEvents.js', () => ({ cosEvents: { on: vi.fn((...args) => queueListeners.cos.push(args)) }, emitLog: vi.fn() }));-vi.mock('./apps.js', () => ({ appsEvents: { on: vi.fn() }, getAppById: vi.fn(), notifyAppsChanged: vi.fn(), resolvePm2HomeForProcess: vi.fn(), updateApp: vi.fn() }));+vi.mock('./apps.js', () => ({ appsEvents: { on: vi.fn() }, getAppById: vi.fn(), notifyAppsChanged: vi.fn(), updateApp: vi.fn() }));+vi.mock('./appProcessStatus.js', () => ({ resolvePm2HomeForProcess: vi.fn() }));// logAction appends to the real history file — mock it or this suite writes to data/.vi.mock('./history.js', () => ({ logAction: vi.fn(async () => {}) }));vi.mock('../lib/errorHandler.js', () => ({ errorEvents: { on: vi.fn() } }));@@ -86,7 +87,8 @@ vi.mock('../sockets/voice.js', () => ({ registerVoiceHandlers: vi.fn() }));import { initSocket } from './socket.js';import { spawnPm2 } from './pm2.js';-import { getAppById, notifyAppsChanged, resolvePm2HomeForProcess } from './apps.js';+import { getAppById, notifyAppsChanged } from './apps.js';+import { resolvePm2HomeForProcess } from './appProcessStatus.js';import { logAction } from './history.js';import { cosEvents } from './cosEvents.js';import { beeperSocketEvents } from './beeperSocketEvents.js';diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.jsindex a5134ad428..14cd932bc7 100644--- a/server/services/streamingDetect.js+++ b/server/services/streamingDetect.js@@ -5,9 +5,8 @@ import { homedir } from 'os';import { listProcessesStrict } from './pm2.js';import { safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';import { detectAppIcon } from './appIconDetect.js';--/** App types that do not use PM2 for process management */-export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'swift']);+import { NON_PM2_TYPES, usesPm2, DESKTOP_TYPES, isDesktopType } from './appProcessTypes.js';+export { NON_PM2_TYPES, usesPm2, DESKTOP_TYPES, isDesktopType };/*** Language markers, checked FIRST: a repo's LANGUAGE beats its packaging, so a@@ -91,19 +90,6 @@ export const NON_STANDARDIZABLE_TYPES = new Set([...NON_PM2_TYPES, ...NON_NODE_T/** Whether the PM2 standardizer (which writes a NODE ecosystem config) applies. */export const isStandardizable = (type) => !NON_STANDARDIZABLE_TYPES.has(type);-/**- * App types that run a GUI/desktop process with no HTTP port (e.g. a Godot- * game binary). These are still supervised through PM2, but launched from the- * app's own `startCommands` — never an ecosystem web-server config — and with- * autorestart OFF: the user closing the window is a NORMAL exit (code 0), not a- * crash to relaunch. Port-dependent surfaces (Open UI, HTTP probes) branch on- * "has a port" rather than assuming one.- */-export const DESKTOP_TYPES = new Set(['desktop']);--/** Check if an app type is a portless GUI/desktop process. */-export const isDesktopType = (type) => DESKTOP_TYPES.has(type);-/*** Detect an optional native Godot launch target alongside the repo's normal* web-process configuration.@@ -147,9 +133,6 @@ export function detectGodotNativeLaunch(dirPath) {*/const ECOSYSTEM_CONFIG_FILENAMES = ['ecosystem.config.js', 'ecosystem.config.cjs'];-/** Check if an app type uses PM2 for process management */-export const usesPm2 = (type) => !NON_PM2_TYPES.has(type);-/*** Count the run of consecutive backslashes immediately before `idx`.* An odd count means the character at `idx` is escaped; even (including 0)diff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.jsindex 12ed5bf0c8..d38f41b858 100644--- a/server/services/streamingDetect.test.js+++ b/server/services/streamingDetect.test.js@@ -2,7 +2,8 @@ import { describe, it, expect, afterEach, vi } from 'vitest';import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { detectGodotNativeLaunch, parseEcosystemConfig, resolveViteConfigPortForProcess, rewriteEcosystemPorts, rewriteEcosystemPortsByProcess, writeEcosystemPorts, writeEcosystemPortsByProcess, writeEcosystemPortEdits, streamDetection, classifyNonNodeType, isStandardizable, usesPm2, DESKTOP_TYPES, NON_PM2_TYPES, NON_NODE_TYPES, NON_STANDARDIZABLE_TYPES } from './streamingDetect.js';+import { detectGodotNativeLaunch, parseEcosystemConfig, resolveViteConfigPortForProcess, rewriteEcosystemPorts, rewriteEcosystemPortsByProcess, writeEcosystemPorts, writeEcosystemPortsByProcess, writeEcosystemPortEdits, streamDetection, classifyNonNodeType, isStandardizable, NON_NODE_TYPES, NON_STANDARDIZABLE_TYPES } from './streamingDetect.js';+import { usesPm2, DESKTOP_TYPES, NON_PM2_TYPES, isDesktopType } from './appProcessTypes.js';// streamDetection shells out to PM2 and scans for an app icon; neither is under// test here and both are slow/environment-dependent.@@ -1022,6 +1023,15 @@ describe('resolveViteConfigPortForProcess', () => {// client-side version of this test therefore passes on a dev machine and fails// in CI. Keep the import one-way.describe('client mirror of the app-type sets', () => {+ it('keeps compatibility exports backed by the process-type leaf', async () => {+ const legacy = await import('./streamingDetect.js');+ const leaf = await import('./appProcessTypes.js');+ expect(legacy.NON_PM2_TYPES).toBe(leaf.NON_PM2_TYPES);+ expect(legacy.usesPm2).toBe(leaf.usesPm2);+ expect(legacy.DESKTOP_TYPES).toBe(leaf.DESKTOP_TYPES);+ expect(legacy.isDesktopType).toBe(leaf.isDesktopType);+ });+it('matches DESKTOP_TYPES', async () => {const client = await import('../../client/src/components/apps/constants.js');expect([...client.DESKTOP_TYPES].sort()).toEqual([...DESKTOP_TYPES].sort());diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex bd5a241f5a..6c683da09b 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -177,6 +177,8 @@ const activeAppsRef = { value: [const desktopNamesRef = { value: new Set() };vi.mock('../apps.js', () => ({getActiveApps: vi.fn(async () => activeAppsRef.value),+}));+vi.mock('../appProcessStatus.js', () => ({annotateExpectedExit: vi.fn(async (procs) =>procs.map(p => ({ ...p, expectedExit: desktopNamesRef.value.has(p?.name) }))),diff --git a/server/services/voice/tools/system.js b/server/services/voice/tools/system.jsindex 0cf2794983..c8aec18567 100644--- a/server/services/voice/tools/system.js+++ b/server/services/voice/tools/system.js@@ -3,7 +3,7 @@// the "ops / things running" mental model but gate on separate regexes.import { listProcesses, restartApp } from '../../pm2.js';-import { annotateExpectedExit } from '../../apps.js';+import { annotateExpectedExit } from '../../appProcessStatus.js';import { getItems, getFeeds, markItemRead, markAllRead } from '../../feeds.js';import { clampLimit } from './shared.js';diff --git a/server/sockets/logs.js b/server/sockets/logs.jsindex e4051f821a..4a3305117f 100644--- a/server/sockets/logs.js+++ b/server/sockets/logs.js@@ -1,5 +1,6 @@import { buildEnv, spawnPm2 } from '../services/pm2.js';-import { getAppById, resolvePm2HomeForProcess } from '../services/apps.js';+import { getAppById } from '../services/apps.js';+import { resolvePm2HomeForProcess } from '../services/appProcessStatus.js';import {logsSubscribeSchema,logsUnsubscribeSchema,diff --git a/server/sockets/logs.test.js b/server/sockets/logs.test.jsindex 967bac1414..00cc015d0e 100644--- a/server/sockets/logs.test.js+++ b/server/sockets/logs.test.js@@ -14,6 +14,8 @@ vi.mock('../services/pm2.js', () => ({}));vi.mock('../services/apps.js', () => ({getAppById: vi.fn(async () => null),+}));+vi.mock('../services/appProcessStatus.js', () => ({resolvePm2HomeForProcess: vi.fn(async () => null),}));