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: stop a failed audio mux from marking a finished CD stitch as failed (#7237)

[._.]/ Adam Eivy957676acfb55
diff --git a/server/lib/README.md b/server/lib/README.md
index a798e8f51b..7d5356728b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -343,7 +343,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → 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`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |
-| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. |
+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |
| `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. |
| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
| `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. |
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index d07c916081..3ae85fe06f 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -471,13 +471,16 @@ const appendFilter = (chain, filter) => {
// .bak first, install the new file, and restore the backup on any failure, so
// the worst case is "the operation was skipped", never "the video is gone".
//
-// Extracted because three callers (`trimVideoFromFrame`, `upscaleVideo2x`,
+// Extracted because three callers here (`trimVideoFromFrame`, `upscaleVideo2x`,
// `optimizeForStreaming`) need this identical rollback, and a data-loss-
// sensitive path with three copies is one that eventually gets fixed in only
-// two of them. `label` names the operation for the failure message.
+// two of them. Exported for the same reason: `pipeline/audioMux.js` replaces
+// the stitched episode in place from four more entry points, and its own bare
+// `rename` was exactly the copy that never got fixed (#7237). `label` names
+// the operation for the failure message.
//
// Returns `{ ok: true, outPath }` or `{ ok: false, reason }`.
-const installEncodedVideo = async (tmpPath, targetPath, label) => {
+export const installEncodedVideo = async (tmpPath, targetPath, label) => {
let backupPath = null;
try {
if (IS_WIN) {
diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.js
index 0c55d8a010..644866bedc 100644
--- a/server/lib/ffmpeg.test.js
+++ b/server/lib/ffmpeg.test.js
@@ -1,12 +1,12 @@
-import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
+import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
-import { writeFileSync, mkdtempSync, rmSync } from 'fs';
+import { writeFileSync, readFileSync, readdirSync, mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join, resolve } from 'path';
import {
verifyVideoPlayable, safeUnder, runFfmpegProcess, hasAudioStream, buildTrimConcatArgs,
- probeVideoStreamInfo, findFfmpeg,
+ probeVideoStreamInfo, findFfmpeg, installEncodedVideo,
BT709_TAG_FILTER, BT709_CONTAINER_ARGS, bt709TagFilter, supportsSetparamsFilter, __resetSetparamsProbe,
} from './ffmpeg.js';
@@ -364,3 +364,69 @@ describe('bt709TagFilter / supportsSetparamsFilter', () => {
]);
});
});
+
+// The in-place install is the one helper in this module that can destroy an
+// existing video, and it is now shared out to `pipeline/audioMux.js` (#7237) —
+// so its rollback contract is pinned here rather than inferred from the three
+// in-module callers.
+//
+// The failure is injected for real, not stubbed: a tmpPath that does not exist
+// makes the `rename` onto the target fail with ENOENT on BOTH platforms, which
+// is also the only injection that exercises the Windows branch honestly (there
+// the target is moved aside to a .bak first, so the assertion that the original
+// survives is really an assertion that the backup was restored).
+describe('installEncodedVideo', () => {
+ let installDir;
+ beforeEach(() => { installDir = mkdtempSync(join(tmpdir(), 'portos-install-')); });
+ afterEach(() => { rmSync(installDir, { recursive: true, force: true }); });
+
+ it('installs the temp file over the target and reports the target path', async () => {
+ const target = join(installDir, 'clip.mp4');
+ const tmp = join(installDir, 'clip.mp4.tmp');
+ writeFileSync(target, 'original');
+ writeFileSync(tmp, 'encoded');
+
+ expect(await installEncodedVideo(tmp, target, 'trimmed')).toEqual({ ok: true, outPath: target });
+ expect(readFileSync(target, 'utf8')).toBe('encoded');
+ expect(readdirSync(installDir)).toEqual(['clip.mp4']);
+ });
+
+ it('leaves the original byte-identical when the install fails', async () => {
+ const target = join(installDir, 'clip.mp4');
+ writeFileSync(target, 'original');
+ // A tmpPath that does not exist fails the rename with ENOENT on BOTH
+ // platforms — and on Windows it fails AFTER the target has been moved aside
+ // to its .bak, so "the original is still here" is really "the backup was
+ // restored". That branch is unreachable on a POSIX runner, which is why the
+ // temp-file cleanup gets its own injection below.
+ const result = await installEncodedVideo(join(installDir, 'never-encoded.mp4'), target, 'trimmed');
+ expect(result.ok).toBe(false);
+ expect(result.reason).toMatch(/^Failed to install trimmed video: /);
+ expect(readFileSync(target, 'utf8')).toBe('original');
+ expect(readdirSync(installDir)).toEqual(['clip.mp4']);
+ });
+
+ it('removes the temp encode when it cannot be installed', async () => {
+ // Target inside a directory that does not exist: the rename fails ENOENT on
+ // both platforms with the temp file genuinely PRESENT, so the unlink in the
+ // rollback is what this observes. (On Windows the move-aside step also hits
+ // ENOENT and correctly reads as "no original to back up".)
+ const tmp = join(installDir, 'clip.mp4.tmp');
+ writeFileSync(tmp, 'encoded');
+ const result = await installEncodedVideo(tmp, join(installDir, 'gone', 'clip.mp4'), 'upscaled');
+ expect(result.ok).toBe(false);
+ expect(result.reason).toMatch(/^Failed to install upscaled video: /);
+ // The half-finished encode does not accumulate in the videos directory.
+ expect(readdirSync(installDir)).toEqual([]);
+ });
+
+ it('installs onto a target that does not exist yet', async () => {
+ const target = join(installDir, 'fresh.mp4');
+ const tmp = join(installDir, 'fresh.mp4.tmp');
+ writeFileSync(tmp, 'encoded');
+
+ expect(await installEncodedVideo(tmp, target, 'upscaled')).toEqual({ ok: true, outPath: target });
+ expect(readFileSync(target, 'utf8')).toBe('encoded');
+ expect(readdirSync(installDir)).toEqual(['fresh.mp4']);
+ });
+});
diff --git a/server/services/creativeDirector/stitchRunner.test.js b/server/services/creativeDirector/stitchRunner.test.js
new file mode 100644
index 0000000000..ce762d9c3b
--- /dev/null
+++ b/server/services/creativeDirector/stitchRunner.test.js
@@ -0,0 +1,148 @@
+/**
+ * The stitch is where a failed in-place audio mux used to become a USER-VISIBLE
+ * data-loss-shaped bug (#7237): `maybeMuxPipelineAudio` is awaited inside
+ * `runStitch`'s try, so a throw out of the mux landed in the catch that writes
+ * `status: 'failed'` — a successfully rendered and stitched episode was orphaned
+ * on disk, never recorded as `finalVideoId`, and never added to its collection,
+ * with a raw `EPERM: ... rename` as the user-facing reason.
+ *
+ * This pins the degradation contract at that boundary: the mux is best-effort,
+ * so an install failure must cost the audio overlay and nothing else.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, rm, writeFile, readFile, readdir } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+const TEST_HOME = join(tmpdir(), `portos-stitchrunner-test-${process.pid}-${Date.now()}`);
+const VIDEOS_DIR = join(TEST_HOME, 'videos');
+
+const FINAL_ENTRY = { id: 'render-job-1', filename: 'episode.mp4' };
+const EPISODE_BYTES = 'the-stitched-episode';
+const MUXED_BYTES = 'the-muxed-episode';
+
+let cdProject;
+const updateProjectCalls = [];
+const addCollectionItemMock = vi.fn();
+let issue;
+let ffmpegWritesOutput = false;
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return { ...actual, PATHS: { ...actual.PATHS, videos: VIDEOS_DIR } };
+});
+
+vi.mock('./local.js', () => ({
+ getProject: async () => cdProject,
+ updateProject: async (id, patch) => {
+ updateProjectCalls.push(patch);
+ cdProject = { ...cdProject, ...patch };
+ },
+}));
+
+vi.mock('./orchestrator.js', () => ({
+ buildTimelineClips: () => [{ videoId: 'clip-1' }],
+}));
+
+vi.mock('../videoTimeline/local.js', () => ({
+ createProject: async () => ({ id: 'timeline-1' }),
+ updateProject: async () => {},
+ renderProject: async () => ({ jobId: FINAL_ENTRY.id }),
+ getProject: async () => null,
+ getRenderJobStatus: () => ({ status: 'running' }),
+}));
+
+vi.mock('../videoGen/local.js', () => ({ loadHistory: async () => [FINAL_ENTRY] }));
+vi.mock('../mediaCollections.js', () => ({ addItem: (...a) => addCollectionItemMock(...a) }));
+
+vi.mock('../pipeline/issues.js', async () => {
+ const actual = await vi.importActual('../pipeline/issues.js');
+ return { ...actual, getIssue: async () => issue };
+});
+
+// The real `installEncodedVideo` and `runFfmpegProcess` are pulled through —
+// only the binary lookup and the spawn are faked, so the rollback under test is
+// the production one.
+vi.mock('../../lib/ffmpeg.js', async () => {
+ const actual = await vi.importActual('../../lib/ffmpeg.js');
+ return { ...actual, findFfmpeg: async () => '/usr/local/bin/ffmpeg' };
+});
+
+// The fake ffmpeg exits 0; whether it PRODUCES its output file is the switch
+// between the two cases below. Withholding the file makes the in-place install
+// the step that fails, which is the shape of the Windows
+// `rename`-onto-an-existing-destination failure this guards.
+vi.mock('../../lib/childProcess.js', async () => {
+ const actual = await vi.importActual('../../lib/childProcess.js');
+ return {
+ ...actual,
+ spawn: (_bin, args) => {
+ const listeners = {};
+ Promise.resolve().then(async () => {
+ if (ffmpegWritesOutput) {
+ const fsp = await import('fs/promises');
+ await fsp.writeFile(args[args.length - 1], Buffer.from(MUXED_BYTES)).catch(() => {});
+ }
+ listeners.close?.(0, null);
+ });
+ return {
+ stderr: { on: () => {} },
+ on: (event, cb) => { listeners[event] = cb; },
+ kill: () => {},
+ };
+ },
+ };
+});
+
+const { runStitch } = await import('./stitchRunner.js');
+
+beforeEach(async () => {
+ updateProjectCalls.length = 0;
+ addCollectionItemMock.mockReset();
+ addCollectionItemMock.mockResolvedValue(undefined);
+ ffmpegWritesOutput = false;
+ cdProject = {
+ id: 'cd-1',
+ name: 'Ep 1',
+ workspace: 'series',
+ collectionId: 'coll-1',
+ sourceIssueId: 'issue-1',
+ };
+ // 'silent' with no VO lines is the single-mux path: muxStripAudio and nothing
+ // else, so a failure here can only be the in-place install.
+ issue = { stages: { audio: { audioMode: 'silent', lines: [] } } };
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+ await mkdir(VIDEOS_DIR, { recursive: true });
+ await writeFile(join(VIDEOS_DIR, FINAL_ENTRY.filename), Buffer.from(EPISODE_BYTES));
+});
+
+afterEach(async () => {
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('runStitch — audio mux is best-effort', () => {
+ it('completes the stitch when the in-place audio install fails', async () => {
+ await runStitch('cd-1');
+
+ const final = updateProjectCalls.at(-1);
+ expect(final).toMatchObject({ finalVideoId: FINAL_ENTRY.id, status: 'complete', failureReason: null });
+ // The regression wrote status:'failed' with the raw rename errno.
+ expect(updateProjectCalls.some((p) => p.status === 'failed')).toBe(false);
+ // The episode still reaches its collection.
+ expect(addCollectionItemMock).toHaveBeenCalledWith('coll-1', { kind: 'video', ref: FINAL_ENTRY.id });
+ // The rendered episode is intact and nothing was stranded beside it.
+ expect(await readFile(join(VIDEOS_DIR, FINAL_ENTRY.filename), 'utf8')).toBe(EPISODE_BYTES);
+ expect(await readdir(VIDEOS_DIR)).toEqual([FINAL_ENTRY.filename]);
+ });
+
+ it('installs the muxed episode over the original when the mux succeeds', async () => {
+ // The same path with the install able to land, so the failure case above is
+ // a real branch rather than a mux that never does anything either way.
+ ffmpegWritesOutput = true;
+ await runStitch('cd-1');
+
+ expect(updateProjectCalls.at(-1)).toMatchObject({ finalVideoId: FINAL_ENTRY.id, status: 'complete' });
+ expect(await readFile(join(VIDEOS_DIR, FINAL_ENTRY.filename), 'utf8')).toBe(MUXED_BYTES);
+ expect(await readdir(VIDEOS_DIR)).toEqual([FINAL_ENTRY.filename]);
+ });
+});
diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.js
index 97462820a1..862a1d3930 100644
--- a/server/services/pipeline/audioMux.js
+++ b/server/services/pipeline/audioMux.js
@@ -20,10 +20,13 @@
* referencing `[0:a]` against a silent AI-gen clip would abort the whole graph.
* (`muxMusicBed` still replaces the track — it's the no-VO music-only path.)
*
- * Failure handling: this is a value-add overlay, not a correctness gate. If
- * the mux pass throws (ffmpeg missing, malformed audio, etc.), callers
- * should log and leave the silent video in place — graceful degradation
- * beats blocking the whole stitch on an optional cosmetic step.
+ * Failure handling: this is a value-add overlay, not a correctness gate. Every
+ * entry point returns `{ ok: false, reason }` rather than throwing — ffmpeg
+ * missing, malformed audio, AND the in-place install that swaps the muxed file
+ * over the episode (which goes through `installEncodedVideo`, so a rename that
+ * cannot land rolls the original back instead of losing it). Callers log and
+ * leave the prior video in place — graceful degradation beats blocking the
+ * whole stitch on an optional cosmetic step.
*
* ffmpeg floor: the VO graph uses `amix ... normalize=0` + `sidechaincompress`
* (ffmpeg 4.4+, 2021). On an older ffmpeg `muxVoLines` returns ok:false and the
@@ -32,11 +35,11 @@
*/
import { join } from 'path';
-import { rename, unlink } from 'fs/promises';
+import { unlink } from 'fs/promises';
import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { PATHS } from '../../lib/fileUtils.js';
-import { findFfmpeg, runFfmpegProcess, hasAudioStream, safeUnder } from '../../lib/ffmpeg.js';
+import { findFfmpeg, runFfmpegProcess, hasAudioStream, safeUnder, installEncodedVideo } from '../../lib/ffmpeg.js';
import { statMusicTrack } from './musicLibrary.js';
// 0.5 ≈ -6 dB — quiet enough to sit under dialogue once VO mixing lands
@@ -144,9 +147,12 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAU
await unlink(tmpOut).catch(() => {});
return result;
}
- // Rename only after ffmpeg confirms success — a crashed mux pass leaves
- // the silent original intact rather than a half-written video.
- await rename(tmpOut, inputVideoPath);
+ // Install only after ffmpeg confirms success — a crashed mux pass leaves the
+ // silent original intact rather than a half-written video. A failed install
+ // rolls back and degrades to "bed skipped" rather than throwing out of the
+ // caller's stitch (#7237); see the failure-handling note at the top.
+ const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'music bed');
+ if (!installed.ok) return installed;
return { ok: true };
}
@@ -296,7 +302,8 @@ export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = nul
await unlink(tmpOut).catch(() => {});
return result;
}
- await rename(tmpOut, inputVideoPath);
+ const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'VO mux');
+ if (!installed.ok) return installed;
return { ok: true, lineCount: placed.length, ducked: !!usableMusic, clipAudio };
}
@@ -492,7 +499,8 @@ export async function muxCueBed(inputVideoPath, { cues = [], voLines = [], music
await unlink(tmpOut).catch(() => {});
return result;
}
- await rename(tmpOut, inputVideoPath);
+ const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'cue bed');
+ if (!installed.ok) return installed;
return { ok: true, cueCount: placedCues.length, ducked: placedVo.length > 0, clipAudio };
}
@@ -525,7 +533,8 @@ export async function muxStripAudio(inputVideoPath, { signal } = {}) {
await unlink(tmpOut).catch(() => {});
return result;
}
- await rename(tmpOut, inputVideoPath);
+ const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'silent strip');
+ if (!installed.ok) return installed;
return { ok: true };
}
diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.js
index ccc1e3c7df..13b1ca834e 100644
--- a/server/services/pipeline/audioMux.test.js
+++ b/server/services/pipeline/audioMux.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { mkdir, rm, writeFile } from 'fs/promises';
+import { mkdir, readdir, readFile, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
import { escapeRegExp } from '../../lib/textUtils.js';
@@ -39,6 +39,10 @@ vi.mock('../../lib/ffmpeg.js', async () => {
const spawnCalls = [];
let mockExitCode = 0;
let mockStderr = '';
+// Simulate "ffmpeg reported success but its output never landed", which is how
+// the in-place install is driven to a REAL failure without stubbing the helper
+// that performs it. See the #7237 suite at the bottom of this file.
+let mockSkipOutputWrite = false;
vi.mock('../../lib/childProcess.js', async () => {
const actual = await vi.importActual('../../lib/childProcess.js');
const fs = await import('fs/promises');
@@ -56,7 +60,7 @@ vi.mock('../../lib/childProcess.js', async () => {
// that side effect on the success path so the subsequent rename in
// muxMusicBed has a file to move.
Promise.resolve().then(async () => {
- if (mockExitCode === 0) {
+ if (mockExitCode === 0 && !mockSkipOutputWrite) {
const outPath = args[args.length - 1];
await fs.writeFile(outPath, Buffer.from('muxed')).catch(() => {});
}
@@ -74,6 +78,7 @@ beforeEach(async () => {
spawnCalls.length = 0;
mockExitCode = 0;
mockStderr = '';
+ mockSkipOutputWrite = false;
findFfmpegMock.mockReset();
// Default: input video has no audio stream (matches today's silent AI-gen
// clips). Tests that exercise clip-audio preservation opt in explicitly.
@@ -701,3 +706,96 @@ describe('muxStripAudio', () => {
expect(args).not.toContain('-filter_complex');
});
});
+
+// Every entry point here replaces the stitched episode IN PLACE, and all four
+// used to do it with a bare uncaught `rename` (#7237). On Windows that rename
+// always fails (the destination exists), so the throw escaped
+// `stitchRunner.maybeMuxPipelineAudio` — which awaits the mux inside the stitch
+// `try` — and marked a successfully-rendered episode Failed, orphaning it and
+// leaving the temp sibling on disk forever. On POSIX the same throw is reachable
+// on EACCES/ENOSPC/EBUSY.
+//
+// The failure is injected at the real install, not by stubbing
+// `installEncodedVideo`: `mockSkipOutputWrite` makes the fake ffmpeg exit 0
+// WITHOUT producing its output file, so the genuine helper runs, its genuine
+// rename fails, and its genuine rollback is what these assertions observe.
+describe('in-place install failure (graceful degradation, #7237)', () => {
+ beforeEach(() => {
+ findFfmpegMock.mockReset();
+ findFfmpegMock.mockResolvedValue('/usr/local/bin/ffmpeg');
+ hasAudioStreamMock.mockReset();
+ hasAudioStreamMock.mockResolvedValue(false);
+ spawnCalls.length = 0;
+ mockSkipOutputWrite = true;
+ });
+ afterEach(() => { mockSkipOutputWrite = false; });
+
+ const ORIGINAL = 'the-stitched-episode';
+
+ // Each case builds the arguments one mux entry point needs to get all the way
+ // to its install step, so a failure here can only be the install.
+ const cases = [
+ {
+ name: 'muxMusicBed',
+ label: 'music bed',
+ run: async (video) => {
+ const music = join(FAKE_MUSIC_DIR, 'bed.mp3');
+ await writeFile(music, Buffer.from('mus'));
+ return muxMusicBed(video, { musicPath: music });
+ },
+ },
+ {
+ name: 'muxVoLines',
+ label: 'VO mux',
+ run: async (video, assetDir) => {
+ const line = join(assetDir, 'line.wav');
+ await writeFile(line, Buffer.from('wav'));
+ return muxVoLines(video, { voLines: [{ path: line, offsetSec: 1 }], musicPath: null });
+ },
+ },
+ {
+ name: 'muxCueBed',
+ label: 'cue bed',
+ run: async (video, assetDir) => {
+ const cue = join(assetDir, 'cue.wav');
+ await writeFile(cue, Buffer.from('wav'));
+ return muxCueBed(video, { cues: [{ path: cue, startSec: 0, endSec: 30, gain: 0.5 }] });
+ },
+ },
+ {
+ name: 'muxStripAudio',
+ label: 'silent strip',
+ run: async (video) => muxStripAudio(video),
+ },
+ ];
+
+ for (const { name, label, run } of cases) {
+ it(`${name} resolves ok:false instead of throwing, keeps the episode, and leaves no temp file`, async () => {
+ // The episode gets a directory of its OWN — the strict listing below is
+ // what proves no temp sibling (or rolled-back .bak) was stranded, so the
+ // input assets have to live somewhere else.
+ const dir = join(TEST_HOME, name);
+ const assetDir = join(TEST_HOME, `${name}-assets`);
+ await mkdir(dir, { recursive: true });
+ await mkdir(assetDir, { recursive: true });
+ const video = join(dir, 'episode.mp4');
+ await writeFile(video, Buffer.from(ORIGINAL));
+
+ // `.resolves` (not `.rejects`): a throw here is the regression itself,
+ // because it bypasses every `result.ok` branch in stitchRunner.
+ const result = await run(video, assetDir);
+ expect(result.ok).toBe(false);
+ // The reason is the helper's, passed straight through — the errno text
+ // itself is platform-specific (EPERM on Windows, ENOENT here).
+ expect(result.reason).toMatch(new RegExp(`^Failed to install ${label} video: `));
+
+ // ffmpeg really ran — this is the install failing, not an early bail.
+ expect(spawnCalls).toHaveLength(1);
+ // The episode the caller keeps is byte-identical to what it handed in.
+ expect(await readFile(video, 'utf8')).toBe(ORIGINAL);
+ // No `.muxing.` / `.vomux.` / `.cuemux.` / `.silent.` sibling stranded in
+ // the videos directory, and no rolled-back `.bak` either.
+ expect(await readdir(dir)).toEqual(['episode.mp4']);
+ });
+ }
+});