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: reject log subscriptions on PM2 home lookup failure (#9958)
[._.]/ Adam Eivy4c9dd58c2e23
diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 76e212160a..dc39a8e4b9 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -998,18 +998,22 @@ describe('socket.js — initSocket', () => {expect(opts.env.PM2_HOME).toBeUndefined();});- it('still streams when the app lookup fails rather than throwing', async () => {+ it('rejects the subscription when the app lookup fails rather than guessing a home', 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.+ // take the process down, so the handler reports a correlated error.await expect(socket.handlers['logs:subscribe']({ processName: 'game', lines: 200, appId: 'app-1' })).resolves.toBeUndefined();- expect(vi.mocked(spawnPm2)).toHaveBeenCalledTimes(1);+ expect(socket.emitted).toContainEqual([+ 'logs:error',+ { error: 'Unable to resolve PM2 home for game', processName: 'game' },+ ]);+ expect(vi.mocked(spawnPm2)).not.toHaveBeenCalled();});it('does not spawn an orphan stream when the socket disconnected mid-lookup', async () => {diff --git a/server/sockets/logs.js b/server/sockets/logs.jsindex 4a3305117f..c2deb68f5a 100644--- a/server/sockets/logs.js+++ b/server/sockets/logs.js@@ -72,22 +72,23 @@ export const registerLogHandlers = (socket, _io) => {// 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.+ // A successful null means the app uses the default PM2 home. A rejected+ // registry read is different: do not start a stream from an unverified+ // home or tell the client that subscription succeeded.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;- });- } else {- pm2Home = await resolvePm2HomeForProcess(processName)- .catch(err => {- console.error(`❌ logs:subscribe could not resolve ${processName}: ${err.message}`);- return null;- });+ try {+ if (appId) {+ const app = await getAppById(appId);+ pm2Home = app?.pm2Home || null;+ } else {+ pm2Home = await resolvePm2HomeForProcess(processName);+ }+ } catch (err) {+ console.error(`❌ logs:subscribe could not resolve PM2 home for ${processName}: ${err?.message ?? String(err)}`);+ if (!socket.disconnected && streamGenerations.get(key) === generation) {+ socket.emit('logs:error', { error: `Unable to resolve PM2 home for ${processName}`, processName });+ }+ return;}// The await above yields, so a disconnect, an unsubscribe, or a newerdiff --git a/server/sockets/logs.test.js b/server/sockets/logs.test.jsindex 00cc015d0e..9d2dfe69de 100644--- a/server/sockets/logs.test.js+++ b/server/sockets/logs.test.js@@ -19,7 +19,9 @@ vi.mock('../services/appProcessStatus.js', () => ({resolvePm2HomeForProcess: vi.fn(async () => null),}));-import { spawnPm2 } from '../services/pm2.js';+import { buildEnv, spawnPm2 } from '../services/pm2.js';+import { getAppById } from '../services/apps.js';+import { resolvePm2HomeForProcess } from '../services/appProcessStatus.js';import { registerLogHandlers, cleanupSocketStreams } from './logs.js';const makeChild = () => {@@ -30,7 +32,7 @@ const makeChild = () => {return child;};-const subscribe = async (processName = 'example-app') => {+const subscribe = async (processName = 'example-app', options = {}) => {const handlers = new Map();const emitted = [];const socket = {@@ -42,7 +44,7 @@ const subscribe = async (processName = 'example-app') => {const child = makeChild();spawnPm2.mockReturnValue(child);registerLogHandlers(socket, { emit: () => {} });- await handlers.get('logs:subscribe')({ processName, lines: 100 });+ await handlers.get('logs:subscribe')({ processName, lines: 100, ...options });return { socket, child, emitted, processName };};@@ -96,3 +98,53 @@ describe('logs:subscribe line reassembly', () => {]);});});++describe('logs:subscribe PM2 home resolution', () => {+ it.each([+ ['app id lookup', async () => getAppById.mockRejectedValueOnce(new Error('registry unavailable')), { appId: 'app-1' }],+ ['process lookup', async () => resolvePm2HomeForProcess.mockRejectedValueOnce(new Error('registry unavailable')), {}],+ ])('reports %s rejection without starting a default-home stream', async (_name, rejectLookup, options) => {+ const handlers = new Map();+ const emitted = [];+ const socket = {+ id: 'socket-test',+ disconnected: false,+ on: (event, fn) => handlers.set(event, fn),+ emit: (event, payload) => emitted.push({ event, payload }),+ };+ registerLogHandlers(socket, { emit: () => {} });+ await rejectLookup();+ await handlers.get('logs:subscribe')({ processName: 'example-app', lines: 100, ...options });++ expect(spawnPm2).not.toHaveBeenCalled();+ expect(emitted).toContainEqual({+ event: 'logs:error',+ payload: { error: 'Unable to resolve PM2 home for example-app', processName: 'example-app' },+ });+ expect(emitted.some(({ event }) => event === 'logs:subscribed')).toBe(false);+ });++ it('uses a successfully resolved custom home', async () => {+ const handlers = new Map();+ const socket = { id: 'socket-test', disconnected: false, on: (event, fn) => handlers.set(event, fn), emit: vi.fn() };+ getAppById.mockResolvedValueOnce({ pm2Home: '/synthetic/custom-home' });+ registerLogHandlers(socket, { emit: () => {} });+ await handlers.get('logs:subscribe')({ processName: 'example-app', appId: 'app-1', lines: 100 });++ expect(buildEnv).toHaveBeenCalledWith('/synthetic/custom-home');+ expect(spawnPm2).toHaveBeenCalledOnce();+ expect(socket.emit).toHaveBeenCalledWith('logs:subscribed', expect.objectContaining({ processName: 'example-app' }));+ });++ it('keeps a successful null lookup on the default home', async () => {+ const handlers = new Map();+ const socket = { id: 'socket-test', disconnected: false, on: (event, fn) => handlers.set(event, fn), emit: vi.fn() };+ resolvePm2HomeForProcess.mockResolvedValueOnce(null);+ registerLogHandlers(socket, { emit: () => {} });+ await handlers.get('logs:subscribe')({ processName: 'example-app', lines: 100 });++ expect(buildEnv).toHaveBeenCalledWith(null);+ expect(spawnPm2).toHaveBeenCalledOnce();+ expect(socket.emit).toHaveBeenCalledWith('logs:subscribed', expect.objectContaining({ processName: 'example-app' }));+ });+});