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(simplify): exempt the third errored-process consumer and batch log lines
[._.]/ Adam Eivy425ea27f4bea
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6bc56b1e2e..badc29bdc9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -32,7 +32,7 @@## Managed apps-- **[issue-2991] Starting a desktop app now shows what it's doing, and quitting it stays quit** — pressing **Start** on a managed desktop app (a game binary) opens a live panel showing the build output as it compiles and imports assets, so a launch that takes a minute before a window appears no longer looks like nothing happened. The panel switches from "Launching" to "Running" once the app is up, and you can dismiss it any time without stopping the app. Closing or force-quitting the app's window is now treated as the normal end of a session everywhere: PortOS will no longer silently relaunch the window you just closed, and quitting no longer shows up as an errored process or raises a failure alert. Apps that run in their own PM2 instance now stream their logs correctly instead of showing an empty panel.+- **[issue-2991] Starting a desktop app now shows what it's doing, and quitting it stays quit** — pressing **Start** on a managed desktop app (a game binary) opens a live panel showing the build output as it compiles and imports assets, so a launch that takes a minute before a window appears no longer looks like nothing happened. The panel switches from "Launching" to "Running" once the app is up, and you can dismiss it any time without stopping the app. Closing or force-quitting the app's window is now treated as the normal end of a session everywhere: PortOS will no longer silently relaunch the window you just closed, and quitting no longer shows up as an errored process, flips your dashboard or CyberCity health to critical, or raises a failure alert. Apps that run in their own PM2 instance now stream their logs correctly instead of showing an empty panel.## Music studiodiff --git a/client/src/components/apps/DesktopLaunchProgress.jsx b/client/src/components/apps/DesktopLaunchProgress.jsxindex 3e2818b80c..97feddad3b 100644--- a/client/src/components/apps/DesktopLaunchProgress.jsx+++ b/client/src/components/apps/DesktopLaunchProgress.jsx@@ -1,6 +1,7 @@import { useEffect, useRef } from 'react';import { X } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';+import ProcessLogLines from '../ui/ProcessLogLines';import { useProcessLogs } from '../../hooks/useProcessLogs';/**@@ -59,20 +60,7 @@ export default function DesktopLaunchProgress({ appId, processName, online, onDiref={scrollRef}className="m-4 mt-2 p-3 bg-port-bg border border-port-border rounded-lg font-mono text-xs h-48 overflow-y-auto">- {logs.length === 0 ? (- <span className="text-gray-500">- {subscribed ? 'Waiting for output…' : 'Connecting to log stream…'}- </span>- ) : (- logs.map((entry, i) => (- <div- key={`${entry.timestamp}-${i}`}- className={`whitespace-pre-wrap break-all ${entry.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}- >- {entry.line}- </div>- ))- )}+ <ProcessLogLines logs={logs} subscribed={subscribed} /></div></div>);diff --git a/client/src/components/apps/DesktopLaunchProgress.test.jsx b/client/src/components/apps/DesktopLaunchProgress.test.jsxindex 54940c76ca..9eb0e260fa 100644--- a/client/src/components/apps/DesktopLaunchProgress.test.jsx+++ b/client/src/components/apps/DesktopLaunchProgress.test.jsx@@ -14,7 +14,12 @@ vi.mock('../../services/socket', () => ({import DesktopLaunchProgress from './DesktopLaunchProgress';import { DESKTOP_TYPES, isDesktopType } from './constants';-const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });+// Lines are batched on a 250ms debounce in useProcessLogs — advance past it so+// the rendered output reflects the frame.+const fire = (event, payload) => {+ act(() => { handlers.get(event)?.(payload); });+ act(() => { vi.advanceTimersByTime(250); });+};const renderPanel = (props = {}) => render(<DesktopLaunchProgress@@ -27,8 +32,8 @@ const renderPanel = (props = {}) => render();describe('DesktopLaunchProgress', () => {- beforeEach(() => { handlers.clear(); emitted.length = 0; });- afterEach(cleanup);+ beforeEach(() => { handlers.clear(); emitted.length = 0; vi.useFakeTimers(); });+ afterEach(() => { cleanup(); vi.useRealTimers(); });it('subscribes to the process log scoped to the app (custom PM2_HOME)', () => {renderPanel();@@ -78,11 +83,6 @@ describe('DesktopLaunchProgress', () => {expect(emitted.map(([e]) => e)).not.toContain('logs:kill');});- it('unsubscribes when the panel unmounts', () => {- const { unmount } = renderPanel();- unmount();- expect(emitted).toContainEqual(['logs:unsubscribe', { processName: 'game' }]);- });});describe('desktop type mirror', () => {diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.jsindex bbe595bf08..2ad74d8b90 100644--- a/client/src/components/apps/constants.js+++ b/client/src/components/apps/constants.js@@ -1,9 +1,11 @@export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'swift']);// Mirrors DESKTOP_TYPES in server/services/streamingDetect.js — app types that run-// a GUI/desktop process with no HTTP port (a game binary). Kept in sync by hand;-// the server stays the source of truth for what the type MEANS (autorestart off,-// command-launched), this mirror only drives client-side presentation.+// 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+// auto-restart supervision). The client only needs it to decide whether Start+// should open the build-output panel.export const DESKTOP_TYPES = new Set(['desktop']);/** Whether an app type is a portless GUI/desktop process. */diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsxindex 5352aeb640..144e2ff21a 100644--- a/client/src/components/apps/tabs/ProcessesTab.jsx+++ b/client/src/components/apps/tabs/ProcessesTab.jsx@@ -4,6 +4,7 @@ import * as api from '../../../services/api';import { executeCommand } from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';import { FormField } from '../../ui/FormField';+import ProcessLogLines from '../../ui/ProcessLogLines';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';import { useProcessLogs } from '../../../hooks/useProcessLogs';import { formatBytes, formatDurationMs } from '../../../utils/formatters';@@ -175,10 +176,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {<FormField className="flex items-center gap-2" label="Tail lines:" labelClassName="text-xs text-gray-500"><selectvalue={tailLines}- onChange={(e) => {- setTailLines(Number(e.target.value));- clearLogs();- }}+ onChange={(e) => setTailLines(Number(e.target.value))}className="px-2 py-1 text-xs bg-port-card border border-port-border rounded text-white"><option value={100}>100</option>@@ -190,7 +188,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {</FormField><span className="text-xs text-gray-600">{logs.length} lines</span><button- onClick={() => clearLogs()}+ onClick={clearLogs}className="text-xs text-gray-500 hover:text-white">Clear@@ -209,23 +207,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {ref={logsRef}className="h-[32rem] overflow-auto p-3 font-mono text-xs">- {logs.length === 0 ? (- <div className="text-gray-500">- {subscribed ? 'No logs yet...' : 'Connecting to log stream...'}- </div>- ) : (- logs.map((log, i) => (- <div- key={i}- className={`py-0.5 ${log.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}- >- <span className="text-gray-600 mr-2">- {new Date(log.timestamp).toLocaleTimeString()}- </span>- {log.line}- </div>- ))- )}+ <ProcessLogLines logs={logs} subscribed={subscribed} showTimestamps /></div></div></td>@@ -259,10 +241,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {<FormField className="flex items-center gap-2" label="Tail lines:" labelClassName="text-sm text-gray-500"><selectvalue={tailLines}- onChange={(e) => {- setTailLines(Number(e.target.value));- clearLogs();- }}+ onChange={(e) => setTailLines(Number(e.target.value))}className="px-2 py-1 text-sm bg-port-bg border border-port-border rounded text-white"><option value={100}>100</option>@@ -274,7 +253,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {</FormField><span className="text-sm text-gray-600">{logs.length} lines</span><button- onClick={() => clearLogs()}+ onClick={clearLogs}className="text-sm text-gray-500 hover:text-white">Clear@@ -292,23 +271,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {ref={fullscreenLogsRef}className="flex-1 overflow-auto p-4 font-mono text-sm">- {logs.length === 0 ? (- <div className="text-gray-500">- {subscribed ? 'No logs yet...' : 'Connecting to log stream...'}- </div>- ) : (- logs.map((log, i) => (- <div- key={i}- className={`py-0.5 ${log.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}- >- <span className="text-gray-600 mr-3">- {new Date(log.timestamp).toLocaleTimeString()}- </span>- {log.line}- </div>- ))- )}+ <ProcessLogLines logs={logs} subscribed={subscribed} showTimestamps timestampGap="mr-3" /></div></div>)}diff --git a/client/src/components/ui/ProcessLogLines.jsx b/client/src/components/ui/ProcessLogLines.jsxnew file mode 100644index 0000000000..5ee4176ad3--- /dev/null+++ b/client/src/components/ui/ProcessLogLines.jsx@@ -0,0 +1,38 @@+/**+ * Renders a PM2 process's log lines (the body of a log pane).+ *+ * Shared by every surface that tails a process via `useProcessLogs` — the+ * Processes tab's inline and fullscreen panes, and the desktop launch-progress+ * panel — so the empty-state copy and the stdout/stderr coloring stay identical.+ * The caller owns the scroll container and its ref; this only renders content.+ *+ * @param {object} props+ * @param {Array<{line: string, type: string, timestamp: number}>} props.logs+ * @param {boolean} props.subscribed Whether the stream is connected — distinguishes+ * "not connected yet" from "connected but the process hasn't written anything".+ * @param {boolean} [props.showTimestamps=false] Prefix each line with its local time.+ * @param {string} [props.timestampGap='mr-2'] Spacing after the timestamp.+ */+export default function ProcessLogLines({ logs, subscribed, showTimestamps = false, timestampGap = 'mr-2' }) {+ if (logs.length === 0) {+ return (+ <div className="text-gray-500">+ {subscribed ? 'Waiting for output…' : 'Connecting to log stream…'}+ </div>+ );+ }++ return logs.map((log, i) => (+ <div+ key={`${log.timestamp}-${i}`}+ className={`py-0.5 whitespace-pre-wrap break-all ${log.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}+ >+ {showTimestamps && (+ <span className={`text-gray-600 ${timestampGap}`}>+ {new Date(log.timestamp).toLocaleTimeString()}+ </span>+ )}+ {log.line}+ </div>+ ));+}diff --git a/client/src/hooks/useProcessLogs.js b/client/src/hooks/useProcessLogs.jsindex 23d6ab3bdd..f6080e782c 100644--- a/client/src/hooks/useProcessLogs.js+++ b/client/src/hooks/useProcessLogs.js@@ -1,9 +1,15 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useRef } from 'react';import socket from '../services/socket';// Ring-buffer cap. `pm2 logs` replays the tail on subscribe and then streams// live, so an unbounded array grows without limit on a chatty process.const MAX_LINES = 1000;+// Batch window. The server emits one `logs:line` event PER LINE, and each lands+// in its own socket task that React won't auto-batch — so a compiling desktop+// app (or the 200-500 line tail replay on subscribe) would otherwise be one+// render and two full array allocations per line. Matches the repo's stated+// ~250ms debounce for high-frequency state writes.+const FLUSH_MS = 250;/*** Subscribe to one PM2 process's live log stream over the shared socket.@@ -32,28 +38,34 @@ export function useProcessLogs(processName, options = {}) {const { lines = 500, appId } = options;const [logs, setLogs] = useState([]);const [subscribed, setSubscribed] = useState(false);+ const pendingRef = useRef([]);+ const flushTimerRef = useRef(null);useEffect(() => {- if (!processName) {- setLogs([]);- setSubscribed(false);- return;- }-- // Reset here rather than in the caller's click handler so switching- // processes can't briefly show the previous one's tail under the new name.setLogs([]);setSubscribed(false);+ if (!processName) return;++ const flush = () => {+ flushTimerRef.current = null;+ if (pendingRef.current.length === 0) return;+ const incoming = pendingRef.current;+ pendingRef.current = [];+ setLogs(prev => {+ const combined = [...prev, ...incoming];+ return combined.length > MAX_LINES ? combined.slice(-MAX_LINES) : combined;+ });+ };+ const append = (entry) => {+ pendingRef.current.push(entry);+ if (flushTimerRef.current == null) flushTimerRef.current = setTimeout(flush, FLUSH_MS);+ };socket.emit('logs:subscribe', { processName, lines, ...(appId ? { appId } : {}) });const handleLog = (data) => {if (data.processName !== processName) return;- setLogs(prev => [...prev.slice(-(MAX_LINES - 1)), {- line: data.line,- type: data.type,- timestamp: data.timestamp- }]);+ append({ line: data.line, type: data.type, timestamp: data.timestamp });};const handleSubscribed = (data) => {@@ -62,7 +74,7 @@ export function useProcessLogs(processName, options = {}) {const handleError = (data) => {if (data.processName !== processName) return;- setLogs(prev => [...prev, { line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() }]);+ append({ line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() });};socket.on('logs:line', handleLog);@@ -74,10 +86,21 @@ export function useProcessLogs(processName, options = {}) {socket.off('logs:line', handleLog);socket.off('logs:subscribed', handleSubscribed);socket.off('logs:error', handleError);+ // Drop the pending batch with the subscription: the effect re-run clears+ // `logs` anyway, so flushing here would append the old process's tail to+ // the new one's empty buffer.+ if (flushTimerRef.current != null) clearTimeout(flushTimerRef.current);+ flushTimerRef.current = null;+ pendingRef.current = [];};}, [processName, lines, appId]);- const clear = useCallback(() => setLogs([]), []);+ const clear = useCallback(() => {+ // Also drop anything buffered but not yet flushed, or a pending timer would+ // repopulate the list the user just cleared.+ pendingRef.current = [];+ setLogs([]);+ }, []);return { logs, subscribed, clear };}diff --git a/client/src/hooks/useProcessLogs.test.jsx b/client/src/hooks/useProcessLogs.test.jsxindex 752da10636..d20bb091a8 100644--- a/client/src/hooks/useProcessLogs.test.jsx+++ b/client/src/hooks/useProcessLogs.test.jsx@@ -15,12 +15,23 @@ vi.mock('../services/socket', () => ({import { useProcessLogs } from './useProcessLogs.js';-const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });+// Log lines are buffered and flushed on a 250ms debounce, so every assertion+// about `logs` must advance timers past the flush window first.+const FLUSH_MS = 250;+const flushLines = () => act(() => { vi.advanceTimersByTime(FLUSH_MS); });++/** Fire a socket frame and let the batch flush, so `logs` reflects it. */+const fire = (event, payload) => {+ act(() => { handlers.get(event)?.(payload); });+ flushLines();+};+/** Fire a frame WITHOUT flushing — for asserting the debounce itself. */+const fireRaw = (event, payload) => act(() => { handlers.get(event)?.(payload); });const emitsOf = (event) => emitted.filter(([e]) => e === event).map(([, payload]) => payload);describe('useProcessLogs', () => {- beforeEach(() => { handlers.clear(); emitted.length = 0; });- afterEach(cleanup);+ beforeEach(() => { handlers.clear(); emitted.length = 0; vi.useFakeTimers(); });+ afterEach(() => { cleanup(); vi.useRealTimers(); });it('subscribes to the named process and reports lines', () => {const { result } = renderHook(() => useProcessLogs('game'));@@ -112,6 +123,7 @@ describe('useProcessLogs', () => {handlers.get('logs:line')?.({ processName: 'game', line: `l${i}`, type: 'stdout', timestamp: i });}});+ flushLines();expect(result.current.logs).toHaveLength(1000);// Oldest lines dropped, newest retained.@@ -119,6 +131,54 @@ describe('useProcessLogs', () => {expect(result.current.logs[0].line).toBe('l100');});+ // The server emits one socket event PER LINE, which React does not auto-batch —+ // so a compiling desktop app would otherwise re-render per line.+ it('batches a burst of lines into a single state update', () => {+ let renders = 0;+ const { result } = renderHook(() => { renders++; return useProcessLogs('game'); });+ const rendersAfterMount = renders;++ act(() => {+ for (let i = 0; i < 50; i++) {+ handlers.get('logs:line')?.({ processName: 'game', line: `l${i}`, type: 'stdout', timestamp: i });+ }+ });+ // Nothing applied yet — still inside the debounce window.+ expect(result.current.logs).toEqual([]);+ expect(renders).toBe(rendersAfterMount);++ flushLines();++ expect(result.current.logs).toHaveLength(50);+ // 50 lines cost one render, not 50.+ expect(renders - rendersAfterMount).toBe(1);+ });++ it('drops the pending batch when the process switches mid-window', () => {+ const { result, rerender } = renderHook(({ name }) => useProcessLogs(name), {+ initialProps: { name: 'game' },+ });+ // Buffered but not yet flushed when the switch happens.+ fireRaw('logs:line', { processName: 'game', line: 'old', type: 'stdout', timestamp: 1 });++ rerender({ name: 'server' });+ flushLines();++ // The old process's buffered tail must not land in the new one's buffer.+ expect(result.current.logs).toEqual([]);+ });++ it('clear() also drops lines buffered but not yet flushed', () => {+ const { result } = renderHook(() => useProcessLogs('game'));+ fireRaw('logs:line', { processName: 'game', line: 'a', type: 'stdout', timestamp: 1 });++ act(() => { result.current.clear(); });+ flushLines();++ // A pending timer must not repopulate the list the user just cleared.+ expect(result.current.logs).toEqual([]);+ });+it('tears down its listeners on unmount', () => {const { unmount } = renderHook(() => useProcessLogs('game'));expect(handlers.has('logs:line')).toBe(true);diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex 812dfc7977..6cc6c44741 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi } from 'vitest';+import { describe, it, expect, vi, beforeEach } from 'vitest';import os from 'os';import express from 'express';import { request } from '../lib/testHelper.js';@@ -23,6 +23,10 @@ vi.mock('../services/auth.js', () => ({isAuthEnabled: vi.fn().mockResolvedValue(false)}));+// `desktopProcessNames` drives the annotateExpectedExit mock below; tests that+// 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([]),getAppStatusSummary: vi.fn().mockResolvedValue({@@ -31,7 +35,11 @@ vi.mock('../services/apps.js', () => ({stopped: 0,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) }))+ )}));vi.mock('../services/cos.js', () => ({@@ -164,4 +172,73 @@ describe('System Health Routes', () => {expect(response.body).toEqual({ memoryWarn: 87, memoryCritical: 96, diskWarn: 92, diskCritical: 99 });});});++ // A quit desktop app must not drive overallHealth to 'critical' — that lights+ // up the dashboard widget and the CyberCity HUD until the PM2 entry is cleared+ // by hand. This is the widest-blast-radius consumer of `errored` (#2991).+ describe('GET /health/details — desktop (GUI) process exemption', () => {+ beforeEach(() => {+ mock.desktopProcessNames = new Set();+ vi.mocked(listProcesses).mockResolvedValue([]);+ });++ it('stays healthy when the only errored process is a quit game window', async () => {+ mock.desktopProcessNames = new Set(['game']);+ vi.mocked(listProcesses).mockResolvedValue([{ name: 'game', status: 'errored' }]);++ const { body } = await request(app).get('/api/system/health/details');++ expect(body.processes.errored).toBe(0);+ expect(body.processes.desktopExited).toBe(1);+ expect(body.overallHealth).not.toBe('critical');+ expect(body.warnings.some(w => w.type === 'process')).toBe(false);+ });++ it('still goes critical for a genuinely errored web process', async () => {+ vi.mocked(listProcesses).mockResolvedValue([{ name: 'web', status: 'errored' }]);++ const { body } = await request(app).get('/api/system/health/details');++ expect(body.processes.errored).toBe(1);+ expect(body.overallHealth).toBe('critical');+ });++ it('does not report a quit game as a crash loop', async () => {+ mock.desktopProcessNames = new Set(['game']);+ vi.mocked(listProcesses).mockResolvedValue([+ { name: 'game', status: 'errored', unstableRestarts: 5 }+ ]);++ const { body } = await request(app).get('/api/system/health/details');++ expect(body.processes.unstableRestarts).toBe(0);+ expect(body.warnings.some(w => w.type === 'restarts')).toBe(false);+ });++ it('counts a cleanly stopped desktop app as exited, not stopped', async () => {+ mock.desktopProcessNames = new Set(['game']);+ vi.mocked(listProcesses).mockResolvedValue([{ name: 'game', status: 'stopped' }]);++ const { body } = await request(app).get('/api/system/health/details');++ expect(body.processes.stopped).toBe(0);+ expect(body.processes.desktopExited).toBe(1);+ // `total` still counts every process, so nothing vanishes from the roster.+ expect(body.processes.total).toBe(1);+ });++ it('keeps resource totals covering every process, exempt or not', async () => {+ mock.desktopProcessNames = new Set(['game']);+ vi.mocked(listProcesses).mockResolvedValue([+ { name: 'game', status: 'errored', memory: 100, cpu: 5, restarts: 2 },+ { name: 'web', status: 'online', memory: 50, cpu: 3, restarts: 1 }+ ]);++ const { body } = await request(app).get('/api/system/health/details');++ expect(body.processes.totalMemory).toBe(150);+ expect(body.processes.totalCpu).toBe(8);+ expect(body.processes.totalRestarts).toBe(3);+ });+ });});diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 5047d377ec..f339edf431 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -113,16 +113,27 @@ router.get('/health/details', asyncHandler(async (req, res) => {}}- // Process status summary from PM2+ // Process status summary from PM2. Processes whose exit is expected (a desktop+ // app the user closed) are excluded from the health-bearing counts: a quit game+ // window would otherwise force overallHealth to 'critical' below and light up+ // the dashboard widget and the CyberCity HUD until the PM2 entry is manually+ // cleared. Resource totals still cover every process. See issue #2991.+ const annotated = await apps.annotateExpectedExit(pm2Processes);+ const supervised = annotated.filter(p => !p.expectedExit);const processStats = {total: pm2Processes.length,- online: pm2Processes.filter(p => p.status === 'online').length,- stopped: pm2Processes.filter(p => p.status === 'stopped').length,- errored: pm2Processes.filter(p => p.status === 'errored').length,+ online: supervised.filter(p => p.status === 'online').length,+ stopped: supervised.filter(p => p.status === 'stopped').length,+ errored: supervised.filter(p => p.status === 'errored').length,+ // A desktop app that exited (cleanly as `stopped`, or `errored` on a+ // force-quit) — reported on its own rather than as a failure.+ desktopExited: annotated.filter(+ p => p.expectedExit && ['errored', 'stopped'].includes(p.status)+ ).length,totalMemory: pm2Processes.reduce((sum, p) => sum + (p.memory || 0), 0),totalCpu: pm2Processes.reduce((sum, p) => sum + (p.cpu || 0), 0),totalRestarts: pm2Processes.reduce((sum, p) => sum + (p.restarts || 0), 0),- unstableRestarts: pm2Processes.reduce((sum, p) => sum + (p.unstableRestarts || 0), 0)+ unstableRestarts: supervised.reduce((sum, p) => sum + (p.unstableRestarts || 0), 0)};// App status summary — PM2-managed apps only (Xcode/iOS-native projects@@ -164,7 +175,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {if (processStats.unstableRestarts > 0) {if (overallHealth !== 'critical') overallHealth = 'warning';- const crashing = pm2Processes.filter(p => (p.unstableRestarts || 0) > 0).map(p => p.name);+ const crashing = supervised.filter(p => (p.unstableRestarts || 0) > 0).map(p => p.name);const plural = processStats.unstableRestarts === 1 ? '' : 's';warnings.push({type: 'restarts',diff --git a/server/services/apps.js b/server/services/apps.jsindex 8b57794a84..6f59d9f68e 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -202,6 +202,37 @@ export async function getDesktopProcessNames() {return names;}+/**+ * 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 is exactly the desktop (GUI) apps, where the user+ * closing the window ends the 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+ * A fourth consumer that reacts to `errored` needs this too; naming the concept+ * here is what makes that discoverable (see issue #2991).+ *+ * 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.*diff --git a/server/services/apps.test.js b/server/services/apps.test.jsindex 43d13d0dff..e27bde6dc8 100644--- a/server/services/apps.test.js+++ b/server/services/apps.test.js@@ -34,7 +34,7 @@ vi.mock('./pm2.js', () => ({import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';import { listProcessesStrict } from './pm2.js';import { resetExecutionHistory } from './taskSchedule.js';-import { createApp, getAppStatuses, getAppStatusSummary, getDesktopProcessNames, getReservedPorts, invalidateCache, PORTOS_APP_ID, updateAppTaskTypeOverride } from './apps.js';+import { annotateExpectedExit, createApp, getAppStatuses, getAppStatusSummary, getDesktopProcessNames, getReservedPorts, invalidateCache, PORTOS_APP_ID, updateAppTaskTypeOverride } from './apps.js';describe('pr-watcher cooldown reset', () => {beforeEach(() => {@@ -306,6 +306,53 @@ describe('portless / desktop apps (#2991)', () => {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.diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.jsindex 31b3cdb121..f4c147a9f3 100644--- a/server/services/cosHealthMonitor.js+++ b/server/services/cosHealthMonitor.js@@ -13,7 +13,7 @@ import { safeJSONParse } from '../lib/fileUtils.js';import { getMemoryStats } from '../lib/memoryStats.js';import { loadState, saveState, withStateLock, isDaemonRunning } from './cosState.js';import { cosEvents, emitLog } from './cosEvents.js';-import { getDesktopProcessNames } from './apps.js';+import { annotateExpectedExit } from './apps.js';const _execFileAsync = promisify(execFile);const execFileAsync = (cmd, args, opts) => _execFileAsync(cmd, args, { ...opts, windowsHide: true });@@ -48,31 +48,26 @@ export async function runHealthCheck() {const pm2Json = jsonStart >= 0 ? pm2Output.slice(jsonStart) : '[]';const pm2Processes = safeJSONParse(pm2Json, [], { logError: true, context: 'pm2 process list' });- // Desktop (GUI) processes are exempt from auto-restart: the user closing or- // force-quitting a game window can leave PM2 `errored`, and restarting it would- // reopen the window they just closed — the same relaunch loop `autorestart: false`- // prevents, arriving by another path. A registry read failure exempts nothing- // (empty set), so the pre-existing behavior stands rather than silently- // disabling auto-restart for every app. See issue #2991.- const desktopProcessNames = await getDesktopProcessNames().catch(err => {- console.error(`❌ Health monitor could not read the app registry: ${err.message}`);- return new Set();- });-- const erroredProcesses = pm2Processes.filter(- p => p.pm2_env?.status === 'errored' && !desktopProcessNames.has(p.name)- );- // A quit game window counted toward `errored` would degrade the health metric- // for a normal user action, so desktop exits are reported separately instead of- // being folded into the error count (or silently dropped from the totals).- const desktopExited = pm2Processes.filter(- p => desktopProcessNames.has(p.name) && ['errored', 'stopped'].includes(p.pm2_env?.status)+ // A process whose stopping is a normal outcome (a desktop app the user closed)+ // must not be auto-restarted — that would reopen the window they just closed,+ // the same relaunch loop `autorestart: false` prevents, arriving by another+ // path. See issue #2991.+ const annotated = await annotateExpectedExit(pm2Processes);+ const supervised = annotated.filter(p => !p.expectedExit);++ const erroredProcesses = supervised.filter(p => p.pm2_env?.status === 'errored');+ // Reported on its own rather than folded into `errored` (which would degrade+ // health for a normal user action) or dropped from the totals. Counted from+ // the expected-exit processes only, so it never overlaps `errored`/`stopped`+ // below — those now count supervised processes exclusively.+ const desktopExited = annotated.filter(+ p => p.expectedExit && ['errored', 'stopped'].includes(p.pm2_env?.status)).length;metrics.pm2 = {total: pm2Processes.length,- online: pm2Processes.filter(p => p.pm2_env?.status === 'online').length,+ online: supervised.filter(p => p.pm2_env?.status === 'online').length,errored: erroredProcesses.length,- stopped: pm2Processes.filter(p => p.pm2_env?.status === 'stopped').length,+ stopped: supervised.filter(p => p.pm2_env?.status === 'stopped').length,desktopExited};diff --git a/server/services/cosHealthMonitor.test.js b/server/services/cosHealthMonitor.test.jsindex bda9aaf203..ce74303e60 100644--- a/server/services/cosHealthMonitor.test.js+++ b/server/services/cosHealthMonitor.test.js@@ -13,10 +13,12 @@ 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', () => ({- getDesktopProcessNames: vi.fn(async () => {- if (mock.desktopLookupError) throw mock.desktopLookupError;- return mock.desktopProcessNames;+ 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/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex df5d3fd850..98eb0be16f 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -16,7 +16,7 @@ import os from 'os';import { getGoals } from './identity.js';import { getPerformanceSummary, getLearningSummary } from './taskLearning.js';import { listProcesses } from './pm2.js';-import { getDesktopProcessNames } from './apps.js';+import { annotateExpectedExit } from './apps.js';import { getUsage } from './usage.js';import { getCareSummary } from './tribe.js';import { findUnansweredTribeThreads } from './tribeOutreach.js';@@ -124,13 +124,11 @@ async function checkSystemHealth() {});}- // PM2 process errors. Desktop (GUI) processes are excluded: quitting a game- // window is a normal user action that can land PM2 in `errored` (a force-quit- // or non-zero exit), and alerting on it would report every play session's end- // as a failure. See issue #2991.+ // PM2 process errors. Processes whose exit is expected (a desktop app the user+ // quit) are excluded: that is a normal end to a session, and alerting on it+ // would report every play session as a failure. See issue #2991.const processes = await listProcesses().catch(() => []);- const desktopProcessNames = await getDesktopProcessNames().catch(() => new Set());- const alertable = processes.filter(p => !desktopProcessNames.has(p.name));+ const alertable = (await annotateExpectedExit(processes)).filter(p => !p.expectedExit);const errored = alertable.filter(p => p.status === 'errored').length;if (errored > 0) {alerts.push({diff --git a/server/services/proactiveAlerts.test.js b/server/services/proactiveAlerts.test.jsindex 004c55eb38..c1d26b6b78 100644--- a/server/services/proactiveAlerts.test.js+++ b/server/services/proactiveAlerts.test.js@@ -12,10 +12,12 @@ vi.mock('./taskLearning.js', () => ({getLearningSummary: vi.fn(async () => ({ byType: [] }))}));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', () => ({- getDesktopProcessNames: vi.fn(async () => {- if (mock.desktopLookupError) throw mock.desktopLookupError;- return mock.desktopProcessNames;+ annotateExpectedExit: vi.fn(async (processes) => {+ const names = mock.desktopLookupError ? new Set() : mock.desktopProcessNames;+ return processes.map(p => ({ ...p, expectedExit: names.has(p?.name) }));})}));vi.mock('./usage.js', () => ({ getUsage: vi.fn(async () => ({ daily: [] })) }));diff --git a/server/services/socket.js b/server/services/socket.jsindex 298e0f8d0b..f32f56395f 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -238,9 +238,11 @@ export function initSocket(io) {console.log(`📜 Log stream started: ${processName} (${lines} lines)`);// Spawn pm2 logs with --raw flag+ // buildEnv(null) is the default-home case, so this is unconditional —+ // matching every other buildEnv call site in pm2.js.const logProcess = spawnPm2(['logs', processName, '--raw', '--lines', String(lines)],- pm2Home ? { env: buildEnv(pm2Home) } : {}+ { env: buildEnv(pm2Home) });activeStreams.set(socket.id, { process: logProcess, processName });diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 7d423834b7..9e3eb8ab0c 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -413,8 +413,9 @@ describe('socket.js — initSocket', () => {await socket.handlers['logs:subscribe']({ processName: 'portos-server', lines: 100 });expect(getAppById).not.toHaveBeenCalled();+ // buildEnv(null) is the default-home env — no PM2_HOME override.const [, opts] = vi.mocked(spawnPm2).mock.calls[0];- expect(opts).toEqual({});+ expect(opts.env.PM2_HOME).toBeUndefined();});it("streams from the app's custom PM2_HOME when it has one", async () => {@@ -438,7 +439,7 @@ describe('socket.js — initSocket', () => {await socket.handlers['logs:subscribe']({ processName: 'game', lines: 200, appId: 'app-1' });const [, opts] = vi.mocked(spawnPm2).mock.calls[0];- expect(opts).toEqual({});+ expect(opts.env.PM2_HOME).toBeUndefined();});it('still streams when the app lookup fails rather than throwing', async () => {