Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: MiniMax-H3 follow-ups from the 7989 review (#8280)

Daniel Han300ff262b713
diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.py
index 1d96757f7ca..57ebf02641b 100644
--- a/studio/backend/core/inference/sd_cpp_args.py
+++ b/studio/backend/core/inference/sd_cpp_args.py
@@ -410,9 +410,12 @@ def build_sd_cpp_video_command(
cmd += [f for f in metal_text_encoder_flags() if f not in offload]
if verbose:
cmd.append("-v")
- for flag in list(extra_args or []):
- if flag not in cmd:
- cmd.append(flag)
+ # Appended verbatim, like every sibling builder: sd.cpp's parser is last-wins, so a power user
+ # can override anything. Token-wise de-duplication broke that contract on any flag that takes a
+ # value, since it drops the token that already appears earlier: ["--rng", "cuda"] lost --rng and
+ # left a bare "cuda" for the parser to choke on.
+ if extra_args:
+ cmd += list(extra_args)
return cmd
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 589019d8d4c..b2750a091c1 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -983,6 +983,7 @@ class VideoBackend:
kind,
te_sources = te_sources,
skip_transformer_weights = skip_transformer_weights,
+ h3_task = kwargs.get("h3_task"),
h3_te_scheme = h3_te_scheme,
)
with self._lock:
@@ -1064,6 +1065,9 @@ class VideoBackend:
ltx23 = ltx23,
skip_te_components = te_skipped + h3_te_skipped,
skip_transformer_weights = skip_transformer_weights,
+ # Picks the H3 denoiser partition: fl2va stages transformer/, ref2va stages the
+ # separate 66.28 GB transformer_ref/ that load_components(workflow="ref2va") opens.
+ h3_task = kwargs.get("h3_task"),
cancel_event = cancel_event,
)
# The 2.3 assembly pulls per component from the hub id (its snapshot lacks the base VAEs), so it only gets the warmed cache.
@@ -1126,7 +1130,7 @@ class VideoBackend:
qwen_filename = h3_text_encoder_filename(filename)
requests = (
(repo_id, filename),
- (H3_GGUF_REPO, qwen_filename),
+ (self._h3_text_encoder_repo(repo_id, qwen_filename), qwen_filename),
(H3_COMPONENT_REPO, H3_VIDEO_VAE),
(H3_COMPONENT_REPO, H3_AUDIO_VAE),
)
@@ -1633,6 +1637,7 @@ class VideoBackend:
ltx23: bool = False,
skip_te_components: tuple[str, ...] = (),
skip_transformer_weights: bool = False,
+ h3_task: Optional[str] = None,
) -> list[tuple[str, int]]:
"""The (rfilename, size) list a load actually needs from the base repo.
@@ -1656,11 +1661,22 @@ class VideoBackend:
denoiser checkpoint (H3's transformer is 66.3 GB of its base repo).
``transformer/config.json`` is kept for the same reason the pre-cast
encoders keep theirs: the pre-quant loader meta-inits the DiT from it,
- so dropping it would break the very load that made the skip safe."""
+ so dropping it would break the very load that made the skip safe.
+
+ ``h3_task`` picks the H3 denoiser partition. The base repo ships two, and a load only ever
+ brings up one: ``transformer/`` for fl2va (which also covers text-only) and
+ ``transformer_ref/`` for ref2va. They are 66.28 GB each, so the scoped list carries exactly
+ one of them, never both."""
from .diffusion_te_prequant import is_prequant_covered_weight
+ from .video_minimax_h3 import H3_TASK_REFERENCES
siblings = list(info.siblings or [])
is_h3_modular = any(s.rfilename == "modular_model_index.json" for s in siblings)
+ h3_denoiser_prefix = (
+ "transformer_ref/"
+ if (h3_task or "").strip().lower() == H3_TASK_REFERENCES
+ else "transformer/"
+ )
h3_prefixes = (
"audio_scheduler/",
"audio_vae/",
@@ -1668,7 +1684,7 @@ class VideoBackend:
"scheduler/",
"text_encoder/",
"tokenizer/",
- "transformer/",
+ h3_denoiser_prefix,
"vae/",
)
files: list[tuple[str, int]] = []
@@ -1709,6 +1725,7 @@ class VideoBackend:
ltx23: bool = False,
te_sources: Optional[dict[str, Any]] = None,
skip_transformer_weights: bool = False,
+ h3_task: Optional[str] = None,
h3_te_scheme: Optional[str] = None,
) -> Optional[int]:
"""Total bytes this load will pull (checkpoint + companions), or None.
@@ -1742,6 +1759,7 @@ class VideoBackend:
ltx23 = ltx23,
skip_te_components = skip_te_components,
skip_transformer_weights = skip_transformer_weights,
+ h3_task = h3_task,
)
)
return total or None
@@ -1759,6 +1777,7 @@ class VideoBackend:
hf_token: Optional[str] = None,
transformer_quant: Optional[str] = None,
text_encoder_quant: Optional[str] = None,
+ h3_task: Optional[str] = None,
**load_kwargs: Any,
) -> dict[str, Any]:
"""The repos + exact files this pick needs, for staging through the Hub download
@@ -1773,7 +1792,11 @@ class VideoBackend:
``transformer_quant`` is read for the mirror-image reason on the denoiser: a scheme with a
hosted PRE-QUANTIZED checkpoint replaces the dense DiT, so staging those shards would cost
66.3 GB the load never opens. It used to be swallowed by ``**load_kwargs`` and the plan
- stayed dense-sized."""
+ stayed dense-sized.
+
+ ``h3_task`` picks which MiniMax-H3 denoiser partition is staged. It was swallowed by
+ ``**load_kwargs`` too, so a ref2va plan staged the fl2va ``transformer/`` and left the
+ 66.28 GB ``transformer_ref/`` the load then needs to be pulled inline."""
from huggingface_hub import HfApi
fam = _detect_load_family(repo_id, gguf_filename, family_override)
@@ -1917,6 +1940,7 @@ class VideoBackend:
skip_transformer_weights = self._denoiser_prequant_covered(
fam, transformer_quant, base
),
+ h3_task = h3_task,
),
revision = getattr(info, "sha", None),
# A pipeline pick has no single file: the base IS the selected model (base =
@@ -1970,6 +1994,25 @@ class VideoBackend:
"checkpoint_bytes": int(checkpoint_bytes),
}
+ @staticmethod
+ def _h3_text_encoder_repo(repo_id: str, qwen_filename: str) -> str:
+ """Which repo the H3 native text encoder comes from, preferring a local bundle.
+
+ The GGUF bundle ships the Qwen encoder beside the denoiser partitions, so when the pick is
+ a LOCAL clone of it the encoder is already on disk. Hardcoding the Hub repo instead would
+ re-fetch multiple GB that are sitting next to the checkpoint, and fail outright offline."""
+ from .video_minimax_h3 import H3_GGUF_REPO
+
+ root = Path(repo_id).expanduser()
+ if root.is_dir():
+ from .diffusion_families import resolve_local_gguf_child
+ try:
+ resolve_local_gguf_child(root, qwen_filename)
+ except Exception: # noqa: BLE001 -- not in the local clone, so the Hub copy it is
+ return H3_GGUF_REPO
+ return repo_id
+ return H3_GGUF_REPO
+
@staticmethod
def _h3_native_download_plan(
repo_id: str, gguf_filename: str, *, hf_token: Optional[str]
@@ -1979,7 +2022,6 @@ class VideoBackend:
from .video_minimax_h3 import (
H3_AUDIO_VAE,
H3_COMPONENT_REPO,
- H3_GGUF_REPO,
H3_VIDEO_VAE,
h3_text_encoder_filename,
validate_h3_transformer_filename,
@@ -1987,9 +2029,10 @@ class VideoBackend:
from core.inference.diffusion import DiffusionBackend
validate_h3_transformer_filename(gguf_filename)
+ qwen_filename = h3_text_encoder_filename(gguf_filename)
wanted = (
(repo_id, gguf_filename),
- (H3_GGUF_REPO, h3_text_encoder_filename(gguf_filename)),
+ (VideoBackend._h3_text_encoder_repo(repo_id, qwen_filename), qwen_filename),
(H3_COMPONENT_REPO, H3_VIDEO_VAE),
(H3_COMPONENT_REPO, H3_AUDIO_VAE),
)
@@ -2124,6 +2167,7 @@ class VideoBackend:
ltx23: bool = False,
skip_te_components: tuple[str, ...] = (),
skip_transformer_weights: bool = False,
+ h3_task: Optional[str] = None,
cancel_event: Optional[threading.Event] = None,
) -> Optional[str]:
"""Pull exactly the base-repo files the load needs; return the local snapshot dir.
@@ -2148,6 +2192,7 @@ class VideoBackend:
ltx23 = ltx23,
skip_te_components = skip_te_components,
skip_transformer_weights = skip_transformer_weights,
+ h3_task = h3_task,
)
if not any(name == "model_index.json" for name, _ in files):
return None
@@ -3307,9 +3352,14 @@ class VideoBackend:
memory_mode = memory_mode,
scheme = None,
)
+ # cache_dir is passed here too, for the same reason the token is: load_components forwards
+ # its extra kwargs through ComponentSpec.load into each component's from_pretrained, and
+ # without it those ~145 GB of Hub-pinned components resolve against the HF_HUB_CACHE snapshot
+ # taken at import time rather than Studio's live cache folder, which the user can move.
pipe.load_components(
workflow = workflow,
dtype = dtype,
+ cache_dir = hub_cache_dir(),
**({"token": hf_token} if hf_token else {}),
)
# The video VAE loads at float32 and the decode runs under float16 autocast, so both
@@ -3757,6 +3807,11 @@ class VideoBackend:
)
steps = int(steps or default_steps)
guidance = float(default_guidance if guidance is None else guidance)
+ if not fam.supports_cfg:
+ # A CFG-free family never reads this number: diffusers gets no guidance kwarg
+ # and the native path pins cfg_scale to 1.0. Clamp it here so the recipe cannot
+ # record a guidance that did not run.
+ guidance = float(fam.default_guidance)
shift, audio_shift = self._resolve_flow_shifts(
fam, state.engine, flow_shift, audio_flow_shift
)
@@ -4399,6 +4454,15 @@ class VideoBackend:
"flow_shift": flow_shift,
# sd.cpp pins the audio schedule, so the recipe records what it actually ran.
"audio_flow_shift": state.family.default_audio_flow_shift,
+ # The BUILD this clip came off, read from the ENGAGED state and never from the
+ # request, exactly as the diffusers path records it. Without these six the
+ # sidecar of every native GGUF clip saves a blank recipe.
+ "model_kind": state.kind,
+ "gguf_filename": state.gguf_filename,
+ "transformer_quant": state.transformer_quant,
+ "text_encoder_quant": state.text_encoder_quant,
+ "memory_mode": state.memory_mode,
+ "offload_policy": state.offload_policy,
}
finally:
output_path.unlink(missing_ok = True)
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index c3864982f1d..85eb8459482 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -486,6 +486,14 @@ def validate_video_request_shape(
step = max(1, fam.frame_step)
offset = max(1, fam.frame_offset)
count = int(num_frames)
+ # The window the family declares it was trained for. Hoisted out of the lattice branch
+ # because it is also enforced below: it used to exist only to WORD the lattice error
+ # ("supported counts run from 124 to 345") while a request outside it was accepted and
+ # silently snapped, so num_frames=5 rendered 124 frames and num_frames=872 rendered 345.
+ ceiling = MAX_VIDEO_NUM_FRAMES
+ if fam.max_num_frames is not None:
+ ceiling = min(ceiling, int(fam.max_num_frames))
+ floor = max(offset, int(fam.min_num_frames))
if count < offset or (count - offset) % step != 0:
# The two lattice points straddling the request say more than a prefix of the lattice would,
# and stay short. Computed from the lattice rather than via snap_num_frames, which floors for
@@ -494,10 +502,6 @@ def validate_video_request_shape(
above = below + step
# Only name a point the caller could actually load: past the request model's own `le`, or
# outside this family's declared range, it answers with a second, differently-shaped 422.
- ceiling = MAX_VIDEO_NUM_FRAMES
- if fam.max_num_frames is not None:
- ceiling = min(ceiling, int(fam.max_num_frames))
- floor = max(offset, int(fam.min_num_frames))
loadable = [n for n in (below, above) if floor <= n <= ceiling]
if len(loadable) == 2:
nearest = f"the nearest supported counts are {loadable[0]} and {loadable[1]}"
@@ -511,6 +515,15 @@ def validate_video_request_shape(
f"{step}, so a frame count must be k * {step} + {offset}; {nearest} "
f"(the default is {fam.default_num_frames})."
)
+ # On the lattice but outside the trained window. The request model bounds num_frames at
+ # 1..1024, so a count well under the floor or well over the ceiling arrives here and used
+ # to be snapped in silence, which on the native path is a 25x compute surprise.
+ if count < floor or count > ceiling:
+ raise VideoShapeError(
+ f"{count} is not a supported frame count for {fam.name}. "
+ f"Supported counts run from {floor} to {ceiling} "
+ f"(the default is {fam.default_num_frames})."
+ )
# Default (steps, guidance) per checkpoint variant, matched by substring (picked id then base repo), most specific first.
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 006d653236e..1886f650523 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -118,6 +118,11 @@ async def video_download_plan(
# pre-quantized checkpoint has to be refused HERE, on the route that stages the
# download, or the panel fetches ~98.7 GB before /video/load can say no.
transformer_quant = request.transformer_quant,
+ # And the partition, because one of those quant-keyed refusals is task-keyed: the
+ # hosted pre-quantized H3 checkpoints are fl2va denoisers, so a quantized ref2va is
+ # rejected. /video/load passes this and refuses; without it here the plan below staged
+ # the 66 GB dense transformer_ref/ AND the incompatible fl2va quant first.
+ h3_task = request.h3_task,
)
# BEFORE the plan is staged, as on the images side: /video/load refuses a precision this
# host cannot honour, but the UI plans and downloads first, so an explicit FP8 on an
@@ -149,6 +154,10 @@ async def video_download_plan(
# checkpoint replaces the dense DiT, so without this the plan stages 66.3 GB of shards
# the load never opens.
transformer_quant = request.transformer_quant,
+ # And the MiniMax-H3 partition, because the two denoisers live in separate 66.28 GB
+ # subfolders: a ref2va load opens transformer_ref/, which the plan would otherwise
+ # miss entirely while staging the fl2va transformer/ it never opens.
+ h3_task = request.h3_task,
)
return DiffusionDownloadPlanResponse(**plan)
except (ValueError, FileNotFoundError) as exc:
diff --git a/studio/backend/tests/test_sd_cpp_args.py b/studio/backend/tests/test_sd_cpp_args.py
index 763024f0be5..4bfece5afad 100644
--- a/studio/backend/tests/test_sd_cpp_args.py
+++ b/studio/backend/tests/test_sd_cpp_args.py
@@ -628,6 +628,39 @@ def test_minimax_h3_video_command_has_all_joint_av_components():
assert cmd[-2:] == ["--diffusion-fa", "--offload-to-cpu"]
+def test_video_build_appends_extra_args_verbatim_and_last():
+ """The video mirror of the image builder's last-wins contract.
+
+ Token-wise de-duplication cannot express an override: the builder already sets --rng cpu, so
+ extra_args ["--rng", "cuda"] dropped the --rng it matched and appended a bare "cuda" for the
+ parser to choke on. Every sibling builder in this module appends the list verbatim.
+ """
+ files = SdCppModelFiles(
+ diffusion_model = "/m/minimax_h3_fl2va-Q4_K_M.gguf",
+ vae = "/m/video.safetensors",
+ audio_vae = "/m/audio.safetensors",
+ llm = "/m/qwen.gguf",
+ )
+ cmd = build_sd_cpp_video_command(
+ "/bin/sd-cli",
+ files,
+ SdCppVideoGenParams(
+ prompt = "a fox runs through snow",
+ width = 960,
+ height = 544,
+ num_frames = 124,
+ fps = 24,
+ seed = 1,
+ ),
+ output_path = "/o.webm",
+ extra_args = ["--rng", "cuda"],
+ )
+ assert cmd[-2:] == ["--rng", "cuda"]
+ assert cmd[-1] != "cuda" or cmd[-2] == "--rng"
+ # Studio's own value is still there, earlier, so sd.cpp's last-wins parser takes the override.
+ assert cmd.count("--rng") == 2
+
+
def _h3_video_cmd(**params):
return build_sd_cpp_video_command(
"/bin/sd-cli",
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 477e548c6fa..6f7c5686d0c 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -1933,6 +1933,53 @@ def test_base_download_files_gguf_drops_transformer():
assert "text_encoder/model-00001-of-00002.safetensors" in names
+_H3_SIBLINGS = [
+ _sibling("model_index.json", 10),
+ _sibling("modular_model_index.json", 10),
+ _sibling("transformer/config.json", 1),
+ _sibling("transformer/diffusion_pytorch_model-00001-of-00002.safetensors", 33),
+ _sibling("transformer/diffusion_pytorch_model-00002-of-00002.safetensors", 33),
+ _sibling("transformer_ref/config.json", 1),
+ _sibling("transformer_ref/diffusion_pytorch_model-00001-of-00002.safetensors", 33),
+ _sibling("transformer_ref/diffusion_pytorch_model-00002-of-00002.safetensors", 33),
+ _sibling("text_encoder/model-00001-of-00001.safetensors", 15),
+ _sibling("tokenizer/chat_template.jinja", 1),
+ _sibling("vae/diffusion_pytorch_model.safetensors", 3),
+ _sibling("audio_vae/diffusion_pytorch_model.safetensors", 1),
+ _sibling("scheduler/scheduler_config.json", 1),
+ _sibling("audio_scheduler/scheduler_config.json", 1),
+ _sibling("processor/preprocessor_config.json", 1),
+]
+
+
+def test_base_download_files_stages_the_h3_partition_the_load_will_open():
+ """H3 ships two denoisers in separate subfolders, 66.28 GB each, and a load opens one.
+
+ ref2va reads transformer_ref/, which the scoped list left out entirely, so a reference load
+ staged the wrong 66.28 GB and then pulled the right ones inline, outside the download panel.
+ Both partitions must never be staged at once either: that is the whole 132 GB.
+ """
+ info = types.SimpleNamespace(siblings = _H3_SIBLINGS)
+
+ keyframes = [n for n, _ in VideoBackend._base_download_files(info, "pipeline")]
+ assert "transformer/diffusion_pytorch_model-00001-of-00002.safetensors" in keyframes
+ assert not any(n.startswith("transformer_ref/") for n in keyframes)
+
+ references = [
+ n for n, _ in VideoBackend._base_download_files(info, "pipeline", h3_task = "ref2va")
+ ]
+ assert "transformer_ref/diffusion_pytorch_model-00001-of-00002.safetensors" in references
+ assert "transformer_ref/diffusion_pytorch_model-00002-of-00002.safetensors" in references
+ assert not any(n.startswith("transformer/") for n in references)
+ # Everything shared still comes along on both.
+ for shared in (
+ "model_index.json",
+ "text_encoder/model-00001-of-00001.safetensors",
+ "vae/diffusion_pytorch_model.safetensors",
+ ):
+ assert shared in keyframes and shared in references
+
+
def test_load_progress_clamps_overshoot(fake_runtime, monkeypatch):
# The cache scan counts blobs a broader previous pull left behind, so the counter must never exceed the scoped estimate.
backend = VideoBackend()
@@ -2421,6 +2468,50 @@ def test_h3_native_download_plan_stages_the_complete_runtime(monkeypatch):
}
+def test_h3_native_uses_the_local_bundles_own_text_encoder(monkeypatch, tmp_path):
+ """A local clone of the H3 GGUF bundle ships the encoder beside the denoisers.
+
+ Hardcoding the Hub repo for the encoder re-fetches multiple GB that are already on disk next
+ to the picked checkpoint, and fails outright with no network. The denoiser was resolved
+ locally and the encoder was not, from the same directory.
+ """
+ local = tmp_path / "MiniMax-H3-GGUF"
+ local.mkdir()
+ (local / "minimax_h3_fl2va-Q4_K_M.gguf").write_bytes(b"x")
+ (local / "qwen3vl_32b_minimax_h3-Q4_K_M.gguf").write_bytes(b"x")
+
+ assert VideoBackend._h3_text_encoder_repo(
+ str(local), "qwen3vl_32b_minimax_h3-Q4_K_M.gguf"
+ ) == str(local)
+ # A clone WITHOUT the encoder still falls back to the hosted copy, so nothing regresses.
+ bare = tmp_path / "bare"
+ bare.mkdir()
+ assert (
+ VideoBackend._h3_text_encoder_repo(str(bare), "qwen3vl_32b_minimax_h3-Q4_K_M.gguf")
+ == "unsloth/MiniMax-H3-GGUF"
+ )
+
+ # And the plan stages only the VAEs: both halves of the local bundle are already on disk.
+ _plan_api(
+ monkeypatch,
+ {
+ "unsloth/MiniMax-H3-GGUF": [
+ _PlanSibling("minimax_h3_fl2va-Q4_K_M.gguf", 19),
+ _PlanSibling("qwen3vl_32b_minimax_h3-Q4_K_M.gguf", 18),
+ ],
+ "Comfy-Org/MiniMax-H3": [
+ _PlanSibling("vae/minimax_h3_video_vae_fp16.safetensors", 5),
+ _PlanSibling("vae/minimax_h3_audio_vae_fp32.safetensors", 1),
+ ],
+ },
+ )
+ plan = VideoBackend._h3_native_download_plan(
+ str(local), "minimax_h3_fl2va-Q4_K_M.gguf", hf_token = None
+ )
+ assert [entry["repo_id"] for entry in plan["entries"]] == ["Comfy-Org/MiniMax-H3"]
+ assert plan["total_bytes"] == 6
+
+
_H3_BASE_SIBLINGS = [
_PlanSibling("transformer/config.json", 1),
_PlanSibling("transformer/diffusion_pytorch_model-00001-of-00002.safetensors", 40),
@@ -3034,6 +3125,54 @@ def test_h3_modular_load_forwards_the_hub_token_to_the_component_loads(fake_runt
assert "token" not in pipe.load_kwargs
+def test_h3_modular_load_pins_the_component_loads_to_the_studio_cache(fake_runtime):
+ """The component from_pretrained calls need the same cache_dir the index load got.
+
+ load_components forwards its extra kwargs through ComponentSpec.load into each component's
+ from_pretrained. Without cache_dir those ~145 GB of Hub-pinned components resolve against the
+ HF_HUB_CACHE snapshot taken at import time, while the scoped pre-download stages into the
+ cache folder Studio currently points at, and the two really can differ (it is a live setting).
+ """
+ from core.inference.video import hub_cache_dir
+
+ pipe = _load_h3_modular(VideoBackend())
+ assert _FakeModularPipeline.last["cache_dir"] == hub_cache_dir()
+ assert pipe.load_kwargs["cache_dir"] == hub_cache_dir()
+
+
+def test_h3_modular_load_refuses_a_text_encoder_quant_it_cannot_honour(fake_runtime):
+ """An explicit text_encoder_quant the modular path cannot honour must RAISE.
+
+ This started life asserting the weaker contract: record the request so a decline reads as
+ FELL_BACK rather than vanishing into a backend-owned row stamped requested=null / APPLIED.
+ #8283 went further and made the modular encoder path fail closed, matching what the
+ conventional path already did, so an unhonourable explicit request never reaches a load at
+ all. That subsumes the original concern -- a request cannot be silently dropped from a run
+ that does not happen -- so this pins the refusal, and the reason, instead.
+ """
+ backend = VideoBackend()
+ diffusers = sys.modules["diffusers"]
+ diffusers.ComponentsManager = _FakeComponentsManager
+ diffusers.ModularPipeline = _FakeModularPipeline
+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")
+ with pytest.raises(RuntimeError, match = "text_encoder_quant='fp8' could not be used"):
+ backend._load_h3_modular_pipeline(
+ diffusers = diffusers,
+ torch = sys.modules["torch"],
+ fam = fam,
+ repo_id = "MiniMaxAI/MiniMax-H3",
+ base = fam.base_repo,
+ kind = "pipeline",
+ dtype = sys.modules["torch"].bfloat16,
+ device = "cpu",
+ hf_token = None,
+ memory_mode = None,
+ text_encoder_quant = "fp8",
+ _load_token = None,
+ _base_local_dir = None,
+ )
+
+
def test_h3_modular_generation_ticks_and_cancels_through_the_scheduler(fake_runtime):
backend = VideoBackend()
pipe = _load_h3_modular(backend)
@@ -4157,6 +4296,50 @@ def test_h3_omitted_size_takes_the_canvas_from_the_keyframe(monkeypatch):
assert (calls[-1]["params"].width, calls[-1]["params"].height) == (1344, 768)
+def test_h3_native_clip_records_the_build_it_came_off(monkeypatch):
+ """A native GGUF clip must carry the same build record as the diffusers twin.
+
+ _run_generate copies model_kind / gguf_filename / transformer_quant / text_encoder_quant /
+ memory_mode / offload_policy out of the result into the saved sidecar, so if the native return
+ dict omits them every native clip saves a blank recipe and the gallery shows nothing.
+ """
+ calls: list = []
+ backend = _h3_native_backend(monkeypatch, calls)
+ import dataclasses
+
+ backend._state = dataclasses.replace(
+ backend._state,
+ transformer_quant = "fp8",
+ text_encoder_quant = "int8",
+ memory_mode = "low",
+ offload_policy = "model",
+ )
+
+ result = backend.generate(prompt = "p", width = 960, height = 544)
+
+ assert result["model_kind"] == "gguf"
+ assert result["gguf_filename"] == "minimax_h3_fl2va-Q4_K_M.gguf"
+ assert result["transformer_quant"] == "fp8"
+ assert result["text_encoder_quant"] == "int8"
+ assert result["memory_mode"] == "low"
+ assert result["offload_policy"] == "model"
+
+
+def test_a_cfg_free_family_records_the_guidance_it_actually_ran(monkeypatch):
+ """H3 has no CFG, so a requested guidance must not reach the recipe.
+
+ The native path pins cfg_scale to 1.0 and the diffusers path passes no guidance kwarg at all,
+ so recording the caller's number would label the clip with a scale that never ran.
+ """
+ calls: list = []
+ backend = _h3_native_backend(monkeypatch, calls)
+
+ result = backend.generate(prompt = "p", width = 960, height = 544, guidance = 7.0)
+
+ assert result["guidance"] == 1.0
+ assert calls[-1]["params"].cfg_scale == 1.0
+
+
def test_keyframes_are_refused_by_a_family_that_has_none(fake_runtime, tmp_path):
# Silently dropping the image would render a text-only clip with nothing to do with it.
backend = VideoBackend()
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index f3dbd086284..263842685c8 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -460,6 +460,33 @@ def test_generate_happy_path_persists_and_reports_record(client):
assert fetched.content == b"MP4-FAKE-BYTES"
+def test_generate_accepts_a_half_specified_size_without_a_keyframe(client):
+ """Half a canvas is only ambiguous next to a keyframe, so the route must still take it.
+
+ validate_video_request_shape has always resolved a missing axis against the family's default
+ preset (768 alone means 768x512 on LTX-2) and that behaviour is pinned at the family level, so
+ a request-model XOR that fires with no keyframe present makes the two layers disagree and
+ breaks the half-spec case for every video family through the API.
+ """
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+
+ video = _generate_and_wait(client, {"prompt": "a cat", "width": 768})
+ assert (video["width"], video["height"]) == (768, 512)
+
+ # With a keyframe the ambiguity is real and the refusal stands.
+ resp = client.post(
+ "/api/inference/video/generate",
+ json = {
+ "prompt": "a cat",
+ "width": 768,
+ "first_frame": "data:image/png;base64,AAAA",
+ },
+ )
+ assert resp.status_code == 422
+ assert "width and height must be sent together" in str(resp.json())
+
+
def test_generate_without_load_returns_409(client):
resp = client.post("/api/inference/video/generate", json = {"prompt": "p"})
assert resp.status_code == 409
@@ -1205,6 +1232,37 @@ def test_video_download_plan_forwards_the_denoiser_policy(client, monkeypatch):
assert seen["transformer_quant"] == "int8"
+def test_video_download_plan_forwards_the_h3_partition(client, monkeypatch):
+ # h3_task decides WHICH of the two 66.28 GB MiniMax-H3 denoiser folders is staged. It was
+ # swallowed by **load_kwargs, so a ref2va plan staged the fl2va partition and the one the load
+ # actually opens came down inline, outside the download panel's preflight.
+ backend = video_module.get_video_backend()
+ seen: dict = {}
+
+ def _plan(model_path, **kwargs):
+ seen["model_path"] = model_path
+ seen.update(kwargs)
+ return {"entries": [], "total_bytes": 0}
+
+ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)
+ monkeypatch.setattr(
+ video_module, "assert_video_precision_available", lambda fam, **kw: None, raising = False
+ )
+
+ resp = client.post(
+ "/api/inference/video/download-plan",
+ json = {
+ "model_path": "unsloth/MiniMax-H3",
+ "model_kind": "pipeline",
+ "family_override": "minimax-h3",
+ "h3_task": "ref2va",
+ },
+ )
+
+ assert resp.status_code == 200, resp.json()
+ assert seen["h3_task"] == "ref2va"
+
+
def test_video_download_plan_refuses_an_unsupported_combination_before_staging(client, monkeypatch):
# The whole point of moving the refusal into validation: this pick used to return a 200 plan,
# stage ~98.7 GB, and only then fail inside the loader. Runs the REAL validation rather than
@@ -1268,6 +1326,87 @@ def test_video_download_plan_refuses_an_unavailable_transformer_quant(client, mo
assert "nvfp4" in resp.json()["detail"]
+def test_video_download_plan_refuses_a_quantized_reference_task(client, monkeypatch):
+ # One of the quant-keyed refusals is task-keyed: the hosted pre-quantized H3 checkpoints are
+ # fl2va denoisers, so a quantized ref2va would seed the wrong partition. Validation only sees
+ # that when the route forwards h3_task, and this is the route that stages the download -- so
+ # without it the plan pulls the 66 GB dense transformer_ref/ AND the incompatible fl2va quant
+ # before /video/load rejects the identical request.
+ backend = video_module.get_video_backend()
+ monkeypatch.setattr(
+ backend,
+ "validate_load_request",
+ video_module.VideoBackend.validate_load_request.__get__(backend),
+ raising = False,
+ )
+ monkeypatch.setattr(
+ backend,
+ "download_plan",
+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("must not be reached")),
+ raising = False,
+ )
+
+ resp = client.post(
+ "/api/inference/video/download-plan",
+ json = {
+ "model_path": "MiniMaxAI/MiniMax-H3",
+ "model_kind": "pipeline",
+ "transformer_quant": "fp8",
+ "h3_task": "ref2va",
+ },
+ )
+
+ assert resp.status_code == 400
+ detail = resp.json()["detail"]
+ assert "fp8" in detail
+ # Naming the way out, not just the dead end.
+ assert "keyframe" in detail
+
+
+def test_video_download_plan_hands_the_h3_task_to_validation(client, monkeypatch):
+ # The other side of the same gate. The refusal above would still pass if a refactor dropped
+ # the forwarding and something else happened to reject that pick, so assert the forwarding
+ # itself -- and that fl2va, which is exactly what the hosted checkpoints are, still plans.
+ #
+ # Validation is stubbed rather than real here because its later transformer_class probe
+ # imports the family's diffusers module, which is an environment question and not this
+ # test's; the negative case above exercises the real validator, since the ref2va refusal
+ # fires before that probe.
+ backend = video_module.get_video_backend()
+ fam = video_module._detect_load_family("MiniMaxAI/MiniMax-H3", None, None)
+ assert fam is not None
+ seen: dict = {}
+
+ def _validate(model_path, **kwargs):
+ seen["validate"] = kwargs
+ return fam
+
+ def _plan(model_path, **kwargs):
+ seen["plan"] = kwargs
+ return {"files": [], "total_bytes": 0, "cached_bytes": 0}
+
+ monkeypatch.setattr(backend, "validate_load_request", _validate, raising = False)
+ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)
+ monkeypatch.setattr(
+ video_module, "assert_video_precision_available", lambda *a, **k: None, raising = False
+ )
+
+ resp = client.post(
+ "/api/inference/video/download-plan",
+ json = {
+ "model_path": "MiniMaxAI/MiniMax-H3",
+ "model_kind": "pipeline",
+ "transformer_quant": "fp8",
+ "h3_task": "fl2va",
+ },
+ )
+
+ assert resp.status_code == 200, resp.text
+ assert seen["validate"]["h3_task"] == "fl2va"
+ assert seen["validate"]["transformer_quant"] == "fp8"
+ assert seen["plan"]["h3_task"] == "fl2va"
+
+
def test_the_training_guard_runs_before_the_precision_probe(client, monkeypatch):
# The precision gate's support check quantises a real Linear on the GPU and synchronises, so
# running it first initialises a CUDA context and allocates next to the training subprocess
diff --git a/studio/backend/tests/test_video_shape_validation.py b/studio/backend/tests/test_video_shape_validation.py
index 3e291b216d6..9a595df613f 100644
--- a/studio/backend/tests/test_video_shape_validation.py
+++ b/studio/backend/tests/test_video_shape_validation.py
@@ -161,6 +161,30 @@ def test_a_suggested_count_never_falls_outside_the_family_range():
assert "supported counts run from 124 to 345" in str(excinfo.value)
+def test_the_frame_gate_enforces_the_range_it_names():
+ """A lattice point outside the family's trained window is refused, not snapped.
+
+ The gate already computed the floor and the ceiling to WORD its lattice error, then accepted
+ counts outside them: 5, 90 and 107 are all real 17k + 5 points below H3's floor of 124 and were
+ snapped up to 124, and 362 and 872 were snapped down to 345. On the native path that turns
+ num_frames=5 into a 25x compute surprise, silently.
+ """
+ h3 = detect_video_family("MiniMaxAI/MiniMax-H3")
+ assert (h3.min_num_frames, h3.max_num_frames) == (124, 345)
+ for count in (5, 90, 107, 362, 872):
+ # Each is genuinely on the lattice, so only the range check can catch it.
+ assert (count - h3.frame_offset) % h3.frame_step == 0
+ with pytest.raises(ValueError) as excinfo:
+ validate_video_request_shape(h3, num_frames = count)
+ assert "counts run from 124 to 345" in str(excinfo.value)
+ # The three counts the interface offers stay valid.
+ for count in (124, 243, 345):
+ validate_video_request_shape(h3, num_frames = count)
+ # Families that declare no window are untouched: LTX-2 keeps its whole lattice.
+ for count in (1, 9, 121, 1017):
+ validate_video_request_shape(LTX2, num_frames = count)
+
+
def test_omitted_fields_are_always_valid():
"""None means "use the family default", which is valid by construction."""
validate_video_request_shape(LTX2)
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
index 9abaebc7a27..3d12c86ff64 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
@@ -453,6 +453,15 @@ assert.equal(
.format,
"bf16",
);
+// The upper tier, in the units the picker is actually handed: 132 GiB of VRAM is 141.7 decimal
+// GB, past the 132 GB at which the backend estimator drops its host-RAM floor to 85 GB, and
+// 85 GiB of RAM is 91.3 GB. So this host fits, and a tier table written in decimal GB would
+// wrongly send it to GGUF.
+assert.equal(
+ pickDefaultArtifact(h3, { gpuGb: 132, systemRamGb: 85, isDownloaded: notDownloaded })
+ .format,
+ "bf16",
+);
// ── official BF16 artifacts (added so groups are not unsloth-quant-only) ────────
// Qwen-Image-2512 BF16 (54 GB) misses a 24/48 GB budget (bnb-4bit/fp8 win there, asserted above) but on an 80 GB GPU (budget 56) it fits and wins.
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
index e459a8fb3c9..9c5dfbb42fd 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
@@ -346,9 +346,17 @@ export const VIDEO_CATALOG: CatalogGroup[] = [
capabilities: { audio: true },
artifacts: [
bf16Pipeline("MiniMaxAI/MiniMax-H3", 145, {
- // Cluster measurements at the default 1344x768, 124-frame preset. The
- // lower-GPU tier holds one 66 GB component at a time and keeps the full
- // model in RAM; the higher tier retains more weights on-device.
+ // Cluster measurements at the default 1344x768, 124-frame preset. The lower-GPU tier
+ // holds one 66 GB component at a time and keeps the full model in RAM; the higher tier
+ // retains more weights on-device.
+ //
+ // THESE ARE GiB, and the backend estimators they mirror are decimal GB, so the two sets
+ // of numbers must never be copied across. The hardware API divides MiB and bytes by
+ // 1024-based units (nvidia.py memory_total_gb, main.py available_gb) while the generation
+ // guard in video.py divides runtime bytes by 1_000_000_000. Converted, these tiers are
+ // 79.5 / 150.3 GB and 132.1 / 85.9 GB, which is exactly the estimators' 78.74 / 150 and
+ // 132 / 85 with a small margin. Raising them to the decimal figures applies the
+ // conversion twice and sends capable hosts to GGUF.
offloadFitTiers: [
{ gpuGb: 74, systemRamGb: 140 },
{ gpuGb: 123, systemRamGb: 80 },
diff --git a/studio/frontend/src/features/video/reference-budget.ts b/studio/frontend/src/features/video/reference-budget.ts
index 82319055f32..a535bb66cca 100644
--- a/studio/frontend/src/features/video/reference-budget.ts
+++ b/studio/frontend/src/features/video/reference-budget.ts
@@ -11,3 +11,77 @@ export function hasReferenceCapacity(
): boolean {
return images + videos + audios < MAX_H3_REFERENCES;
}
+
+export type ReferenceKind = "video" | "audio";
+
+/**
+ * Room for the `data:<mime>;base64,` FileReader prepends.
+ *
+ * Reserved rather than measured, because the cap has to be known before the FileReader runs and
+ * the MIME string is whatever the OS reported: `video/mp4` makes a 22 character prefix and the
+ * long-winded ones (`video/x-matroska`, `audio/vnd.wave`) are half as long again. 256 covers any
+ * of them and costs 192 bytes of the advertised limit, which does not move the rounded MB figure.
+ */
+const DATA_URL_HEADER_BUDGET = 256;
+
+/**
+ * The largest raw file of each kind whose data URL still fits the backend's cap.
+ *
+ * The caps in models/inference.py bound the STRING, not the file: 96 MiB for a reference video and
+ * 32 MiB for its soundtrack. Base64 costs 4 characters per 3 bytes, so a plain three quarters is
+ * off by the header, and a file at exactly that size was accepted here and then 422'd during
+ * request validation. Floor to a multiple of 3 as well, so the encode is exactly (n / 3) * 4 with
+ * no padding to account for.
+ */
+function rawLimitFor(base64Cap: number): number {
+ return Math.floor(((base64Cap - DATA_URL_HEADER_BUDGET) * 3) / 4 / 3) * 3;
+}
+
+export const MAX_REFERENCE_BYTES: Record<ReferenceKind, number> = {
+ video: rawLimitFor(96 * 1024 * 1024),
+ audio: rawLimitFor(32 * 1024 * 1024),
+};
+
+/** Why this file cannot be staged as a reference, or null when it can. */
+export function referenceFileRejection(
+ kind: ReferenceKind,
+ file: { type: string; size: number },
+): string | null {
+ if (!file.type.startsWith(`${kind}/`)) {
+ return `Please choose ${kind === "video" ? "a video" : "an audio"} file`;
+ }
+ if (file.size > MAX_REFERENCE_BYTES[kind]) {
+ const limitMb = Math.round(MAX_REFERENCE_BYTES[kind] / (1024 * 1024));
+ return `This ${kind} is too large (limit ${limitMb} MB)`;
+ }
+ return null;
+}
+
+/**
+ * Read one reference file into the data URL the request carries.
+ *
+ * The size check happens BEFORE the FileReader exists, because a data URL costs roughly 2.33x the
+ * file in renderer memory and it is built long before the backend's 422 can arrive. H3 reference
+ * clips are 2 to 15 seconds by spec, so a 15 second 4K phone clip clears the cap routinely; chat
+ * attachments, OpenDocument imports and the seed dialog all guard the same way.
+ */
+export function readReferenceFile(
+ kind: ReferenceKind,
+ file: File | undefined | null,
+ handlers: {
+ onLoaded: (dataUrl: string | null) => void;
+ onError: (message: string) => void;
+ },
+): void {
+ if (!file) return;
+ const rejection = referenceFileRejection(kind, file);
+ if (rejection !== null) {
+ handlers.onError(rejection);
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = () =>
+ handlers.onLoaded(typeof reader.result === "string" ? reader.result : null);
+ reader.onerror = () => handlers.onError(`Could not read the ${kind} file`);
+ reader.readAsDataURL(file);
+}
diff --git a/studio/frontend/src/features/video/reference-picker.tsx b/studio/frontend/src/features/video/reference-picker.tsx
index a14c2a18932..c43768e3984 100644
--- a/studio/frontend/src/features/video/reference-picker.tsx
+++ b/studio/frontend/src/features/video/reference-picker.tsx
@@ -14,6 +14,8 @@ import {
import { cn } from "@/lib/utils";
import { toast } from "@/lib/toast";
+import { readReferenceFile } from "./reference-budget";
+
/** One staged reference file: the data URL the request carries, plus its name for the chip. */
export interface ReferenceMedia {
name: string;
@@ -41,17 +43,11 @@ export function ReferenceMediaPicker({
const readFile = useCallback(
(file: File | undefined | null) => {
- if (!file || !file.type.startsWith(`${kind}/`)) {
- if (file) toast.error(`Please choose ${kind === "video" ? "a video" : "an audio"} file`);
- return;
- }
- const reader = new FileReader();
- reader.onload = () =>
- onChange(
- typeof reader.result === "string" ? { name: file.name, dataUrl: reader.result } : null,
- );
- reader.onerror = () => toast.error(`Could not read the ${kind} file`);
- reader.readAsDataURL(file);
+ readReferenceFile(kind, file, {
+ onLoaded: (dataUrl) =>
+ onChange(dataUrl === null || !file ? null : { name: file.name, dataUrl }),
+ onError: (message) => toast.error(message),
+ });
},
[kind, onChange],
);
diff --git a/studio/frontend/tests/video-reference-file-size.test.ts b/studio/frontend/tests/video-reference-file-size.test.ts
new file mode 100644
index 00000000000..1702879281c
--- /dev/null
+++ b/studio/frontend/tests/video-reference-file-size.test.ts
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The reference picker used to read ANY file the MIME check let through straight to a base64 data
+ * URL. The backend caps the base64 STRING (96 MiB for a reference video, 32 MiB for its
+ * soundtrack), so the raw file limits are three quarters of those, and a data URL costs about
+ * 2.33x the file in renderer memory before the 422 can arrive. H3 reference clips are 2 to 15
+ * seconds by spec, so a 15 second 4K phone clip clears the cap routinely.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ MAX_REFERENCE_BYTES,
+ readReferenceFile,
+ referenceFileRejection,
+} from "../src/features/video/reference-budget.ts";
+
+/** A File stub: readReferenceFile only ever reads .type, .size and hands the object on. */
+function fileStub(type: string, size: number): File {
+ return { type, size, name: "clip.mp4" } as unknown as File;
+}
+
+function withFileReaderSpy<T>(run: (constructed: () => number) => T): T {
+ let built = 0;
+ const previous = (globalThis as { FileReader?: unknown }).FileReader;
+ class SpyFileReader {
+ result: string | null = null;
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ constructor() {
+ built += 1;
+ }
+ readAsDataURL() {
+ this.result = "data:video/mp4;base64,AAAA";
+ this.onload?.();
+ }
+ }
+ (globalThis as { FileReader?: unknown }).FileReader = SpyFileReader;
+ try {
+ return run(() => built);
+ } finally {
+ (globalThis as { FileReader?: unknown }).FileReader = previous;
+ }
+}
+
+test("a file at the cap still encodes to a data URL the backend accepts", () => {
+ // models/inference.py bounds the STRING, not the file: 96 MiB for the video field and 32 MiB
+ // for the soundtrack. FileReader emits `data:<mime>;base64,` plus 4 characters per 3 bytes, so
+ // a raw cap of exactly three quarters encodes to exactly the limit and the prefix puts it over.
+ // The picker accepted such a file and request validation then rejected it.
+ const caps = { video: 96 * 1024 * 1024, audio: 32 * 1024 * 1024 } as const;
+ for (const kind of ["video", "audio"] as const) {
+ const raw = MAX_REFERENCE_BYTES[kind];
+ // One of the longer MIME strings the OS can report, not the friendly mp4 case.
+ const prefix = `data:${kind}/x-matroska;base64,`.length;
+ assert.ok(
+ Math.ceil(raw / 3) * 4 + prefix <= caps[kind],
+ `${kind}: ${Math.ceil(raw / 3) * 4 + prefix} exceeds ${caps[kind]}`,
+ );
+ // Three quarters exactly would have failed that, so this is the assertion that moved.
+ assert.ok(Math.ceil((caps[kind] * 3) / 4 / 3) * 4 + prefix > caps[kind]);
+ }
+});
+
+test("the headroom does not move the limit the user is shown", () => {
+ assert.equal(Math.round(MAX_REFERENCE_BYTES.video / (1024 * 1024)), 72);
+ assert.equal(Math.round(MAX_REFERENCE_BYTES.audio / (1024 * 1024)), 24);
+});
+
+test("an oversized reference is refused before a FileReader ever exists", () => {
+ withFileReaderSpy((constructed) => {
+ const loaded: (string | null)[] = [];
+ const errors: string[] = [];
+
+ readReferenceFile("video", fileStub("video/mp4", MAX_REFERENCE_BYTES.video + 1), {
+ onLoaded: (dataUrl) => loaded.push(dataUrl),
+ onError: (message) => errors.push(message),
+ });
+
+ assert.equal(constructed(), 0, "the file must not be read into memory at all");
+ // Length rather than deepEqual against []: node's deepEqual is an assertion
+ // signature, so comparing to an empty literal narrows loaded to never[] and
+ // the audio push below stops typechecking.
+ assert.equal(loaded.length, 0);
+ assert.equal(errors.length, 1);
+ assert.match(errors[0], /too large \(limit 72 MB\)/);
+
+ // The soundtrack slot carries its own, smaller cap.
+ errors.length = 0;
+ readReferenceFile("audio", fileStub("audio/wav", MAX_REFERENCE_BYTES.audio + 1), {
+ onLoaded: (dataUrl) => loaded.push(dataUrl),
+ onError: (message) => errors.push(message),
+ });
+ assert.equal(constructed(), 0);
+ assert.match(errors[0], /too large \(limit 24 MB\)/);
+ });
+});
+
+test("a file inside the cap is still read normally", () => {
+ withFileReaderSpy((constructed) => {
+ const loaded: (string | null)[] = [];
+ const errors: string[] = [];
+
+ readReferenceFile("video", fileStub("video/mp4", MAX_REFERENCE_BYTES.video), {
+ onLoaded: (dataUrl) => loaded.push(dataUrl),
+ onError: (message) => errors.push(message),
+ });
+
+ assert.equal(constructed(), 1);
+ assert.deepEqual(loaded, ["data:video/mp4;base64,AAAA"]);
+ assert.deepEqual(errors, []);
+ });
+});
+
+test("the wrong media kind is still refused first", () => {
+ assert.equal(
+ referenceFileRejection("video", { type: "image/png", size: 10 }),
+ "Please choose a video file",
+ );
+ assert.equal(referenceFileRejection("audio", { type: "audio/wav", size: 10 }), null);
+});