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: give pm2 log stdout and stderr their own line buffers (#6637)
[._.]/ Adam Eivy44a62e141544
diff --git a/server/sockets/logs.js b/server/sockets/logs.jsindex a702df2c16..e4051f821a 100644--- a/server/sockets/logs.js+++ b/server/sockets/logs.js@@ -102,39 +102,38 @@ export const registerLogHandlers = (socket, _io) => {);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- });+ // One reader per stream. stdout and stderr are independent EventEmitters+ // on the same child, so a single shared tail buffer lets a chunk from one+ // stream be spliced onto the other's partial line and emitted under the+ // wrong `type` — unrecoverably, since the original two lines can no+ // longer be separated. A closure per stream removes the shared state.+ const makeLineReader = (type) => {+ let buffer = '';+ const send = (line) => {+ if (!line.trim()) return;+ socket.emit('logs:line', { line, type, timestamp: Date.now(), processName });+ };+ return {+ push(chunk) {+ buffer += chunk.toString();+ const lines = buffer.split('\n');+ buffer = lines.pop() || '';+ lines.forEach(send);+ },+ flush() {+ const remainder = buffer;+ buffer = '';+ send(remainder);}- });- });+ };+ };++ const stdoutReader = makeLineReader('stdout');+ const stderrReader = makeLineReader('stderr');++ logProcess.stdout.on('data', (data) => stdoutReader.push(data));+ logProcess.stderr.on('data', (data) => stderrReader.push(data));logProcess.on('error', (err) => {socket.emit('logs:error', { error: err.message, processName });@@ -145,6 +144,10 @@ export const registerLogHandlers = (socket, _io) => {// replacement stream has already registered — so it must not delete the// live replacement or emit a misleading close frame.if (activeStreams.get(key)?.process !== logProcess) return;+ // A crashing process leaves its last line unterminated; flush both tails+ // before the close frame so it arrives in order instead of being dropped.+ stdoutReader.flush();+ stderrReader.flush();socket.emit('logs:close', { code, processName });activeStreams.delete(key);streamGenerations.delete(key);diff --git a/server/sockets/logs.test.js b/server/sockets/logs.test.jsnew file mode 100644index 0000000000..967bac1414--- /dev/null+++ b/server/sockets/logs.test.js@@ -0,0 +1,96 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { EventEmitter } from 'node:events';++// `pm2 logs` writes app output to stdout and its own diagnostics to stderr, on+// two independent EventEmitters of the SAME child. The handler reassembles+// lines from chunk boundaries, so the contract this suite pins is that neither+// stream can ever see, splice onto, or steal the other's partial tail — and+// that a final line with no trailing newline (what a crashing process leaves)+// still reaches the client before `logs:close`.++vi.mock('../services/pm2.js', () => ({+ buildEnv: vi.fn(() => ({})),+ spawnPm2: vi.fn(),+}));+vi.mock('../services/apps.js', () => ({+ getAppById: vi.fn(async () => null),+ resolvePm2HomeForProcess: vi.fn(async () => null),+}));++import { spawnPm2 } from '../services/pm2.js';+import { registerLogHandlers, cleanupSocketStreams } from './logs.js';++const makeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.kill = vi.fn();+ return child;+};++const subscribe = async (processName = 'example-app') => {+ 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 }),+ };+ const child = makeChild();+ spawnPm2.mockReturnValue(child);+ registerLogHandlers(socket, { emit: () => {} });+ await handlers.get('logs:subscribe')({ processName, lines: 100 });+ return { socket, child, emitted, processName };+};++const linesOf = (emitted) => emitted+ .filter((e) => e.event === 'logs:line')+ .map((e) => ({ line: e.payload.line, type: e.payload.type }));++beforeEach(() => {+ vi.clearAllMocks();+ cleanupSocketStreams('socket-test');+});++describe('logs:subscribe line reassembly', () => {+ it('does not splice a stderr chunk onto a partial stdout line', async () => {+ const { child, emitted } = await subscribe();++ // stdout chunk ends mid-line — its tail must stay private to stdout.+ child.stdout.emit('data', Buffer.from('GET /api/app'));+ child.stderr.emit('data', Buffer.from('[PM2] Log rotation\n'));+ child.stdout.emit('data', Buffer.from(' 200 OK\n'));++ expect(linesOf(emitted)).toEqual([+ { line: '[PM2] Log rotation', type: 'stderr' },+ { line: 'GET /api/app 200 OK', type: 'stdout' },+ ]);+ });++ it('emits a trailing line with no newline before logs:close', async () => {+ const { child, emitted } = await subscribe();++ child.stdout.emit('data', Buffer.from('fatal: crashed'));+ child.emit('close', 1);++ const events = emitted.filter((e) => e.event === 'logs:line' || e.event === 'logs:close');+ expect(events).toEqual([+ { event: 'logs:line', payload: expect.objectContaining({ line: 'fatal: crashed', type: 'stdout' }) },+ { event: 'logs:close', payload: { code: 1, processName: 'example-app' } },+ ]);+ });++ it('flushes each stream\'s own tail on close', async () => {+ const { child, emitted } = await subscribe();++ child.stdout.emit('data', Buffer.from('out tail'));+ child.stderr.emit('data', Buffer.from('err tail'));+ child.emit('close', 0);++ expect(linesOf(emitted)).toEqual([+ { line: 'out tail', type: 'stdout' },+ { line: 'err tail', type: 'stderr' },+ ]);+ });+});