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

fix: route managed app logs through custom PM2 homes (#3025)

[._.]/ Adam Eivy273bfe61aeb0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e924493e28..216255aac0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -46,6 +46,7 @@
## Managed apps
+- **[issue-3025] Managed-app logs now follow the PM2 instance that actually owns them** — an app configured with its own PM2 home no longer shows an empty log in the Apps detail page or its HTTP log views. The selected app carries its identity into the Processes tab, and older process-only log requests still find a registered app's custom home automatically; ordinary default-home apps behave exactly as before.
- **[issue-3024] Live app logs can now appear in both the Processes tab and launch panel** — a managed desktop app no longer hides its launch-progress panel when you open **Processes**. Each panel now owns its named PM2 log stream, so closing one leaves the other tailing normally; replacing or closing a stream also cannot orphan a background `pm2 logs` process.
- **[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. An app that runs in its own PM2 instance streams its build output into that panel correctly, rather than showing it empty.
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsx
index a4d952a4d4..36dbd6b3d3 100644
--- a/client/src/components/apps/AppDetailView.jsx
+++ b/client/src/components/apps/AppDetailView.jsx
@@ -213,7 +213,7 @@ export default function AppDetailView() {
case 'gsd':
return <GsdTab appId={appId} repoPath={app.repoPath} />;
case 'processes':
- return <ProcessesTab pm2ProcessNames={app.pm2ProcessNames} />;
+ return <ProcessesTab appId={app.id} pm2ProcessNames={app.pm2ProcessNames} />;
case 'references':
return <ReferencesTab appId={appId} appName={app.name} />;
case 'update':
diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsx
index 144e2ff21a..ef1340a237 100644
--- a/client/src/components/apps/tabs/ProcessesTab.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.jsx
@@ -18,7 +18,7 @@ const getStatusClasses = (status) => {
}
};
-export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
+export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
const [expandedProcess, setExpandedProcess] = useState(null);
const [restarting, setRestarting] = useState({});
const [tailLines, setTailLines] = useState(500);
@@ -28,7 +28,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
// Socket log lifecycle lives in the shared hook so this tab and the desktop
// launch-progress panel can't drift.
- const { logs, subscribed, clear: clearLogs } = useProcessLogs(expandedProcess, { lines: tailLines });
+ 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
diff --git a/client/src/components/apps/tabs/ProcessesTab.test.jsx b/client/src/components/apps/tabs/ProcessesTab.test.jsx
new file mode 100644
index 0000000000..e6d1ce7365
--- /dev/null
+++ b/client/src/components/apps/tabs/ProcessesTab.test.jsx
@@ -0,0 +1,41 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
+
+vi.mock('../../../services/api', () => ({
+ executeCommand: vi.fn(),
+ getProcessesList: vi.fn(),
+}));
+
+vi.mock('../../../hooks/useAutoRefetch', () => ({
+ useAutoRefetch: () => ({
+ data: [{ name: 'example-api', status: 'online', pid: 1, cpu: 0, memory: 0, uptime: null, restarts: 0, pm_id: 1 }],
+ loading: false,
+ refetch: vi.fn(),
+ }),
+}));
+
+vi.mock('../../../hooks/useProcessLogs', () => ({
+ useProcessLogs: vi.fn(() => ({ logs: [], subscribed: false, clear: vi.fn() })),
+}));
+
+vi.mock('../../BrailleSpinner', () => ({ default: () => null }));
+vi.mock('../../ui/FormField', () => ({ FormField: ({ children }) => children }));
+vi.mock('../../ui/ProcessLogLines', () => ({ default: () => null }));
+vi.mock('../../../utils/formatters', () => ({ formatBytes: vi.fn(() => '0 B'), formatDurationMs: vi.fn() }));
+
+import { useProcessLogs } from '../../../hooks/useProcessLogs';
+import ProcessesTab from './ProcessesTab';
+
+describe('ProcessesTab', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('passes its app id to the expanded process log subscription', () => {
+ render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Expand details for example-api' }));
+
+ expect(useProcessLogs).toHaveBeenLastCalledWith('example-api', { lines: 500, appId: 'app-1' });
+ });
+});
diff --git a/server/routes/logs.js b/server/routes/logs.js
index 3c20969208..60041c07fd 100644
--- a/server/routes/logs.js
+++ b/server/routes/logs.js
@@ -48,6 +48,8 @@ router.get('/:processName', asyncHandler(async (req, res) => {
return res.json({ processName: safeProcessName, lines, logs });
}
+ const pm2Home = await appsService.resolvePm2HomeForProcess(safeProcessName);
+
// SSE streaming — shared header boilerplate via openSseStream; this route
// emits named `event:` frames directly so it uses safeEnd but not send.
const { safeEnd } = openSseStream(res);
@@ -57,7 +59,10 @@ router.get('/:processName', asyncHandler(async (req, res) => {
// Spawn pm2 logs with --raw flag for clean output
// Security: safeProcessName is validated above to only contain safe characters
- const logProcess = spawnPm2(['logs', safeProcessName, '--raw', '--lines', String(lines)]);
+ const logProcess = spawnPm2(
+ ['logs', safeProcessName, '--raw', '--lines', String(lines)],
+ { env: pm2Service.buildEnv(pm2Home) }
+ );
let buffer = '';
@@ -115,7 +120,7 @@ router.get('/app/:appId', asyncHandler(async (req, res) => {
const results = {};
for (const processName of app.pm2ProcessNames || []) {
- results[processName] = await pm2Service.getLogs(processName, lines)
+ results[processName] = await pm2Service.getLogs(processName, lines, app.pm2Home)
.catch(err => `Error: ${err.message}`);
}
diff --git a/server/routes/logs.test.js b/server/routes/logs.test.js
new file mode 100644
index 0000000000..6ea9ee85fe
--- /dev/null
+++ b/server/routes/logs.test.js
@@ -0,0 +1,100 @@
+import { EventEmitter } from 'events';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../../lib/testHelper.js';
+
+const makeLogProcess = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ return child;
+};
+
+vi.mock('../services/apps.js', () => ({
+ getAppById: vi.fn(),
+ resolvePm2HomeForProcess: vi.fn(),
+}));
+
+vi.mock('../services/pm2.js', () => ({
+ buildEnv: vi.fn((pm2Home) => ({ ...(pm2Home ? { PM2_HOME: pm2Home } : {}) })),
+ getLogs: vi.fn(),
+ spawnPm2: vi.fn(),
+}));
+
+import * as appsService from '../services/apps.js';
+import * as pm2Service from '../services/pm2.js';
+import logsRoutes from './logs.js';
+
+const createApp = () => {
+ const app = express();
+ app.use('/api/logs', logsRoutes);
+ return app;
+};
+
+describe('log routes PM2_HOME resolution', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ pm2Service.getLogs.mockResolvedValue('line');
+ pm2Service.spawnPm2.mockImplementation(() => {
+ const child = makeLogProcess();
+ queueMicrotask(() => child.emit('close', 0));
+ return child;
+ });
+ });
+
+ it('uses the app custom home for every process in the app log response', async () => {
+ appsService.getAppById.mockResolvedValue({
+ id: 'app-1',
+ name: 'Example App',
+ pm2Home: '/tmp/example-pm2',
+ pm2ProcessNames: ['example-api', 'example-ui'],
+ });
+
+ const response = await request(createApp()).get('/api/logs/app/app-1?lines=250');
+
+ expect(response.status).toBe(200);
+ expect(pm2Service.getLogs).toHaveBeenNthCalledWith(1, 'example-api', 250, '/tmp/example-pm2');
+ expect(pm2Service.getLogs).toHaveBeenNthCalledWith(2, 'example-ui', 250, '/tmp/example-pm2');
+ });
+
+ it('keeps app log responses on the default home when no custom home is configured', async () => {
+ appsService.getAppById.mockResolvedValue({
+ id: 'app-1',
+ name: 'Example App',
+ pm2ProcessNames: ['example-api'],
+ });
+
+ const response = await request(createApp()).get('/api/logs/app/app-1');
+
+ expect(response.status).toBe(200);
+ expect(pm2Service.getLogs).toHaveBeenCalledWith('example-api', 100, undefined);
+ });
+
+ it('follows a process from its resolved custom PM2 home', async () => {
+ appsService.resolvePm2HomeForProcess.mockResolvedValue('/tmp/example-pm2');
+
+ const response = await request(createApp()).get('/api/logs/example-api?follow=true');
+
+ expect(response.status).toBe(200);
+ expect(appsService.resolvePm2HomeForProcess).toHaveBeenCalledWith('example-api');
+ expect(pm2Service.buildEnv).toHaveBeenCalledWith('/tmp/example-pm2');
+ expect(pm2Service.spawnPm2).toHaveBeenCalledWith(
+ ['logs', 'example-api', '--raw', '--lines', '100'],
+ { env: { PM2_HOME: '/tmp/example-pm2' } }
+ );
+ });
+
+ it('follows a process from the default PM2 home when no custom home resolves', async () => {
+ appsService.resolvePm2HomeForProcess.mockResolvedValue(null);
+
+ const response = await request(createApp()).get('/api/logs/example-api?follow=true&lines=25');
+
+ expect(response.status).toBe(200);
+ expect(pm2Service.buildEnv).toHaveBeenCalledWith(null);
+ expect(pm2Service.spawnPm2).toHaveBeenCalledWith(
+ ['logs', 'example-api', '--raw', '--lines', '25'],
+ { env: {} }
+ );
+ });
+});
diff --git a/server/services/apps.js b/server/services/apps.js
index c64f160878..abd19dedee 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -202,6 +202,22 @@ export async function getDesktopProcessNames() {
return names;
}
+/**
+ * Resolve the custom PM2 home for a registered process name.
+ *
+ * Process-name-only log consumers use this as a backward-compatible fallback
+ * when they do not already have an app id. An app id remains the preferred
+ * disambiguator because process names may be reused across PM2 homes.
+ *
+ * @param {string} processName PM2 process name to look up
+ * @returns {Promise<string|null>} The owning app's custom PM2_HOME, if any
+ */
+export async function resolvePm2HomeForProcess(processName) {
+ const apps = await getAllApps();
+ const app = apps.find(candidate => candidate.pm2ProcessNames?.includes(processName));
+ return app?.pm2Home || null;
+}
+
/**
* Stamp `expectedExit` onto each PM2 process so supervisors can branch on the
* concept rather than each re-deriving it from a name set.
diff --git a/server/services/apps.test.js b/server/services/apps.test.js
index e27bde6dc8..a10315eb68 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 { annotateExpectedExit, createApp, getAppStatuses, getAppStatusSummary, getDesktopProcessNames, getReservedPorts, invalidateCache, PORTOS_APP_ID, updateAppTaskTypeOverride } from './apps.js';
+import { annotateExpectedExit, createApp, getAppStatuses, getAppStatusSummary, getDesktopProcessNames, getReservedPorts, invalidateCache, PORTOS_APP_ID, resolvePm2HomeForProcess, updateAppTaskTypeOverride } from './apps.js';
describe('pr-watcher cooldown reset', () => {
beforeEach(() => {
@@ -368,6 +368,35 @@ describe('portless / desktop apps (#2991)', () => {
});
});
+describe('resolvePm2HomeForProcess', () => {
+ beforeEach(() => {
+ invalidateCache();
+ vi.clearAllMocks();
+ });
+
+ it('returns the owning app custom home for a registered process', async () => {
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },
+ 'custom-home': { name: 'Example App', pm2Home: '/tmp/example-pm2', pm2ProcessNames: ['example-api'] },
+ },
+ });
+
+ await expect(resolvePm2HomeForProcess('example-api')).resolves.toBe('/tmp/example-pm2');
+ });
+
+ it('returns null when the matching app uses the default PM2 home', async () => {
+ readJSONFile.mockResolvedValue({
+ apps: {
+ [PORTOS_APP_ID]: { name: 'PortOS', type: 'express', pm2ProcessNames: ['portos-server'] },
+ 'default-home': { name: 'Example App', pm2ProcessNames: ['example-api'] },
+ },
+ });
+
+ await expect(resolvePm2HomeForProcess('example-api')).resolves.toBeNull();
+ });
+});
+
describe('getAppStatusSummary', () => {
beforeEach(() => {
invalidateCache();
diff --git a/server/services/socket.js b/server/services/socket.js
index f41fbfba73..c26c328fd3 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,7 +1,7 @@
import { spawnPm2, buildEnv } from './pm2.js';
import { streamDetection } from './streamingDetect.js';
import { cosEvents } from './cosEvents.js';
-import { appsEvents, getAppById } from './apps.js';
+import { appsEvents, getAppById, resolvePm2HomeForProcess } from './apps.js';
import { errorEvents, sanitizeContext } from '../lib/errorHandler.js';
import { handleErrorRecovery } from './autoFixer.js';
import * as pm2Standardizer from './pm2Standardizer.js';
@@ -235,9 +235,11 @@ export function initSocket(io) {
cleanupStream(key);
const generation = bumpStreamGeneration(key);
- // 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
- // a lookup failure must not throw — fall back to the default home.
+ // Resolve the app's custom PM2_HOME so the stream tails the home its
+ // processes actually run in. appId remains the disambiguating fast path;
+ // legacy callers without it fall back to the process-name registry lookup.
+ // This runs outside the Express lifecycle, so a lookup failure must not
+ // throw — fall back to the default home.
let pm2Home = null;
if (appId) {
pm2Home = await getAppById(appId)
@@ -246,6 +248,12 @@ export function initSocket(io) {
console.error(`❌ logs:subscribe could not resolve app ${appId}: ${err.message}`);
return null;
});
+ } else {
+ pm2Home = await resolvePm2HomeForProcess(processName)
+ .catch(err => {
+ console.error(`❌ logs:subscribe could not resolve ${processName}: ${err.message}`);
+ return null;
+ });
}
// The await above yields, so a disconnect, an unsubscribe, or a newer
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 28169073c6..5cf7e63712 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -14,7 +14,7 @@ vi.mock('./pm2.js', () => ({
}));
vi.mock('./streamingDetect.js', () => ({ streamDetection: vi.fn() }));
vi.mock('./cosEvents.js', () => ({ cosEvents: { on: vi.fn() }, emitLog: vi.fn() }));
-vi.mock('./apps.js', () => ({ appsEvents: { on: vi.fn() }, getAppById: vi.fn(), updateApp: vi.fn() }));
+vi.mock('./apps.js', () => ({ appsEvents: { on: vi.fn() }, getAppById: vi.fn(), resolvePm2HomeForProcess: vi.fn(), updateApp: vi.fn() }));
vi.mock('../lib/errorHandler.js', () => ({ errorEvents: { on: vi.fn() } }));
vi.mock('./autoFixer.js', () => ({ handleErrorRecovery: vi.fn() }));
vi.mock('./pm2Standardizer.js', () => ({ analyzeApp: vi.fn(), createGitBackup: vi.fn(), applyStandardization: vi.fn(), runStandardizeFlow: vi.fn() }));
@@ -64,7 +64,7 @@ vi.mock('../sockets/voice.js', () => ({ registerVoiceHandlers: vi.fn() }));
import { initSocket } from './socket.js';
import { spawnPm2 } from './pm2.js';
-import { getAppById } from './apps.js';
+import { getAppById, resolvePm2HomeForProcess } from './apps.js';
import { cosEvents } from './cosEvents.js';
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { audioGenEvents } from './audioGen/events.js';
@@ -405,20 +405,37 @@ describe('socket.js — initSocket', () => {
beforeEach(() => {
vi.mocked(spawnPm2).mockClear();
vi.mocked(getAppById).mockReset();
+ vi.mocked(resolvePm2HomeForProcess).mockReset();
+ vi.mocked(resolvePm2HomeForProcess).mockResolvedValue(null);
});
- it('streams from the default home when no appId is supplied', async () => {
+ it('streams from the default home when the process resolver finds no custom home', async () => {
const socket = makeSocket('logs-default');
io.connect(socket);
+ vi.mocked(resolvePm2HomeForProcess).mockResolvedValue(null);
await socket.handlers['logs:subscribe']({ processName: 'portos-server', lines: 100 });
expect(getAppById).not.toHaveBeenCalled();
+ expect(resolvePm2HomeForProcess).toHaveBeenCalledWith('portos-server');
// buildEnv(null) is the default-home env — no PM2_HOME override.
const [, opts] = vi.mocked(spawnPm2).mock.calls[0];
expect(opts.env.PM2_HOME).toBeUndefined();
});
+ it('uses the process resolver for a custom home when no appId is supplied', async () => {
+ const socket = makeSocket('logs-resolved-home');
+ io.connect(socket);
+ vi.mocked(resolvePm2HomeForProcess).mockResolvedValue('/tmp/example-pm2');
+
+ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 200 });
+
+ expect(getAppById).not.toHaveBeenCalled();
+ expect(resolvePm2HomeForProcess).toHaveBeenCalledWith('game');
+ const [, opts] = vi.mocked(spawnPm2).mock.calls[0];
+ expect(opts.env.PM2_HOME).toBe('/tmp/example-pm2');
+ });
+
it("streams from the app's custom PM2_HOME when it has one", async () => {
const socket = makeSocket('logs-custom-home');
io.connect(socket);
@@ -427,6 +444,7 @@ describe('socket.js — initSocket', () => {
await socket.handlers['logs:subscribe']({ processName: 'game', lines: 200, appId: 'app-1' });
expect(getAppById).toHaveBeenCalledWith('app-1');
+ expect(resolvePm2HomeForProcess).not.toHaveBeenCalled();
const [args, opts] = vi.mocked(spawnPm2).mock.calls[0];
expect(args).toEqual(['logs', 'game', '--raw', '--lines', '200']);
expect(opts.env.PM2_HOME).toBe('/opt/example/.pm2');