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: isolate video conditioning preparation and cleanup (#7124)
[._.]/ Adam Eivyfca982907ec1
diff --git a/server/services/videoGen/conditioningMedia.js b/server/services/videoGen/conditioningMedia.jsnew file mode 100644index 0000000000..d9af3273f8--- /dev/null+++ b/server/services/videoGen/conditioningMedia.js@@ -0,0 +1,213 @@+import { execFile } from '../../lib/childProcess.js';+import { promisify } from 'util';+import { join, basename } from 'path';+import { tmpdir } from 'os';+import { unlinkGuarded } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';+import { safeChildProcessOptions } from '../../lib/processEnv.js';+import { isIcLoraMode, icLoraSpecForMode } from '../../lib/icLoraWeights.js';+import { modelAnchorsLastFrame, routesToWindowsHelper } from './runtimes.js';+import { IC_STILL_REFERENCE_FRAMES } from './renderArgs.js';++const execFileAsync = promisify(execFile);++/** Resolve local conditioning media and return its existing cleanup capability.+ * Derived files are always owned here; upload/audio cleanup stays caller-selected.+ */+export async function prepareVideoConditioningMedia({+ model, mode, sourceImagePath, lastImagePath, keyframes, icReferencePaths,+ w, h, parsedFps, jobId, uploadedTempPath, uploadedTempPaths, audioFilePath,+}) {+ // Resize conditioning images to match the model resolution. mlx_video and+ // ltx2 both require exact dimensions (they don't auto-pad), and pixie-forge+ // learned the hard way that letting the model upscale a portrait reference+ // makes garbled output.+ //+ // Skip the last-image resize when buildArgs / the Python child won't+ // actually consume it:+ // - A last-frame-anchored runtime (see LAST_FRAME_ANCHORED_RUNTIMES) really+ // consumes both frames — ltx2 via --image/--last-image, MiniMax H3 via+ // --image/--anchor pairs — so resize the last frame even when a source+ // image is also present.+ // - On macOS/mlx_video the FFLF fallback only consumes the last image when+ // no source image is also provided (single conditioning frame only).+ // Anything else is a no-op, so resizing is wasted ffmpeg work.+ // - A model that routes to generate_win.py takes --last-image only so the+ // script can log status; the LTX-Video 0.9.5 pipeline reads --image+ // alone, so it never opens the last-frame file. That gate keys on the+ // RUNNER, not on the platform (see routesToWindowsHelper): both Windows+ // and Linux have BYOV runtimes whose helper genuinely anchors the last+ // frame, and a bare platform check would hand them an unresized frame.+ const lastImageWillBeUsed = !!lastImagePath && !routesToWindowsHelper(model) && mode === 'fflf'+ && (modelAnchorsLastFrame(model) || !sourceImagePath);+ // A non-null `keyframes` that ISN'T a length-≥2 array is malformed —+ // fail fast instead of silently dropping it (which would produce an+ // unexpected text/i2v render with the user's anchors ignored). The+ // route guarantees the array shape, but non-route callers (tests,+ // persisted queue replays) could pass a stray scalar/empty array.+ if (keyframes != null && !(Array.isArray(keyframes) && keyframes.length >= 2)) {+ throw new ServerError(+ `keyframes must be null OR an array of length >= 2; got ${Array.isArray(keyframes) ? `array(length=${keyframes.length})` : typeof keyframes}`,+ { status: 400, code: 'KEYFRAME_INVALID_SHAPE' },+ );+ }+ const hasMultiKeyframes = Array.isArray(keyframes) && keyframes.length >= 2;+ const ffmpeg = (sourceImagePath || lastImageWillBeUsed || hasMultiKeyframes) ? await findFfmpeg() : null;+ const ffprobe = model.runtime === 'minimax_h3_ref2va' ? await findFfprobe() : null;+ const resizeImage = async (srcPath, tag) => {+ if (!srcPath || !ffmpeg) return { resolved: srcPath, tempPath: null };+ const resizedPath = join(tmpdir(), `resized-${tag}-${jobId}.png`);+ const resizeResult = await execFileAsync(ffmpeg, [+ '-i', srcPath,+ '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,+ '-update', '1', '-frames:v', '1',+ '-y', resizedPath,+ ], safeChildProcessOptions({ timeout: 10000 })).catch((err) => ({ error: err }));+ if (resizeResult.error) {+ console.log(`⚠️ Failed to resize ${tag} image, using original: ${resizeResult.error.message}`);+ return { resolved: srcPath, tempPath: null };+ }+ return { resolved: resizedPath, tempPath: resizedPath };+ };+ // Two independent ffmpeg spawns — fan out for the same reason the keyframe+ // loop below does, so a true-FFLF render doesn't pay them back to back.+ const [+ { resolved: resolvedSourceImage, tempPath: resizedSrcTempPath },+ { resolved: resolvedLastImage, tempPath: resizedLastTempPath },+ ] = await Promise.all([+ resizeImage(sourceImagePath, 'src'),+ lastImageWillBeUsed+ ? resizeImage(lastImagePath, 'last')+ : { resolved: lastImagePath, tempPath: null },+ ]);+ // Resize each multi-keyframe image to the target resolution (the helper+ // requires exact W×H, same as i2v). Indices pass through unchanged.+ // Each ffmpeg subprocess is independent — fan out so 8 keyframes don't+ // serialize behind 7 unrelated ffmpeg startups.+ const resizedKeyframeTempPaths = [];+ let resolvedKeyframes = null;+ if (hasMultiKeyframes) {+ // The route validates shape, but a non-route caller (test, persisted+ // queue replay, future internal API) could pass malformed entries.+ // Fail fast with a clear error instead of letting `undefined` paths+ // flow into ffmpeg or the Python helper, where the failure is opaque.+ keyframes.forEach((kf, i) => {+ if (!kf || typeof kf !== 'object') {+ throw new ServerError(`keyframes[${i}] must be an object: got ${typeof kf}`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });+ }+ if (typeof kf.path !== 'string' || !kf.path) {+ throw new ServerError(`keyframes[${i}].path must be a non-empty string`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });+ }+ // The Python helper enforces `index` is an int; a float or numeric+ // string here would crash mid-render. Coerce + verify integerness+ // up-front so non-route callers (tests, persisted queue replays)+ // get a clear 400 instead of a Python traceback.+ const n = Number(kf.index);+ if (!Number.isInteger(n)) {+ throw new ServerError(`keyframes[${i}].index must be an integer: got ${kf.index}`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });+ }+ });+ const results = await Promise.all(keyframes.map((kf, i) => resizeImage(kf.path, `kf${i}`)));+ resolvedKeyframes = results.map((r, i) => {+ if (r.tempPath) resizedKeyframeTempPaths.push(r.tempPath);+ // Normalize index to a real Number so the JSON we hand to the+ // Python helper is unambiguous (no '5' string sneaking through+ // from a multipart form).+ return { path: r.resolved, index: Number(keyframes[i].index) };+ });+ }++ // An `image`-kind IC weight (Ingredients) takes STILLS, but the pipeline's+ // reference channel is a video encoder end-to-end: iclora_utils probes the+ // reference with ffprobe and feeds it to the VAE, which requires a (1 + 8k)+ // frame count. A bare PNG has neither a probeable frame count nor 9 frames, so+ // materialize each still into a tiny 9-frame constant clip at the render+ // resolution first. 9 = the smallest legal (1 + 8k) count, so this is the+ // cheapest possible encode and every frame is identical — the reference is a+ // still either way.+ //+ // Done here rather than in the route because the target resolution is only+ // known after the resolution flooring in the renderer, and it mirrors resizeImage's contract:+ // temp paths are tracked for the same cleanup sites.+ const icReferenceTempPaths = [];+ // Both throw sites in this block land BEFORE the renderer's buildArgs try/catch+ // (whose catch is what normally unlinks resizedSrcTempPath/+ // resizedLastTempPath/resizedKeyframeTempPaths/icReferenceTempPaths) — a+ // throw here escapes uncaught by that cleanup, and the caller's outer catch+ // only unlinks the route-level upload/audio temp files, not these+ // internally-created resize/still-clip temp files. Clean them up explicitly+ // before either throw so a missing ffmpeg or a failed still-encode doesn't+ // leak every resized temp file for the request into os.tmpdir().+ const cleanupTempFiles = ({ includeUploads = false, includeUntrackedAudio = false } = {}) => {+ const paths = [+ resizedSrcTempPath,+ resizedLastTempPath,+ ...resizedKeyframeTempPaths,+ ...icReferenceTempPaths,+ ...(includeUploads ? [uploadedTempPath, ...uploadedTempPaths] : []),+ ...(includeUntrackedAudio && audioFilePath && !uploadedTempPaths.includes(audioFilePath)+ ? [audioFilePath]+ : []),+ ];+ return Promise.all(paths.filter(Boolean).map((path) => unlinkGuarded(path).catch(() => {})));+ };+ const resolvedIcReferencePaths = await materializeIngredientsReferences({+ mode, icReferencePaths, ffmpeg, w, h, parsedFps, jobId,+ icReferenceTempPaths, cleanupTempFiles,+ });+ return {+ resolvedSourceImage, resolvedLastImage, resolvedKeyframes, resolvedIcReferencePaths,+ hasMultiKeyframes, ffmpeg, ffprobe, cleanupTempFiles,+ };+}++/** Materialize Ingredients stills, settling every encode before failure cleanup. */+async function materializeIngredientsReferences({+ mode, icReferencePaths, ffmpeg, w, h, parsedFps, jobId,+ icReferenceTempPaths, cleanupTempFiles,+}) {+ if (isIcLoraMode(mode) && icLoraSpecForMode(mode)?.referenceKind === 'image'+ && Array.isArray(icReferencePaths) && icReferencePaths.length) {+ const stillFfmpeg = ffmpeg || await findFfmpeg();+ if (!stillFfmpeg) {+ await cleanupTempFiles();+ throw new ServerError(+ 'ffmpeg is required to prepare still references for Ingredients mode — install it (brew install ffmpeg) and retry.',+ { status: 400, code: 'IC_LORA_STILL_NEEDS_FFMPEG' },+ );+ }+ // Register EVERY target path up-front, before any encode starts, and settle+ // all of them before deciding. `Promise.all` + push-on-success would reject+ // at the first failure while sibling encodes were still in flight, so their+ // files would land after cleanup already ran and leak. Registering the paths+ // eagerly also means the outer error/close handlers can clean up regardless+ // of which encodes finished.+ const clipPaths = icReferencePaths.map((_, i) => join(tmpdir(), `ic-still-${i}-${jobId}.mp4`));+ icReferenceTempPaths.push(...clipPaths);+ const encodes = await Promise.all(icReferencePaths.map((stillPath, i) => execFileAsync(stillFfmpeg, [+ '-loop', '1', '-i', stillPath,+ '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,+ '-frames:v', String(IC_STILL_REFERENCE_FRAMES),+ '-r', String(parsedFps),+ '-pix_fmt', 'yuv420p', '-an',+ '-y', clipPaths[i],+ ], safeChildProcessOptions({ timeout: 30000 })).catch((err) => ({ error: err }))));+ const failedAt = encodes.findIndex((r) => r?.error);+ if (failedAt !== -1) {+ // Unlike the resizeImage fallback (which degrades to the original), there is+ // no usable degradation here — a still handed straight to the pipeline fails+ // deep inside the VAE reshape. Fail loudly with the ffmpeg reason.+ // cleanupTempFiles() also unlinks clipPaths (already pushed into+ // icReferenceTempPaths above), plus any earlier resize temp files.+ await cleanupTempFiles();+ throw new ServerError(+ `Failed to prepare Ingredients reference ${basename(icReferencePaths[failedAt])}: ${encodes[failedAt].error.message}`,+ { status: 400, code: 'IC_LORA_STILL_PREP_FAILED' },+ );+ }+ return clipPaths;+ }++ return icReferencePaths;+}diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex 3a9a8442a9..849fd7aedf 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -1,3 +1,4 @@+import { prepareVideoConditioningMedia } from './conditioningMedia.js';import { planVideoBatch, supportsWarmVideoBatch, validateVideoBatch } from './batch.js';import { normalizeVideoFailure } from '../../lib/videoFailure.js';/**@@ -12,13 +13,11 @@ import { normalizeVideoFailure } from '../../lib/videoFailure.js';* the model sees them.*/-import { execFile } from '../../lib/childProcess.js';import { mkdtemp } from 'fs/promises';import { join, basename } from 'path';import { tmpdir } from 'os';import { randomUUID } from 'crypto';-import { promisify } from 'util';-import { ensureDir, PATHS, unlinkGuarded, rmGuarded } from '../../lib/fileUtils.js';+import { ensureDir, PATHS, rmGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { wan22FrameCountError } from './wan22Controls.js';import {@@ -29,9 +28,7 @@ import { broadcastSse, closeJobAfterDelay } from '../../lib/sseUtils.js';import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';import { hardwareUnavailableReason, isHardwareCompatible } from '../../lib/systemCapabilities.js';import { resolveVideoModelSelection } from './modelSelection.js';-import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';import { findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';-import { safeChildProcessOptions } from '../../lib/processEnv.js';import { describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';import { readTriggerWordsByFilename, readLoraLicensesByFilename } from '../loras.js';import { provenanceForRender } from '../../lib/assetProvenance.js';@@ -41,7 +38,7 @@ import {publicVideoTextEncoderOptions, resolveVideoTextEncoder,} from '../../lib/videoTextEncoders.js';import {- isIcLoraMode, icLoraSpecForMode, resolveIcLoraWeight,+ isIcLoraMode, resolveIcLoraWeight,} from '../../lib/icLoraWeights.js';import {BYOV_VIDEO_RUNTIMES,@@ -61,7 +58,6 @@ import {assertRenderModeContract,buildArgs,DEFAULT_NUM_FRAMES,- IC_STILL_REFERENCE_FRAMES,resolveVideoDimensions,resolveVideoLoras,resolveT2vTwoStageOverride,@@ -93,12 +89,10 @@ export {icLoraArgs,ltx25TextEncoderArgs,DEFAULT_NUM_FRAMES,- IC_STILL_REFERENCE_FRAMES,} from './renderArgs.js';export { attachSseClient, cancel } from './jobState.js';export { loadHistory, saveHistory, mutateVideoHistory, getHistoryItem };-const execFileAsync = promisify(execFile);// Catalog comes from data/media-models.json (see server/lib/mediaModels.js).// Cached as a plain object at boot for O(1) lookup by id, matching the prior shape.@@ -489,181 +483,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst parsedNumFrames = Number(numFrames);const parsedFps = Number(fps);- // Resize conditioning images to match the model resolution. mlx_video and- // ltx2 both require exact dimensions (they don't auto-pad), and pixie-forge- // learned the hard way that letting the model upscale a portrait reference- // makes garbled output.- //- // Skip the last-image resize when buildArgs / the Python child won't- // actually consume it:- // - A last-frame-anchored runtime (see LAST_FRAME_ANCHORED_RUNTIMES) really- // consumes both frames — ltx2 via --image/--last-image, MiniMax H3 via- // --image/--anchor pairs — so resize the last frame even when a source- // image is also present.- // - On macOS/mlx_video the FFLF fallback only consumes the last image when- // no source image is also provided (single conditioning frame only).- // Anything else is a no-op, so resizing is wasted ffmpeg work.- // - A model that routes to generate_win.py takes --last-image only so the- // script can log status; the LTX-Video 0.9.5 pipeline reads --image- // alone, so it never opens the last-frame file. That gate keys on the- // RUNNER, not on the platform (see routesToWindowsHelper): both Windows- // and Linux have BYOV runtimes whose helper genuinely anchors the last- // frame, and a bare platform check would hand them an unresized frame.- const lastImageWillBeUsed = !!lastImagePath && !routesToWindowsHelper(model) && mode === 'fflf'- && (modelAnchorsLastFrame(model) || !sourceImagePath);- // A non-null `keyframes` that ISN'T a length-≥2 array is malformed —- // fail fast instead of silently dropping it (which would produce an- // unexpected text/i2v render with the user's anchors ignored). The- // route guarantees the array shape, but non-route callers (tests,- // persisted queue replays) could pass a stray scalar/empty array.- if (keyframes != null && !(Array.isArray(keyframes) && keyframes.length >= 2)) {- throw new ServerError(- `keyframes must be null OR an array of length >= 2; got ${Array.isArray(keyframes) ? `array(length=${keyframes.length})` : typeof keyframes}`,- { status: 400, code: 'KEYFRAME_INVALID_SHAPE' },- );- }- const hasMultiKeyframes = Array.isArray(keyframes) && keyframes.length >= 2;- const ffmpeg = (sourceImagePath || lastImageWillBeUsed || hasMultiKeyframes) ? await findFfmpeg() : null;- const ffprobe = model.runtime === 'minimax_h3_ref2va' ? await findFfprobe() : null;- const resizeImage = async (srcPath, tag) => {- if (!srcPath || !ffmpeg) return { resolved: srcPath, tempPath: null };- const resizedPath = join(tmpdir(), `resized-${tag}-${jobId}.png`);- const resizeResult = await execFileAsync(ffmpeg, [- '-i', srcPath,- '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,- '-update', '1', '-frames:v', '1',- '-y', resizedPath,- ], safeChildProcessOptions({ timeout: 10000 })).catch((err) => ({ error: err }));- if (resizeResult.error) {- console.log(`⚠️ Failed to resize ${tag} image, using original: ${resizeResult.error.message}`);- return { resolved: srcPath, tempPath: null };- }- return { resolved: resizedPath, tempPath: resizedPath };- };- // Two independent ffmpeg spawns — fan out for the same reason the keyframe- // loop below does, so a true-FFLF render doesn't pay them back to back.- const [- { resolved: resolvedSourceImage, tempPath: resizedSrcTempPath },- { resolved: resolvedLastImage, tempPath: resizedLastTempPath },- ] = await Promise.all([- resizeImage(sourceImagePath, 'src'),- lastImageWillBeUsed- ? resizeImage(lastImagePath, 'last')- : { resolved: lastImagePath, tempPath: null },- ]);- // Resize each multi-keyframe image to the target resolution (the helper- // requires exact W×H, same as i2v). Indices pass through unchanged.- // Each ffmpeg subprocess is independent — fan out so 8 keyframes don't- // serialize behind 7 unrelated ffmpeg startups.- const resizedKeyframeTempPaths = [];- let resolvedKeyframes = null;- if (hasMultiKeyframes) {- // The route validates shape, but a non-route caller (test, persisted- // queue replay, future internal API) could pass malformed entries.- // Fail fast with a clear error instead of letting `undefined` paths- // flow into ffmpeg or the Python helper, where the failure is opaque.- keyframes.forEach((kf, i) => {- if (!kf || typeof kf !== 'object') {- throw new ServerError(`keyframes[${i}] must be an object: got ${typeof kf}`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });- }- if (typeof kf.path !== 'string' || !kf.path) {- throw new ServerError(`keyframes[${i}].path must be a non-empty string`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });- }- // The Python helper enforces `index` is an int; a float or numeric- // string here would crash mid-render. Coerce + verify integerness- // up-front so non-route callers (tests, persisted queue replays)- // get a clear 400 instead of a Python traceback.- const n = Number(kf.index);- if (!Number.isInteger(n)) {- throw new ServerError(`keyframes[${i}].index must be an integer: got ${kf.index}`, { status: 400, code: 'KEYFRAME_INVALID_SHAPE' });- }- });- const results = await Promise.all(keyframes.map((kf, i) => resizeImage(kf.path, `kf${i}`)));- resolvedKeyframes = results.map((r, i) => {- if (r.tempPath) resizedKeyframeTempPaths.push(r.tempPath);- // Normalize index to a real Number so the JSON we hand to the- // Python helper is unambiguous (no '5' string sneaking through- // from a multipart form).- return { path: r.resolved, index: Number(keyframes[i].index) };- });- }-- // An `image`-kind IC weight (Ingredients) takes STILLS, but the pipeline's- // reference channel is a video encoder end-to-end: iclora_utils probes the- // reference with ffprobe and feeds it to the VAE, which requires a (1 + 8k)- // frame count. A bare PNG has neither a probeable frame count nor 9 frames, so- // materialize each still into a tiny 9-frame constant clip at the render- // resolution first. 9 = the smallest legal (1 + 8k) count, so this is the- // cheapest possible encode and every frame is identical — the reference is a- // still either way.- //- // Done here rather than in the route because the target resolution is only- // known after the 64-flooring above, and it mirrors resizeImage's contract:- // temp paths are tracked for the same cleanup sites.- const icReferenceTempPaths = [];- let resolvedIcReferencePaths = icReferencePaths;- // Both throw sites in this block land BEFORE the buildArgs try/catch below- // (whose catch is what normally unlinks resizedSrcTempPath/- // resizedLastTempPath/resizedKeyframeTempPaths/icReferenceTempPaths) — a- // throw here escapes uncaught by that cleanup, and the caller's outer catch- // only unlinks the route-level upload/audio temp files, not these- // internally-created resize/still-clip temp files. Clean them up explicitly- // before either throw so a missing ffmpeg or a failed still-encode doesn't- // leak every resized temp file for the request into os.tmpdir().- const cleanupTempFiles = ({ includeUploads = false, includeUntrackedAudio = false } = {}) => {- const paths = [- resizedSrcTempPath,- resizedLastTempPath,- ...resizedKeyframeTempPaths,- ...icReferenceTempPaths,- ...(includeUploads ? [uploadedTempPath, ...uploadedTempPaths] : []),- ...(includeUntrackedAudio && audioFilePath && !uploadedTempPaths.includes(audioFilePath)- ? [audioFilePath]- : []),- ];- return Promise.all(paths.filter(Boolean).map((path) => unlinkGuarded(path).catch(() => {})));- };- if (isIcLoraMode(mode) && icLoraSpecForMode(mode)?.referenceKind === 'image'- && Array.isArray(icReferencePaths) && icReferencePaths.length) {- const stillFfmpeg = ffmpeg || await findFfmpeg();- if (!stillFfmpeg) {- await cleanupTempFiles();- throw new ServerError(- 'ffmpeg is required to prepare still references for Ingredients mode — install it (brew install ffmpeg) and retry.',- { status: 400, code: 'IC_LORA_STILL_NEEDS_FFMPEG' },- );- }- // Register EVERY target path up-front, before any encode starts, and settle- // all of them before deciding. `Promise.all` + push-on-success would reject- // at the first failure while sibling encodes were still in flight, so their- // files would land after cleanup already ran and leak. Registering the paths- // eagerly also means the outer error/close handlers can clean up regardless- // of which encodes finished.- const clipPaths = icReferencePaths.map((_, i) => join(tmpdir(), `ic-still-${i}-${jobId}.mp4`));- icReferenceTempPaths.push(...clipPaths);- const encodes = await Promise.all(icReferencePaths.map((stillPath, i) => execFileAsync(stillFfmpeg, [- '-loop', '1', '-i', stillPath,- '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,- '-frames:v', String(IC_STILL_REFERENCE_FRAMES),- '-r', String(parsedFps),- '-pix_fmt', 'yuv420p', '-an',- '-y', clipPaths[i],- ], safeChildProcessOptions({ timeout: 30000 })).catch((err) => ({ error: err }))));- const failedAt = encodes.findIndex((r) => r?.error);- if (failedAt !== -1) {- // Unlike the resizeImage fallback (which degrades to the original), there is- // no usable degradation here — a still handed straight to the pipeline fails- // deep inside the VAE reshape. Fail loudly with the ffmpeg reason.- // cleanupTempFiles() also unlinks clipPaths (already pushed into- // icReferenceTempPaths above), plus any earlier resize temp files.- await cleanupTempFiles();- throw new ServerError(- `Failed to prepare Ingredients reference ${basename(icReferencePaths[failedAt])}: ${encodes[failedAt].error.message}`,- { status: 400, code: 'IC_LORA_STILL_PREP_FAILED' },- );- }- resolvedIcReferencePaths = clipPaths;- }+ const {+ resolvedSourceImage, resolvedLastImage, resolvedKeyframes, resolvedIcReferencePaths,+ hasMultiKeyframes, ffmpeg, ffprobe, cleanupTempFiles,+ } = await prepareVideoConditioningMedia({+ model, mode, sourceImagePath, lastImagePath, keyframes, icReferencePaths,+ w, h, parsedFps, jobId, uploadedTempPath, uploadedTempPaths, audioFilePath,+ });const createdAt = new Date().toISOString();const meta = {diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex a613048540..9078c0bc05 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -4245,43 +4245,67 @@ describe('generateVideo — IC-LoRA remix arg threading (#3100)', () => {]);});- it('cleans up EVERY temp clip when one still fails to encode', async () => {- // Promise.all rejects at the first failure while siblings are still in- // flight, so a push-on-success registry would miss the ones that landed- // afterwards. Every target path is registered before any encode starts.+ it('waits for every encode before rejecting and cleaning derived files', async () => {const { execFile } = await import('../../lib/childProcess.js');const { unlink } = await import('fs/promises');- const execFileMock = vi.mocked(execFile);- const unlinkMock = vi.mocked(unlink);- execFileMock.mockClear();- unlinkMock.mockClear();-- // Fail the SECOND still; the first and third still succeed.- let stillIndex = 0;- execFileMock.mockImplementation((_bin, args, _opts, cb) => {- if (args.includes('-loop')) {- const mine = stillIndex++;- if (mine === 1) return cb?.(new Error('ffmpeg exploded'));+ const pending = [];+ const originals = [...baseIngredients.icReferencePaths, '/mock/images/source.png'];+ const files = new Set(originals);+ vi.mocked(unlink).mockImplementation(async (path) => { files.delete(path); });+ vi.mocked(execFile).mockImplementation((_bin, args, _opts, cb) => {+ const target = args.at(-1);+ if (args.includes('-loop')) pending.push((error) => {+ files.add(target);+ cb(error);+ });+ else {+ files.add(target);+ cb?.(null, '', '');}- return cb?.(null, '', '');});+ let settled = false;+ const result = generateVideo({+ ...baseIngredients, jobId: 'ing-delayed', sourceImagePath: originals[2],+ }).catch((error) => error).finally(() => { settled = true; });+ await vi.waitFor(() => expect(pending).toHaveLength(2));+ // Finish input 1 first, but report input 0's failure after both settle.+ pending[1](new Error('second failed'));+ await new Promise((resolve) => setImmediate(resolve));+ expect(settled).toBe(false);+ expect(files.size).toBe(5);+ expect(vi.mocked(unlink).mock.calls.filter(([path]) => path.includes('ing-delayed'))).toEqual([]);+ pending[0](new Error('first failed'));+ expect(await result).toMatchObject({+ code: 'IC_LORA_STILL_PREP_FAILED',+ message: 'Failed to prepare Ingredients reference owl.png: first failed',+ });+ expect([...files]).toEqual(originals);+ vi.mocked(unlink).mockImplementation(async () => {});+ vi.mocked(execFile).mockImplementation((_bin, _args, _opts, cb) => cb?.(null, '', ''));+ });+ it('requires ffmpeg for Ingredients even when ordinary images can pass through', async () => {+ const { findFfmpeg } = await import('../../lib/ffmpeg.js');+ vi.mocked(findFfmpeg).mockResolvedValueOnce(null).mockResolvedValueOnce(null);await expect(generateVideo({- ...baseIngredients, jobId: 'ing-partial-fail',- icReferencePaths: ['/mock/images/a.png', '/mock/images/b.png', '/mock/images/c.png'],- })).rejects.toThrow(/Failed to prepare Ingredients reference b\.png/);+ ...baseIngredients, jobId: 'ing-no-ffmpeg', sourceImagePath: '/mock/images/source.png',+ })).rejects.toMatchObject({ code: 'IC_LORA_STILL_NEEDS_FFMPEG', status: 400 });+ });- // All three temp paths unlinked, not just the ones that had resolved when- // the rejection fired.- const unlinked = unlinkMock.mock.calls.map(([p]) => String(p));- for (const i of [0, 1, 2]) {- expect(unlinked.some((p) => p.includes(`ic-still-${i}-ing-partial-fail.mp4`))).toBe(true);- }- // The ORIGINAL gallery stills are the user's files and must survive.- for (const f of ['/mock/images/a.png', '/mock/images/b.png', '/mock/images/c.png']) {- expect(unlinked).not.toContain(f);- }- execFileMock.mockImplementation((_bin, _args, _opts, cb) => cb?.(null, '', ''));+ it.each(['missing ffmpeg', 'failed resize'])('passes the original image to the child after %s', async (failure) => {+ const { findFfmpeg } = await import('../../lib/ffmpeg.js');+ const { execFile } = await import('../../lib/childProcess.js');+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const { unlink } = await import('fs/promises');+ if (failure === 'missing ffmpeg') vi.mocked(findFfmpeg).mockResolvedValueOnce(null);+ else vi.mocked(execFile).mockImplementationOnce((_bin, _args, _opts, cb) => cb?.(new Error('resize failed')));+ await generateVideo({+ ...baseIcRender, mode: 'image', icReferencePaths: null,+ jobId: 'image-fallback', sourceImagePath: '/mock/images/source.png',+ });+ const args = vi.mocked(spawnDetached).mock.calls.find(([, argv]) => argv.includes('--image'))[1];+ expect(args[args.indexOf('--image') + 1]).toBe('/mock/images/source.png');+ expect(vi.mocked(unlink).mock.calls.flat()).not.toContain('/mock/images/source.png');});it('also cleans up an earlier resized-source temp file when a still fails to encode', async () => {