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
address review (agy): one line reader per stream, and fully detach the daemon
Adam Eivy3ec20503d755
diff --git a/server/lib/streamingSpawn.js b/server/lib/streamingSpawn.jsindex af8d7c40f8..2def8c01fb 100644--- a/server/lib/streamingSpawn.js+++ b/server/lib/streamingSpawn.js@@ -21,6 +21,7 @@import { spawn } from './childProcess.js';import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';+import { createLineReader } from './streamLines.js';/** Char budget for the recent-output tail attached to a failure message. */const TAIL_BUDGET = 1024;@@ -42,7 +43,6 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, envstdio: ['ignore', 'pipe', 'pipe'],}));- let buffer = '';let settled = false;const tail = []; // recent non-empty lines, capped by char budget for the error messagelet tailChars = 0;@@ -76,22 +76,23 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env}, timeoutMs): null;- const onData = (chunk) => {- buffer += chunk.toString();- let nl;- while ((nl = buffer.indexOf('\n')) !== -1) {- safeLine(buffer.slice(0, nl).trim());- buffer = buffer.slice(nl + 1);- }- };+ // ONE reader per stream — never a shared buffer. Chunks arrive on arbitrary+ // byte boundaries, so a single carry shared by stdout and stderr splices a+ // half-written stdout line onto the next stderr chunk: `npm install` writing+ // `added 42 ` and a warning arriving mid-line yields one corrupt line and+ // loses both real ones. (Inherited from the hand-rolled splitter this was+ // extracted from; `streamLines.js` carries the rule.)+ const stdoutReader = createLineReader((line) => safeLine(line.trim()));+ const stderrReader = createLineReader((line) => safeLine(line.trim()));- child.stdout?.on('data', onData);- child.stderr?.on('data', onData);+ child.stdout?.on('data', stdoutReader.push);+ child.stderr?.on('data', stderrReader.push);child.on('error', (err) => finish({ success: false, error: err.message }));// 'close' rather than 'exit': 'exit' can fire with stdio still buffered,// which would drop the very lines the failure message needs.child.on('close', (code) => {- safeLine(buffer.trim());+ stdoutReader.flush();+ stderrReader.flush();if (code === 0) return finish({ success: true });const detail = tail.join(' — ').trim();finish({ success: false, error: detail ? `exit ${code}: ${detail}` : `exited with code ${code}` });diff --git a/server/lib/streamingSpawn.test.js b/server/lib/streamingSpawn.test.jsindex 3efc6e5b27..4b73d9c9a6 100644--- a/server/lib/streamingSpawn.test.js+++ b/server/lib/streamingSpawn.test.js@@ -57,3 +57,22 @@ describe('runStreamingCommand', () => {expect(result).toEqual({ success: true });});});++describe('runStreamingCommand — stream separation', () => {+ it('keeps stdout and stderr lines intact when partial chunks interleave', async () => {+ // One buffer shared by both streams splices a half-written stdout line into+ // the next stderr chunk: the caller sees `OUT-ERR-one` and loses both real+ // lines. `server/lib/README.md` states the rule this pins — one line reader+ // per stream.+ const lines = [];+ const result = await runStreamingCommand(+ NODE,+ ['-e', 'process.stdout.write("OUT-"); process.stderr.write("ERR-"); process.stdout.write("one\\n"); process.stderr.write("two\\n")'],+ (line) => lines.push(line),+ );++ expect(result).toEqual({ success: true });+ expect(lines).toContain('OUT-one');+ expect(lines).toContain('ERR-two');+ });+});diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.jsindex 82ca3bccf9..d09e30f726 100644--- a/server/services/localRuntimeSetup.js+++ b/server/services/localRuntimeSetup.js@@ -52,6 +52,14 @@ const CONTROL_TIMEOUT_MS = 60 * 1000;* loads a multi-gigabyte MLX checkpoint before it binds, so this is sized for a* cold model load rather than for a socket coming up.*/+/**+ * Parked on a detached daemon's `error` once this module stops watching it. An+ * EventEmitter `error` with NO listener throws, which outside the request+ * lifecycle takes the PortOS process down — so the watchers are replaced, never+ * merely removed. Module-scope, so it closes over nothing.+ */+const IGNORE_ERROR = () => {};+const START_TIMEOUT_MS = 3 * 60 * 1000;const START_POLL_MS = 1_500;@@ -99,25 +107,36 @@ async function startDaemon({ command, args, endpoint, emit, isCancelled = () =>};child.stdout?.on('data', onData);child.stderr?.on('data', onData);+ // Outside the request lifecycle: an unhandled 'error' on a child is a process+ // crash, and the exit code is what turns "still waiting" into a real reason.+ const onError = (err) => { exited = `failed to start: ${err.message}`; };+ const onExit = (code, signal) => {+ if (exited === null) exited = `exited early (${signal || `code ${code}`})`;+ };+ child.on('error', onError);+ child.on('exit', onExit);/**- * Stop forwarding, but keep DRAINING: a daemon whose stdout pipe fills up- * blocks on its next write, and `resume()` on a listener-less stream discards- * what it reads. Dropping the listener also releases `emit`'s closure over the- * SSE response, which would otherwise be retained for the daemon's lifetime.+ * Detach from the daemon, which outlives this request.+ *+ * Keep DRAINING: a daemon whose stdout pipe fills up blocks on its next+ * write, and `resume()` on a listener-less stream discards what it reads.+ *+ * Drop EVERY listener, not just `onData`: they share one closure scope, so+ * any one of them left attached to a long-lived child pins that scope — and+ * `emit` in it — which holds the SSE response open for the daemon's whole+ * lifetime. `IGNORE_ERROR` takes the `error` slot back so a later crash+ * cannot throw on an emitter with no listener.*/const stopStreaming = () => {for (const stream of [child.stdout, child.stderr]) {stream?.off('data', onData);stream?.resume();}+ child.off('error', onError);+ child.off('exit', onExit);+ child.on('error', IGNORE_ERROR);child.unref();};- // Outside the request lifecycle: an unhandled 'error' on a child is a process- // crash, and the exit code is what turns "still waiting" into a real reason.- child.on('error', (err) => { exited = `failed to start: ${err.message}`; });- child.on('exit', (code, signal) => {- if (exited === null) exited = `exited early (${signal || `code ${code}`})`;- });const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.jsindex edc2f22b35..630daf2ff8 100644--- a/server/services/localRuntimeSetup.test.js+++ b/server/services/localRuntimeSetup.test.js@@ -42,6 +42,7 @@ const fakeChild = () => {stdout: stream(),stderr: stream(),on: vi.fn((event, fn) => { handlers[event] = fn; }),+ off: vi.fn(),unref: vi.fn(),emitEvent: (event, ...args) => handlers[event]?.(...args),};@@ -243,6 +244,37 @@ describe('runLocalRuntimeSetup', () => {expect(result).toMatchObject({ success: true, message: expect.stringContaining('http://127.0.0.1:8010/v1') });});+ it('detaches every listener from the daemon it leaves running', async () => {+ // The daemon outlives the request. Any listener still attached pins the+ // closure scope holding `emit` — and through it the SSE response — for the+ // daemon's whole lifetime. The `error` slot is REPLACED rather than left+ // empty: an EventEmitter `error` with no listener throws, and outside the+ // request lifecycle that takes the process down.+ const daemon = fakeChild();+ child.spawn.mockReturnValue(daemon);+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');+ probe.probeOpenAiModels+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValueOnce(unreachable)+ .mockResolvedValueOnce(reachable(['mtplx']))+ .mockResolvedValueOnce(reachable(['mtplx']));+ const restore = pinPlatform('darwin');++ await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });+ restore();++ const detached = daemon.off.mock.calls.map(([event]) => event);+ expect(detached).toContain('error');+ expect(detached).toContain('exit');+ for (const stream of [daemon.stdout, daemon.stderr]) {+ expect(stream.off).toHaveBeenCalledWith('data', expect.any(Function));+ // …and keep draining, so a full pipe can't block the daemon's next write.+ expect(stream.resume).toHaveBeenCalled();+ }+ // A no-op error listener is parked in place of the one that was removed.+ expect(daemon.on.mock.calls.filter(([event]) => event === 'error')).toHaveLength(2);+ });+it('reports a daemon that died on startup instead of waiting out the timeout', async () => {const daemon = fakeChild();child.spawn.mockReturnValue(daemon);