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 child-process stream/discovery helpers into shared lib (#2392)
Adam Eivyc87f5f41e127
diff --git a/server/lib/README.md b/server/lib/README.mdindex a454a77223..49b45c5e3a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -57,6 +57,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. || `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. || `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |+| `streamLines.js` | `createLineReader(onLine, {splitRe?, maxCarry?})` — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across `data` chunks and `flush()`es the final unterminated line on `close`; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). `splitRe: /[\r\n]+/` handles torch/tqdm bare-`\r` progress redraws. || `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). || `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. || `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). |@@ -152,7 +153,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. || `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. || `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |-| `processEnv.js` | `stripDebugMallocEnv(env)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. |+| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (Malloc-stripped env, 5s timeout) returning the absolute binary path or `null`; the shared discovery probe behind `findYtDlp`/`findFfmpeg`/`detectPython`/voice `which`. || `pythonSetup.js` | Python venv / runner setup helpers. || `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. |diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex ea26b7d83e..efeb7fddbc 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -13,7 +13,7 @@ import { join, resolve as resolvePath, sep as PATH_SEP, dirname } from 'path';import { randomUUID } from 'crypto';import { promisify } from 'util';import { ensureDir, PATHS } from './fileUtils.js';-import { safeChildProcessEnv } from './processEnv.js';+import { safeChildProcessEnv, whichFirst } from './processEnv.js';const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';@@ -40,9 +40,7 @@ export const findFfmpeg = async () => {for (const p of candidates) {if (existsSync(p)) { cachedFfmpegPath = p; return p; }}- const cmd = IS_WIN ? 'where' : 'which';- const { stdout } = await execFileAsync(cmd, ['ffmpeg'], { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));- cachedFfmpegPath = stdout.trim().split(/\r?\n/)[0] || null;+ cachedFfmpegPath = await whichFirst('ffmpeg');return cachedFfmpegPath;};@@ -135,9 +133,7 @@ export const findFfprobe = async () => {// the casing question entirely.const probe = join(dirname(ffmpeg), IS_WIN ? 'ffprobe.exe' : 'ffprobe');if (existsSync(probe)) { cachedFfprobePath = probe; return probe; }- const cmd = IS_WIN ? 'where' : 'which';- const { stdout } = await execFileAsync(cmd, ['ffprobe'], { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));- cachedFfprobePath = stdout.trim().split(/\r?\n/)[0] || null;+ cachedFfprobePath = await whichFirst('ffprobe');return cachedFfprobePath;};diff --git a/server/lib/hfDownload.js b/server/lib/hfDownload.jsindex 6cd7c727e7..a91220a062 100644--- a/server/lib/hfDownload.js+++ b/server/lib/hfDownload.js@@ -27,6 +27,7 @@ import {import { PATHS } from './fileUtils.js';import { getHfTokenInfo } from './hfToken.js';import { safeChildProcessEnv } from './processEnv.js';+import { createLineReader } from './streamLines.js';import { getSettings } from '../services/settings.js';const HELPER_SCRIPT = join(PATHS.root, 'scripts', 'hf_download_repo.py');@@ -150,19 +151,12 @@ export function downloadHfRepo({ repo, revision = null, onEvent }) {// Line-buffer across chunks so a STAGE:/USER_ERROR: marker split across// pipe boundaries isn't truncated and routed to the generic log path- // (which loses the typed-error / progress wire shape).- let stdoutBuf = '';- let stderrBuf = '';- const flushChunk = (chunk, key) => {- const buf = (key === 'stdout' ? stdoutBuf : stderrBuf) + chunk.toString();- const lines = buf.split(/\r?\n/);- const trailing = lines.pop();- if (key === 'stdout') stdoutBuf = trailing;- else stderrBuf = trailing;- for (const l of lines) handleLine(l);- };- proc.stderr.on('data', (chunk) => flushChunk(chunk, 'stderr'));- proc.stdout.on('data', (chunk) => flushChunk(chunk, 'stdout'));+ // (which loses the typed-error / progress wire shape). Separate reader+ // per stream — a shared carry buffer would splice stdout onto stderr.+ const stdoutReader = createLineReader(handleLine);+ const stderrReader = createLineReader(handleLine);+ proc.stderr.on('data', stderrReader.push);+ proc.stdout.on('data', stdoutReader.push);proc.on('error', (err) => {const msg = `Failed to spawn python: ${err.message}`;onEvent({ type: 'error', message: msg, kind: 'spawn_failed' });@@ -172,8 +166,8 @@ export function downloadHfRepo({ repo, revision = null, onEvent }) {// Flush any trailing partial line the python helper emitted without a// newline before exit (rare with line-buffered stderr but possible// when the process is SIGKILL'd mid-write).- if (stdoutBuf) { handleLine(stdoutBuf); stdoutBuf = ''; }- if (stderrBuf) { handleLine(stderrBuf); stderrBuf = ''; }+ stdoutReader.flush();+ stderrReader.flush();if (killed) {onEvent({ type: 'error', message: 'Cancelled', kind: 'cancelled' });return resolve({ ok: false, errorKind: 'cancelled', errorMessage: 'Cancelled' });diff --git a/server/lib/index.js b/server/lib/index.jsindex ee8c0d5fee..80bba12390 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -66,6 +66,7 @@ export * from './storyArc.js';export * from './styleGuide.js';export * from './storyBuilderIntegrity.js';export * from './storyBuilderSteps.js';+export * from './streamLines.js';// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for// back-compat — namespace it so the canonical scenePrompt export wins flat.export * as storyBible from './storyBible.js';diff --git a/server/lib/processEnv.js b/server/lib/processEnv.jsindex dce2c396f8..45057d4745 100644--- a/server/lib/processEnv.js+++ b/server/lib/processEnv.js@@ -10,6 +10,12 @@//// The Malloc* family is documented in libmalloc(3) and only affects macOS;// stripping the prefix is a no-op on Linux/Windows.+import { execFile } from 'child_process';+import { promisify } from 'util';++const execFileAsync = promisify(execFile);+const IS_WIN = process.platform === 'win32';+export function stripDebugMallocEnv(env) {return Object.fromEntries(Object.entries(env).filter(([k]) => !k.startsWith('Malloc'))@@ -19,3 +25,16 @@ export function stripDebugMallocEnv(env) {export function safeChildProcessEnv(extra = {}) {return stripDebugMallocEnv({ ...process.env, ...extra });}++// Resolve the first PATH hit for a binary via `which` (POSIX) / `where`+// (Windows) — the "is this system tool installed, and where?" probe copied+// inline across ytdlp/ffmpeg/pythonSetup/voice discovery. Returns the absolute+// path of the first match, or `null` when the binary isn't on PATH or the+// probe fails. Spawns through `safeChildProcessEnv()` (Malloc-stripped) with a+// 5s timeout; `where` can return several lines, so we take the first.+export async function whichFirst(name) {+ const cmd = IS_WIN ? 'where' : 'which';+ const { stdout } = await execFileAsync(cmd, [name], { env: safeChildProcessEnv(), timeout: 5000 })+ .catch(() => ({ stdout: '' }));+ return stdout.trim().split(/\r?\n/)[0] || null;+}diff --git a/server/lib/processEnv.test.js b/server/lib/processEnv.test.jsindex 64aa59cc53..5aeedadcaa 100644--- a/server/lib/processEnv.test.js+++ b/server/lib/processEnv.test.js@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest';-import { safeChildProcessEnv, stripDebugMallocEnv } from './processEnv.js';+import { basename } from 'path';+import { safeChildProcessEnv, stripDebugMallocEnv, whichFirst } from './processEnv.js';describe('stripDebugMallocEnv', () => {it('drops every key that starts with "Malloc"', () => {@@ -62,3 +63,25 @@ describe('safeChildProcessEnv', () => {}});});++describe('whichFirst', () => {+ // `node` (both `which node` and `where node`) is on PATH wherever this runs.+ it('resolves an on-PATH binary to an absolute path', async () => {+ const resolved = await whichFirst('node');+ expect(resolved).toBeTruthy();+ expect(basename(resolved).toLowerCase()).toContain('node');+ });++ it('returns the FIRST line when the probe reports several matches', async () => {+ // The contract is single-line: `where` on Windows can print several paths;+ // whichFirst must return exactly one, never a multi-line blob.+ const resolved = await whichFirst('node');+ expect(resolved).not.toContain('\n');+ expect(resolved).not.toContain('\r');+ });++ it('returns null for a binary that is not on PATH', async () => {+ const resolved = await whichFirst('portos-nonexistent-binary-xyz-2392');+ expect(resolved).toBeNull();+ });+});diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 80d67cdae4..52445fd6c8 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -4,7 +4,7 @@ import { arch, homedir, platform } from 'node:os';import { join } from 'node:path';import { promisify } from 'node:util';import { PATHS } from './fileUtils.js';-import { safeChildProcessEnv } from './processEnv.js';+import { safeChildProcessEnv, whichFirst } from './processEnv.js';const execFileAsync = promisify(execFile);const IS_WIN = platform() === 'win32';@@ -123,10 +123,7 @@ export async function detectPython() {if (match) return match;}if (present.length) return present[0];- const which = IS_WIN ? 'where' : 'which';- const name = IS_WIN ? 'python' : 'python3';- const { stdout } = await execFileAsync(which, [name], { timeout: 5000 }).catch(() => ({ stdout: '' }));- return stdout.trim().split(/\r?\n/)[0] || null;+ return whichFirst(IS_WIN ? 'python' : 'python3');}export async function detectArm64Python() {diff --git a/server/lib/streamLines.js b/server/lib/streamLines.jsnew file mode 100644index 0000000000..ba638119a3--- /dev/null+++ b/server/lib/streamLines.js@@ -0,0 +1,51 @@+// Buffered chunk→line splitter for child-process stdout/stderr streams.+//+// Node delivers a stream's 'data' chunks on arbitrary byte boundaries, so a+// single output line can arrive split across two chunks (or several lines can+// arrive in one chunk). `createLineReader` carries the partial trailing line+// between chunks and emits each COMPLETE line to `onLine`; call `flush()` on+// the process 'close'/'exit' event to emit any final line the child wrote+// without a trailing newline (a SIGKILL mid-write, or a progress bar that+// never terminated its last redraw). Flushing the tail is the drift this+// helper ends — hand-copied splitters (ytdlpAudioImport, videoDownload) were+// dropping that unterminated last line while hfDownload's copy alone flushed.+//+// Each stream needs its OWN reader: a shared carry buffer would splice a+// partial line from stdout onto a chunk from stderr and corrupt marker lines.+//+// `splitRe` defaults to `/\r?\n/` (newline-terminated lines). Pass+// `splitRe: /[\r\n]+/` for torch/tqdm-style progress bars that redraw the same+// line with a bare `\r` and no `\n`, so each redraw surfaces as its own line.++const DEFAULT_SPLIT_RE = /\r?\n/;+// Clamp so a stream that never emits a separator can't grow the carry buffer+// without bound (a runaway child writing megabytes with no newline). At the+// threshold the oversized carry is flushed as a line and the buffer reset.+const DEFAULT_MAX_CARRY = 1 << 20; // 1 MiB++export function createLineReader(onLine, { splitRe = DEFAULT_SPLIT_RE, maxCarry = DEFAULT_MAX_CARRY } = {}) {+ let carry = '';++ const push = (chunk) => {+ carry += chunk.toString();+ const lines = carry.split(splitRe);+ carry = lines.pop() ?? '';+ for (const line of lines) onLine(line);+ if (carry.length > maxCarry) {+ // Safety valve: no separator seen within maxCarry bytes. Emit what we+ // have as a line rather than buffer unbounded, then reset.+ const oversized = carry;+ carry = '';+ onLine(oversized);+ }+ };++ const flush = () => {+ if (carry.length === 0) return;+ const line = carry;+ carry = '';+ onLine(line);+ };++ return { push, flush };+}diff --git a/server/lib/streamLines.test.js b/server/lib/streamLines.test.jsnew file mode 100644index 0000000000..473dde5346--- /dev/null+++ b/server/lib/streamLines.test.js@@ -0,0 +1,88 @@+import { describe, it, expect } from 'vitest';+import { createLineReader } from './streamLines.js';++const collect = (opts) => {+ const lines = [];+ const reader = createLineReader((l) => lines.push(l), opts);+ return { lines, reader };+};++describe('createLineReader', () => {+ it('emits complete newline-terminated lines and holds the partial tail', () => {+ const { lines, reader } = collect();+ reader.push('alpha\nbeta\npar');+ expect(lines).toEqual(['alpha', 'beta']); // 'par' is still buffered+ reader.push('tial\n');+ expect(lines).toEqual(['alpha', 'beta', 'partial']);+ });++ it('joins a line split across two chunks', () => {+ const { lines, reader } = collect();+ reader.push('STAGE:down');+ reader.push('load:3/5\n');+ expect(lines).toEqual(['STAGE:download:3/5']);+ });++ it('handles \\r\\n (Windows) newlines with the default split', () => {+ const { lines, reader } = collect();+ reader.push('one\r\ntwo\r\n');+ expect(lines).toEqual(['one', 'two']);+ });++ it('flush() emits a final line written without a trailing newline', () => {+ const { lines, reader } = collect();+ reader.push('done-no-newline');+ expect(lines).toEqual([]); // nothing yet — no separator seen+ reader.flush();+ expect(lines).toEqual(['done-no-newline']);+ });++ it('flush() is a no-op when the buffer is empty or already drained', () => {+ const { lines, reader } = collect();+ reader.push('x\n');+ expect(lines).toEqual(['x']);+ reader.flush();+ reader.flush();+ expect(lines).toEqual(['x']); // no spurious empty-string line+ });++ it('does not emit an empty trailing line after a terminating newline until flushed', () => {+ const { lines, reader } = collect();+ reader.push('only\n');+ expect(lines).toEqual(['only']);+ reader.flush(); // carry is '' -> no-op+ expect(lines).toEqual(['only']);+ });++ it('supports splitRe: /[\\r\\n]+/ for bare-\\r progress redraws', () => {+ const { lines, reader } = collect({ splitRe: /[\r\n]+/ });+ reader.push('10%\r20%\r30%'); // no trailing separator — '30%' still redrawing+ expect(lines).toEqual(['10%', '20%']); // '30%' held until next \r or flush+ reader.flush();+ expect(lines).toEqual(['10%', '20%', '30%']);+ });++ it('collapses runs of separators with /[\\r\\n]+/ (no empty lines between redraws)', () => {+ const { lines, reader } = collect({ splitRe: /[\r\n]+/ });+ reader.push('a\r\n\r\nb\n');+ expect(lines).toEqual(['a', 'b']);+ });++ it('clamps the carry buffer when no separator arrives within maxCarry', () => {+ const { lines, reader } = collect({ maxCarry: 8 });+ reader.push('123456789'); // 9 chars, exceeds maxCarry of 8, no newline+ expect(lines).toEqual(['123456789']); // flushed as a safety-valve line+ reader.push('next\n');+ expect(lines).toEqual(['123456789', 'next']); // buffer reset cleanly+ });++ it('gives each stream reader an independent carry buffer', () => {+ const out = [];+ const stdout = createLineReader((l) => out.push(`o:${l}`));+ const stderr = createLineReader((l) => out.push(`e:${l}`));+ stdout.push('OUT-par');+ stderr.push('ERR-full\n');+ stdout.push('tial\n');+ expect(out).toEqual(['e:ERR-full', 'o:OUT-partial']);+ });+});diff --git a/server/lib/ytdlp.js b/server/lib/ytdlp.jsindex 60d1005c7e..a5365c6207 100644--- a/server/lib/ytdlp.js+++ b/server/lib/ytdlp.js@@ -5,12 +5,9 @@* or auto-install.*/-import { execFile } from 'child_process';import { existsSync } from 'fs';-import { promisify } from 'util';-import { safeChildProcessEnv } from './processEnv.js';+import { whichFirst } from './processEnv.js';-const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';let cachedYtDlpPath;@@ -22,8 +19,6 @@ export const findYtDlp = async () => {for (const p of candidates) {if (existsSync(p)) { cachedYtDlpPath = p; return p; }}- const cmd = IS_WIN ? 'where' : 'which';- const { stdout } = await execFileAsync(cmd, ['yt-dlp'], { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));- cachedYtDlpPath = stdout.trim().split(/\r?\n/)[0] || null;+ cachedYtDlpPath = await whichFirst('yt-dlp');return cachedYtDlpPath;};diff --git a/server/services/videoDownload.js b/server/services/videoDownload.jsindex 425acbe3fa..05278af0c8 100644--- a/server/services/videoDownload.js+++ b/server/services/videoDownload.js@@ -26,6 +26,7 @@ import { findFfmpeg, generateThumbnail, probeVideoDuration } from '../lib/ffmpegimport { findYtDlp } from '../lib/ytdlp.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';import { safeChildProcessEnv } from '../lib/processEnv.js';+import { createLineReader } from '../lib/streamLines.js';import { loadHistory, mutateVideoHistory } from './videoGen/history.js';import { deleteHistoryItem } from './videoGen/local.js';import { videoGenEvents } from './videoGen/events.js';@@ -231,24 +232,20 @@ export async function startVideoDownload(url) {broadcastSse(job, { type: 'progress', percent: 100, stage: line.slice(STAGE_PREFIX.length) });}};- // Separate buffers per stream — a shared buffer can complete a partial+ // Separate readers per stream — a shared buffer can complete a partial// line from one stream with a chunk from the other, corrupting a marker.- const makeLineReader = () => {- let buf = '';- return (chunk) => {- buf += chunk.toString();- const lines = buf.split(/\r?\n/);- buf = lines.pop();- lines.forEach(onLine);- };- };- proc.stdout.on('data', makeLineReader());- proc.stderr.on('data', makeLineReader()); // yt-dlp writes some progress/info lines to stderr too+ const stdoutReader = createLineReader(onLine);+ const stderrReader = createLineReader(onLine);+ proc.stdout.on('data', stdoutReader.push);+ proc.stderr.on('data', stderrReader.push); // yt-dlp writes some progress/info lines to stderr tooconst exit = await new Promise((resolve) => {proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));proc.on('close', (code, signal) => resolve({ code, signal }));});+ // Flush any final line written without a trailing newline before exit.+ stdoutReader.flush();+ stderrReader.flush();job.process = null;if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.jsindex 0b0a958970..546258cea0 100644--- a/server/services/voice/bootstrap.js+++ b/server/services/voice/bootstrap.js@@ -12,15 +12,14 @@ import { expandPath, piperVoiceTildePath, voiceHome, IS_WIN, PIPER_BIN_NAME } frimport { isToolCapable, isReasoningModel } from './llm.js';import { getProviderById } from '../providers.js';import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';+import { whichFirst } from '../../lib/processEnv.js';export const pexec = promisify(execFile);export const WHISPER_APP = 'portos-whisper';-export const which = async (bin) => {- const res = await pexec(IS_WIN ? 'where' : 'which', [bin]).catch(() => null);- return res?.stdout?.split(/\r?\n/)[0]?.trim() || null;-};+// Thin re-export of the shared PATH probe so voice callers keep the local name.+export const which = (bin) => whichFirst(bin);export const verifyBinaries = async (cfg) => {const piperLocal = join(voiceHome(), 'piper', PIPER_BIN_NAME);diff --git a/server/services/ytdlpAudioImport.js b/server/services/ytdlpAudioImport.jsindex 24ab087756..34d5d5a56f 100644--- a/server/services/ytdlpAudioImport.js+++ b/server/services/ytdlpAudioImport.js@@ -29,6 +29,7 @@ import { ServerError } from '../lib/errorHandler.js';import { findFfmpeg } from '../lib/ffmpeg.js';import { findYtDlp } from '../lib/ytdlp.js';import { safeChildProcessEnv } from '../lib/processEnv.js';+import { createLineReader } from '../lib/streamLines.js';const TITLE_PREFIX = 'PORTOS_TITLE:';// Custom progress markers via yt-dlp's `--progress-template`, rather than@@ -137,25 +138,21 @@ export async function downloadAudioToTempMp3({onProgress({ percent: 100, stage: line.slice(STAGE_PREFIX.length) });}};- // Separate buffers per stream — stdout and stderr chunks arrive+ // Separate readers per stream — stdout and stderr chunks arrive// independently, so a shared buffer can complete a partial line from one// stream with a chunk from the other, corrupting a marker line.- const makeLineReader = () => {- let buf = '';- return (chunk) => {- buf += chunk.toString();- const lines = buf.split(/\r?\n/);- buf = lines.pop();- lines.forEach(onLine);- };- };- proc.stdout.on('data', makeLineReader());- proc.stderr.on('data', makeLineReader()); // yt-dlp writes some progress/info lines to stderr too+ const stdoutReader = createLineReader(onLine);+ const stderrReader = createLineReader(onLine);+ proc.stdout.on('data', stdoutReader.push);+ proc.stderr.on('data', stderrReader.push); // yt-dlp writes some progress/info lines to stderr tooconst exit = await new Promise((resolve) => {proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));proc.on('close', (code, signal) => resolve({ code, signal }));});+ // Flush any final line written without a trailing newline before exit.+ stdoutReader.flush();+ stderrReader.flush();registerProcess(null);if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {