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

refactor: converge tqdm progress splitters onto createLineReader + skip flush on cancel (#2392)

Adam Eivy04211bd523bb
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 52445fd6c8..54b806923b 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -5,6 +5,7 @@ import { join } from 'node:path';
import { promisify } from 'node:util';
import { PATHS } from './fileUtils.js';
import { safeChildProcessEnv, whichFirst } from './processEnv.js';
+import { createLineReader } from './streamLines.js';
const execFileAsync = promisify(execFile);
const IS_WIN = platform() === 'win32';
@@ -445,15 +446,18 @@ function streamSpawn(bin, args, onLog, onProc) {
return new Promise((resolve) => {
const proc = spawn(bin, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
onProc(proc);
- const onChunk = (chunk) => {
- for (const line of chunk.toString().split(/[\r\n]+/)) {
- const t = line.trim();
- if (t) onLog({ type: 'log', message: t });
- }
+ // `splitRe: /[\r\n]+/` so a torch/tqdm progress bar that redraws with a
+ // bare `\r` surfaces each redraw as its own log line; the carry buffer
+ // stitches a line split across chunk boundaries.
+ const onLine = (line) => {
+ const t = line.trim();
+ if (t) onLog({ type: 'log', message: t });
};
- proc.stdout.on('data', onChunk);
- proc.stderr.on('data', onChunk);
- proc.on('close', (code) => { onProc(null); resolve(code ?? -1); });
+ const stdoutReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ const stderrReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ proc.stdout.on('data', stdoutReader.push);
+ proc.stderr.on('data', stderrReader.push);
+ proc.on('close', (code) => { stdoutReader.flush(); stderrReader.flush(); onProc(null); resolve(code ?? -1); });
proc.on('error', (err) => { onLog({ type: 'error', message: err.message }); onProc(null); resolve(-1); });
});
}
diff --git a/server/routes/midiRuntime.js b/server/routes/midiRuntime.js
index 1861d795a5..29f5d05402 100644
--- a/server/routes/midiRuntime.js
+++ b/server/routes/midiRuntime.js
@@ -21,6 +21,7 @@ import { join } from 'path';
import { asyncHandler } from '../lib/errorHandler.js';
import { PATHS } from '../lib/fileUtils.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { createLineReader } from '../lib/streamLines.js';
import { openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
import {
@@ -128,14 +129,17 @@ router.get('/install', asyncHandler(async (req, res) => {
});
installInFlight = child;
- const onChunk = (chunk) => {
- for (const line of chunk.toString().split(/[\r\n]+/)) {
- const t = line.trimEnd();
- if (t) emit({ type: 'log', message: t });
- }
+ // `splitRe: /[\r\n]+/` so a bash/pip/tqdm progress bar that redraws with a
+ // bare `\r` surfaces each redraw as its own log line; the carry buffer
+ // stitches a line split across chunk boundaries (flushed on close).
+ const onLine = (line) => {
+ const t = line.trimEnd();
+ if (t) emit({ type: 'log', message: t });
};
- child.stdout.on('data', onChunk);
- child.stderr.on('data', onChunk);
+ const stdoutReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ const stderrReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ child.stdout.on('data', stdoutReader.push);
+ child.stderr.on('data', stderrReader.push);
child.on('error', (err) => {
finished = true;
installInFlight = null;
@@ -143,6 +147,8 @@ router.get('/install', asyncHandler(async (req, res) => {
safeEnd();
});
child.on('close', async (code) => {
+ stdoutReader.flush();
+ stderrReader.flush();
finished = true;
installInFlight = null;
// Drop the cached resolve/ready so this probe (and the next transcription)
diff --git a/server/routes/music.js b/server/routes/music.js
index e45345410b..750448c0d6 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -25,6 +25,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { PATHS } from '../lib/fileUtils.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { createLineReader } from '../lib/streamLines.js';
import { ENGINES, DEFAULT_ENGINE_ID, getEngine, isEngineReady, generateMusic } from '../services/pipeline/musicGen.js';
import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
@@ -130,14 +131,17 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
runtimeInstallInFlight.set(engine.id, child);
let finished = false;
- const onChunk = (chunk) => {
- for (const line of chunk.toString().split(/[\r\n]+/)) {
- const t = line.trimEnd();
- if (t) emit({ type: 'log', message: t });
- }
+ // `splitRe: /[\r\n]+/` so a bash/pip/tqdm progress bar that redraws with a
+ // bare `\r` surfaces each redraw as its own log line; the carry buffer
+ // stitches a line split across chunk boundaries (flushed on close).
+ const onLine = (line) => {
+ const t = line.trimEnd();
+ if (t) emit({ type: 'log', message: t });
};
- child.stdout.on('data', onChunk);
- child.stderr.on('data', onChunk);
+ const stdoutReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ const stderrReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ child.stdout.on('data', stdoutReader.push);
+ child.stderr.on('data', stderrReader.push);
child.on('error', (err) => {
finished = true;
runtimeInstallInFlight.delete(engine.id);
@@ -145,6 +149,8 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
safeEnd();
});
child.on('close', (code) => {
+ stdoutReader.flush();
+ stderrReader.flush();
finished = true;
runtimeInstallInFlight.delete(engine.id);
if (code === 0 && isEngineReady(engine.id)) {
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 4ff5b00f61..14846fd8e5 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -21,6 +21,7 @@ import { safeUnder } from '../lib/ffmpeg.js';
import { getSettings } from '../services/settings.js';
import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { createLineReader } from '../lib/streamLines.js';
import {
listVideoModels,
defaultVideoModelId,
@@ -343,20 +344,25 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
});
runtimeInstallInFlight.set(info.id, child);
- const onChunk = (chunk) => {
- for (const line of chunk.toString().split(/[\r\n]+/)) {
- const t = line.trimEnd();
- if (t) emit({ type: 'log', message: t });
- }
+ // `splitRe: /[\r\n]+/` so a bash/pip/tqdm progress bar that redraws with a
+ // bare `\r` surfaces each redraw as its own log line; the carry buffer
+ // stitches a line split across chunk boundaries (flushed on close).
+ const onLine = (line) => {
+ const t = line.trimEnd();
+ if (t) emit({ type: 'log', message: t });
};
- child.stdout.on('data', onChunk);
- child.stderr.on('data', onChunk);
+ const stdoutReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ const stderrReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ child.stdout.on('data', stdoutReader.push);
+ child.stderr.on('data', stderrReader.push);
child.on('error', (err) => {
runtimeInstallInFlight.delete(info.id);
emit({ type: 'error', message: `Installer failed to spawn: ${err.message}` });
safeEnd();
});
child.on('close', async (code) => {
+ stdoutReader.flush();
+ stderrReader.flush();
runtimeInstallInFlight.delete(info.id);
// Re-probe rather than trusting exit code alone — partial installs
// (network drop mid-clone, missing requirements file, ctrl-c via
diff --git a/server/services/videoDownload.js b/server/services/videoDownload.js
index 05278af0c8..24e6d287cf 100644
--- a/server/services/videoDownload.js
+++ b/server/services/videoDownload.js
@@ -243,17 +243,20 @@ export async function startVideoDownload(url) {
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') {
+ // Don't flush on cancel — a SIGKILL'd child leaves only a partial
+ // marker line in the carry, and emitting it would broadcast a stray
+ // progress/stage SSE frame right before the cancellation frame.
console.log(`🛑 Video download ${shortId(jobId)} cancelled`);
broadcastSse(job, { type: 'canceled' });
await cleanupDownloadFiles(jobId);
return;
}
+ // Flush any final line the child wrote without a trailing newline.
+ stdoutReader.flush();
+ stderrReader.flush();
const produced = await findDownloadedFile(jobId);
if (exit.code !== 0 || !produced) {
// A --match-filters/--max-filesize rejection exits 0 with no output
diff --git a/server/services/ytdlpAudioImport.js b/server/services/ytdlpAudioImport.js
index 34d5d5a56f..19191b87bc 100644
--- a/server/services/ytdlpAudioImport.js
+++ b/server/services/ytdlpAudioImport.js
@@ -150,15 +150,18 @@ export async function downloadAudioToTempMp3({
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') {
+ // Don't flush on cancel — a SIGKILL'd child leaves only a partial marker
+ // line in the carry, and emitting it would fire a stray progress/stage
+ // callback right before the caller reports the cancellation.
await cleanupYtDlpTemp(tempPrefix);
return { outcome: 'canceled' };
}
+ // Flush any final line the child wrote without a trailing newline before exit.
+ stdoutReader.flush();
+ stderrReader.flush();
if (exit.code !== 0 || !existsSync(outPath)) {
// A --match-filters/--max-filesize rejection exits 0 with no output file
// (yt-dlp treats a filtered-out video as "nothing to do", not an error) —