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
fix: multiplex PM2 log streams (#3024)
[._.]/ Adam Eivy9258788fe44a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0a8a45e9f4..15bc36d38a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -42,6 +42,7 @@## Managed apps+- **[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.## Music studiodiff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex 68884c082a..a4d952a4d4 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -445,10 +445,7 @@ export default function AppDetailView() {{/* Tab Content */}<div className="flex-1 overflow-auto p-4 sm:p-6 space-y-4">- {/* Desktop launch output. Suppressed on the Processes tab: the server keeps- ONE log stream per socket, so two mounted tails would clobber each other- and the tab's own expanded-process view is the better surface there. */}- {launchProcess && effectiveTab !== 'processes' && (+ {launchProcess && (<DesktopLaunchProgressappId={appId}processName={launchProcess}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ef7909ad44..721802f1f0 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -44,7 +44,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useSpriteRecordCrud` | Rename/delete state machine for one sprite record: `view`/`rename`/`confirm` mode, name draft, busy/inline-error, silent PATCH/DELETE. | A surface that renames or deletes a sprite record (the Library catalog card, the detail header) — share this so both stay in lock-step. || `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. || `useImporterProgress` | Live analyze-phase stage checklist via the `importer:progress` socket (runId-filtered); exports `stageStatusIcon` for the status→icon lookup. | Importer analyze progress UI only. |-| `useProcessLogs` | Live PM2 log tail for one process over the shared socket: owns the `logs:subscribe`/`line`/`subscribed`/`error` lifecycle, per-`processName` frame filtering, and a 1000-line ring buffer. Pass `appId` so an app with its own PM2_HOME streams from the right home. Returns `{ logs, subscribed }`. | Any surface showing a PM2 process's live output (Processes tab, desktop-app launch progress). **One stream per socket** — never mount two at once. |+| `useProcessLogs` | Live PM2 log tail for one process over the shared socket: owns the `logs:subscribe`/`line`/`subscribed`/`error` lifecycle, per-`processName` frame filtering, and a 1000-line ring buffer. Pass `appId` so an app with its own PM2_HOME streams from the right home. Returns `{ logs, subscribed }`. | Any surface showing a PM2 process's live output (Processes tab, desktop-app launch progress). || `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. || `useSceneRenderLifecycle` | One Music Video board lane's async-render lifecycle: owns the per-scene spinner state (`genScenes`), job-id→scene correlation, orphan-terminal reconcile, and the durable-attach + `*-gen:completed/failed/canceled` socket subscription (with running-cancel toast disambiguation). Returns `{ genScenes, startScene, clearScene, trackJob }`. | A board lane that kicks media-job renders per scene and clears spinners from terminal events (reference frame, i2v clip). One call per lane. || `useSlotInFlight` | Whether a render slot (`{ jobId, filename }`) has an in-flight render; returns `{ inFlight, setStatus }`. A present `filename` (or 5s grace on a stale/expired job) clears `inFlight` so the render button never sticks "loading". | A render button that should disable + spin only while its own slot is actually rendering (comic pages, covers). Wire `setStatus` to the slot's `MediaJobThumb` `onStatus`. |diff --git a/client/src/hooks/useProcessLogs.js b/client/src/hooks/useProcessLogs.jsindex f6080e782c..fe7fb3a71f 100644--- a/client/src/hooks/useProcessLogs.js+++ b/client/src/hooks/useProcessLogs.js@@ -20,11 +20,6 @@ const FLUSH_MS = 250;* line, and a stale frame from a just-unsubscribed process would otherwise be* appended to the new one's buffer.*- * **One stream per socket.** The server calls `cleanupStream(socket.id)` on- * every subscribe, so two mounted callers fight over the single slot and the- * later mount wins. Only ever have one of these active at a time (the app detail- * view's tabs are mutually exclusive, which is what makes that safe).- ** @param {string|null} processName PM2 process to tail; falsy = unsubscribed/idle.* @param {object} [options]* @param {number} [options.lines=500] Tail depth requested on subscribe.diff --git a/server/lib/socketValidation.js b/server/lib/socketValidation.jsindex a1f055597e..709a4aa19f 100644--- a/server/lib/socketValidation.js+++ b/server/lib/socketValidation.js@@ -29,6 +29,13 @@ export const logsSubscribeSchema = z.object({appId: z.string().min(1).optional()});+// logs:unsubscribe — scoped cleanup for one live PM2 stream. The empty legacy+// payload remains valid so an older client can retain the former "unsubscribe+// everything" behavior while newer clients release only their own process.+export const logsUnsubscribeSchema = z.object({+ processName: z.string().min(1, 'processName is required').optional()+}).default({});+// error:recover — error code and contextexport const errorRecoverSchema = z.object({code: z.string().min(1, 'error code is required'),diff --git a/server/lib/socketValidation.test.js b/server/lib/socketValidation.test.jsindex 3387a99233..80677bc825 100644--- a/server/lib/socketValidation.test.js+++ b/server/lib/socketValidation.test.js@@ -3,6 +3,7 @@ import {detectStartSchema,standardizeStartSchema,logsSubscribeSchema,+ logsUnsubscribeSchema,errorRecoverSchema,shellInputSchema,shellResizeSchema,@@ -86,6 +87,23 @@ describe('socketValidation schemas', () => {});});+ describe('logsUnsubscribeSchema', () => {+ it('accepts a named stream for scoped cleanup', () => {+ expect(logsUnsubscribeSchema.safeParse({ processName: 'game' })).toMatchObject({+ success: true,+ data: { processName: 'game' }+ });+ });++ it('defaults an omitted legacy payload to an all-stream cleanup', () => {+ expect(logsUnsubscribeSchema.safeParse()).toMatchObject({ success: true, data: {} });+ });++ it('rejects an empty process name rather than silently sweeping streams', () => {+ expect(logsUnsubscribeSchema.safeParse({ processName: '' }).success).toBe(false);+ });+ });+describe('errorRecoverSchema', () => {it('accepts a code with default empty context', () => {const result = errorRecoverSchema.safeParse({ code: 'E_FOO' });diff --git a/server/services/socket.js b/server/services/socket.jsindex 6eac8ea5ce..f41fbfba73 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -35,6 +35,7 @@ import {detectStartSchema,standardizeStartSchema,logsSubscribeSchema,+ logsUnsubscribeSchema,errorRecoverSchema,shellInputSchema,shellResizeSchema,@@ -51,22 +52,23 @@ import { registerVoiceHandlers } from '../sockets/voice.js';import { getBuildId } from '../lib/buildId.js';import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.js';-// Store active log streams per socket+// Store active log streams per socket/process pair.const activeStreams = new Map();-// Monotonic per-socket subscribe generation. `logs:subscribe` awaits an app+const streamKey = (socketId, processName) => `${socketId}:${processName}`;+// Monotonic per-stream 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+// obsolete by the time it resolves. Stream 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+// subscribes for the same process 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);+const bumpStreamGeneration = (key) => {+ const next = (streamGenerations.get(key) || 0) + 1;+ streamGenerations.set(key, next);return next;};// Store CoS subscribers@@ -226,11 +228,12 @@ export function initSocket(io) {const data = validateSocketData(logsSubscribeSchema, rawData, socket, 'logs:subscribe');if (!data) return;const { processName, lines, appId } = data;+ const key = streamKey(socket.id, processName);- // Clean up any existing stream for this socket, then claim this request.+ // Clean up only this process's existing stream, then claim this request.// Claiming AFTER the cleanup bump is what makes this generation current.- cleanupStream(socket.id);- const generation = bumpStreamGeneration(socket.id);+ 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@@ -252,7 +255,7 @@ export function initSocket(io) {// 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;+ if (streamGenerations.get(key) !== generation) return;console.log(`📜 Log stream started: ${processName} (${lines} lines)`);@@ -264,7 +267,7 @@ export function initSocket(io) {{ env: buildEnv(pm2Home) });- activeStreams.set(socket.id, { process: logProcess, processName });+ activeStreams.set(key, { process: logProcess, processName });let buffer = '';@@ -310,18 +313,22 @@ export function initSocket(io) {// `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;+ if (activeStreams.get(key)?.process !== logProcess) return;socket.emit('logs:close', { code, processName });- activeStreams.delete(socket.id);+ activeStreams.delete(key);+ streamGenerations.delete(key);});socket.emit('logs:subscribed', { processName, timestamp: Date.now() });});// Handle unsubscribe- socket.on('logs:unsubscribe', () => {- cleanupStream(socket.id);- socket.emit('logs:unsubscribed');+ socket.on('logs:unsubscribe', (rawData) => {+ const data = validateSocketData(logsUnsubscribeSchema, rawData, socket, 'logs:unsubscribe');+ if (!data) return;+ if (data.processName) cleanupStream(streamKey(socket.id, data.processName));+ else cleanupSocketStreams(socket.id);+ socket.emit('logs:unsubscribed', { processName: data.processName });});// CoS subscriptions@@ -571,10 +578,7 @@ export function initSocket(io) {// Cleanup on disconnect — detach sessions, don't kill themsocket.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);+ cleanupSocketStreams(socket.id);for (const set of ALL_SUBSCRIBER_SETS) set.delete(socket);const detached = shellService.detachSocketSessions(socket);if (detached > 0) {@@ -720,15 +724,29 @@ function setupProactiveSpeechForwarding() {wireProactiveTriggers({ io: ioInstance });}-function cleanupStream(socketId) {+function cleanupStream(key) {// 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);+ bumpStreamGeneration(key);+ const stream = activeStreams.get(key);if (stream) {stream.process.kill('SIGTERM');- activeStreams.delete(socketId);+ activeStreams.delete(key);+ }+}++function cleanupSocketStreams(socketId) {+ const prefix = `${socketId}:`;+ for (const [key, stream] of activeStreams) {+ if (!key.startsWith(prefix)) continue;+ stream.process.kill('SIGTERM');+ activeStreams.delete(key);+ }+ // Dropping a pending stream's generation invalidates an in-flight lookup+ // without needing a synthetic process entry to represent it.+ for (const key of streamGenerations.keys()) {+ if (key.startsWith(prefix)) streamGenerations.delete(key);}}diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex e0e3f37f8d..28169073c6 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -9,7 +9,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';*/vi.mock('./pm2.js', () => ({- spawnPm2: vi.fn(() => ({ stdout: { on: vi.fn() }, stderr: { on: vi.fn() }, on: vi.fn() })),+ spawnPm2: vi.fn(() => ({ stdout: { on: vi.fn() }, stderr: { on: vi.fn() }, on: vi.fn(), kill: vi.fn() })),buildEnv: vi.fn((pm2Home) => ({ PATH: '/usr/bin', ...(pm2Home ? { PM2_HOME: pm2Home } : {}) }))}));vi.mock('./streamingDetect.js', () => ({ streamDetection: vi.fn() }));@@ -48,6 +48,7 @@ vi.mock('../lib/socketValidation.js', () => ({detectStartSchema: {},standardizeStartSchema: {},logsSubscribeSchema: {},+ logsUnsubscribeSchema: {},errorRecoverSchema: {},shellInputSchema: {},shellResizeSchema: {},@@ -478,7 +479,7 @@ describe('socket.js — initSocket', () => {const socket = makeSocket('logs-unsub-midlookup');io.connect(socket);vi.mocked(getAppById).mockImplementation(async () => {- socket.handlers['logs:unsubscribe']();+ socket.handlers['logs:unsubscribe']({ processName: 'game' });return { id: 'app-1', pm2Home: '/opt/example/.pm2' };});@@ -487,7 +488,7 @@ describe('socket.js — initSocket', () => {expect(vi.mocked(spawnPm2)).not.toHaveBeenCalled();});- it('lets the NEWER of two overlapping subscribes win', async () => {+ it('lets the NEWER of two overlapping subscribes for the same process 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@@ -499,18 +500,69 @@ describe('socket.js — initSocket', () => {() => 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' });+ const first = socket.handlers['logs:subscribe']({ processName: 'game', lines: 100, appId: 'app-1' });+ const second = socket.handlers['logs:subscribe']({ processName: 'game', 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']);+ expect(vi.mocked(spawnPm2).mock.calls[0][0]).toEqual(['logs', 'game', '--raw', '--lines', '100']);const subscribed = socket.emitted.filter(([ev]) => ev === 'logs:subscribed');expect(subscribed).toHaveLength(1);- expect(subscribed[0][1].processName).toBe('new');+ expect(subscribed[0][1].processName).toBe('game');+ });++ it('keeps different process streams active and unsubscribes only the named process', async () => {+ const socket = makeSocket('logs-multiplexed');+ io.connect(socket);++ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 100 });+ await socket.handlers['logs:subscribe']({ processName: 'portos-server', lines: 100 });++ const gameStream = vi.mocked(spawnPm2).mock.results[0].value;+ const serverStream = vi.mocked(spawnPm2).mock.results[1].value;+ expect(vi.mocked(spawnPm2)).toHaveBeenCalledTimes(2);+ expect(gameStream.kill).not.toHaveBeenCalled();++ socket.handlers['logs:unsubscribe']({ processName: 'game' });++ expect(gameStream.kill).toHaveBeenCalledWith('SIGTERM');+ expect(serverStream.kill).not.toHaveBeenCalled();+ expect(socket.emitted).toContainEqual(['logs:unsubscribed', { processName: 'game' }]);+ });++ it('keeps a replacement registered when its predecessor closes asynchronously', async () => {+ const socket = makeSocket('logs-stale-close');+ io.connect(socket);++ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 100 });+ const predecessor = vi.mocked(spawnPm2).mock.results[0].value;+ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 100 });+ const replacement = vi.mocked(spawnPm2).mock.results[1].value;+ const onClose = predecessor.on.mock.calls.find(([event]) => event === 'close')[1];++ onClose(0);+ socket.handlers['logs:unsubscribe']({ processName: 'game' });++ expect(predecessor.kill).toHaveBeenCalledWith('SIGTERM');+ expect(replacement.kill).toHaveBeenCalledWith('SIGTERM');+ });++ it('reaps every process stream when its socket disconnects', async () => {+ const socket = makeSocket('logs-disconnect-sweep');+ io.connect(socket);++ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 100 });+ await socket.handlers['logs:subscribe']({ processName: 'portos-server', lines: 100 });+ const gameStream = vi.mocked(spawnPm2).mock.results[0].value;+ const serverStream = vi.mocked(spawnPm2).mock.results[1].value;++ socket.handlers.disconnect();++ expect(gameStream.kill).toHaveBeenCalledWith('SIGTERM');+ expect(serverStream.kill).toHaveBeenCalledWith('SIGTERM');});});});