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: extract shared ffmpeg spawn-state/terminal-guard helper (#2398)

Adam Eivya790704593cd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5dd9bd7d0b..b77226d240 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -94,4 +94,5 @@
- **[issue-2386] ffmpeg render errors are now separated into pre-spawn and post-spawn, so a failed kill can no longer let a replacement render overlap the live process.** The music-video and timeline renderers both routed every `'error'` event through the same immediate finalizer — which released the per-project render mutex and dropped process ownership. But `'error'` fires for two very different cases: a genuine pre-spawn failure (ENOENT — the child never started, no `'close'` follows) and a *later* child-process error such as a failed kill while ffmpeg is still running. Releasing the mutex on the latter let a re-render spawn and overlap the still-live ffmpeg. Both services now track spawn state (a `'spawn'` listener sets a flag) and finalize immediately only for pre-spawn errors; a post-spawn error is recorded but retains process + project-mutex ownership until the pending `'close'` runs the sole terminal finalization. A shared `terminal` guard makes terminal handling exactly-once across the error and close paths, and both handlers wrap their body per the child-process-callback convention. Covered by new error-to-close sequence tests before and after spawn in both services.
- **[issue-2385] Digital Twin evaluation suites now distinguish a load failure from a genuinely empty suite.** Values-Alignment (and its sibling Adversarial-Boundary / Multi-Turn panels, which share the same hook) caught a failed suite load with `.catch(() => [])`, so a server/network error rendered the same "No suite found" empty state as an install that legitimately has no `VALUES_ALIGNMENT_SUITE.md`. The shared `useTwinEvaluationSuite` hook now uses a `null` sentinel for a failed tests-load (distinct from `[]` = successfully-loaded-but-empty) and exposes a `loadError`; `TwinEvaluationSuitePanel` renders an explicit inline load-error state with a **Retry** button that re-runs the load — while the true empty state stays distinct. Feedback stays non-duplicative (inline only, load calls remain `silent`, no toast). History remains secondary: a failed history load degrades to no history without blocking the panel. Covered by new hook tests (failure vs empty vs history-only failure vs reload recovery) and a component test asserting both the load-error/Retry render and the empty-response render.
+- **[issue-2398] Extracted the shared ffmpeg spawn-state/terminal-guard block behind one helper.** After #2386, the ~25-line spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn error dispatch was byte-for-byte parallel in the music-video (`server/services/musicVideo/render.js`) and timeline (`server/services/videoTimeline/local.js`) renderers. Both now call a single `attachFfmpegRenderGuard(proc, { label, onSpawnError, onProcessError, onClose })` helper (`server/lib/ffmpegRenderGuard.js`, barreled + documented) that owns the `'spawn'`/`'error'`/`'close'` wiring — only the pre-spawn `'error'` or `'close'` finalizes; a post-spawn `'error'` records the reason and retains process + mutex ownership — and takes the service-specific finalize bodies as callbacks (music-video mutates the project's render status; timeline does not). Behavior is unchanged — all 42 existing terminal-guard sequence tests still pass — with a new unit test covering the exactly-once dispatch and crash-guard directly. No behavior change.
- **[issue-2375] Split the ~1,380-line `server/routes/apps.js` into domain-focused sub-routers.** The single apps router (24+ endpoints spanning CRUD/status enrichment, PM2 lifecycle, config repair, Xcode provisioning, icon serving, task-type overrides, document git-commits, editor/folder launch, and agent history) is now assembled from nine mountable sub-routers under `server/routes/apps/` (`crud`, `lifecycle`, `viteTls`, `xcode`, `icons`, `taskTypes`, `launch`, `documents`, `agents`), mirroring the pipeline sub-router pattern. Shared plumbing (`loadApp` middleware, `pathExists`, and the port/overall-status derivation helpers previously duplicated between the list and detail endpoints) lives in one `apps/shared.js`, and the ~130-line ecosystem-config port-rewrite orchestration moved out of the PUT handler into a `server/services/appPortConfig.js` service. The `/api/apps` route contract is byte-for-byte identical (all 35 path+method pairs verified) and the oversized route test file is split along the same domain boundaries. No behavior change.
diff --git a/server/lib/README.md b/server/lib/README.md
index 3fdce4d517..d96fbbceee 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -145,6 +145,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |
+| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. |
diff --git a/server/lib/ffmpegRenderGuard.js b/server/lib/ffmpegRenderGuard.js
new file mode 100644
index 0000000000..8b6b9c37e9
--- /dev/null
+++ b/server/lib/ffmpegRenderGuard.js
@@ -0,0 +1,77 @@
+/**
+ * Shared ffmpeg render-process lifecycle guard (#2398).
+ *
+ * The two SSE render runners — `server/services/musicVideo/render.js` and
+ * `server/services/videoTimeline/local.js` — spawn ffmpeg and then wire an
+ * identical spawn-state + exactly-once `terminal` guard around its 'spawn',
+ * 'error', and 'close' events. That block is byte-for-byte parallel across the
+ * two renderers; only the finalization *bodies* differ (music-video mutates the
+ * project's render status; timeline does not). This helper owns the shared
+ * mechanics and takes the service-specific finalize bodies as callbacks.
+ *
+ * The mechanics it owns:
+ * - **Spawn-state tracking.** ffmpeg's 'error' fires for BOTH a genuine
+ * pre-spawn failure (ENOENT — the child never started, so no 'close' will
+ * follow) AND a later child-process error such as a failed kill (the ffmpeg
+ * is still live and 'close' still owes a terminal event). The 'spawn' event
+ * flips `spawned` so the 'error' handler can tell the two apart.
+ * - **Pre-vs-post-spawn dispatch.** Pre-spawn errors finalize immediately
+ * (via `onSpawnError`); post-spawn errors only *record* the reason (via
+ * `onProcessError`) and retain process + mutex ownership until 'close' runs
+ * the sole terminal finalization — otherwise a replacement render could
+ * spawn and overlap the still-live ffmpeg.
+ * - **Exactly-once `terminal` guard.** Whichever of {pre-spawn 'error',
+ * 'close'} fires first sets `terminal` and runs the sole finalization; the
+ * other is a no-op. A post-spawn 'error' deliberately does NOT set `terminal`
+ * (the pending 'close' still owes the terminal event).
+ *
+ * These listeners run OUTSIDE the Express request lifecycle, so an uncaught
+ * throw from a callback would crash the Node process (there is no `next(err)`
+ * to bubble to). Each listener is wrapped in a last-resort try/catch that logs
+ * via the emoji-prefixed convention — callbacks that want richer recovery
+ * (emit an SSE error frame, release the mutex) keep their own inner try/catch.
+ *
+ * @param {import('child_process').ChildProcess} proc - the spawned ffmpeg child
+ * @param {object} handlers
+ * @param {string} handlers.label - log label for the crash-guard messages (e.g. "Music-video render")
+ * @param {(err: Error) => void|Promise<void>} handlers.onSpawnError - pre-spawn failure: the child never started; finalize the job.
+ * @param {(err: Error) => void|Promise<void>} handlers.onProcessError - post-spawn error: ffmpeg still live; record only, do NOT finalize.
+ * @param {(code: number|null, signal: string|null) => void|Promise<void>} handlers.onClose - the sole terminal 'close' finalization.
+ */
+export function attachFfmpegRenderGuard(proc, { label, onSpawnError, onProcessError, onClose }) {
+ let spawned = false;
+ let terminal = false;
+ proc.on('spawn', () => { spawned = true; });
+
+ proc.on('error', async (err) => {
+ try {
+ // Already finalized (a pre-spawn error or 'close' won the race) — a late
+ // stray 'error' (e.g. ESRCH/EPERM from a kill on the now-dead pid) must
+ // not clobber a completed job.
+ if (terminal) return;
+ if (spawned) {
+ // Post-spawn error. ffmpeg is still live — do NOT set `terminal` or
+ // release ownership; the pending 'close' runs the sole finalization.
+ await onProcessError(err);
+ return;
+ }
+ // Pre-spawn failure: the child never started, so 'close' won't follow —
+ // finalize here. Set `terminal` BEFORE the callback so a throw inside it
+ // can't let 'close' re-run the finalization.
+ terminal = true;
+ await onSpawnError(err);
+ } catch (e) {
+ console.error(`❌ ${label} error handler failed: ${e.message}`);
+ }
+ });
+
+ proc.on('close', async (code, signal) => {
+ try {
+ if (terminal) return; // a pre-spawn error already finalized this job
+ terminal = true;
+ await onClose(code, signal);
+ } catch (e) {
+ console.error(`❌ ${label} close handler failed: ${e.message}`);
+ }
+ });
+}
diff --git a/server/lib/ffmpegRenderGuard.test.js b/server/lib/ffmpegRenderGuard.test.js
new file mode 100644
index 0000000000..3c521e3098
--- /dev/null
+++ b/server/lib/ffmpegRenderGuard.test.js
@@ -0,0 +1,173 @@
+import { describe, it, expect, vi } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { attachFfmpegRenderGuard } from './ffmpegRenderGuard.js';
+
+// Let the async listener bodies (they `await` the callbacks) settle.
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+const makeProc = () => new EventEmitter();
+
+const makeHandlers = (overrides = {}) => ({
+ label: 'Test render',
+ onSpawnError: vi.fn(),
+ onProcessError: vi.fn(),
+ onClose: vi.fn(),
+ ...overrides,
+});
+
+describe('attachFfmpegRenderGuard', () => {
+ it('routes a pre-spawn error (no "spawn" fired) to onSpawnError only', async () => {
+ const proc = makeProc();
+ const h = makeHandlers();
+ attachFfmpegRenderGuard(proc, h);
+
+ const err = new Error('ENOENT');
+ proc.emit('error', err);
+ await flush();
+
+ expect(h.onSpawnError).toHaveBeenCalledTimes(1);
+ expect(h.onSpawnError).toHaveBeenCalledWith(err);
+ expect(h.onProcessError).not.toHaveBeenCalled();
+ expect(h.onClose).not.toHaveBeenCalled();
+ });
+
+ it('routes a post-spawn error to onProcessError WITHOUT consuming the terminal slot', async () => {
+ const proc = makeProc();
+ const h = makeHandlers();
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('spawn');
+ proc.emit('error', new Error('failed kill'));
+ await flush();
+
+ expect(h.onProcessError).toHaveBeenCalledTimes(1);
+ expect(h.onSpawnError).not.toHaveBeenCalled();
+
+ // ffmpeg is still live; the pending 'close' must still run the sole
+ // terminal finalization.
+ proc.emit('close', 0, null);
+ await flush();
+ expect(h.onClose).toHaveBeenCalledTimes(1);
+ expect(h.onClose).toHaveBeenCalledWith(0, null);
+ });
+
+ it('runs onClose for a normal exit', async () => {
+ const proc = makeProc();
+ const h = makeHandlers();
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('spawn');
+ proc.emit('close', 0, null);
+ await flush();
+
+ expect(h.onClose).toHaveBeenCalledTimes(1);
+ expect(h.onClose).toHaveBeenCalledWith(0, null);
+ expect(h.onSpawnError).not.toHaveBeenCalled();
+ expect(h.onProcessError).not.toHaveBeenCalled();
+ });
+
+ it('passes the signal through to onClose for a cancelled render', async () => {
+ const proc = makeProc();
+ const h = makeHandlers();
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('spawn');
+ proc.emit('close', null, 'SIGTERM');
+ await flush();
+
+ expect(h.onClose).toHaveBeenCalledWith(null, 'SIGTERM');
+ });
+
+ it('is exactly-once: a pre-spawn error already finalized, so a later "close" is a no-op', async () => {
+ const proc = makeProc();
+ const h = makeHandlers();
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('error', new Error('ENOENT'));
+ await flush();
+ proc.emit('close', 1, null); // late stray close after the process never started
+ await flush();
+
+ expect(h.onSpawnError).toHaveBeenCalledTimes(1);
+ expect(h.onClose).not.toHaveBeenCalled();
+ });
+
+ it('is exactly-once: after "close" finalizes, a late stray "error" is ignored', async () => {
+ const proc = makeProc();
+ const h = makeHandlers();
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('spawn');
+ proc.emit('close', 0, null);
+ await flush();
+ proc.emit('error', new Error('ESRCH from a kill on the dead pid'));
+ await flush();
+
+ expect(h.onClose).toHaveBeenCalledTimes(1);
+ expect(h.onProcessError).not.toHaveBeenCalled();
+ expect(h.onSpawnError).not.toHaveBeenCalled();
+ });
+
+ it('runs onClose exactly once even if "close" is emitted twice', async () => {
+ const proc = makeProc();
+ const h = makeHandlers();
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('spawn');
+ proc.emit('close', 0, null);
+ proc.emit('close', 0, null);
+ await flush();
+
+ expect(h.onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('swallows a throwing onClose so the process does not crash (crash-guard try/catch)', async () => {
+ const proc = makeProc();
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const h = makeHandlers({
+ onClose: vi.fn(() => { throw new Error('finalize boom'); }),
+ });
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('spawn');
+ // Must not reject/throw out of the listener.
+ expect(() => proc.emit('close', 0, null)).not.toThrow();
+ await flush();
+
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('Test render close handler failed'));
+ errSpy.mockRestore();
+ });
+
+ it('swallows a throwing onSpawnError (crash-guard try/catch)', async () => {
+ const proc = makeProc();
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const h = makeHandlers({
+ onSpawnError: vi.fn(() => { throw new Error('spawn-finalize boom'); }),
+ });
+ attachFfmpegRenderGuard(proc, h);
+
+ expect(() => proc.emit('error', new Error('ENOENT'))).not.toThrow();
+ await flush();
+
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('Test render error handler failed'));
+ errSpy.mockRestore();
+ });
+
+ it('awaits async finalize callbacks', async () => {
+ const proc = makeProc();
+ const order = [];
+ const h = makeHandlers({
+ onClose: vi.fn(async () => {
+ await Promise.resolve();
+ order.push('closed');
+ }),
+ });
+ attachFfmpegRenderGuard(proc, h);
+
+ proc.emit('spawn');
+ proc.emit('close', 0, null);
+ await flush();
+
+ expect(order).toEqual(['closed']);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index dc8731ade2..e11219c82d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -135,6 +135,7 @@ export * from './commandSecurity.js';
export * from './detachedSpawn.js';
export * from './execGit.js';
export * from './ffmpeg.js';
+export * from './ffmpegRenderGuard.js';
export * from './gitArgs.js';
export * from './gitForge.js';
export * from './gitOutputParsers.js';
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index fe61ade0a7..ab7c6f5326 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -31,6 +31,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '
import { findFfmpeg, safeUnder, generateThumbnail, probeVideoDuration } from '../../lib/ffmpeg.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';
import { getTrack } from '../tracks/index.js';
import { getProject, updateProject } from './projects.js';
@@ -301,18 +302,6 @@ export async function renderMusicVideo(projectId) {
const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'ignore', 'pipe'] });
job.process = proc;
- // 'error' fires for BOTH a genuine pre-spawn failure (ENOENT — the child
- // never started, so no 'close' will follow) AND a later child-process error
- // such as a failed kill (the ffmpeg is still live and 'close' still owes us
- // a terminal event). Track spawn state so only the pre-spawn case finalizes
- // immediately; a post-spawn error must retain process + project-mutex
- // ownership until 'close' so a replacement render can't overlap the live
- // ffmpeg process. `terminal` makes the terminal handling exactly-once,
- // shared between the pre-spawn error branch and 'close'.
- let spawned = false;
- let terminal = false;
- proc.on('spawn', () => { spawned = true; });
-
let stderrBuf = '';
proc.stderr.on('data', (chunk) => {
stderrBuf += chunk.toString();
@@ -335,24 +324,21 @@ export async function renderMusicVideo(projectId) {
}
});
- proc.on('error', async (err) => {
- try {
- // Already finalized (a pre-spawn error or 'close' won the race) — a late
- // stray 'error' (e.g. ESRCH/EPERM from a kill on the now-dead pid) must
- // not clobber lastError on a completed job.
- if (terminal) return;
- if (spawned) {
- // Post-spawn error (e.g. a failed kill during cancel). The ffmpeg is
- // still live — do NOT release the project mutex or null job.process
- // here, or a replacement render could spawn and overlap it. Record
- // the reason; the pending 'close' runs the sole terminal finalization.
- job.lastError = `ffmpeg process error: ${err.message}`;
- console.log(`⚠️ Music-video render post-spawn error [${jobId.slice(0, 8)}]: ${err.message}`);
- return;
- }
- // Pre-spawn failure: the child never started, so 'close' won't follow —
- // finalize here.
- terminal = true;
+ // Spawn-state tracking + exactly-once terminal guard + pre-vs-post-spawn
+ // dispatch live in the shared helper; only the finalize bodies below are
+ // service-specific (music-video mutates the project's render status).
+ attachFfmpegRenderGuard(proc, {
+ label: `Music-video render [${jobId.slice(0, 8)}]`,
+ onProcessError: (err) => {
+ // Post-spawn error (e.g. a failed kill during cancel). The ffmpeg is
+ // still live — do NOT release the project mutex or null job.process
+ // here, or a replacement render could spawn and overlap it. Record
+ // the reason; the pending 'close' runs the sole terminal finalization.
+ job.lastError = `ffmpeg process error: ${err.message}`;
+ console.log(`⚠️ Music-video render post-spawn error [${jobId.slice(0, 8)}]: ${err.message}`);
+ },
+ onSpawnError: async (err) => {
+ // Pre-spawn failure: the child never started, so 'close' won't follow.
job.process = null;
job.status = 'error';
const reason = `Failed to spawn ffmpeg: ${err.message}`;
@@ -362,65 +348,61 @@ export async function renderMusicVideo(projectId) {
projectRenders.delete(projectId);
await updateProject(projectId, { status: 'failed' }).catch(() => {});
closeJobAfterDelay(jobs, jobId);
- } catch (e) {
- console.error(`❌ Music-video render error handler failed [${jobId.slice(0, 8)}]: ${e.message}`);
- }
- });
-
- proc.on('close', async (code, signal) => {
- if (terminal) return; // a pre-spawn error already finalized this job
- terminal = true;
- job.process = null;
- if (code !== 0) {
- const canceled = signal === 'SIGTERM' || signal === 'SIGKILL';
- job.status = canceled ? 'canceled' : 'error';
- const reason = canceled ? 'Render cancelled' : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;
- job.lastError = reason;
- console.log(`${canceled ? '🛑' : '❌'} Music-video render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);
- await unlink(outputPath).catch(() => {});
- broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
- projectRenders.delete(projectId);
- // A cancel restores the pre-render status (so a cancelled re-render of a
- // 'complete' project stays 'complete'); a real failure marks it 'failed'.
- await updateProject(projectId, { status: canceled ? priorStatus : 'failed' }).catch(() => {});
- closeJobAfterDelay(jobs, jobId);
- return;
- }
- // Success finalization runs in an event callback (no request to bubble to)
- // — a throw in thumbnailing/history I/O would otherwise leave the project
- // stuck 'rendering' and projectRenders un-cleared (every later render 409s).
- // Wrap it so any failure still emits a terminal frame and releases the slot.
- try {
- job.status = 'complete';
- const thumb = await generateThumbnail(outputPath, jobId);
- const meta = {
- id: jobId,
- prompt: `Music Video: ${project.name}`,
- modelId: 'music-video',
- seed: 0,
- width: canonW,
- height: canonH,
- numFrames: Math.round(totalDuration * (fps || 24)),
- fps: fps || 24,
- filename,
- thumbnail: thumb,
- createdAt: new Date().toISOString(),
- musicVideoProjectId: projectId,
- };
- await appendToVideoHistory(meta);
- await updateProject(projectId, { renderHistoryId: jobId, status: 'complete' }).catch(() => {});
- console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);
- broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });
- } catch (err) {
- job.status = 'error';
- job.lastError = `Finalize failed: ${err.message}`;
- console.error(`❌ Music-video render finalize failed [${jobId.slice(0, 8)}]: ${err.message}`);
- broadcastSse(job, { type: 'error', error: 'Render finalize failed' });
- await updateProject(projectId, { status: 'failed' }).catch(() => {});
- } finally {
- projectRenders.delete(projectId);
- closeJobAfterDelay(jobs, jobId);
- }
+ },
+ onClose: async (code, signal) => {
+ job.process = null;
+ if (code !== 0) {
+ const canceled = signal === 'SIGTERM' || signal === 'SIGKILL';
+ job.status = canceled ? 'canceled' : 'error';
+ const reason = canceled ? 'Render cancelled' : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;
+ job.lastError = reason;
+ console.log(`${canceled ? '🛑' : '❌'} Music-video render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);
+ await unlink(outputPath).catch(() => {});
+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
+ projectRenders.delete(projectId);
+ // A cancel restores the pre-render status (so a cancelled re-render of a
+ // 'complete' project stays 'complete'); a real failure marks it 'failed'.
+ await updateProject(projectId, { status: canceled ? priorStatus : 'failed' }).catch(() => {});
+ closeJobAfterDelay(jobs, jobId);
+ return;
+ }
+ // Success finalization runs in an event callback (no request to bubble
+ // to) — a throw in thumbnailing/history I/O would otherwise leave the
+ // project stuck 'rendering' and projectRenders un-cleared (every later
+ // render 409s). Wrap it so any failure still emits a terminal frame and
+ // releases the slot.
+ try {
+ job.status = 'complete';
+ const thumb = await generateThumbnail(outputPath, jobId);
+ const meta = {
+ id: jobId,
+ prompt: `Music Video: ${project.name}`,
+ modelId: 'music-video',
+ seed: 0,
+ width: canonW,
+ height: canonH,
+ numFrames: Math.round(totalDuration * (fps || 24)),
+ fps: fps || 24,
+ filename,
+ thumbnail: thumb,
+ createdAt: new Date().toISOString(),
+ musicVideoProjectId: projectId,
+ };
+ await appendToVideoHistory(meta);
+ await updateProject(projectId, { renderHistoryId: jobId, status: 'complete' }).catch(() => {});
+ console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);
+ broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });
+ } catch (err) {
+ job.status = 'error';
+ job.lastError = `Finalize failed: ${err.message}`;
+ console.error(`❌ Music-video render finalize failed [${jobId.slice(0, 8)}]: ${err.message}`);
+ broadcastSse(job, { type: 'error', error: 'Render finalize failed' });
+ await updateProject(projectId, { status: 'failed' }).catch(() => {});
+ } finally {
+ projectRenders.delete(projectId);
+ closeJobAfterDelay(jobs, jobId);
+ }
+ },
});
return { jobId };
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index 7948b13c3b..d6cb194dff 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -24,6 +24,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '
import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail } from '../../lib/ffmpeg.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';
const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');
@@ -373,18 +374,6 @@ export async function renderProject(projectId) {
const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'ignore', 'pipe'] });
job.process = proc;
- // 'error' fires for BOTH a genuine pre-spawn failure (ENOENT — the child
- // never started, so no 'close' will follow) AND a later child-process error
- // such as a failed kill (the ffmpeg is still live and 'close' still owes us a
- // terminal event). Track spawn state so only the pre-spawn case finalizes
- // immediately; a post-spawn error must retain process + project-mutex
- // ownership until 'close' so a replacement render can't overlap the live
- // ffmpeg process. `terminal` makes the terminal handling exactly-once, shared
- // between the pre-spawn error branch and 'close'.
- let spawned = false;
- let terminal = false;
- proc.on('spawn', () => { spawned = true; });
-
// ffmpeg's -progress pipe:2 emits key=value lines, one per line, every
// few hundred ms. The relevant key is `out_time_us` (microseconds of
// output written so far). Divide by total duration to get a 0..1 ratio.
@@ -412,24 +401,21 @@ export async function renderProject(projectId) {
}
});
- proc.on('error', (err) => {
- try {
- // Already finalized (a pre-spawn error or 'close' won the race) — a late
- // stray 'error' (e.g. ESRCH/EPERM from a kill on the now-dead pid) must
- // not clobber lastError on a completed job.
- if (terminal) return;
- if (spawned) {
- // Post-spawn error (e.g. a failed kill during cancel). The ffmpeg is
- // still live — do NOT release the project mutex or null job.process
- // here, or a replacement render could spawn and overlap it. Record the
- // reason; the pending 'close' runs the sole terminal finalization.
- job.lastError = `ffmpeg process error: ${err.message}`;
- console.log(`⚠️ Timeline render post-spawn error [${jobId.slice(0, 8)}]: ${err.message}`);
- return;
- }
- // Pre-spawn failure: the child never started, so 'close' won't follow —
- // finalize here.
- terminal = true;
+ // Spawn-state tracking + exactly-once terminal guard + pre-vs-post-spawn
+ // dispatch live in the shared helper; only the finalize bodies below are
+ // service-specific (timeline does NOT mutate any project status).
+ attachFfmpegRenderGuard(proc, {
+ label: `Timeline render [${jobId.slice(0, 8)}]`,
+ onProcessError: (err) => {
+ // Post-spawn error (e.g. a failed kill during cancel). The ffmpeg is
+ // still live — do NOT release the project mutex or null job.process
+ // here, or a replacement render could spawn and overlap it. Record the
+ // reason; the pending 'close' runs the sole terminal finalization.
+ job.lastError = `ffmpeg process error: ${err.message}`;
+ console.log(`⚠️ Timeline render post-spawn error [${jobId.slice(0, 8)}]: ${err.message}`);
+ },
+ onSpawnError: (err) => {
+ // Pre-spawn failure: the child never started, so 'close' won't follow.
job.process = null;
job.status = 'error';
const reason = `Failed to spawn ffmpeg: ${err.message}`;
@@ -438,73 +424,68 @@ export async function renderProject(projectId) {
broadcastSse(job, { type: 'error', error: reason });
projectRenders.delete(projectId);
closeJobAfterDelay(jobs, jobId);
- } catch (e) {
- console.error(`❌ Timeline render error handler failed [${jobId.slice(0, 8)}]: ${e.message}`);
- }
- });
-
- proc.on('close', async (code, signal) => {
- // Runs outside the request lifecycle — an uncaught throw from
- // generateThumbnail/loadHistory/saveHistory would crash the process, so
- // wrap the body and surface the failure over SSE instead.
- try {
- if (terminal) return; // a pre-spawn error already finalized this job
- terminal = true;
- job.process = null;
- if (code !== 0) {
- const canceled = signal === 'SIGTERM' || signal === 'SIGKILL';
- // 'canceled' (single l) matches every other SSE emitter in the app —
- // useSseProgress treats it as terminal.
- job.status = canceled ? 'canceled' : 'error';
- const reason = canceled
- ? 'Render cancelled'
- : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;
- job.lastError = reason;
- console.log(`${canceled ? '🛑' : '❌'} Timeline render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);
- await unlink(outputPath).catch(() => {});
- broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
- projectRenders.delete(projectId);
- closeJobAfterDelay(jobs, jobId);
- return;
- }
- job.status = 'complete';
- // The encode args already include -movflags +faststart, so no separate
- // remux pass is needed here.
- const thumb = await generateThumbnail(outputPath, jobId);
-
- // Push to existing video history with a timelineProjectId flag so the
- // Media History page picks it up alongside generated clips.
- const renderedNumFrames = Math.round(totalDuration * (fps || 24));
- const meta = {
- id: jobId,
- prompt: `Timeline: ${project.name}`,
- modelId: 'timeline',
- seed: 0,
- width: canonW,
- height: canonH,
- numFrames: renderedNumFrames,
- fps: fps || 24,
- filename,
- thumbnail: thumb,
- createdAt: new Date().toISOString(),
- timelineProjectId: projectId,
- };
- // Serialized append through the single shared history tail so a concurrent
- // download/render/timeline write can't clobber this entry.
- await mutateVideoHistory((history) => { history.unshift(meta); return history; });
- console.log(`✅ Timeline rendered [${jobId.slice(0, 8)}]: ${filename}`);
- broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });
- projectRenders.delete(projectId);
- closeJobAfterDelay(jobs, jobId);
- } catch (err) {
- const reason = `Post-render failed: ${err.message}`;
- job.status = 'error';
- job.lastError = reason;
- console.error(`❌ Timeline render post-processing error [${jobId.slice(0, 8)}]: ${reason}`);
- broadcastSse(job, { type: 'error', error: reason });
- projectRenders.delete(projectId);
- closeJobAfterDelay(jobs, jobId);
- }
+ },
+ onClose: async (code, signal) => {
+ // Runs outside the request lifecycle — an uncaught throw from
+ // generateThumbnail/loadHistory/saveHistory would crash the process, so
+ // wrap the body and surface the failure over SSE instead.
+ try {
+ job.process = null;
+ if (code !== 0) {
+ const canceled = signal === 'SIGTERM' || signal === 'SIGKILL';
+ // 'canceled' (single l) matches every other SSE emitter in the app —
+ // useSseProgress treats it as terminal.
+ job.status = canceled ? 'canceled' : 'error';
+ const reason = canceled
+ ? 'Render cancelled'
+ : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;
+ job.lastError = reason;
+ console.log(`${canceled ? '🛑' : '❌'} Timeline render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);
+ await unlink(outputPath).catch(() => {});
+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });
+ projectRenders.delete(projectId);
+ closeJobAfterDelay(jobs, jobId);
+ return;
+ }
+ job.status = 'complete';
+ // The encode args already include -movflags +faststart, so no separate
+ // remux pass is needed here.
+ const thumb = await generateThumbnail(outputPath, jobId);
+
+ // Push to existing video history with a timelineProjectId flag so the
+ // Media History page picks it up alongside generated clips.
+ const renderedNumFrames = Math.round(totalDuration * (fps || 24));
+ const meta = {
+ id: jobId,
+ prompt: `Timeline: ${project.name}`,
+ modelId: 'timeline',
+ seed: 0,
+ width: canonW,
+ height: canonH,
+ numFrames: renderedNumFrames,
+ fps: fps || 24,
+ filename,
+ thumbnail: thumb,
+ createdAt: new Date().toISOString(),
+ timelineProjectId: projectId,
+ };
+ // Serialized append through the single shared history tail so a concurrent
+ // download/render/timeline write can't clobber this entry.
+ await mutateVideoHistory((history) => { history.unshift(meta); return history; });
+ console.log(`✅ Timeline rendered [${jobId.slice(0, 8)}]: ${filename}`);
+ broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });
+ projectRenders.delete(projectId);
+ closeJobAfterDelay(jobs, jobId);
+ } catch (err) {
+ const reason = `Post-render failed: ${err.message}`;
+ job.status = 'error';
+ job.lastError = reason;
+ console.error(`❌ Timeline render post-processing error [${jobId.slice(0, 8)}]: ${reason}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ projectRenders.delete(projectId);
+ closeJobAfterDelay(jobs, jobId);
+ }
+ },
});
return { jobId };