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

feat: MiniMax H3 video generation on Windows with CUDA

[._.]/ Adam Eivy4e6e53fc19b4
diff --git a/.changelog/next/added-agent-2b7be877.md b/.changelog/next/added-agent-2b7be877.md
new file mode 100644
index 0000000000..a4d1cb58d9
--- /dev/null
+++ b/.changelog/next/added-agent-2b7be877.md
@@ -0,0 +1 @@
+- MiniMax H3 video generation now runs on Windows/Linux with an NVIDIA GPU, through diffusers' MiniMaxH3ModularPipeline. The macOS list has had H3 since #242, but it runs on PipeNetwork's Apple-Silicon MLX port, so an NVIDIA box had no H3 path at all — the Windows video catalog held exactly one model (LTX-Video 0.9.5). A new `minimax_h3_cuda` BYOV runtime (`~/.portos/minimax-h3-cuda`, installed from Video Gen or `INSTALL_MINIMAX_H3_CUDA=1 bash scripts/setup-image-video.sh`) plus a `MiniMax H3 CUDA int8` model entry bring the same joint video+audio model, the same 768px 32-aligned canvas, the same fl2va first/last keyframe anchoring and the same license gate to the Windows list. Weights are ~144 GB, rendering needs ~24 GB VRAM and ~75 GB of system RAM for offloaded weights, and the runner picks its offload recipe from the card's own VRAM (bf16 auto-offload at 60 GB+, int8 + streamed block offload at 20 GB+, int8 + leaf-level below).
diff --git a/.changelog/next/fixed-agent-2b7be877.md b/.changelog/next/fixed-agent-2b7be877.md
new file mode 100644
index 0000000000..c98b5e4637
--- /dev/null
+++ b/.changelog/next/fixed-agent-2b7be877.md
@@ -0,0 +1,2 @@
+- `scripts/setup-image-video.sh` runs its mflux + FLUX.2 preamble again on a bare invocation. The "was any BYOV runtime requested?" check concatenated ten `INSTALL_*` defaults and compared the result to a literal eight-zero string, so it never matched — every bare `bash scripts/setup-image-video.sh` took the BYOV-only branch and silently skipped the image-gen setup it advertises. It now tests for any non-zero character, which cannot drift as runtimes are added.
+- Migration 242 no longer suppresses video models added to the catalog after it shipped. Its `_shippedDefaults` bootstrap unioned the user's model ids with **today's** `data.reference/media-models.json`, so on a registry that predated the snapshot key it recorded every current built-in as already-delivered — including entries added long after 242 was written. `appendNewlyShippedEntries` reads a recorded id as "the user deleted this", so those entries were then permanently hidden on exactly the installs that had never seen them, with no later migration able to tell the difference. The bootstrap now unions against the id set pinned in the migration itself.
diff --git a/PLAN.md b/PLAN.md
index b0b3c16f71..b86976fa82 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -367,3 +367,11 @@ is not reliably announced.
### Extract the hand-rolled progress meter into a shared ui primitive
- [ ] There is no progress-bar component in `client/src/components/ui/`, so every surface that needs one re-implements the same `h-1.5 rounded-full` track + `style={{ width: `${pct}%` }}` fill: `client/src/pages/Loras.jsx`, `client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx`, `client/src/components/pipeline/stages/EpisodeVideoStage.jsx`, `client/src/components/meatspace/post/PostLlmDrillRunner.jsx`, `client/src/components/meatspace/post/MemoryPractice.jsx`, and now `client/src/components/pipeline/AutopilotMilestones.jsx` — six copies. They already disagree on accessibility: only two carry `role="progressbar"` with `aria-valuenow`, so the rest are invisible to a screen reader. **The call to make:** add `client/src/components/ui/ProgressBar.jsx` taking `{ percent, tone, label }`, always emitting the ARIA trio, and migrate the six call sites (each is 3-8 lines of markup, no behavior change); register it in the ui README the way the other primitives are. Surfaced by the /simplify reuse review on the milestone-map change.
+
+### Move the MiniMax H3 CUDA diffusers pin off a git commit once a release ships it
+
+- [ ] `scripts/requirements-minimax-h3-cuda.txt` installs diffusers from a `git+https://github.com/huggingface/diffusers.git@2da7040b` pin because the MiniMax-H3 modular integration (PR #14355) merged to `main` on 2026-08-05, *after* the v0.39.0 release (2026-07-03) — no tagged release carries it. A git pin means every `INSTALL_MINIMAX_H3_CUDA=1` install clones the diffusers repo to build a wheel, which is slower and needs git on the box, and it will silently keep doing so long after a release makes it unnecessary. **The call to make:** when a diffusers release containing `src/diffusers/modular_pipelines/minimax_h3/` ships, replace the git line with `diffusers==<version>` and drop the explanatory comment above it; nothing else changes, because the runtime's `importProbe` in `server/services/videoGen/runtimes.js` already asserts `MiniMaxH3Transformer3DModel` imports, so a wrong pin reports as not-ready rather than failing inside a render. Check with `curl -s https://api.github.com/repos/huggingface/diffusers/releases | grep tag_name` against the merge date. Surfaced while adding the CUDA runtime.
+
+### Give the video model catalog a platform axis that can reach Linux
+
+- [ ] `getVideoModels()` (`server/lib/mediaModels.js`) picks `IS_WIN ? video.windows : video.macos`, so **a Linux install is served the macOS list** — every entry on it is an MLX runtime (`mlx_video`, `ltx2`, `wan22`, `hunyuan`, `minimax_h3`) that cannot run on Linux at all, while the two entries that genuinely would run there (`ltx_video` via `scripts/generate_win.py` and `minimax_h3_cuda` via diffusers, both plain torch+CUDA) sit in the unreachable `windows` list. Nothing is broken for the two platforms PortOS actually ships to, which is why this has gone unnoticed; the cost is that adding a CUDA runtime has to be documented as Windows-only even when its venv provisions perfectly on Linux (see the scoping notes in `server/services/videoGen/runtimes.js` and the `is_windows` warning in `scripts/setup-image-video.sh`). **The call to make:** the axis is really "MLX vs CUDA", not "macOS vs Windows" — rename the registry buckets to say so (keeping `macos`/`windows` as read aliases so existing `data/media-models.json` files and `_shippedDefaults.video.*` snapshots keep resolving) and select on `process.platform === 'darwin'` rather than on `IS_WIN`. Check `_shippedDefaults.video.{macos,windows}`, `findModelLocation`, the `kind === 'video'` list picker (~line 1202), migrations 233/242/247/268, and `data.reference/media-models.json` — all of them name the two buckets. Do NOT simply flip `IS_WIN ? windows : macos` to `IS_MAC ? macos : windows` without the alias work: it silently swaps every existing Linux install's catalog. Surfaced by the /simplify altitude review while adding the MiniMax H3 CUDA runtime.
diff --git a/client/src/lib/runnerFamilies.js b/client/src/lib/runnerFamilies.js
index 6fd55e1a49..eb1ca95a1b 100644
--- a/client/src/lib/runnerFamilies.js
+++ b/client/src/lib/runnerFamilies.js
@@ -26,6 +26,17 @@ export const VIDEO_LORA_FAMILIES = Object.freeze({
// server/lib/runners.js.
const VIDEO_LORA_FAMILY_SET = new Set(Object.values(VIDEO_LORA_FAMILIES));
export const isVideoLoraFamily = (family) => VIDEO_LORA_FAMILY_SET.has(family);
+// The MiniMax H3 runtimes: PipeNetwork's Apple-Silicon MLX port (`minimax_h3`)
+// and the diffusers + CUDA path Windows/Linux NVIDIA boxes run
+// (`minimax_h3_cuda`). They load the same weights family, so every control H3
+// fixes in the model itself — 24 fps, joint video+audio, CFG-distilled (no
+// negative prompt), the 17n+5 frame grid, no tiling knob — is true of both.
+// Gates asserting one of those facts ask this predicate instead of naming a
+// single runtime, which is what would silently exempt the other one.
+// Mirror of server/lib/runners.js.
+export const MINIMAX_H3_RUNTIMES = Object.freeze(['minimax_h3', 'minimax_h3_cuda']);
+const MINIMAX_H3_RUNTIME_SET = new Set(MINIMAX_H3_RUNTIMES);
+export const isMiniMaxH3Runtime = (runtime) => MINIMAX_H3_RUNTIME_SET.has(runtime);
// The family an INSTALLED LoRA belongs to. `loraCompatKey` is the refined key
// (e.g. flux2-9b) written by the importer; `runnerFamily` is the coarse legacy
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 3878aa71e0..915567a49f 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -37,6 +37,7 @@
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useSearchParams } from 'react-router';
+import { isMiniMaxH3Runtime } from '../lib/runnerFamilies';
import Drawer from '../components/Drawer';
import { ImageGenTab } from '../components/settings/ImageGenTab';
import LocalSetupPanel from '../components/settings/LocalSetupPanel';
@@ -1182,7 +1183,7 @@ export default function VideoGen() {
onChange={handleResolutionChange}
{...localResolutionBounds}
snapOnBlur
- note={currentModel?.runtime === 'minimax_h3'
+ note={isMiniMaxH3Runtime(currentModel?.runtime)
? 'H3 quality presets follow its trained 768px short-edge, area-capped canvas. Smaller custom sizes are off-distribution but useful for faster wiring tests; each edge snaps to 32px.'
: 'Each edge 64–2048px; the server rounds each down to the nearest multiple of 64.'}
/>
diff --git a/data.reference/media-models.json b/data.reference/media-models.json
index 3a683af55d..3e7e18f7e2 100644
--- a/data.reference/media-models.json
+++ b/data.reference/media-models.json
@@ -466,6 +466,170 @@
},
"reviewedAt": "2026-08-09"
}
+ },
+ {
+ "id": "minimax_h3_cuda",
+ "name": "MiniMax H3 CUDA int8 (joint video + audio, ~144 GB download, 24 GB VRAM + 96 GB RAM)",
+ "repo": "MiniMaxAI/MiniMax-H3",
+ "revision": "42ed227ee7df40d41602854ae760620d6eb651fe",
+ "repoFiles": [
+ "LICENSE",
+ "modular_model_index.json",
+ "transformer/config.json",
+ "transformer/diffusion_pytorch_model.safetensors.index.json",
+ "transformer/diffusion_pytorch_model-00001-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00002-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00003-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00004-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00005-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00006-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00007-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00008-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00009-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00010-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00011-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00012-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00013-of-00014.safetensors",
+ "transformer/diffusion_pytorch_model-00014-of-00014.safetensors",
+ "text_encoder/config.json",
+ "text_encoder/model.safetensors.index.json",
+ "text_encoder/model-00001-of-00014.safetensors",
+ "text_encoder/model-00002-of-00014.safetensors",
+ "text_encoder/model-00003-of-00014.safetensors",
+ "text_encoder/model-00004-of-00014.safetensors",
+ "text_encoder/model-00005-of-00014.safetensors",
+ "text_encoder/model-00006-of-00014.safetensors",
+ "text_encoder/model-00007-of-00014.safetensors",
+ "text_encoder/model-00008-of-00014.safetensors",
+ "text_encoder/model-00009-of-00014.safetensors",
+ "text_encoder/model-00010-of-00014.safetensors",
+ "text_encoder/model-00011-of-00014.safetensors",
+ "text_encoder/model-00012-of-00014.safetensors",
+ "text_encoder/model-00013-of-00014.safetensors",
+ "text_encoder/model-00014-of-00014.safetensors",
+ "text_encoder/chat_template.json",
+ "text_encoder/merges.txt",
+ "text_encoder/preprocessor_config.json",
+ "text_encoder/tokenizer.json",
+ "text_encoder/tokenizer_config.json",
+ "text_encoder/video_preprocessor_config.json",
+ "text_encoder/vocab.json",
+ "vae/config.json",
+ "vae/diffusion_pytorch_model.safetensors.index.json",
+ "vae/diffusion_pytorch_model-00001-of-00003.safetensors",
+ "vae/diffusion_pytorch_model-00002-of-00003.safetensors",
+ "vae/diffusion_pytorch_model-00003-of-00003.safetensors",
+ "audio_vae/config.json",
+ "audio_vae/diffusion_pytorch_model.safetensors",
+ "processor/chat_template.json",
+ "processor/merges.txt",
+ "processor/preprocessor_config.json",
+ "processor/tokenizer.json",
+ "processor/tokenizer_config.json",
+ "processor/video_preprocessor_config.json",
+ "processor/vocab.json",
+ "tokenizer/merges.txt",
+ "tokenizer/tokenizer.json",
+ "tokenizer/tokenizer_config.json",
+ "tokenizer/vocab.json",
+ "scheduler/scheduler_config.json",
+ "audio_scheduler/scheduler_config.json"
+ ],
+ "runtime": "minimax_h3_cuda",
+ "supportedModes": [
+ "text",
+ "image",
+ "fflf"
+ ],
+ "defaultFrames": 124,
+ "frameOptions": [
+ 124,
+ 141,
+ 158,
+ 175,
+ 192,
+ 209,
+ 226,
+ 243,
+ 260,
+ 277,
+ 294,
+ 311,
+ 328,
+ 345
+ ],
+ "fpsOptions": [
+ 24
+ ],
+ "defaultWidth": 1344,
+ "defaultHeight": 768,
+ "resolutionStep": 32,
+ "resolutionOptions": [
+ {
+ "label": "1536x672 (21:9 H3 native)",
+ "w": 1536,
+ "h": 672
+ },
+ {
+ "label": "1344x768 (16:9 H3 default)",
+ "w": 1344,
+ "h": 768
+ },
+ {
+ "label": "1024x768 (4:3 H3 native)",
+ "w": 1024,
+ "h": 768
+ },
+ {
+ "label": "768x768 (1:1 H3 native)",
+ "w": 768,
+ "h": 768
+ },
+ {
+ "label": "768x1024 (3:4 H3 native)",
+ "w": 768,
+ "h": 1024
+ },
+ {
+ "label": "768x1344 (9:16 H3 native)",
+ "w": 768,
+ "h": 1344
+ }
+ ],
+ "memoryGb": 96,
+ "steps": 8,
+ "guidance": 0,
+ "samplerLocked": true,
+ "samplerNote": "MiniMax H3 is CFG-distilled; this profile locks the validated 8-point sigma schedule and does not use CFG.",
+ "supportsNegativePrompt": false,
+ "supportsTiling": false,
+ "supportsDisableAudio": false,
+ "disclosure": {
+ "modelCardUrl": "https://huggingface.co/MiniMaxAI/MiniMax-H3",
+ "weightsLicense": {
+ "name": "MiniMax H3 Community License",
+ "url": "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE"
+ },
+ "runtimeLicense": {
+ "name": "Apache-2.0",
+ "url": "https://github.com/huggingface/diffusers/blob/main/LICENSE"
+ },
+ "estimatedDownloadGb": 144.1,
+ "reviewedAt": "2026-08-09"
+ },
+ "termsGate": {
+ "id": "minimax-h3-community-license-2026-08-02",
+ "title": "MiniMax H3 eligibility and terms",
+ "summary": "MiniMax grants use only in its Applicable Territory. The license excludes the European Union, United Kingdom, Republic of Korea, and United States of America.",
+ "acknowledgement": "I confirm I am in the Applicable Territory and agree to the MiniMax H3 Community License and its Acceptable Use Policy.",
+ "licenseUrl": "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/6818f6c32d12b210915e44ad56a4228c2608f160/LICENSE",
+ "excludedTerritories": [
+ "European Union",
+ "United Kingdom",
+ "Republic of Korea",
+ "United States of America"
+ ]
+ }
}
],
"defaultMacos": "ltx23_distilled_q4",
diff --git a/scripts/_minimax_h3_common.py b/scripts/_minimax_h3_common.py
new file mode 100644
index 0000000000..b228ecdf42
--- /dev/null
+++ b/scripts/_minimax_h3_common.py
@@ -0,0 +1,163 @@
+"""Shared helpers for the two PortOS MiniMax H3 runners.
+
+`generate_minimax_h3.py` drives PipeNetwork's Apple-Silicon MLX port and
+`generate_minimax_h3_cuda.py` drives diffusers' `MiniMaxH3ModularPipeline` on
+NVIDIA. They run in *different venvs* and load different pipelines, but they
+present the same CLI to PortOS and enforce the same model facts — so everything
+that is a property of the H3 checkpoint rather than of the runtime in front of
+it belongs here, stated once.
+
+Cross-venv sharing works the same way `_runner_common.py` already does: this
+module is stdlib-only at import time (`huggingface_hub` and `PIL` are imported
+inside the function that needs them), and both runners reach it through the
+same-directory `sys.path.insert` idiom. Neither venv is forced to grow a
+dependency it didn't already pin.
+
+What must NOT move here: anything true of only one runner. The MLX port's
+`resolve_transformer_snapshot` (its quantized DiT ships a separate
+`quant_config.json`), its LoRA argument pairing, and the CUDA path's
+`--repo-file` requirement and offload profiles all stay in their own runner.
+The frame WINDOW is the subtle one — it differs between the two (diffusers
+requires the snapped duration in 5-15s where the MLX port accepts 4-15s), so
+`validate_h3_output_args` takes it as a parameter rather than asserting one.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import sys
+from pathlib import Path
+
+# H3 renders at a fixed 24 fps, and its video VAE can only decode a frame count
+# on the 17n+5 grid. Both are checkpoint facts, identical on every runtime.
+FPS = 24
+FRAME_MODULUS = 17
+FRAME_REMAINDER = 5
+
+
+def snapshot_root(resolved_file: str | Path, repo_filename: str) -> Path:
+ """Return the HF snapshot directory containing one resolved repo file."""
+ levels = len(Path(repo_filename).parts)
+ # Hugging Face snapshot entries are normally symlinks into `blobs/`.
+ # Resolving the symlink would therefore walk OUT of the snapshot and hand
+ # the pipeline a blob directory. `hf_hub_download` already returns an
+ # absolute snapshot path, so preserve that lexical path deliberately.
+ return Path(resolved_file).absolute().parents[levels - 1]
+
+
+def resolve_cached_snapshot(repo: str, revision: str, required_files: list[str]) -> Path:
+ """Resolve exact cached files without ever permitting a network fallback."""
+ if not required_files:
+ raise RuntimeError(f"No required files declared for {repo}.")
+
+ from huggingface_hub import hf_hub_download
+
+ resolved: list[tuple[str, Path]] = []
+ for filename in required_files:
+ try:
+ path = hf_hub_download(
+ repo_id=repo,
+ filename=filename,
+ revision=revision,
+ local_files_only=True,
+ )
+ except Exception as exc:
+ raise RuntimeError(
+ f"Required cached weight is missing: {repo}@{revision[:12]}/{filename}. "
+ "Use Download in Video Gen before generating."
+ ) from exc
+ resolved.append((filename, Path(path)))
+
+ roots = {snapshot_root(path, filename) for filename, path in resolved}
+ if len(roots) != 1:
+ raise RuntimeError(f"Cached files for {repo}@{revision[:12]} span multiple snapshots; repair the model in Video Gen.")
+ return roots.pop()
+
+
+def require_ffmpeg() -> str:
+ """Fail before loading tens of GB of weights when muxing cannot succeed."""
+ path = shutil.which("ffmpeg")
+ if path is None:
+ raise RuntimeError("ffmpeg is required to mux MiniMax H3 video and audio; install it before generating.")
+ return path
+
+
+def emit_result(output: Path) -> None:
+ """Emit the completion contract that arms PortOS's teardown watchdog."""
+ print(json.dumps({"video_path": str(output)}), flush=True)
+
+
+def validate_h3_output_args(
+ args,
+ *,
+ min_frames: int,
+ max_frames: int,
+ frame_window_message: str,
+) -> None:
+ """Check every output constraint the H3 checkpoint imposes on both runners.
+
+ `frame_window_message` is the one genuinely runtime-specific part: the two
+ pipelines accept different duration windows on the same 17n+5 grid, so each
+ runner supplies its own bounds and the sentence that explains them.
+
+ Raises SystemExit so a bad request reports as a clean one-line runner error
+ rather than a traceback (both runners' main() are invoked via SystemExit).
+ """
+ if args.fps != FPS:
+ raise SystemExit(f"MiniMax H3 runs at a fixed {FPS} fps; got {args.fps}.")
+ if args.width <= 0 or args.height <= 0 or args.width % 32 or args.height % 32:
+ raise SystemExit(f"MiniMax H3 dimensions must be positive multiples of 32; got {args.width}x{args.height}.")
+ if not min_frames <= args.num_frames <= max_frames:
+ raise SystemExit(frame_window_message)
+ if args.num_frames % FRAME_MODULUS != FRAME_REMAINDER:
+ 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."""
+ # Every path is checked before anything is opened, so a bad second keyframe
+ # doesn't cost a decode of the first — and the message names the PortOS-side
+ # cause rather than surfacing Pillow's bare FileNotFoundError.
+ for path in paths:
+ if not Path(path).is_file():
+ raise RuntimeError(f"Conditioning image is missing: {path}")
+ # Imported only once there is something to decode: a text-only run never
+ # pulls Pillow in, and the missing-file path above stays dependency-free.
+ if not paths:
+ return []
+ from PIL import Image, ImageOps
+
+ images = []
+ for path in paths:
+ 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 multi-GB load that follows.
+ ImageOps.exif_transpose(image, in_place=True)
+ images.append(image)
+ return images
+
+
+__all__ = [
+ "FPS",
+ "FRAME_MODULUS",
+ "FRAME_REMAINDER",
+ "emit_result",
+ "load_keyframes",
+ "require_ffmpeg",
+ "resolve_cached_snapshot",
+ "snapshot_root",
+ "validate_h3_output_args",
+]
diff --git a/scripts/_minimax_h3_common.test.js b/scripts/_minimax_h3_common.test.js
new file mode 100644
index 0000000000..119db8e649
--- /dev/null
+++ b/scripts/_minimax_h3_common.test.js
@@ -0,0 +1,241 @@
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../server/lib/testHelper.js';
+
+// The helpers both MiniMax H3 runners share. They used to be copied into each
+// runner and tested twice, which is exactly the shape that lets a fix land in
+// one copy and leave the other broken — the lexical-snapshot-root rule below
+// being the one where that would be silent. One module, one suite.
+const script = join(dirname(fileURLToPath(import.meta.url)), '_minimax_h3_common.py');
+
+// Probe for an interpreter that actually RUNS rather than assuming a name. On
+// Windows a box with no Store-installed Python still has `python` on PATH as an
+// alias STUB: it exists, exits non-zero, and prints "Python was not found", so a
+// name-only choice passes here and then every case dies with an opaque "Command
+// failed". Null when there is genuinely none, so the suite skips.
+const pyBin = resolveTestPython();
+const runPython = (source) => execFileSync(pyBin, ['-c', source, script], {
+ encoding: 'utf8',
+});
+
+// Python on Windows writes CRLF, so splitting on newlines alone leaves a
+// trailing carriage return that fails every string comparison on its own.
+const lines = (output) => output.trim().split('\n').map((line) => line.trimEnd());
+
+// Load the module by path (it is stdlib-only at import time, which is what
+// makes it importable from both venvs — and from a bare interpreter here).
+const importShared = [
+ 'import importlib.util, sys',
+ 'from pathlib import Path',
+ 'script = Path(sys.argv[1])',
+ 'spec = importlib.util.spec_from_file_location("_minimax_h3_common", script)',
+ 'shared = importlib.util.module_from_spec(spec)',
+ 'spec.loader.exec_module(shared)',
+].join('\n');
+
+// Drive validate_h3_output_args through a real argparse Namespace, the same
+// object both runners build.
+const validate = (overrides = {}, window = {}) => {
+ const fields = {
+ fps: 24, width: 1344, height: 768, num_frames: 124, steps: 8,
+ image: [], anchor: [], ...overrides,
+ };
+ const bounds = { min_frames: 124, max_frames: 345, ...window };
+ return runPython(`${importShared}\n${[
+ 'import argparse, json',
+ `args = argparse.Namespace(**json.loads(${JSON.stringify(JSON.stringify(fields))}))`,
+ 'try:',
+ ' shared.validate_h3_output_args(',
+ ' args,',
+ ` min_frames=${bounds.min_frames},`,
+ ` max_frames=${bounds.max_frames},`,
+ ' frame_window_message="WINDOW",',
+ ' )',
+ ' print("OK")',
+ 'except SystemExit as exc:',
+ ' print(f"REJECTED:{exc}")',
+ ].join('\n')}`).trim();
+};
+
+describe.skipIf(!pyBin)('_minimax_h3_common.py — checkpoint facts shared by both H3 runners', () => {
+ it('states the fixed fps and frame grid once', () => {
+ const output = lines(runPython(`${importShared}\n${[
+ 'print(f"{shared.FPS},{shared.FRAME_MODULUS},{shared.FRAME_REMAINDER}")',
+ ].join('\n')}`));
+ expect(output[0]).toBe('24,17,5');
+ });
+
+ describe('validate_h3_output_args', () => {
+ it('accepts a legal request', () => {
+ expect(validate()).toBe('OK');
+ });
+
+ it('locks fps to 24', () => {
+ expect(validate({ fps: 30 })).toMatch(/^REJECTED:.*fixed 24 fps/);
+ });
+
+ it('requires positive 32px-aligned dimensions', () => {
+ expect(validate({ width: 0 })).toMatch(/^REJECTED:.*multiples of 32/);
+ expect(validate({ height: 770 })).toMatch(/^REJECTED:.*multiples of 32/);
+ expect(validate({ width: 960, height: 544 })).toBe('OK');
+ });
+
+ it('takes the duration window from the caller, not from a shared constant', () => {
+ // This is the one H3 constraint that genuinely differs between the two
+ // runners (diffusers 5-15s vs the MLX port's 4-15s), so the shared check
+ // must defer to the bounds and the message it is handed.
+ expect(validate({ num_frames: 107 }, { min_frames: 124 })).toBe('REJECTED:WINDOW');
+ expect(validate({ num_frames: 107 }, { min_frames: 107 })).toBe('OK');
+ expect(validate({ num_frames: 362 }, { max_frames: 345 })).toBe('REJECTED:WINDOW');
+ expect(validate({ num_frames: 362 }, { max_frames: 362 })).toBe('OK');
+ });
+
+ it('requires a 17n+5 frame count inside whatever window it was given', () => {
+ expect(validate({ num_frames: 130 })).toMatch(/^REJECTED:.*17n\+5/);
+ });
+
+ it('requires at least 2 sigma grid points', () => {
+ expect(validate({ steps: 1 })).toMatch(/^REJECTED:.*2 sigma grid points/);
+ });
+
+ it('requires one anchor per image, and distinct anchors', () => {
+ expect(validate({ image: ['a.png', 'b.png'], anchor: ['first'] }))
+ .toMatch(/^REJECTED:.*one --anchor per --image/);
+ // A repeated anchor would overwrite one keyframe's latent position with
+ // the other's, silently rendering something nobody asked for.
+ expect(validate({ image: ['a.png', 'b.png'], anchor: ['first', 'first'] }))
+ .toMatch(/^REJECTED:.*distinct/);
+ expect(validate({ image: ['a.png', 'b.png'], anchor: ['first', 'last'] })).toBe('OK');
+ });
+ });
+
+ describe('resolve_cached_snapshot', () => {
+ it('keeps the lexical snapshot root when cache entries are blob symlinks', () => {
+ // Resolving the symlink would walk OUT of the snapshot into blobs/ and
+ // hand the pipeline a directory with no component layout at all.
+ const output = runPython(`${importShared}\n${[
+ 'import tempfile, types',
+ 'with tempfile.TemporaryDirectory() as temp:',
+ ' root = Path(temp)',
+ ' blob = root / "blobs" / "abc"',
+ ' blob.parent.mkdir(parents=True)',
+ ' blob.write_text("weights")',
+ ' entry = root / "snapshots" / "revision" / "transformer" / "config.json"',
+ ' entry.parent.mkdir(parents=True)',
+ ' entry.symlink_to(blob)',
+ ' fake = types.ModuleType("huggingface_hub")',
+ ' fake.hf_hub_download = lambda **kw: str(entry)',
+ ' sys.modules["huggingface_hub"] = fake',
+ ' print(shared.resolve_cached_snapshot("org/repo", "revision", ["transformer/config.json"]))',
+ ].join('\n')}`);
+ expect(output.trim()).toMatch(/snapshots[/\\]revision$/);
+ });
+
+ it('names the PortOS-side remedy when a pinned file is not cached', () => {
+ // A bare huggingface_hub error would send the user hunting through a
+ // cache directory; naming the file and the remedy is what makes it act.
+ const output = runPython(`${importShared}\n${[
+ 'import types',
+ 'fake = types.ModuleType("huggingface_hub")',
+ 'def boom(**kw): raise OSError("not found locally")',
+ 'fake.hf_hub_download = boom',
+ 'sys.modules["huggingface_hub"] = fake',
+ 'try:',
+ ' shared.resolve_cached_snapshot("org/repo", "0123456789abcdef", ["transformer/config.json"])',
+ 'except RuntimeError as exc:',
+ ' print(exc)',
+ ].join('\n')}`);
+ expect(output).toContain('Use Download in Video Gen');
+ expect(output).toContain('transformer/config.json');
+ });
+
+ it('refuses an empty file list rather than resolving nothing', () => {
+ const output = runPython(`${importShared}\n${[
+ 'try:',
+ ' shared.resolve_cached_snapshot("org/repo", "revision", [])',
+ 'except RuntimeError as exc:',
+ ' print(exc)',
+ ].join('\n')}`);
+ expect(output).toContain('No required files declared');
+ });
+
+ it('refuses a set of files that spans two snapshots', () => {
+ const output = runPython(`${importShared}\n${[
+ 'import itertools, tempfile, types',
+ 'with tempfile.TemporaryDirectory() as temp:',
+ ' root = Path(temp)',
+ ' paths = []',
+ ' for rev in ("revA", "revB"):',
+ ' entry = root / "snapshots" / rev / "transformer" / "config.json"',
+ ' entry.parent.mkdir(parents=True)',
+ ' entry.write_text("x")',
+ ' paths.append(str(entry))',
+ ' it = iter(paths)',
+ ' fake = types.ModuleType("huggingface_hub")',
+ ' fake.hf_hub_download = lambda **kw: next(it)',
+ ' sys.modules["huggingface_hub"] = fake',
+ ' try:',
+ ' shared.resolve_cached_snapshot("org/repo", "revision", ["transformer/config.json", "transformer/other.json"])',
+ ' except RuntimeError as exc:',
+ ' print(exc)',
+ ].join('\n')}`);
+ expect(output).toContain('span multiple snapshots');
+ });
+ });
+
+ it('fails the ffmpeg preflight before any model load can begin', () => {
+ // Tens of GB of weights load before the mux; discovering a missing ffmpeg
+ // after that wastes the whole render.
+ const output = runPython(`${importShared}\n${[
+ 'shared.shutil.which = lambda name: None',
+ 'try:',
+ ' shared.require_ffmpeg()',
+ 'except RuntimeError as exc:',
+ ' print(exc)',
+ ].join('\n')}`);
+ expect(output).toContain('ffmpeg is required');
+ });
+
+ it('emits the video_path JSON completion contract on stdout', () => {
+ // PortOS arms its teardown watchdog on this line, so it must be the only
+ // thing on stdout and must parse.
+ const output = runPython(`${importShared}\nshared.emit_result(Path("/tmp/example.mp4"))`);
+ expect(JSON.parse(output).video_path).toMatch(/example\.mp4$/);
+ });
+
+ describe('load_keyframes', () => {
+ it('skips the Pillow import entirely for a text-only run', () => {
+ const output = lines(runPython(`${importShared}\n${[
+ 'print(shared.load_keyframes([]))',
+ 'print("PIL" in sys.modules)',
+ ].join('\n')}`));
+ expect(output[0]).toBe('[]');
+ expect(output[1]).toBe('False');
+ });
+
+ it('names the missing conditioning image rather than surfacing a decode error', () => {
+ const output = runPython(`${importShared}\n${[
+ 'try:',
+ ' shared.load_keyframes(["/definitely/missing.png"])',
+ 'except RuntimeError as exc:',
+ ' print(exc)',
+ ].join('\n')}`);
+ expect(output).toContain('Conditioning image is missing');
+ });
+
+ it('checks every path before decoding any of them', () => {
+ // A bad second keyframe must not cost a decode of the first.
+ const output = runPython(`${importShared}\n${[
+ 'try:',
+ ' shared.load_keyframes(["/definitely/a.png", "/definitely/b.png"])',
+ 'except RuntimeError as exc:',
+ ' print(exc)',
+ 'print("PIL" in sys.modules)',
+ ].join('\n')}`);
+ expect(output).toContain('/definitely/a.png');
+ expect(output.trim().endsWith('False')).toBe(true);
+ });
+ });
+});
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.py
index 434f12862d..84e9134b9d 100644
--- a/scripts/generate_minimax_h3.py
+++ b/scripts/generate_minimax_h3.py
@@ -17,7 +17,6 @@ import argparse
import json
import os
import re
-import shutil
import subprocess
import sys
from contextlib import redirect_stdout
@@ -25,13 +24,17 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _runner_common import emit_runtime_fingerprint, heartbeat, register_source_namespace # noqa: E402
+from _minimax_h3_common import ( # noqa: E402
+ FPS, emit_result, load_keyframes, require_ffmpeg, resolve_cached_snapshot,
+ validate_h3_output_args,
+)
-FPS = 24
+# The MLX port accepts H3's full documented 4-15s range. The diffusers CUDA
+# runner is narrower (5-15s) — see generate_minimax_h3_cuda.py — which is why
+# the window is per-runner while FPS and the 17n+5 grid are shared.
MIN_FRAMES = 107 # first 17n+5 grid point at or above the upstream 4-second minimum
MAX_FRAMES = 362 # first 17n+5 grid point at or above 15 seconds
-FRAME_MODULUS = 17
-FRAME_REMAINDER = 5
STEP_RE = re.compile(r"\bstep\s+(\d+)/(\d+)\b", re.IGNORECASE)
@@ -74,45 +77,6 @@ def parse_args() -> argparse.Namespace:
return parser.parse_args()
-def snapshot_root(resolved_file: str | Path, repo_filename: str) -> Path:
- """Return the HF snapshot directory containing one resolved repo file."""
- levels = len(Path(repo_filename).parts)
- # Hugging Face snapshot entries are normally symlinks into `blobs/`.
- # Resolving the symlink would therefore walk OUT of the snapshot and hand
- # the pipeline a blob directory. `hf_hub_download` already returns an
- # absolute snapshot path, so preserve that lexical path deliberately.
- return Path(resolved_file).absolute().parents[levels - 1]
-
-
-def resolve_cached_snapshot(repo: str, revision: str, required_files: list[str]) -> Path:
- """Resolve exact cached files without ever permitting a network fallback."""
- if not required_files:
- raise RuntimeError(f"No required files declared for {repo}.")
-
- from huggingface_hub import hf_hub_download
-
- resolved: list[tuple[str, Path]] = []
- for filename in required_files:
- try:
- path = hf_hub_download(
- repo_id=repo,
- filename=filename,
- revision=revision,
- local_files_only=True,
- )
- except Exception as exc:
- raise RuntimeError(
- f"Required cached weight is missing: {repo}@{revision[:12]}/{filename}. "
- "Use Download in Video Gen before generating."
- ) from exc
- resolved.append((filename, Path(path)))
-
- roots = {snapshot_root(path, filename) for filename, path in resolved}
- if len(roots) != 1:
- raise RuntimeError(f"Cached files for {repo}@{revision[:12]} span multiple snapshots; repair the model in Video Gen.")
- return roots.pop()
-
-
def resolve_transformer_snapshot(repo: str, revision: str) -> Path:
"""Resolve the quantized transformer and every shard named by its index."""
root = resolve_cached_snapshot(
@@ -249,14 +213,6 @@ def build_encoder_shim(
return root
-def require_ffmpeg() -> str:
- """Fail before loading ~83 GB of weights when muxing cannot succeed."""
- path = shutil.which("ffmpeg")
- if path is None:
- raise RuntimeError("ffmpeg is required to mux MiniMax H3 video and audio; install it before generating.")
- return path
-
-
def verify_runtime_checkout(runtime_dir: Path, expected_revision: str) -> None:
"""Require the exact commit and a clean executable source package."""
try:
@@ -279,11 +235,6 @@ def verify_runtime_checkout(runtime_dir: Path, expected_revision: str) -> None:
raise RuntimeError("MiniMax H3 runtime source differs from the pinned checkout; use Repair in Video Gen.")
-def emit_result(output: Path) -> None:
- """Emit the completion contract that arms PortOS's teardown watchdog."""
- print(json.dumps({"video_path": str(output)}), flush=True)
-
-
class ProgressWriter:
"""Translate the port's human step lines into PortOS STAGE progress."""
@@ -320,24 +271,18 @@ class ProgressWriter:
def validate_args(args: argparse.Namespace) -> None:
- if args.fps != FPS:
- raise SystemExit(f"MiniMax H3 runs at a fixed {FPS} fps; got {args.fps}.")
- if args.width <= 0 or args.height <= 0 or args.width % 32 or args.height % 32:
- raise SystemExit(f"MiniMax H3 dimensions must be positive multiples of 32; got {args.width}x{args.height}.")
- if not MIN_FRAMES <= args.num_frames <= MAX_FRAMES:
- raise SystemExit(f"MiniMax H3 supports approximately 4-15 seconds ({MIN_FRAMES}-{MAX_FRAMES} aligned frames).")
- if args.num_frames % FRAME_MODULUS != FRAME_REMAINDER:
- 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}.")
+ # Everything the H3 checkpoint imposes regardless of runtime — fps, the 32px
+ # canvas grid, the 17n+5 frame grid, the sigma floor, keyframe anchoring —
+ # lives in the shared module so this runner and the CUDA one cannot drift.
+ # Only the duration window and the LoRA pairing below are ours.
+ validate_h3_output_args(
+ args,
+ min_frames=MIN_FRAMES,
+ max_frames=MAX_FRAMES,
+ frame_window_message=(
+ f"MiniMax H3 supports approximately 4-15 seconds ({MIN_FRAMES}-{MAX_FRAMES} aligned frames)."
+ ),
+ )
if len(args.lora_scale) != len(args.lora):
raise SystemExit(
f"MiniMax H3 needs one --lora-scale per --lora; got {len(args.lora)} LoRAs "
@@ -361,32 +306,6 @@ def validate_args(args: argparse.Namespace) -> None:
raise SystemExit("--text-encoder-key-prefix / --text-encoder-final-norm-key need --text-encoder-file.")
-def load_keyframes(paths: list[str]) -> list:
- """Open each conditioning image upright, in RGB, in the order given."""
- # Every path is checked before anything is opened, so a bad second keyframe
- # doesn't cost a decode of the first — and the message names the PortOS-side
- # cause rather than surfacing Pillow's bare FileNotFoundError.
- for path in paths:
- if not Path(path).is_file():
- raise RuntimeError(f"Conditioning image is missing: {path}")
- # Imported only once there is something to decode: a text-only run never
- # pulls Pillow in, and the missing-file path above stays dependency-free.
- if not paths:
- return []
- from PIL import Image, ImageOps
-
- images = []
- for path in paths:
- 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)
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index 42594aaf6e..c6fe23ca2a 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -68,22 +68,6 @@ const argsExpr = (overrides = {}) => {
};
describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
- it('keeps the lexical HF snapshot root when cache entries are blob symlinks', () => {
- const output = runPython(`${importRunner}\n${[
- 'import tempfile',
- 'with tempfile.TemporaryDirectory() as temp:',
- ' root = Path(temp)',
- ' blob = root / "blobs" / "abc"',
- ' blob.parent.mkdir(parents=True)',
- ' blob.write_text("weights")',
- ' entry = root / "snapshots" / "revision" / "FL2VA" / "config.json"',
- ' entry.parent.mkdir(parents=True)',
- ' entry.symlink_to(blob)',
- ' print(runner.snapshot_root(entry, "FL2VA/config.json"))',
- ].join('\n')}`);
- expect(output.trim()).toMatch(/snapshots[/\\]revision$/);
- });
-
it('preflights transformer config, quant config, index, and every indexed shard', () => {
const output = runPython(`${importRunner}\n${[
'import json, tempfile',
@@ -106,70 +90,36 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
expect(result.resolved).toBeTruthy();
});
- it('fails the ffmpeg preflight before any model load can begin', () => {
- const output = runPython(`${importRunner}\n${[
- 'runner.shutil.which = lambda _name: None',
- 'try:',
- ' runner.require_ffmpeg()',
- 'except RuntimeError as exc:',
- ' print(str(exc))',
- 'else:',
- ' raise SystemExit("missing preflight did not fail")',
- ].join('\n')}`);
- expect(output).toMatch(/ffmpeg is required/i);
- });
-
- it('rejects zero dimensions at the execution boundary', () => {
- const output = runPython(`${importRunner}\n${[
- 'from types import SimpleNamespace',
- argsExpr({ width: 0 }),
- 'try:',
- ' runner.validate_args(args)',
- 'except SystemExit as exc:',
- ' print(str(exc))',
- 'else:',
- ' raise SystemExit("zero dimensions were accepted")',
- ].join('\n')}`);
- expect(output).toMatch(/dimensions must be positive multiples of 32/i);
- });
-
- it('accepts the upstream 4-second aligned frame count and native 32px canvas grid', () => {
- const output = runPython(`${importRunner}\n${[
+ // The duration window is the one output fact that is per-runner: the MLX port
+ // takes H3's full documented 4-15s range, where the diffusers CUDA runner is
+ // narrower. Everything else on the grid (fps, the 32px canvas, the 17n+5 step,
+ // anchoring) is shared, and asserted once in _minimax_h3_common.test.js.
+ it.each([107, 124, 362])('accepts the MLX window's %i-frame grid point', (frames) => {
+ const output = runPython(`${importRunner}
+${[
'from types import SimpleNamespace',
- argsExpr({ width: 1536, height: 672, num_frames: 107 }),
+ argsExpr({ width: 1536, height: 672, num_frames: frames }),
'runner.validate_args(args)',
'print("ok")',
- ].join('\n')}`);
+ ].join('
+')}`);
expect(output.trim()).toBe('ok');
});
- // 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${[
+ it('rejects a frame count outside the MLX window', () => {
+ const output = runPython(`${importRunner}
+${[
'from types import SimpleNamespace',
- argsExpr({ image: images, anchor: anchors }),
+ argsExpr({ width: 1536, height: 672, num_frames: 90 }),
'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',
- argsExpr({ image: ['a.png', 'b.png'], anchor: ['first', 'last'] }),
- 'runner.validate_args(args)',
- 'print("ok")',
- ].join('\n')}`);
- expect(output.trim()).toBe('ok');
+ ' raise SystemExit("an out-of-window frame count was accepted")',
+ ].join('
+')}`);
+ expect(output).toMatch(/approximately 4-15 seconds \(107-362 aligned frames\)/i);
});
// An unpaired --lora/--lora-scale would apply the wrong strength (or none) to
@@ -192,51 +142,6 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
expect(output).toMatch(pattern);
});
- // Reading the keyframes happens before the ~83 GB load, so a bad path costs
- // a second rather than an hour. Both branches asserted here run WITHOUT
- // Pillow — CI's bare python3 has no PIL, and blocking `import PIL` on them
- // would make a missing-file report (and every text-only run) need it.
- it('fails a missing conditioning image without importing Pillow', () => {
- const output = runPython(`${importRunner}\n${[
- 'import sys',
- 'sys.modules["PIL"] = None # make any `from PIL import ...` fail loudly',
- '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('skips the Pillow import entirely for a text-only run', () => {
- const output = runPython(`${importRunner}\n${[
- 'import sys',
- 'sys.modules["PIL"] = None',
- 'print(runner.load_keyframes([]))',
- ].join('\n')}`);
- expect(output.trim()).toBe('[]');
- });
-
- // A later keyframe's bad path must not cost a decode of the earlier one.
- it('validates every keyframe path before opening any of them', () => {
- const output = runPython(`${importRunner}\n${[
- 'import sys, tempfile',
- 'sys.modules["PIL"] = None',
- 'with tempfile.NamedTemporaryFile(suffix=".png") as good:',
- ' try:',
- ' runner.load_keyframes([good.name, "/nonexistent/last.png"])',
- ' except RuntimeError as exc:',
- ' print(str(exc))',
- ' else:',
- ' raise SystemExit("missing second keyframe was accepted")',
- ].join('\n')}`);
- expect(output).toMatch(/Conditioning image is missing: \/nonexistent\/last\.png/);
- });
-
- // ---- substituted prompt conditioner (#4081) --------------------------------
-
// A partial flag set would silently fall back to the stock conditioner and
// hand back a render the user has no way to tell apart from the one they asked
// for, so the boundary rejects it instead of choosing for them.
@@ -474,15 +379,6 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
expect(result.built).toBe(false);
});
- it('emits the video_path JSON completion contract on stdout', () => {
- const output = runPython(`${importRunner}\nrunner.emit_result(Path("/tmp/example.mp4"))`);
- // pathlib.Path renders with the platform separator, so the emitted path is
- // backslashed on Windows. Normalize what was RECEIVED — the contract under
- // test is the JSON shape and the key, not the separator the OS spells.
- const { video_path: videoPath } = JSON.parse(output);
- expect(videoPath.split('\\').join('/')).toBe('/tmp/example.mp4');
- });
-
it('loads only the pinned namespace and cannot import a root-level shadow module', () => {
const output = runPython(`${importRunner}\n${[
'import importlib, tempfile',
diff --git a/scripts/generate_minimax_h3_cuda.py b/scripts/generate_minimax_h3_cuda.py
new file mode 100644
index 0000000000..cba144bdcc
--- /dev/null
+++ b/scripts/generate_minimax_h3_cuda.py
@@ -0,0 +1,300 @@
+#!/usr/bin/env python3
+"""Cache-only PortOS runner for MiniMax H3 on CUDA (Windows / Linux NVIDIA).
+
+The CUDA sibling of `generate_minimax_h3.py`. Where that helper drives
+PipeNetwork's pinned Apple-Silicon MLX port, this one drives diffusers'
+`MiniMaxH3ModularPipeline` — the upstream integration, which is the only H3
+path an NVIDIA box has. The two present the SAME CLI to PortOS (`--prompt`,
+geometry, `--image` / `--anchor` pairs, `--output`) and emit the same
+STAGE:/STATUS:/RUNTIME: progress frames, so `local.js` differs only in which
+binary and helper it spawns.
+
+The Video Gen UI owns every network operation. This helper resolves only the
+exact revision already present in Hugging Face's cache, loads the diffusers
+`fl2va` workflow from it, 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.
+
+Memory: the bf16 components are 66.3 GB (transformer) + 66.7 GB (Qwen3-VL
+conditioner), so nothing fits on a consumer card unquantized. The offload
+profiles below are the recipes upstream documents, chosen from the card's own
+VRAM unless `--offload-profile` pins one.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _runner_common import emit_runtime_fingerprint, heartbeat # noqa: E402
+from _minimax_h3_common import ( # noqa: E402
+ FPS, emit_result, load_keyframes, require_ffmpeg, resolve_cached_snapshot,
+ validate_h3_output_args,
+)
+
+
+# The diffusers integration snaps `num_frames` up to the next 17n+5 the video
+# VAE can decode and then requires the RESULTING duration to land in 5-15 s.
+# That is narrower than the MLX port's 4-15 s at both ends, so these bounds are
+# deliberately not shared with generate_minimax_h3.py — see the frameOptions
+# note on MINIMAX_H3_CUDA_PROFILE in server/lib/mediaModels.js.
+MIN_FRAMES = 124 # first 17n+5 grid point at or above 5 seconds
+MAX_FRAMES = 345 # last 17n+5 grid point at or below 15 seconds
+OFFLOAD_PROFILES = ("auto", "bf16", "int8-stream", "int8-lean")
+
+# int8 weight-only quantization must skip the projection / embedding / norm
+# layers on each component — they are small, numerically sensitive, and
+# quantizing them is what degrades the output rather than saving memory. These
+# two lists are upstream's documented `modules_to_not_convert` sets.
+TRANSFORMER_KEEP_BF16 = [
+ "proj_in", "audio_proj_in", "context_embedder", "time_embedder", "time_proj",
+ "token_refiner", "norm_out", "proj_out", "audio_proj_out",
+]
+TEXT_ENCODER_KEEP_BF16 = [
+ "model.visual",
+ "model.language_model.embed_tokens",
+ "model.language_model.norm",
+ "lm_head",
+]
+
+
+def log(message: str) -> None:
+ print(message, file=sys.stderr, flush=True)
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model-repo", required=True)
+ parser.add_argument("--model-revision", required=True)
+ parser.add_argument("--repo-file", action="append", default=[],
+ help="repo-relative diffusers component file that must already be cached (repeatable)")
+ parser.add_argument("--prompt", required=True)
+ parser.add_argument("--width", type=int, required=True)
+ parser.add_argument("--height", type=int, required=True)
+ parser.add_argument("--num-frames", type=int, required=True)
+ 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("--offload-profile", choices=OFFLOAD_PROFILES, default="auto",
+ help="weight-placement recipe; 'auto' sizes one from the visible CUDA device")
+ parser.add_argument("--output", required=True)
+ return parser.parse_args()
+
+
+def validate_args(args: argparse.Namespace) -> None:
+ # Everything the H3 checkpoint imposes regardless of runtime — fps, the 32px
+ # canvas grid, the 17n+5 frame grid, the sigma floor, keyframe anchoring —
+ # lives in the shared module so this runner and the MLX one cannot drift.
+ # Only the duration window and the file-list requirement below are ours.
+ validate_h3_output_args(
+ args,
+ min_frames=MIN_FRAMES,
+ max_frames=MAX_FRAMES,
+ frame_window_message=(
+ f"MiniMax H3 on diffusers supports 5-15 seconds "
+ f"({MIN_FRAMES}-{MAX_FRAMES} aligned frames); got {args.num_frames}."
+ ),
+ )
+ if not args.repo_file:
+ raise SystemExit("MiniMax H3 needs its pinned component file list (--repo-file).")
+
+
+def resolve_offload_profile(requested: str) -> str:
+ """Pick a weight-placement recipe from the visible CUDA device's VRAM.
+
+ An explicit request always wins — the registry entry can pin one, and a user
+ who knows their box better than a capacity heuristic does should not be
+ overridden. 'auto' is the default because the entry is shared across every
+ install that syncs it and cannot know what GPU is on the other end.
+ """
+ import torch
+
+ if not torch.cuda.is_available():
+ raise RuntimeError(
+ "MiniMax H3 CUDA needs a visible NVIDIA device. Repair the MiniMax H3 CUDA runtime from Video Gen."
+ )
+ if requested != "auto":
+ return requested
+ total_gb = torch.cuda.get_device_properties(0).total_memory / 1e9
+ # 60 GB is the floor for holding one bf16 component resident while the
+ # manager swaps the other; below it, int8 is the only thing that fits.
+ # 20 GB is where streamed block-level offload stops fitting a block plus
+ # its activations, and the leaner leaf-level recipe takes over.
+ if total_gb >= 60:
+ return "bf16"
+ return "int8-stream" if total_gb >= 20 else "int8-lean"
+
+
+def load_pipeline(snapshot: Path, profile: str):
+ """Load the `fl2va` workflow under one of the documented memory recipes.
+
+ `fl2va` covers text-to-video too (it is the same `transformer/` partition),
+ so one workflow serves every mode PortOS exposes and the 66 GB
+ `transformer_ref/` partition is never loaded — which is also why it is
+ absent from the model entry's download list.
+ """
+ import torch
+ from diffusers import ComponentsManager, ModularPipeline
+
+ if profile == "bf16":
+ manager = ComponentsManager()
+ pipe = ModularPipeline.from_pretrained(str(snapshot), components_manager=manager)
+ pipe.load_components(workflow="fl2va", dtype=torch.bfloat16)
+ manager.enable_auto_cpu_offload(device="cuda", memory_reserve_margin="12GB")
+ return pipe
+
+ from diffusers import MiniMaxH3Transformer3DModel, TorchAoConfig
+ from diffusers.hooks import apply_group_offloading
+ from torchao.quantization import Int8WeightOnlyConfig
+ from transformers import Qwen3VLForConditionalGeneration
+ from transformers import TorchAoConfig as TransformersTorchAoConfig
+
+ pipe = ModularPipeline.from_pretrained(str(snapshot))
+ pipe.update_components(
+ transformer=MiniMaxH3Transformer3DModel.from_pretrained(
+ str(snapshot), subfolder="transformer", dtype=torch.bfloat16,
+ quantization_config=TorchAoConfig(
+ Int8WeightOnlyConfig(version=2),
+ modules_to_not_convert=TRANSFORMER_KEEP_BF16,
+ ),
+ low_cpu_mem_usage=False,
+ ),
+ text_encoder=Qwen3VLForConditionalGeneration.from_pretrained(
+ str(snapshot), subfolder="text_encoder", dtype=torch.bfloat16,
+ quantization_config=TransformersTorchAoConfig(
+ Int8WeightOnlyConfig(version=2),
+ modules_to_not_convert=TEXT_ENCODER_KEEP_BF16,
+ ),
+ ),
+ )
+ pipe.load_components(workflow="fl2va", dtype=torch.bfloat16)
+
+ # version=2 int8 tensors are pinnable, which streamed offload needs, and
+ # freezing removes the one autograd path the quantized tensors cannot serve.
+ pipe.transformer.requires_grad_(False)
+ pipe.text_encoder.requires_grad_(False)
+
+ stream = profile == "int8-stream"
+ offload = dict(
+ onload_device=torch.device("cuda"),
+ offload_device=torch.device("cpu"),
+ use_stream=stream,
+ )
+ pipe.transformer.enable_group_offload(
+ offload_type="block_level", num_blocks_per_group=1, **offload
+ )
+ apply_group_offloading(pipe.text_encoder.model, offload_type="leaf_level", **offload)
+ if stream:
+ pipe.vae.to("cuda")
+ else:
+ # On a 12-16 GB card the video VAE no longer fits beside the streamed
+ # transformer blocks, so it is offloaded leaf-by-leaf as well.
+ apply_group_offloading(pipe.vae, offload_type="leaf_level", **offload)
+ pipe.audio_vae.to("cuda")
+ return pipe
+
+
+def keyframe_kwargs(images: list, anchors: list[str]) -> dict:
+ """Map PortOS's (image, anchor) pairs onto the blocks' two keyframe inputs."""
+ return {
+ {"first": "image", "last": "last_image"}[anchor]: image
+ for image, anchor in zip(images, anchors)
+ }
+
+
+def main() -> int:
+ args = parse_args()
+ validate_args(args)
+ # Read the keyframes first: everything below is ~60 HF cache lookups and a
+ # torch/diffusers 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. No-op on
+ # Windows, which has no process groups in this sense — the Node side kills
+ # by PID there.
+ if hasattr(os, "setpgid"):
+ try:
+ os.setpgid(0, 0)
+ except OSError:
+ pass
+
+ require_ffmpeg()
+
+ # Resolve the cache BEFORE importing torch. The lookups are pure
+ # huggingface_hub path arithmetic against a pinned commit — no network, no
+ # metadata fetch — so an undownloaded model reports "use Download in Video
+ # Gen" immediately instead of after a multi-second torch import.
+ log("STAGE:resolve-cache")
+ snapshot = resolve_cached_snapshot(args.model_repo, args.model_revision, args.repo_file)
+
+ import torch
+
+ emit_runtime_fingerprint(
+ "minimax_h3_cuda",
+ ["torch", "diffusers", "transformers", "torchao", "accelerate", "huggingface-hub"],
+ extra_versions={"cuda": getattr(torch.version, "cuda", None)},
+ )
+
+ profile = resolve_offload_profile(args.offload_profile)
+ log(f"STATUS:MiniMax H3 CUDA offload profile: {profile}")
+
+ log("STAGE:load-pipeline")
+ with heartbeat("minimax-h3-cuda-load"):
+ pipe = load_pipeline(snapshot, profile)
+
+ # No explicit step callback: a ModularPipeline validates its inputs by
+ # name against the workflow's declared set, and `callback_on_step_end` is
+ # not one of them. The denoise loop's own tqdm bar goes to stderr, which
+ # PortOS's line handler already parses into progress frames
+ # (`makeVideoGenLineHandler`'s `NN%|` branch) — same as every other runner
+ # that leaves progress to tqdm.
+ log("STAGE:inference")
+ with heartbeat("minimax-h3-cuda-inference"):
+ results = pipe(
+ prompt=args.prompt,
+ num_frames=args.num_frames,
+ height=args.height,
+ width=args.width,
+ num_inference_steps=args.steps,
+ # A CPU generator keeps the three documented draws (conditioning,
+ # video, audio) reproducible regardless of which device each
+ # component happens to be resident on under an offload profile.
+ generator=torch.Generator().manual_seed(args.seed),
+ output=["videos", "audio", "sampling_rate"],
+ **keyframe_kwargs(images, args.anchor),
+ )
+
+ output = Path(args.output)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ log("STAGE:mux")
+ from diffusers.utils.export_utils import encode_video
+
+ frames = results["videos"][0]
+ encode_video(
+ frames,
+ fps=FPS,
+ output_path=str(output),
+ audio=results["audio"][0],
+ audio_sample_rate=results["sampling_rate"],
+ )
+
+ if not output.is_file() or output.stat().st_size == 0:
+ raise RuntimeError(f"MiniMax H3 completed but did not write {output}.")
+ log(f"STATUS:MiniMax H3 saved {output.name} ({len(frames)} frames with stereo audio)")
+ emit_result(output)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/generate_minimax_h3_cuda.test.js b/scripts/generate_minimax_h3_cuda.test.js
new file mode 100644
index 0000000000..182f88832b
--- /dev/null
+++ b/scripts/generate_minimax_h3_cuda.test.js
@@ -0,0 +1,141 @@
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../server/lib/testHelper.js';
+
+const script = join(dirname(fileURLToPath(import.meta.url)), 'generate_minimax_h3_cuda.py');
+
+// Probe for an interpreter that actually RUNS rather than assuming a name. On
+// Windows a box with no Store-installed Python still has `python` on PATH as an
+// alias STUB: it exists, exits non-zero, and prints "Python was not found", so a
+// name-only choice passes here and then every case dies with an opaque "Command
+// failed". Null when there is genuinely none, so the suite skips.
+const pyBin = resolveTestPython();
+const runPython = (source) => execFileSync(pyBin, ['-c', source, script], {
+ encoding: 'utf8',
+});
+
+// Python on Windows writes CRLF, so splitting the output on newlines alone
+// leaves a trailing carriage return on every line but the last — and each
+// comparison below would then fail on that, not on anything the runner did.
+const lines = (output) => output.trim().split('\n').map((line) => line.trimEnd());
+
+// Import the runner as a module without executing main(). Every heavy import
+// (torch, diffusers, PIL) is deferred inside the function that needs it, which
+// is what makes this possible in a bare interpreter — the arg contract has to
+// be testable without a 144 GB runtime installed.
+const importRunner = [
+ 'import importlib.util, sys',
+ 'from pathlib import Path',
+ 'script = Path(sys.argv[1])',
+ 'spec = importlib.util.spec_from_file_location("generate_minimax_h3_cuda", script)',
+ 'runner = importlib.util.module_from_spec(spec)',
+ 'spec.loader.exec_module(runner)',
+].join('\n');
+
+// Drive validate_args through a real argparse Namespace so the test exercises
+// the same object main() builds, rather than a hand-rolled stand-in that could
+// silently omit a field the validator reads.
+const validate = (overrides) => {
+ const fields = {
+ fps: 24,
+ width: 1344,
+ height: 768,
+ num_frames: 124,
+ steps: 8,
+ image: [],
+ anchor: [],
+ repo_file: ['modular_model_index.json'],
+ ...overrides,
+ };
+ return runPython(`${importRunner}\n${[
+ 'import argparse, json',
+ `args = argparse.Namespace(**json.loads(${JSON.stringify(JSON.stringify(fields))}))`,
+ 'try:',
+ ' runner.validate_args(args)',
+ ' print("OK")',
+ 'except SystemExit as exc:',
+ ' print(f"REJECTED:{exc}")',
+ ].join('\n')}`).trim();
+};
+
+describe.skipIf(!pyBin)('generate_minimax_h3_cuda.py', () => {
+ it('accepts a legal request at both ends of the diffusers window', () => {
+ expect(validate({})).toBe('OK');
+ expect(validate({ num_frames: 345 })).toBe('OK');
+ });
+
+ it("enforces the diffusers 5-15s window, which is narrower than the MLX port's", () => {
+ // 107 (4.46s) and 362 (15.08s) are both legal 17n+5 grid points that the
+ // MLX runner accepts. diffusers snaps up to the grid and THEN requires the
+ // resulting duration in 5-15s, so both are out of range here. This is the
+ // one H3 constraint that genuinely differs between the two runners, which
+ // is why the frame grid is a per-entry fact rather than a shared constant.
+ expect(validate({ num_frames: 107 })).toMatch(/^REJECTED:.*5-15 seconds/);
+ expect(validate({ num_frames: 362 })).toMatch(/^REJECTED:.*5-15 seconds/);
+ });
+
+ it('refuses to run without a pinned component file list', () => {
+ // Without it the loaders would fall back to a repo-wide resolve against a
+ // ~498 GB repo carrying three layouts — not a recoverable default.
+ expect(validate({ repo_file: [] })).toMatch(/^REJECTED:.*--repo-file/);
+ });
+
+ it('maps anchors onto the diffusers keyframe input names, in packed order', () => {
+ const output = lines(runPython(`${importRunner}\n${[
+ 'kwargs = runner.keyframe_kwargs(["FIRST", "LAST"], ["first", "last"])',
+ 'print(",".join(f"{k}={v}" for k, v in kwargs.items()))',
+ 'print(runner.keyframe_kwargs(["ONLY"], ["last"]))',
+ 'print(runner.keyframe_kwargs([], []))',
+ ].join('\n')}`));
+ expect(output[0]).toBe('image=FIRST,last_image=LAST');
+ // A last-only request is legal in fl2va — "generate up to this frame".
+ expect(output[1]).toBe("{'last_image': 'ONLY'}");
+ expect(output[2]).toBe('{}');
+ });
+
+ it('sizes the offload recipe from VRAM, and lets an explicit profile win', () => {
+ const output = lines(runPython(`${importRunner}\n${[
+ 'import types',
+ 'fake = types.ModuleType("torch")',
+ 'fake.cuda = types.SimpleNamespace(',
+ ' is_available=lambda: True,',
+ ' get_device_properties=lambda i: types.SimpleNamespace(total_memory=int(TOTAL_GB * 1e9)),',
+ ')',
+ 'sys.modules["torch"] = fake',
+ 'for TOTAL_GB in (80, 32, 24, 16, 12):',
+ ' print(f"{TOTAL_GB}:{runner.resolve_offload_profile(\'auto\')}")',
+ 'TOTAL_GB = 12',
+ "print('pinned:' + runner.resolve_offload_profile('bf16'))",
+ ].join('\n')}`));
+ expect(output).toEqual([
+ '80:bf16',
+ '32:int8-stream',
+ '24:int8-stream',
+ '16:int8-lean',
+ '12:int8-lean',
+ // An explicit request always wins: the registry entry is shared across
+ // every install that syncs it and can't know the GPU on the other end,
+ // but a user who pins one knows their box better than the heuristic.
+ 'pinned:bf16',
+ ]);
+ });
+
+ it('refuses to run when no CUDA device is visible', () => {
+ // A CPU-only torch wheel installs cleanly on Windows and would otherwise
+ // just render unusably slowly instead of saying what is wrong.
+ const output = runPython(`${importRunner}\n${[
+ 'import types',
+ 'fake = types.ModuleType("torch")',
+ 'fake.cuda = types.SimpleNamespace(is_available=lambda: False)',
+ 'sys.modules["torch"] = fake',
+ 'try:',
+ " runner.resolve_offload_profile('auto')",
+ 'except RuntimeError as exc:',
+ ' print(exc)',
+ ].join('\n')}`);
+ expect(output).toContain('needs a visible NVIDIA device');
+ });
+
+});
diff --git a/scripts/migrations/242-minimax-h3-mlx-model.js b/scripts/migrations/242-minimax-h3-mlx-model.js
index e71c5f7422..e15a54b42b 100644
--- a/scripts/migrations/242-minimax-h3-mlx-model.js
+++ b/scripts/migrations/242-minimax-h3-mlx-model.js
@@ -21,6 +21,21 @@ const REFERENCE_PATH = join(
'..', '..', 'data.reference', 'media-models.json',
);
+// The built-in video model ids as of the release that introduced this
+// migration (commit ffac284f9), used for the `_shippedDefaults` bootstrap union
+// below. Frozen deliberately: this is a historical fact about what this
+// migration delivered, not a live view of the catalog, so it must never be
+// re-read from `data.reference/media-models.json`.
+const SHIPPED_AT_242 = Object.freeze({
+ macos: Object.freeze([
+ 'ltx2_unified', 'ltx23_unified', 'ltx23_distilled_q4', 'ltx23_dgrauet_q4',
+ 'ltx23_dgrauet_q8', 'minimax_h3_8bit', 'wan22_ti2v_5b', 'wan22_t2v_a14b',
+ 'wan22_i2v_a14b', 'wan22_t2v_a14b_lightning', 'wan22_i2v_a14b_lightning',
+ 'hunyuan_video',
+ ]),
+ windows: Object.freeze(['ltx_video']),
+});
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
const ids = (entries) => (Array.isArray(entries)
? entries.map((entry) => entry?.id).filter((id) => typeof id === 'string')
@@ -79,11 +94,20 @@ export default {
// mediaModels.js would use for a legacy registry. A partial [H3]-only
// snapshot would make every historically deleted default look new and
// silently repopulate the user's curated list on the next load.
+ //
+ // The union is against the id set THIS MIGRATION shipped with, pinned
+ // below — never against today's `data.reference`. Re-deriving it meant a
+ // model added to the catalog *after* this migration got recorded as
+ // "already shipped" the first time a legacy install ran it, and was then
+ // permanently suppressed: `appendNewlyShippedEntries` reads a recorded id
+ // as "the user deleted this", so the entry would never appear and no
+ // later migration could tell the difference. Adding a default must not
+ // retroactively change what this migration claims to have delivered.
const nextRoot = shippedRoot || {};
const nextVideo = shippedVideo || {};
- nextVideo.macos = bootstrapIds(macos, referenceMacos);
+ nextVideo.macos = bootstrapIds(macos, SHIPPED_AT_242.macos.map((id) => ({ id })));
if (!shippedVideo) {
- nextVideo.windows = bootstrapIds(config.video.windows, reference?.video?.windows);
+ nextVideo.windows = bootstrapIds(config.video.windows, SHIPPED_AT_242.windows.map((id) => ({ id })));
}
nextRoot.video = nextVideo;
config._shippedDefaults = nextRoot;
diff --git a/scripts/migrations/268-minimax-h3-cuda-model.js b/scripts/migrations/268-minimax-h3-cuda-model.js
new file mode 100644
index 0000000000..165abfe0cc
--- /dev/null
+++ b/scripts/migrations/268-minimax-h3-cuda-model.js
@@ -0,0 +1,87 @@
+/**
+ * Add the never-before-shipped MiniMax H3 CUDA profile to existing Windows
+ * registries. Fresh installs receive it from data.reference/media-models.json.
+ *
+ * Same reason migration 242 exists for the macOS MLX profile: a registry whose
+ * `_shippedDefaults.video.windows` snapshot predates this entry has no record
+ * of it, and `appendNewlyShippedEntries` in mediaModels.js reads a recorded id
+ * as "the user deleted this". That mechanism delivers the new row correctly on
+ * its own — this migration only covers the install whose snapshot was written
+ * by 242's legacy bootstrap, which unions the user's ids with the built-in set.
+ *
+ * (242 now pins that union to the ids IT shipped with rather than re-reading
+ * `data.reference`, so it can no longer record this entry as already-shipped.
+ * This migration is the belt to that braces: it runs after 242 and appends the
+ * row when nothing has recorded it.)
+ */
+
+import { readFile } from 'fs/promises';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+
+const REL_PATH = 'data/media-models.json';
+const CUDA_ID = 'minimax_h3_cuda';
+const REFERENCE_PATH = join(
+ dirname(fileURLToPath(import.meta.url)),
+ '..', '..', 'data.reference', 'media-models.json',
+);
+
+const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+
+const parseJson = (raw, label) => {
+ try {
+ return JSON.parse(raw);
+ } catch (err) {
+ throw new Error(`Cannot migrate ${label}: invalid JSON (${err.message})`, { cause: err });
+ }
+};
+
+export default {
+ async up({ rootDir }) {
+ const path = join(rootDir, REL_PATH);
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return;
+
+ const config = parseJson(raw, REL_PATH);
+ const windows = Array.isArray(config?.video?.windows) ? config.video.windows : null;
+ if (!windows) return;
+
+ const reference = parseJson(await readFile(REFERENCE_PATH, 'utf-8'), 'data.reference/media-models.json');
+ const referenceWindows = Array.isArray(reference?.video?.windows) ? reference.video.windows : [];
+ const cuda = referenceWindows.find((entry) => entry?.id === CUDA_ID);
+ if (!cuda) throw new Error(`Cannot migrate ${REL_PATH}: shipped ${CUDA_ID} reference is missing`);
+
+ const shippedWindows = isObject(config._shippedDefaults?.video)
+ && Array.isArray(config._shippedDefaults.video.windows)
+ ? config._shippedDefaults.video.windows
+ : null;
+ const wasAlreadyShipped = shippedWindows?.includes(CUDA_ID) === true;
+ const existing = windows.find((entry) => entry?.id === CUDA_ID);
+ let changed = false;
+
+ // A recorded-but-missing id is a user deletion and stays deleted. An
+ // existing row may be user-customized and is never overwritten.
+ if (!existing && !wasAlreadyShipped) {
+ windows.push(structuredClone(cuda));
+ changed = true;
+ }
+
+ // Record it so the load-time appender doesn't offer it a second time after
+ // a deliberate deletion. A registry with no snapshot key at all is left
+ // alone — 242 owns creating it, and writing a partial one here would make
+ // every historically deleted default look new on the next load.
+ if (shippedWindows && windows.some((entry) => entry?.id === CUDA_ID) && !wasAlreadyShipped) {
+ shippedWindows.push(CUDA_ID);
+ changed = true;
+ }
+
+ if (changed) {
+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);
+ console.log(`📝 ${REL_PATH}: added the MiniMax H3 CUDA video profile`);
+ }
+ },
+};
diff --git a/scripts/migrations/268-minimax-h3-cuda-model.test.js b/scripts/migrations/268-minimax-h3-cuda-model.test.js
new file mode 100644
index 0000000000..35241da96b
--- /dev/null
+++ b/scripts/migrations/268-minimax-h3-cuda-model.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration242 from './242-minimax-h3-mlx-model.js';
+import migration from './268-minimax-h3-cuda-model.js';
+
+const CUDA_ID = 'minimax_h3_cuda';
+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+const legacyRegistry = () => ({
+ video: {
+ macos: [{ id: 'ltx23_distilled_q4', name: 'My tuned default', steps: 17 }],
+ windows: [{ id: 'ltx_video', name: 'LTX Windows' }],
+ defaultMacos: 'ltx23_distilled_q4',
+ defaultWindows: 'ltx_video',
+ },
+ image: [{ id: 'my-image', name: 'My image model' }],
+});
+
+describe('migration 268 — MiniMax H3 CUDA model', () => {
+ let rootDir;
+ let path;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-268-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ path = join(rootDir, 'data', 'media-models.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('adds and records the CUDA profile when a snapshot registry has not received it', async () => {
+ const config = legacyRegistry();
+ config._shippedDefaults = { video: { macos: ['ltx23_distilled_q4'], windows: ['ltx_video'] } };
+ writeJson(path, config);
+ await migration.up({ rootDir });
+
+ const got = readJson(path);
+ const cuda = got.video.windows.find((entry) => entry.id === CUDA_ID);
+ expect(cuda).toMatchObject({
+ repo: 'MiniMaxAI/MiniMax-H3',
+ revision: '42ed227ee7df40d41602854ae760620d6eb651fe',
+ runtime: 'minimax_h3_cuda',
+ termsGate: { id: 'minimax-h3-community-license-2026-08-02' },
+ });
+ expect(cuda.repoFiles.length).toBeGreaterThan(0);
+ expect(got._shippedDefaults.video.windows).toContain(CUDA_ID);
+ // The user's own rows and the rest of the registry are untouched.
+ expect(got.video.windows[0]).toEqual(config.video.windows[0]);
+ expect(got.video.macos).toEqual(config.video.macos);
+ expect(got.image).toEqual(config.image);
+ });
+
+ it('is idempotent', async () => {
+ const config = legacyRegistry();
+ config._shippedDefaults = { video: { macos: [], windows: ['ltx_video'] } };
+ writeJson(path, config);
+ await migration.up({ rootDir });
+ await migration.up({ rootDir });
+ const got = readJson(path);
+ expect(got.video.windows.filter((entry) => entry.id === CUDA_ID)).toHaveLength(1);
+ expect(got._shippedDefaults.video.windows.filter((id) => id === CUDA_ID)).toHaveLength(1);
+ });
+
+ it('respects a deliberate deletion — a recorded-but-absent id stays absent', async () => {
+ const config = legacyRegistry();
+ config._shippedDefaults = { video: { macos: [], windows: ['ltx_video', CUDA_ID] } };
+ writeJson(path, config);
+ await migration.up({ rootDir });
+ const got = readJson(path);
+ expect(got.video.windows.some((entry) => entry.id === CUDA_ID)).toBe(false);
+ });
+
+ it('never overwrites a user-customized row', async () => {
+ const config = legacyRegistry();
+ config.video.windows.push({ id: CUDA_ID, name: 'My tuned H3 CUDA', steps: 4 });
+ config._shippedDefaults = { video: { macos: [], windows: ['ltx_video'] } };
+ writeJson(path, config);
+ await migration.up({ rootDir });
+ const got = readJson(path);
+ const rows = got.video.windows.filter((entry) => entry.id === CUDA_ID);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toEqual({ id: CUDA_ID, name: 'My tuned H3 CUDA', steps: 4 });
+ });
+
+ it('leaves a registry with no snapshot key to 242, which owns creating it', async () => {
+ writeJson(path, legacyRegistry());
+ await migration.up({ rootDir });
+ const got = readJson(path);
+ expect(got._shippedDefaults).toBeUndefined();
+ expect(got.video.windows.some((entry) => entry.id === CUDA_ID)).toBe(true);
+ });
+
+ it('is not suppressed by 242 running first on a pre-snapshot registry', async () => {
+ // The regression this pair exists for: 242's bootstrap used to union the
+ // user's ids with TODAY's data.reference, so it recorded this entry as
+ // already-shipped without ever adding it — and `appendNewlyShippedEntries`
+ // reads a recorded id as a user deletion, suppressing the row forever.
+ writeJson(path, legacyRegistry());
+ await migration242.up({ rootDir });
+ const afterMlx = readJson(path);
+ expect(afterMlx._shippedDefaults.video.windows).not.toContain(CUDA_ID);
+
+ await migration.up({ rootDir });
+ const got = readJson(path);
+ expect(got.video.windows.some((entry) => entry.id === CUDA_ID)).toBe(true);
+ expect(got._shippedDefaults.video.windows).toContain(CUDA_ID);
+ });
+
+ it('does nothing when the registry file is absent', async () => {
+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();
+ });
+});
diff --git a/scripts/requirements-minimax-h3-cuda.txt b/scripts/requirements-minimax-h3-cuda.txt
new file mode 100644
index 0000000000..8432110b2f
--- /dev/null
+++ b/scripts/requirements-minimax-h3-cuda.txt
@@ -0,0 +1,41 @@
+# MiniMax H3 CUDA runtime — direct dependency pins for ~/.portos/minimax-h3-cuda/.venv.
+#
+# NOT a fully-resolved lock, unlike its MLX sibling
+# (requirements-minimax-h3-mlx.lock.txt). `torch` is installed separately and
+# from a different index depending on the host — PyTorch's own CUDA wheel index
+# on Windows, plain PyPI elsewhere (where the default wheel already bundles
+# CUDA) — so one resolved transitive lock cannot describe every install. Pinning
+# the direct dependencies exactly is the strongest guarantee that holds for all
+# of them.
+#
+# `torch` is deliberately absent for that reason — setup-image-video.sh installs
+# it first, from the host's correct index (see WIN_TORCH_CUDA_INDEX in
+# server/lib/pythonSetup.js, and PORTOS_TORCH_CUDA_INDEX to override).
+
+# diffusers' MiniMax-H3 integration (PR #14355) merged to main on 2026-08-05 and
+# is NOT in any tagged release — v0.39.0 predates it. Pinned to a main commit
+# until a release ships it; when one does, swap this for the `==` version and
+# drop the git URL. The runtime's import probe checks for
+# `MiniMaxH3Transformer3DModel` specifically, so an install that silently
+# resolved to a release without the integration reports as not-ready rather than
+# failing deep inside a render.
+diffusers @ git+https://github.com/huggingface/diffusers.git@2da7040be1a2e5f2fcbc8b985083342a308f5a86
+
+# int8 weight-only quantization. This is what makes H3 fit a consumer card at
+# all: the bf16 transformer + Qwen3-VL conditioner are 133 GB together, and
+# `Int8WeightOnlyConfig(version=2)` is specifically required because only
+# version=2 tensors are pinnable, which streamed group offload needs.
+torchao==0.18.0
+
+# Qwen3VLForConditionalGeneration + the transformers-side TorchAoConfig.
+transformers==5.15.0
+accelerate==1.14.0
+huggingface_hub==1.27.0
+
+# PyAV backs diffusers' encode_video() muxing of the joint video + audio output.
+av==18.1.0
+
+# Keyframe decode (image / FFLF conditioning) and the frame arrays encode_video
+# writes.
+pillow==12.3.0
+numpy==2.5.2
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index a085fcfbc8..cfa4d126bd 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -10,7 +10,8 @@
# PORTOS_DATA Path to PortOS data dir (default: ./data, resolved from $REPO_ROOT)
# INSTALL_VIDEO '1' to also install mlx_video for LTX video generation (default: 1 on macOS, 0 on Windows)
# INSTALL_LTX2 '1' to also clone + uv-sync dgrauet/ltx-2-mlx at ~/.portos/ltx-2-mlx for the second-gen LTX-2.3 pipeline (proper keyframe interpolation, true video extend, audio-to-video). Default: 0; opt in with INSTALL_LTX2=1.
-# INSTALL_MINIMAX_H3 '1' to install the pinned MiniMax H3 MLX runtime at ~/.portos/minimax-h3-mlx. Weights remain a separate explicit Video Gen download. Default: 0.
+# INSTALL_MINIMAX_H3 '1' to install the pinned MiniMax H3 MLX runtime at ~/.portos/minimax-h3-mlx (Apple Silicon). Weights remain a separate explicit Video Gen download. Default: 0.
+# INSTALL_MINIMAX_H3_CUDA '1' to install the MiniMax H3 CUDA runtime at ~/.portos/minimax-h3-cuda (Windows + NVIDIA), via diffusers' MiniMaxH3ModularPipeline. Weights remain a separate explicit Video Gen download (~144 GB). Default: 0.
# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)
# INSTALL_MUSICGEN '1' to bootstrap a venv at ~/.portos/venv-musicgen + clone ml-explore/mlx-examples to ~/.portos/mlx-examples for local MusicGen (MLX) background-music generation (pipeline audio stage). Default: 0; opt in with INSTALL_MUSICGEN=1 (macOS / Apple Silicon only).
# MLX_EXAMPLES_PIN commit SHA of ml-explore/mlx-examples to check out for MusicGen (default: main).
@@ -27,6 +28,9 @@ PORTOS_DATA="${PORTOS_DATA:-${REPO_ROOT}/data}"
have() { command -v "$1" >/dev/null 2>&1; }
is_macos() { [[ "$(uname -s)" == "Darwin" ]]; }
+# Git-bash / MSYS / Cygwin all report a prefixed uname; PortOS runs the
+# in-app installer through git-bash on Windows, so match all three.
+is_windows() { case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) return 0;; *) return 1;; esac; }
# Check out a pin (a commit SHA, tag, or branch name) in an already-fetched
# clone. A bare `git checkout <branch>` lands on the *local* branch created at
@@ -54,7 +58,7 @@ mkdir -p "${PORTOS_DATA}/videos"
mkdir -p "${PORTOS_DATA}/video-thumbnails"
# When the user only wants a specific BYOV runtime (set via INSTALL_LTX2 /
-# INSTALL_WAN22 / INSTALL_HUNYUAN / INSTALL_MINIMAX_H3 — or one of the self-contained MUSIC venvs
+# INSTALL_WAN22 / INSTALL_HUNYUAN / INSTALL_MINIMAX_H3 / INSTALL_MINIMAX_H3_CUDA — or one of the self-contained MUSIC venvs
# INSTALL_MUSICGEN / INSTALL_AUDIOLDM2 / INSTALL_ACESTEP — typically from the
# in-app installer), skip the mflux + legacy mlx_video preamble. Those
# bring-your-own-venv runtimes are self-contained and don't depend on mflux;
@@ -63,8 +67,14 @@ mkdir -p "${PORTOS_DATA}/video-thumbnails"
# install ever starts — which on Linux/CPU/CUDA blocks the advertised
# `INSTALL_ACESTEP=1 bash …` path. A bare `bash setup-image-video.sh` still
# installs mflux as before.
-ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_MINIMAX_MUSIC3:-0}${INSTALL_MUSCRIPTOR:-0}"
-if [[ "$ANY_BYOV" == "00000000" ]]; then
+ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MINIMAX_H3_CUDA:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_MINIMAX_MUSIC3:-0}${INSTALL_MUSCRIPTOR:-0}"
+# "no BYOV runtime was requested" = the concatenation contains no non-zero
+# character. Matching a literal string of zeros instead made this a counting
+# exercise that the string and the variable list had to agree on — and they had
+# already fallen out of step, so a bare `bash setup-image-video.sh` was taking
+# the BYOV-only branch and skipping the mflux + flux2 preamble it advertises.
+# This form cannot drift as runtimes are added.
+if [[ "$ANY_BYOV" != *[!0]* ]]; then
DEFAULT_INSTALL_MFLUX=1
DEFAULT_INSTALL_VIDEO=$(is_macos && echo 1 || echo 0)
DEFAULT_INSTALL_FLUX2=$(is_macos && echo 1 || echo 0)
@@ -376,6 +386,80 @@ if [[ "$INSTALL_MINIMAX_H3" == "1" ]]; then
echo " Weights remain uninstalled until you accept the model terms and choose Download in Video Gen."
fi
+INSTALL_MINIMAX_H3_CUDA="${INSTALL_MINIMAX_H3_CUDA:-0}"
+if [[ "$INSTALL_MINIMAX_H3_CUDA" == "1" ]]; then
+ # MiniMax H3 on NVIDIA, through diffusers' MiniMaxH3ModularPipeline. Unlike
+ # the MLX sibling above there is no source checkout to pin — everything this
+ # runtime executes is an installed distribution, so the pin is the exact
+ # `==` set in requirements-minimax-h3-cuda.txt. Reached only from the
+ # explicit runtime Install / Repair action, never from PortOS boot.
+ if is_macos; then
+ echo "❌ MiniMax H3 CUDA needs an NVIDIA GPU. On Apple Silicon use INSTALL_MINIMAX_H3=1 (the MLX port) instead." >&2
+ exit 1
+ fi
+ # The venv provisions fine on Linux, but PortOS only surfaces this model on
+ # Windows: the catalog picks video.windows[] vs video.macos[] off IS_WIN, so
+ # a Linux install is served the macOS/MLX list and would never see the row.
+ # Warn rather than refuse — the install is harmless and ready for the day
+ # that axis widens (tracked in PLAN.md).
+ if ! is_windows; then
+ echo "⚠️ MiniMax H3 CUDA is only surfaced in Video Gen on Windows today; this venv will install but no model row will appear." >&2
+ fi
+ # diffusers is pinned to a git commit until a release carries the MiniMax-H3
+ # integration (see the note in requirements-minimax-h3-cuda.txt), so pip needs
+ # git to build that wheel. Say so up front rather than failing several minutes
+ # into a torch download.
+ if ! have git; then
+ echo "❌ INSTALL_MINIMAX_H3_CUDA=1 requires git (the diffusers pin is a git commit)." >&2
+ exit 1
+ fi
+
+ MINIMAX_H3_CUDA_DIR="${HOME}/.portos/minimax-h3-cuda"
+ MINIMAX_H3_CUDA_VENV="${MINIMAX_H3_CUDA_DIR}/.venv"
+ MINIMAX_H3_CUDA_REQS="${SCRIPT_DIR}/requirements-minimax-h3-cuda.txt"
+ mkdir -p "${MINIMAX_H3_CUDA_DIR}"
+ # A Windows venv puts the interpreter under Scripts/, a POSIX one under bin/.
+ # Probe for either rather than branching on `uname`, so an MSYS/Cygwin bash on
+ # Windows (which is what the in-app installer runs) resolves correctly.
+ MINIMAX_H3_CUDA_PY="${MINIMAX_H3_CUDA_VENV}/bin/python3"
+ if [[ ! -x "$MINIMAX_H3_CUDA_PY" && ! -x "${MINIMAX_H3_CUDA_VENV}/Scripts/python.exe" ]]; then
+ echo "📦 Creating MiniMax H3 CUDA venv..."
+ "$PYTHON_BIN" -m venv "$MINIMAX_H3_CUDA_VENV"
+ fi
+ [[ -x "$MINIMAX_H3_CUDA_PY" ]] || MINIMAX_H3_CUDA_PY="${MINIMAX_H3_CUDA_VENV}/Scripts/python.exe"
+
+ "$MINIMAX_H3_CUDA_PY" -m pip install --disable-pip-version-check --upgrade pip wheel setuptools
+ # torch comes from PyTorch's own CUDA index on Windows — the default PyPI
+ # Windows wheel is CPU-only, which on a 33B model is not "slower" but
+ # unusable. Linux's PyPI torch already bundles CUDA, so it needs no swap.
+ # Mirrors WIN_TORCH_CUDA_INDEX in server/lib/pythonSetup.js.
+ MINIMAX_H3_TORCH_INDEX="${PORTOS_TORCH_CUDA_INDEX:-https://download.pytorch.org/whl/cu126}"
+ if is_windows; then
+ echo "📦 Installing CUDA torch from ${MINIMAX_H3_TORCH_INDEX}..."
+ "$MINIMAX_H3_CUDA_PY" -m pip install --upgrade --index-url "$MINIMAX_H3_TORCH_INDEX" torch
+ else
+ echo "📦 Installing torch..."
+ "$MINIMAX_H3_CUDA_PY" -m pip install --upgrade torch
+ fi
+ echo "📦 Installing pinned MiniMax H3 CUDA packages..."
+ "$MINIMAX_H3_CUDA_PY" -m pip install --upgrade --progress-bar on -r "$MINIMAX_H3_CUDA_REQS"
+
+ # Three separate ways this install can look complete and not be: a CPU-only
+ # torch, a diffusers without the H3 integration, or a missing torchao. Check
+ # all three here so the failure names itself, instead of surfacing hours later
+ # as an ImportError inside a render. Same assertions as the runtime's
+ # `importProbe` in server/services/videoGen/runtimes.js.
+ if ! "$MINIMAX_H3_CUDA_PY" -c "import torch; from diffusers import MiniMaxH3Transformer3DModel; from diffusers.modular_pipelines.minimax_h3 import MiniMaxH3ImageReference; import torchao; assert torch.cuda.is_available(), 'no CUDA device'"; then
+ echo "❌ MiniMax H3 CUDA installed but its readiness check failed (see the error above)." >&2
+ echo " A 'no CUDA device' assertion means torch cannot see your GPU; anything else means the" >&2
+ echo " diffusers pin does not carry the MiniMax-H3 integration. Use Repair from the Video Gen runtime panel." >&2
+ exit 1
+ fi
+ echo "✅ MiniMax H3 CUDA runtime ready: ${MINIMAX_H3_CUDA_PY}"
+ echo " Weights remain uninstalled until you accept the model terms and choose Download in Video Gen."
+ echo " That download is ~144 GB, and rendering needs ~24 GB VRAM plus ~75 GB of system RAM for offloaded weights."
+fi
+
INSTALL_HUNYUAN="${INSTALL_HUNYUAN:-0}"
if [[ "$INSTALL_HUNYUAN" == "1" ]]; then
# gaurav-nelson/HunyuanVideo_MLX — community MLX port of Tencent's
diff --git a/server/lib/README.md b/server/lib/README.md
index 6f42e2dd02..99d2138ee1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -112,11 +112,11 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptStageCallSites.generated.json` | Generated `stageKey -> [server source paths]` index of every prompt stage `server/` names by literal key (plus interpolated-prefix stages like `pipeline-panel-${id}`). Regenerate with `node scripts/generate-prompt-stage-call-sites.js`; `scripts/generate-prompt-stage-call-sites.test.js` fails on drift. Never hand-edit. |
| `promptTemplate.js` | Mustache-flavored, dot-notation-aware prompt template engine. |
| `promptPartials.js` | Mustache-style partial expansion. |
-| `mediaModels.js` | Single source of truth for image/video model metadata. |
+| `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |
| `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. |
| `videoDisclosure.js` | Video Gen provenance/licensing + backend policy-scope facts (#3674). `VIDEO_MODEL_DISCLOSURES` maps each shipped video model id to `{ shippedRepo, disclosure }` (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. `applyVideoDisclosures(list)` is the load-time backfill (twin of migration 237) with the same preservation guards: an existing `disclosure` key wins, a custom id is skipped, and a `repo` pointed at a fork keeps Unknown. `VIDEO_BACKEND_DISCLOSURES` / `videoBackendDisclosure(id)` state where inference runs (`execution: local or hosted`) and whose policy applies — execution facts only, never a restrictiveness ranking. |
| `videoFinishProfiles.js` | Draft → delivery ("Finish") relationships between video models (#3696). `VIDEO_FINISH_PROFILES` declares each fast draft entry id → `{ shippedRepo, finishModelId }`, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. `applyVideoFinishProfiles(list)` is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked `repo` skipped); `validateFinishProfileGraph(list)` returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and `sanitizeFinishProfiles(list)` warns + strips them at load so a typo can never surface a Finish button targeting nothing. `finishTargetForModel(model, availableModels)` resolves the delivery entry scoped to what this install can run. |
-| `videoModeProfiles.js` | The shipped `supportedModes` fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ `runtime === '…'` comparisons. `VIDEO_RUNTIME_MODES` maps each runtime to the base semantic modes its helper's argv can actually render (`mlx_video`/`ltx2` text+image+fflf+extend, `wan22` text+image, `minimax_h3` text+image+fflf — also the mode ceiling in `videoGen/modeContract.js` — `hunyuan` text only, replacing the legacy unread `mode: 't2v'` field); `VIDEO_BASE_MODES` is the fallback for an unknown (user-added or peer-synced) runtime, deliberately the full base set so a custom model doesn't vanish from every picker. `resolveVideoSupportedModes(entry)` (declared non-empty list always wins) and `applyVideoSupportedModes(list)` — the read-time decoration `mediaModels.js#getVideoModels` applies, so the derived list never lands in `data/media-models.json` where it would read back as a *declared* list no later correction could reach. a2v and the IC-LoRA remix ids are NOT enumerated here: they're ltx2 pipeline capabilities, gated by runtime (`A2V_REQUIRES_LTX2` / `IC_LORA_REQUIRES_LTX2`). |
+| `videoModeProfiles.js` | The shipped `supportedModes` fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ `runtime === '…'` comparisons. `VIDEO_RUNTIME_MODES` maps each runtime to the base semantic modes its helper's argv can actually render (`mlx_video`/`ltx2` text+image+fflf+extend, `wan22` text+image, `minimax_h3` / `minimax_h3_cuda` text+image+fflf off one shared array — also the mode ceiling in `videoGen/modeContract.js` — `hunyuan` text only, replacing the legacy unread `mode: 't2v'` field); `VIDEO_BASE_MODES` is the fallback for an unknown (user-added or peer-synced) runtime, deliberately the full base set so a custom model doesn't vanish from every picker. `resolveVideoSupportedModes(entry)` (declared non-empty list always wins) and `applyVideoSupportedModes(list)` — the read-time decoration `mediaModels.js#getVideoModels` applies, so the derived list never lands in `data/media-models.json` where it would read back as a *declared* list no later correction could reach. a2v and the IC-LoRA remix ids are NOT enumerated here: they're ltx2 pipeline capabilities, gated by runtime (`A2V_REQUIRES_LTX2` / `IC_LORA_REQUIRES_LTX2`). |
| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision/file, in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. |
| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`) plus reasoning-effort helpers for the claude/codex/agy CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, and `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`) plus codex startup-arg helpers (`CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal). |
| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |
@@ -134,7 +134,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (`--print`, implies `--afk`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |
-| `runners.js` | Image-runner family constants. |
+| `runners.js` | Image-runner family constants (`RUNNER_FAMILIES`, `loraCompatKey`), the separate `VIDEO_LORA_FAMILIES` + `videoLoraFamily` used by the video LoRA picker, and `isMiniMaxH3Runtime` / `MINIMAX_H3_RUNTIMES` — the predicate every gate asserting a MiniMax H3 model fact (24 fps, joint A/V, CFG-distilled, the 17n+5 grid) must use so the MLX and CUDA runtimes cannot drift apart. Mirrored to `client/src/lib/runnerFamilies.js`. |
| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index b694701346..a030b6d78b 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -12,12 +12,22 @@
* Models may also declare `defaultWidth` / `defaultHeight`,
* `resolutionStep`, and `resolutionOptions[]` when their native canvas
* differs from the shared Video Gen presets.
+ * `repoFiles[]` (optional) narrows the model's OWN `repo` to an explicit
+ * list of repo-relative POSIX filenames, the way `requiredWeights[].files`
+ * already does for a secondary repo. Absent means "snapshot the whole
+ * repo", which is right for a repo that holds exactly one model. Declare
+ * it when the repo is an AGGREGATE holding more than the runner loads —
+ * `MiniMaxAI/MiniMax-H3` ships three layouts totalling ~498 GB where the
+ * CUDA runner needs ~144 GB of them — since the download, cache-status,
+ * integrity-verify and repair paths all fan out from the same
+ * `modelDownloadTargets()` in routes/videoGen.js and would otherwise pull
+ * and checksum the lot.
* `disclosure` is optional provenance/licensing metadata (issue #3674):
* { modelCardUrl?, weightsLicense?: { name, url }, runtimeLicense?: { name, url },
* estimatedDownloadGb?, reviewedAt? }. Every key is optional and an
* absent key means "not established" — the UI renders it as Unknown
* rather than guessing. Canonical fields (repo/revision/runtime/memoryGb/
- * supportedModes/requiredWeights) are NOT duplicated inside it. Shipped
+ * supportedModes/requiredWeights/repoFiles) are NOT duplicated inside it. Shipped
* values live in lib/videoDisclosure.js and are backfilled at load.
* `finishModelId` (optional, issue #3696) names the delivery model a
* fast draft entry finishes into — declared in lib/videoFinishProfiles.js,
@@ -54,11 +64,13 @@ const IS_WIN = process.platform === 'win32';
// contract. The load-time half is essential because route imports can cache the
// registry before bootstrap migrations run; a later registry edit would
// otherwise persist that stale object over the migrated file in the same boot.
-export const MINIMAX_H3_OUTPUT_PROFILE = Object.freeze({
- id: 'minimax_h3_8bit',
- shippedRepo: 'pipenetwork/MiniMax-H3-MLX-8bit',
- oldFrameOptions: Object.freeze([124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362]),
- frameOptions: Object.freeze([107, 124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362]),
+// MiniMax H3's canvas contract — a property of the CHECKPOINT, so it is
+// identical on the MLX port and the diffusers CUDA path. H3-Base was trained on
+// a native 768px short edge; its canvas resolver caps area at 768x1344 and
+// rounds each edge to 32px, and these are the exact outputs for the aspect
+// ratios MiniMax documents. Both model entries spread this rather than restating
+// it — `mediaModels.test.js` asserts they stay identical.
+export const MINIMAX_H3_CANVAS = Object.freeze({
defaultWidth: 1344,
defaultHeight: 768,
resolutionStep: 32,
@@ -72,6 +84,87 @@ export const MINIMAX_H3_OUTPUT_PROFILE = Object.freeze({
]),
});
+// The MLX entry's output profile: the shared canvas above PLUS the upgrade
+// machinery migration 267 and `upgradeMiniMaxH3OutputControls` key off (the id,
+// the repo it was checked against, and the frame list it supersedes). That
+// upgrade half is specific to this one registry row, which is why the canvas is
+// factored out rather than left tangled with it.
+export const MINIMAX_H3_OUTPUT_PROFILE = Object.freeze({
+ id: 'minimax_h3_8bit',
+ shippedRepo: 'pipenetwork/MiniMax-H3-MLX-8bit',
+ oldFrameOptions: Object.freeze([124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362]),
+ frameOptions: Object.freeze([107, 124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362]),
+ ...MINIMAX_H3_CANVAS,
+});
+
+// Expand one diffusers sharded-component file set. Written out rather than
+// listed literally because these are 14- and 3-way shards whose names differ
+// only by index — a hand-typed list is 30+ near-identical lines in which a
+// single wrong digit is invisible in review and surfaces only as a failed
+// cache resolve mid-render.
+const shardFiles = (dir, stem, count) => Array.from(
+ { length: count },
+ (_, i) => `${dir}/${stem}-${String(i + 1).padStart(5, '0')}-of-${String(count).padStart(5, '0')}.safetensors`,
+);
+
+// MiniMax H3 on CUDA loads through diffusers' `MiniMaxH3ModularPipeline`, whose
+// `fl2va` workflow reads the `transformer/` partition plus the shared
+// conditioner, VAEs, tokenizers and schedulers.
+//
+// This MUST stay an explicit file list rather than a repo snapshot.
+// `MiniMaxAI/MiniMax-H3` is ~498 GB: it ships the diffusers layout enumerated
+// here (~144 GB), the `transformer_ref/` partition for the `ref2va` workflow
+// PortOS does not expose (~66 GB), and the ORIGINAL non-diffusers `FL2VA/` +
+// `Ref2VA/` layouts (~144 GB each) that the MLX port consumes. A snapshot would
+// pull 3.5x what the render path can use.
+const MINIMAX_H3_CUDA_REPO_FILES = Object.freeze([
+ 'LICENSE',
+ 'modular_model_index.json',
+ 'transformer/config.json',
+ 'transformer/diffusion_pytorch_model.safetensors.index.json',
+ ...shardFiles('transformer', 'diffusion_pytorch_model', 14),
+ 'text_encoder/config.json',
+ 'text_encoder/model.safetensors.index.json',
+ ...shardFiles('text_encoder', 'model', 14),
+ 'text_encoder/chat_template.json',
+ 'text_encoder/merges.txt',
+ 'text_encoder/preprocessor_config.json',
+ 'text_encoder/tokenizer.json',
+ 'text_encoder/tokenizer_config.json',
+ 'text_encoder/video_preprocessor_config.json',
+ 'text_encoder/vocab.json',
+ 'vae/config.json',
+ 'vae/diffusion_pytorch_model.safetensors.index.json',
+ ...shardFiles('vae', 'diffusion_pytorch_model', 3),
+ 'audio_vae/config.json',
+ 'audio_vae/diffusion_pytorch_model.safetensors',
+ // The Qwen3-VL processor/tokenizer pair the keyframe (image / FFLF) path
+ // runs conditioning images through. ~20 MB, so it rides along rather than
+ // becoming a second opt-in pull the way a multi-GB component would.
+ 'processor/chat_template.json',
+ 'processor/merges.txt',
+ 'processor/preprocessor_config.json',
+ 'processor/tokenizer.json',
+ 'processor/tokenizer_config.json',
+ 'processor/video_preprocessor_config.json',
+ 'processor/vocab.json',
+ 'tokenizer/merges.txt',
+ 'tokenizer/tokenizer.json',
+ 'tokenizer/tokenizer_config.json',
+ 'tokenizer/vocab.json',
+ 'scheduler/scheduler_config.json',
+ 'audio_scheduler/scheduler_config.json',
+]);
+
+// The diffusers integration's duration window, which is NARROWER than the MLX
+// port's at both ends: frames are snapped up to the next 17n+5 and the RESULTING
+// duration must land in 5-15 s, so 107 (4.46 s) is under the floor and 362
+// (15.08 s) is over the ceiling. Mirrored by MIN_FRAMES / MAX_FRAMES in
+// scripts/generate_minimax_h3_cuda.py, which rejects the same values.
+const MINIMAX_H3_CUDA_FRAME_OPTIONS = Object.freeze([
+ 124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345,
+]);
+
const sameValues = (left, right) => (
Array.isArray(left)
&& left.length === right.length
@@ -153,13 +246,9 @@ const DEFAULT_REGISTRY = {
defaultFrames: 124,
frameOptions: [...MINIMAX_H3_OUTPUT_PROFILE.frameOptions],
fpsOptions: [24],
- // H3-Base was trained on a native 768px short edge. Its canvas resolver
- // caps area at 768x1344 and rounds each edge to 32px; these are the
- // exact outputs for the aspect ratios MiniMax documents.
- defaultWidth: MINIMAX_H3_OUTPUT_PROFILE.defaultWidth,
- defaultHeight: MINIMAX_H3_OUTPUT_PROFILE.defaultHeight,
- resolutionStep: MINIMAX_H3_OUTPUT_PROFILE.resolutionStep,
- resolutionOptions: MINIMAX_H3_OUTPUT_PROFILE.resolutionOptions.map((preset) => ({ ...preset })),
+ // The checkpoint's canvas contract, shared verbatim with the CUDA entry.
+ ...MINIMAX_H3_CANVAS,
+ resolutionOptions: MINIMAX_H3_CANVAS.resolutionOptions.map((preset) => ({ ...preset })),
memoryGb: 128,
steps: 8,
guidance: 0,
@@ -340,6 +429,40 @@ const DEFAULT_REGISTRY = {
])),
windows: applyVideoFinishProfiles(applyVideoDisclosures([
{ id: 'ltx_video', name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', runtime: 'mlx_video', steps: 25, guidance: 3.0 },
+ // MiniMax H3 on NVIDIA, through diffusers' MiniMaxH3ModularPipeline —
+ // the same joint video+audio model the macOS list runs on MLX, so it
+ // shares H3's canvas grid, its fixed 24 fps, its locked CFG-distilled
+ // sampler and the same license gate. Generation is cache-only: PortOS
+ // owns the explicit file-list download (see MINIMAX_H3_CUDA_REPO_FILES —
+ // never a snapshot of this repo) and the runtime is provisioned only
+ // after the user selects Install in Video Gen.
+ {
+ id: 'minimax_h3_cuda',
+ name: 'MiniMax H3 CUDA int8 (joint video + audio, ~144 GB download, 24 GB VRAM + 96 GB RAM)',
+ repo: 'MiniMaxAI/MiniMax-H3',
+ revision: '42ed227ee7df40d41602854ae760620d6eb651fe',
+ repoFiles: [...MINIMAX_H3_CUDA_REPO_FILES],
+ runtime: 'minimax_h3_cuda',
+ supportedModes: ['text', 'image', 'fflf'],
+ defaultFrames: 124,
+ frameOptions: [...MINIMAX_H3_CUDA_FRAME_OPTIONS],
+ fpsOptions: [24],
+ ...MINIMAX_H3_CANVAS,
+ resolutionOptions: MINIMAX_H3_CANVAS.resolutionOptions.map((preset) => ({ ...preset })),
+ // HOST RAM, not VRAM: at int8 the transformer's blocks and the
+ // conditioner's leaves are streamed from CPU memory, so ~75 GB of the
+ // weights are resident off-GPU for the whole render. The card itself
+ // needs ~24 GB, and the runner steps down to a leaner offload profile
+ // on a smaller one (see scripts/generate_minimax_h3_cuda.py).
+ memoryGb: 96,
+ steps: 8,
+ guidance: 0,
+ samplerLocked: true,
+ samplerNote: 'MiniMax H3 is CFG-distilled; this profile locks the validated 8-point sigma schedule and does not use CFG.',
+ supportsNegativePrompt: false,
+ supportsTiling: false,
+ supportsDisableAudio: false,
+ },
])),
defaultMacos: 'ltx23_distilled_q4',
defaultWindows: 'ltx_video',
diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.js
index 9eea37d903..e12f102a3c 100644
--- a/server/lib/mediaModels.test.js
+++ b/server/lib/mediaModels.test.js
@@ -120,6 +120,78 @@ describe('mediaModels registry', () => {
expect(h3.termsGate.id).toBe('minimax-h3-community-license-2026-08-02');
});
+ it('ships MiniMax H3 CUDA as the Windows/NVIDIA H3 profile', async () => {
+ const { loadMediaModels } = await import('./mediaModels.js');
+ // The CUDA entry is Windows-list-only, so inspect the shipped catalog
+ // directly rather than the current platform's filtered list.
+ const h3 = loadMediaModels().video.windows.find((model) => model.id === 'minimax_h3_cuda');
+ expect(h3).toMatchObject({
+ runtime: 'minimax_h3_cuda',
+ repo: 'MiniMaxAI/MiniMax-H3',
+ revision: '42ed227ee7df40d41602854ae760620d6eb651fe',
+ supportedModes: ['text', 'image', 'fflf'],
+ defaultFrames: 124,
+ fpsOptions: [24],
+ samplerLocked: true,
+ supportsNegativePrompt: false,
+ supportsDisableAudio: false,
+ steps: 8,
+ });
+ // Same canvas contract as the MLX profile — it's the checkpoint's, not the
+ // runner's — so these must not drift apart.
+ const mlx = loadMediaModels().video.macos.find((model) => model.id === 'minimax_h3_8bit');
+ expect(h3.defaultWidth).toBe(mlx.defaultWidth);
+ expect(h3.defaultHeight).toBe(mlx.defaultHeight);
+ expect(h3.resolutionStep).toBe(mlx.resolutionStep);
+ expect(h3.resolutionOptions).toEqual(mlx.resolutionOptions);
+ // The frame grid, by contrast, MUST differ: diffusers snaps to 17n+5 and
+ // then requires 5-15 s, so the MLX grid's 107 (4.46 s) and 362 (15.08 s)
+ // ends are both illegal here.
+ expect(h3.frameOptions).toEqual([124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345]);
+ expect(h3.frameOptions).not.toContain(107);
+ expect(h3.frameOptions).not.toContain(362);
+ expect(h3.frameOptions.every((n) => n % 17 === 5)).toBe(true);
+ // Same weights, same license, so one acceptance covers both entries.
+ expect(h3.termsGate.id).toBe(mlx.termsGate.id);
+ });
+
+ it('pins an explicit file list for MiniMax H3 CUDA rather than a repo snapshot', async () => {
+ const { loadMediaModels } = await import('./mediaModels.js');
+ const h3 = loadMediaModels().video.windows.find((model) => model.id === 'minimax_h3_cuda');
+ // `MiniMaxAI/MiniMax-H3` is ~498 GB: it carries the diffusers layout, the
+ // `transformer_ref/` partition for the ref2va workflow PortOS doesn't
+ // expose, AND the original non-diffusers FL2VA/ + Ref2VA/ layouts the MLX
+ // port consumes. Snapshotting it would pull 3.5x what the runner loads, so
+ // the absence of this list is a download bug, not a missing optimization.
+ expect(Array.isArray(h3.repoFiles)).toBe(true);
+ expect(h3.repoFiles).not.toHaveLength(0);
+ for (const prefix of ['transformer_ref/', 'FL2VA/', 'Ref2VA/', 'assets/', 'scripts/', 'docs/']) {
+ expect(h3.repoFiles.filter((file) => file.startsWith(prefix)), prefix).toEqual([]);
+ }
+ // Every sharded component needs its index AND all of its shards; a missing
+ // shard only surfaces as a cache-resolve failure deep into a render.
+ for (const [dir, stem, count] of [
+ ['transformer', 'diffusion_pytorch_model', 14],
+ ['text_encoder', 'model', 14],
+ ['vae', 'diffusion_pytorch_model', 3],
+ ]) {
+ expect(h3.repoFiles, `${dir} index`).toContain(`${dir}/${stem}.safetensors.index.json`);
+ const shards = h3.repoFiles.filter((file) => new RegExp(`^${dir}/${stem}-\\d{5}-of-\\d{5}\\.safetensors$`).test(file));
+ expect(shards, `${dir} shards`).toEqual(Array.from(
+ { length: count },
+ (_, i) => `${dir}/${stem}-${String(i + 1).padStart(5, '0')}-of-${String(count).padStart(5, '0')}.safetensors`,
+ ));
+ }
+ // Keyframe conditioning runs each image through Qwen3-VL's AutoProcessor,
+ // which reads `processor/` — same requirement as the MLX profile.
+ expect(h3.repoFiles).toContain('processor/preprocessor_config.json');
+ expect(h3.repoFiles).toContain('audio_vae/diffusion_pytorch_model.safetensors');
+ expect(h3.repoFiles).toContain('modular_model_index.json');
+ // Every path stays repo-relative POSIX — the download route rejects
+ // anything else as VIDEO_MODEL_MISCONFIGURED.
+ expect(h3.repoFiles.every((file) => !file.startsWith('/') && !file.includes('..') && !file.includes('\\'))).toBe(true);
+ });
+
// #3737: capability has to be answerable off the entry, or every consumer
// re-derives it from `runtime` string comparisons and the two ends drift.
describe('supportedModes resolution (#3737)', () => {
diff --git a/server/lib/runners.js b/server/lib/runners.js
index 6bfa2d463c..8fe65b19a0 100644
--- a/server/lib/runners.js
+++ b/server/lib/runners.js
@@ -46,6 +46,17 @@ export const VIDEO_LORA_FAMILIES = Object.freeze({
// client/src/lib/runnerFamilies.js.
const VIDEO_LORA_FAMILY_SET = new Set(Object.values(VIDEO_LORA_FAMILIES));
export const isVideoLoraFamily = (family) => VIDEO_LORA_FAMILY_SET.has(family);
+// The MiniMax H3 runtimes: PipeNetwork's Apple-Silicon MLX port (`minimax_h3`)
+// and the diffusers + CUDA path Windows/Linux NVIDIA boxes run
+// (`minimax_h3_cuda`). They load the same weights family, so every control H3
+// fixes in the model itself — 24 fps, joint video+audio, CFG-distilled (no
+// negative prompt), the 17n+5 frame grid, no tiling knob — is true of both.
+// Gates asserting one of those facts ask this predicate instead of naming a
+// single runtime, which is what would silently exempt the other one.
+// Mirrored to client/src/lib/runnerFamilies.js.
+export const MINIMAX_H3_RUNTIMES = Object.freeze(['minimax_h3', 'minimax_h3_cuda']);
+const MINIMAX_H3_RUNTIME_SET = new Set(MINIMAX_H3_RUNTIMES);
+export const isMiniMaxH3Runtime = (runtime) => MINIMAX_H3_RUNTIME_SET.has(runtime);
// The family an INSTALLED LoRA belongs to. `loraCompatKey` is the refined key
// (e.g. flux2-9b) written by the importer; `runnerFamily` is the coarse legacy
diff --git a/server/lib/runners.test.js b/server/lib/runners.test.js
index 8b52956d09..85b6a4f60a 100644
--- a/server/lib/runners.test.js
+++ b/server/lib/runners.test.js
@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
-import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, videoLoraFamily, isMlxVideoLtxLoraCapable, loraFamilyOf, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, MINIMAX_H3_RUNTIMES, videoLoraFamily, isMiniMaxH3Runtime, isMlxVideoLtxLoraCapable, loraFamilyOf, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';
const __dirname_self = dirname(fileURLToPath(import.meta.url));
const CLIENT_MIRROR_PATH = join(__dirname_self, '..', '..', 'client', 'src', 'lib', 'runnerFamilies.js');
@@ -128,6 +128,8 @@ describe('VIDEO_LORA_FAMILIES / videoLoraFamily', () => {
expect(text).toMatch(/export const videoLoraFamily/);
expect(text).toMatch(/export const isMlxVideoLtxLoraCapable/);
expect(text).toMatch(/export const loraFamilyOf/);
+ expect(text).toMatch(/export const isMiniMaxH3Runtime/);
+ expect(text).toMatch(/'minimax_h3', 'minimax_h3_cuda'/);
});
});
@@ -199,3 +201,26 @@ describe('composeCompatKey', () => {
.toBe(composeCompatKey('flux2', '9b'));
});
});
+
+// H3's controls (24 fps, joint A/V, no CFG, the 17n+5 grid) are facts about the
+// checkpoint, so the gates that assert them must cover BOTH runtimes. Naming
+// one runtime in a gate is precisely how the CUDA path would silently escape
+// a rule the MLX path enforces.
+describe('isMiniMaxH3Runtime', () => {
+ it('covers both H3 runtimes and nothing else', () => {
+ expect(MINIMAX_H3_RUNTIMES).toEqual(['minimax_h3', 'minimax_h3_cuda']);
+ expect(isMiniMaxH3Runtime('minimax_h3')).toBe(true);
+ expect(isMiniMaxH3Runtime('minimax_h3_cuda')).toBe(true);
+ });
+
+ it.each(['mlx_video', 'ltx2', 'wan22', 'hunyuan', 'minimax', '', undefined, null])(
+ 'reports %s as not an H3 runtime',
+ (runtime) => { expect(isMiniMaxH3Runtime(runtime)).toBe(false); },
+ );
+
+ it('does not grant the CUDA runtime a LoRA family — the diffusers path has no applicator', () => {
+ expect(videoLoraFamily({ runtime: 'minimax_h3_cuda' })).toBe(null);
+ // Not even when a stale/synced payload claims the MLX port's probe verdict.
+ expect(videoLoraFamily({ runtime: 'minimax_h3_cuda', runtimeLoraCapable: true })).toBe(null);
+ });
+});
diff --git a/server/lib/videoContinuity.js b/server/lib/videoContinuity.js
index 0c31397fac..517c8ccd8e 100644
--- a/server/lib/videoContinuity.js
+++ b/server/lib/videoContinuity.js
@@ -71,7 +71,8 @@ export const LATENT_FRAME_STRIDE = 8;
/**
* Runtimes whose helper can condition on a source *video* rather than a still.
- * `ltx2` routes to ExtendPipeline.extend_from_video; `minimax_h3`, `wan22`,
+ * `ltx2` routes to ExtendPipeline.extend_from_video; the `minimax_h3`
+ * runtimes, `wan22`,
* `hunyuan` and `mlx_video` have no equivalent and take the 'frame' path.
*
* Kept here rather than in `videoGen/modeContract.js` — that module's "declare
diff --git a/server/lib/videoDisclosure.js b/server/lib/videoDisclosure.js
index 28e8f7afc7..a27e8c50c9 100644
--- a/server/lib/videoDisclosure.js
+++ b/server/lib/videoDisclosure.js
@@ -59,12 +59,40 @@ const RUNTIME_LICENSE = {
name: 'Apache-2.0',
url: 'https://github.com/PipeNetwork/minimax-h3-mlx/blob/fcd9e9b79a1d6018d91ac477c0968de1fa067e49/LICENSE',
},
+ // The diffusers CUDA path executes no vendored source — the license that
+ // governs the inference code is diffusers' own.
+ minimax_h3_cuda: { name: 'Apache-2.0', url: 'https://github.com/huggingface/diffusers/blob/main/LICENSE' },
hunyuan: {
name: 'Tencent Hunyuan Community License',
url: 'https://github.com/gaurav-nelson/HunyuanVideo_MLX/blob/main/LICENSE.txt',
},
};
+// Unlike an informational disclosure, this is an execution gate. The upstream
+// license grants rights solely in its Applicable Territory and makes use itself
+// acceptance, so PortOS requires the exact versioned key on both download and
+// generation requests.
+//
+// Shared verbatim by every MiniMax H3 entry — the MLX port and the CUDA path
+// load the same weights under the same license, so one acceptance is the honest
+// scope. Sharing the OBJECT (rather than repeating its fields) is what keeps the
+// `id` identical: acceptance is recorded by id in settings, so a second entry
+// with its own id would re-prompt a user who has already accepted, and a later
+// edit to one copy would silently split the two gates apart.
+const MINIMAX_H3_TERMS_GATE = Object.freeze({
+ id: 'minimax-h3-community-license-2026-08-02',
+ title: 'MiniMax H3 eligibility and terms',
+ summary: 'MiniMax grants use only in its Applicable Territory. The license excludes the European Union, United Kingdom, Republic of Korea, and United States of America.',
+ acknowledgement: 'I confirm I am in the Applicable Territory and agree to the MiniMax H3 Community License and its Acceptable Use Policy.',
+ licenseUrl: MINIMAX_H3_LICENSE_URL,
+ excludedTerritories: Object.freeze([
+ 'European Union',
+ 'United Kingdom',
+ 'Republic of Korea',
+ 'United States of America',
+ ]),
+});
+
const hfModelCard = (repo) => `https://huggingface.co/${repo}`;
// A model card that declares `license: other` with no `license_name` /
@@ -80,12 +108,14 @@ const customLicense = (repo) => ({ name: 'Custom — see model card', url: hfMod
* re-pointed `repo` at a fork keeps "Unknown" rather than inheriting upstream's
* license and size claims.
*
- * `estimatedDownloadGb` is the total size of the pinned repository snapshot in
+ * `estimatedDownloadGb` is what PortOS's own download path actually pulls, in
* decimal GB (10^9 bytes), summed from the HuggingFace file listing at the
- * entry's pinned revision (or `main` when unpinned) — i.e. what PortOS's own
- * download path actually pulls, which can exceed the resident-memory figure in
- * a model's display name. Lightning entries include their `requiredWeights`
- * LoRA files.
+ * entry's pinned revision (or `main` when unpinned) — which can exceed the
+ * resident-memory figure in a model's display name. That is the whole repo
+ * snapshot for most entries, but only the enumerated files for an entry that
+ * narrows its repo with `repoFiles` (or adds one with `requiredWeights`), so
+ * quote the file set the entry actually declares rather than the repo total.
+ * Lightning entries include their `requiredWeights` LoRA files.
*/
export const VIDEO_MODEL_DISCLOSURES = Object.freeze({
minimax_h3_8bit: {
@@ -100,23 +130,24 @@ export const VIDEO_MODEL_DISCLOSURES = Object.freeze({
estimatedDownloadGb: 103.3,
reviewedAt: VIDEO_DISCLOSURE_REVIEWED_AT,
},
- // Unlike an informational disclosure, this is an execution gate. The
- // upstream license grants rights solely in its Applicable Territory and
- // makes use itself acceptance, so PortOS requires the exact versioned key
- // on both download and generation requests.
- termsGate: {
- id: 'minimax-h3-community-license-2026-08-02',
- title: 'MiniMax H3 eligibility and terms',
- summary: 'MiniMax grants use only in its Applicable Territory. The license excludes the European Union, United Kingdom, Republic of Korea, and United States of America.',
- acknowledgement: 'I confirm I am in the Applicable Territory and agree to the MiniMax H3 Community License and its Acceptable Use Policy.',
- licenseUrl: MINIMAX_H3_LICENSE_URL,
- excludedTerritories: [
- 'European Union',
- 'United Kingdom',
- 'Republic of Korea',
- 'United States of America',
- ],
+ termsGate: MINIMAX_H3_TERMS_GATE,
+ },
+ minimax_h3_cuda: {
+ shippedRepo: 'MiniMaxAI/MiniMax-H3',
+ disclosure: {
+ modelCardUrl: hfModelCard('MiniMaxAI/MiniMax-H3'),
+ weightsLicense: MINIMAX_H3_WEIGHTS,
+ runtimeLicense: RUNTIME_LICENSE.minimax_h3_cuda,
+ // The bf16 diffusers components the fl2va workflow loads: 66.28 GB
+ // transformer + 66.73 GB Qwen3-VL conditioner + 10.42 GB video VAE +
+ // 0.61 GB audio VAE, plus ~0.02 GB of tokenizer / processor / scheduler
+ // configs. NOT the repo total — `MiniMaxAI/MiniMax-H3` is 498 GB because
+ // it also ships the `Ref2VA` partition and the original non-diffusers
+ // `FL2VA/` layout, which is why this entry pulls an explicit file list.
+ estimatedDownloadGb: 144.1,
+ reviewedAt: VIDEO_DISCLOSURE_REVIEWED_AT,
},
+ termsGate: MINIMAX_H3_TERMS_GATE,
},
ltx23_unified: {
shippedRepo: 'notapalindrome/ltx23-mlx-av',
diff --git a/server/lib/videoDisclosure.test.js b/server/lib/videoDisclosure.test.js
index edd078ba64..122043cb08 100644
--- a/server/lib/videoDisclosure.test.js
+++ b/server/lib/videoDisclosure.test.js
@@ -11,7 +11,7 @@ import {
videoBackendDisclosure,
} from './videoDisclosure.js';
-const CANONICAL_FIELDS = ['repo', 'revision', 'runtime', 'memoryGb', 'supportedModes', 'requiredWeights'];
+const CANONICAL_FIELDS = ['repo', 'revision', 'runtime', 'memoryGb', 'supportedModes', 'requiredWeights', 'repoFiles'];
const RANKING_WORDS = /uncensored|unrestricted|\bunsafe\b|\bsafe\b|less restrictive|no limits/i;
describe('VIDEO_MODEL_DISCLOSURES', () => {
diff --git a/server/lib/videoModeProfiles.js b/server/lib/videoModeProfiles.js
index f5a9e56afe..edb3228612 100644
--- a/server/lib/videoModeProfiles.js
+++ b/server/lib/videoModeProfiles.js
@@ -40,18 +40,26 @@ export const VIDEO_BASE_MODES = Object.freeze(['text', 'image', 'fflf', 'extend'
* - `wan22` — MLX-Gen's Wan CLI is t2v or i2v depending on the checkpoint, so
* each shipped profile narrows this itself; the pair is the widest any Wan
* checkpoint reaches (no keyframe interpolation, no extend).
- * - `minimax_h3` — fl2va conditioning anchored at the first / last latent
- * frame: 'image' anchors one, 'fflf' anchors both. Doubles as the mode
- * ceiling in videoGen/modeContract.js.
+ * - `minimax_h3` / `minimax_h3_cuda` — fl2va conditioning anchored at the
+ * first / last latent frame: 'image' anchors one, 'fflf' anchors both. The
+ * MLX port and the diffusers CUDA path expose the same three, because the
+ * capability is the checkpoint partition's, not the runner's. Doubles as
+ * the mode ceiling in videoGen/modeContract.js.
* - `hunyuan` — the MLX port's `hyvideo.inference` helper takes a prompt and
* nothing else (see buildHunyuanArgs); text-to-video only. This replaces the
* legacy `mode: 't2v'` field, which no reader ever consulted.
*/
+// One array, referenced by both H3 runtimes: the modes are the fl2va
+// checkpoint partition's, so a second literal would be a copy the comment above
+// says must never differ — with nothing enforcing it.
+const MINIMAX_H3_MODE_SET = Object.freeze(['text', 'image', 'fflf']);
+
export const VIDEO_RUNTIME_MODES = Object.freeze({
mlx_video: Object.freeze(['text', 'image', 'fflf', 'extend']),
ltx2: Object.freeze(['text', 'image', 'fflf', 'extend']),
wan22: Object.freeze(['text', 'image']),
- minimax_h3: Object.freeze(['text', 'image', 'fflf']),
+ minimax_h3: MINIMAX_H3_MODE_SET,
+ minimax_h3_cuda: MINIMAX_H3_MODE_SET,
hunyuan: Object.freeze(['text']),
});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 9a816c21bb..2d855a5619 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -603,19 +603,36 @@ router.get('/models', (_req, res) => {
// Resolve the repo set an integrity scan should cover. A specific `modelId`
// scopes to that model's repo; no modelId scans every model repo plus the
// shared text encoder.
+const safeOnlyList = (model, files, label) => {
+ const only = Array.isArray(files) ? files.filter((file) => typeof file === 'string' && file.length > 0) : [];
+ if (only.some((file) => !isSafeHfRepoRelativePath(file))) {
+ throw new ServerError(
+ `Video model "${model.id}" has an unsafe ${label} path. Use repo-relative POSIX filenames only.`,
+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
+ );
+ }
+ return only;
+};
+
const modelDownloadTargets = (model) => {
const repo = repoForModel(model);
if (!repo) return [];
- const targets = [{ repo, revision: model?.revision || null, only: [] }];
+ // `repoFiles` narrows the model's OWN repo to an explicit file list, the way
+ // `requiredWeights[].files` already does for a secondary repo. It is required
+ // — not an optimization — whenever the model's repo is an aggregate that
+ // holds more than the one component set the runner loads: MiniMax H3 ships
+ // its diffusers layout, a second transformer partition and the original
+ // non-diffusers layout in one ~498 GB repo, so the default whole-snapshot
+ // target would pull 3.5x what the render path can use. Absent (every other
+ // model) still means "snapshot the repo".
+ const targets = [{
+ repo,
+ revision: model?.revision || null,
+ only: safeOnlyList(model, model?.repoFiles, 'repo-file'),
+ }];
for (const dep of Array.isArray(model?.requiredWeights) ? model.requiredWeights : []) {
if (typeof dep?.repo !== 'string') continue;
- const only = Array.isArray(dep.files) ? dep.files.filter((file) => typeof file === 'string' && file.length > 0) : [];
- if (only.some((file) => !isSafeHfRepoRelativePath(file))) {
- throw new ServerError(
- `Video model "${model.id}" has an unsafe required-weight path. Use repo-relative POSIX filenames only.`,
- { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
- );
- }
+ const only = safeOnlyList(model, dep.files, 'required-weight');
if (only.length > 0) targets.push({ repo: dep.repo, revision: dep.revision || null, only });
}
return targets;
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 90bd8d1fce..91aa4999b1 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -40,7 +40,7 @@ import { inspectModelCache, findCachedRepoFile } from '../../lib/hfCache.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
import { assertSafeLoraFilename, getLoraKeyLayout } from '../loras.js';
-import { videoLoraFamily } from '../../lib/runners.js';
+import { videoLoraFamily, isMiniMaxH3Runtime } from '../../lib/runners.js';
import {
isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsGateId, videoModelTermsError,
} from '../../lib/videoDisclosure.js';
@@ -62,6 +62,8 @@ import {
MINIMAX_H3_REPO_DIR,
MINIMAX_H3_ENCODER_SHIM_DIR,
MINIMAX_H3_EXPECTED_REVISION,
+ MINIMAX_H3_CUDA_VENV_PYTHON,
+ MINIMAX_H3_CUDA_HELPER_SCRIPT,
HUNYUAN_VENV_PYTHON,
HUNYUAN_HELPER_SCRIPT,
HUNYUAN_REPO_DIR,
@@ -71,12 +73,14 @@ import {
resolveByovRuntimeLoraCapable,
videoLoraUnsupportedError,
modelAnchorsLastFrame,
+ routesToWindowsHelper,
assertByovRuntimeInstalled,
invalidateByovReadyCache,
pickDeathFingerprint,
} from './runtimes.js';
import { loadHistory, saveHistory, mutateVideoHistory } from './history.js';
import { videoModeContractError, videoChainUnsupportedError, VIDEO_MODE_GATED_RUNTIMES } from './modeContract.js';
+import { minimaxH3ControlError } from './minimaxH3Controls.js';
import { estimateRenderMs } from './eta.js';
// Re-export the extracted runtime + history surface so existing deep imports
// (`from '../videoGen/local.js'`) keep resolving every symbol they used to.
@@ -96,8 +100,6 @@ const AV_LORA_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_av_lora.py')
const execFileAsync = promisify(execFile);
-const IS_WIN = process.platform === 'win32';
-
const MODULE_NOT_FOUND_RE = /ModuleNotFoundError: No module named ['"]([^'"]+)['"]/;
// Panel-side SIGKILL watchdog (defense-in-depth at the Node layer).
@@ -654,36 +656,8 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF
audioStartSec,
icReferencePaths,
});
- if (negativePrompt?.trim()) {
- throw new ServerError(
- 'MiniMax H3 is CFG-distilled and does not accept a negative prompt.',
- { status: 400, code: 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED' },
- );
- }
- if (disableAudio) {
- throw new ServerError(
- 'MiniMax H3 jointly generates video and audio; its audio track cannot be disabled.',
- { status: 400, code: 'MINIMAX_H3_AUDIO_REQUIRED' },
- );
- }
- if (tiling && tiling !== 'auto') {
- throw new ServerError(
- 'MiniMax H3 does not expose a tiling mode.',
- { status: 400, code: 'MINIMAX_H3_TILING_UNSUPPORTED' },
- );
- }
- if (!Array.isArray(model.frameOptions) || !model.frameOptions.includes(Number(numFrames))) {
- throw new ServerError(
- `MiniMax H3 requires a 17n+5 frame count between 107 and 362; got ${numFrames}.`,
- { status: 400, code: 'MINIMAX_H3_INVALID_FRAME_COUNT' },
- );
- }
- if (Number(fps) !== 24) {
- throw new ServerError(
- `MiniMax H3 runs at a fixed 24 fps; got ${fps}.`,
- { status: 400, code: 'MINIMAX_H3_INVALID_FPS' },
- );
- }
+ const controlError = minimaxH3ControlError({ model, negativePrompt, disableAudio, tiling, numFrames, fps });
+ if (controlError) throw controlError;
if (typeof model.repo !== 'string' || typeof model.revision !== 'string') {
throw new ServerError(
`MiniMax H3 model "${model.id}" is missing its pinned transformer repo or revision.`,
@@ -744,6 +718,74 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF
return { bin: MINIMAX_H3_VENV_PYTHON, args };
};
+// Build args for MiniMax H3 on CUDA — diffusers' MiniMaxH3ModularPipeline in a
+// pip venv, which is the only H3 path an NVIDIA box has (the MLX port above is
+// Apple-Silicon-only). Same cache-only contract: the helper resolves exactly
+// the pinned revisions already on disk and never reaches the network, so every
+// download stays an explicit, terms-gated Video Gen action.
+//
+// Unlike the MLX lane this is ONE repo — diffusers' modular layout keeps the
+// transformer, conditioner, both VAEs and the schedulers in the model's own
+// `repo`, so the file list rides on `repoFiles` and there is no separate
+// upstream-checkpoint dependency to resolve.
+const buildMiniMaxH3CudaArgs = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath }) => {
+ assertByovRuntimeInstalled('minimax_h3_cuda');
+ assertRenderModeContract({
+ model,
+ mode,
+ sourceImagePath,
+ lastImagePath,
+ keyframes,
+ extendFromVideoPath,
+ audioFilePath,
+ audioStartSec,
+ icReferencePaths,
+ });
+ const controlError = minimaxH3ControlError({ model, negativePrompt, disableAudio, tiling, numFrames, fps });
+ if (controlError) throw controlError;
+ if (typeof model.repo !== 'string' || typeof model.revision !== 'string') {
+ throw new ServerError(
+ `MiniMax H3 model "${model.id}" is missing its pinned repo or revision.`,
+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
+ );
+ }
+ const files = Array.isArray(model.repoFiles) ? model.repoFiles.filter((file) => typeof file === 'string' && file) : [];
+ if (files.length === 0) {
+ // Fail here rather than let the helper fall back to a repo-wide resolve:
+ // `MiniMaxAI/MiniMax-H3` is ~498 GB and holds three layouts, so "load
+ // whatever is cached" is not a recoverable default for this model.
+ throw new ServerError(
+ `MiniMax H3 model "${model.id}" is missing its pinned diffusers component file list.`,
+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
+ );
+ }
+ const args = [
+ MINIMAX_H3_CUDA_HELPER_SCRIPT,
+ '--model-repo', model.repo,
+ '--model-revision', model.revision,
+ '--prompt', prompt,
+ '--width', String(width),
+ '--height', String(height),
+ '--num-frames', String(numFrames),
+ '--fps', String(fps),
+ '--steps', String(steps),
+ '--seed', String(seed),
+ '--output', outputPath,
+ ];
+ for (const file of files) args.push('--repo-file', file);
+ // A user-pinned offload recipe from data/media-models.json. Omitted, the
+ // helper sizes one from the card's own VRAM — the right default, since the
+ // registry entry is shared across every install that syncs it and can't know
+ // what GPU is on the other end.
+ if (model.offloadProfile) args.push('--offload-profile', String(model.offloadProfile));
+ // Anchor order is packed order, same as the MLX lane: diffusers takes the
+ // first keyframe as `image` (which sets the canvas) and the last as
+ // `last_image`, 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_CUDA_VENV_PYTHON, args };
+};
+
// Allowed precision tokens for runners that expose dtype as a CLI flag. The
// Python side already gates argparse with `choices=`, but a bogus value in
// data/media-models.json would otherwise reach the helper and surface as a
@@ -806,14 +848,18 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeight
// applicator. All of those macOS/mlx-only. The route already rejects the rest,
// but a non-route caller (test, queue replay) — or a Windows install with a
// hand-edited/synced entry — could reach here. Fail clearly rather than fall
- // through to the IS_WIN generate_win.py branch below, which would silently drop
- // the LoRAs and produce a base render the user thinks is LoRA-styled.
+ // through to the generate_win.py branch below, which would silently drop the
+ // LoRAs and produce a base render the user thinks is LoRA-styled.
// The same predicate the enqueue gate uses, off the same decorated model, so
- // the two can't disagree — and the reason text comes from one factory.
- if (hasLoras && (!videoLoraFamily(model) || IS_WIN)) {
- throw IS_WIN
+ // the two can't disagree — and the reason text comes from one factory. The
+ // legacy-Windows-helper arm is keyed on the RUNNER, not the platform: a
+ // Windows BYOV runtime now gets the same runner-based reason the enqueue gate
+ // gives it, instead of a blanket "can't fuse LoRAs on Windows" that would
+ // contradict it.
+ if (hasLoras && (!videoLoraFamily(model) || routesToWindowsHelper(model))) {
+ throw routesToWindowsHelper(model)
? new ServerError(
- `LoRA fusion runs through the macOS-only mlx_video path; model "${modelId}" can't fuse LoRAs on Windows.`,
+ `LoRA fusion runs through the macOS-only mlx_video path; model "${modelId}" can't fuse LoRAs on the Windows LTX-Video helper.`,
{ status: 400, code: 'LORAS_REQUIRE_LTX2' },
)
: videoLoraUnsupportedError(model, modelId);
@@ -824,6 +870,9 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeight
if (model.runtime === 'minimax_h3') {
return buildMiniMaxH3Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras, textEncoder });
}
+ if (model.runtime === 'minimax_h3_cuda') {
+ return buildMiniMaxH3CudaArgs({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath });
+ }
if (model.runtime === 'hunyuan') {
return buildHunyuanArgs({ model, prompt, negativePrompt, width, height, numFrames, steps, guidance, seed, outputPath });
}
@@ -839,7 +888,9 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeight
{ status: 400, code: 'A2V_REQUIRES_LTX2' },
);
}
- if (IS_WIN) {
+ // The site the predicate is named for: every BYOV runtime has declined above,
+ // so what's left on win32 is the legacy LTX-Video 0.9.5 diffusers wrapper.
+ if (routesToWindowsHelper(model)) {
const scriptPath = join(PATHS.root, 'scripts', 'generate_win.py');
const args = [scriptPath, '--model', modelId, '--prompt', prompt, '--height', String(height), '--width', String(width), '--num-frames', String(numFrames), '--fps', String(fps), '--steps', String(steps), '--guidance', String(guidance), '--seed', String(seed), '--output', outputPath];
if (negativePrompt) args.push('--negative-prompt', negativePrompt);
@@ -1058,10 +1109,12 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
if (!pythonPath && !BYOV_VIDEO_RUNTIMES.has(model.runtime)) {
throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' });
}
- // macOS/mlx_video requires a HuggingFace repo id — Windows doesn't (the
- // diffusers wrapper hardcodes Lightricks/LTX-Video). A user-edited registry
- // entry missing `repo` would otherwise pass `undefined` into spawn args.
- if (!IS_WIN && (typeof model.repo !== 'string' || model.repo.length === 0)) {
+ // Every runner resolves its weights from a HuggingFace repo id EXCEPT the
+ // legacy Windows helper, which hardcodes Lightricks/LTX-Video. A user-edited
+ // registry entry missing `repo` would otherwise pass `undefined` into spawn
+ // args. Keyed on the runner rather than the platform, so a Windows BYOV
+ // runtime — which does need its repo — is still held to it here.
+ if (!routesToWindowsHelper(model) && (typeof model.repo !== 'string' || model.repo.length === 0)) {
throw new ServerError(`Video model "${modelId}" is missing the required \`repo\` field in data/media-models.json`, { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' });
}
@@ -1166,10 +1219,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// - 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.
- // - On Windows we forward --last-image to generate_win.py so it can log
- // 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'
+ // - A model that routes to generate_win.py takes --last-image only so the
+ // script can log status; the LTX-Video 0.9.5 pipeline reads --image
+ // alone, so it never opens the last-frame file. That gate keys on the
+ // RUNNER, not on the platform (see routesToWindowsHelper): Windows also
+ // has a BYOV runtime, MiniMax H3 CUDA, whose helper genuinely anchors the
+ // last frame, and a bare platform check would hand it an unresized frame.
+ const lastImageWillBeUsed = !!lastImagePath && !routesToWindowsHelper(model) && mode === 'fflf'
&& (modelAnchorsLastFrame(model) || !sourceImagePath);
// A non-null `keyframes` that ISN'T a length-≥2 array is malformed —
// fail fast instead of silently dropping it (which would produce an
@@ -1451,7 +1507,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// python helpers can authenticate snapshot_download() against gated repos
// (mirrors the imageGen child-spawn pattern). LTX-2 doesn't currently use
// a gated repo, but the merge is harmless when no token is configured.
- const childEnv = model.runtime === 'minimax_h3'
+ const childEnv = isMiniMaxH3Runtime(model.runtime)
? safeChildProcessEnv()
: await hfChildEnv();
delete childEnv.PYTHONPATH;
@@ -1460,7 +1516,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// long inference loops emit nothing to handleLine() for minutes — the UI
// looks dead even when the model is making progress.
childEnv.PYTHONUNBUFFERED = '1';
- if (model.runtime === 'minimax_h3') {
+ if (isMiniMaxH3Runtime(model.runtime)) {
// The H3 repositories are public and the runner is cache-only. Do not hand
// it an ambient saved HF credential it neither needs nor may transmit.
delete childEnv.HF_TOKEN;
@@ -1482,7 +1538,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
env: childEnv,
controlDir: join(PATHS.videos, '.detached', jobId),
cleanup: true,
- killProcessGroup: model.runtime === 'wan22' || model.runtime === 'minimax_h3',
+ killProcessGroup: model.runtime === 'wan22' || isMiniMaxH3Runtime(model.runtime),
});
activeProcess = proc;
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index bfac3d7f82..4919312435 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -90,6 +90,20 @@ vi.mock('../../lib/mediaModels.js', () => ({
files: ['LICENSE', 'FL2VA/vae/video/config.json'],
}],
},
+ {
+ id: 'minimax_h3_cuda', name: 'MiniMax H3 CUDA int8', runtime: 'minimax_h3_cuda',
+ repo: 'MiniMaxAI/MiniMax-H3',
+ revision: '42ed227ee7df40d41602854ae760620d6eb651fe',
+ repoFiles: ['modular_model_index.json', 'transformer/config.json'],
+ supportedModes: ['text', 'image', 'fflf'], defaultFrames: 124,
+ // Deliberately excludes 107 — the diffusers window starts at 5 s, so the
+ // MLX grid's first point is illegal here and the two entries must not
+ // share a frame list.
+ frameOptions: [124, 141, 158], fpsOptions: [24],
+ defaultWidth: 1344, defaultHeight: 768, resolutionStep: 32,
+ steps: 8, guidance: 0, samplerLocked: true,
+ termsGate: { id: 'minimax-h3-community-license-2026-08-02' },
+ },
{
id: 'wan22_ti2v_5b', name: 'Wan TI2V', runtime: 'wan22',
repo: 'AbstractFramework/wan2.2-ti2v-5b-diffusers-8bit',
@@ -3460,3 +3474,122 @@ describe('resolveVideoLoras — safetensors key-layout gate', () => {
expect(getLoraKeyLayout).not.toHaveBeenCalled();
});
});
+
+describe('generateVideo — MiniMax H3 CUDA contract', () => {
+ // Same license gate as the MLX entry: it is the same weights under the same
+ // terms, so acceptance is recorded once and honored by both runtimes.
+ beforeEach(() => { settingsState.acceptedModelTerms = [H3_TERMS]; });
+
+ const cudaCall = (spawnMock) => spawnMock.mock.calls.find(([, args]) => (
+ Array.isArray(args) && args.some((arg) => basename(String(arg)) === 'generate_minimax_h3_cuda.py')
+ ));
+
+ it('dispatches to the CUDA helper and venv, never to the MLX port or generate_win.py', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'h3-cuda-args',
+ modelId: 'minimax_h3_cuda',
+ prompt: 'a fox watches the rain',
+ width: 1344, height: 768, numFrames: 141, fps: 24,
+ steps: 99, guidanceScale: 12, mode: 'text',
+ });
+
+ const call = cudaCall(spawnMock);
+ expect(call).toBeDefined();
+ const [bin, args, options] = call;
+ expect(String(bin)).toContain(join('.portos', 'minimax-h3-cuda'));
+ // The MLX port's checkout flags describe a runtime this lane doesn't have.
+ expect(args).not.toContain('--runtime-dir');
+ expect(args).not.toContain('--runtime-revision');
+ expect(args).not.toContain('--checkpoint-repo');
+ expect(args[args.indexOf('--model-repo') + 1]).toBe('MiniMaxAI/MiniMax-H3');
+ expect(args[args.indexOf('--model-revision') + 1]).toBe('42ed227ee7df40d41602854ae760620d6eb651fe');
+ expect(args[args.indexOf('--width') + 1]).toBe('1344');
+ expect(args[args.indexOf('--num-frames') + 1]).toBe('141');
+ // The sampler is locked, so a caller's steps/guidance are ignored.
+ expect(args[args.indexOf('--steps') + 1]).toBe('8');
+ // One --repo-file per pinned component file; this is what keeps the runner
+ // cache-only against a repo whose full snapshot is ~498 GB.
+ expect(args.flatMap((arg, i) => (arg === '--repo-file' ? [args[i + 1]] : [])))
+ .toEqual(['modular_model_index.json', 'transformer/config.json']);
+ // H3's repos are public and the runner never reaches the network, so no
+ // ambient credential is handed to the child — same posture as the MLX lane.
+ expect(options.env).toMatchObject({
+ HF_HUB_DISABLE_IMPLICIT_TOKEN: '1',
+ HF_HUB_OFFLINE: '1',
+ TRANSFORMERS_OFFLINE: '1',
+ });
+ expect(options.env).not.toHaveProperty('HF_TOKEN');
+ expect(options.killProcessGroup).toBe(true);
+ });
+
+ it('anchors both keyframes, in packed order', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'h3-cuda-fflf',
+ modelId: 'minimax_h3_cuda',
+ prompt: 'a fox watches the rain',
+ width: 1344, height: 768, numFrames: 141, fps: 24,
+ mode: 'fflf', sourceImagePath: '/mock/source.png', lastImagePath: '/mock/last.png',
+ });
+
+ const [, args] = cudaCall(spawnMock);
+ expect(args.flatMap((arg, i) => (
+ arg === '--image' ? [args[i + 2] === '--anchor' ? args[i + 3] : 'UNPAIRED'] : []
+ ))).toEqual(['first', 'last']);
+ });
+
+ it('enforces its own frame window, not the MLX port\'s', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+
+ // 107 is legal on the MLX grid and illegal here — the check has to read the
+ // entry's own frameOptions or the two lanes silently share one window.
+ await expect(generateVideo({
+ jobId: 'h3-cuda-frames',
+ modelId: 'minimax_h3_cuda',
+ prompt: 'a fox watches the rain',
+ width: 1344, height: 768, numFrames: 107, fps: 24, mode: 'text',
+ })).rejects.toMatchObject({ code: 'MINIMAX_H3_INVALID_FRAME_COUNT' });
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a negative prompt', { negativePrompt: 'blurry' }, 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED'],
+ ['disabled audio', { disableAudio: true }, 'MINIMAX_H3_AUDIO_REQUIRED'],
+ ['a tiling mode', { tiling: 'spatial' }, 'MINIMAX_H3_TILING_UNSUPPORTED'],
+ ['a non-24 fps', { fps: 30 }, 'MINIMAX_H3_INVALID_FPS'],
+ ])('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-cuda-controls',
+ modelId: 'minimax_h3_cuda',
+ prompt: 'a fox watches the rain',
+ width: 1344, height: 768, numFrames: 141, fps: 24, mode: 'text',
+ ...fields,
+ })).rejects.toMatchObject({ code });
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+
+ it('rejects the license gate from the install record, same as the MLX entry', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+ settingsState.acceptedModelTerms = [];
+
+ await expect(generateVideo({
+ jobId: 'h3-cuda-terms',
+ modelId: 'minimax_h3_cuda',
+ prompt: 'a fox watches the rain',
+ width: 1344, height: 768, numFrames: 141, fps: 24, mode: 'text',
+ })).rejects.toMatchObject({ code: 'VIDEO_MODEL_TERMS_ACCEPTANCE_REQUIRED' });
+ expect(spawnDetached).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/videoGen/minimaxH3Controls.js b/server/services/videoGen/minimaxH3Controls.js
new file mode 100644
index 0000000000..dd6c18926d
--- /dev/null
+++ b/server/services/videoGen/minimaxH3Controls.js
@@ -0,0 +1,88 @@
+/**
+ * MiniMax H3's non-mode control gate — the knobs H3 fixes in the model itself
+ * rather than exposing to the caller.
+ *
+ * Companion to `modeContract.js`, which owns the mode/source rules and
+ * explicitly leaves "H3's fps / negative-prompt / tiling / frame-grid checks"
+ * to their call sites. There are TWO such call sites — the enqueue boundary
+ * (`prepareParams.js`, which must clean up staged uploads before it throws) and
+ * the render boundary (`local.js#buildMiniMaxH3Args`) — and they carried
+ * near-identical copies of all five checks. That is the same shape that had
+ * already drifted once before #3736 collapsed the mode gates, so the checks
+ * live here and both boundaries call in.
+ *
+ * Returns a ServerError to throw, or null when every control is legal, so a
+ * caller with teardown to run (`await cleanupStaged()`) can do it before
+ * throwing. Same convention as `videoModeContractError`.
+ *
+ * Covers BOTH H3 runtimes. The controls are facts about the checkpoint — 24
+ * fps, joint video+audio, CFG-distilled, a 17n+5 frame grid — so the MLX port
+ * and the diffusers CUDA path enforce the identical set. The one thing that
+ * genuinely differs is the legal frame WINDOW (diffusers requires the snapped
+ * duration to land in 5-15 s where the MLX port accepts 4-15 s), so the grid
+ * check reads the entry's own `frameOptions` rather than a hardcoded range.
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+
+const h3Error = (message, code) => new ServerError(message, { status: 400, code });
+
+// The canonical coercion, matching `routes/videoGen.js`. The route's schema
+// types this field as `z.union([z.boolean(), z.literal('true'), z.literal('false')])`
+// and every internal producer passes a real boolean, so `true | false | 'true' |
+// 'false' | undefined` is the whole input space — and `'false'` is why a plain
+// truthiness check is wrong (`Boolean('false')` is true, which would read an
+// explicit opt-OUT as an opt-in).
+const isRequestedTrue = (value) => value === true || value === 'true';
+
+/**
+ * @param {object} opts
+ * @param {object} opts.model - registry entry (`frameOptions`, `runtime`)
+ * @param {string} [opts.negativePrompt]
+ * @param {boolean|string} [opts.disableAudio]
+ * @param {string} [opts.tiling]
+ * @param {number|string} [opts.numFrames]
+ * @param {number|string} [opts.fps]
+ * @returns {ServerError|null}
+ */
+export const minimaxH3ControlError = ({ model, negativePrompt, disableAudio, tiling, numFrames, fps }) => {
+ if (typeof negativePrompt === 'string' && negativePrompt.trim()) {
+ return h3Error(
+ 'MiniMax H3 is CFG-distilled and does not accept a negative prompt.',
+ 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED',
+ );
+ }
+ if (isRequestedTrue(disableAudio)) {
+ return h3Error(
+ 'MiniMax H3 jointly generates video and audio; its audio track cannot be disabled.',
+ 'MINIMAX_H3_AUDIO_REQUIRED',
+ );
+ }
+ if (tiling && tiling !== 'auto') {
+ return h3Error(
+ 'MiniMax H3 does not expose a tiling mode.',
+ 'MINIMAX_H3_TILING_UNSUPPORTED',
+ );
+ }
+ const options = Array.isArray(model?.frameOptions) ? model.frameOptions : [];
+ const frames = Number(numFrames);
+ if (!options.includes(frames)) {
+ // Quote the entry's own window rather than a constant: the two runtimes
+ // ship different grids, and an install that narrowed its own frameOptions
+ // would otherwise be told to use a frame count this build rejects.
+ const window = options.length > 0
+ ? `between ${options[0]} and ${options[options.length - 1]}`
+ : 'from this model\'s frame options';
+ return h3Error(
+ `MiniMax H3 requires a 17n+5 frame count ${window}; got ${numFrames}.`,
+ 'MINIMAX_H3_INVALID_FRAME_COUNT',
+ );
+ }
+ if (Number(fps) !== 24) {
+ return h3Error(
+ `MiniMax H3 runs at a fixed 24 fps; got ${fps}.`,
+ 'MINIMAX_H3_INVALID_FPS',
+ );
+ }
+ return null;
+};
diff --git a/server/services/videoGen/minimaxH3Controls.test.js b/server/services/videoGen/minimaxH3Controls.test.js
new file mode 100644
index 0000000000..27f63cc2ae
--- /dev/null
+++ b/server/services/videoGen/minimaxH3Controls.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect } from 'vitest';
+import { minimaxH3ControlError } from './minimaxH3Controls.js';
+
+// The MLX and CUDA entries ship different frame grids on purpose (diffusers
+// requires the snapped duration to land in 5-15 s, the MLX port accepts
+// 4-15 s), which is exactly what the gate must read off the entry rather than
+// hardcode.
+const MLX = { runtime: 'minimax_h3', frameOptions: [107, 124, 141, 345, 362] };
+const CUDA = { runtime: 'minimax_h3_cuda', frameOptions: [124, 141, 345] };
+
+const legal = (model, overrides = {}) => minimaxH3ControlError({
+ model, numFrames: 124, fps: 24, ...overrides,
+});
+
+describe('minimaxH3ControlError', () => {
+ it('passes a legal request on either runtime', () => {
+ expect(legal(MLX)).toBe(null);
+ expect(legal(CUDA)).toBe(null);
+ });
+
+ it('rejects a negative prompt (the checkpoint is CFG-distilled)', () => {
+ const err = legal(CUDA, { negativePrompt: 'blurry' });
+ expect(err?.code).toBe('MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED');
+ expect(err?.status).toBe(400);
+ });
+
+ it('treats a whitespace-only negative prompt as absent', () => {
+ expect(legal(CUDA, { negativePrompt: ' ' })).toBe(null);
+ expect(legal(CUDA, { negativePrompt: '' })).toBe(null);
+ });
+
+ it('rejects disabling audio, including the form-encoded string form', () => {
+ expect(legal(CUDA, { disableAudio: true })?.code).toBe('MINIMAX_H3_AUDIO_REQUIRED');
+ // A query-string / multipart caller sends strings, where Boolean('false')
+ // is true — so an explicit opt-OUT must not read as an opt-in.
+ expect(legal(CUDA, { disableAudio: 'true' })?.code).toBe('MINIMAX_H3_AUDIO_REQUIRED');
+ expect(legal(CUDA, { disableAudio: 'false' })).toBe(null);
+ expect(legal(CUDA, { disableAudio: false })).toBe(null);
+ expect(legal(CUDA, { disableAudio: undefined })).toBe(null);
+ });
+
+ it('allows the default tiling value but rejects any other mode', () => {
+ expect(legal(CUDA, { tiling: 'auto' })).toBe(null);
+ expect(legal(CUDA, { tiling: undefined })).toBe(null);
+ expect(legal(CUDA, { tiling: 'spatial' })?.code).toBe('MINIMAX_H3_TILING_UNSUPPORTED');
+ });
+
+ it('rejects a fps other than 24', () => {
+ expect(legal(CUDA, { fps: 30 })?.code).toBe('MINIMAX_H3_INVALID_FPS');
+ // String-typed fps from a form-encoded caller still compares numerically.
+ expect(legal(CUDA, { fps: '24' })).toBe(null);
+ });
+
+ it('reads the frame grid off the entry, so each runtime quotes its own window', () => {
+ // 107 is legal on the MLX grid and NOT on the diffusers one — the whole
+ // reason this can't be a shared constant.
+ expect(legal(MLX, { numFrames: 107 })).toBe(null);
+ const err = legal(CUDA, { numFrames: 107 });
+ expect(err?.code).toBe('MINIMAX_H3_INVALID_FRAME_COUNT');
+ expect(err?.message).toContain('between 124 and 345');
+ expect(legal(MLX, { numFrames: 362 })).toBe(null);
+ expect(legal(CUDA, { numFrames: 362 })?.message).toContain('between 124 and 345');
+ });
+
+ it('accepts a string frame count (form-encoded caller)', () => {
+ expect(legal(CUDA, { numFrames: '124' })).toBe(null);
+ });
+
+ it('rejects rather than waves through when the entry declares no frame grid', () => {
+ const err = legal({ runtime: 'minimax_h3_cuda' }, { numFrames: 124 });
+ expect(err?.code).toBe('MINIMAX_H3_INVALID_FRAME_COUNT');
+ // Nothing to quote, so the message must not claim a bogus range.
+ expect(err?.message).not.toMatch(/between/);
+ });
+
+ it('reports the negative prompt before the frame grid — the first illegal control wins', () => {
+ const err = legal(CUDA, { negativePrompt: 'blurry', numFrames: 999 });
+ expect(err?.code).toBe('MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED');
+ });
+});
diff --git a/server/services/videoGen/modeContract.js b/server/services/videoGen/modeContract.js
index c3cfda4771..3f548c4422 100644
--- a/server/services/videoGen/modeContract.js
+++ b/server/services/videoGen/modeContract.js
@@ -56,6 +56,26 @@ const DEFAULT_MESSAGES = Object.freeze({
fflfRequiresImage: ({ model }) => `${model.name} FFLF requires a first and/or last frame image.`,
});
+// H3's two runtimes share ONE row: the mode rules come from the fl2va
+// checkpoint partition, not from the MLX / diffusers runner in front of it, and
+// the error codes are the same `MINIMAX_H3_*` contract on both — so both keys
+// below reference this object rather than each carrying a copy, which is
+// exactly what drifted before #3736. `modeUnsupported` names the model rather
+// than the runtime for the same reason: a message that hardcoded one runtime's
+// name would be wrong for whichever entry it wasn't written for.
+const MINIMAX_H3_CONTRACT = Object.freeze({
+ codePrefix: 'MINIMAX_H3',
+ modeCeiling: MINIMAX_H3_MODES,
+ extraConditioningUnsupported: true,
+ messages: Object.freeze({
+ modeUnsupported: ({ model, allowedModes }) => `${model.name} 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.',
+ }),
+});
+
/**
* The per-runtime rows. `modeCeiling` is the set of modes the *helper* has
* arguments for — a `null` ceiling means the registry entry's `supportedModes`
@@ -87,18 +107,8 @@ const VIDEO_MODE_CONTRACTS = Object.freeze({
: '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.',
- },
- },
+ minimax_h3: MINIMAX_H3_CONTRACT,
+ minimax_h3_cuda: MINIMAX_H3_CONTRACT,
});
// An empty array is "no references", not "references present" — and an empty
diff --git a/server/services/videoGen/modeContract.test.js b/server/services/videoGen/modeContract.test.js
index d11b903d3d..0cef3fda55 100644
--- a/server/services/videoGen/modeContract.test.js
+++ b/server/services/videoGen/modeContract.test.js
@@ -12,7 +12,7 @@ const h3 = (supportedModes) => ({ runtime: 'minimax_h3', name: 'Example H3', sup
describe('videoModeContractError — shared gate', () => {
it('gates exactly the runtimes that declare a contract row', () => {
- expect([...VIDEO_MODE_GATED_RUNTIMES].sort()).toEqual(['minimax_h3', 'wan22']);
+ expect([...VIDEO_MODE_GATED_RUNTIMES].sort()).toEqual(['minimax_h3', 'minimax_h3_cuda', 'wan22']);
});
it.each(['ltx2', 'mlx_video', 'hunyuan', undefined])('leaves the %s runtime ungated', (runtime) => {
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 007c247c34..b64cde9c19 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -34,10 +34,11 @@ import { PATHS, ensureDir, resolveGalleryImage } from '../../lib/fileUtils.js';
import { safeUnder } from '../../lib/ffmpeg.js';
import { RENDER_TARGET } from '../../lib/renderTargets.js';
import { isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsError } from '../../lib/videoDisclosure.js';
-import { videoLoraFamily } from '../../lib/runners.js';
+import { videoLoraFamily, isMiniMaxH3Runtime } from '../../lib/runners.js';
import {
isStockTextEncoder, supportsVideoTextEncoder, videoTextEncoderUnsupportedError,
} from '../../lib/videoTextEncoders.js';
+import { minimaxH3ControlError } from './minimaxH3Controls.js';
import { resolveContextFrames } from '../../lib/videoContinuity.js';
import {
IC_LORA_MODE_VALUES, icLoraSpecForMode,
@@ -445,47 +446,23 @@ async function resolvePreparedParams({
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') {
- if (body.negativePrompt?.trim()) {
- await cleanupStaged();
- throw new ServerError(
- 'MiniMax H3 is CFG-distilled and does not accept a negative prompt.',
- { status: 400, code: 'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED' },
- );
- }
- if (body.disableAudio === true || body.disableAudio === 'true') {
- await cleanupStaged();
- throw new ServerError(
- 'MiniMax H3 jointly generates video and audio; its audio track cannot be disabled.',
- { status: 400, code: 'MINIMAX_H3_AUDIO_REQUIRED' },
- );
- }
- if (body.tiling && body.tiling !== 'auto') {
- await cleanupStaged();
- throw new ServerError(
- 'MiniMax H3 does not expose a tiling mode.',
- { status: 400, code: 'MINIMAX_H3_TILING_UNSUPPORTED' },
- );
- }
- const frames = Number(body.numFrames ?? effectiveModel.defaultFrames);
- if (!Array.isArray(effectiveModel.frameOptions) || !effectiveModel.frameOptions.includes(frames)) {
- await cleanupStaged();
- throw new ServerError(
- `MiniMax H3 requires a 17n+5 frame count between 107 and 362; got ${frames}.`,
- { status: 400, code: 'MINIMAX_H3_INVALID_FRAME_COUNT' },
- );
- }
- const fps = Number(body.fps ?? 24);
- if (fps !== 24) {
+ // MiniMax H3 is fixed-24fps, joint A/V and CFG-distilled on both its runtimes
+ // (MLX and CUDA). These are the model'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 —
+ // the render boundary re-checks with the same helper.
+ if (isMiniMaxH3Runtime(effectiveModel?.runtime)) {
+ const controlError = minimaxH3ControlError({
+ model: effectiveModel,
+ negativePrompt: body.negativePrompt,
+ disableAudio: body.disableAudio,
+ tiling: body.tiling,
+ numFrames: body.numFrames ?? effectiveModel.defaultFrames,
+ fps: body.fps ?? 24,
+ });
+ if (controlError) {
await cleanupStaged();
- throw new ServerError(
- `MiniMax H3 runs at a fixed 24 fps; got ${fps}.`,
- { status: 400, code: 'MINIMAX_H3_INVALID_FPS' },
- );
+ throw controlError;
}
}
// Wan profiles have a narrower temporal-shape contract than the shared
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index a98a15b266..2c9f68bd18 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -17,6 +17,7 @@ import { PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { createSingleFlight } from '../../lib/singleFlight.js';
+import { MINIMAX_H3_RUNTIMES } from '../../lib/runners.js';
// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1
// scripts/setup-image-video.sh`. Used when a model entry has
@@ -49,6 +50,23 @@ export const MINIMAX_H3_EXPECTED_REVISION = 'fcd9e9b79a1d6018d91ac477c0968de1fa0
// untracked in the pin verification that both /status and the render helper run.
export const MINIMAX_H3_ENCODER_SHIM_DIR = join(homedir(), '.portos', 'minimax-h3-encoder-shims');
+// MiniMax H3 on CUDA — the diffusers `MiniMaxH3ModularPipeline` rather than a
+// pinned source checkout, so this runtime is a plain pip venv with no revision
+// to verify and no source package to keep clean.
+//
+// SHIPPED FOR WINDOWS. The venv itself is not win32-specific (which is why the
+// interpreter is resolved by venv layout below rather than assumed), but the
+// model catalog's platform axis is a macOS/Windows binary —
+// `getVideoModels()` is `IS_WIN ? video.windows : video.macos` — so a Linux
+// install is served the macOS/MLX list and cannot select this runtime's model
+// however well the venv provisions. Widening that axis is tracked in PLAN.md;
+// until then, do not advertise Linux support here or in the installer.
+export const MINIMAX_H3_CUDA_REPO_DIR = join(homedir(), '.portos', 'minimax-h3-cuda');
+export const MINIMAX_H3_CUDA_VENV_PYTHON = process.platform === 'win32'
+ ? join(MINIMAX_H3_CUDA_REPO_DIR, '.venv', 'Scripts', 'python.exe')
+ : join(MINIMAX_H3_CUDA_REPO_DIR, '.venv', 'bin', 'python3');
+export const MINIMAX_H3_CUDA_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_minimax_h3_cuda.py');
+
// HunyuanVideo MLX runtime — gaurav-nelson/HunyuanVideo_MLX cloned at
// ~/.portos/hunyuan-video-mlx/. ~60 GB resident at bf16 so practical only
// with the 4-bit Gemma text encoder + everything else evicted. Provisioned
@@ -106,6 +124,31 @@ export const BYOV_RUNTIME_INFO = Object.freeze({
loraProbeArgs: [MINIMAX_H3_LORA_PROBE_SCRIPT, MINIMAX_H3_REPO_DIR],
fingerprintPackages: ['mlx', 'mlx-metal', 'mlx-vlm', 'transformers', 'huggingface-hub'],
},
+ minimax_h3_cuda: {
+ id: 'minimax_h3_cuda',
+ label: 'MiniMax H3 CUDA',
+ venvPython: MINIMAX_H3_CUDA_VENV_PYTHON,
+ repoDir: MINIMAX_H3_CUDA_REPO_DIR,
+ installEnvVar: 'INSTALL_MINIMAX_H3_CUDA',
+ // Everything this runtime executes is an installed distribution, so there
+ // is no `expectedRevision` / `sourcePath` clean-checkout probe to run: the
+ // `==` set in scripts/requirements-minimax-h3-cuda.txt is the pin. `repoUrl`
+ // is therefore the integration's documentation rather than a clone source —
+ // there is no checkout under repoDir, only the venv.
+ repoUrl: 'https://huggingface.co/docs/diffusers/main/en/api/pipelines/minimax_h3',
+ // Three things must hold before a render is even attempted, and each fails
+ // as an unusable install rather than as a bad render: diffusers must carry
+ // the H3 modular integration (merged to main after v0.39.0 and in no tagged
+ // release yet, so a released wheel imports fine and then has no pipeline —
+ // which is why the requirements file pins a commit), torchao must be present
+ // (int8 weight-only is the only way the 133 GB bf16 pair fits a consumer
+ // card), and CUDA must actually be visible. A CPU-only torch is the trap
+ // here: it installs cleanly on Windows, hides the setup banner, and then
+ // renders a 33B model on the CPU.
+ importProbe: 'import torch; from diffusers import MiniMaxH3Transformer3DModel; from diffusers.modular_pipelines.minimax_h3 import MiniMaxH3ImageReference; import torchao; assert torch.cuda.is_available(), "no CUDA device"',
+ // Mirror scripts/generate_minimax_h3_cuda.py's emit_runtime_fingerprint list.
+ fingerprintPackages: ['torch', 'diffusers', 'transformers', 'torchao', 'accelerate', 'huggingface-hub'],
+ },
hunyuan: {
id: 'hunyuan',
label: 'HunyuanVideo MLX',
@@ -151,15 +194,31 @@ export const BYOV_RUNTIME_INFO = Object.freeze({
export const BYOV_VIDEO_RUNTIMES = Object.freeze(new Set(Object.keys(BYOV_RUNTIME_INFO)));
+// Does this model render through the legacy Windows helper, `generate_win.py`?
+// That script is the fallback `buildArgs` reaches only after every BYOV runtime
+// has declined, so the answer is "on win32, and not a BYOV runtime" — NOT the
+// bare `process.platform === 'win32'` this used to be spelled as at three
+// separate sites in local.js.
+//
+// The distinction became load-bearing the moment Windows gained a BYOV runtime
+// (MiniMax H3 CUDA): `generate_win.py` hardcodes its repo and reads only
+// `--image`, so the platform check was standing in for facts that are true of
+// that ONE script — it takes no repo id, and it never opens the last frame.
+// Applied to an H3 CUDA render those become wrong answers: it does require a
+// pinned repo, and it does anchor both keyframes.
+export const routesToWindowsHelper = (model) => process.platform === 'win32'
+ && !BYOV_VIDEO_RUNTIMES.has(model?.runtime);
+
// 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
+// both MiniMax H3 runtimes pack both frames as fl2va conditioning rows (the
+// anchoring is the checkpoint's, so the MLX and CUDA runners agree). 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 LAST_FRAME_ANCHORED_RUNTIMES = Object.freeze(new Set(['ltx2', ...MINIMAX_H3_RUNTIMES]));
export const modelAnchorsLastFrame = (model) => LAST_FRAME_ANCHORED_RUNTIMES.has(model?.runtime);
@@ -271,6 +330,15 @@ export function videoLoraUnsupportedError(model, modelId) {
{ status: 400, code: 'MINIMAX_H3_LORA_UNSUPPORTED' },
);
}
+ if (model?.runtime === 'minimax_h3_cuda') {
+ // Do NOT fall through to the LTX-2 suggestion below: those are macOS/MLX
+ // entries, and this runtime only appears in the Windows catalog, so the
+ // advice would name models the user cannot select.
+ return new ServerError(
+ `MiniMax H3 on CUDA cannot apply LoRAs. Model "${modelId}" renders through diffusers' MiniMaxH3ModularPipeline, which has no LoRA path for H3. No video model in the Windows catalog takes LoRAs today.`,
+ { status: 400, code: 'MINIMAX_H3_LORA_UNSUPPORTED' },
+ );
+ }
return new ServerError(
`LoRAs aren't supported on this model. Model "${modelId}" runs on "${model?.runtime || 'mlx_video'}" — use an LTX-2.x model (dgrauet ltx2, or the bf16 Unified Beta).`,
{ status: 400, code: 'LORAS_REQUIRE_LTX2' },
diff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.js
index 18360b8f4b..0b6978e100 100644
--- a/server/services/videoGen/runtimes.test.js
+++ b/server/services/videoGen/runtimes.test.js
@@ -16,6 +16,7 @@ vi.mock('child_process', async (importOriginal) => ({
}));
import {
+ BYOV_RUNTIME_INFO, BYOV_VIDEO_RUNTIMES,
byovRuntimeLoraCapable, invalidateByovLoraCapabilityCache, invalidateByovReadyCache,
isByovRuntimeReady, isPinnedSourceStatusClean, modelAnchorsLastFrame,
resolveByovRuntimeLoraCapable,
@@ -149,6 +150,9 @@ describe('modelAnchorsLastFrame', () => {
it.each([
['ltx2', true],
['minimax_h3', true],
+ // Anchoring is a property of the fl2va checkpoint, not of the runner in
+ // front of it, so the CUDA path must agree with the MLX one.
+ ['minimax_h3_cuda', true],
['mlx_video', false],
['wan22', false],
['hunyuan', false],
@@ -161,3 +165,52 @@ describe('modelAnchorsLastFrame', () => {
expect(modelAnchorsLastFrame({})).toBe(false);
});
});
+
+describe('minimax_h3_cuda runtime registration', () => {
+ const info = BYOV_RUNTIME_INFO.minimax_h3_cuda;
+
+ it('is a BYOV runtime with its own venv, distinct from the MLX port', () => {
+ expect(BYOV_VIDEO_RUNTIMES.has('minimax_h3_cuda')).toBe(true);
+ expect(info.installEnvVar).toBe('INSTALL_MINIMAX_H3_CUDA');
+ // Sharing a venv with the MLX port would let one install's `pip sync`
+ // silently uninstall the other's packages.
+ expect(info.venvPython).not.toBe(BYOV_RUNTIME_INFO.minimax_h3.venvPython);
+ expect(info.repoDir).not.toBe(BYOV_RUNTIME_INFO.minimax_h3.repoDir);
+ });
+
+ it('resolves the interpreter by venv layout, not by platform name', () => {
+ // A Windows venv puts python under Scripts\, a POSIX one under bin/. This
+ // is the whole reason the constant can't be the MLX port's bin/python3
+ // literal — that path never exists on the platform this runtime targets.
+ const expected = process.platform === 'win32'
+ ? ['Scripts', 'python.exe']
+ : ['bin', 'python3'];
+ for (const part of expected) expect(info.venvPython).toContain(part);
+ });
+
+ it('probes for CUDA and the H3 integration, not merely for an importable diffusers', () => {
+ // Each of these is a distinct way the install can look complete and not be:
+ // a CPU-only torch wheel, a diffusers release predating PR #14355, or a
+ // missing torchao (int8 is what makes the 133 GB bf16 pair fit at all).
+ expect(info.probeArgs).toBeUndefined();
+ expect(info.importProbe).toContain('MiniMaxH3Transformer3DModel');
+ expect(info.importProbe).toContain('torchao');
+ expect(info.importProbe).toContain('torch.cuda.is_available()');
+ });
+
+ it('declares no revision pin or LoRA probe — it runs distributions, not a checkout', () => {
+ // `expectedRevision`/`sourcePath` drive the clean-checkout gate, which has
+ // nothing to verify here; `loraProbeArgs` absent is the correct "this
+ // runtime can never take LoRAs", matching wan22 / hunyuan.
+ expect(info.expectedRevision).toBeUndefined();
+ expect(info.sourcePath).toBeUndefined();
+ expect(info.loraProbeArgs).toBeUndefined();
+ });
+
+ it('never reports LoRA capability, even after a probe attempt', async () => {
+ expect(byovRuntimeLoraCapable('minimax_h3_cuda')).toBe(false);
+ await expect(resolveByovRuntimeLoraCapable('minimax_h3_cuda')).resolves.toBe(false);
+ // No probe child may be spawned for a runtime with no loraProbeArgs.
+ expect(runtimeMocks.spawn).not.toHaveBeenCalled();
+ });
+});