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

feat([issue-2991]): show live build output while a desktop app launches

[._.]/ Adam Eivy6e897f454cbf
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsx
index 44ebc37208..6d94b9dcfc 100644
--- a/client/src/components/apps/AppDetailView.jsx
+++ b/client/src/components/apps/AppDetailView.jsx
@@ -9,7 +9,8 @@ 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 } from './constants';
+import { APP_DETAIL_TABS, NON_PM2_TYPES, getAppTypeLabel, isDesktopType } from './constants';
+import DesktopLaunchProgress from './DesktopLaunchProgress';
import OverviewTab from './tabs/OverviewTab';
import TasksTab from './tabs/TasksTab';
import AutomationTab from './tabs/AutomationTab';
@@ -31,6 +32,8 @@ export default function AppDetailView() {
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
const [actionLoading, setActionLoading] = useState(null);
+ // PM2 process whose live output the desktop launch panel is tailing (null = hidden).
+ const [launchProcess, setLaunchProcess] = useState(null);
const [buildLoading, setBuildLoading] = useState(false);
const [editing, setEditing] = useState(false);
// Vite Dev-UI host guard: when an online app exposes a Vite dev server, check
@@ -84,13 +87,23 @@ export default function AppDetailView() {
const handleStart = async () => {
setActionLoading('start');
- await api.startApp(appId).catch(() => null);
+ 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);
+ }
setActionLoading(null);
};
const handleStop = async () => {
setActionLoading('stop');
await api.stopApp(appId).catch(() => null);
+ // The stream would keep tailing a dead process; drop the panel with the app.
+ setLaunchProcess(null);
setActionLoading(null);
};
@@ -433,7 +446,18 @@ export default function AppDetailView() {
</div>
{/* Tab Content */}
- <div className="flex-1 overflow-auto p-4 sm:p-6">
+ <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' && (
+ <DesktopLaunchProgress
+ appId={appId}
+ processName={launchProcess}
+ online={app.overallStatus === 'online'}
+ onDismiss={() => setLaunchProcess(null)}
+ />
+ )}
{renderTab()}
</div>
diff --git a/client/src/components/apps/DesktopLaunchProgress.jsx b/client/src/components/apps/DesktopLaunchProgress.jsx
new file mode 100644
index 0000000000..3e2818b80c
--- /dev/null
+++ b/client/src/components/apps/DesktopLaunchProgress.jsx
@@ -0,0 +1,79 @@
+import { useEffect, useRef } from 'react';
+import { X } from 'lucide-react';
+import BrailleSpinner from '../BrailleSpinner';
+import { useProcessLogs } from '../../hooks/useProcessLogs';
+
+/**
+ * Live build/launch output for a desktop (portless GUI) app.
+ *
+ * A web server binds its port in milliseconds; a desktop app's start command
+ * compiles the project and imports assets first, so the window can be tens of
+ * seconds away while PM2 already reports `online`. Without this the Start button
+ * settles instantly and the app reads as hung. Streaming the process log is the
+ * honest progress signal — there is no percentage to report, but visible output
+ * proves work is happening.
+ *
+ * Dismissible: the panel is informational, so closing it must not stop the
+ * launch. Unmounting only tears down the log subscription.
+ *
+ * @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 {() => 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);
+
+ useEffect(() => {
+ if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }, [logs]);
+
+ return (
+ <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 />}
+ <span className="text-sm text-white truncate">
+ {online ? 'Running' : 'Launching'} — {processName}
+ </span>
+ </div>
+ <button
+ onClick={onDismiss}
+ aria-label="Hide launch output"
+ className="text-gray-400 hover:text-white transition-colors shrink-0"
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ <p className="px-4 pt-2 text-xs text-gray-500">
+ {online
+ ? '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.'}
+ </p>
+
+ <div
+ ref={scrollRef}
+ className="m-4 mt-2 p-3 bg-port-bg border border-port-border rounded-lg font-mono text-xs h-48 overflow-y-auto"
+ >
+ {logs.length === 0 ? (
+ <span className="text-gray-500">
+ {subscribed ? 'Waiting for output…' : 'Connecting to log stream…'}
+ </span>
+ ) : (
+ logs.map((entry, i) => (
+ <div
+ key={`${entry.timestamp}-${i}`}
+ className={`whitespace-pre-wrap break-all ${entry.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}
+ >
+ {entry.line}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/apps/DesktopLaunchProgress.test.jsx b/client/src/components/apps/DesktopLaunchProgress.test.jsx
new file mode 100644
index 0000000000..54940c76ca
--- /dev/null
+++ b/client/src/components/apps/DesktopLaunchProgress.test.jsx
@@ -0,0 +1,102 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, cleanup, act, fireEvent } from '@testing-library/react';
+
+const handlers = new Map();
+const emitted = [];
+vi.mock('../../services/socket', () => ({
+ default: {
+ on: (event, fn) => { handlers.set(event, fn); },
+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },
+ emit: (event, ...args) => { emitted.push([event, ...args]); },
+ },
+}));
+
+import DesktopLaunchProgress from './DesktopLaunchProgress';
+import { DESKTOP_TYPES, isDesktopType } from './constants';
+
+const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });
+
+const renderPanel = (props = {}) => render(
+ <DesktopLaunchProgress
+ appId="app-1"
+ processName="game"
+ online={false}
+ onDismiss={() => {}}
+ {...props}
+ />
+);
+
+describe('DesktopLaunchProgress', () => {
+ beforeEach(() => { handlers.clear(); emitted.length = 0; });
+ afterEach(cleanup);
+
+ it('subscribes to the process log scoped to the app (custom PM2_HOME)', () => {
+ renderPanel();
+ expect(emitted).toContainEqual([
+ 'logs:subscribe', { processName: 'game', lines: 200, appId: 'app-1' },
+ ]);
+ });
+
+ it('reads as in-progress while the build runs, so a slow launch is not "hung"', () => {
+ renderPanel({ online: false });
+ expect(screen.getByText(/Launching — game/)).toBeInTheDocument();
+ expect(screen.getByText(/Building and importing assets/)).toBeInTheDocument();
+ });
+
+ it('streams build output as it arrives', () => {
+ renderPanel();
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'Importing assets…', type: 'stdout', timestamp: 1 });
+
+ expect(screen.getByText('Importing assets…')).toBeInTheDocument();
+ });
+
+ it('distinguishes not-yet-connected from connected-but-silent', () => {
+ renderPanel();
+ expect(screen.getByText(/Connecting to log stream/)).toBeInTheDocument();
+
+ fire('logs:subscribed', { processName: 'game' });
+ expect(screen.getByText(/Waiting for output/)).toBeInTheDocument();
+ });
+
+ it('flips to running once the process is up, and frames a quit as normal', () => {
+ renderPanel({ online: true });
+ expect(screen.getByText(/Running — game/)).toBeInTheDocument();
+ // A closed window is a clean exit for a desktop app, not a crash — the copy
+ // must not read as an error (issue #2991).
+ expect(screen.getByText(/normal exit, not a crash/)).toBeInTheDocument();
+ });
+
+ it('dismisses without stopping the app', () => {
+ const onDismiss = vi.fn();
+ renderPanel({ onDismiss });
+
+ fireEvent.click(screen.getByLabelText('Hide launch output'));
+
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ // Dismiss is presentation-only — it never emits a stop/kill.
+ expect(emitted.map(([e]) => e)).not.toContain('logs:kill');
+ });
+
+ it('unsubscribes when the panel unmounts', () => {
+ const { unmount } = renderPanel();
+ unmount();
+ expect(emitted).toContainEqual(['logs:unsubscribe', { processName: 'game' }]);
+ });
+});
+
+describe('desktop type mirror', () => {
+ // The client mirrors DESKTOP_TYPES from server/services/streamingDetect.js.
+ // A server-side addition that never reaches this set silently regresses the
+ // portless UI branches (Open UI hidden, launch panel) back to the web-app path.
+ it('matches the server set', async () => {
+ const server = await import('../../../../server/services/streamingDetect.js');
+ expect([...DESKTOP_TYPES].sort()).toEqual([...server.DESKTOP_TYPES].sort());
+ });
+
+ it('classifies desktop apps and not web apps', () => {
+ expect(isDesktopType('desktop')).toBe(true);
+ expect(isDesktopType('express')).toBe(false);
+ expect(isDesktopType(undefined)).toBe(false);
+ });
+});
diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.js
index 9c3ac3a18b..bbe595bf08 100644
--- a/client/src/components/apps/constants.js
+++ b/client/src/components/apps/constants.js
@@ -1,5 +1,14 @@
export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'swift']);
+// Mirrors DESKTOP_TYPES in server/services/streamingDetect.js — app types that run
+// a GUI/desktop process with no HTTP port (a game binary). Kept in sync by hand;
+// the server stays the source of truth for what the type MEANS (autorestart off,
+// command-launched), this mirror only drives client-side presentation.
+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);
+
export const getAppTypeLabel = (type) =>
type === 'ios-native' ? '📱 iOS' :
type === 'macos-native' ? '🖥️ macOS' :
diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsx
index 9dd55da799..5352aeb640 100644
--- a/client/src/components/apps/tabs/ProcessesTab.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.jsx
@@ -2,10 +2,10 @@ import { useState, useEffect, useRef, Fragment } from 'react';
import { Maximize2, X } from 'lucide-react';
import * as api from '../../../services/api';
import { executeCommand } from '../../../services/api';
-import socket from '../../../services/socket';
import BrailleSpinner from '../../BrailleSpinner';
import { FormField } from '../../ui/FormField';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { useProcessLogs } from '../../../hooks/useProcessLogs';
import { formatBytes, formatDurationMs } from '../../../utils/formatters';
const getStatusClasses = (status) => {
@@ -19,14 +19,16 @@ const getStatusClasses = (status) => {
export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
const [expandedProcess, setExpandedProcess] = useState(null);
- const [logs, setLogs] = useState([]);
const [restarting, setRestarting] = useState({});
const [tailLines, setTailLines] = useState(500);
- const [subscribed, setSubscribed] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const logsRef = useRef(null);
const fullscreenLogsRef = useRef(null);
+ // 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 });
+
// 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.
@@ -36,56 +38,13 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
);
const processes = data ?? [];
+ // Pin both log panes to the bottom as lines arrive. Driven off `logs` rather
+ // than the socket frame so it also fires on the initial tail replay.
useEffect(() => {
- if (!expandedProcess) {
- setLogs([]);
- setSubscribed(false);
- return;
+ for (const ref of [logsRef, fullscreenLogsRef]) {
+ if (ref.current) ref.current.scrollTop = ref.current.scrollHeight;
}
-
- socket.emit('logs:subscribe', { processName: expandedProcess, lines: tailLines });
-
- const handleLog = (data) => {
- if (data.processName === expandedProcess) {
- setLogs(prev => [...prev.slice(-1000), {
- line: data.line,
- type: data.type,
- timestamp: data.timestamp
- }]);
- setTimeout(() => {
- if (logsRef.current) {
- logsRef.current.scrollTop = logsRef.current.scrollHeight;
- }
- if (fullscreenLogsRef.current) {
- fullscreenLogsRef.current.scrollTop = fullscreenLogsRef.current.scrollHeight;
- }
- }, 10);
- }
- };
-
- const handleSubscribed = (data) => {
- if (data.processName === expandedProcess) {
- setSubscribed(true);
- }
- };
-
- const handleError = (data) => {
- if (data.processName === expandedProcess) {
- setLogs(prev => [...prev, { line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() }]);
- }
- };
-
- socket.on('logs:line', handleLog);
- socket.on('logs:subscribed', handleSubscribed);
- socket.on('logs:error', handleError);
-
- return () => {
- socket.emit('logs:unsubscribe', { processName: expandedProcess });
- socket.off('logs:line', handleLog);
- socket.off('logs:subscribed', handleSubscribed);
- socket.off('logs:error', handleError);
- };
- }, [expandedProcess, tailLines]);
+ }, [logs]);
const pm2Action = async (action, name) => {
setRestarting(prev => ({ ...prev, [name]: true }));
@@ -96,9 +55,10 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
}, 2000);
};
+ // No explicit clear here — useProcessLogs resets its buffer whenever
+ // processName changes, so the new process never shows the old one's tail.
const toggleExpand = (name) => {
setExpandedProcess(prev => prev === name ? null : name);
- setLogs([]);
};
const filteredProcesses = filterFn
@@ -217,7 +177,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
value={tailLines}
onChange={(e) => {
setTailLines(Number(e.target.value));
- setLogs([]);
+ clearLogs();
}}
className="px-2 py-1 text-xs bg-port-card border border-port-border rounded text-white"
>
@@ -230,7 +190,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
</FormField>
<span className="text-xs text-gray-600">{logs.length} lines</span>
<button
- onClick={() => setLogs([])}
+ onClick={() => clearLogs()}
className="text-xs text-gray-500 hover:text-white"
>
Clear
@@ -301,7 +261,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
value={tailLines}
onChange={(e) => {
setTailLines(Number(e.target.value));
- setLogs([]);
+ clearLogs();
}}
className="px-2 py-1 text-sm bg-port-bg border border-port-border rounded text-white"
>
@@ -314,7 +274,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
</FormField>
<span className="text-sm text-gray-600">{logs.length} lines</span>
<button
- onClick={() => setLogs([])}
+ onClick={() => clearLogs()}
className="text-sm text-gray-500 hover:text-white"
>
Clear
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index a98ec5b1b0..ef7909ad44 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -44,6 +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. |
| `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/index.js b/client/src/hooks/index.js
index 86b530ae52..0fb53878e4 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -85,6 +85,7 @@ export * from './useArcCanvasSync.js';
export * from './useImageGenProgress.js';
export * from './useImporterProgress.js';
export * from './useInstallStream.js';
+export * from './useProcessLogs.js';
export * from './useOpenClawStream.js';
export * from './usePipelineProgress.js';
export * from './useReaderPanel.js';
diff --git a/client/src/hooks/useProcessLogs.js b/client/src/hooks/useProcessLogs.js
new file mode 100644
index 0000000000..23d6ab3bdd
--- /dev/null
+++ b/client/src/hooks/useProcessLogs.js
@@ -0,0 +1,85 @@
+import { useState, useEffect, useCallback } from 'react';
+import socket from '../services/socket';
+
+// Ring-buffer cap. `pm2 logs` replays the tail on subscribe and then streams
+// live, so an unbounded array grows without limit on a chatty process.
+const MAX_LINES = 1000;
+
+/**
+ * Subscribe to one PM2 process's live log stream over the shared socket.
+ *
+ * Wraps the `logs:subscribe` / `logs:line` / `logs:subscribed` / `logs:error`
+ * dance so callers only deal with `{ logs, subscribed }`. Every frame is
+ * filtered by `processName` before it lands — the server emits the name on each
+ * 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.
+ * @param {string} [options.appId] App whose custom PM2_HOME holds the process.
+ * Omit for processes in the default home.
+ * @returns {{ logs: Array<{line: string, type: string, timestamp: number}>, subscribed: boolean, clear: () => void }}
+ * `clear()` empties the local buffer only — the stream stays subscribed, so
+ * new lines keep arriving (this backs a "Clear" button, not an unsubscribe).
+ */
+export function useProcessLogs(processName, options = {}) {
+ const { lines = 500, appId } = options;
+ const [logs, setLogs] = useState([]);
+ const [subscribed, setSubscribed] = useState(false);
+
+ useEffect(() => {
+ if (!processName) {
+ setLogs([]);
+ setSubscribed(false);
+ return;
+ }
+
+ // Reset here rather than in the caller's click handler so switching
+ // processes can't briefly show the previous one's tail under the new name.
+ setLogs([]);
+ setSubscribed(false);
+
+ socket.emit('logs:subscribe', { processName, lines, ...(appId ? { appId } : {}) });
+
+ const handleLog = (data) => {
+ if (data.processName !== processName) return;
+ setLogs(prev => [...prev.slice(-(MAX_LINES - 1)), {
+ line: data.line,
+ type: data.type,
+ timestamp: data.timestamp
+ }]);
+ };
+
+ const handleSubscribed = (data) => {
+ if (data.processName === processName) setSubscribed(true);
+ };
+
+ const handleError = (data) => {
+ if (data.processName !== processName) return;
+ setLogs(prev => [...prev, { line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() }]);
+ };
+
+ socket.on('logs:line', handleLog);
+ socket.on('logs:subscribed', handleSubscribed);
+ socket.on('logs:error', handleError);
+
+ return () => {
+ socket.emit('logs:unsubscribe', { processName });
+ socket.off('logs:line', handleLog);
+ socket.off('logs:subscribed', handleSubscribed);
+ socket.off('logs:error', handleError);
+ };
+ }, [processName, lines, appId]);
+
+ const clear = useCallback(() => setLogs([]), []);
+
+ return { logs, subscribed, clear };
+}
+
+export default useProcessLogs;
diff --git a/client/src/hooks/useProcessLogs.test.jsx b/client/src/hooks/useProcessLogs.test.jsx
new file mode 100644
index 0000000000..752da10636
--- /dev/null
+++ b/client/src/hooks/useProcessLogs.test.jsx
@@ -0,0 +1,132 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act, cleanup } from '@testing-library/react';
+
+// Mock the shared socket so the test can drive the `logs:*` handlers the hook
+// registers and observe the subscribe/unsubscribe emits it sends.
+const handlers = new Map();
+const emitted = [];
+vi.mock('../services/socket', () => ({
+ default: {
+ on: (event, fn) => { handlers.set(event, fn); },
+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },
+ emit: (event, ...args) => { emitted.push([event, ...args]); },
+ },
+}));
+
+import { useProcessLogs } from './useProcessLogs.js';
+
+const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });
+const emitsOf = (event) => emitted.filter(([e]) => e === event).map(([, payload]) => payload);
+
+describe('useProcessLogs', () => {
+ beforeEach(() => { handlers.clear(); emitted.length = 0; });
+ afterEach(cleanup);
+
+ it('subscribes to the named process and reports lines', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+
+ expect(emitsOf('logs:subscribe')).toEqual([{ processName: 'game', lines: 500 }]);
+ expect(result.current.logs).toEqual([]);
+ expect(result.current.subscribed).toBe(false);
+
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'Compiling…', type: 'stdout', timestamp: 1 });
+
+ expect(result.current.subscribed).toBe(true);
+ expect(result.current.logs).toEqual([{ line: 'Compiling…', type: 'stdout', timestamp: 1 }]);
+ });
+
+ it('passes appId through so a custom PM2_HOME can be resolved server-side', () => {
+ renderHook(() => useProcessLogs('game', { lines: 200, appId: 'app-1' }));
+ expect(emitsOf('logs:subscribe')).toEqual([{ processName: 'game', lines: 200, appId: 'app-1' }]);
+ });
+
+ it('omits appId entirely when not supplied (default PM2_HOME)', () => {
+ renderHook(() => useProcessLogs('game'));
+ expect(emitsOf('logs:subscribe')[0]).not.toHaveProperty('appId');
+ });
+
+ it('ignores frames for a different process', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'other' });
+ fire('logs:line', { processName: 'other', line: 'not mine', type: 'stdout', timestamp: 1 });
+
+ expect(result.current.subscribed).toBe(false);
+ expect(result.current.logs).toEqual([]);
+ });
+
+ it('renders a stream error as a stderr line rather than throwing it away', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:error', { processName: 'game', error: 'pm2 unreachable' });
+
+ expect(result.current.logs).toHaveLength(1);
+ expect(result.current.logs[0]).toMatchObject({ line: 'Error: pm2 unreachable', type: 'stderr' });
+ });
+
+ it('does not subscribe when no process is named, and clears state', () => {
+ const { result, rerender } = renderHook(({ name }) => useProcessLogs(name), {
+ initialProps: { name: 'game' },
+ });
+ fire('logs:line', { processName: 'game', line: 'a', type: 'stdout', timestamp: 1 });
+ expect(result.current.logs).toHaveLength(1);
+
+ rerender({ name: null });
+
+ expect(result.current.logs).toEqual([]);
+ expect(result.current.subscribed).toBe(false);
+ // Unsubscribed on the way out so the server tears the pm2 stream down.
+ expect(emitsOf('logs:unsubscribe')).toEqual([{ processName: 'game' }]);
+ });
+
+ it('resets the buffer when switching processes so the old tail never bleeds through', () => {
+ const { result, rerender } = renderHook(({ name }) => useProcessLogs(name), {
+ initialProps: { name: 'game' },
+ });
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'old', type: 'stdout', timestamp: 1 });
+
+ rerender({ name: 'server' });
+
+ expect(result.current.logs).toEqual([]);
+ expect(result.current.subscribed).toBe(false);
+ expect(emitsOf('logs:subscribe')).toHaveLength(2);
+ });
+
+ it('clear() empties the buffer without unsubscribing', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:line', { processName: 'game', line: 'a', type: 'stdout', timestamp: 1 });
+
+ act(() => { result.current.clear(); });
+ expect(result.current.logs).toEqual([]);
+ expect(emitsOf('logs:unsubscribe')).toEqual([]);
+
+ // Still live — a new line lands after the clear.
+ fire('logs:line', { processName: 'game', line: 'b', type: 'stdout', timestamp: 2 });
+ expect(result.current.logs).toHaveLength(1);
+ });
+
+ it('caps the buffer so a chatty process cannot grow it without bound', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ act(() => {
+ for (let i = 0; i < 1100; i++) {
+ handlers.get('logs:line')?.({ processName: 'game', line: `l${i}`, type: 'stdout', timestamp: i });
+ }
+ });
+
+ expect(result.current.logs).toHaveLength(1000);
+ // Oldest lines dropped, newest retained.
+ expect(result.current.logs.at(-1).line).toBe('l1099');
+ expect(result.current.logs[0].line).toBe('l100');
+ });
+
+ it('tears down its listeners on unmount', () => {
+ const { unmount } = renderHook(() => useProcessLogs('game'));
+ expect(handlers.has('logs:line')).toBe(true);
+
+ unmount();
+
+ expect(handlers.has('logs:line')).toBe(false);
+ expect(handlers.has('logs:subscribed')).toBe(false);
+ expect(handlers.has('logs:error')).toBe(false);
+ });
+});
diff --git a/server/lib/socketValidation.js b/server/lib/socketValidation.js
index 7c9e38efe4..a1f055597e 100644
--- a/server/lib/socketValidation.js
+++ b/server/lib/socketValidation.js
@@ -18,10 +18,15 @@ export const standardizeStartSchema = z.object({
overwriteEcosystem: z.boolean().optional()
});
-// logs:subscribe — process name and optional line count
+// logs:subscribe — process name and optional line count. `appId` is optional and
+// only used to resolve that app's custom PM2_HOME: an app running in its own PM2
+// instance keeps its logs in a separate home, so a stream spawned against the
+// default home would silently tail nothing. Absent = default PM2_HOME (the common
+// case), so existing subscribers are unaffected.
export const logsSubscribeSchema = z.object({
processName: z.string().min(1, 'processName is required'),
- lines: z.number().int().positive().max(10000).default(100)
+ lines: z.number().int().positive().max(10000).default(100),
+ appId: z.string().min(1).optional()
});
// error:recover — error code and context
diff --git a/server/lib/socketValidation.test.js b/server/lib/socketValidation.test.js
index 8330d9477a..3387a99233 100644
--- a/server/lib/socketValidation.test.js
+++ b/server/lib/socketValidation.test.js
@@ -67,6 +67,23 @@ describe('socketValidation schemas', () => {
expect(logsSubscribeSchema.safeParse({ processName: 'p', lines: -1 }).success).toBe(false);
expect(logsSubscribeSchema.safeParse({ processName: 'p', lines: 1.5 }).success).toBe(false);
});
+
+ // appId scopes the stream to an app's custom PM2_HOME (issue #2991).
+ it('accepts an optional appId', () => {
+ const result = logsSubscribeSchema.safeParse({ processName: 'game', appId: 'app-1' });
+ expect(result.success).toBe(true);
+ expect(result.data.appId).toBe('app-1');
+ });
+
+ it('leaves appId absent when omitted (default PM2_HOME)', () => {
+ const result = logsSubscribeSchema.safeParse({ processName: 'game' });
+ expect(result.success).toBe(true);
+ expect(result.data.appId).toBeUndefined();
+ });
+
+ it('rejects an empty appId rather than treating it as absent', () => {
+ expect(logsSubscribeSchema.safeParse({ processName: 'game', appId: '' }).success).toBe(false);
+ });
});
describe('errorRecoverSchema', () => {
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 9fe251d62b..cddcf11325 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -81,11 +81,16 @@ export function execPm2(pm2Args, opts = {}) {
}
/**
- * Build environment object with optional custom PM2_HOME
+ * Build environment object with optional custom PM2_HOME.
+ *
+ * Exported because the log-stream socket handler spawns `pm2 logs` directly
+ * (not through spawnPm2Cli) and must target the same home the app's processes
+ * live in — otherwise an app with its own PM2 instance streams an empty log.
+ *
* @param {string} pm2Home Optional custom PM2_HOME path
* @returns {object} Environment variables
*/
-function buildEnv(pm2Home) {
+export function buildEnv(pm2Home) {
const env = { ...process.env };
if (pm2Home) {
env.PM2_HOME = pm2Home;
diff --git a/server/services/socket.js b/server/services/socket.js
index ab43e7a8d1..298e0f8d0b 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,7 +1,7 @@
-import { spawnPm2 } from './pm2.js';
+import { spawnPm2, buildEnv } from './pm2.js';
import { streamDetection } from './streamingDetect.js';
import { cosEvents } from './cosEvents.js';
-import { appsEvents } from './apps.js';
+import { appsEvents, getAppById } from './apps.js';
import { errorEvents, sanitizeContext } from '../lib/errorHandler.js';
import { handleErrorRecovery } from './autoFixer.js';
import * as pm2Standardizer from './pm2Standardizer.js';
@@ -206,18 +206,42 @@ export function initSocket(io) {
});
// Handle log streaming requests
- socket.on('logs:subscribe', (rawData) => {
+ socket.on('logs:subscribe', async (rawData) => {
const data = validateSocketData(logsSubscribeSchema, rawData, socket, 'logs:subscribe');
if (!data) return;
- const { processName, lines } = data;
+ const { processName, lines, appId } = data;
// Clean up any existing stream for this socket
cleanupStream(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
+ // a lookup failure must not throw — fall back to the default home.
+ let pm2Home = null;
+ if (appId) {
+ pm2Home = await getAppById(appId)
+ .then(app => app?.pm2Home || null)
+ .catch(err => {
+ console.error(`❌ logs:subscribe could not resolve app ${appId}: ${err.message}`);
+ return null;
+ });
+ }
+
+ // 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.
+ 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;
+
console.log(`📜 Log stream started: ${processName} (${lines} lines)`);
// Spawn pm2 logs with --raw flag
- const logProcess = spawnPm2(['logs', processName, '--raw', '--lines', String(lines)]);
+ const logProcess = spawnPm2(
+ ['logs', processName, '--raw', '--lines', String(lines)],
+ pm2Home ? { env: buildEnv(pm2Home) } : {}
+ );
activeStreams.set(socket.id, { process: logProcess, processName });
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index b4feb1c3dc..7d423834b7 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -8,7 +8,10 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
* subscription / broadcast / disconnect behavior through observable socket events.
*/
-vi.mock('./pm2.js', () => ({ spawnPm2: vi.fn(() => ({ stdout: { on: vi.fn() }, stderr: { on: vi.fn() }, on: vi.fn() })) }));
+vi.mock('./pm2.js', () => ({
+ spawnPm2: vi.fn(() => ({ stdout: { on: vi.fn() }, stderr: { on: vi.fn() }, on: vi.fn() })),
+ buildEnv: vi.fn((pm2Home) => ({ PATH: '/usr/bin', ...(pm2Home ? { PM2_HOME: pm2Home } : {}) }))
+}));
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() }));
@@ -59,6 +62,8 @@ vi.mock('./appDeployer.js', () => ({ hasDeployScript: vi.fn(), deployApp: vi.fn(
vi.mock('../sockets/voice.js', () => ({ registerVoiceHandlers: vi.fn() }));
import { initSocket } from './socket.js';
+import { spawnPm2 } from './pm2.js';
+import { getAppById } from './apps.js';
import { cosEvents } from './cosEvents.js';
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { audioGenEvents } from './audioGen/events.js';
@@ -386,4 +391,82 @@ describe('socket.js — initSocket', () => {
expect(err).toBeTruthy();
expect(err[1].sessionId).toBe('gone');
});
+
+ // ===========================================================================
+ // logs:subscribe — PM2_HOME resolution (issue #2991)
+ //
+ // An app running in its OWN PM2 instance keeps its logs in a separate home.
+ // Spawning `pm2 logs` against the default home would tail nothing at all, so
+ // the desktop launch-progress panel would sit empty while the game builds —
+ // exactly the "reads as hung" failure the panel exists to prevent.
+ // ===========================================================================
+ describe('logs:subscribe PM2_HOME resolution', () => {
+ beforeEach(() => {
+ vi.mocked(spawnPm2).mockClear();
+ vi.mocked(getAppById).mockReset();
+ });
+
+ it('streams from the default home when no appId is supplied', async () => {
+ const socket = makeSocket('logs-default');
+ io.connect(socket);
+
+ await socket.handlers['logs:subscribe']({ processName: 'portos-server', lines: 100 });
+
+ expect(getAppById).not.toHaveBeenCalled();
+ const [, opts] = vi.mocked(spawnPm2).mock.calls[0];
+ expect(opts).toEqual({});
+ });
+
+ it("streams from the app's custom PM2_HOME when it has one", async () => {
+ const socket = makeSocket('logs-custom-home');
+ io.connect(socket);
+ vi.mocked(getAppById).mockResolvedValue({ id: 'app-1', pm2Home: '/opt/example/.pm2' });
+
+ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 200, appId: 'app-1' });
+
+ expect(getAppById).toHaveBeenCalledWith('app-1');
+ 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');
+ });
+
+ it('falls back to the default home for an app with no custom home', async () => {
+ const socket = makeSocket('logs-no-custom-home');
+ io.connect(socket);
+ vi.mocked(getAppById).mockResolvedValue({ id: 'app-1', pm2Home: null });
+
+ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 200, appId: 'app-1' });
+
+ const [, opts] = vi.mocked(spawnPm2).mock.calls[0];
+ expect(opts).toEqual({});
+ });
+
+ it('still streams when the app lookup fails rather than throwing', async () => {
+ const socket = makeSocket('logs-lookup-fails');
+ io.connect(socket);
+ vi.mocked(getAppById).mockRejectedValue(new Error('registry unreadable'));
+
+ // Runs outside the Express lifecycle — an unhandled rejection here would
+ // take the process down, so the lookup degrades to the default home.
+ await expect(
+ socket.handlers['logs:subscribe']({ processName: 'game', lines: 200, appId: 'app-1' })
+ ).resolves.toBeUndefined();
+
+ expect(vi.mocked(spawnPm2)).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not spawn an orphan stream when the socket disconnected mid-lookup', async () => {
+ const socket = makeSocket('logs-disconnected');
+ io.connect(socket);
+ vi.mocked(getAppById).mockImplementation(async () => {
+ // The socket drops while the registry read is in flight.
+ socket.disconnected = true;
+ 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();
+ });
+ });
});