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: collapse per-runtime video mode gates into one modeContract contract (#3736)

[._.]/ Adam Eivyac1a867566bd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9b6c476c0f..fac9ecc0f2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -249,3 +249,5 @@
- **[issue-3733] The reviewer row's Effort cell now narrows to the tiers its pinned model actually offers.** `agy` validates the model/effort PAIR — `gemini-3.1-pro` has no `medium` tier — and the provider pickers already honored that, but `ReviewerPicker`'s Effort column read a static `low|medium|high` ladder with no knowledge of the model pinned beside it. So a user could pick `gemini-3.1-pro` + `medium` and PortOS would store, display, and emit an invocation agy rejects. `useReviewerModelOptions` (which already fetches `/api/providers` for the Model column) now exposes a `modelEffortLevels(reviewer, model)` accessor built on the same `antigravityModelEffortLevels` helper, and the Effort cell narrows through it — falling back to the full ladder whenever the catalog is empty, the model is unset, or the caller passes no options, so no surface loses its control. A model the catalog lists with no tiers at all drops the cell, unless an effort is already stored: a stale pin stays visible (`medium (unsupported)`) and clearable rather than silently reading as unset.
- **[issue-3730] Un-blocking a paused CoS task from the Tasks tab now resumes it on the worktree its paused run left behind, instead of starting clean.** Releasing a pause takes two things, and only one of them had moved out of the Resume dialog: the bookkeeping is now dropped by the task itself whichever path un-blocks it, but the *pointer* at the branch and worktree the paused run left on disk was still resolved inside Resume. So clicking the blocked-status icon on a paused task — or any of the five dispatch paths that revive a blocked twin (on-demand Run, pipeline advance, a Creative Director re-trigger, a manual job trigger, voice dispatch) — put the task back in the queue with nothing pointing at that work, and the next agent started from a clean checkout and redid it. The pointer is now resolved by the same transition that clears the pause, so every door resumes in place; it is resolved *before* the task becomes queueable, so no spawn can grab the task in the moment between un-blocking it and pointing it. The paused agent card is also retired the instant its task starts running again rather than waiting for the next background sweep to notice, and a pointer that can't be resolved (the branch merged, the worktree is gone) still un-blocks the task and simply starts clean, as every other resume path does.
+
+- **[issue-3736] The per-runtime video mode gates now resolve through one contract.** `wan22` and `minimax_h3` each carried a near-copy of the same five-step mode gate — resolve the requested mode, check it against the model's `supportedModes`, forbid a conditioning image in text mode, require a source in image mode — restated at *both* the route boundary (`prepareParams.js`) and the render boundary (`local.js`), four copies in all. They had already drifted: wan22 had no first/last-frame rules at all, and identical request shapes returned differently-worded errors depending on which copy caught them. Every one of those gates now calls `videoModeContractError` in `server/services/videoGen/modeContract.js`, a single `supportedModes`-driven rule table with a per-runtime row supplying only its error-code prefix and its wording; adding a runtime is now a row, not another forty lines across two files, and the module records that as a hard rule. No API change — `WAN22_*`, `MINIMAX_H3_*` and `VIDEO_CHAIN_REQUIRES_IMAGE_MODE` all keep their codes and messages, and the existing route and service suites pass unmodified. One drift closes as a side effect: an H3 request naming a gallery image that no longer resolves is now rejected at the route with `MINIMAX_H3_I2V_REQUIRES_IMAGE`, the way the wan22 lane always was, instead of being enqueued and failing later in the worker.
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 0b56e6de68..4286f66e66 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -60,7 +60,7 @@ import {
pickDeathFingerprint,
} from './runtimes.js';
import { loadHistory, saveHistory, mutateVideoHistory } from './history.js';
-import { miniMaxH3InputError, videoChainUnsupportedError } from './modeContract.js';
+import { videoModeContractError, videoChainUnsupportedError, VIDEO_MODE_GATED_RUNTIMES } from './modeContract.js';
// Re-export the extracted runtime + history surface so existing deep imports
// (`from '../videoGen/local.js'`) keep resolving every symbol they used to.
export * from './runtimes.js';
@@ -532,24 +532,34 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames
return { bin: LTX2_VENV_PYTHON, args };
};
+// The render-side adapter for the shared mode/source contract: `prepareParams`
+// wants the error value (it unlinks staged uploads first), this path just
+// throws, and it names its inputs by resolved path rather than by presence.
+// EVERY gated runtime goes through here — do not re-type a mode rule.
+const assertRenderModeContract = ({
+ model, mode, sourceImagePath, lastImagePath, keyframes,
+ extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths,
+}) => {
+ const err = videoModeContractError({
+ model,
+ mode,
+ hasFirstImage: !!sourceImagePath,
+ hasLastImage: !!lastImagePath,
+ keyframes,
+ extendFromVideo: extendFromVideoPath,
+ audioFile: audioFilePath,
+ audioStartSec,
+ icReferences: icReferencePaths,
+ });
+ if (err) throw err;
+};
+
// Build args for the pinned MLX-Gen Wan CLI. The helper itself never downloads:
// all base + profile weights must already be present through the UI flow.
const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, mode, outputPath }) => {
assertByovRuntimeInstalled('wan22');
const requestedMode = mode || (sourceImagePath ? 'image' : 'text');
- const supportedModes = Array.isArray(model.supportedModes) ? model.supportedModes : [];
- if (!supportedModes.includes(requestedMode)) {
- throw new ServerError(
- `${model.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,
- { status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
- );
- }
- if (requestedMode === 'text' && sourceImagePath) {
- throw new ServerError(
- 'Wan 2.2 text-to-video cannot consume a source image — switch to image mode or remove the source.',
- { status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' },
- );
- }
+ assertRenderModeContract({ model, mode, sourceImagePath });
const args = [
WAN22_HELPER_SCRIPT,
'--model-repo', wanModelPath,
@@ -567,15 +577,8 @@ const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, prompt, negat
if (model.guidance2 != null) args.push('--guidance-2', String(model.guidance2));
if (model.flowShift != null) args.push('--flow-shift', String(model.flowShift));
if (model.solver) args.push('--solver', model.solver);
- if (requestedMode === 'image') {
- if (!sourceImagePath) {
- throw new ServerError(
- 'Wan 2.2 image-to-video requires a source image — upload one before running this model.',
- { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
- );
- }
- args.push('--image', sourceImagePath);
- }
+ // The contract above already rejected image mode without a source.
+ if (requestedMode === 'image') args.push('--image', sourceImagePath);
for (const weight of wanRequiredWeights) {
args.push('--lora-path', weight.path);
args.push('--lora-target-role', weight.role);
@@ -586,27 +589,9 @@ const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, prompt, negat
// Build args for PipeNetwork's pinned MiniMax H3 MLX port. The helper resolves
// only exact, already-cached HF revisions; every network download remains an
// explicit Video Gen UI action guarded by the model's terms acknowledgement.
-const assertMiniMaxH3SupportedInputs = ({
- model, mode, sourceImagePath, lastImagePath, keyframes,
- extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths,
-}) => {
- const err = miniMaxH3InputError({
- mode,
- hasFirstImage: !!sourceImagePath,
- hasLastImage: !!lastImagePath,
- supportedModes: model?.supportedModes,
- keyframes,
- extendFromVideo: extendFromVideoPath,
- audioFile: audioFilePath,
- audioStartSec,
- icReferences: icReferencePaths,
- });
- if (err) throw err;
-};
-
const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath }) => {
assertByovRuntimeInstalled('minimax_h3');
- assertMiniMaxH3SupportedInputs({
+ assertRenderModeContract({
model,
mode,
sourceImagePath,
@@ -878,52 +863,31 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
&& !isVideoModelTermsAccepted(model, acceptedVideoModelTerms(await getSettings()))) {
throw videoModelTermsError(model);
}
- // Validate H3's mode contract before cache lookups, image resize, or staging
+ // Validate the mode contract before cache lookups, image resize, or staging
// work. Internal producers and persisted/retried jobs bypass route
// preparation, so silently dropping one of these inputs here would render a
- // materially different video than the caller requested.
- if (model.runtime === 'minimax_h3') {
- // Promote before checking, mirroring wan22 below: the route sets both
- // fields, but a direct caller that only staged `uploadedTempPath` would
- // otherwise pass the mode guard and then render text-only with its image
- // dropped.
- sourceImagePath ||= uploadedTempPath;
- assertMiniMaxH3SupportedInputs({
- model,
- mode,
- sourceImagePath,
- lastImagePath,
- keyframes,
- extendFromVideoPath,
- audioFilePath,
- audioStartSec,
- icReferencePaths,
- });
- }
+ // materially different video than the caller requested. Ungated runtimes
+ // (ltx2 / mlx_video / hunyuan) fall through untouched.
+ //
+ // Promote before checking: the route sets both fields, but a direct caller
+ // that only staged `uploadedTempPath` would otherwise pass the mode guard and
+ // then render text-only with its image dropped.
+ if (VIDEO_MODE_GATED_RUNTIMES.has(model.runtime)) sourceImagePath ||= uploadedTempPath;
+ assertRenderModeContract({
+ model,
+ mode,
+ sourceImagePath,
+ lastImagePath,
+ keyframes,
+ extendFromVideoPath,
+ audioFilePath,
+ audioStartSec,
+ icReferencePaths,
+ });
numFrames = numFrames ?? model.defaultFrames ?? DEFAULT_NUM_FRAMES;
let wanModelPath = null;
const wanRequiredWeights = [];
if (model.runtime === 'wan22') {
- sourceImagePath ||= uploadedTempPath;
- const requestedMode = mode || (sourceImagePath ? 'image' : 'text');
- if (!Array.isArray(model.supportedModes) || !model.supportedModes.includes(requestedMode)) {
- throw new ServerError(
- `${model.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,
- { status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
- );
- }
- if (requestedMode === 'image' && !sourceImagePath) {
- throw new ServerError(
- 'Wan 2.2 image-to-video requires a source image — upload one before running this model.',
- { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
- );
- }
- if (requestedMode === 'text' && sourceImagePath) {
- throw new ServerError(
- 'Wan 2.2 text-to-video cannot consume a source image — switch to image mode or remove the source.',
- { status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' },
- );
- }
const frameStride = Number(model.frameStride);
if (Number.isFinite(frameStride) && frameStride > 0 && (Number(numFrames) - 1) % frameStride !== 0) {
throw new ServerError(
diff --git a/server/services/videoGen/modeContract.js b/server/services/videoGen/modeContract.js
index 0313b85ac9..5109d135de 100644
--- a/server/services/videoGen/modeContract.js
+++ b/server/services/videoGen/modeContract.js
@@ -21,10 +21,16 @@
* 'a2v' | 'extend' | an IC-LoRA remix id), not the local/grok render backend
* that `modes.js` enumerates.
*
- * DO NOT add a third runtime's mode gate as another near-copy of the H3 table
- * below — wan22's copy in `prepareParams.js` plus this one is already two, and
- * they have drifted. Issue #3736 collapses them into one `supportedModes`-driven
- * contract; a third runtime should land on that instead.
+ * HARD RULE — DO NOT add a third runtime's mode gate anywhere else. Every
+ * runtime whose mode/source pairing needs gating declares a row in
+ * `VIDEO_MODE_CONTRACTS` below and resolves through `videoModeContractError`;
+ * the shape of the gate (which modes are legal, text-forbids-an-image,
+ * image-requires-a-source, the FFLF pair rules) is the same on every runtime and
+ * is stated exactly once, here. Only genuinely runtime-specific extras stay at
+ * their call site — H3's fps / negative-prompt / tiling / frame-grid checks and
+ * wan22's `frameStride`, none of which are mode rules. wan22 and minimax_h3 each
+ * carried a near-copy of this gate at two boundaries before #3736 collapsed
+ * them, and the copies had already drifted into different rules.
*/
import { ServerError } from '../../lib/errorHandler.js';
@@ -35,70 +41,145 @@ import { ServerError } from '../../lib/errorHandler.js';
// pins arbitrary frame indices H3 has no anchor for) still have no equivalent.
export const MINIMAX_H3_MODES = Object.freeze(['text', 'image', 'fflf']);
+// Message defaults, used for any rule a runtime row doesn't phrase itself. Each
+// takes `{ model, requestedMode, allowedModes }` so a new runtime can adopt the
+// whole table by declaring nothing but its code prefix.
+const DEFAULT_MESSAGES = Object.freeze({
+ modeUnsupported: ({ model, requestedMode }) => `${model.name} does not support ${requestedMode}-to-video. Choose a compatible model.`,
+ textSourceConflict: ({ model }) => `${model.name} text-to-video cannot consume a conditioning image — switch to image mode or remove the source.`,
+ imageRequiresFirst: ({ model }) => `${model.name} image-to-video requires a source image — choose an existing gallery image or upload one.`,
+ imageLastConflict: ({ model }) => `${model.name} image-to-video takes a single first-frame image — switch to FFLF mode to use a last frame.`,
+ fflfRequiresImage: ({ model }) => `${model.name} FFLF requires a first and/or last frame image.`,
+});
+
+/**
+ * The per-runtime rows. `modeCeiling` is the set of modes the *helper* has
+ * arguments for — a `null` ceiling means the registry entry's `supportedModes`
+ * is the only authority. A row's `codePrefix` is what keeps the pre-existing
+ * per-runtime error codes (`WAN22_*`, `MINIMAX_H3_*`) intact: no client reads
+ * them, but they are the server's API contract and this refactor doesn't move
+ * them.
+ */
+const VIDEO_MODE_CONTRACTS = Object.freeze({
+ wan22: {
+ codePrefix: 'WAN22',
+ chainCode: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE',
+ // No ceiling: MLX-Gen's Wan CLI takes whatever the profile declares, and an
+ // entry with no `supportedModes` at all declares nothing — so it renders
+ // nothing, which is how both wan22 boundaries have always read it.
+ modeCeiling: null,
+ // The wan22 lane rejects multi-keyframe / extend / audio / IC inputs by
+ // runtime elsewhere (KEYFRAMES_REQUIRE_LTX2, A2V_REQUIRES_LTX2,
+ // IC_LORA_REQUIRES_LTX2), so folding them in here would double-report.
+ extraConditioningUnsupported: false,
+ messages: {
+ modeUnsupported: ({ model, requestedMode }) => `${model.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,
+ textSourceConflict: () => 'Wan 2.2 text-to-video cannot consume a source image — switch to image mode or remove the source.',
+ // Two phrasings, one rule: before staging, the caller can still supply an
+ // upload; after resolution, the gallery pick they *did* supply didn't
+ // resolve, and "upload one" would be misleading advice.
+ imageRequiresFirst: ({ sourceResolved }) => (sourceResolved
+ ? 'Wan 2.2 image-to-video requires a resolvable source image — choose an existing gallery image or upload one.'
+ : 'Wan 2.2 image-to-video requires a source image — upload one before running this model.'),
+ },
+ },
+ minimax_h3: {
+ codePrefix: 'MINIMAX_H3',
+ modeCeiling: MINIMAX_H3_MODES,
+ extraConditioningUnsupported: true,
+ messages: {
+ modeUnsupported: ({ allowedModes }) => `MiniMax H3 MLX supports ${allowedModes.join(', ') || 'no'} modes only; remove multi-keyframe, video, audio, or reference conditioning.`,
+ textSourceConflict: () => 'MiniMax H3 text-to-video cannot consume a conditioning image — switch to image or FFLF mode.',
+ imageRequiresFirst: () => 'MiniMax H3 image-to-video requires a source image — choose an existing gallery image or upload one.',
+ imageLastConflict: () => 'MiniMax H3 image-to-video takes a single first-frame image — switch to FFLF mode to use a last frame.',
+ fflfRequiresImage: () => 'MiniMax H3 FFLF requires a first and/or last frame image.',
+ },
+ },
+});
+
+// An empty array is "no references", not "references present" — and an empty
+// string path is no path. Everything else non-nullish counts.
+/**
+ * The runtimes whose mode/source pairing this contract gates. Callers that need
+ * to do gate-adjacent work (the render path promotes a legacy upload field into
+ * `sourceImagePath` before checking) read the set rather than re-listing names.
+ */
+export const VIDEO_MODE_GATED_RUNTIMES = new Set(Object.keys(VIDEO_MODE_CONTRACTS));
+
+const isPresent = (value) => (Array.isArray(value) ? value.length > 0 : Boolean(value));
+
/**
- * The MiniMax H3 input contract. Returns a ServerError to throw, or null when
- * the request is legal.
+ * The one video mode/source contract, driven by `model.supportedModes`. Returns
+ * a ServerError to throw, or null when the request is legal (including for a
+ * runtime that declares no row — ltx2, mlx_video and hunyuan gate their modes
+ * through their own helpers).
*
* `supportedModes` comes off the registry entry so the picker and the API agree
* even on an install whose `data/media-models.json` was hand-edited or narrowed;
- * `MINIMAX_H3_MODES` stays the ceiling, because an entry can't declare a mode
+ * a row's `modeCeiling` stays the ceiling, because an entry can't declare a mode
* the helper has no arguments for.
+ *
+ * @param {object} opts
+ * @param {object} opts.model - registry entry (`runtime`, `name`, `supportedModes`)
+ * @param {string} [opts.mode] - requested semantic mode; unset resolves from the images
+ * @param {boolean} [opts.hasFirstImage] - a first-frame image is present
+ * @param {boolean} [opts.hasLastImage] - a last-frame image is present
+ * @param {boolean} [opts.sourceResolved] - the caller has already resolved the
+ * source to a real path (post-staging boundary), which picks the phrasing that
+ * doesn't tell the user to upload a file they already supplied
+ * @returns {ServerError|null}
*/
-export const miniMaxH3InputError = ({
+export const videoModeContractError = ({
+ model,
mode,
- hasFirstImage,
- hasLastImage,
- supportedModes = null,
+ hasFirstImage = false,
+ hasLastImage = false,
+ sourceResolved = false,
keyframes = null,
extendFromVideo = null,
audioFile = null,
audioStartSec = null,
icReferences = null,
}) => {
+ const contract = VIDEO_MODE_CONTRACTS[model?.runtime];
+ if (!contract) return null;
+ const { codePrefix, modeCeiling, extraConditioningUnsupported } = contract;
+ const messages = { ...DEFAULT_MESSAGES, ...contract.messages };
const requestedMode = mode || (hasFirstImage ? 'image' : 'text');
- const allowedModes = Array.isArray(supportedModes)
- ? supportedModes.filter((m) => MINIMAX_H3_MODES.includes(m))
- : MINIMAX_H3_MODES;
- const hasIcReferences = Array.isArray(icReferences) ? icReferences.length > 0 : icReferences != null;
- const fail = (message, code) => new ServerError(message, { status: 400, code });
- if (
- !allowedModes.includes(requestedMode)
- || (Array.isArray(keyframes) ? keyframes.length > 0 : keyframes != null)
- || extendFromVideo
- || audioFile
- || audioStartSec != null
- || hasIcReferences
- ) {
- return fail(
- `MiniMax H3 MLX supports ${allowedModes.join(', ') || 'no'} modes only; remove multi-keyframe, video, audio, or reference conditioning.`,
- 'MINIMAX_H3_MODE_UNSUPPORTED',
- );
+ const declaredModes = model?.supportedModes;
+ const allowedModes = Array.isArray(declaredModes)
+ ? (modeCeiling ? declaredModes.filter((m) => modeCeiling.includes(m)) : declaredModes)
+ : (modeCeiling ?? []);
+ const ctx = { model, requestedMode, allowedModes, sourceResolved };
+ const fail = (key, code) => new ServerError(messages[key](ctx), { status: 400, code });
+
+ const extraConditioning = extraConditioningUnsupported && (
+ isPresent(keyframes) || isPresent(extendFromVideo) || isPresent(audioFile)
+ || audioStartSec != null || isPresent(icReferences)
+ );
+ if (!allowedModes.includes(requestedMode) || extraConditioning) {
+ return fail('modeUnsupported', `${codePrefix}_MODE_UNSUPPORTED`);
}
// Each mode has exactly one legal image shape. Silently dropping (or silently
// adding) a keyframe would render a materially different clip than asked for.
if (requestedMode === 'text' && (hasFirstImage || hasLastImage)) {
- return fail(
- 'MiniMax H3 text-to-video cannot consume a conditioning image — switch to image or FFLF mode.',
- 'MINIMAX_H3_TEXT_MODE_SOURCE_CONFLICT',
- );
+ return fail('textSourceConflict', `${codePrefix}_TEXT_MODE_SOURCE_CONFLICT`);
}
if (requestedMode === 'image' && !hasFirstImage) {
- return fail(
- 'MiniMax H3 image-to-video requires a source image — choose an existing gallery image or upload one.',
- 'MINIMAX_H3_I2V_REQUIRES_IMAGE',
- );
- }
- if (requestedMode === 'image' && hasLastImage) {
- return fail(
- 'MiniMax H3 image-to-video takes a single first-frame image — switch to FFLF mode to use a last frame.',
- 'MINIMAX_H3_I2V_LAST_IMAGE_CONFLICT',
- );
+ return fail('imageRequiresFirst', `${codePrefix}_I2V_REQUIRES_IMAGE`);
}
- if (requestedMode === 'fflf' && !hasFirstImage && !hasLastImage) {
- return fail(
- 'MiniMax H3 FFLF requires a first and/or last frame image.',
- 'MINIMAX_H3_FFLF_REQUIRES_IMAGE',
- );
+ // The last-frame pair rules only mean something on a runtime that can anchor
+ // one, so they key off the resolved mode set rather than the runtime name — a
+ // profile that never declares 'fflf' (every wan22 profile today) keeps its
+ // historical indifference to a stray last frame instead of gaining a new
+ // rejection in a refactor.
+ if (allowedModes.includes('fflf')) {
+ if (requestedMode === 'image' && hasLastImage) {
+ return fail('imageLastConflict', `${codePrefix}_I2V_LAST_IMAGE_CONFLICT`);
+ }
+ if (requestedMode === 'fflf' && !hasFirstImage && !hasLastImage) {
+ return fail('fflfRequiresImage', `${codePrefix}_FFLF_REQUIRES_IMAGE`);
+ }
}
return null;
};
@@ -118,9 +199,7 @@ export const videoChainUnsupportedError = (model) => {
`${model.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,
{
status: 400,
- code: model.runtime === 'wan22'
- ? 'WAN22_CHAIN_REQUIRES_IMAGE_MODE'
- : 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE',
+ code: VIDEO_MODE_CONTRACTS[model.runtime]?.chainCode || 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE',
},
);
};
diff --git a/server/services/videoGen/modeContract.test.js b/server/services/videoGen/modeContract.test.js
new file mode 100644
index 0000000000..ee1fa945b1
--- /dev/null
+++ b/server/services/videoGen/modeContract.test.js
@@ -0,0 +1,150 @@
+import { describe, it, expect } from 'vitest';
+import {
+ videoModeContractError,
+ videoChainUnsupportedError,
+ VIDEO_MODE_GATED_RUNTIMES,
+ MINIMAX_H3_MODES,
+} from './modeContract.js';
+
+// Fake registry entries — never a real install's media-models.json.
+const wan = (supportedModes) => ({ runtime: 'wan22', name: 'Example Wan Profile', supportedModes });
+const h3 = (supportedModes) => ({ runtime: 'minimax_h3', name: 'Example H3', supportedModes });
+
+describe('videoModeContractError — shared gate', () => {
+ it('gates exactly the runtimes that declare a contract row', () => {
+ expect([...VIDEO_MODE_GATED_RUNTIMES].sort()).toEqual(['minimax_h3', 'wan22']);
+ });
+
+ it.each(['ltx2', 'mlx_video', 'hunyuan', undefined])('leaves the %s runtime ungated', (runtime) => {
+ expect(videoModeContractError({
+ model: { runtime, name: 'Example Model' }, mode: 'extend', hasFirstImage: true,
+ })).toBeNull();
+ });
+
+ it('returns null for a missing model rather than throwing', () => {
+ expect(videoModeContractError({ model: null, mode: 'image' })).toBeNull();
+ });
+
+ it('resolves an unset mode from the presence of a first image', () => {
+ // t2v-only profile + an image ⇒ the request really asked for i2v.
+ expect(videoModeContractError({ model: wan(['text']), hasFirstImage: true }))
+ .toMatchObject({ status: 400, code: 'WAN22_MODE_UNSUPPORTED' });
+ expect(videoModeContractError({ model: wan(['text']), hasFirstImage: false })).toBeNull();
+ });
+});
+
+describe('videoModeContractError — wan22 codes and messages', () => {
+ it('rejects a mode the profile does not declare', () => {
+ const err = videoModeContractError({ model: wan(['text']), mode: 'image', hasFirstImage: true });
+ expect(err).toMatchObject({ status: 400, code: 'WAN22_MODE_UNSUPPORTED' });
+ expect(err.message).toContain('Example Wan Profile does not support image-to-video');
+ });
+
+ it('treats an entry with no declared supportedModes as declaring nothing', () => {
+ expect(videoModeContractError({ model: wan(undefined), mode: 'text' }))
+ .toMatchObject({ code: 'WAN22_MODE_UNSUPPORTED' });
+ });
+
+ it('rejects text mode carrying a source image', () => {
+ expect(videoModeContractError({ model: wan(['text', 'image']), mode: 'text', hasFirstImage: true }))
+ .toMatchObject({ code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' });
+ });
+
+ it('phrases the missing-source message for the boundary that asked', () => {
+ const staged = videoModeContractError({ model: wan(['image']), mode: 'image' });
+ expect(staged).toMatchObject({ code: 'WAN22_I2V_REQUIRES_IMAGE' });
+ expect(staged.message).toContain('upload one before running this model');
+ // Past resolution the caller may already have supplied a gallery pick that
+ // didn't resolve, so "upload one" alone would be misleading advice.
+ const resolved = videoModeContractError({ model: wan(['image']), mode: 'image', sourceResolved: true });
+ expect(resolved).toMatchObject({ code: 'WAN22_I2V_REQUIRES_IMAGE' });
+ expect(resolved.message).toContain('choose an existing gallery image or upload one');
+ });
+
+ it('keeps a profile that never declares fflf indifferent to a stray last frame', () => {
+ expect(videoModeContractError({
+ model: wan(['text', 'image']), mode: 'image', hasFirstImage: true, hasLastImage: true,
+ })).toBeNull();
+ });
+
+ it('ignores conditioning channels the wan lane rejects by runtime elsewhere', () => {
+ expect(videoModeContractError({
+ model: wan(['image']), mode: 'image', hasFirstImage: true,
+ keyframes: [{ path: '/mock/a.png', index: 0 }], audioFile: '/mock/a.wav',
+ })).toBeNull();
+ });
+});
+
+describe('videoModeContractError — minimax_h3 codes and messages', () => {
+ it('caps a hand-widened supportedModes at the helper ceiling', () => {
+ const err = videoModeContractError({ model: h3([...MINIMAX_H3_MODES, 'extend']), mode: 'extend' });
+ expect(err).toMatchObject({ code: 'MINIMAX_H3_MODE_UNSUPPORTED' });
+ expect(err.message).toContain('supports text, image, fflf modes only');
+ });
+
+ it('falls back to the ceiling when the entry declares no supportedModes', () => {
+ expect(videoModeContractError({ model: h3(undefined), mode: 'fflf', hasFirstImage: true })).toBeNull();
+ });
+
+ it('honors a narrowed supportedModes', () => {
+ const err = videoModeContractError({ model: h3(['text']), mode: 'fflf', hasFirstImage: true });
+ expect(err).toMatchObject({ code: 'MINIMAX_H3_MODE_UNSUPPORTED' });
+ expect(err.message).toContain('supports text modes only');
+ });
+
+ it.each([
+ ['keyframes', { keyframes: [{ path: '/mock/a.png', index: 0 }] }],
+ ['extend video', { extendFromVideo: '/mock/prior.mp4' }],
+ ['audio file', { audioFile: '/mock/audio.wav' }],
+ ['audio offset', { audioStartSec: 0 }],
+ ['IC references', { icReferences: ['/mock/reference.mp4'] }],
+ ])('folds %s conditioning into the mode gate', (_label, extra) => {
+ expect(videoModeContractError({ model: h3(MINIMAX_H3_MODES), mode: 'text', ...extra }))
+ .toMatchObject({ code: 'MINIMAX_H3_MODE_UNSUPPORTED' });
+ });
+
+ it.each([
+ ['empty keyframes', { keyframes: [] }],
+ ['empty IC references', { icReferences: [] }],
+ ['unset audio offset', { audioStartSec: null }],
+ ])('reads %s as absent, not present', (_label, extra) => {
+ expect(videoModeContractError({ model: h3(MINIMAX_H3_MODES), mode: 'text', ...extra })).toBeNull();
+ });
+
+ it.each([
+ [{ mode: 'text', hasFirstImage: true }, 'MINIMAX_H3_TEXT_MODE_SOURCE_CONFLICT'],
+ [{ mode: 'text', hasLastImage: true }, 'MINIMAX_H3_TEXT_MODE_SOURCE_CONFLICT'],
+ [{ mode: 'image' }, 'MINIMAX_H3_I2V_REQUIRES_IMAGE'],
+ [{ mode: 'image', hasFirstImage: true, hasLastImage: true }, 'MINIMAX_H3_I2V_LAST_IMAGE_CONFLICT'],
+ [{ mode: 'fflf' }, 'MINIMAX_H3_FFLF_REQUIRES_IMAGE'],
+ ])('rejects %o with the H3-prefixed code', (fields, code) => {
+ expect(videoModeContractError({ model: h3(MINIMAX_H3_MODES), ...fields }))
+ .toMatchObject({ status: 400, code });
+ });
+
+ it.each([
+ ['text with no images', { mode: 'text' }],
+ ['image with a first frame', { mode: 'image', hasFirstImage: true }],
+ ['fflf with a first frame only', { mode: 'fflf', hasFirstImage: true }],
+ ['fflf with a last frame only', { mode: 'fflf', hasLastImage: true }],
+ ['fflf with both frames', { mode: 'fflf', hasFirstImage: true, hasLastImage: true }],
+ ])('accepts %s', (_label, fields) => {
+ expect(videoModeContractError({ model: h3(MINIMAX_H3_MODES), ...fields })).toBeNull();
+ });
+});
+
+describe('videoChainUnsupportedError', () => {
+ it('allows a model that declares image mode, or declares nothing at all', () => {
+ expect(videoChainUnsupportedError(wan(['text', 'image']))).toBeNull();
+ expect(videoChainUnsupportedError({ runtime: 'ltx2', name: 'Example LTX' })).toBeNull();
+ });
+
+ it('keeps the wan-prefixed chain code and the generic one apart', () => {
+ expect(videoChainUnsupportedError(wan(['text'])))
+ .toMatchObject({ status: 400, code: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE' });
+ expect(videoChainUnsupportedError(h3(['text'])))
+ .toMatchObject({ status: 400, code: 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE' });
+ expect(videoChainUnsupportedError({ runtime: 'mlx_video', name: 'Example Model', supportedModes: ['text'] }))
+ .toMatchObject({ code: 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE' });
+ });
+});
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 71005fecdf..1f316218ae 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -52,7 +52,7 @@ import {
} from './local.js';
// Straight from the leaf, not through local.js: the suites that exercise this
// module mock local.js wholesale, and a mocked rule table would assert nothing.
-import { miniMaxH3InputError, videoChainUnsupportedError } from './modeContract.js';
+import { videoModeContractError, videoChainUnsupportedError } from './modeContract.js';
/**
* Best-effort unlink of every multipart temp file the parser wrote before the
@@ -408,25 +408,33 @@ async function resolvePreparedParams({
throw chainError;
}
}
- // MiniMax H3's released MLX path is fixed-24fps, joint A/V and CFG-distilled,
- // and conditions on at most two keyframes (first / last latent frame). Fail
- // before queue persistence so a direct API caller cannot enqueue a request
- // whose controls the runtime would silently ignore.
+ // Mode ↔ source pairing for every gated runtime, resolved through the one
+ // contract the render boundary also throws from (#3736), so the two entry
+ // points can't disagree about which shapes are legal or which code they
+ // return. Runs before durable upload staging, keeping rejection cleanup cheap.
+ const hasDeclaredFirstImage = Boolean(uploads.sourceImage || body.sourceImageFile);
+ const hasDeclaredLastImage = Boolean(uploads.lastImage || body.lastImageFile);
+ // Pinned here rather than re-derived at the resolved pass below: once a
+ // declared gallery pick fails to resolve, "was this an i2v request?" can only
+ // be answered from what the caller declared.
+ const declaredMode = body.mode || (hasDeclaredFirstImage ? 'image' : 'text');
+ const modeContractError = videoModeContractError({
+ model: effectiveModel,
+ mode: declaredMode,
+ hasFirstImage: hasDeclaredFirstImage,
+ hasLastImage: hasDeclaredLastImage,
+ keyframes: body.keyframes,
+ extendFromVideo: body.extendFromVideoId,
+ });
+ if (modeContractError) {
+ await cleanupStaged();
+ throw modeContractError;
+ }
+ // MiniMax H3's released MLX path is fixed-24fps, joint A/V and CFG-distilled.
+ // These are the runtime's non-mode controls; the mode gate above already ran.
+ // Fail before queue persistence so a direct API caller cannot enqueue a
+ // request whose controls the runtime would silently ignore.
if (effectiveModel?.runtime === 'minimax_h3') {
- // Same rule table the render boundary throws from, so the two entry points
- // can't disagree about which shapes are legal or which code they return.
- const h3InputError = miniMaxH3InputError({
- mode: body.mode,
- hasFirstImage: Boolean(uploads.sourceImage || body.sourceImageFile),
- hasLastImage: Boolean(uploads.lastImage || body.lastImageFile),
- supportedModes: effectiveModel.supportedModes,
- keyframes: body.keyframes,
- extendFromVideo: body.extendFromVideoId,
- });
- if (h3InputError) {
- await cleanupStaged();
- throw h3InputError;
- }
if (body.negativePrompt?.trim()) {
await cleanupStaged();
throw new ServerError(
@@ -465,40 +473,11 @@ async function resolvePreparedParams({
);
}
}
- // Wan profiles have narrower mode + temporal-shape contracts than the
- // shared request schema can express. Mirror the worker's guards here so a
- // direct API caller cannot persist a job that is already known to fail.
- // This runs before durable upload staging, keeping rejection cleanup cheap.
- let wanRequestedMode = null;
+ // Wan profiles have a narrower temporal-shape contract than the shared
+ // request schema can express (the mode side is the shared gate above). Mirror
+ // the worker's frame-grid guard here so a direct API caller cannot persist a
+ // job that is already known to fail.
if (effectiveModel?.runtime === 'wan22') {
- const hasDeclaredSource = Boolean(uploads.sourceImage || body.sourceImageFile);
- const requestedMode = body.mode
- || (uploads.sourceImage || body.sourceImageFile ? 'image' : 'text');
- wanRequestedMode = requestedMode;
- const supportedModes = Array.isArray(effectiveModel.supportedModes)
- ? effectiveModel.supportedModes
- : [];
- if (!supportedModes.includes(requestedMode)) {
- await cleanupStaged();
- throw new ServerError(
- `${effectiveModel.name} does not support ${requestedMode}-to-video. Choose a compatible Wan model.`,
- { status: 400, code: 'WAN22_MODE_UNSUPPORTED' },
- );
- }
- if (requestedMode === 'image' && !hasDeclaredSource) {
- await cleanupStaged();
- throw new ServerError(
- 'Wan 2.2 image-to-video requires a source image — upload one before running this model.',
- { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
- );
- }
- if (requestedMode === 'text' && hasDeclaredSource) {
- await cleanupStaged();
- throw new ServerError(
- 'Wan 2.2 text-to-video cannot consume a source image — switch to image mode or remove the source.',
- { status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' },
- );
- }
const numFrames = body.numFrames != null ? Number(body.numFrames) : DEFAULT_NUM_FRAMES;
const frameStride = Number(effectiveModel.frameStride);
if (Number.isFinite(frameStride) && frameStride > 0 && (numFrames - 1) % frameStride !== 0) {
@@ -536,12 +515,21 @@ async function resolvePreparedParams({
} else if (body.sourceImageFile) {
sourceImagePath = resolveGalleryImage(body.sourceImageFile);
}
- if (effectiveModel?.runtime === 'wan22' && wanRequestedMode === 'image' && !sourceImagePath) {
+ // Re-run the same contract now that the gallery pick has been resolved to a
+ // real path: the pre-staging pass only saw that a filename was *declared*, so
+ // a stale/missing gallery entry would otherwise fall through to a text render.
+ const resolvedModeError = videoModeContractError({
+ model: effectiveModel,
+ mode: declaredMode,
+ hasFirstImage: Boolean(sourceImagePath),
+ hasLastImage: hasDeclaredLastImage,
+ sourceResolved: true,
+ keyframes: body.keyframes,
+ extendFromVideo: body.extendFromVideoId,
+ });
+ if (resolvedModeError) {
await cleanupStaged();
- throw new ServerError(
- 'Wan 2.2 image-to-video requires a resolvable source image — choose an existing gallery image or upload one.',
- { status: 400, code: 'WAN22_I2V_REQUIRES_IMAGE' },
- );
+ throw resolvedModeError;
}
// Music Video director-board renders are always i2v FROM the scene's reference
// frame (#1760 Phase 1). resolveGalleryImage returns null for a missing/invalid