Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (claude): count a live desktop app as online, and close three launch-path holes

[._.]/ Adam Eivy1f0c9506624a
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsx
index 6d94b9dcfc..68884c082a 100644
--- a/client/src/components/apps/AppDetailView.jsx
+++ b/client/src/components/apps/AppDetailView.jsx
@@ -9,7 +9,7 @@ import StatusBadge from '../StatusBadge';
import * as api from '../../services/api';
import { getLaunchUrls } from '../../services/appUrls';
import socket from '../../services/socket';
-import { APP_DETAIL_TABS, NON_PM2_TYPES, getAppTypeLabel, isDesktopType } from './constants';
+import { APP_DETAIL_TABS, NON_PM2_TYPES, getAppTypeLabel, resolveLaunchPanelProcess } from './constants';
import DesktopLaunchProgress from './DesktopLaunchProgress';
import OverviewTab from './tabs/OverviewTab';
import TasksTab from './tabs/TasksTab';
@@ -90,12 +90,10 @@ export default function AppDetailView() {
const result = await api.startApp(appId).catch(() => null);
// A desktop app's start command builds and imports assets before a window
// appears, so the POST returning tells the user almost nothing. Open the live
- // log panel so the slow launch is visibly progressing rather than hung.
- // Only on success — a failed start has no process to tail.
- if (result && isDesktopType(app?.type)) {
- const processName = app?.pm2ProcessNames?.[0];
- if (processName) setLaunchProcess(processName);
- }
+ // log panel so the slow launch is visibly progressing rather than hung — but
+ // only for a process that actually started (see resolveLaunchPanelProcess).
+ const launchTarget = resolveLaunchPanelProcess(app, result);
+ if (launchTarget) setLaunchProcess(launchTarget);
setActionLoading(null);
};
diff --git a/client/src/components/apps/DesktopLaunchProgress.jsx b/client/src/components/apps/DesktopLaunchProgress.jsx
index 97feddad3b..c4552bfa79 100644
--- a/client/src/components/apps/DesktopLaunchProgress.jsx
+++ b/client/src/components/apps/DesktopLaunchProgress.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { X } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import ProcessLogLines from '../ui/ProcessLogLines';
@@ -20,13 +20,23 @@ import { useProcessLogs } from '../../hooks/useProcessLogs';
* @param {object} props
* @param {string} props.appId App whose PM2_HOME holds the process.
* @param {string} props.processName PM2 process to tail.
- * @param {boolean} props.online Whether the process is up — flips the header
- * copy from "Launching" to "Running" so a finished launch reads as done.
+ * @param {boolean} props.online Whether the process is up — drives the header
+ * copy through launching → running → exited so a finished launch reads as done
+ * and a closed window reads as a normal end rather than a launch still running.
* @param {() => void} props.onDismiss Close the panel (does not stop the app).
*/
export default function DesktopLaunchProgress({ appId, processName, online, onDismiss }) {
const { logs, subscribed } = useProcessLogs(processName, { lines: 200, appId });
const scrollRef = useRef(null);
+ // `online` is two-state, but the panel has three phases. Without remembering
+ // that the process was ever up, a panel still open when the user closes the game
+ // window would revert to the spinner and claim the build is in progress for a
+ // process that already ended.
+ const [wasOnline, setWasOnline] = useState(false);
+ useEffect(() => {
+ if (online) setWasOnline(true);
+ }, [online]);
+ const phase = online ? 'running' : wasOnline ? 'exited' : 'launching';
useEffect(() => {
if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
@@ -36,9 +46,9 @@ export default function DesktopLaunchProgress({ appId, processName, online, onDi
<div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
<div className="flex items-center justify-between gap-2 px-4 py-2 border-b border-port-border">
<div className="flex items-center gap-2 min-w-0">
- {!online && <BrailleSpinner />}
+ {phase === 'launching' && <BrailleSpinner />}
<span className="text-sm text-white truncate">
- {online ? 'Running' : 'Launching'} — {processName}
+ {phase === 'running' ? 'Running' : phase === 'exited' ? 'Exited' : 'Launching'} — {processName}
</span>
</div>
<button
@@ -51,9 +61,11 @@ export default function DesktopLaunchProgress({ appId, processName, online, onDi
</div>
<p className="px-4 pt-2 text-xs text-gray-500">
- {online
+ {phase === 'running'
? 'The app is running. Closing its window stops it — that is a normal exit, not a crash.'
- : 'Building and importing assets. The window opens when this finishes — this can take a while on a cold build.'}
+ : phase === 'exited'
+ ? 'The app has exited. Closing its window is a normal end to a session — press Start to launch it again.'
+ : 'Building and importing assets. The window opens when this finishes — this can take a while on a cold build.'}
</p>
<div
diff --git a/client/src/components/apps/DesktopLaunchProgress.test.jsx b/client/src/components/apps/DesktopLaunchProgress.test.jsx
index 9eb0e260fa..68c98170ba 100644
--- a/client/src/components/apps/DesktopLaunchProgress.test.jsx
+++ b/client/src/components/apps/DesktopLaunchProgress.test.jsx
@@ -12,7 +12,7 @@ vi.mock('../../services/socket', () => ({
}));
import DesktopLaunchProgress from './DesktopLaunchProgress';
-import { DESKTOP_TYPES, isDesktopType } from './constants';
+import { DESKTOP_TYPES, isDesktopType, resolveLaunchPanelProcess } from './constants';
// Lines are batched on a 250ms debounce in useProcessLogs — advance past it so
// the rendered output reflects the frame.
@@ -72,6 +72,22 @@ describe('DesktopLaunchProgress', () => {
expect(screen.getByText(/normal exit, not a crash/)).toBeInTheDocument();
});
+ it('reads as exited once a running app goes away, not back to "building"', () => {
+ // `online` is two-state but the panel has three phases. Reverting to the
+ // spinner and "the window opens when this finishes" for a process that
+ // already ended tells the user a launch is still in flight (issue #2991).
+ const { rerender } = renderPanel({ online: true });
+ expect(screen.getByText(/Running — game/)).toBeInTheDocument();
+
+ rerender(
+ <DesktopLaunchProgress appId="app-1" processName="game" online={false} onDismiss={() => {}} />
+ );
+
+ expect(screen.getByText(/Exited — game/)).toBeInTheDocument();
+ expect(screen.getByText(/normal end to a session/)).toBeInTheDocument();
+ expect(screen.queryByText(/Building and importing assets/)).not.toBeInTheDocument();
+ });
+
it('dismisses without stopping the app', () => {
const onDismiss = vi.fn();
renderPanel({ onDismiss });
@@ -100,3 +116,45 @@ describe('desktop type mirror', () => {
expect(isDesktopType(undefined)).toBe(false);
});
});
+
+// The start endpoint answers 200 `{ success: true, results }` even when every
+// entry in `results` failed, so "did it start?" can only be read per-process.
+describe('resolveLaunchPanelProcess', () => {
+ const desktopApp = { type: 'desktop', pm2ProcessNames: ['game'] };
+
+ it('tails the process on a successful start', () => {
+ expect(resolveLaunchPanelProcess(desktopApp, { success: true, results: { game: { success: true } } }))
+ .toBe('game');
+ });
+
+ it('opens nothing when the process itself failed to start', () => {
+ // The whole point: an overall-200 with a failed process must NOT leave a
+ // panel spinning "the window opens when this finishes" for a dead launch.
+ expect(resolveLaunchPanelProcess(desktopApp, {
+ success: true,
+ results: { game: { success: false, error: 'spawn ENOENT' } },
+ })).toBeNull();
+ });
+
+ it('opens nothing when the request itself rejected', () => {
+ expect(resolveLaunchPanelProcess(desktopApp, null)).toBeNull();
+ });
+
+ it('trusts a 200 that carries no per-process detail', () => {
+ expect(resolveLaunchPanelProcess(desktopApp, { success: true })).toBe('game');
+ });
+
+ it('treats an already-running desktop app as tailable', () => {
+ expect(resolveLaunchPanelProcess(desktopApp, {
+ success: true,
+ results: { game: { success: true, alreadyRunning: true } },
+ })).toBe('game');
+ });
+
+ it('never opens for a web app or an app with no process names', () => {
+ const ok = { success: true, results: { game: { success: true } } };
+ expect(resolveLaunchPanelProcess({ type: 'express', pm2ProcessNames: ['game'] }, ok)).toBeNull();
+ expect(resolveLaunchPanelProcess({ type: 'desktop', pm2ProcessNames: [] }, ok)).toBeNull();
+ expect(resolveLaunchPanelProcess(null, ok)).toBeNull();
+ });
+});
diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.js
index 2ad74d8b90..5e64493e74 100644
--- a/client/src/components/apps/constants.js
+++ b/client/src/components/apps/constants.js
@@ -11,6 +11,29 @@ export const DESKTOP_TYPES = new Set(['desktop']);
/** Whether an app type is a portless GUI/desktop process. */
export const isDesktopType = (type) => DESKTOP_TYPES.has(type);
+/**
+ * The process whose live output the launch panel should tail after a Start —
+ * or `null` when no panel should open.
+ *
+ * The gate is on the PROCESS's own result, not on the response being truthy:
+ * `POST /api/apps/:id/start` answers 200 `{ success: true, results }` even when
+ * every entry in `results` reports `{ success: false }`, so truthiness would open
+ * a panel that spins on "Building and importing assets" forever for a process
+ * that never launched — the exact "reads as hung" failure the panel exists to
+ * remove. A rejected request (`result` null) opens nothing either. A 200 that
+ * carries no per-process detail is trusted, so an older server still gets a panel.
+ *
+ * @param {object|null} app The app record (needs `type` + `pm2ProcessNames`).
+ * @param {object|null} result The start endpoint's parsed response, or null if it threw.
+ * @returns {string|null} PM2 process name to tail, or null.
+ */
+export function resolveLaunchPanelProcess(app, result) {
+ if (!isDesktopType(app?.type)) return null;
+ const processName = app?.pm2ProcessNames?.[0];
+ if (!processName || !result) return null;
+ return result?.results?.[processName]?.success === false ? null : processName;
+}
+
export const getAppTypeLabel = (type) =>
type === 'ios-native' ? '📱 iOS' :
type === 'macos-native' ? '🖥️ macOS' :
diff --git a/server/routes/health.test.js b/server/routes/health.test.js
index 6cc6c44741..bd1b4be852 100644
--- a/server/routes/health.test.js
+++ b/server/routes/health.test.js
@@ -227,6 +227,23 @@ describe('System Health Routes', () => {
expect(body.processes.total).toBe(1);
});
+ it('still counts a RUNNING desktop app as online', async () => {
+ // Only the FAILURE-bearing counts filter on `expectedExit`. Filtering
+ // `online` too would render "1 of 2 running · all healthy" with both up,
+ // and read identically whether the game is running or quit.
+ mock.desktopProcessNames = new Set(['game']);
+ vi.mocked(listProcesses).mockResolvedValue([
+ { name: 'game', status: 'online' },
+ { name: 'web', status: 'online' }
+ ]);
+
+ const { body } = await request(app).get('/api/system/health/details');
+
+ expect(body.processes.online).toBe(2);
+ expect(body.processes.total).toBe(2);
+ expect(body.processes.desktopExited).toBe(0);
+ });
+
it('keeps resource totals covering every process, exempt or not', async () => {
mock.desktopProcessNames = new Set(['game']);
vi.mocked(listProcesses).mockResolvedValue([
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index f339edf431..60a51a13a1 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -114,15 +114,19 @@ router.get('/health/details', asyncHandler(async (req, res) => {
}
// 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
+ // app the user closed) are excluded from the FAILURE-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.
+ // cleared. `expectedExit` describes a process's exit *semantics*, not its
+ // liveness — so `online` counts every process, exempt or not, or a *running*
+ // 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 supervised = annotated.filter(p => !p.expectedExit);
const processStats = {
total: pm2Processes.length,
- online: supervised.filter(p => p.status === 'online').length,
+ online: annotated.filter(p => p.status === 'online').length,
stopped: supervised.filter(p => p.status === 'stopped').length,
errored: supervised.filter(p => p.status === 'errored').length,
// A desktop app that exited (cleanly as `stopped`, or `errored` on a
diff --git a/server/services/apps.js b/server/services/apps.js
index 6f59d9f68e..c64f160878 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -211,12 +211,18 @@ export async function getDesktopProcessNames() {
* 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
+ * - 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`
diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.js
index f4c147a9f3..ee5b40279d 100644
--- a/server/services/cosHealthMonitor.js
+++ b/server/services/cosHealthMonitor.js
@@ -63,9 +63,13 @@ export async function runHealthCheck() {
const desktopExited = annotated.filter(
p => p.expectedExit && ['errored', 'stopped'].includes(p.pm2_env?.status)
).length;
+ // `online` counts EVERY process, exempt or not: the exemption is about exit
+ // semantics, not liveness, so a running desktop app must still report as online
+ // (otherwise it lands in `total` and in no bucket, and the metric reads the same
+ // whether the game is running or quit).
metrics.pm2 = {
total: pm2Processes.length,
- online: supervised.filter(p => p.pm2_env?.status === 'online').length,
+ online: annotated.filter(p => p.pm2_env?.status === 'online').length,
errored: erroredProcesses.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.js
index ce74303e60..647943e82c 100644
--- a/server/services/cosHealthMonitor.test.js
+++ b/server/services/cosHealthMonitor.test.js
@@ -146,6 +146,21 @@ describe('cosHealthMonitor.runHealthCheck', () => {
expect(metrics.pm2.desktopExited).toBe(1);
});
+ it('still counts a RUNNING desktop process as online', async () => {
+ // The exemption is about exit semantics, not liveness. Filtering `online`
+ // on it too would leave a live game in `total` and in no bucket at all —
+ // and make the metric read identically whether it is running or quit.
+ mock.desktopProcessNames = new Set(['game']);
+ mock.pm2Stdout = JSON.stringify([
+ { name: 'game', pm2_env: { status: 'online' }, monit: { memory: 0 } },
+ { name: 'web', pm2_env: { status: 'online' }, monit: { memory: 0 } }
+ ]);
+
+ const { metrics } = await runHealthCheck();
+
+ expect(metrics.pm2).toEqual({ total: 2, online: 2, errored: 0, stopped: 0, desktopExited: 0 });
+ });
+
it('still auto-restarts non-desktop processes alongside an exempt one', async () => {
mock.desktopProcessNames = new Set(['game']);
mock.pm2Stdout = JSON.stringify([
diff --git a/server/services/socket.js b/server/services/socket.js
index f32f56395f..6eac8ea5ce 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -53,6 +53,22 @@ import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.j
// Store active log streams per socket
const activeStreams = new Map();
+// Monotonic per-socket subscribe generation. `logs:subscribe` awaits an app
+// lookup before it can spawn `pm2 logs`, so the request it started for may be
+// obsolete by the time it resolves. Slot occupancy alone cannot tell the cases
+// apart: an `logs:unsubscribe` that lands mid-lookup leaves the slot EMPTY, so a
+// stale handler would spawn an orphan `pm2 logs` nothing ever kills; and when two
+// subscribes overlap, the OLDER one can fill the slot first, so the newer one
+// bails and its client waits forever for `logs:subscribed`. Every claim and
+// release bumps this counter and a handler only resumes while its own generation
+// is current — the server-side mirror of the `{ target, generation }`
+// pending-request convention in CLAUDE.md.
+const streamGenerations = new Map();
+const bumpStreamGeneration = (socketId) => {
+ const next = (streamGenerations.get(socketId) || 0) + 1;
+ streamGenerations.set(socketId, next);
+ return next;
+};
// Store CoS subscribers
const cosSubscribers = new Set();
// Store error subscribers for auto-fix notifications
@@ -211,8 +227,10 @@ export function initSocket(io) {
if (!data) return;
const { processName, lines, appId } = data;
- // Clean up any existing stream for this socket
+ // Clean up any existing stream for this socket, then claim this request.
+ // Claiming AFTER the cleanup bump is what makes this generation current.
cleanupStream(socket.id);
+ const generation = bumpStreamGeneration(socket.id);
// Resolve the app's custom PM2_HOME (if it has one) so the stream tails the
// home its processes actually run in. Runs outside the Express lifecycle, so
@@ -227,13 +245,14 @@ export function initSocket(io) {
});
}
- // The await above yields, so a rapid resubscribe (or a disconnect) may have
- // landed in the meantime. Bail if this socket is gone rather than spawning an
- // orphan `pm2 logs` that nothing will ever clean up.
+ // The await above yields, so a disconnect, an unsubscribe, or a newer
+ // subscribe may have landed in the meantime. Bail if this socket is gone
+ // rather than spawning an orphan `pm2 logs` nothing will ever clean up.
if (socket.disconnected) return;
- // A newer logs:subscribe already claimed this socket's stream slot — its
- // cleanupStream ran before ours resolved. Yield to it instead of clobbering.
- if (activeStreams.has(socket.id)) return;
+ // Superseded or cancelled while the lookup was in flight. Covers both the
+ // unsubscribe (slot left empty) and the two-overlapping-subscribes cases
+ // that a bare `activeStreams.has()` check gets wrong in opposite directions.
+ if (streamGenerations.get(socket.id) !== generation) return;
console.log(`📜 Log stream started: ${processName} (${lines} lines)`);
@@ -286,6 +305,12 @@ export function initSocket(io) {
});
logProcess.on('close', (code) => {
+ // A SIGTERM'd predecessor's `close` fires asynchronously — after the
+ // replacement stream has already registered — so an unscoped
+ // `activeStreams.delete` here would unregister the LIVE stream and leak
+ // it (no later cleanupStream would find it to kill), while `logs:close`
+ // would tell the client the stream it is watching had ended.
+ if (streamGenerations.get(socket.id) !== generation) return;
socket.emit('logs:close', { code, processName });
activeStreams.delete(socket.id);
});
@@ -547,6 +572,9 @@ export function initSocket(io) {
socket.on('disconnect', () => {
console.log(`🔌 Client disconnected: ${socket.id}`);
cleanupStream(socket.id);
+ // The bump inside cleanupStream already cancelled any in-flight subscribe;
+ // drop the counter so the map doesn't grow one entry per socket forever.
+ streamGenerations.delete(socket.id);
for (const set of ALL_SUBSCRIBER_SETS) set.delete(socket);
const detached = shellService.detachSocketSessions(socket);
if (detached > 0) {
@@ -693,6 +721,10 @@ function setupProactiveSpeechForwarding() {
}
function cleanupStream(socketId) {
+ // Bump unconditionally, even with no stream to kill: this is the cancellation
+ // point for a `logs:subscribe` still awaiting its app lookup, which has not
+ // claimed the slot yet and so would otherwise survive an unsubscribe.
+ bumpStreamGeneration(socketId);
const stream = activeStreams.get(socketId);
if (stream) {
stream.process.kill('SIGTERM');
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 9e3eb8ab0c..e0e3f37f8d 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -469,5 +469,48 @@ describe('socket.js — initSocket', () => {
expect(vi.mocked(spawnPm2)).not.toHaveBeenCalled();
});
+
+ it('does not spawn an orphan stream when unsubscribe lands mid-lookup', async () => {
+ // The cancellation case an `activeStreams.has()` check gets exactly wrong:
+ // the unsubscribe's cleanupStream leaves the slot EMPTY, so an occupancy
+ // check reads "free" and the stale handler spawns a `pm2 logs` that no
+ // later cleanup will ever find to kill.
+ const socket = makeSocket('logs-unsub-midlookup');
+ io.connect(socket);
+ vi.mocked(getAppById).mockImplementation(async () => {
+ socket.handlers['logs:unsubscribe']();
+ return { id: 'app-1', pm2Home: '/opt/example/.pm2' };
+ });
+
+ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 200, appId: 'app-1' });
+
+ expect(vi.mocked(spawnPm2)).not.toHaveBeenCalled();
+ });
+
+ it('lets the NEWER of two overlapping subscribes win', async () => {
+ // The opposite failure of the same check: with two subscribes in flight the
+ // older one can fill the slot first, so an occupancy check makes the NEWER
+ // one bail — and its client never gets `logs:subscribed`, leaving the panel
+ // stuck on "Connecting to log stream…" forever.
+ const socket = makeSocket('logs-overlapping');
+ io.connect(socket);
+ const gates = [];
+ vi.mocked(getAppById).mockImplementation(
+ () => new Promise(resolve => gates.push(() => resolve({ id: 'app-1', pm2Home: null })))
+ );
+
+ const first = socket.handlers['logs:subscribe']({ processName: 'old', lines: 100, appId: 'app-1' });
+ const second = socket.handlers['logs:subscribe']({ processName: 'new', lines: 100, appId: 'app-1' });
+ // Resolve them out of order: the older lookup finishes last.
+ gates[1]();
+ gates[0]();
+ await Promise.all([first, second]);
+
+ expect(vi.mocked(spawnPm2)).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(spawnPm2).mock.calls[0][0]).toEqual(['logs', 'new', '--raw', '--lines', '100']);
+ const subscribed = socket.emitted.filter(([ev]) => ev === 'logs:subscribed');
+ expect(subscribed).toHaveLength(1);
+ expect(subscribed[0][1].processName).toBe('new');
+ });
});
});
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index a324a28f74..600d08674d 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -164,8 +164,14 @@ const activeAppsRef = { value: [
{ id: 'bookloom-abc', name: 'BookLoom' },
{ id: 'portos-default', name: 'PortOS' },
] };
+// `desktopNamesRef` drives pm2_status's expected-exit exemption (#2991): a
+// desktop app the user closed must not be read back as an "issue".
+const desktopNamesRef = { value: new Set() };
vi.mock('../apps.js', () => ({
getActiveApps: vi.fn(async () => activeAppsRef.value),
+ annotateExpectedExit: vi.fn(async (procs) =>
+ procs.map(p => ({ ...p, expectedExit: desktopNamesRef.value.has(p?.name) }))
+ ),
}));
const catalogItemsRef = { value: [] };
const catalogRefsRef = { value: [] };
@@ -561,6 +567,53 @@ describe('pm2_restart type guard', () => {
});
});
+// "Is anything crashed?" must not answer "the game (errored)" when the user
+// simply closed its window. pm2_status is the fourth consumer of `errored` the
+// expected-exit exemption has to cover (#2991).
+describe('pm2_status — desktop (GUI) exit exemption', () => {
+ const setProcesses = async (procs) => {
+ const { listProcesses } = await import('../pm2.js');
+ vi.mocked(listProcesses).mockResolvedValue(procs);
+ };
+
+ it('reports a quit game as closed-by-you, not as an issue', async () => {
+ desktopNamesRef.value = new Set(['game']);
+ await setProcesses([
+ { name: 'game', status: 'errored', restarts: 0 },
+ { name: 'web', status: 'online', restarts: 0 },
+ ]);
+
+ const res = await dispatchTool('pm2_status', {});
+
+ expect(res.unhealthy).toEqual([]);
+ expect(res.desktopExited).toEqual([{ name: 'game', status: 'errored' }]);
+ expect(res.summary).toMatch(/closed by you: game/);
+ expect(res.summary).not.toMatch(/issues/);
+ });
+
+ it('still reports a genuinely errored web process as an issue', async () => {
+ desktopNamesRef.value = new Set();
+ await setProcesses([{ name: 'web', status: 'errored', restarts: 3 }]);
+
+ const res = await dispatchTool('pm2_status', {});
+
+ expect(res.unhealthy).toEqual([{ name: 'web', status: 'errored', restarts: 3 }]);
+ expect(res.summary).toMatch(/issues: web \(errored\)/);
+ });
+
+ it('counts a running desktop app as online — the exemption is about exits', async () => {
+ desktopNamesRef.value = new Set(['game']);
+ await setProcesses([{ name: 'game', status: 'online', restarts: 0 }]);
+
+ const res = await dispatchTool('pm2_status', {});
+
+ expect(res.online).toBe(1);
+ expect(res.total).toBe(1);
+ expect(res.desktopExited).toEqual([]);
+ expect(res.summary).toBe('1 of 1 processes online.');
+ });
+});
+
// Bug: "Instead of entering what I asked into the description form field,
// it created a brain entry." Form-fill utterances were seeing brain_capture
// in the tool list because brain_capture used to be always-on; the LLM
diff --git a/server/services/voice/tools/system.js b/server/services/voice/tools/system.js
index b9904ef997..0cf2794983 100644
--- a/server/services/voice/tools/system.js
+++ b/server/services/voice/tools/system.js
@@ -3,6 +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 { getItems, getFeeds, markItemRead, markAllRead } from '../../feeds.js';
import { clampLimit } from './shared.js';
@@ -20,20 +21,28 @@ export const SYSTEM_TOOLS = [
'Report the status of PortOS PM2 processes. Use when the user asks "is anything crashed?", "is everything running?", "any errors?". Reports total, healthy, and any processes in errored/stopped states.',
parameters: { type: 'object', properties: {} },
execute: async () => {
- const procs = await listProcesses();
- const unhealthy = procs.filter((p) => p.status !== 'online');
- const online = procs.length - unhealthy.length;
+ // A desktop app the user closed is NOT an issue to read back — annotate
+ // before classifying so "is anything crashed?" doesn't answer "the game
+ // (errored)" when the user simply quit its window. See issue #2991.
+ const procs = await annotateExpectedExit(await listProcesses());
+ const unhealthy = procs.filter((p) => !p.expectedExit && p.status !== 'online');
+ const exited = procs.filter((p) => p.expectedExit && p.status !== 'online');
+ const online = procs.filter((p) => p.status === 'online').length;
const parts = [`${online} of ${procs.length} processes online`];
if (unhealthy.length) {
parts.push(
`issues: ${unhealthy.map((p) => `${p.name} (${p.status})`).join(', ')}`,
);
}
+ if (exited.length) {
+ parts.push(`closed by you: ${exited.map((p) => p.name).join(', ')}`);
+ }
return {
ok: true,
total: procs.length,
online,
unhealthy: unhealthy.map((p) => ({ name: p.name, status: p.status, restarts: p.restarts })),
+ desktopExited: exited.map((p) => ({ name: p.name, status: p.status })),
summary: parts.join('. ') + '.',
};
},