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

fix: separate pre-spawn and post-spawn ffmpeg render errors (#2386)

Adam Eivy82505656fabf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 97620dc070..a69304b5cc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -75,3 +75,5 @@
- **Layered Intelligence loop now supports every provider type.** The per-app AI-provider picker previously listed only `cli` providers, while the reasoning call went through the api-only `callProviderAISimple` — so a selected CLI provider failed at runtime with "requires an API-based provider," and API/TUI providers (Ollama, LM Studio, Claude/Codex/OpenCode TUI, etc.) never appeared at all. The reasoning call now routes through the unified `runPromptThroughProvider`, which dispatches on `provider.type`, and the picker lists all enabled `cli`/`api`/`tui` providers. CLI/TUI spawns run in the app's repo (`cwd`).
- **A "Run now" of Layered Intelligence now tells you what actually happened.** Because the loop is handler-backed — it files one tracker issue rather than spawning a visible agent — a run that filed nothing gave no usable signal: the on-demand toast collapsed every non-filed outcome (reasoning model returned unparseable JSON, a duplicate/near-duplicate was suppressed, it parked on a blocking issue, no AI provider was configured, Jira wasn't set up, the tracker read failed) into a blanket "nothing to do right now," and on mobile that transient toast was easy to miss entirely. The handler now threads the real terminal reason through the on-demand feedback (so the toast reads e.g. "the reasoning model returned no usable JSON — try a non-reasoning model" or "paused on a blocking issue"), and every run persists its outcome (`lastRunAt` / action / reason / filed ref) so Edit App → Intelligence shows a durable **Last run** status line you can check any time. This is what made a reasoning-style local model (which often emits thinking text with no parseable JSON) look like a queued-but-not-running task with no explanation.
- **Rounds and Music Video can now turn a reference audio file into MIDI locally via MuScriptor.** MuScriptor (github.com/muscriptor/muscriptor) is a multi-instrument audio → MIDI transcription model that runs in an opt-in venv (`INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh`, weights auto-download from HuggingFace on first use; small/medium/large tiers). A new shared service (`server/services/audioMidiTranscription.js` + the `scripts/transcribe_muscriptor.py` sidecar, same STAGE:/RESULT: wire protocol as the music-gen sidecars) exposes the kickoff/SSE/cancel job shape in both features: a Rounds reference with attached audio gains a **Transcribe MIDI** control (the resulting `.mid` lands as `references[].midiFilename` on Save, cleared with the audio like segments), and a Music Video project gains a **MIDI** toolbar button + download link (`project.midiTranscription` is persisted server-side on completion and invalidated when the audio source changes, exactly like `audioAnalysis`). When the venv isn't provisioned the kickoff 503s with the install hint instead of a bare spawn error.
+
+- **[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.
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 3fe25ab868..44d4a27957 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -301,6 +301,18 @@ 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();
@@ -324,17 +336,35 @@ export async function renderMusicVideo(projectId) {
});
proc.on('error', async (err) => {
- job.status = 'error';
- const reason = `Failed to spawn ffmpeg: ${err.message}`;
- job.lastError = reason;
- console.log(`❌ Music-video render spawn error [${jobId.slice(0, 8)}]: ${reason}`);
- broadcastSse(job, { type: 'error', error: reason });
- projectRenders.delete(projectId);
- await updateProject(projectId, { status: 'failed' }).catch(() => {});
- closeJobAfterDelay(jobs, jobId);
+ try {
+ 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;
+ }
+ if (terminal) return;
+ terminal = true;
+ job.process = null;
+ job.status = 'error';
+ const reason = `Failed to spawn ffmpeg: ${err.message}`;
+ job.lastError = reason;
+ console.log(`❌ Music-video render spawn error [${jobId.slice(0, 8)}]: ${reason}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ 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';
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
new file mode 100644
index 0000000000..7f901ec8d1
--- /dev/null
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -0,0 +1,152 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// #2386 — exactly-once terminal handling for the music-video renderer that
+// distinguishes a pre-spawn failure (finalize immediately) from a post-spawn
+// error such as a failed kill (retain process + project-mutex ownership until
+// 'close'). These tests drive a fake ffmpeg child process and emit the
+// error/close sequences before AND after 'spawn'.
+
+// A tiny synchronous event emitter — avoids pulling `events` into the hoisted
+// mock factory (which runs before imports resolve).
+const h = vi.hoisted(() => {
+ const procs = [];
+ const makeEmitter = () => {
+ const listeners = {};
+ return {
+ on(ev, fn) { (listeners[ev] ||= []).push(fn); return this; },
+ emit(ev, ...args) {
+ const fns = listeners[ev] || [];
+ for (const fn of fns) fn(...args);
+ return fns.length > 0;
+ },
+ };
+ };
+ const spawn = () => {
+ const p = makeEmitter();
+ p.stderr = makeEmitter();
+ p.kill = () => {};
+ procs.push(p);
+ return p;
+ };
+ return { procs, spawn };
+});
+
+vi.mock('child_process', () => ({ spawn: h.spawn }));
+vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));
+vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}) }));
+vi.mock('../../lib/fileUtils.js', () => ({
+ ensureDir: vi.fn(async () => {}),
+ PATHS: { videos: '/data/videos', videoThumbnails: '/data/thumbs', music: '/data/music', data: '/data' },
+}));
+vi.mock('../../lib/sseUtils.js', () => ({
+ broadcastSse: vi.fn(),
+ attachSseClient: vi.fn(),
+ closeJobAfterDelay: vi.fn(),
+}));
+vi.mock('../../lib/ffmpeg.js', () => ({
+ findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),
+ safeUnder: (root, name) => (name ? `${root}/${name}` : null),
+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),
+ probeVideoDuration: vi.fn(async () => 30),
+}));
+vi.mock('../../lib/processEnv.js', () => ({ safeChildProcessEnv: () => ({}) }));
+vi.mock('../../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn() }));
+vi.mock('../videoGen/local.js', () => ({
+ loadHistory: vi.fn(),
+ mutateVideoHistory: vi.fn(async (fn) => fn([])),
+}));
+vi.mock('../tracks/index.js', () => ({ getTrack: vi.fn() }));
+vi.mock('./projects.js', () => ({ getProject: vi.fn(), updateProject: vi.fn(async () => ({})) }));
+
+import { renderMusicVideo, getRenderJobStatus } from './render.js';
+import { findFfmpeg } from '../../lib/ffmpeg.js';
+import { loadHistory } from '../videoGen/local.js';
+import { getTrack } from '../tracks/index.js';
+import { getProject, updateProject } from './projects.js';
+
+const tick = () => new Promise((r) => setTimeout(r, 0));
+const lastProc = () => h.procs[h.procs.length - 1];
+
+const prime = (projectId) => {
+ getProject.mockResolvedValue({
+ id: projectId, name: 'P', trackId: 't1', status: 'ready',
+ scenes: [{ sceneId: 's1', order: 0, videoHistoryId: 'h1' }],
+ });
+ getTrack.mockResolvedValue({ audioFilename: 'song.wav' });
+ loadHistory.mockResolvedValue([{ id: 'h1', filename: 'a.mp4', width: 768, height: 512, fps: 24, numFrames: 48 }]);
+ findFfmpeg.mockResolvedValue('/usr/bin/ffmpeg');
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.procs.length = 0;
+});
+
+describe('renderMusicVideo terminal handling (#2386)', () => {
+ it('finalizes immediately on a PRE-spawn error and releases the project slot', async () => {
+ const pid = 'pre-1';
+ prime(pid);
+ const { jobId } = await renderMusicVideo(pid);
+ const proc = lastProc();
+
+ // No 'spawn' event → genuine spawn failure. 'close' will not follow.
+ proc.emit('error', new Error('spawn ENOENT'));
+ await tick();
+
+ expect(getRenderJobStatus(jobId).status).toBe('error');
+ expect(getRenderJobStatus(jobId).error).toMatch(/Failed to spawn ffmpeg/);
+ expect(updateProject).toHaveBeenCalledWith(pid, { status: 'failed' });
+
+ // Slot released — a re-render reaches spawn again instead of 409ing.
+ const again = await renderMusicVideo(pid);
+ expect(again.jobId).toBeTruthy();
+ expect(again.jobId).not.toBe(jobId);
+ });
+
+ it('retains the slot on a POST-spawn error until close (no overlapping render)', async () => {
+ const pid = 'post-1';
+ prime(pid);
+ const { jobId } = await renderMusicVideo(pid);
+ const proc = lastProc();
+
+ proc.emit('spawn'); // child is live
+ proc.emit('error', new Error('kill EPERM')); // failed kill, process still running
+ await tick();
+
+ // NOT finalized: status stays running, project not marked failed, slot held.
+ expect(getRenderJobStatus(jobId).status).toBe('running');
+ expect(updateProject).not.toHaveBeenCalledWith(pid, { status: 'failed' });
+ await expect(renderMusicVideo(pid)).rejects.toMatchObject({
+ status: 409, code: 'RENDER_IN_PROGRESS', context: { jobId },
+ });
+
+ // 'close' is the sole terminal handler for the post-spawn error.
+ proc.emit('close', 1, null);
+ await tick();
+ expect(getRenderJobStatus(jobId).status).toBe('error');
+ expect(updateProject).toHaveBeenCalledWith(pid, { status: 'failed' });
+
+ // Slot now released.
+ const again = await renderMusicVideo(pid);
+ expect(again.jobId).not.toBe(jobId);
+ });
+
+ it('handles terminal state exactly once (a stray close after a pre-spawn error is a no-op)', async () => {
+ const pid = 'once-1';
+ prime(pid);
+ const { jobId } = await renderMusicVideo(pid);
+ const proc = lastProc();
+
+ proc.emit('error', new Error('spawn ENOENT'));
+ await tick();
+ proc.emit('close', 1, null); // must not re-finalize / double-release
+ await tick();
+
+ // updateProject('failed') fired exactly once for this project.
+ const failedCalls = updateProject.mock.calls.filter(
+ ([id, patch]) => id === pid && patch && patch.status === 'failed',
+ );
+ expect(failedCalls).toHaveLength(1);
+ expect(getRenderJobStatus(jobId).status).toBe('error');
+ });
+});
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index ded2301b67..c7a4cb83c1 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -373,6 +373,18 @@ 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.
@@ -401,13 +413,29 @@ export async function renderProject(projectId) {
});
proc.on('error', (err) => {
- job.status = 'error';
- const reason = `Failed to spawn ffmpeg: ${err.message}`;
- job.lastError = reason;
- console.log(`❌ Timeline render spawn error [${jobId.slice(0, 8)}]: ${reason}`);
- broadcastSse(job, { type: 'error', error: reason });
- projectRenders.delete(projectId);
- closeJobAfterDelay(jobs, jobId);
+ try {
+ 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;
+ }
+ if (terminal) return;
+ terminal = true;
+ job.process = null;
+ job.status = 'error';
+ const reason = `Failed to spawn ffmpeg: ${err.message}`;
+ job.lastError = reason;
+ console.log(`❌ Timeline render spawn error [${jobId.slice(0, 8)}]: ${reason}`);
+ 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) => {
@@ -415,6 +443,8 @@ export async function renderProject(projectId) {
// 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';
diff --git a/server/services/videoTimeline/local.terminal.test.js b/server/services/videoTimeline/local.terminal.test.js
new file mode 100644
index 0000000000..df0d4e41de
--- /dev/null
+++ b/server/services/videoTimeline/local.terminal.test.js
@@ -0,0 +1,140 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// #2386 — exactly-once terminal handling for the timeline renderer that
+// distinguishes a pre-spawn failure (finalize immediately) from a post-spawn
+// error such as a failed kill (retain process + project-mutex ownership until
+// 'close'). Drives a fake ffmpeg child process through error/close sequences
+// before AND after 'spawn'.
+
+const h = vi.hoisted(() => {
+ const procs = [];
+ const makeEmitter = () => {
+ const listeners = {};
+ return {
+ on(ev, fn) { (listeners[ev] ||= []).push(fn); return this; },
+ emit(ev, ...args) {
+ const fns = listeners[ev] || [];
+ for (const fn of fns) fn(...args);
+ return fns.length > 0;
+ },
+ };
+ };
+ const spawn = () => {
+ const p = makeEmitter();
+ p.stdout = makeEmitter();
+ p.stderr = makeEmitter();
+ p.kill = () => {};
+ procs.push(p);
+ return p;
+ };
+ return { procs, spawn };
+});
+
+vi.mock('child_process', () => ({ spawn: h.spawn }));
+vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));
+vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}) }));
+vi.mock('../../lib/fileUtils.js', () => ({
+ ensureDir: vi.fn(async () => {}),
+ atomicWrite: vi.fn(async () => {}),
+ readJSONFile: vi.fn(async () => []),
+ PATHS: { videos: '/data/videos', videoThumbnails: '/data/thumbs', data: '/data' },
+}));
+vi.mock('../../lib/sseUtils.js', () => ({
+ broadcastSse: vi.fn(),
+ attachSseClient: vi.fn(),
+ closeJobAfterDelay: vi.fn(),
+}));
+vi.mock('../../lib/ffmpeg.js', () => ({
+ findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),
+ findFfprobe: vi.fn(async () => null), // → probeAudio returns false without spawning
+ safeUnder: (root, name) => (name ? `${root}/${name}` : null),
+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),
+}));
+vi.mock('../../lib/processEnv.js', () => ({ safeChildProcessEnv: () => ({}) }));
+vi.mock('../../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn() }));
+vi.mock('../videoGen/local.js', () => ({
+ loadHistory: vi.fn(),
+ mutateVideoHistory: vi.fn(async (fn) => fn([])),
+}));
+
+import { renderProject, getRenderJobStatus } from './local.js';
+import { readJSONFile } from '../../lib/fileUtils.js';
+import { loadHistory } from '../videoGen/local.js';
+
+const tick = () => new Promise((r) => setTimeout(r, 0));
+const lastProc = () => h.procs[h.procs.length - 1];
+
+const prime = (projectId) => {
+ readJSONFile.mockResolvedValue([
+ { id: projectId, name: 'P', clips: [{ clipId: 'c1', inSec: 0, outSec: 2 }] },
+ ]);
+ loadHistory.mockResolvedValue([
+ { id: 'c1', filename: 'a.mp4', numFrames: 48, fps: 24, width: 768, height: 512 },
+ ]);
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.procs.length = 0;
+});
+
+describe('renderProject terminal handling (#2386)', () => {
+ it('finalizes immediately on a PRE-spawn error and releases the project slot', async () => {
+ const pid = 'tpre-1';
+ prime(pid);
+ const { jobId } = await renderProject(pid);
+ const proc = lastProc();
+
+ proc.emit('error', new Error('spawn ENOENT')); // no 'spawn' first
+ await tick();
+
+ expect(getRenderJobStatus(jobId).status).toBe('error');
+ expect(getRenderJobStatus(jobId).error).toMatch(/Failed to spawn ffmpeg/);
+
+ // Slot released — a re-render reaches spawn again instead of 409ing.
+ const again = await renderProject(pid);
+ expect(again.jobId).toBeTruthy();
+ expect(again.jobId).not.toBe(jobId);
+ });
+
+ it('retains the slot on a POST-spawn error until close (no overlapping render)', async () => {
+ const pid = 'tpost-1';
+ prime(pid);
+ const { jobId } = await renderProject(pid);
+ const proc = lastProc();
+
+ proc.emit('spawn');
+ proc.emit('error', new Error('kill EPERM')); // failed kill, process still running
+ await tick();
+
+ expect(getRenderJobStatus(jobId).status).toBe('running');
+ await expect(renderProject(pid)).rejects.toMatchObject({
+ status: 409, code: 'RENDER_IN_PROGRESS', context: { jobId },
+ });
+
+ proc.emit('close', 1, null); // sole terminal handler for the post-spawn error
+ await tick();
+ expect(getRenderJobStatus(jobId).status).toBe('error');
+
+ const again = await renderProject(pid);
+ expect(again.jobId).not.toBe(jobId);
+ });
+
+ it('handles terminal state exactly once (a stray close after a pre-spawn error is a no-op)', async () => {
+ const pid = 'tonce-1';
+ prime(pid);
+ const { jobId } = await renderProject(pid);
+ const proc = lastProc();
+
+ proc.emit('error', new Error('spawn ENOENT'));
+ await tick();
+ const afterError = getRenderJobStatus(jobId);
+ proc.emit('close', 1, null); // must not re-finalize
+ await tick();
+
+ // Status unchanged by the stray close; still the pre-spawn error outcome.
+ expect(afterError.status).toBe('error');
+ expect(getRenderJobStatus(jobId).status).toBe('error');
+ expect(getRenderJobStatus(jobId).error).toMatch(/Failed to spawn ffmpeg/);
+ });
+});