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([issue-1153]): extract video-gen progress parsing + finalize into a tested helper module
[._.]/ Adam Eivydd1f4bad9180
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f0e416f35e..96cdae847b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,6 +35,8 @@## Changed+- **[issue-1153] Internal cleanup of the local video-generation service** — the progress-parsing and finalize steps of the video generator moved into a separately-tested helper module. No behavior change.+- **[issue-1152] Internal reorganization of the story-arc planning service** — the arc-planning code (overview, episode seeding, manuscript completeness, arc-from-manuscript derivation) split from one 2,100-line file into focused modules. No behavior change.- **[issue-1151] Internal reorganization of request validation** — the peer-sync, Creative Director, importer, and Story Builder validation rules moved into their own focused files. No behavior change.diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.jsnew file mode 100644index 0000000000..e51de9ec05--- /dev/null+++ b/server/services/videoGen/generateVideoHelpers.js@@ -0,0 +1,147 @@+/**+ * generateVideoHelpers — extracted, unit-testable pieces of the (formerly+ * ~508-line) generateVideo() orchestrator in local.js (issue #1153).+ *+ * Kept as a sibling module rather than inlined so the line-parsing state+ * machine and the success-path finalize can be tested in isolation without+ * spawning a real python child. generateVideo() wires these into its spawn+ * closure; the functions here own no module-level state.+ */++import { existsSync, statSync } from 'fs';+import { broadcastSse } from '../../lib/sseUtils.js';+import { generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';+import { videoGenEvents } from './events.js';++/**+ * Build the stdout/stderr line handler for one generation. Parses the+ * python child's STATUS:/STAGE:/DOWNLOAD:/tqdm protocol into SSE frames+ * (`broadcastSse`) + queue-dispatcher events (`videoGenEvents`).+ *+ * Returns a `handleLine(raw)` fn: true when the line was a recognized+ * progress/status/noise line the caller should suppress from raw logging,+ * false for an unhandled line worth raw-logging.+ *+ * @param {object} ctx+ * @param {object} ctx.job - the in-flight job record (broadcastSse target)+ * @param {string} ctx.jobId+ * @param {RegExp} ctx.pythonNoiseRe - lines to silently drop (PYTHON_NOISE_RE)+ */+export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {+ return (raw) => {+ const line = raw.trim();+ if (!line) return true;+ if (pythonNoiseRe.test(line)) return true;+ // Heartbeat for the queue's idle watchdog (see imageGen/local.js).+ videoGenEvents.emit('activity', { generationId: jobId });+ if (line.startsWith('STATUS:')) {+ const message = line.slice(7);+ broadcastSse(job, { type: 'status', message });+ // Mirror status to videoGenEvents so the mediaJobQueue SSE dispatcher+ // forwards it to the client. Without this, only STAGE: progress+ // reaches the UI and long pre-render phases ("Loading pipeline…",+ // "Generating I2V…") display nothing.+ videoGenEvents.emit('status', { generationId: jobId, message });+ return true;+ }+ if (line.startsWith('STAGE:')) {+ const parts = line.split(':');+ // Three STAGE: shapes ship today:+ // STAGE:<stage>:step:<cur>:<total>:<msg> — explicit progress (parts[2]='step')+ // STAGE:<stage>:heartbeat:<N>s — idle-watchdog ping (parts[2]='heartbeat')+ // STAGE:<stage> — terse phase marker (no extra fields)+ // The legacy "treat every STAGE: as step:" parse mangled heartbeat+ // lines: parts[3]='20s' → parseInt=20, parts[4]=undefined → total=1, so+ // a download-clip heartbeat broadcast progress=20.0 (= 2000%) to the UI.+ // Normalize tag case — generate_ltx2.py emits `STEP:` (uppercase),+ // generate_hunyuan.py emits `step:` and `heartbeat:` (lowercase).+ const tag = (parts[2] || '').toLowerCase();+ if (tag === 'heartbeat') {+ // Surface as a status message; the activity emit above already+ // resets the queue watchdog. Mirror to videoGenEvents so the+ // mediaJobQueue SSE dispatcher forwards it to the client.+ const message = `${parts[1]}: heartbeat ${parts[3] || ''}`;+ broadcastSse(job, { type: 'status', message });+ videoGenEvents.emit('status', { generationId: jobId, message });+ return true;+ }+ if (tag === 'step') {+ const step = parseInt(parts[3], 10) || 0;+ const total = parseInt(parts[4], 10) || 1;+ const label = parts.slice(5).join(':');+ broadcastSse(job, { type: 'progress', progress: step / total, message: label });+ // Pass the python-side label as `message` so the dispatcher surfaces+ // it to the client instead of falling back to the synthesized+ // "Rendering step X/Y" (which hides useful labels like "Loading+ // model" emitted at stage boundaries).+ videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total, message: label || undefined });+ return true;+ }+ // Bare phase marker (e.g. STAGE:load-pipeline, STAGE:from-pretrained) —+ // surface as a status line. No progress %, no division-by-undefined.+ // Mirror to videoGenEvents for client forwarding.+ const message = parts.slice(1).join(':');+ broadcastSse(job, { type: 'status', message });+ videoGenEvents.emit('status', { generationId: jobId, message });+ return true;+ }+ if (line.startsWith('DOWNLOAD:')) {+ const message = `Downloading model... ${line.slice(9)}`;+ broadcastSse(job, { type: 'status', message });+ videoGenEvents.emit('status', { generationId: jobId, message });+ return true;+ }+ const m = line.match(/(\d+)%\|/);+ if (m) {+ const pct = parseInt(m[1], 10) / 100;+ broadcastSse(job, { type: 'progress', progress: pct, message: line });+ // Omit `message` on the queue-dispatcher emit: the raw tqdm bar+ // (`60%|██████ | 6/10 [00:30<00:20, ...]`) is terminal noise that+ // would clobber the last meaningful STATUS/STAGE line on every+ // percent update. Client renders the percentage separately.+ videoGenEvents.emit('progress', { generationId: jobId, progress: pct });+ return true;+ }+ return false;+ };+}++/**+ * Whether a watchdog-triggered SIGKILL should be treated as success: the+ * render emitted its completion marker (so the watchdog armed + fired) and+ * the output file is actually on disk and non-empty. A marker without a real+ * output (malformed runtime) still fails loudly.+ */+export function isWatchdogSuccess({ completionWatchdogFired, signal, outputPath }) {+ return completionWatchdogFired && signal === 'SIGKILL'+ && existsSync(outputPath) && statSync(outputPath).size > 0;+}++/**+ * Success path of generateVideo's `close` handler: faststart-optimize the+ * output, generate a thumbnail, prepend the history entry, and emit the+ * `complete` SSE frame + `completed` queue event. Mutates `job.status` to+ * 'complete'. Returns the thumbnail name.+ *+ * @param {object} ctx+ * @param {object} ctx.job+ * @param {string} ctx.jobId+ * @param {string} ctx.outputPath+ * @param {string} ctx.filename+ * @param {object} ctx.meta - the history-entry metadata built up-front+ * @param {number} ctx.actualSeed+ * @param {() => Promise<Array>} ctx.loadHistory+ * @param {(h: Array) => Promise<void>} ctx.saveHistory+ */+export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, loadHistory, saveHistory }) {+ job.status = 'complete';+ await optimizeForStreaming(outputPath);+ const thumbnail = await generateThumbnail(outputPath, jobId);+ const history = await loadHistory();+ history.unshift({ ...meta, thumbnail });+ await saveHistory(history);+ console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);+ broadcastSse(job, { type: 'complete', result: { filename, seed: actualSeed, thumbnail, path: `/data/videos/${filename}` } });+ videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });+ return thumbnail;+}diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.jsnew file mode 100644index 0000000000..f5d7de13f8--- /dev/null+++ b/server/services/videoGen/generateVideoHelpers.test.js@@ -0,0 +1,127 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { writeFileSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makeVideoGenLineHandler, isWatchdogSuccess } from './generateVideoHelpers.js';++// broadcastSse + videoGenEvents are the two output sinks the line handler+// writes to; capture both so we can assert the parse → frame mapping.+const sse = vi.hoisted(() => vi.fn());+const emitted = vi.hoisted(() => []);+vi.mock('../../lib/sseUtils.js', () => ({ broadcastSse: sse }));+vi.mock('./events.js', () => ({+ videoGenEvents: { emit: (type, payload) => { emitted.push({ type, payload }); } },+}));+// generateVideoHelpers also imports ffmpeg + fs at module top; stub ffmpeg so+// the import graph stays light (finalize isn't exercised in this file).+vi.mock('../../lib/ffmpeg.js', () => ({ generateThumbnail: vi.fn(), optimizeForStreaming: vi.fn() }));++const PYTHON_NOISE_RE = /^(Loading|Fetching|tokenizer|Some weights)/;++describe('makeVideoGenLineHandler', () => {+ let job;+ let handle;++ beforeEach(() => {+ sse.mockClear();+ emitted.length = 0;+ job = { id: 'j1', clients: [] };+ handle = makeVideoGenLineHandler({ job, jobId: 'job-12345678', pythonNoiseRe: PYTHON_NOISE_RE });+ });++ const sseFrames = () => sse.mock.calls.map((c) => c[1]);+ const eventsOfType = (t) => emitted.filter((e) => e.type === t).map((e) => e.payload);++ it('suppresses blank + python-noise lines without emitting', () => {+ expect(handle('')).toBe(true);+ expect(handle(' ')).toBe(true);+ expect(handle('Loading pipeline components...')).toBe(true);+ expect(sse).not.toHaveBeenCalled();+ expect(emitted).toHaveLength(0);+ });++ it('STATUS: → status SSE frame + status event, and an activity heartbeat', () => {+ expect(handle('STATUS:Generating I2V…')).toBe(true);+ expect(sseFrames()).toContainEqual({ type: 'status', message: 'Generating I2V…' });+ expect(eventsOfType('status')).toContainEqual({ generationId: 'job-12345678', message: 'Generating I2V…' });+ expect(eventsOfType('activity')).toContainEqual({ generationId: 'job-12345678' });+ });++ it('STAGE:<s>:step:<cur>:<total>:<label> → fractional progress with label', () => {+ expect(handle('STAGE:render:step:6:10:Sampling latents')).toBe(true);+ expect(sseFrames()).toContainEqual({ type: 'progress', progress: 0.6, message: 'Sampling latents' });+ expect(eventsOfType('progress')).toContainEqual({+ generationId: 'job-12345678', progress: 0.6, step: 6, totalSteps: 10, message: 'Sampling latents',+ });+ });++ it('STAGE: heartbeat does NOT become bogus progress (regression: 20s → 2000%)', () => {+ expect(handle('STAGE:download-clip:heartbeat:20s')).toBe(true);+ // Heartbeat is a status line, never a progress frame.+ expect(sseFrames()).toContainEqual({ type: 'status', message: 'download-clip: heartbeat 20s' });+ expect(sseFrames().some((f) => f.type === 'progress')).toBe(false);+ });++ it('normalizes uppercase STEP tag (generate_ltx2.py emits STEP:)', () => {+ expect(handle('STAGE:render:STEP:1:4:warmup')).toBe(true);+ expect(sseFrames()).toContainEqual({ type: 'progress', progress: 0.25, message: 'warmup' });+ });++ it('bare STAGE: phase marker → status (no division-by-undefined progress)', () => {+ expect(handle('STAGE:load-pipeline')).toBe(true);+ expect(sseFrames()).toContainEqual({ type: 'status', message: 'load-pipeline' });+ expect(sseFrames().some((f) => f.type === 'progress')).toBe(false);+ });++ it('DOWNLOAD: → prefixed status frame', () => {+ expect(handle('DOWNLOAD:model.safetensors 40%')).toBe(true);+ expect(sseFrames()).toContainEqual({ type: 'status', message: 'Downloading model... model.safetensors 40%' });+ });++ it('tqdm bar → progress frame; queue event omits the noisy message', () => {+ expect(handle('60%|██████ | 6/10 [00:30<00:20, 1.2s/it]')).toBe(true);+ expect(sseFrames()).toContainEqual({ type: 'progress', progress: 0.6, message: '60%|██████ | 6/10 [00:30<00:20, 1.2s/it]' });+ // The mediaJobQueue dispatcher emit must NOT carry the raw bar as message.+ expect(eventsOfType('progress')).toContainEqual({ generationId: 'job-12345678', progress: 0.6 });+ });++ it('returns false for an unrecognized line (caller raw-logs it)', () => {+ expect(handle('🐍 some unexpected diagnostic')).toBe(false);+ });+});++describe('isWatchdogSuccess', () => {+ // The non-fs short-circuits are pure; the on-disk branch is gated on a real+ // existsSync + non-empty statSync, exercised against actual temp files.+ it('false unless the watchdog actually fired', () => {+ expect(isWatchdogSuccess({ completionWatchdogFired: false, signal: 'SIGKILL', outputPath: '/tmp/x.mp4' })).toBe(false);+ });++ it('false unless the kill signal was SIGKILL', () => {+ expect(isWatchdogSuccess({ completionWatchdogFired: true, signal: 'SIGTERM', outputPath: '/tmp/x.mp4' })).toBe(false);+ });++ it('false when the output file is absent (no real render landed)', () => {+ expect(isWatchdogSuccess({ completionWatchdogFired: true, signal: 'SIGKILL', outputPath: `/tmp/definitely-missing-${process.pid}.mp4` })).toBe(false);+ });++ it('true when the watchdog fired on SIGKILL and a non-empty output exists', () => {+ const p = join(tmpdir(), `wd-success-${process.pid}.mp4`);+ writeFileSync(p, 'x');+ try {+ expect(isWatchdogSuccess({ completionWatchdogFired: true, signal: 'SIGKILL', outputPath: p })).toBe(true);+ } finally {+ rmSync(p, { force: true });+ }+ });++ it('false when the output file exists but is empty (marker without real render)', () => {+ const p = join(tmpdir(), `wd-empty-${process.pid}.mp4`);+ writeFileSync(p, '');+ try {+ expect(isWatchdogSuccess({ completionWatchdogFired: true, signal: 'SIGKILL', outputPath: p })).toBe(false);+ } finally {+ rmSync(p, { force: true });+ }+ });+});diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 7f32fd4960..5a64dab223 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -25,6 +25,7 @@ import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../.import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x, extractEvaluationFrames } from '../../lib/ffmpeg.js';import { hfTokenEnv } from '../../lib/hfToken.js';import { safeChildProcessEnv } from '../../lib/processEnv.js';+import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess } from './generateVideoHelpers.js';// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1// scripts/setup-image-video.sh`. Used when a model entry has@@ -938,85 +939,11 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mlet outputBuf = '';let missingPyModule = null;- // Returns true when the line was a known progress/status message (already- // broadcast over SSE) or python-noise — caller should suppress logging.- // Returns false for unhandled lines that are worth raw-logging.- const handleLine = (raw) => {- const line = raw.trim();- if (!line) return true;- if (PYTHON_NOISE_RE.test(line)) return true;- // Heartbeat for the queue's idle watchdog (see imageGen/local.js).- videoGenEvents.emit('activity', { generationId: jobId });- if (line.startsWith('STATUS:')) {- const message = line.slice(7);- broadcastSse(job, { type: 'status', message });- // Mirror status to videoGenEvents so the mediaJobQueue SSE dispatcher- // forwards it to the client. Without this, only STAGE: progress- // reaches the UI and long pre-render phases ("Loading pipeline…",- // "Generating I2V…") display nothing.- videoGenEvents.emit('status', { generationId: jobId, message });- return true;- }- if (line.startsWith('STAGE:')) {- const parts = line.split(':');- // Three STAGE: shapes ship today:- // STAGE:<stage>:step:<cur>:<total>:<msg> — explicit progress (parts[2]='step')- // STAGE:<stage>:heartbeat:<N>s — idle-watchdog ping (parts[2]='heartbeat')- // STAGE:<stage> — terse phase marker (no extra fields)- // The legacy "treat every STAGE: as step:" parse mangled heartbeat- // lines: parts[3]='20s' → parseInt=20, parts[4]=undefined → total=1, so- // a download-clip heartbeat broadcast progress=20.0 (= 2000%) to the UI.- // Normalize tag case — generate_ltx2.py emits `STEP:` (uppercase),- // generate_hunyuan.py emits `step:` and `heartbeat:` (lowercase).- const tag = (parts[2] || '').toLowerCase();- if (tag === 'heartbeat') {- // Surface as a status message; the activity emit above already- // resets the queue watchdog. Mirror to videoGenEvents so the- // mediaJobQueue SSE dispatcher forwards it to the client.- const message = `${parts[1]}: heartbeat ${parts[3] || ''}`;- broadcastSse(job, { type: 'status', message });- videoGenEvents.emit('status', { generationId: jobId, message });- return true;- }- if (tag === 'step') {- const step = parseInt(parts[3], 10) || 0;- const total = parseInt(parts[4], 10) || 1;- const label = parts.slice(5).join(':');- broadcastSse(job, { type: 'progress', progress: step / total, message: label });- // Pass the python-side label as `message` so the dispatcher surfaces- // it to the client instead of falling back to the synthesized- // "Rendering step X/Y" (which hides useful labels like "Loading- // model" emitted at stage boundaries).- videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total, message: label || undefined });- return true;- }- // Bare phase marker (e.g. STAGE:load-pipeline, STAGE:from-pretrained) —- // surface as a status line. No progress %, no division-by-undefined.- // Mirror to videoGenEvents for client forwarding.- const message = parts.slice(1).join(':');- broadcastSse(job, { type: 'status', message });- videoGenEvents.emit('status', { generationId: jobId, message });- return true;- }- if (line.startsWith('DOWNLOAD:')) {- const message = `Downloading model... ${line.slice(9)}`;- broadcastSse(job, { type: 'status', message });- videoGenEvents.emit('status', { generationId: jobId, message });- return true;- }- const m = line.match(/(\d+)%\|/);- if (m) {- const pct = parseInt(m[1], 10) / 100;- broadcastSse(job, { type: 'progress', progress: pct, message: line });- // Omit `message` on the queue-dispatcher emit: the raw tqdm bar- // (`60%|██████ | 6/10 [00:30<00:20, ...]`) is terminal noise that- // would clobber the last meaningful STATUS/STAGE line on every- // percent update. Client renders the percentage separately.- videoGenEvents.emit('progress', { generationId: jobId, progress: pct });- return true;- }- return false;- };+ // The python child's STATUS:/STAGE:/DOWNLOAD:/tqdm → SSE-frame parser lives+ // in generateVideoHelpers.js so it can be unit-tested without a real child.+ // Returns true for a recognized progress/status/noise line (suppress raw+ // logging), false for an unhandled line worth raw-logging.+ const handleLine = makeVideoGenLineHandler({ job, jobId, pythonNoiseRe: PYTHON_NOISE_RE });proc.stdout.on('data', (chunk) => {outputBuf += chunk.toString();@@ -1081,8 +1008,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// on disk, so treat it as success (not the generic "killed, likely OOM"// failure). Guard on the file actually existing + being non-empty so a// marker without a real output (a malformed runtime) still fails loudly.- const watchdogSuccess = completionWatchdogFired && signal === 'SIGKILL'- && existsSync(outputPath) && statSync(outputPath).size > 0;+ const watchdogSuccess = isWatchdogSuccess({ completionWatchdogFired, signal, outputPath });if (code !== 0 && !watchdogSuccess) {job.status = 'error';@@ -1112,15 +1038,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mif (watchdogSuccess) {console.log(`⚠️ video child force-killed after completion teardown hang — output is intact [${jobId.slice(0, 8)}]`);}- job.status = 'complete';- await optimizeForStreaming(outputPath);- const thumbnail = await generateThumbnail(outputPath, jobId);- const history = await loadHistory();- history.unshift({ ...meta, thumbnail });- await saveHistory(history);- console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);- broadcastSse(job, { type: 'complete', result: { filename, seed: actualSeed, thumbnail, path: `/data/videos/${filename}` } });- videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, loadHistory, saveHistory });}closeJobAfterDelay(jobs, jobId);});