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: validate the LM Studio routes and stop dropping log-stream errors

[._.]/ Adam Eivy5f9a6a3314c8
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 9eac3ca2a2..1dfe212cdd 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1154,6 +1154,52 @@ export const settingsEmbeddingsSchema = z.object({
model: z.string().trim().max(200).optional().nullable(),
}).strict();
+// =============================================================================
+// LM STUDIO (server/routes/lmstudio.js)
+// =============================================================================
+
+// PUT /api/lmstudio/config — persisted straight into module-level state
+// (lmStudioManager's `config`) that every other LM Studio call site reads via
+// getBaseUrl(). A malformed baseUrl must be rejected up front rather than
+// degrading local-LLM connectivity until the process restarts.
+export const lmStudioConfigSchema = z.object({
+ baseUrl: z.string().trim().url().optional(),
+ timeout: z.number().int().positive().optional(),
+ defaultThinkingModel: z.string().trim().min(1).optional(),
+});
+
+// Shared by /download, /load, /unload — each acts on a single model id.
+export const lmStudioModelIdSchema = z.object({
+ modelId: z.string().trim().min(1),
+});
+
+// POST /api/lmstudio/completion
+export const lmStudioCompletionSchema = z.object({
+ prompt: z.string().min(1),
+ model: z.string().trim().min(1).optional(),
+ maxTokens: z.number().int().positive().optional(),
+ temperature: z.number().min(0).max(2).optional(),
+ systemPrompt: z.string().optional(),
+});
+
+// POST /api/lmstudio/analyze-task
+export const lmStudioAnalyzeTaskSchema = z.object({
+ description: z.string().min(1),
+ id: z.string().optional(),
+ metadata: z.record(z.any()).optional(),
+});
+
+// POST /api/lmstudio/classify-memory
+export const lmStudioClassifyMemorySchema = z.object({
+ content: z.string().min(1),
+});
+
+// POST /api/lmstudio/embeddings
+export const lmStudioEmbeddingsSchema = z.object({
+ text: z.string().min(1),
+ model: z.string().trim().min(1).optional(),
+});
+
// Subscription creation: persistent (bucket, record) tuple. Series + universe
// are the subscribable kinds (records that change over time and benefit from
// auto-re-export). Media is one-shot via /buckets/:id/export.
diff --git a/server/routes/lmstudio.js b/server/routes/lmstudio.js
index 1c746ba302..74d94cefdb 100644
--- a/server/routes/lmstudio.js
+++ b/server/routes/lmstudio.js
@@ -8,6 +8,15 @@ import { Router } from 'express'
import * as lmStudioManager from '../services/lmStudioManager.js'
import * as localThinking from '../services/localThinking.js'
import { asyncHandler, ServerError } from '../lib/errorHandler.js'
+import {
+ validateRequest,
+ lmStudioConfigSchema,
+ lmStudioModelIdSchema,
+ lmStudioCompletionSchema,
+ lmStudioAnalyzeTaskSchema,
+ lmStudioClassifyMemorySchema,
+ lmStudioEmbeddingsSchema
+} from '../lib/validation.js'
const router = Router()
@@ -52,11 +61,7 @@ router.get('/models', asyncHandler(async (req, res) => {
* Download a model by ID
*/
router.post('/download', asyncHandler(async (req, res) => {
- const { modelId } = req.body
-
- if (!modelId) {
- throw new ServerError('modelId is required', { status: 400 })
- }
+ const { modelId } = validateRequest(lmStudioModelIdSchema, req.body)
const result = await lmStudioManager.downloadModel(modelId)
res.json(result)
@@ -67,11 +72,7 @@ router.post('/download', asyncHandler(async (req, res) => {
* Load a model into memory
*/
router.post('/load', asyncHandler(async (req, res) => {
- const { modelId } = req.body
-
- if (!modelId) {
- throw new ServerError('modelId is required', { status: 400 })
- }
+ const { modelId } = validateRequest(lmStudioModelIdSchema, req.body)
const result = await lmStudioManager.loadModel(modelId)
res.json(result)
@@ -82,11 +83,7 @@ router.post('/load', asyncHandler(async (req, res) => {
* Unload a model from memory
*/
router.post('/unload', asyncHandler(async (req, res) => {
- const { modelId } = req.body
-
- if (!modelId) {
- throw new ServerError('modelId is required', { status: 400 })
- }
+ const { modelId } = validateRequest(lmStudioModelIdSchema, req.body)
const result = await lmStudioManager.unloadModel(modelId)
res.json(result)
@@ -97,11 +94,7 @@ router.post('/unload', asyncHandler(async (req, res) => {
* Quick completion using local model
*/
router.post('/completion', asyncHandler(async (req, res) => {
- const { prompt, model, maxTokens, temperature, systemPrompt } = req.body
-
- if (!prompt) {
- throw new ServerError('prompt is required', { status: 400 })
- }
+ const { prompt, model, maxTokens, temperature, systemPrompt } = validateRequest(lmStudioCompletionSchema, req.body)
const result = await lmStudioManager.quickCompletion(prompt, {
model,
@@ -118,11 +111,7 @@ router.post('/completion', asyncHandler(async (req, res) => {
* Analyze a task for complexity and escalation needs
*/
router.post('/analyze-task', asyncHandler(async (req, res) => {
- const { description, id, metadata } = req.body
-
- if (!description) {
- throw new ServerError('description is required', { status: 400 })
- }
+ const { description, id, metadata } = validateRequest(lmStudioAnalyzeTaskSchema, req.body)
const analysis = await localThinking.analyzeTask({
id,
@@ -138,11 +127,7 @@ router.post('/analyze-task', asyncHandler(async (req, res) => {
* Classify memory content
*/
router.post('/classify-memory', asyncHandler(async (req, res) => {
- const { content } = req.body
-
- if (!content) {
- throw new ServerError('content is required', { status: 400 })
- }
+ const { content } = validateRequest(lmStudioClassifyMemorySchema, req.body)
const classification = await localThinking.classifyMemory(content)
res.json(classification)
@@ -153,11 +138,7 @@ router.post('/classify-memory', asyncHandler(async (req, res) => {
* Get embeddings for text
*/
router.post('/embeddings', asyncHandler(async (req, res) => {
- const { text, model } = req.body
-
- if (!text) {
- throw new ServerError('text is required', { status: 400 })
- }
+ const { text, model } = validateRequest(lmStudioEmbeddingsSchema, req.body)
const result = await lmStudioManager.getEmbeddings(text, { model })
res.json(result)
@@ -168,7 +149,7 @@ router.post('/embeddings', asyncHandler(async (req, res) => {
* Update LM Studio configuration
*/
router.put('/config', asyncHandler(async (req, res) => {
- const { baseUrl, timeout, defaultThinkingModel } = req.body
+ const { baseUrl, timeout, defaultThinkingModel } = validateRequest(lmStudioConfigSchema, req.body)
const config = lmStudioManager.updateConfig({
baseUrl,
diff --git a/server/routes/lmstudio.test.js b/server/routes/lmstudio.test.js
new file mode 100644
index 0000000000..90ac3a8374
--- /dev/null
+++ b/server/routes/lmstudio.test.js
@@ -0,0 +1,138 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/lmStudioManager.js', () => ({
+ getStatus: vi.fn(),
+ checkLMStudioAvailable: vi.fn(),
+ getLoadedModels: vi.fn(),
+ getRecommendedThinkingModel: vi.fn(),
+ downloadModel: vi.fn(),
+ loadModel: vi.fn(),
+ unloadModel: vi.fn(),
+ quickCompletion: vi.fn(),
+ getEmbeddings: vi.fn(),
+ updateConfig: vi.fn(),
+ resetCache: vi.fn()
+}));
+
+vi.mock('../services/localThinking.js', () => ({
+ getStats: vi.fn(),
+ analyzeTask: vi.fn(),
+ classifyMemory: vi.fn()
+}));
+
+import * as lmStudioManager from '../services/lmStudioManager.js';
+import lmstudioRoutes from './lmstudio.js';
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/lmstudio', lmstudioRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+describe('lmstudio routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = buildApp();
+ vi.clearAllMocks();
+ });
+
+ describe('PUT /api/lmstudio/config', () => {
+ it('rejects a malformed baseUrl instead of persisting it', async () => {
+ const res = await request(app)
+ .put('/api/lmstudio/config')
+ .send({ baseUrl: 'not-a-url' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(lmStudioManager.updateConfig).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-numeric timeout', async () => {
+ const res = await request(app)
+ .put('/api/lmstudio/config')
+ .send({ timeout: 'soon' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(lmStudioManager.updateConfig).not.toHaveBeenCalled();
+ });
+
+ it('accepts a valid config payload and forwards it to the manager', async () => {
+ lmStudioManager.updateConfig.mockReturnValue({
+ baseUrl: 'http://localhost:1234',
+ timeout: 30000,
+ defaultThinkingModel: 'qwen-14b'
+ });
+
+ const res = await request(app)
+ .put('/api/lmstudio/config')
+ .send({ baseUrl: 'http://localhost:1234', timeout: 30000, defaultThinkingModel: 'qwen-14b' });
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(lmStudioManager.updateConfig).toHaveBeenCalledWith({
+ baseUrl: 'http://localhost:1234',
+ timeout: 30000,
+ defaultThinkingModel: 'qwen-14b'
+ });
+ });
+
+ it('accepts an empty payload (all fields optional)', async () => {
+ lmStudioManager.updateConfig.mockReturnValue({ baseUrl: 'http://localhost:1234' });
+
+ const res = await request(app).put('/api/lmstudio/config').send({});
+
+ expect(res.status).toBe(200);
+ expect(lmStudioManager.updateConfig).toHaveBeenCalledWith({
+ baseUrl: undefined,
+ timeout: undefined,
+ defaultThinkingModel: undefined
+ });
+ });
+ });
+
+ describe('POST /api/lmstudio/download', () => {
+ it('rejects a missing modelId', async () => {
+ const res = await request(app).post('/api/lmstudio/download').send({});
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(lmStudioManager.downloadModel).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-string modelId', async () => {
+ const res = await request(app).post('/api/lmstudio/download').send({ modelId: 42 });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(lmStudioManager.downloadModel).not.toHaveBeenCalled();
+ });
+
+ it('forwards a valid modelId', async () => {
+ lmStudioManager.downloadModel.mockResolvedValue({ success: true });
+ const res = await request(app).post('/api/lmstudio/download').send({ modelId: 'qwen-14b' });
+ expect(res.status).toBe(200);
+ expect(lmStudioManager.downloadModel).toHaveBeenCalledWith('qwen-14b');
+ });
+ });
+
+ describe('POST /api/lmstudio/completion', () => {
+ it('rejects a missing prompt', async () => {
+ const res = await request(app).post('/api/lmstudio/completion').send({});
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(lmStudioManager.quickCompletion).not.toHaveBeenCalled();
+ });
+
+ it('forwards a valid prompt', async () => {
+ lmStudioManager.quickCompletion.mockResolvedValue({ text: 'ok' });
+ const res = await request(app).post('/api/lmstudio/completion').send({ prompt: 'hello' });
+ expect(res.status).toBe(200);
+ expect(lmStudioManager.quickCompletion).toHaveBeenCalledWith('hello', expect.any(Object));
+ });
+ });
+});
diff --git a/server/scripts/pruneImportedLegacyFiles.js b/server/scripts/pruneImportedLegacyFiles.js
index 408b3d6dd7..bc95a3c3b2 100644
--- a/server/scripts/pruneImportedLegacyFiles.js
+++ b/server/scripts/pruneImportedLegacyFiles.js
@@ -77,7 +77,7 @@
import { readFile, writeFile, rm, readdir, stat } from 'fs/promises';
import { join } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, tryReadFile } from '../lib/fileUtils.js';
const MARKER_VERSION = 1;
const MARKER_FILENAME = 'legacy-prune.applied.json';
@@ -309,7 +309,7 @@ async function pathExists(p) {
}
async function readJson(base, file) {
- const raw = await readFile(join(base, file), 'utf-8').catch(() => null);
+ const raw = await tryReadFile(join(base, file));
if (!raw) return null;
try { return JSON.parse(raw); } catch { return null; }
}
diff --git a/server/services/digital-twin-avatar-bio.js b/server/services/digital-twin-avatar-bio.js
index 52aa4213d4..27099441b6 100644
--- a/server/services/digital-twin-avatar-bio.js
+++ b/server/services/digital-twin-avatar-bio.js
@@ -14,8 +14,6 @@
* the deterministic draft into first-person, avatar-ready prose.
*/
-import { readFile } from 'fs/promises';
-import { existsSync } from 'fs';
import { join } from 'path';
import { DIGITAL_TWIN_DIR, callProviderAI } from './digital-twin-helpers.js';
import { loadMeta } from './digital-twin-meta.js';
@@ -23,6 +21,7 @@ import { getTraits } from './digital-twin-analysis.js';
import { getGoals } from './identity.js';
import { getProviderById } from './providers.js';
import { estimateTokens } from '../lib/contextBudget.js';
+import { tryReadFile } from '../lib/fileUtils.js';
// Bio length presets. `blurb` is a single paragraph per section (avatar persona
// fields are often short); `persona` is the balanced default; `knowledge` keeps
@@ -32,8 +31,7 @@ export const DEFAULT_AVATAR_BIO_LENGTH = 'persona';
async function readDoc(filename) {
const filePath = join(DIGITAL_TWIN_DIR, filename);
- if (!existsSync(filePath)) return null;
- return readFile(filePath, 'utf-8').catch(() => null);
+ return tryReadFile(filePath);
}
/**
diff --git a/server/services/loops.js b/server/services/loops.js
index ca48ee36f0..8cf1ae2052 100644
--- a/server/services/loops.js
+++ b/server/services/loops.js
@@ -9,7 +9,7 @@
import { EventEmitter } from 'events';
import { join } from 'path';
-import { PATHS, ensureDir, atomicWrite } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { randomUUID } from 'crypto';
import { createRun } from './runner.js';
import { resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
@@ -46,8 +46,7 @@ function formatInterval(ms) {
let loopsTail = Promise.resolve();
async function loadLoops() {
- const { readFile } = await import('fs/promises');
- const raw = await readFile(LOOPS_FILE, 'utf-8').catch(() => null);
+ const raw = await tryReadFile(LOOPS_FILE);
if (raw === null) return [];
try {
return JSON.parse(raw);
diff --git a/server/services/loops.test.js b/server/services/loops.test.js
index c0a6e135b2..ab114bda84 100644
--- a/server/services/loops.test.js
+++ b/server/services/loops.test.js
@@ -40,8 +40,7 @@ vi.mock('./providers.js', () => ({
getActiveProvider: vi.fn(),
}));
-import { readFile } from 'fs/promises';
-import { atomicWrite } from '../lib/fileUtils.js';
+import { tryReadFile, atomicWrite } from '../lib/fileUtils.js';
import { createRun } from './runner.js';
import { runPromptThroughProvider, resolveProviderAndModel } from '../lib/promptRunner.js';
import {
@@ -82,7 +81,7 @@ function setupProviderMocks() {
describe('loops.js', () => {
// Track IDs of loops created in each test so afterEach can stop them reliably.
- // getLoops() reads from the mocked readFile (which stays '[]'), so we cannot
+ // getLoops() reads from the mocked tryReadFile (which stays '[]'), so we cannot
// rely on it to discover active loops; instead we intercept atomicWrite.
let createdLoopIds = [];
@@ -91,7 +90,7 @@ describe('loops.js', () => {
vi.useFakeTimers();
createdLoopIds = [];
// Default: file has no saved loops
- readFile.mockResolvedValue('[]');
+ tryReadFile.mockResolvedValue('[]');
atomicWrite.mockImplementation((_path, data) => {
try {
// atomicWrite receives the data object directly (not JSON string)
@@ -181,9 +180,9 @@ describe('loops.js', () => {
});
// Capture the loop data that was written to disk
- // atomicWrite receives the data object directly; stringify it for readFile mock
+ // atomicWrite receives the data object directly; stringify it for tryReadFile mock
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
await stopLoop(loop.id);
@@ -202,9 +201,9 @@ describe('loops.js', () => {
runImmediately: false
});
- // atomicWrite receives the data object directly; stringify it for readFile mock
+ // atomicWrite receives the data object directly; stringify it for tryReadFile mock
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
const emitted = [];
loopEvents.on('stopped', (data) => emitted.push(data));
@@ -232,16 +231,16 @@ describe('loops.js', () => {
runImmediately: false
});
- // atomicWrite receives the data object directly; stringify it for readFile mock
+ // atomicWrite receives the data object directly; stringify it for tryReadFile mock
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
const result = await triggerLoop(loop.id);
expect(result).toEqual({ triggered: true });
});
it('throws when loop id does not exist in saved file', async () => {
- readFile.mockResolvedValue('[]');
+ tryReadFile.mockResolvedValue('[]');
await expect(triggerLoop('ghost-id')).rejects.toThrow('not found');
});
@@ -253,7 +252,7 @@ describe('loops.js', () => {
intervalMs: 30_000,
status: 'stopped'
}];
- readFile.mockResolvedValue(JSON.stringify(loopRecord));
+ tryReadFile.mockResolvedValue(JSON.stringify(loopRecord));
await expect(triggerLoop('test-stopped')).rejects.toThrow('not running');
});
});
@@ -269,9 +268,9 @@ describe('loops.js', () => {
runImmediately: false
});
- // atomicWrite receives the data object directly; stringify it for readFile mock
+ // atomicWrite receives the data object directly; stringify it for tryReadFile mock
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
// Make runPromptThroughProvider reject (replaces the old executeCliRun
// rejection path — same failure surface, new dispatcher).
@@ -297,9 +296,9 @@ describe('loops.js', () => {
runImmediately: false
});
- // atomicWrite receives the data object directly; stringify it for readFile mock
+ // atomicWrite receives the data object directly; stringify it for tryReadFile mock
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
mockCreateRun.mockRejectedValue(new Error('createRun blew up'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -324,9 +323,9 @@ describe('loops.js', () => {
runImmediately: false
});
- // atomicWrite receives the data object directly; stringify it for readFile mock
+ // atomicWrite receives the data object directly; stringify it for tryReadFile mock
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
const errors = [];
loopEvents.on('iteration:error', (data) => errors.push(data));
@@ -355,7 +354,7 @@ describe('loops.js', () => {
runImmediately: false,
});
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
const completes = [];
loopEvents.on('iteration:complete', (data) => completes.push(data));
@@ -411,9 +410,9 @@ describe('loops.js', () => {
runImmediately: false
});
- // atomicWrite receives the data object directly; stringify it for readFile mock
+ // atomicWrite receives the data object directly; stringify it for tryReadFile mock
const savedBefore = atomicWrite.mock.calls[0][1];
- readFile.mockResolvedValue(JSON.stringify(savedBefore));
+ tryReadFile.mockResolvedValue(JSON.stringify(savedBefore));
// Should not throw — the `let` fix allows provider reassignment
let threw = false;
diff --git a/server/services/malwareScanReports.js b/server/services/malwareScanReports.js
index 8a2ec4a10d..d0347852ae 100644
--- a/server/services/malwareScanReports.js
+++ b/server/services/malwareScanReports.js
@@ -1,8 +1,7 @@
/** Malware scan report lifecycle shared by CoS completion and Brain links. */
-import { readFile } from 'fs/promises';
import { join } from 'path';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, tryReadFile } from '../lib/fileUtils.js';
const REPORT_ID_RE = /^[a-f0-9-]{36}$/i;
const VERDICTS = new Set(['CLEAN', 'CAUTION', 'DANGEROUS']);
@@ -28,7 +27,7 @@ export async function prepareScanReportDirectory() {
export async function getScanReport(reportId) {
const path = reportPathForId(reportId);
- return path ? readFile(path, 'utf8').catch(() => null) : null;
+ return path ? tryReadFile(path) : null;
}
export async function finalizeMalwareScan({ agentId, task, success }) {
diff --git a/server/services/socket.js b/server/services/socket.js
index ea3d790931..333fec3473 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -270,109 +270,120 @@ export function initSocket(io) {
// Handle log streaming requests
socket.on('logs:subscribe', async (rawData) => {
- const data = validateSocketData(logsSubscribeSchema, rawData, socket, 'logs:subscribe');
- if (!data) return;
- const { processName, lines, appId } = data;
- const key = streamKey(socket.id, processName);
-
- // Clean up only this process's existing stream, then claim this request.
- // Claiming AFTER the cleanup bump is what makes this generation current.
- cleanupStream(key);
- const generation = bumpStreamGeneration(key);
-
- // 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)
- .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;
- });
- }
-
- // The await above yields, so a disconnect, an unsubscribe, or a newer
- // subscribe may have landed in the meantime. Bail if this socket is gone
- // rather than spawning an orphan `pm2 logs` nothing will ever clean up.
- if (socket.disconnected) return;
- // 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(key) !== generation) return;
-
- console.log(`📜 Log stream started: ${processName} (${lines} lines)`);
-
- // Spawn pm2 logs with --raw flag
- // buildEnv(null) is the default-home case, so this is unconditional —
- // matching every other buildEnv call site in pm2.js.
- const logProcess = spawnPm2(
- ['logs', processName, '--raw', '--lines', String(lines)],
- { env: buildEnv(pm2Home) }
- );
-
- activeStreams.set(key, { process: logProcess, processName });
-
- let buffer = '';
-
- logProcess.stdout.on('data', (data) => {
- buffer += data.toString();
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
- lines.forEach(line => {
- if (line.trim()) {
- socket.emit('logs:line', {
- line,
- type: 'stdout',
- timestamp: Date.now(),
- processName
+ // Declared outside the try so the catch can echo it back: the client's
+ // logs:error listener filters on processName, so an error emitted
+ // without it is silently dropped and the log panel just hangs.
+ let processName;
+ try {
+ const data = validateSocketData(logsSubscribeSchema, rawData, socket, 'logs:subscribe');
+ if (!data) return;
+ let lines, appId;
+ ({ processName, lines, appId } = data);
+ const key = streamKey(socket.id, processName);
+
+ // Clean up only this process's existing stream, then claim this request.
+ // Claiming AFTER the cleanup bump is what makes this generation current.
+ cleanupStream(key);
+ const generation = bumpStreamGeneration(key);
+
+ // 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)
+ .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;
+ });
+ }
+
+ // The await above yields, so a disconnect, an unsubscribe, or a newer
+ // subscribe may have landed in the meantime. Bail if this socket is gone
+ // rather than spawning an orphan `pm2 logs` nothing will ever clean up.
+ if (socket.disconnected) return;
+ // 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(key) !== generation) return;
+
+ console.log(`📜 Log stream started: ${processName} (${lines} lines)`);
+
+ // Spawn pm2 logs with --raw flag
+ // buildEnv(null) is the default-home case, so this is unconditional —
+ // matching every other buildEnv call site in pm2.js.
+ const logProcess = spawnPm2(
+ ['logs', processName, '--raw', '--lines', String(lines)],
+ { env: buildEnv(pm2Home) }
+ );
+
+ activeStreams.set(key, { process: logProcess, processName });
+
+ let buffer = '';
+
+ logProcess.stdout.on('data', (data) => {
+ buffer += data.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ lines.forEach(line => {
+ if (line.trim()) {
+ socket.emit('logs:line', {
+ line,
+ type: 'stdout',
+ timestamp: Date.now(),
+ processName
+ });
+ }
+ });
});
- });
- logProcess.stderr.on('data', (data) => {
- buffer += data.toString();
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
- lines.forEach(line => {
- if (line.trim()) {
- socket.emit('logs:line', {
- line,
- type: 'stderr',
- timestamp: Date.now(),
- processName
- });
- }
+ logProcess.stderr.on('data', (data) => {
+ buffer += data.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ lines.forEach(line => {
+ if (line.trim()) {
+ socket.emit('logs:line', {
+ line,
+ type: 'stderr',
+ timestamp: Date.now(),
+ processName
+ });
+ }
+ });
});
- });
- logProcess.on('error', (err) => {
- socket.emit('logs:error', { error: err.message, processName });
- });
+ logProcess.on('error', (err) => {
+ socket.emit('logs:error', { error: err.message, processName });
+ });
- logProcess.on('close', (code) => {
- // A SIGTERM'd predecessor's `close` fires asynchronously — after the
- // replacement stream has already registered — so an unscoped
- // `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 (activeStreams.get(key)?.process !== logProcess) return;
- socket.emit('logs:close', { code, processName });
- activeStreams.delete(key);
- streamGenerations.delete(key);
- });
+ logProcess.on('close', (code) => {
+ // A SIGTERM'd predecessor's `close` fires asynchronously — after the
+ // replacement stream has already registered — so an unscoped
+ // `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 (activeStreams.get(key)?.process !== logProcess) return;
+ socket.emit('logs:close', { code, processName });
+ activeStreams.delete(key);
+ streamGenerations.delete(key);
+ });
- socket.emit('logs:subscribed', { processName, timestamp: Date.now() });
+ socket.emit('logs:subscribed', { processName, timestamp: Date.now() });
+ } catch (err) {
+ const message = err?.message ?? String(err);
+ console.error(`❌ Socket handler error [logs:subscribe]: ${message}`);
+ socket.emit('logs:error', { error: message, processName });
+ }
});
// Handle unsubscribe
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index c813b40582..142bbbc177 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -451,6 +451,24 @@ describe('socket.js — initSocket', () => {
expect(opts.env.PM2_HOME).toBe('/opt/example/.pm2');
});
+ // The handler's try/catch exists so a synchronous throw can't become a
+ // process-killing unhandled rejection. But the client's logs:error
+ // listener (client/src/hooks/useProcessLogs.js) drops any event whose
+ // processName doesn't match the panel's, so an error emitted without it
+ // is invisible and the panel just hangs — the failure the catch was
+ // added to prevent, in a quieter form.
+ it('reports the failing process name when the log stream throws', async () => {
+ const socket = makeSocket('logs-spawn-throws');
+ io.connect(socket);
+ vi.mocked(spawnPm2).mockImplementationOnce(() => { throw new Error('pm2 missing'); });
+
+ await socket.handlers['logs:subscribe']({ processName: 'game', lines: 100 });
+
+ const err = socket.emitted.find(([event]) => event === 'logs:error');
+ expect(err).toBeDefined();
+ expect(err[1]).toEqual({ error: 'pm2 missing', processName: 'game' });
+ });
+
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);