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: make useProcessLogs a client-side refcount owner for shared PM2 log streams (#8113)
[._.]/ Adam Eivy1e32ecd50547
diff --git a/client/src/components/apps/DesktopLaunchProgress.test.jsx b/client/src/components/apps/DesktopLaunchProgress.test.jsxindex 643214deaa..b1d8b21b17 100644--- a/client/src/components/apps/DesktopLaunchProgress.test.jsx+++ b/client/src/components/apps/DesktopLaunchProgress.test.jsx@@ -1,12 +1,22 @@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 = [];+// useProcessLogs (#8113) binds ONE listener per event at module load, shared+// across every mounted consumer via its refcount registry — so `on` must+// support multiple registrations per event, and `handlers` must NOT be+// cleared between tests: the module-level listeners are bound exactly once+// for the whole file.+const { handlers, emitted } = vi.hoisted(() => ({+ handlers: new Map(), // event -> Set<fn>+ emitted: [],+}));vi.mock('../../services/socket', () => ({default: {- on: (event, fn) => { handlers.set(event, fn); },- off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },+ 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); },emit: (event, ...args) => { emitted.push([event, ...args]); },},}));@@ -17,7 +27,7 @@ import { DESKTOP_TYPES, isDesktopType, resolveLaunchPanelProcess } from './const// Lines are batched on a 250ms debounce in useProcessLogs — advance past it so// the rendered output reflects the frame.const fire = (event, payload) => {- act(() => { handlers.get(event)?.(payload); });+ act(() => { handlers.get(event)?.forEach(fn => fn(payload)); });act(() => { vi.advanceTimersByTime(250); });};@@ -32,7 +42,7 @@ const renderPanel = (props = {}) => render();describe('DesktopLaunchProgress', () => {- beforeEach(() => { handlers.clear(); emitted.length = 0; vi.useFakeTimers(); });+ beforeEach(() => { emitted.length = 0; vi.useFakeTimers(); });afterEach(() => { cleanup(); vi.useRealTimers(); });it('subscribes to the process log scoped to the app (custom PM2_HOME)', () => {diff --git a/client/src/hooks/useProcessLogs.js b/client/src/hooks/useProcessLogs.jsindex fe7fb3a71f..84e0ab78ad 100644--- a/client/src/hooks/useProcessLogs.js+++ b/client/src/hooks/useProcessLogs.js@@ -11,6 +11,72 @@ const MAX_LINES = 1000;// ~250ms debounce for high-frequency state writes.const FLUSH_MS = 250;+// The server keeps ONE `pm2 logs` stream per (socket.id, processName)+// (server/sockets/logs.js) — a second `logs:subscribe` for a key already in+// use kills the first stream and starts another, so two mounted+// `useProcessLogs` consumers of the same process (e.g. the desktop launch+// panel and the Processes tab) would otherwise clobber each other's stream+// (#8113). This module-level registry makes the CLIENT the refcount owner:+// the first consumer subscribes, later consumers attach to the existing+// entry, and only the last consumer to leave unsubscribes. One shared socket+// listener per event fans each frame out to every attached consumer.+const registry = new Map(); // processName -> entry++const createEntry = (processName, lines, appId) => ({+ processName,+ appId,+ lines,+ consumers: new Set(), // Set<{ onLine, onSubscribed }>+ buffer: [], // shared tail buffer for late joiners, capped at MAX_LINES+ subscribed: false,+});++const subscribeEntry = (entry) => {+ entry.subscribed = false;+ socket.emit('logs:subscribe', {+ processName: entry.processName,+ lines: entry.lines,+ ...(entry.appId ? { appId: entry.appId } : {}),+ });+};++const appendToEntry = (entry, payload) => {+ entry.buffer.push(payload);+ if (entry.buffer.length > MAX_LINES) entry.buffer.splice(0, entry.buffer.length - MAX_LINES);+ entry.consumers.forEach((consumer) => consumer.onLine(payload));+};++// One listener per event for the whole module. A per-consumer `socket.on`+// would need a per-consumer `socket.off` on unmount, and the LAST consumer+// leaving must not silence the SURVIVING consumers of other processes.+socket.on('logs:line', (data) => {+ const entry = registry.get(data.processName);+ if (!entry) return;+ appendToEntry(entry, { line: data.line, type: data.type, timestamp: data.timestamp });+});++socket.on('logs:subscribed', (data) => {+ const entry = registry.get(data.processName);+ if (!entry) return;+ entry.subscribed = true;+ entry.consumers.forEach((consumer) => consumer.onSubscribed());+});++socket.on('logs:error', (data) => {+ const entry = registry.get(data.processName);+ if (!entry) return;+ appendToEntry(entry, { line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() });+});++// The server drops every stream owned by a disconnected socket+// (`cleanupSocketStreams`), so a reconnect must re-subscribe every still-live+// entry, or every mounted consumer freezes with no error frame ever emitted.+socket.on('connect', () => {+ registry.forEach((entry) => {+ if (entry.consumers.size > 0) subscribeEntry(entry);+ });+});+/*** Subscribe to one PM2 process's live log stream over the shared socket.*@@ -20,6 +86,13 @@ const FLUSH_MS = 250;* line, and a stale frame from a just-unsubscribed process would otherwise be* appended to the new one's buffer.*+ * Multiple consumers naming the same `processName` (e.g. the desktop launch+ * panel and the Processes tab tailing the same app) share one underlying+ * server stream via the module-level registry above — see #8113. A later+ * consumer is seeded from the shared entry's current tail instead of+ * triggering a re-subscribe, so the earlier consumer never sees its tail+ * replayed a second time.+ ** @param {string|null} processName PM2 process to tail; falsy = unsubscribed/idle.* @param {object} [options]* @param {number} [options.lines=500] Tail depth requested on subscribe.@@ -28,6 +101,8 @@ const FLUSH_MS = 250;* @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).+ * It never mutates the shared entry buffer, so it does not affect any other+ * consumer's view of the same process.*/export function useProcessLogs(processName, options = {}) {const { lines = 500, appId } = options;@@ -39,7 +114,7 @@ export function useProcessLogs(processName, options = {}) {useEffect(() => {setLogs([]);setSubscribed(false);- if (!processName) return;+ if (!processName) return undefined;const flush = () => {flushTimerRef.current = null;@@ -51,48 +126,54 @@ export function useProcessLogs(processName, options = {}) {return combined.length > MAX_LINES ? combined.slice(-MAX_LINES) : combined;});};- const append = (entry) => {+ const queueLine = (entry) => {pendingRef.current.push(entry);if (flushTimerRef.current == null) flushTimerRef.current = setTimeout(flush, FLUSH_MS);};- socket.emit('logs:subscribe', { processName, lines, ...(appId ? { appId } : {}) });-- const handleLog = (data) => {- if (data.processName !== processName) return;- append({ line: data.line, type: data.type, timestamp: data.timestamp });- };-- const handleSubscribed = (data) => {- if (data.processName === processName) setSubscribed(true);- };+ let entry = registry.get(processName);+ const isFirstConsumer = !entry;+ if (!entry) {+ entry = createEntry(processName, lines, appId);+ registry.set(processName, entry);+ }- const handleError = (data) => {- if (data.processName !== processName) return;- append({ line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() });+ const consumer = {+ onLine: queueLine,+ onSubscribed: () => setSubscribed(true),};+ entry.consumers.add(consumer);- socket.on('logs:line', handleLog);- socket.on('logs:subscribed', handleSubscribed);- socket.on('logs:error', handleError);+ if (isFirstConsumer) {+ subscribeEntry(entry);+ } else {+ // Late joiner: seed from the existing entry's tail (capped to this+ // consumer's own `lines`) instead of re-subscribing, which would+ // replay the tail into every consumer already watching this stream.+ if (entry.subscribed) setSubscribed(true);+ const seeded = entry.buffer.slice(-lines);+ if (seeded.length > 0) setLogs(seeded);+ }return () => {- socket.emit('logs:unsubscribe', { processName });- socket.off('logs:line', handleLog);- socket.off('logs:subscribed', handleSubscribed);- socket.off('logs:error', handleError);- // Drop the pending batch with the subscription: the effect re-run clears- // `logs` anyway, so flushing here would append the old process's tail to- // the new one's empty buffer.+ entry.consumers.delete(consumer);if (flushTimerRef.current != null) clearTimeout(flushTimerRef.current);flushTimerRef.current = null;pendingRef.current = [];+ // Last consumer out unsubscribes and drops the entry so a later+ // remount starts a fresh stream instead of replaying a stale tail.+ if (entry.consumers.size === 0) {+ registry.delete(processName);+ socket.emit('logs:unsubscribe', { processName });+ }};}, [processName, lines, appId]);const clear = useCallback(() => {// Also drop anything buffered but not yet flushed, or a pending timer would- // repopulate the list the user just cleared.+ // repopulate the list the user just cleared. This only touches THIS+ // consumer's own state — the shared entry buffer other consumers seed+ // from is left untouched.pendingRef.current = [];setLogs([]);}, []);diff --git a/client/src/hooks/useProcessLogs.test.jsx b/client/src/hooks/useProcessLogs.test.jsxindex d20bb091a8..ce5b490beb 100644--- a/client/src/hooks/useProcessLogs.test.jsx+++ b/client/src/hooks/useProcessLogs.test.jsx@@ -2,13 +2,23 @@ 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 = [];+// registers and observe the subscribe/unsubscribe emits it sends. The hook now+// binds ONE listener per event at module load (shared across every consumer,+// per #8113's refcount registry), so `on` must support multiple registrations+// per event — unlike the earlier single-consumer version, `handlers` is never+// cleared between tests: the module-level listeners are bound exactly once+// for the whole file and must keep dispatching to every subsequent test.+const { handlers, emitted } = vi.hoisted(() => ({+ handlers: new Map(), // event -> Set<fn>+ emitted: [],+}));vi.mock('../services/socket', () => ({default: {- on: (event, fn) => { handlers.set(event, fn); },- off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },+ 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); },emit: (event, ...args) => { emitted.push([event, ...args]); },},}));@@ -20,17 +30,17 @@ import { useProcessLogs } from './useProcessLogs.js';const FLUSH_MS = 250;const flushLines = () => act(() => { vi.advanceTimersByTime(FLUSH_MS); });-/** Fire a socket frame and let the batch flush, so `logs` reflects it. */+/** Fire a socket frame on every registered listener and let the batch flush. */const fire = (event, payload) => {- act(() => { handlers.get(event)?.(payload); });+ act(() => { handlers.get(event)?.forEach(fn => fn(payload)); });flushLines();};/** Fire a frame WITHOUT flushing — for asserting the debounce itself. */-const fireRaw = (event, payload) => act(() => { handlers.get(event)?.(payload); });+const fireRaw = (event, payload) => act(() => { handlers.get(event)?.forEach(fn => fn(payload)); });const emitsOf = (event) => emitted.filter(([e]) => e === event).map(([, payload]) => payload);describe('useProcessLogs', () => {- beforeEach(() => { handlers.clear(); emitted.length = 0; vi.useFakeTimers(); });+ beforeEach(() => { emitted.length = 0; vi.useFakeTimers(); });afterEach(() => { cleanup(); vi.useRealTimers(); });it('subscribes to the named process and reports lines', () => {@@ -120,7 +130,7 @@ describe('useProcessLogs', () => {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 });+ handlers.get('logs:line')?.forEach(fn => fn({ processName: 'game', line: `l${i}`, type: 'stdout', timestamp: i }));}});flushLines();@@ -140,7 +150,7 @@ describe('useProcessLogs', () => {act(() => {for (let i = 0; i < 50; i++) {- handlers.get('logs:line')?.({ processName: 'game', line: `l${i}`, type: 'stdout', timestamp: i });+ handlers.get('logs:line')?.forEach(fn => fn({ processName: 'game', line: `l${i}`, type: 'stdout', timestamp: i }));}});// Nothing applied yet — still inside the debounce window.@@ -179,14 +189,89 @@ describe('useProcessLogs', () => {expect(result.current.logs).toEqual([]);});- it('tears down its listeners on unmount', () => {- const { unmount } = renderHook(() => useProcessLogs('game'));- expect(handlers.has('logs:line')).toBe(true);+ // --- Shared-stream registry (#8113) ---------------------------------++ it('two consumers of the same process share one subscribe, not two', () => {+ const first = renderHook(() => useProcessLogs('game'));+ const second = renderHook(() => useProcessLogs('game'));++ // Only the first consumer triggered a `logs:subscribe`.+ expect(emitsOf('logs:subscribe')).toHaveLength(1);++ fire('logs:line', { processName: 'game', line: 'shared', type: 'stdout', timestamp: 1 });+ expect(first.result.current.logs).toEqual([{ line: 'shared', type: 'stdout', timestamp: 1 }]);+ expect(second.result.current.logs).toEqual([{ line: 'shared', type: 'stdout', timestamp: 1 }]);++ first.unmount();+ second.unmount();+ });++ it('unmounting one of two consumers does not unsubscribe or freeze the survivor', () => {+ const first = renderHook(() => useProcessLogs('game'));+ const second = renderHook(() => useProcessLogs('game'));++ first.unmount();+ // The survivor is still attached — the server stream must stay alive.+ expect(emitsOf('logs:unsubscribe')).toEqual([]);++ fire('logs:line', { processName: 'game', line: 'still here', type: 'stdout', timestamp: 2 });+ expect(second.result.current.logs).toEqual([{ line: 'still here', type: 'stdout', timestamp: 2 }]);++ second.unmount();+ // Now the last consumer left — exactly one unsubscribe.+ expect(emitsOf('logs:unsubscribe')).toEqual([{ processName: 'game' }]);+ });++ it('a late-joining consumer is seeded from the existing tail without re-subscribing or duplicating the first consumer\'s tail', () => {+ const first = renderHook(() => useProcessLogs('game'));+ fire('logs:line', { processName: 'game', line: 'a', type: 'stdout', timestamp: 1 });+ fire('logs:line', { processName: 'game', line: 'b', type: 'stdout', timestamp: 2 });++ const second = renderHook(() => useProcessLogs('game'));++ // Still exactly one subscribe — the late joiner attached instead of+ // triggering a second `pm2 logs` spawn.+ expect(emitsOf('logs:subscribe')).toHaveLength(1);+ // Seeded with the tail seen so far, not an empty buffer.+ expect(second.result.current.logs).toEqual([+ { line: 'a', type: 'stdout', timestamp: 1 },+ { line: 'b', type: 'stdout', timestamp: 2 },+ ]);+ // The first consumer's own view is untouched by the late joiner — no+ // duplicated tail.+ expect(first.result.current.logs).toEqual([+ { line: 'a', type: 'stdout', timestamp: 1 },+ { line: 'b', type: 'stdout', timestamp: 2 },+ ]);++ first.unmount();+ second.unmount();+ });++ it('clear() on one consumer does not empty another consumer\'s lines', () => {+ const first = renderHook(() => useProcessLogs('game'));+ const second = renderHook(() => useProcessLogs('game'));+ fire('logs:line', { processName: 'game', line: 'a', type: 'stdout', timestamp: 1 });- unmount();+ act(() => { first.result.current.clear(); });+ expect(first.result.current.logs).toEqual([]);+ expect(second.result.current.logs).toEqual([{ line: 'a', type: 'stdout', timestamp: 1 }]);++ first.unmount();+ second.unmount();+ });++ it('re-subscribes and resumes streaming after a reconnect', () => {+ const { result } = renderHook(() => useProcessLogs('game'));+ expect(emitsOf('logs:subscribe')).toHaveLength(1);++ // Server drops every stream owned by a disconnected socket+ // (cleanupSocketStreams) — a mounted consumer must re-subscribe on+ // 'connect' or it freezes with no error frame ever emitted.+ fireRaw('connect', undefined);+ expect(emitsOf('logs:subscribe')).toHaveLength(2);- expect(handlers.has('logs:line')).toBe(false);- expect(handlers.has('logs:subscribed')).toBe(false);- expect(handlers.has('logs:error')).toBe(false);+ fire('logs:line', { processName: 'game', line: 'resumed', type: 'stdout', timestamp: 3 });+ expect(result.current.logs).toEqual([{ line: 'resumed', type: 'stdout', timestamp: 3 }]);});});