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
refactor: converge media-gen splitters onto createLineReader (#2463)
Adam Eivycb9994225f20
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1f1ae0da1e..687714d321 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changes+- **Media-gen marker parsers converged onto `createLineReader` too (#2463, follow-up to #2392).** The two remaining hand-copied per-chunk splitters — `imageGen/local.js` (stderr + stdout) and `videoGen/local.js` (stderr, plus a stdout `'\n'`-carry that never flushed the last line and decoded each chunk independently) — parsed `STAGE:`/`STATUS:`/`DOWNLOAD:` protocol markers with no carry buffer, so a marker or multibyte char split across a pipe chunk boundary could tear a progress event. Both services now route line parsing through `server/lib/streamLines.js#createLineReader` (StringDecoder-backed, carry across chunks, `flush()` on `close`), while the render-critical machinery is left exactly as-is: idle-stall + completion watchdogs still fire on the same signals (`resetIdleStallTimer` stays in the per-chunk `data` handler; the videoGen flush runs *before* the watchdog clears so a final result-JSON line can't re-arm a stray SIGKILL), the imageGen `stderrBuffer` error tail keeps accumulating raw chunk text, and the stdout JSON `video_path`/result capture is unchanged. Behavior-preserving; adds a chunk-boundary test proving a marker split across two chunks parses as one event.+- **Duplicated child-process stream/discovery helpers converged into shared lib modules (#2392).** Three hand-copied "split a stdout/stderr chunk stream into lines with a carry buffer" implementations (`ytdlpAudioImport.js`, `videoDownload.js`, `hfDownload.js`) had already drifted — only hfDownload's copy flushed the final unterminated line. They now share `server/lib/streamLines.js#createLineReader(onLine, {splitRe?, maxCarry?})`, which carries the partial trailing line across chunks, exposes a `flush()` for the last newline-less line (so the two yt-dlp paths stop dropping it — and skip the flush on cancel so a partial marker can't fire a stray progress frame), clamps the carry buffer against a newline-less runaway stream, and takes a `splitRe: /[\r\n]+/` option for bare-`\r` torch/tqdm progress redraws. The four bare-`\r` progress-splitter siblings (`midiRuntime.js`, `videoGen.js`, `music.js` install-log routes, and `pythonSetup.js#streamSpawn`) are converged onto the same reader with that option, so a progress line split across a chunk boundary is no longer torn. Separately, the inline `which`/`where` PATH probes in `ytdlp.js`, `ffmpeg.js` (×2), `pythonSetup.js`, and voice `bootstrap.js` are replaced by a single `whichFirst(name)` in `server/lib/processEnv.js` (Malloc-stripped env, 5s timeout, first-line result). The vendored `aiToolkit/providers.js` copy is intentionally left alone (self-contained by design). Behavior-preserving; both new helpers are unit-tested.- **Runtime/venv install SSE flows now log to the server console too, matching the HF model-download logging (#2432).** The image/video/MuScriptor runtime installers (spawning `setup-image-video.sh`), the FLUX.2 venv bootstrap, and the local image-gen pip installer streamed multi-GB pip/git progress only to the browser via SSE — a headless / PM2 log had no record the install ever ran (the same gap `startHfDownloadStream` had already closed for HF model downloads). A new shared `createInstallLogger` chokepoint (`server/lib/installLogger.js`) now emits a single-line START, throttled heartbeats + `stage` milestones, and the OUTCOME (success/fail/cancel) with installer name, target, and elapsed time — without echoing every raw pip/bash line. Wired into all five install spawn sites in `music.js`, `videoGen.js`, `imageGen.js` (FLUX.2 venv + local pip install), and `midiRuntime.js`.diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 933f0e1f28..8ec304a825 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -29,6 +29,7 @@ import { hfTokenEnv } from '../../lib/hfToken.js';import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';import { safeChildProcessEnv } from '../../lib/processEnv.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';+import { createLineReader } from '../../lib/streamLines.js';import { IMAGE_GEN_MODE } from './modes.js';import { computePixelDelta } from './regen.js';import { parseByteProgress, formatDownloadMessage } from '../videoGen/generateVideoHelpers.js';@@ -699,22 +700,30 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =};const shortId = jobId.slice(0, 8);+ // Route marker parsing through per-stream line readers so a STAGE:/STATUS:/+ // DOWNLOAD: marker (or a multibyte char) split across a pipe chunk boundary+ // can't tear a progress event. Each reader carries the partial trailing line+ // across chunks and is flushed on 'close'.+ const stderrReader = createLineReader((line) => {+ const trimmed = line.trim();+ if (!handleLine(line) && trimmed) console.log(`🐍 [${shortId}] ${trimmed}`);+ }, { splitRe: /[\n\r]+/ });+ const stdoutReader = createLineReader((line) => {+ const trimmed = line.trim();+ if (!handleLine(line) && trimmed) console.log(`🐍-out [${shortId}] ${trimmed}`);+ }, { splitRe: /[\n\r]+/ });proc.stderr.on('data', (chunk) => {+ // The bounded error-tail stays on the raw chunk text — the failure path+ // slices its last N bytes for context independently of line parsing.const text = chunk.toString();stderrBuffer += text;if (stderrBuffer.length > STDERR_TAIL_BYTES) {stderrBuffer = stderrBuffer.slice(-STDERR_TAIL_BYTES);}- for (const line of text.split(/[\n\r]+/)) {- const trimmed = line.trim();- if (!handleLine(line) && trimmed) console.log(`🐍 [${shortId}] ${trimmed}`);- }+ stderrReader.push(chunk);});proc.stdout.on('data', (chunk) => {- for (const line of chunk.toString().split(/[\n\r]+/)) {- const trimmed = line.trim();- if (!handleLine(line) && trimmed) console.log(`🐍-out [${shortId}] ${trimmed}`);- }+ stdoutReader.push(chunk);});proc.on('close', async (code, signal) => {@@ -726,6 +735,11 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =finalized = true;activeProcess = null;activeJob = null;+ // Emit any final unterminated marker line each stream wrote without a+ // trailing newline (a SIGKILL mid-write, or a progress bar whose last+ // redraw never terminated) before finalizing the job.+ stderrReader.flush();+ stdoutReader.flush();if (watcher) { try { watcher.close(); } catch { /* ignore */ } }rm(stepwiseDir, { recursive: true, force: true }).catch(() => {});if (code !== 0) {diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex fb2bd47bed..fafaaa6c8b 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -20,6 +20,7 @@ import { promisify } from 'util';import { ensureDir, PATHS, UUID_RE } from '../../lib/fileUtils.js';import { spawnDetached } from '../../lib/detachedSpawn.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';+import { createLineReader } from '../../lib/streamLines.js';import { ServerError } from '../../lib/errorHandler.js';import { videoGenEvents } from './events.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';@@ -1001,7 +1002,6 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mcloseJobAfterDelay(jobs, jobId);});- let outputBuf = '';let missingPyModule = null;// The python child's STATUS:/STAGE:/DOWNLOAD:/tqdm → SSE-frame parser lives@@ -1010,51 +1010,62 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// logging), false for an unhandled line worth raw-logging.const handleLine = makeVideoGenLineHandler({ job, jobId, pythonNoiseRe: PYTHON_NOISE_RE });+ // Per-stream line readers carry the partial trailing line across chunk+ // boundaries and decode through a StringDecoder, so a marker (or multibyte+ // char) split across a pipe chunk can't tear an event — and the final+ // unterminated line is emitted on 'close' via flush().+ const stdoutReader = createLineReader((raw) => {+ const line = raw.trim();+ if (!line) return;+ // mlx_video emits one JSON line on stdout when finished — capture it+ // for the result metadata; otherwise raw-log so we can debug failures.+ try {+ const parsed = JSON.parse(line);+ if (parsed.video_path) {+ job.resultJson = parsed;+ // The result JSON is the strongest "work is done" signal — arm the+ // watchdog so a post-completion teardown hang can't wedge the job.+ armCompletionWatchdog();+ }+ return;+ } catch { /* not JSON */ }+ // Some runtimes don't print the result JSON but do log the final+ // decode+mux line right before they should exit — treat it the same way.+ if (MUXING_DONE_RE.test(line)) armCompletionWatchdog();+ console.log(`🐍-out [${jobId.slice(0, 8)}] ${line}`);+ });+ const stderrReader = createLineReader((raw) => {+ // Record the root-cause module only — downstream imports in the same+ // traceback raise the same error against later names.+ if (!missingPyModule) {+ const m = raw.match(MODULE_NOT_FOUND_RE);+ if (m) missingPyModule = m[1];+ }+ if (!handleLine(raw)) console.log(`🐍 [${jobId.slice(0, 8)}] ${raw.trim()}`);+ }, { splitRe: /[\n\r]+/ });+proc.stdout.on('data', (chunk) => {// Any output proves the render is progressing — restart the idle-stall// countdown before parsing so a slow-but-alive render is never killed.resetIdleStallTimer();- outputBuf += chunk.toString();- const lines = outputBuf.split('\n');- outputBuf = lines.pop();- for (const raw of lines) {- const line = raw.trim();- if (!line) continue;- // mlx_video emits one JSON line on stdout when finished — capture it- // for the result metadata; otherwise raw-log so we can debug failures.- try {- const parsed = JSON.parse(line);- if (parsed.video_path) {- job.resultJson = parsed;- // The result JSON is the strongest "work is done" signal — arm the- // watchdog so a post-completion teardown hang can't wedge the job.- armCompletionWatchdog();- }- continue;- } catch { /* not JSON */ }- // Some runtimes don't print the result JSON but do log the final- // decode+mux line right before they should exit — treat it the same way.- if (MUXING_DONE_RE.test(line)) armCompletionWatchdog();- console.log(`🐍-out [${jobId.slice(0, 8)}] ${line}`);- }+ stdoutReader.push(chunk);});proc.stderr.on('data', (chunk) => {// Weight-load / kernel-compile progress often streams to stderr (loguru,// tqdm) long before the first stdout line — count it as liveness too.resetIdleStallTimer();- for (const raw of chunk.toString().split(/[\n\r]+/)) {- // Record the root-cause module only — downstream imports in the same- // traceback raise the same error against later names.- if (!missingPyModule) {- const m = raw.match(MODULE_NOT_FOUND_RE);- if (m) missingPyModule = m[1];- }- if (!handleLine(raw)) console.log(`🐍 [${jobId.slice(0, 8)}] ${raw.trim()}`);- }+ stderrReader.push(chunk);});proc.on('close', async (code, signal) => {+ // Flush any final unterminated line each stream buffered (the JSON result,+ // a missing-module trace) BEFORE clearing the watchdogs, so a flush that+ // captures the result JSON and re-arms the completion watchdog is then+ // immediately cancelled by clearCompletionWatchdog() rather than firing a+ // stray SIGKILL during teardown.+ stdoutReader.flush();+ stderrReader.flush();clearCompletionWatchdog();clearIdleStallTimer();activeProcess = null;diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex d396b6083a..ae28607e05 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -1516,3 +1516,106 @@ describe('resolveVideoModel — live registry lookup (#2124 no-restart add)', ()expect(resolveVideoModel('hf-newly-added')?.id).toBe('hf-newly-added');});});++describe('generateVideo — chunk-boundary marker parsing (#2463)', () => {+ // Controllable child that never exits on its own, exposing its stdout/stderr+ // 'data' listeners and 'close' handler so the test can feed pipe chunks on+ // arbitrary byte boundaries and assert markers are stitched into one event.+ function makeControllableProc() {+ const listeners = {};+ let stdoutData = null;+ let stderrData = null;+ const proc = {+ pid: 5150,+ exitCode: null,+ signalCode: null,+ killed: false,+ stdout: { on: vi.fn((event, fn) => { if (event === 'data') stdoutData = fn; }) },+ stderr: { on: vi.fn((event, fn) => { if (event === 'data') stderrData = fn; }) },+ on(event, fn) { listeners[event] = fn; return proc; },+ kill: vi.fn((signal) => { proc.killed = true; proc.signalCode = signal; }),+ };+ return {+ proc,+ // Pass raw Buffers so the reader's StringDecoder path is exercised.+ emitStdout: (buf) => stdoutData?.(Buffer.isBuffer(buf) ? buf : Buffer.from(buf)),+ emitStderr: (buf) => stderrData?.(Buffer.isBuffer(buf) ? buf : Buffer.from(buf)),+ fireClose: (code, signal) => listeners.close?.(code, signal),+ };+ }++ const statusFrames = (broadcastSse, message) =>+ broadcastSse.mock.calls.filter((c) => c[1]?.type === 'status' && c[1]?.message === message);++ beforeEach(() => { vi.useFakeTimers(); });+ afterEach(() => { vi.useRealTimers(); });++ async function startRender(jobId, ctrl) {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ vi.mocked(spawnDetached).mockImplementationOnce(async () => ctrl.proc);+ generateVideo({+ jobId,+ pythonPath: '/usr/bin/python3',+ modelId: 'ltx2_unified',+ prompt: 'boundary test',+ width: 512, height: 512, numFrames: 25, fps: 24,+ mode: 'text',+ });+ // Let generateVideo await spawnDetached and register the stream handlers.+ await vi.advanceTimersByTimeAsync(0);+ }++ it('stitches a STATUS marker split across two stderr chunks into one event', async () => {+ const { broadcastSse } = await import('../../lib/sseUtils.js');+ const ctrl = makeControllableProc();+ await startRender('boundary-stderr-split', ctrl);++ // The `STATUS:Loading model` marker arrives torn across a pipe boundary.+ ctrl.emitStderr('STATUS:Loading ');+ // First half has no line terminator → carried, nothing emitted yet.+ expect(statusFrames(vi.mocked(broadcastSse), 'Loading model')).toHaveLength(0);+ expect(statusFrames(vi.mocked(broadcastSse), 'Loading')).toHaveLength(0);++ ctrl.emitStderr('model\n');+ // The completed line is parsed exactly once as the full marker.+ expect(statusFrames(vi.mocked(broadcastSse), 'Loading model')).toHaveLength(1);+ });++ it('stitches a multibyte codepoint split across two stdout chunks (result JSON captured)', async () => {+ const { videoGenEvents } = await import('./events.js');+ const ctrl = makeControllableProc();+ const completed = [];+ const onCompleted = (e) => completed.push(e);+ videoGenEvents.on('completed', onCompleted);+ await startRender('boundary-stdout-multibyte', ctrl);++ // "café" (é = 0xC3 0xA9) — split the 2-byte codepoint across the boundary.+ const json = Buffer.from('{"video_path": "/data/videos/café.mp4"}\n', 'utf8');+ const cut = json.indexOf(0xa9); // byte AFTER the 0xC3 lead byte+ ctrl.emitStdout(json.subarray(0, cut)); // ends mid-codepoint+ ctrl.emitStdout(json.subarray(cut)); // completes it + the newline+ ctrl.fireClose(0, null);+ await vi.advanceTimersByTimeAsync(0);++ videoGenEvents.off('completed', onCompleted);+ // A torn decode would have yielded replacement chars and failed JSON.parse,+ // so no result would be captured and the job would not complete cleanly.+ expect(completed).toHaveLength(1);+ });++ it('flushes a final unterminated STATUS marker on close', async () => {+ const { broadcastSse } = await import('../../lib/sseUtils.js');+ const ctrl = makeControllableProc();+ await startRender('boundary-flush-on-close', ctrl);++ // Marker written without a trailing newline (a killed child mid-write).+ ctrl.emitStderr('STATUS:Finalizing');+ // Nothing emitted while it sits in the carry buffer…+ expect(statusFrames(vi.mocked(broadcastSse), 'Finalizing')).toHaveLength(0);++ ctrl.fireClose(0, null);+ await vi.advanceTimersByTimeAsync(0);+ // …the reader's flush() on 'close' emits the final line exactly once.+ expect(statusFrames(vi.mocked(broadcastSse), 'Finalizing')).toHaveLength(1);+ });+});