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

add MiniMax H3 image-to-video and FFLF keyframe conditioning

[._.]/ Adam Eivy8751f02a8b9e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8391ad2db2..2542aa7179 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -30,6 +30,8 @@
## Added
+- **MiniMax H3 can now animate a still image.** H3 shipped locked to text-to-video, so picking it greyed out Image and FFLF and refused any conditioning frame — even though the model is an `fl2va` ("first/last frame to video with audio") release and the pinned MLX runtime already implemented that path. Video Gen now offers Image and FFLF on H3: one image anchors the first latent frame, a first/last pair anchors both, and the render still produces joint video and audio in one pass. Because chunk chaining re-seeds each chunk from the previous one's last frame, multi-chunk H3 renders work too. The last frame is a real anchor on H3, so the "last frame is advisory" note no longer appears for it (or for the LTX-2 keyframe runtime, where it was also wrong). Keyframes run through the model's Qwen3-VL image processor, which adds about 11 MB to H3's download — existing installs will show H3 as needing a top-up download once, and the vision weights themselves were already included.
+
- **Series Autopilot can split one run across a writer and an independent critic.** Options now exposes separate soft provider/model/effort routes for creation-and-repair work versus judging-and-verification work, so a run can, for example, draft with Luna at max effort while Sol at xhigh independently evaluates whether those edits actually improved the story. The split applies across foundation judging, arc and beat verification, script/editorial analysis, iterative-quality judging, and pipeline diagnosis; corrective rewrites stay on the creative route, and exact stage pins in Prompts still take precedence. Cooperative stops and ordinary pauses preserve both routes for Resume instead of silently falling back to the series default.
- **Series Autopilot now builds characters before it spends on plot.** A new pre-arc planning stage completes the core cast's causal Ghost → Wound → Lie → Want → Need engines, distinct voices, secrets, relationships, and provisional whole-series transitions before the macro arc is generated. Arc planning then treats those foundations as plot engines: external turns must force character choices rather than inventing a plot and asking late repair passes to retrofit motivation. The existing full-foundation gate remains after the issue-level synopsis plan, where it acts as reconciliation—preserving established identities and adding at most a small number of genuinely story-required characters—so character and story can still change one another without repeatedly rebuilding the expensive arc.
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 04da0a6008..c5a5616483 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -426,6 +426,11 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
// file, indices strictly ascending and within [0, numFrames-1].
const keyframesSupported = currentModel?.runtime === 'ltx2';
const keyframesActive = mode === 'fflf' && keyframesMode && keyframesSupported;
+ // Whether an FFLF last frame is a real anchor or just a hint. The server
+ // decorates each model with `lastFrameAnchored` from the one runtime list
+ // (server/services/videoGen/runtimes.js), so this can't drift from the
+ // resize/forwarding decision the render path makes off the same flag.
+ const lastFrameIsAdvisory = !currentModel?.lastFrameAnchored;
// IC-LoRA remix mode is on. `icSpec` is the registry entry (reference count +
// the resolution-divisibility rule its encoder imposes); null outside the
// family, so every consumer gates on `icModeActive` first.
@@ -1144,7 +1149,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
sourceImageFile, sourceImageUpload, sourceUploadUrl,
pickSourceImage, uploadSourceImage, clearSourceImage,
lastImageFile, lastImageUpload, lastUploadUrl,
- pickLastImage, uploadLastImage, clearLastImage,
+ pickLastImage, uploadLastImage, clearLastImage, lastFrameIsAdvisory,
// Keyframes
keyframesMode, keyframes, keyframesSupported, keyframesActive, keyframesError, keyframesBlocked,
toggleKeyframesMode, addKeyframe, updateKeyframe, removeKeyframe,
diff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsx
index cb59d5182a..2c8be37c30 100644
--- a/client/src/hooks/useVideoGenForm.test.jsx
+++ b/client/src/hooks/useVideoGenForm.test.jsx
@@ -13,12 +13,15 @@ const { useVideoGenForm } = await import('./useVideoGenForm.js');
// Two runtimes matter to the payload shape: `ltx2` unlocks keyframes / LoRAs /
// a2v / IC remix and routes extend through the video id, `mlx_video` is the
// legacy path that extends from an extracted last frame.
-const LTX2 = { id: 'ltx2-model', name: 'LTX-2.3', runtime: 'ltx2' };
-const MLX = { id: 'mlx-model', name: 'LTX distilled', runtime: 'mlx_video' };
+// `lastFrameAnchored` is server-decorated onto every model by listVideoModels()
+// (from LAST_FRAME_ANCHORED_RUNTIMES) — fixtures carry it as the payload does.
+const LTX2 = { id: 'ltx2-model', name: 'LTX-2.3', runtime: 'ltx2', lastFrameAnchored: true };
+const MLX = { id: 'mlx-model', name: 'LTX distilled', runtime: 'mlx_video', lastFrameAnchored: false };
const WAN_T2V = { id: 'wan-t2v', name: 'Wan T2V', runtime: 'wan22', supportedModes: ['text'], frameStride: 4 };
const WAN_TI2V = { id: 'wan-ti2v', name: 'Wan TI2V', runtime: 'wan22', supportedModes: ['text', 'image'], frameStride: 4 };
const H3 = {
- id: 'minimax-h3', name: 'MiniMax H3', runtime: 'minimax_h3', supportedModes: ['text'],
+ id: 'minimax-h3', name: 'MiniMax H3', runtime: 'minimax_h3', supportedModes: ['text', 'image', 'fflf'],
+ lastFrameAnchored: true,
frameOptions: [124, 141, 158], fpsOptions: [24], defaultFrames: 124,
supportsNegativePrompt: false, supportsTiling: false, supportsDisableAudio: false,
};
@@ -196,7 +199,7 @@ describe('useVideoGenForm', () => {
expect(result.current.buildGeneratePayload().chunks).toBe('');
});
- it('normalizes MiniMax H3 to its text-only temporal and sampler contract', async () => {
+ it('normalizes MiniMax H3 to its fixed temporal and sampler contract', async () => {
const { result } = render({
models: [MLX, H3],
status: { connected: true, defaultModel: MLX.id },
@@ -207,7 +210,6 @@ describe('useVideoGenForm', () => {
result.current.setNegativePrompt('blurry');
result.current.setNumFrames(129);
result.current.setFps(30);
- result.current.setChunks(3);
result.current.setTiling('full');
result.current.setDisableAudio(true);
result.current.setNoMusic(true);
@@ -217,7 +219,6 @@ describe('useVideoGenForm', () => {
await waitFor(() => expect(result.current.numFrames).toBe(124));
expect(result.current.mode).toBe('text');
- expect(result.current.chainingActive).toBe(false);
const payload = result.current.buildGeneratePayload();
expect(payload).toMatchObject({
modelId: H3.id,
@@ -225,13 +226,42 @@ describe('useVideoGenForm', () => {
negativePrompt: '',
numFrames: 124,
fps: 24,
- chunks: '',
tiling: 'auto',
disableAudio: 'false',
});
expect(payload.prompt).toBe('a fox watches the rain');
});
+ // H3's fl2va path anchors keyframes at the first/last latent frame, so image
+ // mode (and therefore chunk chaining, which re-seeds from the prior chunk's
+ // last frame) is available — and its last frame is a real anchor, not a hint.
+ it('offers MiniMax H3 image mode, chaining and a non-advisory last frame', async () => {
+ const { result } = render({
+ models: [MLX, H3],
+ status: { connected: true, defaultModel: MLX.id },
+ });
+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));
+ act(() => {
+ result.current.setPrompt('a fox watches the rain');
+ result.current.setChunks(3);
+ result.current.handleModelChange(H3.id);
+ });
+ await waitFor(() => expect(result.current.modelId).toBe(H3.id));
+
+ expect(result.current.chainingActive).toBe(true);
+ expect(result.current.buildGeneratePayload().chunks).toBe(3);
+ expect(result.current.lastFrameIsAdvisory).toBe(false);
+ act(() => result.current.handleModeChange('image'));
+ await waitFor(() => expect(result.current.mode).toBe('image'));
+ expect(result.current.modelId).toBe(H3.id);
+ });
+
+ it('keeps the advisory last-frame note on a single-frame mlx_video runtime', async () => {
+ const { result } = render({ models: [MLX, H3] });
+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));
+ expect(result.current.lastFrameIsAdvisory).toBe(true);
+ });
+
describe('per-chunk prompt beats (#3695)', () => {
const chained = async (count = 3) => {
const { result } = render();
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index ff2db6b4cb..e544ec7be7 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -153,7 +153,7 @@ export default function VideoGen() {
sourceImageFile, sourceImageUpload, sourceUploadUrl,
pickSourceImage, uploadSourceImage, clearSourceImage,
lastImageFile, lastImageUpload, lastUploadUrl,
- pickLastImage, uploadLastImage, clearLastImage,
+ pickLastImage, uploadLastImage, clearLastImage, lastFrameIsAdvisory,
keyframesMode, keyframes, keyframesSupported, keyframesActive, keyframesError, keyframesBlocked,
toggleKeyframesMode, addKeyframe, updateKeyframe, removeKeyframe,
extendFromVideoId, extendingFrame, handleExtendPick, extendModeBlocked,
@@ -897,10 +897,10 @@ export default function VideoGen() {
onUpload={uploadLastImage}
onClear={clearLastImage}
alt="End frame"
- advisoryNote={{
+ advisoryNote={lastFrameIsAdvisory ? {
text: 'Experimental — last frame is advisory.',
- title: 'FFLF backend support is experimental — LTX/mlx_video uses the start frame and treats the last frame as advisory.',
- }}
+ title: `FFLF backend support is experimental — the ${currentModel?.runtime || 'selected'} runtime conditions on the start frame only and treats the last frame as advisory.`,
+ } : null}
hint={{
text: 'Tip: use keyframes that share scene geometry — same camera, same subject. The model interpolates between them; unrelated images produce a visual cut.',
title: 'FFLF works best when the two frames depict the same scene with continuous geometry. Both runtimes (notapalindrome and dgrauet) benefit from this.',
diff --git a/data.reference/media-models.json b/data.reference/media-models.json
index 7814659fc7..2cb6916433 100644
--- a/data.reference/media-models.json
+++ b/data.reference/media-models.json
@@ -107,7 +107,9 @@
"revision": "3ac52081470b0488921c3ec3ba84a39097bf2361",
"runtime": "minimax_h3",
"supportedModes": [
- "text"
+ "text",
+ "image",
+ "fflf"
],
"defaultFrames": 124,
"frameOptions": [
@@ -162,6 +164,13 @@
"FL2VA/text_encoder/model-00011-of-00014.safetensors",
"FL2VA/text_encoder/model-00014-of-00014.safetensors",
"FL2VA/text_encoder/model.safetensors.index.json",
+ "FL2VA/processor/chat_template.json",
+ "FL2VA/processor/merges.txt",
+ "FL2VA/processor/preprocessor_config.json",
+ "FL2VA/processor/tokenizer.json",
+ "FL2VA/processor/tokenizer_config.json",
+ "FL2VA/processor/video_preprocessor_config.json",
+ "FL2VA/processor/vocab.json",
"FL2VA/tokenizer/merges.txt",
"FL2VA/tokenizer/tokenizer.json",
"FL2VA/tokenizer/tokenizer_config.json",
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.py
index 36b73ae875..9b9c15ace8 100644
--- a/scripts/generate_minimax_h3.py
+++ b/scripts/generate_minimax_h3.py
@@ -5,6 +5,10 @@ The Video Gen UI owns every network operation. This helper resolves only the
exact revisions already present in Hugging Face's cache, loads PipeNetwork's
pinned source checkout, emits PortOS progress/runtime frames, and writes one
joint video-and-audio MP4.
+
+Conditioning is H3's own `fl2va` keyframe path: zero images is text-to-video,
+one `--image first` is image-to-video, and a `first` + `last` pair is FFLF.
+Each `--image` needs its own `--anchor`, in the same order.
"""
from __future__ import annotations
@@ -47,6 +51,10 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--fps", type=int, default=FPS)
parser.add_argument("--steps", type=int, default=8)
parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--image", action="append", default=[],
+ help="keyframe conditioning image (repeatable, max 2)")
+ parser.add_argument("--anchor", action="append", default=[], choices=["first", "last"],
+ help="latent anchor for each --image, in the same order")
parser.add_argument("--output", required=True)
return parser.parse_args()
@@ -189,11 +197,43 @@ def validate_args(args: argparse.Namespace) -> None:
raise SystemExit(f"MiniMax H3 frame count must be 17n+5; got {args.num_frames}.")
if args.steps < 2:
raise SystemExit("MiniMax H3 needs at least 2 sigma grid points.")
+ if len(args.anchor) != len(args.image):
+ raise SystemExit(
+ f"MiniMax H3 needs one --anchor per --image; got {len(args.image)} images and {len(args.anchor)} anchors."
+ )
+ # H3's fl2va conditioning defines exactly two latent anchors, so a repeated
+ # anchor would silently overwrite one keyframe's position with another's.
+ if len(set(args.anchor)) != len(args.anchor):
+ raise SystemExit(f"MiniMax H3 anchors must be distinct; got {args.anchor}.")
+
+
+def load_keyframes(paths: list[str]) -> list:
+ """Open each conditioning image upright, in RGB, in the order given."""
+ from PIL import Image, ImageOps
+
+ images = []
+ for path in paths:
+ # Checked explicitly so a bad path reports the PortOS-side cause rather
+ # than Pillow's bare FileNotFoundError.
+ if not Path(path).is_file():
+ raise RuntimeError(f"Conditioning image is missing: {path}")
+ with Image.open(path) as handle:
+ image = handle.convert("RGB")
+ # In place: PortOS hands us ffmpeg-normalized PNGs with no orientation
+ # tag, and the copying form would duplicate every pixel buffer for
+ # nothing — then hold it across the 83 GB load below.
+ ImageOps.exif_transpose(image, in_place=True)
+ images.append(image)
+ return images
def main() -> int:
args = parse_args()
validate_args(args)
+ # Read the keyframes first: everything below is a git probe, ~35 HF cache
+ # lookups and an mlx/transformers import, so an unreadable conditioning
+ # image should not cost seconds before it reports.
+ images = load_keyframes(args.image)
# PortOS cancels this helper by process group; ffmpeg inherits the group and
# cannot remain behind muxing after the user presses Cancel. Establish the
@@ -236,7 +276,9 @@ def main() -> int:
pipe = MiniMaxH3Pipeline.from_pretrained(
checkpoint_dir,
transformer_dir=transformer_dir,
- load_vision=False,
+ # The Qwen3-VL vision tower is only loaded when a keyframe needs
+ # encoding — a text-only run keeps skipping it.
+ load_vision=bool(images),
)
print("STAGE:inference", file=sys.stderr, flush=True)
@@ -247,6 +289,8 @@ def main() -> int:
duration_seconds=args.num_frames / FPS,
num_inference_steps=args.steps,
seed=args.seed,
+ images=images or None,
+ keyframe_anchors=tuple(args.anchor),
height=args.height,
width=args.width,
drop_adaln=True,
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index 82eeee9b6b..e2c6f582a5 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -73,7 +73,7 @@ describe('generate_minimax_h3.py', () => {
it('rejects zero dimensions at the execution boundary', () => {
const output = runPython(`${importRunner}\n${[
'from types import SimpleNamespace',
- 'args = SimpleNamespace(fps=24, width=0, height=320, num_frames=124, steps=8)',
+ 'args = SimpleNamespace(fps=24, width=0, height=320, num_frames=124, steps=8, image=[], anchor=[])',
'try:',
' runner.validate_args(args)',
'except SystemExit as exc:',
@@ -84,6 +84,49 @@ describe('generate_minimax_h3.py', () => {
expect(output).toMatch(/dimensions must be positive multiples of 32/i);
});
+ // An unpaired or repeated anchor would silently mis-place a keyframe in the
+ // packed sequence, so both fail at the boundary rather than rendering.
+ it.each([
+ [['a.png', 'b.png'], ['first'], /one --anchor per --image/i],
+ [['a.png', 'b.png'], ['first', 'first'], /anchors must be distinct/i],
+ ])('rejects mismatched keyframe anchors (%j / %j)', (images, anchors, pattern) => {
+ const output = runPython(`${importRunner}\n${[
+ 'from types import SimpleNamespace',
+ `args = SimpleNamespace(fps=24, width=512, height=320, num_frames=124, steps=8, image=${JSON.stringify(images)}, anchor=${JSON.stringify(anchors)})`,
+ 'try:',
+ ' runner.validate_args(args)',
+ 'except SystemExit as exc:',
+ ' print(str(exc))',
+ 'else:',
+ ' raise SystemExit("bad anchors were accepted")',
+ ].join('\n')}`);
+ expect(output).toMatch(pattern);
+ });
+
+ it('accepts a paired first/last keyframe request', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'from types import SimpleNamespace',
+ 'args = SimpleNamespace(fps=24, width=512, height=320, num_frames=124, steps=8, image=["a.png", "b.png"], anchor=["first", "last"])',
+ 'runner.validate_args(args)',
+ 'print("ok")',
+ ].join('\n')}`);
+ expect(output.trim()).toBe('ok');
+ });
+
+ // Reading the keyframes happens before the ~83 GB load, so a bad path costs
+ // a second rather than an hour.
+ it('fails a missing conditioning image before any model load', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'try:',
+ ' runner.load_keyframes(["/nonexistent/first.png"])',
+ 'except RuntimeError as exc:',
+ ' print(str(exc))',
+ 'else:',
+ ' raise SystemExit("missing keyframe was accepted")',
+ ].join('\n')}`);
+ expect(output).toMatch(/Conditioning image is missing/i);
+ });
+
it('emits the video_path JSON completion contract on stdout', () => {
const output = runPython(`${importRunner}\nrunner.emit_result(Path("/tmp/example.mp4"))`);
expect(JSON.parse(output)).toEqual({ video_path: '/tmp/example.mp4' });
diff --git a/scripts/migrations/244-minimax-h3-image-to-video.js b/scripts/migrations/244-minimax-h3-image-to-video.js
new file mode 100644
index 0000000000..66e38eef83
--- /dev/null
+++ b/scripts/migrations/244-minimax-h3-image-to-video.js
@@ -0,0 +1,108 @@
+/**
+ * Open MiniMax H3 up to image-to-video and FFLF on existing registries.
+ *
+ * H3 shipped as `supportedModes: ['text']` because PortOS only drove the port's
+ * `t2va` path. The same pinned runtime already implements `fl2va` keyframe
+ * conditioning, so `scripts/generate_minimax_h3.py` now forwards
+ * `--image`/`--anchor` pairs and the entry advertises image + fflf.
+ *
+ * Two registry fields have to move together:
+ * - `supportedModes` gains 'image' and 'fflf' (the model picker and both
+ * server mode gates read it);
+ * - `requiredWeights[0].files` gains the seven `FL2VA/processor/*` files.
+ * Keyframes run through Qwen3-VL's AutoProcessor, which reads the
+ * `processor/` directory — `tokenizer/` alone is not enough, and a render
+ * that reaches the helper without them dies on a cache miss ~83 GB into
+ * loading. The vision tower's own weights need no new download: they live
+ * in shard 14, which the entry already pulls.
+ *
+ * `data/media-models.json` is gitignored runtime state and is not a
+ * JSON_MERGE_TARGET, so a fresh install gets this from
+ * data.reference/media-models.json while existing installs need this patch.
+ *
+ * Idempotent, and conservative about customization: the mode list is only
+ * rewritten when it is still exactly the shipped `['text']`, and each processor
+ * file is appended only when absent. An entry a user re-pointed at a different
+ * repo/revision is left alone entirely — its files may not exist there.
+ */
+
+import { join } from 'path';
+import { atomicWrite, readJSONFileStrict } from '../../server/lib/fileUtils.js';
+
+const REL_PATH = 'data/media-models.json';
+const H3_ID = 'minimax_h3_8bit';
+const SHIPPED_REPO = 'pipenetwork/MiniMax-H3-MLX-8bit';
+const SHIPPED_CHECKPOINT_REPO = 'MiniMaxAI/MiniMax-H3';
+const NEW_SHIPPED_MODES = ['text', 'image', 'fflf'];
+const PROCESSOR_FILES = [
+ 'FL2VA/processor/chat_template.json',
+ 'FL2VA/processor/merges.txt',
+ 'FL2VA/processor/preprocessor_config.json',
+ 'FL2VA/processor/tokenizer.json',
+ 'FL2VA/processor/tokenizer_config.json',
+ 'FL2VA/processor/video_preprocessor_config.json',
+ 'FL2VA/processor/vocab.json',
+];
+
+export default {
+ async up({ rootDir }) {
+ const path = join(rootDir, REL_PATH);
+ // `ok` separates "never written" (fresh install — the seed will carry this
+ // change) from "unreadable or corrupt", where rewriting the file would
+ // destroy a registry we couldn't read.
+ const { ok, value: config } = await readJSONFileStrict(path, null);
+ if (!ok) {
+ console.log(`⚠️ ${REL_PATH}: unreadable or invalid JSON, skipping`);
+ return;
+ }
+ if (config == null) {
+ console.log(`📄 ${REL_PATH} not present — skipping (fresh install seeds from data.reference)`);
+ return;
+ }
+
+ const macos = Array.isArray(config?.video?.macos) ? config.video.macos : null;
+ if (!macos) {
+ console.log(`⚠️ ${REL_PATH}: no video.macos[] array — skipping`);
+ return;
+ }
+
+ const entry = macos.find((m) => m?.id === H3_ID);
+ if (!entry) {
+ console.log(`✅ ${REL_PATH}: no '${H3_ID}' entry — user removed it, nothing to migrate`);
+ return;
+ }
+ if (entry.repo !== SHIPPED_REPO) {
+ console.log(`✅ ${REL_PATH}: '${H3_ID}' points at ${entry.repo} — user-repointed, leaving it alone`);
+ return;
+ }
+
+ let changed = false;
+ // Only rewrite a mode list that is still exactly the shipped `['text']` —
+ // anything else is the user's own narrowing and stays theirs.
+ if (entry.supportedModes?.length === 1 && entry.supportedModes[0] === 'text') {
+ entry.supportedModes = [...NEW_SHIPPED_MODES];
+ changed = true;
+ }
+
+ const checkpoint = Array.isArray(entry.requiredWeights) ? entry.requiredWeights[0] : null;
+ if (checkpoint?.repo === SHIPPED_CHECKPOINT_REPO && Array.isArray(checkpoint.files)) {
+ // Insert ahead of the tokenizer block so the stored order matches the
+ // shipped seed — the two files are otherwise byte-compared by eye during
+ // support, and a reordered list reads as drift.
+ const anchor = checkpoint.files.findIndex((file) => file === 'FL2VA/tokenizer/merges.txt');
+ const missing = PROCESSOR_FILES.filter((file) => !checkpoint.files.includes(file));
+ if (missing.length > 0) {
+ if (anchor >= 0) checkpoint.files.splice(anchor, 0, ...missing);
+ else checkpoint.files.push(...missing);
+ changed = true;
+ }
+ }
+
+ if (changed) {
+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);
+ console.log(`📝 ${REL_PATH}: enabled MiniMax H3 image-to-video + FFLF (added the Qwen3-VL processor files)`);
+ } else {
+ console.log(`✅ ${REL_PATH}: MiniMax H3 already keyframe-capable, no changes`);
+ }
+ },
+};
diff --git a/scripts/migrations/244-minimax-h3-image-to-video.test.js b/scripts/migrations/244-minimax-h3-image-to-video.test.js
new file mode 100644
index 0000000000..f0a48e9217
--- /dev/null
+++ b/scripts/migrations/244-minimax-h3-image-to-video.test.js
@@ -0,0 +1,144 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import migration from './244-minimax-h3-image-to-video.js';
+
+const REFERENCE_PATH = join(
+ dirname(fileURLToPath(import.meta.url)), '..', '..', 'data.reference', 'media-models.json',
+);
+
+const H3_ID = 'minimax_h3_8bit';
+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+const PROCESSOR_FILES = [
+ 'FL2VA/processor/chat_template.json',
+ 'FL2VA/processor/merges.txt',
+ 'FL2VA/processor/preprocessor_config.json',
+ 'FL2VA/processor/tokenizer.json',
+ 'FL2VA/processor/tokenizer_config.json',
+ 'FL2VA/processor/video_preprocessor_config.json',
+ 'FL2VA/processor/vocab.json',
+];
+
+const shippedH3 = () => ({
+ id: H3_ID,
+ name: 'MiniMax H3 MLX 8-bit',
+ repo: 'pipenetwork/MiniMax-H3-MLX-8bit',
+ revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',
+ runtime: 'minimax_h3',
+ supportedModes: ['text'],
+ requiredWeights: [{
+ repo: 'MiniMaxAI/MiniMax-H3',
+ revision: '6818f6c32d12b210915e44ad56a4228c2608f160',
+ files: [
+ 'LICENSE',
+ 'FL2VA/text_encoder/model.safetensors.index.json',
+ 'FL2VA/tokenizer/merges.txt',
+ 'FL2VA/tokenizer/vocab.json',
+ ],
+ }],
+});
+
+const registryWith = (h3) => ({
+ video: {
+ macos: [{ id: 'ltx23_distilled_q4', name: 'Default' }, ...(h3 ? [h3] : [])],
+ windows: [],
+ defaultMacos: 'ltx23_distilled_q4',
+ defaultWindows: 'ltx_video',
+ },
+ image: [],
+});
+
+const h3In = (config) => config.video.macos.find((entry) => entry.id === H3_ID);
+
+describe('migration 244 — MiniMax H3 image-to-video', () => {
+ let rootDir;
+ let path;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-244-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ path = join(rootDir, 'data', 'media-models.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ // The migration keeps a frozen copy of the file set on purpose (reading the
+ // live seed would let a later seed edit retroactively change what 244 does),
+ // so pin it here — otherwise fresh installs and migrated installs could end
+ // up downloading different files with nothing failing.
+ it('migrates to exactly what data.reference ships today', async () => {
+ writeJson(path, registryWith(shippedH3()));
+ await migration.up({ rootDir });
+
+ const migrated = h3In(readJson(path));
+ const seeded = JSON.parse(readFileSync(REFERENCE_PATH, 'utf-8'))
+ .video.macos.find((entry) => entry.id === H3_ID);
+ expect(migrated.supportedModes).toEqual(seeded.supportedModes);
+ expect(migrated.requiredWeights[0].files.filter((f) => f.startsWith('FL2VA/processor/')))
+ .toEqual(seeded.requiredWeights[0].files.filter((f) => f.startsWith('FL2VA/processor/')));
+ });
+
+ it('opens the shipped entry to image + fflf and adds the Qwen3-VL processor files', async () => {
+ writeJson(path, registryWith(shippedH3()));
+ await migration.up({ rootDir });
+
+ const h3 = h3In(readJson(path));
+ expect(h3.supportedModes).toEqual(['text', 'image', 'fflf']);
+ expect(h3.requiredWeights[0].files.filter((f) => f.startsWith('FL2VA/processor/')))
+ .toEqual(PROCESSOR_FILES);
+ // Inserted ahead of the tokenizer block so stored order matches the seed.
+ const files = h3.requiredWeights[0].files;
+ expect(files.indexOf('FL2VA/processor/vocab.json'))
+ .toBeLessThan(files.indexOf('FL2VA/tokenizer/merges.txt'));
+ expect(files[0]).toBe('LICENSE');
+ });
+
+ it('is idempotent', async () => {
+ writeJson(path, registryWith(shippedH3()));
+ await migration.up({ rootDir });
+ const once = readJson(path);
+ await migration.up({ rootDir });
+ expect(readJson(path)).toEqual(once);
+ });
+
+ it('leaves a user-narrowed mode list alone but still adds the processor files', async () => {
+ const custom = shippedH3();
+ custom.supportedModes = ['text', 'image'];
+ writeJson(path, registryWith(custom));
+ await migration.up({ rootDir });
+
+ const h3 = h3In(readJson(path));
+ expect(h3.supportedModes).toEqual(['text', 'image']);
+ expect(h3.requiredWeights[0].files).toContain('FL2VA/processor/tokenizer.json');
+ });
+
+ it('skips an entry the user re-pointed at another repo', async () => {
+ const forked = shippedH3();
+ forked.repo = 'example-org/h3-fork';
+ const before = registryWith(forked);
+ writeJson(path, before);
+ await migration.up({ rootDir });
+ expect(readJson(path)).toEqual(before);
+ });
+
+ it('does nothing when the user deleted the entry', async () => {
+ const before = registryWith(null);
+ writeJson(path, before);
+ await migration.up({ rootDir });
+ expect(readJson(path)).toEqual(before);
+ });
+
+ it('skips a missing registry file (fresh install seeds from data.reference)', async () => {
+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();
+ });
+
+ it('skips an invalid registry file rather than throwing', async () => {
+ writeFileSync(path, '{ not json');
+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();
+ expect(readFileSync(path, 'utf-8')).toBe('{ not json');
+ });
+});
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index a2200b2cb2..312e853140 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -80,7 +80,10 @@ const DEFAULT_REGISTRY = {
repo: 'pipenetwork/MiniMax-H3-MLX-8bit',
revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',
runtime: 'minimax_h3',
- supportedModes: ['text'],
+ // H3 is an fl2va model: it conditions on up to two keyframes anchored
+ // at the first / last latent frame. 'image' anchors one at 'first',
+ // 'fflf' anchors both.
+ supportedModes: ['text', 'image', 'fflf'],
defaultFrames: 124,
frameOptions: [124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362],
fpsOptions: [24],
@@ -118,6 +121,18 @@ const DEFAULT_REGISTRY = {
// shard 14 remains necessary for the final norm tensor.
'FL2VA/text_encoder/model-00014-of-00014.safetensors',
'FL2VA/text_encoder/model.safetensors.index.json',
+ // Keyframe conditioning runs each image through the Qwen3-VL
+ // processor (AutoProcessor reads the `processor/` directory, not
+ // `tokenizer/`) before the vision tower, whose weights already ride
+ // along in shard 14. ~11 MB total, so it stays in the base download
+ // rather than becoming a second opt-in pull.
+ 'FL2VA/processor/chat_template.json',
+ 'FL2VA/processor/merges.txt',
+ 'FL2VA/processor/preprocessor_config.json',
+ 'FL2VA/processor/tokenizer.json',
+ 'FL2VA/processor/tokenizer_config.json',
+ 'FL2VA/processor/video_preprocessor_config.json',
+ 'FL2VA/processor/vocab.json',
'FL2VA/tokenizer/merges.txt',
'FL2VA/tokenizer/tokenizer.json',
'FL2VA/tokenizer/tokenizer_config.json',
diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.js
index 5c5ba8d679..34ff4b32ce 100644
--- a/server/lib/mediaModels.test.js
+++ b/server/lib/mediaModels.test.js
@@ -57,14 +57,14 @@ describe('mediaModels registry', () => {
expect(list.every((m) => m.id && m.name)).toBe(true);
});
- it('ships MiniMax H3 as a pinned, text-only 128 GB BYOV profile', async () => {
+ it('ships MiniMax H3 as a pinned, keyframe-capable 128 GB BYOV profile', async () => {
const { getVideoModels } = await import('./mediaModels.js');
const h3 = getVideoModels().find((model) => model.id === 'minimax_h3_8bit');
expect(h3).toMatchObject({
runtime: 'minimax_h3',
repo: 'pipenetwork/MiniMax-H3-MLX-8bit',
revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',
- supportedModes: ['text'],
+ supportedModes: ['text', 'image', 'fflf'],
defaultFrames: 124,
fpsOptions: [24],
memoryGb: 128,
@@ -76,11 +76,26 @@ describe('mediaModels registry', () => {
repo: 'MiniMaxAI/MiniMax-H3',
revision: '6818f6c32d12b210915e44ad56a4228c2608f160',
});
+ // Keyframe conditioning runs each image through Qwen3-VL's AutoProcessor,
+ // which reads `processor/` — not the `tokenizer/` directory the text path
+ // uses. Without these the vision path dies on a cache miss ~83 GB into
+ // loading, so they belong in the base download, not a second opt-in pull.
+ expect(h3.requiredWeights[0].files.filter((file) => file.startsWith('FL2VA/processor/')))
+ .toEqual([
+ 'FL2VA/processor/chat_template.json',
+ 'FL2VA/processor/merges.txt',
+ 'FL2VA/processor/preprocessor_config.json',
+ 'FL2VA/processor/tokenizer.json',
+ 'FL2VA/processor/tokenizer_config.json',
+ 'FL2VA/processor/video_preprocessor_config.json',
+ 'FL2VA/processor/vocab.json',
+ ]);
// The pinned port builds only decoder layers 0-49. Shards 12/13 contain
// only layers 53-63, which its _wanted() loader deliberately skips; shard
- // 14 remains required for the final norm. Keep this selective 12-shard
- // contract explicit so a generic "download every index shard" rewrite
- // does not add roughly 10 GB of weights the H3 text path never loads.
+ // 14 remains required for the final norm — and, since every `model.visual.*`
+ // tensor also lives there, for the vision tower keyframes load. Keep this
+ // selective 12-shard contract explicit so a generic "download every index
+ // shard" rewrite does not add roughly 10 GB of weights H3 never loads.
expect(h3.requiredWeights[0].files.filter((file) => /model-\d{5}-of-00014\.safetensors$/.test(file)))
.toEqual([
...Array.from(
diff --git a/server/lib/videoDisclosure.js b/server/lib/videoDisclosure.js
index 89ed2e68b2..654ebff88f 100644
--- a/server/lib/videoDisclosure.js
+++ b/server/lib/videoDisclosure.js
@@ -91,7 +91,8 @@ export const VIDEO_MODEL_DISCLOSURES = Object.freeze({
weightsLicense: MINIMAX_H3_WEIGHTS,
runtimeLicense: RUNTIME_LICENSE.minimax_h3,
// 35.302 GB quantized transformer + 67.996 GB selective upstream
- // conditioner / video VAE / audio VAE files used by text-to-video.
+ // conditioner / video VAE / audio VAE files, plus the ~0.011 GB
+ // Qwen3-VL processor the keyframe (image / FFLF) path reads.
estimatedDownloadGb: 103.3,
reviewedAt: VIDEO_DISCLOSURE_REVIEWED_AT,
},
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index d9078462c3..e3398943ae 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -51,14 +51,17 @@ import {
HUNYUAN_REPO_DIR,
BYOV_RUNTIME_INFO,
BYOV_VIDEO_RUNTIMES,
+ modelAnchorsLastFrame,
assertByovRuntimeInstalled,
invalidateByovReadyCache,
pickDeathFingerprint,
} from './runtimes.js';
import { loadHistory, saveHistory, mutateVideoHistory } from './history.js';
+import { miniMaxH3InputError, videoChainUnsupportedError } 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';
+export * from './modeContract.js';
export { loadHistory, saveHistory, mutateVideoHistory };
// LoRA wrapper for the notapalindrome `mlx_video` runtime. The stock
@@ -137,7 +140,11 @@ export const VIDEO_MODELS = Object.fromEntries(getVideoModels().map((m) => [m.id
export const resolveVideoModel = (modelId) =>
getVideoModels().find((m) => m.id === modelId) || VIDEO_MODELS[modelId] || null;
-export const listVideoModels = () => getVideoModels();
+// Decorated with the one runtime capability the client can't derive: whether an
+// FFLF last frame is a real anchor. Declared in runtimes.js, surfaced here so
+// the Video Gen form reads it off the model instead of keeping its own list.
+export const listVideoModels = () => getVideoModels()
+ .map((m) => ({ ...m, lastFrameAnchored: modelAnchorsLastFrame(m) }));
export const defaultVideoModelId = () => getDefaultVideoModelId();
@@ -576,45 +583,28 @@ 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 assertMiniMaxH3TextOnly = ({
- mode,
- sourceImagePath,
- uploadedTempPath,
- uploadedTempPaths,
- lastImagePath,
- keyframes,
- extendFromVideoPath,
- audioFilePath,
- audioStartSec,
- icReferencePaths,
+const assertMiniMaxH3SupportedInputs = ({
+ model, mode, sourceImagePath, lastImagePath, keyframes,
+ extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths,
}) => {
- const requestedMode = mode || ((sourceImagePath || uploadedTempPath) ? 'image' : 'text');
- const hasUploadedKeyframes = Array.isArray(uploadedTempPaths) && uploadedTempPaths.length > 0;
- const hasIcReferences = Array.isArray(icReferencePaths)
- ? icReferencePaths.length > 0
- : icReferencePaths != null;
- if (
- requestedMode !== 'text'
- || sourceImagePath
- || uploadedTempPath
- || hasUploadedKeyframes
- || lastImagePath
- || keyframes != null
- || extendFromVideoPath
- || audioFilePath
- || audioStartSec != null
- || hasIcReferences
- ) {
- throw new ServerError(
- 'MiniMax H3 MLX currently supports text-to-video only; remove image, keyframe, video, audio, or reference conditioning.',
- { status: 400, code: 'MINIMAX_H3_MODE_UNSUPPORTED' },
- );
- }
+ 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');
- assertMiniMaxH3TextOnly({
+ assertMiniMaxH3SupportedInputs({
+ model,
mode,
sourceImagePath,
lastImagePath,
@@ -686,6 +676,10 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF
'--output', outputPath,
];
for (const file of files) args.push('--checkpoint-file', file);
+ // Anchor order is packed order: the helper stretches the FIRST keyframe onto
+ // the canvas as the geometry anchor, so a first-frame image must lead.
+ if (sourceImagePath) args.push('--image', sourceImagePath, '--anchor', 'first');
+ if (lastImagePath) args.push('--image', lastImagePath, '--anchor', 'last');
return { bin: MINIMAX_H3_VENV_PYTHON, args };
};
@@ -879,16 +873,20 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', t
{ status: 403, code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' },
);
}
- // Validate H3's strict T2V-only contract before cache lookups, image resize,
- // or staging-file 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.
+ // Validate H3's 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') {
- assertMiniMaxH3TextOnly({
+ // 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,
- uploadedTempPath,
- uploadedTempPaths,
lastImagePath,
keyframes,
extendFromVideoPath,
@@ -1058,8 +1056,10 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', t
//
// Skip the last-image resize when buildArgs / the Python child won't
// actually consume it:
- // - ltx2 true-FFLF consumes both --image and --last-image, so resize the
- // last frame even when a source image is also present.
+ // - 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.
@@ -1067,7 +1067,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', t
// status, but the diffusers pipeline only reads --image — the script
// never opens the last-frame file, so no resize is needed there either.
const lastImageWillBeUsed = !!lastImagePath && !IS_WIN && mode === 'fflf'
- && (model.runtime === 'ltx2' || !sourceImagePath);
+ && (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
@@ -1096,10 +1096,17 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', t
}
return { resolved: resizedPath, tempPath: resizedPath };
};
- const { resolved: resolvedSourceImage, tempPath: resizedSrcTempPath } = await resizeImage(sourceImagePath, 'src');
- const { resolved: resolvedLastImage, tempPath: resizedLastTempPath } = lastImageWillBeUsed
- ? await resizeImage(lastImagePath, 'last')
- : { resolved: lastImagePath, tempPath: null };
+ // 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
@@ -1665,17 +1672,8 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJ
if (!outerJobId) throw new ServerError('generateChainedVideo requires jobId', { status: 500, code: 'INTERNAL' });
const chainModel = resolveVideoModel(rest.modelId || defaultVideoModelId());
- if (Array.isArray(chainModel?.supportedModes) && !chainModel.supportedModes.includes('image')) {
- throw new ServerError(
- `${chainModel.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,
- {
- status: 400,
- code: chainModel.runtime === 'wan22'
- ? 'WAN22_CHAIN_REQUIRES_IMAGE_MODE'
- : 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE',
- },
- );
- }
+ const chainError = videoChainUnsupportedError(chainModel);
+ if (chainError) throw chainError;
const chainState = { stopped: false };
activeChain = chainState;
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index f0cf98164d..0e8c880c64 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -46,7 +46,7 @@ vi.mock('../../lib/mediaModels.js', () => ({
id: 'minimax_h3_8bit', name: 'MiniMax H3 MLX 8-bit', runtime: 'minimax_h3',
repo: 'pipenetwork/MiniMax-H3-MLX-8bit',
revision: '3ac52081470b0488921c3ec3ba84a39097bf2361',
- supportedModes: ['text'], defaultFrames: 124,
+ supportedModes: ['text', 'image', 'fflf'], defaultFrames: 124,
frameOptions: [124, 141, 158], fpsOptions: [24],
steps: 8, guidance: 0, samplerLocked: true,
termsGate: { id: 'minimax-h3-community-license-2026-08-02' },
@@ -1771,12 +1771,13 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {
expect(spawnDetached).not.toHaveBeenCalled();
});
+ // H3 anchors keyframes at the first/last latent frame only, so the ltx2
+ // arbitrary-index array and every non-keyframe conditioning channel stay out.
it.each([
- ['uploaded image', { uploadedTempPath: '/mock/source.png' }],
['keyframes', { keyframes: [{ path: '/mock/first.png', frame: 0 }, { path: '/mock/last.png', frame: 140 }] }],
- ['extension video', { extendFromVideoPath: '/mock/prior.mp4' }],
- ['audio file', { audioFilePath: '/mock/audio.wav' }],
- ['IC reference', { icReferencePaths: ['/mock/reference.mp4'] }],
+ ['extension video', { mode: 'extend', extendFromVideoPath: '/mock/prior.mp4' }],
+ ['audio file', { mode: 'a2v', audioFilePath: '/mock/audio.wav' }],
+ ['IC reference', { mode: 'ic-restyle', icReferencePaths: ['/mock/reference.mp4'] }],
])('rejects direct %s conditioning before any child is spawned', async (_label, conditioning) => {
const { spawnDetached } = await import('../../lib/detachedSpawn.js');
vi.mocked(spawnDetached).mockClear();
@@ -1793,6 +1794,60 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {
expect(spawnDetached).not.toHaveBeenCalled();
});
+ // Each mode has exactly one legal image shape; a mismatch must fail rather
+ // than silently render a different clip than the caller asked for.
+ it.each([
+ ['text mode with a source image', { mode: 'text', sourceImagePath: '/mock/source.png' }, 'MINIMAX_H3_TEXT_MODE_SOURCE_CONFLICT'],
+ ['image mode with no image', { mode: 'image' }, 'MINIMAX_H3_I2V_REQUIRES_IMAGE'],
+ ['image mode with a last frame', { mode: 'image', sourceImagePath: '/mock/source.png', lastImagePath: '/mock/last.png' }, 'MINIMAX_H3_I2V_LAST_IMAGE_CONFLICT'],
+ ['fflf mode with no frames', { mode: 'fflf' }, 'MINIMAX_H3_FFLF_REQUIRES_IMAGE'],
+ ])('rejects %s before any child is spawned', async (_label, fields, code) => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+
+ await expect(generateVideo({
+ jobId: 'h3-image-shape',
+ modelId: 'minimax_h3_8bit',
+ termsAcceptance: 'minimax-h3-community-license-2026-08-02',
+ prompt: 'a fox watches the rain',
+ width: 512, height: 320, numFrames: 141, fps: 24,
+ ...fields,
+ })).rejects.toMatchObject({ code });
+
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+
+ // The helper stretches the FIRST keyframe onto the canvas as the geometry
+ // anchor, so packed order has to put the first frame ahead of the last.
+ it.each([
+ ['image', { mode: 'image', sourceImagePath: '/mock/source.png' }, ['first']],
+ ['fflf', { mode: 'fflf', sourceImagePath: '/mock/source.png', lastImagePath: '/mock/last.png' }, ['first', 'last']],
+ ['fflf with only a last frame', { mode: 'fflf', lastImagePath: '/mock/last.png' }, ['last']],
+ ['text', { mode: 'text' }, []],
+ ])('forwards %s conditioning as anchored --image pairs', async (_label, fields, expectedAnchors) => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'h3-keyframes',
+ modelId: 'minimax_h3_8bit',
+ termsAcceptance: 'minimax-h3-community-license-2026-08-02',
+ prompt: 'a fox watches the rain',
+ width: 512, height: 320, numFrames: 141, fps: 24,
+ ...fields,
+ });
+
+ const [, args] = spawnMock.mock.calls.find(([, a]) => (
+ Array.isArray(a) && a.some((arg) => String(arg).endsWith('/generate_minimax_h3.py'))
+ ));
+ // Paths are the ffmpeg-resized copies, so assert the anchors and that each
+ // one directly follows its own --image rather than the literal input path.
+ expect(args.flatMap((arg, i) => (
+ arg === '--image' ? [args[i + 2] === '--anchor' ? args[i + 3] : 'UNPAIRED'] : []
+ ))).toEqual(expectedAnchors);
+ });
+
it('uses the pinned cache-only helper, locked sampler and credential-free environment', async () => {
const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const { hfChildEnv } = await import('../../lib/hfToken.js');
diff --git a/server/services/videoGen/modeContract.js b/server/services/videoGen/modeContract.js
new file mode 100644
index 0000000000..0313b85ac9
--- /dev/null
+++ b/server/services/videoGen/modeContract.js
@@ -0,0 +1,126 @@
+/**
+ * Video Gen — per-model input contracts, as pure rule tables.
+ *
+ * Every one of these rules has to hold at TWO boundaries: `prepareParams.js`
+ * rejects before the request is persisted to the media job queue, and
+ * `local.js` rejects again at the render boundary (internal producers,
+ * persisted-queue replays and retries all reach `generateVideo` directly).
+ * Checking twice is deliberate — see the a2v and wan22 precedents in
+ * `prepareParams.js` — but *stating* the rule twice is how the two ends drift
+ * into different messages and different error codes for the same request.
+ *
+ * So the rules live here, return a `ServerError` (or null) rather than throwing,
+ * and each caller decides only what to do first: the route unlinks its staged
+ * uploads, the render path just throws.
+ *
+ * Dependency-free apart from the error leaf, which keeps it importable from
+ * `prepareParams.js` without dragging in `local.js` — the module suites mock
+ * `local.js` wholesale, and a mocked rule table is no rule table at all.
+ *
+ * Careful: `mode` here is the t2v/i2v *semantic* ('text' | 'image' | 'fflf' |
+ * '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.
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+
+// H3's fl2va path conditions on up to two keyframes anchored at the first and
+// last latent frame — so text, image (first only) and FFLF (first + last) all
+// run, while extend / a2v / IC-remix and the ltx2 multi-keyframe array (which
+// pins arbitrary frame indices H3 has no anchor for) still have no equivalent.
+export const MINIMAX_H3_MODES = Object.freeze(['text', 'image', 'fflf']);
+
+/**
+ * The MiniMax H3 input contract. Returns a ServerError to throw, or null when
+ * the request is legal.
+ *
+ * `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
+ * the helper has no arguments for.
+ */
+export const miniMaxH3InputError = ({
+ mode,
+ hasFirstImage,
+ hasLastImage,
+ supportedModes = null,
+ keyframes = null,
+ extendFromVideo = null,
+ audioFile = null,
+ audioStartSec = null,
+ icReferences = null,
+}) => {
+ 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',
+ );
+ }
+ // 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',
+ );
+ }
+ 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',
+ );
+ }
+ if (requestedMode === 'fflf' && !hasFirstImage && !hasLastImage) {
+ return fail(
+ 'MiniMax H3 FFLF requires a first and/or last frame image.',
+ 'MINIMAX_H3_FFLF_REQUIRES_IMAGE',
+ );
+ }
+ return null;
+};
+
+/**
+ * Chunk chaining seeds chunk N+1 from chunk N's extracted last frame, so it
+ * needs image-to-video on any runtime. Returns a ServerError for a model that
+ * lacks it, else null.
+ *
+ * An entry with no declared `supportedModes` is permitted — unset means
+ * "unconstrained", not "text-only" — and both boundaries must read it that way,
+ * which is why this is one function rather than a rule re-typed per runtime.
+ */
+export const videoChainUnsupportedError = (model) => {
+ if (!Array.isArray(model?.supportedModes) || model.supportedModes.includes('image')) return null;
+ return new ServerError(
+ `${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',
+ },
+ );
+};
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index db2f301af7..0db210718f 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -50,6 +50,9 @@ import {
loadHistory,
DEFAULT_NUM_FRAMES,
} 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';
/**
* Best-effort unlink of every multipart temp file the parser wrote before the
@@ -393,20 +396,34 @@ async function resolvePreparedParams({
{ status: 400, code: 'A2V_REQUIRES_LTX2' },
);
}
- // MiniMax H3's released MLX path is text-only, fixed-24fps, joint A/V and
- // CFG-distilled. Fail before queue persistence so a direct API caller cannot
- // enqueue a request whose controls the runtime would silently ignore.
+ // Chunk chaining needs image-to-video on any runtime — the same rule
+ // generateChainedVideo enforces at dispatch, applied once here so a doomed
+ // chain never reaches the persisted queue.
+ if (body.chunks != null && Number(body.chunks) > 1) {
+ const chainError = videoChainUnsupportedError(effectiveModel);
+ if (chainError) {
+ await cleanupStaged();
+ 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.
if (effectiveModel?.runtime === 'minimax_h3') {
- const hasImageInput = Boolean(
- uploads.sourceImage || uploads.lastImage || body.sourceImageFile
- || body.lastImageFile || body.keyframes?.length || body.extendFromVideoId,
- );
- if ((body.mode && body.mode !== 'text') || hasImageInput) {
+ // 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 new ServerError(
- 'MiniMax H3 MLX currently supports text-to-video only; remove image/keyframe conditioning.',
- { status: 400, code: 'MINIMAX_H3_MODE_UNSUPPORTED' },
- );
+ throw h3InputError;
}
if (body.negativePrompt?.trim()) {
await cleanupStaged();
@@ -429,13 +446,6 @@ async function resolvePreparedParams({
{ status: 400, code: 'MINIMAX_H3_TILING_UNSUPPORTED' },
);
}
- if (body.chunks != null && Number(body.chunks) > 1) {
- await cleanupStaged();
- throw new ServerError(
- `${effectiveModel.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,
- { status: 400, code: 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE' },
- );
- }
const frames = Number(body.numFrames ?? effectiveModel.defaultFrames);
if (!Array.isArray(effectiveModel.frameOptions) || !effectiveModel.frameOptions.includes(frames)) {
await cleanupStaged();
@@ -487,13 +497,6 @@ async function resolvePreparedParams({
{ status: 400, code: 'WAN22_TEXT_MODE_SOURCE_CONFLICT' },
);
}
- if (body.chunks != null && Number(body.chunks) > 1 && !supportedModes.includes('image')) {
- await cleanupStaged();
- throw new ServerError(
- `${effectiveModel.name} cannot generate chunks > 1 because continuation requires image-to-video support.`,
- { status: 400, code: 'WAN22_CHAIN_REQUIRES_IMAGE_MODE' },
- );
- }
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) {
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index 8d781912ad..a60d1aa068 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -69,7 +69,7 @@ const H3_MODEL = {
id: 'minimax_h3_8bit',
name: 'MiniMax H3 MLX 8-bit',
runtime: 'minimax_h3',
- supportedModes: ['text'],
+ supportedModes: ['text', 'image', 'fflf'],
defaultFrames: 124,
frameOptions: [124, 141, 158],
fpsOptions: [24],
@@ -395,23 +395,51 @@ describe('prepareVideoGenParams — MiniMax H3 contract', () => {
});
it.each([
- [{ mode: 'image' }, 'MINIMAX_H3_MODE_UNSUPPORTED'],
+ [{ mode: 'extend' }, 'MINIMAX_H3_MODE_UNSUPPORTED'],
[{ extendFromVideoId: '00000000-0000-4000-8000-000000000001' }, 'MINIMAX_H3_MODE_UNSUPPORTED'],
+ [{ mode: 'image' }, 'MINIMAX_H3_I2V_REQUIRES_IMAGE'],
+ [{ mode: 'text', sourceImageFile: 'first.png' }, 'MINIMAX_H3_TEXT_MODE_SOURCE_CONFLICT'],
+ [{ mode: 'image', sourceImageFile: 'first.png', lastImageFile: 'last.png' }, 'MINIMAX_H3_I2V_LAST_IMAGE_CONFLICT'],
+ [{ mode: 'fflf' }, 'MINIMAX_H3_FFLF_REQUIRES_IMAGE'],
[{ negativePrompt: 'blur' }, 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED'],
[{ disableAudio: true }, 'MINIMAX_H3_AUDIO_REQUIRED'],
[{ tiling: 'full' }, 'MINIMAX_H3_TILING_UNSUPPORTED'],
- [{ chunks: 2 }, 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE'],
[{ numFrames: 125 }, 'MINIMAX_H3_INVALID_FRAME_COUNT'],
[{ fps: 30 }, 'MINIMAX_H3_INVALID_FPS'],
])('rejects an unsupported H3 request (%o)', async (fields, code) => {
await expect(prepare({
modelId: H3_MODEL.id,
- mode: 'text',
termsAcceptance: H3_TERMS,
...fields,
})).rejects.toMatchObject({ status: 400, code });
});
+ it('rejects chunks > 1 only while the entry lacks image-to-video', async () => {
+ listVideoModels.mockReturnValue([{ ...H3_MODEL, supportedModes: ['text'] }]);
+ await expect(prepare({
+ modelId: H3_MODEL.id, mode: 'text', termsAcceptance: H3_TERMS, chunks: 2,
+ })).rejects.toMatchObject({ status: 400, code: 'VIDEO_CHAIN_REQUIRES_IMAGE_MODE' });
+
+ listVideoModels.mockReturnValue([H3_MODEL]);
+ const prepared = await prepare({
+ modelId: H3_MODEL.id, mode: 'text', termsAcceptance: H3_TERMS, chunks: 2,
+ });
+ expect(prepared.effectiveChunks).toBe(2);
+ });
+
+ it.each([
+ ['image', { mode: 'image', sourceImageFile: 'first.png' }],
+ ['fflf', { mode: 'fflf', sourceImageFile: 'first.png', lastImageFile: 'last.png' }],
+ ])('accepts %s keyframe conditioning', async (_label, fields) => {
+ const prepared = await prepare({
+ modelId: H3_MODEL.id,
+ termsAcceptance: H3_TERMS,
+ ...fields,
+ });
+ expect(prepared.effectiveModelId).toBe(H3_MODEL.id);
+ expect(prepared.sourceImagePath).toBe('/mock/images/first.png');
+ });
+
it('accepts another supported temporal shape at fixed 24 fps', async () => {
const prepared = await prepare({
modelId: H3_MODEL.id,
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index 726b657e20..6779b3a73d 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -131,6 +131,18 @@ export const BYOV_RUNTIME_INFO = Object.freeze({
export const BYOV_VIDEO_RUNTIMES = Object.freeze(new Set(Object.keys(BYOV_RUNTIME_INFO)));
+// Runtimes whose FFLF *last* frame is a real conditioning anchor rather than an
+// advisory hint: ltx2 runs a true keyframe-interpolation pipeline, and
+// minimax_h3 packs both frames as fl2va conditioning rows. Every other runtime
+// conditions on a single frame and drops the other. Declared once here because
+// three consumers must agree — buildArgs (which forwards it), the last-frame
+// resize in local.js (wasted ffmpeg work otherwise), and the client's
+// "last frame is advisory" note, which reads it off the model payload via
+// `lastFrameAnchored`.
+export const LAST_FRAME_ANCHORED_RUNTIMES = Object.freeze(new Set(['ltx2', 'minimax_h3']));
+
+export const modelAnchorsLastFrame = (model) => LAST_FRAME_ANCHORED_RUNTIMES.has(model?.runtime);
+
export function isByovRuntimeInstalled(runtimeId) {
const info = BYOV_RUNTIME_INFO[runtimeId];
if (!info) return false;
diff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.js
index 193386c73f..054625997c 100644
--- a/server/services/videoGen/runtimes.test.js
+++ b/server/services/videoGen/runtimes.test.js
@@ -15,7 +15,9 @@ vi.mock('child_process', async (importOriginal) => ({
spawn: runtimeMocks.spawn,
}));
-import { invalidateByovReadyCache, isByovRuntimeReady, isPinnedSourceStatusClean } from './runtimes.js';
+import {
+ invalidateByovReadyCache, isByovRuntimeReady, isPinnedSourceStatusClean, modelAnchorsLastFrame,
+} from './runtimes.js';
const REVISION = 'fcd9e9b79a1d6018d91ac477c0968de1fa067e49';
@@ -68,3 +70,23 @@ describe('isByovRuntimeReady', () => {
expect(runtimeMocks.spawn.mock.calls[0][0]).toBe('git');
});
});
+
+// One declaration feeds three consumers: buildArgs (which forwards the last
+// frame), the last-image resize in local.js, and the client's advisory note via
+// the `lastFrameAnchored` field listVideoModels() decorates onto each model.
+describe('modelAnchorsLastFrame', () => {
+ it.each([
+ ['ltx2', true],
+ ['minimax_h3', true],
+ ['mlx_video', false],
+ ['wan22', false],
+ ['hunyuan', false],
+ ])('reports %s as %s', (runtime, anchored) => {
+ expect(modelAnchorsLastFrame({ runtime })).toBe(anchored);
+ });
+
+ it('treats a missing model or runtime as not anchored', () => {
+ expect(modelAnchorsLastFrame(null)).toBe(false);
+ expect(modelAnchorsLastFrame({})).toBe(false);
+ });
+});