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

perf: push PM2 process and native launch snapshots (#8549)

[._.]/ Adam Eivy6d48f09a2014
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsx
index 27734bbf90..e6fa4e1b08 100644
--- a/client/src/components/apps/AppDetailView.jsx
+++ b/client/src/components/apps/AppDetailView.jsx
@@ -15,7 +15,7 @@ import * as api from '../../services/api';
import { getLaunchUrls } from '../../services/appUrls';
import socket from '../../services/socket';
import { APP_DETAIL_TABS, NON_PM2_TYPES, getAppTypeLabel, isAppFeatureEnabled, resolveLaunchPanelProcess } from './constants';
-import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';
+import { useProcessSnapshot } from '../../hooks/useProcessSnapshot.js';
import { useInstanceFeatures } from '../../hooks/useInstanceFeatures.js';
import DesktopLaunchProgress from './DesktopLaunchProgress';
import OverviewTab from './tabs/OverviewTab';
@@ -166,25 +166,16 @@ function AppDetail() {
setNativeLaunchOnline(true);
};
- // Native launch status is independent of the web app's overall PM2 state.
- // Poll only while its live-output panel is open so closing the game moves the
- // panel from Running to Exited without disturbing the standard web controls.
- const refreshNativeLaunchStatus = useCallback(() => (
- api.getNativeLaunchStatus(appId, { silent: true })
- .then(result => {
- if (['online', 'launching'].includes(result?.status)) {
- setNativeLaunchOnline(true);
- } else if (['stopped', 'errored', 'not_found', 'not_started'].includes(result?.status)) {
- setNativeLaunchOnline(false);
- }
- })
- // A failed status read is unknown, not evidence that the game exited.
- .catch(() => {})
- ), [appId]);
- useAutoRefetch(refreshNativeLaunchStatus, 1500, {
+ // Native targets share their app's PM2 home, but not its web-process status.
+ const { data: nativeProcesses } = useProcessSnapshot(appId, {
enabled: Boolean(launchProcess) && launchProcess === app?.nativeLaunch?.processName,
- pollOnly: true,
});
+ useEffect(() => {
+ if (!nativeProcesses) return; // Failed probes preserve the last good state.
+ const status = nativeProcesses.find(proc => proc.name === launchProcess)?.status ?? 'not_found';
+ if (['online', 'launching'].includes(status)) setNativeLaunchOnline(true);
+ else if (['stopped', 'errored', 'not_found', 'not_started'].includes(status)) setNativeLaunchOnline(false);
+ }, [nativeProcesses, launchProcess]);
const handleStop = async () => {
setActionLoading('stop');
diff --git a/client/src/components/apps/AppDetailView.test.jsx b/client/src/components/apps/AppDetailView.test.jsx
index 80fed418d0..8679d68ad0 100644
--- a/client/src/components/apps/AppDetailView.test.jsx
+++ b/client/src/components/apps/AppDetailView.test.jsx
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router';
@@ -15,10 +15,13 @@ const instanceFeatureMock = vi.hoisted(() => ({
vi.mock('../../services/api', () => ({
PORTOS_APP_ID: 'portos-default',
getApp: vi.fn(),
+ getProcessesList: vi.fn(),
+ launchNativeApp: vi.fn(),
}));
vi.mock('../../services/socket', () => ({
default: {
+ emit: vi.fn(),
on: vi.fn((event, handler) => socketHandlers.set(event, handler)),
off: vi.fn((event, handler) => {
if (socketHandlers.get(event) === handler) socketHandlers.delete(event);
@@ -41,7 +44,7 @@ vi.mock('../BrailleSpinner', () => ({ default: () => null }));
vi.mock('../StatusBadge', () => ({ default: () => null }));
vi.mock('./DeployPanel', () => ({ default: () => null }));
vi.mock('./EditAppDrawer', () => ({ default: () => null }));
-vi.mock('./DesktopLaunchProgress', () => ({ default: () => null }));
+vi.mock('./DesktopLaunchProgress', () => ({ default: ({ online }) => <output data-testid="native-state">{online ? 'Running' : 'Exited'}</output> }));
vi.mock('./tabs/OverviewTab', () => ({ default: ({ app }) => <output data-testid="overview-app">{app.id}</output> }));
vi.mock('./tabs/TasksTab', () => ({ default: () => null }));
vi.mock('./tabs/AutomationTab', () => ({ default: () => null }));
@@ -312,3 +315,34 @@ describe('AppDetailView fetch lifecycle', () => {
expect(api.getApp).toHaveBeenCalledTimes(4);
});
});
+
+
+describe('native launch realtime status', () => {
+ afterEach(() => vi.useRealTimers());
+ it('applies process pushes without polling and reconciles reconnect/reshow once', async () => {
+ vi.clearAllMocks();
+ socketHandlers.clear();
+ vi.useFakeTimers();
+ api.getApp.mockResolvedValue({ ...APP, nativeLaunch: { label: 'Native', processName: 'example-native' } });
+ api.launchNativeApp.mockResolvedValue({ processName: 'example-native' });
+ api.getProcessesList.mockResolvedValue([{ name: 'example-native', status: 'online' }]);
+ const view = renderDetail();
+ await act(async () => {});
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Launch Native for Example App' })));
+ expect(screen.getByTestId('native-state')).toHaveTextContent('Running');
+ expect(api.getProcessesList).toHaveBeenCalledTimes(1);
+ await act(async () => vi.advanceTimersByTimeAsync(15000));
+ expect(api.getProcessesList).toHaveBeenCalledTimes(1);
+ await act(async () => socketHandlers.get('processes:changed')({ appIds: [APP.id], processes: null }));
+ expect(screen.getByTestId('native-state')).toHaveTextContent('Running');
+ await act(async () => socketHandlers.get('processes:changed')({ appIds: [APP.id], processes: [{ name: 'example-native', status: 'stopped' }] }));
+ expect(screen.getByTestId('native-state')).toHaveTextContent('Exited');
+ await act(async () => socketHandlers.get('connect')());
+ expect(api.getProcessesList).toHaveBeenCalledTimes(2);
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(api.getProcessesList).toHaveBeenCalledTimes(3);
+ view.unmount();
+ expect(socketHandlers.has('processes:changed')).toBe(false);
+ expect(socketHandlers.has('connect')).toBe(false);
+ });
+});
diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsx
index 7c753e0fcb..207b15580e 100644
--- a/client/src/components/apps/tabs/ProcessesTab.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.jsx
@@ -1,12 +1,11 @@
import { useState, useEffect, useRef, Fragment } from 'react';
import { createPortal } from 'react-dom';
import { Maximize2, X } from 'lucide-react';
-import * as api from '../../../services/api';
-import { executeCommand } from '../../../services/api';
+import { applyProcessAction } from '../../../services/api';
import BrailleSpinner from '../../BrailleSpinner';
import { FormField } from '../../ui/FormField';
import ProcessLogLines from '../../ui/ProcessLogLines';
-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { useProcessSnapshot } from '../../../hooks/useProcessSnapshot';
import { useProcessLogs } from '../../../hooks/useProcessLogs';
import { copyToClipboard } from '../../../lib/clipboard';
import { formatBytes, formatCount, formatDurationMs, formatTimeOfDaySeconds } from '../../../utils/formatters';
@@ -32,13 +31,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
// launch-progress panel can't drift.
const { logs, subscribed, clear: clearLogs } = useProcessLogs(expandedProcess, { lines: tailLines, appId });
- // Let errors throw — `useAutoRefetch` preserves the last-good process list
- // on transient failures. `silent: true` is essential here because the 5s
- // poll would otherwise spit a toast every 5 seconds during any blip.
- const { data, loading, refetch } = useAutoRefetch(
- () => api.getProcessesList({ silent: true }),
- 5000,
- );
+ const { data, loading, error, refetch, applySnapshot } = useProcessSnapshot(appId);
const processes = data ?? [];
// Pin both log panes to the bottom as lines arrive. Driven off `logs` rather
@@ -51,11 +44,9 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
const pm2Action = async (action, name) => {
setRestarting(prev => ({ ...prev, [name]: true }));
- await executeCommand(`pm2 ${action} ${name}`, undefined).catch(() => null);
- setTimeout(() => {
- setRestarting(prev => ({ ...prev, [name]: false }));
- refetch();
- }, 2000);
+ const result = await applyProcessAction(name, action, appId).catch(() => null);
+ if (result) applySnapshot(result.processes);
+ setRestarting(prev => ({ ...prev, [name]: false }));
};
// No explicit clear here — useProcessLogs resets its buffer whenever
@@ -85,6 +76,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
return (
<>
<div className="space-y-4">
+ {error && <p role="status" className="text-port-warning">Process status unavailable; showing the last known state.</p>}
<div className="flex justify-between items-center">
<p className="text-gray-500 text-sm">{filteredProcesses.length} process{filteredProcesses.length !== 1 ? 'es' : ''}</p>
<button
diff --git a/client/src/components/apps/tabs/ProcessesTab.realtime.test.jsx b/client/src/components/apps/tabs/ProcessesTab.realtime.test.jsx
new file mode 100644
index 0000000000..574cd08d05
--- /dev/null
+++ b/client/src/components/apps/tabs/ProcessesTab.realtime.test.jsx
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+
+const handlers = new Map();
+vi.mock('../../../services/socket', () => ({ default: {
+ emit: vi.fn(),
+ on: (event, fn) => { if (!handlers.has(event)) handlers.set(event, new Set()); handlers.get(event).add(fn); },
+ off: (event, fn) => handlers.get(event)?.delete(fn),
+} }));
+vi.mock('../../../services/api', () => ({ getProcessesList: vi.fn(), applyProcessAction: vi.fn() }));
+vi.mock('../../../hooks/useProcessLogs', () => ({ useProcessLogs: () => ({ logs: [], subscribed: false }) }));
+import * as api from '../../../services/api';
+import ProcessesTab from './ProcessesTab';
+const emit = (event, data) => act(async () => { for (const fn of handlers.get(event) ?? []) fn(data); });
+const process = { name: 'example-api', status: 'online', pm_id: 1 };
+beforeEach(() => { vi.useFakeTimers(); vi.clearAllMocks(); handlers.clear(); api.getProcessesList.mockResolvedValue([process]); });
+afterEach(() => vi.useRealTimers());
+
+it('renders pushed process state, ignores unrelated homes, and recovers without polling', async () => {
+ const view = render(<ProcessesTab appId="app-a" />);
+ await act(async () => {});
+ expect(screen.getByText('online')).toBeInTheDocument();
+ expect(api.getProcessesList).toHaveBeenCalledWith({ appId: 'app-a', silent: true });
+ await act(async () => vi.advanceTimersByTimeAsync(30000));
+ expect(api.getProcessesList).toHaveBeenCalledTimes(1);
+ await emit('processes:changed', { appIds: ['app-b'], processes: [] });
+ expect(screen.getByText('online')).toBeInTheDocument();
+ await emit('processes:changed', { appIds: ['app-a'], processes: [{ ...process, status: 'stopped' }] });
+ expect(screen.getByText('stopped')).toBeInTheDocument();
+ await emit('processes:changed', { appIds: ['app-a'], processes: null });
+ expect(screen.getByText('stopped')).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent('unavailable');
+ await emit('connect');
+ expect(api.getProcessesList).toHaveBeenCalledTimes(2);
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+ expect(api.getProcessesList).toHaveBeenCalledTimes(3);
+ view.unmount();
+ expect(handlers.get('processes:changed').size).toBe(0);
+ await emit('connect');
+ expect(api.getProcessesList).toHaveBeenCalledTimes(3);
+});
+
+it('does not overwrite a pushed snapshot or a new app with an older HTTP response', async () => {
+ let finish;
+ api.getProcessesList.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));
+ const view = render(<ProcessesTab appId="app-a" />);
+ await emit('processes:changed', { appIds: ['app-a'], processes: [{ ...process, status: 'stopped' }] });
+ await act(async () => finish([process]));
+ expect(screen.getByText('stopped')).toBeInTheDocument();
+ api.getProcessesList.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));
+ await emit('connect');
+ view.rerender(<ProcessesTab appId="app-b" />);
+ await act(async () => {});
+ await act(async () => finish([]));
+ expect(screen.getByText('online')).toBeInTheDocument();
+});
+
+
+it('applies a scoped command response immediately without a delayed refetch', async () => {
+ api.applyProcessAction.mockResolvedValue({ processes: [{ ...process, status: 'stopped' }] });
+ render(<ProcessesTab appId="app-a" />);
+ await act(async () => {});
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Stop' })));
+ expect(api.applyProcessAction).toHaveBeenCalledWith('example-api', 'stop', 'app-a');
+ expect(screen.getByText('stopped')).toBeInTheDocument();
+ await act(async () => vi.advanceTimersByTimeAsync(10000));
+ expect(api.getProcessesList).toHaveBeenCalledTimes(1);
+});
diff --git a/client/src/components/apps/tabs/ProcessesTab.test.jsx b/client/src/components/apps/tabs/ProcessesTab.test.jsx
index 0ae95ad158..4620108bac 100644
--- a/client/src/components/apps/tabs/ProcessesTab.test.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.test.jsx
@@ -2,12 +2,12 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
vi.mock('../../../services/api', () => ({
- executeCommand: vi.fn(),
+ applyProcessAction: vi.fn(),
getProcessesList: vi.fn(),
}));
-vi.mock('../../../hooks/useAutoRefetch', () => ({
- useAutoRefetch: () => ({
+vi.mock('../../../hooks/useProcessSnapshot', () => ({
+ useProcessSnapshot: () => ({
data: [{ name: 'example-api', status: 'online', pid: 1, cpu: 0, memory: 0, uptime: null, restarts: 0, pm_id: 1 }],
loading: false,
refetch: vi.fn(),
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index c38b829e8b..97ba20560e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -87,6 +87,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
+| `useProcessSnapshot` | PM2 snapshots from entry reads and server pushes, with reconnect/reshow recovery and stale-read protection. | Process lists and native-launch panels; pass an app id for custom PM2 homes. |
| `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. |
| `useSocketResource` | Initial resource read plus room/broadcast event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |
| `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 315edb2869..1d2bf317ee 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -248,3 +248,5 @@ export * from './usePagedCollection.js';
export * from './useGoalOrganize.js';
export * from './useSocketResource.js';
+
+export * from './useProcessSnapshot.js';
diff --git a/client/src/hooks/useProcessSnapshot.js b/client/src/hooks/useProcessSnapshot.js
new file mode 100644
index 0000000000..137e7593e1
--- /dev/null
+++ b/client/src/hooks/useProcessSnapshot.js
@@ -0,0 +1,64 @@
+import { useEffect, useRef, useState, useCallback } from 'react';
+import * as api from '../services/api';
+import socket from '../services/socket';
+import { useSocketSubscription } from './useSocketSubscription.js';
+import { useVisibilityEvent } from './useVisibilityEvent.js';
+
+/** PM2 snapshots: one entry read, pushed updates, and reconnect/reshow recovery. */
+export function useProcessSnapshot(appId, { enabled = true } = {}) {
+ const [state, setState] = useState({ appId, data: null, loading: true, error: null });
+ const refreshRef = useRef(null);
+ const applyRef = useRef(null);
+ const identityRef = useRef(appId);
+ identityRef.current = appId;
+ const applySnapshot = useCallback(data => {
+ if (identityRef.current === appId) applyRef.current?.(data);
+ }, [appId]);
+ const refetch = useCallback(() => refreshRef.current?.(), []);
+
+ useEffect(() => {
+ let active = true;
+ let pending = false;
+ let trailing = false;
+ let revision = 0;
+ setState({ appId, data: null, loading: enabled, error: null });
+ if (!enabled) return;
+
+ const refresh = async () => {
+ if (!active || document.visibilityState === 'hidden') return;
+ if (pending) { trailing = true; return; }
+ pending = true;
+ const started = revision;
+ await api.getProcessesList({ appId, silent: true }).then(data => {
+ if (active && revision === started) setState({ appId, data, loading: false, error: null });
+ }).catch(error => {
+ if (active && revision === started) setState(prev => ({ ...prev, loading: false, error }));
+ });
+ pending = false;
+ if (active && trailing) { trailing = false; void refresh(); }
+ };
+ const apply = data => {
+ ++revision;
+ if (Array.isArray(data)) setState({ appId, data, loading: false, error: null });
+ else setState(prev => ({ ...prev, loading: false, error: new Error('PM2 status unavailable') }));
+ };
+ applyRef.current = apply;
+ const onSnapshot = frame => {
+ if (appId ? !frame?.appIds?.includes(appId) : !frame?.defaultHome) return;
+ apply(frame.processes);
+ };
+ refreshRef.current = refresh;
+ socket.on('processes:changed', onSnapshot);
+ void refresh();
+ return () => {
+ active = false;
+ refreshRef.current = null;
+ applyRef.current = null;
+ socket.off('processes:changed', onSnapshot);
+ };
+ }, [appId, enabled]);
+
+ useSocketSubscription('processes', { enabled, onResubscribe: refetch });
+ useVisibilityEvent(state => { if (state === 'visible') refetch(); });
+ return { ...state, data: enabled && state.appId === appId ? state.data : null, refetch, applySnapshot };
+}
diff --git a/client/src/hooks/useSocketSubscription.js b/client/src/hooks/useSocketSubscription.js
index 3f4ed1b359..51d1536311 100644
--- a/client/src/hooks/useSocketSubscription.js
+++ b/client/src/hooks/useSocketSubscription.js
@@ -49,14 +49,14 @@ function getEntry(namespace) {
*
* @param {string} namespace - a namespace registered server-side via
* `registerSubscriber` (e.g. 'notifications', 'errors', 'instances', 'loops').
- * @param {{ onResubscribe?: () => void }} [options]
+ * @param {{ onResubscribe?: () => void, enabled?: boolean }} [options]
*/
-export function useSocketSubscription(namespace, { onResubscribe } = {}) {
+export function useSocketSubscription(namespace, { onResubscribe, enabled = true } = {}) {
const onResubscribeRef = useRef(onResubscribe);
onResubscribeRef.current = onResubscribe;
useEffect(() => {
- if (!namespace) return;
+ if (!namespace || !enabled) return;
const entry = getEntry(namespace);
const callback = () => onResubscribeRef.current?.();
@@ -81,5 +81,5 @@ export function useSocketSubscription(namespace, { onResubscribe } = {}) {
registry.delete(namespace);
}
};
- }, [namespace]);
+ }, [namespace, enabled]);
}
diff --git a/client/src/services/apiCommands.js b/client/src/services/apiCommands.js
index 9af408318e..b8eab08e36 100644
--- a/client/src/services/apiCommands.js
+++ b/client/src/services/apiCommands.js
@@ -8,4 +8,10 @@ export const executeCommand = (command, workspacePath, options = {}) => request(
});
export const stopCommand = (id) => request(`/commands/${id}/stop`, { method: 'POST' });
export const getAllowedCommands = () => request('/commands/allowed');
-export const getProcessesList = (options) => request('/commands/processes', options);
+export const getProcessesList = ({ appId, ...options } = {}) => request(
+ `/commands/processes${appId ? `?appId=${encodeURIComponent(appId)}` : ''}`, options
+);
+
+export const applyProcessAction = (name, action, appId) => request(`/commands/processes/${encodeURIComponent(name)}/action`, {
+ method: 'POST', body: JSON.stringify({ action, appId })
+});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index e780407b66..9100c69114 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -37,6 +37,22 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
payloadSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false },
},
+ 'processes:changed': Object.freeze({
+ direction: 'server-to-client',
+ summary: 'PM2 snapshot for registered apps sharing a home; null means the probe failed.',
+ payloadSchema: {
+ type: 'object', required: ['appIds', 'defaultHome', 'processes'],
+ properties: {
+ appIds: { type: 'array', items: { type: 'string' } },
+ defaultHome: { type: 'boolean' },
+ processes: { type: ['array', 'null'], items: { type: 'object', properties: {
+ name: { type: 'string' }, status: { type: 'string' }, pid: { type: 'number' },
+ pm_id: { type: 'number' }, cpu: { type: 'number' }, memory: { type: 'number' },
+ uptime: { type: ['number', 'null'] }, restarts: { type: 'number' }, unstableRestarts: { type: 'number' }
+ } } }
+ }
+ }
+ }),
'app:deploy': input(appDeploySchema, 'Deploy a managed app with allowlisted flags.'),
'app:standardize': input(appStandardizeSchema, 'Standardize one registered app.'),
'app:update': input(appUpdateSchema, 'Run the update lifecycle for one registered app.'),
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 802c2f8d7c..60ba1df8fc 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -87,6 +87,13 @@ export {
// `ports` is an open-ended label→port map so app-specific keys derived from
// *_PORT env vars (coinbaseIpc, geminiIpc, etc.) survive validation alongside
// the well-known labels (api, ui, devUi, cdp, health).
+export const processListQuerySchema = z.object({ appId: z.string().min(1).optional() });
+
+export const processActionSchema = z.object({
+ action: z.enum(['start', 'stop', 'restart']),
+ appId: z.string().min(1).optional()
+});
+
export const processSchema = z.object({
name: z.string().min(1),
port: z.number().int().min(1).max(65535).nullable().optional(),
diff --git a/server/routes/commands.js b/server/routes/commands.js
index fbcece59e1..c7754bb92e 100644
--- a/server/routes/commands.js
+++ b/server/routes/commands.js
@@ -1,4 +1,6 @@
import { Router } from 'express';
+import { processActionSchema, processListQuerySchema, validateRequest } from '../lib/validation.js';
+import { validateCommand } from '../lib/commandSecurity.js';
import { existsSync, statSync, realpathSync } from 'fs';
import { resolve } from 'path';
import * as commands from '../services/commands.js';
@@ -90,10 +92,35 @@ router.get('/allowed', asyncHandler(async (req, res) => {
// GET /api/commands/processes - Get PM2 process list with details
router.get('/processes', asyncHandler(async (req, res) => {
- const processes = await pm2Service.listProcesses();
+ const { appId } = validateRequest(processListQuerySchema, req.query);
+ const app = appId ? await (await import('../services/apps.js')).getAppById(appId) : null;
+ if (appId && !app) throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
+ const processes = await pm2Service.listProcessesStrict(app?.pm2Home || null);
+ if (processes === null) throw new ServerError('PM2 status unavailable', { status: 503, code: 'PM2_UNAVAILABLE' });
res.json(processes);
}));
+// Apply a scoped process action and return its resulting snapshot.
+router.post('/processes/:name/action', requireHostControl, asyncHandler(async (req, res) => {
+ const { action, appId } = validateRequest(processActionSchema, req.body);
+ const name = req.params.name;
+ const command = validateCommand(`pm2 ${action} ${name}`);
+ if (!command.valid || !/^[a-zA-Z0-9_.-]+$/.test(name) || name.startsWith('-')) {
+ throw new ServerError('Process command not allowed', { status: 403, code: 'FORBIDDEN' });
+ }
+ const app = appId ? await (await import('../services/apps.js')).getAppById(appId) : null;
+ if (appId && !app) throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
+ const home = app?.pm2Home || null;
+ const before = await pm2Service.listProcessesStrict(home);
+ if (!before) throw new ServerError('PM2 status unavailable', { status: 503, code: 'PM2_UNAVAILABLE' });
+ if (!before.some(proc => proc.name === name)) throw new ServerError('Process not found', { status: 404, code: 'NOT_FOUND' });
+ // Restart also starts an existing stopped process without inventing a script.
+ if (action === 'stop') await pm2Service.stopApp(name, home);
+ else await pm2Service.restartApp(name, home);
+ pm2Service.clearJlistCache(home);
+ res.json({ processes: await pm2Service.listProcessesStrict(home) });
+}));
+
// GET /api/commands/processes/:name/monit - Get PM2 monit data for a process
router.get('/processes/:name/monit', asyncHandler(async (req, res) => {
const processes = await pm2Service.listProcesses();
diff --git a/server/routes/commands.test.js b/server/routes/commands.test.js
index 382ae26b82..e27517c103 100644
--- a/server/routes/commands.test.js
+++ b/server/routes/commands.test.js
@@ -7,6 +7,10 @@ import { errorEvents, errorMiddleware } from '../lib/errorHandler.js';
import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
import { ALLOWED_COMMANDS } from '../lib/commandSecurity.js';
+vi.mock('../services/apps.js', () => ({ getAppById: vi.fn() }));
+import { getAppById } from '../services/apps.js';
+import * as pm2Service from '../services/pm2.js';
+
const spawnMock = vi.hoisted(() => vi.fn());
vi.mock('../lib/childProcess.js', async (importOriginal) => ({
@@ -20,6 +24,10 @@ vi.mock('../services/history.js', () => ({
vi.mock('../services/pm2.js', () => ({
listProcesses: vi.fn().mockResolvedValue([]),
+ listProcessesStrict: vi.fn().mockResolvedValue([]),
+ stopApp: vi.fn().mockResolvedValue({ success: true }),
+ restartApp: vi.fn().mockResolvedValue({ success: true }),
+ clearJlistCache: vi.fn(),
}));
vi.mock('../lib/workspaceRoots.js', () => ({
@@ -118,6 +126,29 @@ describe('commands routes', () => {
vi.restoreAllMocks();
});
+ it('reads the selected PM2 home, preserves unavailable status, and applies scoped actions', async () => {
+ getAppById.mockResolvedValue({ id: 'app-a', pm2Home: '/example/pm2' });
+ pm2Service.listProcessesStrict.mockResolvedValue([{ name: 'example-api', status: 'online' }]);
+ const { app } = createApp(undefined, { remoteAddress: '127.0.0.1' });
+ const list = await request(app).get('/api/commands/processes?appId=app-a');
+ expect(list.status).toBe(200);
+ expect(pm2Service.listProcessesStrict).toHaveBeenLastCalledWith('/example/pm2');
+ const result = await request(app).post('/api/commands/processes/example-api/action').send({ action: 'stop', appId: 'app-a' });
+ expect(result.status).toBe(200);
+ expect(pm2Service.stopApp).toHaveBeenCalledWith('example-api', '/example/pm2');
+ expect(result.body.processes).toEqual(list.body);
+ pm2Service.listProcessesStrict.mockResolvedValue(null);
+ expect((await request(app).get('/api/commands/processes?appId=app-a')).status).toBe(503);
+ });
+
+ it('preserves host-control and command-policy gates on process actions', async () => {
+ const remote = createApp(undefined, { remoteAddress: '192.0.2.10' }).app;
+ expect((await request(remote).post('/api/commands/processes/example-api/action').send({ action: 'stop' })).status).toBe(403);
+ const local = createApp(undefined, { remoteAddress: '127.0.0.1' }).app;
+ expect((await request(local).post('/api/commands/processes/all/action').send({ action: 'stop' })).status).toBe(403);
+ expect(pm2Service.stopApp).not.toHaveBeenCalled();
+ });
+
describe('host-control authorization through the real auth gate', () => {
const basic = `Basic ${Buffer.from(':example-peer-password').toString('base64')}`;
diff --git a/server/services/socket.js b/server/services/socket.js
index fd6238e617..ff63f64508 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -34,6 +34,7 @@ import {
errorRecoverSchema
} from '../lib/socketValidation.js';
import { registerVoiceHandlers } from '../sockets/voice.js';
+import { registerProcessHandlers } from '../sockets/processes.js';
import { registerAppHandlers } from '../sockets/apps.js';
import { registerFableLoomHostedNamespace } from '../sockets/fableLoomHosted.js';
import { cleanupSocketStreams, registerLogHandlers } from '../sockets/logs.js';
@@ -195,6 +196,7 @@ const SOCKET_HANDLER_REGISTRARS = [
registerBuildHandlers,
registerImporterHandlers,
registerAppHandlers,
+ registerProcessHandlers,
registerLogHandlers,
registerSubscriptionHandlers,
registerErrorHandlers,
diff --git a/server/sockets/processes.js b/server/sockets/processes.js
new file mode 100644
index 0000000000..288b94e520
--- /dev/null
+++ b/server/sockets/processes.js
@@ -0,0 +1,61 @@
+import { getAllApps } from '../services/apps.js';
+import { listProcessesStrict } from '../services/pm2.js';
+
+// PM2's Node singleton targets one daemon; CLI reads also support per-app homes.
+// Share one sampling loop across all viewers, and send snapshots rather than
+// making every viewer shell out again after an invalidation.
+const subscribers = new Set();
+let run = null;
+
+async function sample(owner) {
+ const apps = await getAllApps({ includeArchived: false });
+ const homes = new Map([[null, []]]);
+ for (const app of apps) {
+ const home = app.pm2Home || null;
+ if (!homes.has(home)) homes.set(home, []);
+ homes.get(home).push(app.id);
+ }
+ for (const [home, appIds] of homes) {
+ if (run !== owner) return;
+ const processes = await listProcessesStrict(home);
+ if (run !== owner) return;
+ const frame = { appIds, defaultHome: home === null, processes };
+ // Uptime increases even on an idle daemon. CPU/memory are telemetry and
+ // arrive in the same push without another HTTP read from every viewer.
+ const signature = JSON.stringify({ ...frame, processes: processes?.map(({ uptime, ...proc }) => proc) ?? null });
+ if (owner.snapshots.get(home) === signature) continue;
+ owner.snapshots.set(home, signature);
+ for (const socket of subscribers) socket.emit('processes:changed', frame);
+ }
+ for (const home of owner.snapshots.keys()) {
+ if (!homes.has(home)) owner.snapshots.delete(home);
+ }
+}
+
+function start() {
+ if (run) return;
+ const owner = { timer: null, snapshots: new Map() };
+ run = owner;
+ const tick = () => sample(owner)
+ .catch(err => console.error(`❌ Process status watcher failed: ${err.message}`))
+ .finally(() => {
+ if (run === owner) owner.timer = setTimeout(tick, 1500);
+ });
+ void tick();
+}
+
+function release(socket) {
+ subscribers.delete(socket);
+ if (subscribers.size || !run) return;
+ clearTimeout(run.timer);
+ run = null;
+}
+
+export function registerProcessHandlers(socket) {
+ socket.on('processes:subscribe', () => {
+ subscribers.add(socket);
+ start();
+ });
+ socket.on('processes:unsubscribe', () => release(socket));
+ socket.on('disconnect', () => release(socket));
+}
diff --git a/server/sockets/processes.test.js b/server/sockets/processes.test.js
new file mode 100644
index 0000000000..56115ef052
--- /dev/null
+++ b/server/sockets/processes.test.js
@@ -0,0 +1,58 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+vi.mock('../services/apps.js', () => ({ getAllApps: vi.fn() }));
+vi.mock('../services/pm2.js', () => ({ listProcessesStrict: vi.fn() }));
+import { getAllApps } from '../services/apps.js';
+import { listProcessesStrict } from '../services/pm2.js';
+import { registerProcessHandlers } from './processes.js';
+const sockets = [];
+function connect() {
+ const socket = new EventEmitter();
+ socket.emit = vi.fn(socket.emit.bind(socket));
+ registerProcessHandlers(socket);
+ sockets.push(socket);
+ socket.emit('processes:subscribe');
+ return socket;
+}
+beforeEach(() => {
+ vi.useFakeTimers(); vi.clearAllMocks();
+ getAllApps.mockResolvedValue([{ id: 'app-a', pm2Home: '/example/pm2' }, { id: 'app-b', pm2Home: '/example/pm2' }]);
+ listProcessesStrict.mockResolvedValue([{ name: 'example-process', status: 'online', uptime: 100 }]);
+});
+afterEach(() => { for (const socket of sockets.splice(0)) socket.emit('disconnect'); vi.useRealTimers(); });
+it('shares probes by home, pushes changes and failures, and releases the last subscriber', async () => {
+ const first = connect(); const second = connect();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(listProcessesStrict.mock.calls).toEqual([[null], ['/example/pm2']]);
+ expect(first.emit).toHaveBeenCalledWith('processes:changed', expect.objectContaining({ appIds: ['app-a', 'app-b'], defaultHome: false }));
+ first.emit.mockClear(); second.emit.mockClear();
+ listProcessesStrict.mockResolvedValue([{ name: 'example-process', status: 'online', uptime: 1600 }]);
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(first.emit).not.toHaveBeenCalled();
+ listProcessesStrict.mockResolvedValue([{ name: 'example-process', status: 'stopped' }]);
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(second.emit).toHaveBeenCalledWith('processes:changed', expect.objectContaining({ processes: [expect.objectContaining({ status: 'stopped' })] }));
+ listProcessesStrict.mockResolvedValue(null);
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(second.emit).toHaveBeenCalledWith('processes:changed', expect.objectContaining({ processes: null }));
+ listProcessesStrict.mockResolvedValue([]);
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(second.emit).toHaveBeenCalledWith('processes:changed', expect.objectContaining({ processes: [] }));
+ first.emit('processes:unsubscribe'); listProcessesStrict.mockClear();
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(listProcessesStrict).toHaveBeenCalledTimes(2);
+ second.emit('disconnect'); listProcessesStrict.mockClear();
+ await vi.advanceTimersByTimeAsync(15000);
+ expect(listProcessesStrict).not.toHaveBeenCalled();
+});
+it('drops an in-flight sample after the last viewer disconnects', async () => {
+ let finish;
+ listProcessesStrict.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));
+ const socket = connect();
+ await vi.advanceTimersByTimeAsync(0);
+ socket.emit('disconnect'); socket.emit.mockClear();
+ finish([]);
+ await vi.advanceTimersByTimeAsync(15000);
+ expect(socket.emit).not.toHaveBeenCalled();
+ expect(listProcessesStrict).toHaveBeenCalledTimes(1);
+});