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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: image and video generation follow each model's defaults and prompting tips, and /v1/videos takes Unsloth Studio controls (#14078)
Etherl4a1037e9a97e
diff --git a/studio/MCP.md b/studio/MCP.mdindex 11e3842320f..27aa34442d2 100644--- a/studio/MCP.md+++ b/studio/MCP.md@@ -273,10 +273,10 @@ api_key_format = "Bearer {token}"| `chat` | Ask the loaded model, with optional images. Returns a `cancel_id`. || `embed` | Embed up to 2048 texts. || `system_one` | Ask the Decision API typed questions. The Decision API must be on. |-| `generate_image` | Text to image, image to image, inpaint, edit, outpaint and upscale. |+| `generate_image` | Text to image, image to image, inpaint, edit, reference, outpaint and upscale, one image or a batch of seeds or prompts. Left out, steps and guidance follow the loaded model. || `generate_audio` | Clone, speak, edit, convert, music and separate, on the loaded model or a named `model`. || `transcribe` | Speech to text, or translation to English. |-| `generate_video` | Start a video. Poll it with `get_job`. |+| `generate_video` | Start a video, with a seed, frame count, last frame and image or audio references. One renders at a time. Poll it with `get_job`. || `get_job` | The state of a video, recipe or export job. || `run_recipe` | Validate, preview or run a Data Recipe. || `datasets` | List, check, download and follow training datasets. |diff --git a/studio/backend/core/inference/bundled_skills/image-prompting/SKILL.md b/studio/backend/core/inference/bundled_skills/image-prompting/SKILL.mdnew file mode 100644index 00000000000..84966d97ee0--- /dev/null+++ b/studio/backend/core/inference/bundled_skills/image-prompting/SKILL.md@@ -0,0 +1,20 @@+---+name: image-prompting+description: Write detailed prompts for the loaded image or video model when the user asks to generate one.+allowed-tools: generate_image generate_video+---++# Write an image or video prompt++Use this skill when the user asks for an image or a video and their request is short or vague.++1. Read the generate_image or generate_video tool description: when it carries a tip for the model loaded in Unsloth Studio and that tip disagrees with a step below, follow the tip.+2. Name the subject first, with the details that must stay the same across shots.+3. Add the setting: place, time of day and weather.+4. Pick a style: photo, illustration, painting or 3D render, plus the lens or medium when it matters.+5. Describe the light and the mood.+6. Set the composition: framing and camera angle, and for a video how the camera and the subject move.+7. Put any words that must appear in the picture in quotes.+8. For more shots of the same character, repeat the subject's details word for word.++Keep the user's own words and intent. Add no people, brands or text they did not ask for, and leave steps and guidance out unless the user asks, so the model's own defaults apply.diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 1bab04817ae..f56b0f79fdc 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -12776,6 +12776,7 @@ class DiffusionBackend:# Workflows the loaded family supports, so the UI can gate its tabs."workflows": _family_workflows(state.family),"supports_negative_prompt": state.family.uses_negative_prompt,+ "prompt_hint": state.family.prompt_hint,"samplers": sampler_options(getattr(state.pipe, "scheduler", None)),"conditioning": conditioning_capabilities(state.family, _family_workflows(state.family)diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 7c807828a13..e913454b6ab 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -89,6 +89,8 @@ class DiffusionFamily:cfg_kwarg: str = "guidance_scale"# False when the diffusers pipeline ignores a negative prompt; the native engine decides on its own.uses_negative_prompt: bool = True+ # One or two sentences on how this family reads prompts; None when it has no quirks.+ prompt_hint: Optional[str] = None# The pipe attribute holding the denoiser: ``pipe.transformer`` for DiT families, ``pipe.unet`` for SDXL.denoiser_attr: str = "transformer"# True when a single-file ``.safetensors`` is the WHOLE pipeline (SDXL), so the loader calls ``from_single_file``.@@ -639,6 +641,10 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (), # ComfyUI ModelSamplingFlux fixed mu 1.15 (Kontext template)pipeline_class = "FluxKontextPipeline",uses_negative_prompt = False,+ prompt_hint = (+ 'Write the change you want as an instruction, such as "make the sky orange", not a'+ " description of the whole picture."+ ),transformer_class = "FluxTransformer2DModel",base_repo = "black-forest-labs/FLUX.1-Kontext-dev",# FLUX.1's pre-cast T5-XXL: Kontext ships the same text_encoder_2 shards (sha256 compared 2026-10-16).@@ -697,6 +703,10 @@ _FAMILIES: tuple[DiffusionFamily, ...] = ("qwenimageedit",),edit = True,+ prompt_hint = (+ "Write the change you want as an instruction, not a description of the whole picture."+ " With several input images, refer to them as Image 1, Image 2 and so on."+ ),# same DiT as qwen-imagefp16_incompatible = True,# Native: qwen-image's VAE + Qwen2.5-VL, plus its projector (edits read the source through the VLM; a GGUF@@ -917,6 +927,11 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (# 2.5-2.7 GiB per 1024-square condition image against the estimator's 8 GiB per output megapixel.condition_pixel_weight = 0.32,aliases = ("qwen_image_21", "qwenimage21", "qwen-image-21"),+ prompt_hint = (+ "Describe the image, or give an edit instruction over the input images and refer to them"+ ' as Image 1, Image 2. For a transparent background, start with "This is an RGBA image'+ ' with transparency."'+ ),# Built by us from Qwen/Qwen-Image-2.1 itself: the same 238 tensors under upstream's own# names, cast fp32 -> bf16 and written as one file, because sd-cli takes --vae as a single# file rather than a diffusers subfolder. That is 0.63 GiB against upstream's 1.26 GiB of@@ -1164,6 +1179,9 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (),pipeline_class = "Ideogram4Pipeline",uses_negative_prompt = False,+ prompt_hint = (+ "Ideogram 4 follows long, descriptive prompts, and text in quotes renders as lettering."+ ),transformer_class = "Ideogram4Transformer2DModel",base_repo = "ideogram-ai/ideogram-4-fp8",# Qwen3-VL-8B, built from the vendor's per-channel-scaled fp8 shards dequantized to bf16 (what a dense loaddiff --git a/studio/backend/core/inference/mlx_diffusion_backend.py b/studio/backend/core/inference/mlx_diffusion_backend.pyindex 36b260a6ddb..aa04763b9ca 100644--- a/studio/backend/core/inference/mlx_diffusion_backend.py+++ b/studio/backend/core/inference/mlx_diffusion_backend.py@@ -1315,6 +1315,7 @@ class MlxDiffusionBackend:"supports_lora": False,"supports_controlnet": False,"supports_negative_prompt": negative,+ "prompt_hint": state.family.prompt_hint,"workflows": ["txt2img"],"conditioning": conditioning,}diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex c8ff29ce151..3ec085751b8 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -4977,6 +4977,7 @@ class SdCppDiffusionBackend:),"supports_controlnet": False,"supports_negative_prompt": state.family.name not in _EMBEDDED_GUIDANCE_FAMILIES,+ "prompt_hint": state.family.prompt_hint,# "server" = resident sd-server (load once); "oneshot" = legacy per-image sd-cli."native_mode": state.mode,# txt2img always; reference and edit only where this build and its loaded assets run them.diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 711308d8b38..f04cd5068f5 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -12734,6 +12734,7 @@ class VideoBackend:**_nvfp4_backend_fields(_video_transformer_quant_backend(state), owner = self),"text_encoder_quant": state.text_encoder_quant,"has_audio": fam.has_audio,+ "prompt_hint": fam.prompt_hint,"supports_cfg": fam.supports_cfg,# Expose only conditioning supported by the resident partition."supports_keyframes": fam.supports_keyframes and state.h3_task != H3_TASK_REFERENCES,diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.pyindex 5c4be408ac5..e98b556cd3b 100644--- a/studio/backend/core/inference/video_families.py+++ b/studio/backend/core/inference/video_families.py@@ -237,6 +237,8 @@ class VideoFamily:# True when the pipeline returns synchronized audio (LTX-2): export muxes the track and size estimates count the# audio VAE + vocoder.has_audio: bool = False+ # One or two sentences on how this family reads prompts; None when it has no quirks.+ prompt_hint: Optional[str] = None# Wan2.2-A14B dual-expert MoE: a second DiT handles the low-noise steps with its own guidance kwargtransformer2_class: Optional[str] = Noneis_moe: bool = Falsediff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 4d7756ee739..ef9763e71b0 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -33,11 +33,15 @@ from core.inference.llama_server_args import (PARALLEL_MIN,)from core.inference.runtime_context import MAX_REQUESTABLE_CONTEXT+from utils.upload_limits import VIDEO_INPUT_REFERENCE_JSON_MAX_BYTESfrom core.inference.video_families import MAX_VIDEO_NUM_FRAMESfrom picker.schemas import MAX_CHAT_TEMPLATE_BYTESfrom models.providers import ProviderReasoningConfigfrom utils.reasoning_budget import validate_reasoning_budget_message+# A 24 MB reference audio as a base64 data URL, with room for its header.+_VIDEO_REFERENCE_AUDIO_MAX_CHARS = ((24 * 1024 * 1024 + 2) // 3) * 4 + 64 * 1024+def resolve_inventory_handle(value: str) -> str:"""Turn a `ref:...` inventory identity back into the path it stands for. A reference this@@ -4833,8 +4837,19 @@ class DiffusionGenerateRequest(BaseModel):le = 2752,description = "Image height in pixels (multiple of 16; the loaded model may require more)",)- steps: int = Field(9, ge = 1, le = 100, description = "Number of denoising steps")- guidance: float = Field(0.0, ge = 0.0, le = 20.0, description = "Classifier-free guidance scale")+ steps: int = Field(+ 9,+ ge = 1,+ le = 100,+ description = "Number of denoising steps. Omitted: the loaded model's default "+ "(status generation_defaults).",+ )+ guidance: float = Field(+ 0.0,+ ge = 0.0,+ le = 20.0,+ description = "Classifier-free guidance scale. Omitted: the loaded model's default.",+ )# le = 2**53-1: seeds round-trip through JSON recipes, where JavaScript rounds larger integers and a restored recipe would differ.seed: Optional[int] = Field(None, ge = 0, le = 2**53 - 1, description = "Seed for reproducibility (random if omitted)"@@ -4945,10 +4960,11 @@ class DiffusionGenerateRequest(BaseModel):)workflow: Optional[Literal["edit", "reference", "outpaint"]] = Field(None,- description = "Explicit image-conditioned workflow. edit: follow the prompt as an "- "instruction over init_image (and reference_images); reference: generate a new image "- "guided by them; outpaint: runs as inpaint over the padded init_image + mask_image and "- "is recorded as outpaint. Omitted keeps the workflow implied by the other fields.",+ description = "Explicit image-conditioned workflow; every one needs init_image. edit: "+ "follow the prompt as an instruction over init_image (and reference_images); reference: "+ "draw a new image from init_image plus reference_images; outpaint: runs as inpaint over "+ "the padded init_image under mask_image (required) and is recorded as outpaint. Omitted "+ "keeps the workflow implied by the other fields.",)reference_resolution: Optional[int] = Field(None,@@ -5537,6 +5553,11 @@ class DiffusionStatusResponse(BaseModel):"(drives the Negative prompt field). False for FLUX and Ideogram 4 on diffusers, and ""for FLUX.1 / Kontext / FLUX.2-dev on the native engine.",)+ prompt_hint: Optional[str] = Field(+ None,+ description = "How the loaded model reads prompts, in one or two sentences; null when "+ "it has no tip.",+ )samplers: list[Dict[str, Any]] = Field(default_factory = list,description = "Samplers the loaded model can run, each {id, label, schedule_types}; the "@@ -6179,13 +6200,114 @@ class VideoJobCreateRequest(BaseModel):size: Optional[str] = Field(None, description = "'<width>x<height>', a resolution preset of the loaded family.")+ # Unsloth Studio extensions; a plain OpenAI request leaves them all out.+ seed: Optional[int] = Field(+ None,+ ge = 0,+ le = 2**53 - 1,+ description = "Seed for a repeatable take. Omitted: Unsloth Studio draws one and returns "+ "it on the job.",+ )+ negative_prompt: Optional[str] = Field(+ None, description = "What the video should avoid, on models that take a negative prompt."+ )+ steps: Optional[int] = Field(+ None, ge = 1, le = 100, description = "Number of denoising steps (default per model)."+ )+ guidance: Optional[float] = Field(+ None,+ ge = 0.0,+ le = 20.0,+ description = "Classifier-free guidance scale (default per model).",+ )+ num_frames: Optional[int] = Field(+ None,+ ge = 1,+ le = MAX_VIDEO_NUM_FRAMES,+ description = "Frame count on the model's frame lattice; send seconds or num_frames, "+ "not both.",+ )+ fps: Optional[int] = Field(+ None, ge = 1, le = 120, description = "Playback frame rate (default per model)."+ )+ last_frame: Optional[str] = Field(+ None,+ # A 32 MB image, the input_reference limit, as a base64 data URL.+ max_length = VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,+ description = "Image the clip ends on (MiniMax-H3 only, status supports_last_frame): a "+ 'file upload, a base64 data URL or {"image_url": ...}.',+ )+ reference_images: Optional[list[str]] = Field(+ None,+ max_length = 9,+ description = "Subject, style or scene references, at most 9, in the shapes "+ "input_reference takes. The prompt calls them <Picture 1>, <Picture 2>, ... in order. "+ "One request body carries about 32 MB of images and audio in all.",+ )+ reference_audios: Optional[list[Union[str, AudioSourceRef]]] = Field(+ None,+ max_length = 3,+ description = "Voice or score references, at most 3 of up to 24 MB each: a file upload, a "+ 'base64 data URL or an Unsloth Studio audio id {"input_id" | "clip_id" | "voice_id": ...}. '+ "The prompt calls them <Audio 1>, <Audio 2>, ... in order. They need a reference image "+ "to go with. Inline audio counts toward the request body's 32 MB, so send larger or "+ "several clips as ids (POST /v1/audio/inputs stores one).",+ )@field_validator("model", "seconds", "size", mode = "before")@classmethod- def _blank_means_default(cls, value):+ def _blank_means_default(cls, value, info):if value is None:return None- return str(value).strip() or None+ text = str(value).strip()+ # "auto" is OpenAI's omitted duration, so it must not count against num_frames.+ if info.field_name == "seconds" and text.lower() == "auto":+ return None+ return text or None++ @field_validator(+ "seed",+ "negative_prompt",+ "steps",+ "guidance",+ "num_frames",+ "fps",+ "last_frame",+ mode = "before",+ )+ @classmethod+ def _blank_means_omitted(cls, value):+ # A multipart form sends an empty field as "".+ if isinstance(value, str) and not value.strip():+ return None+ return value++ @field_validator("reference_images", "reference_audios")+ @classmethod+ def _bounded_references(cls, value, info):+ # Bound each item like last_frame, so a list cannot buffer what one field may not:+ # a 32 MB image or a 24 MB audio clip, base64-encoded.+ image = info.field_name == "reference_images"+ cap = VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES if image else _VIDEO_REFERENCE_AUDIO_MAX_CHARS+ for item in value or []:+ if isinstance(item, str) and len(item) > cap:+ raise ValueError(+ "each reference image must be at most 32 MB"+ if image+ else "each reference audio must be at most 24 MB"+ )+ return value++ @model_validator(mode = "after")+ def _one_length_and_one_conditioning(self) -> "VideoJobCreateRequest":+ if self.seconds is not None and self.num_frames is not None:+ raise ValueError("Send seconds or num_frames, not both.")+ if self.last_frame and (self.reference_images or self.reference_audios):+ raise ValueError(+ "keyframes and references cannot be combined: MiniMax-H3 runs them against "+ "different denoiser partitions"+ )+ return selfclass VideoJobError(BaseModel):@@ -6205,6 +6327,8 @@ class VideoJob(BaseModel):prompt: Optional[str] = Nonesize: strseconds: str+ # Unsloth Studio extension: the seed this take used; null on jobs from before seeds were kept.+ seed: Optional[int] = Noneerror: Optional[VideoJobError] = Noneremixed_from_video_id: Optional[str] = None@@ -6869,6 +6993,11 @@ class VideoStatusResponse(BaseModel):defaults: Optional[VideoGenerationDefaults] = Field(None, description = "Per-family generation defaults + shape constraints; null when unloaded")+ prompt_hint: Optional[str] = Field(+ None,+ description = "How the loaded model reads prompts, in one or two sentences; null when "+ "it has no tip.",+ )# Additive per-control provenance, same shape as the diffusion status; null when nothing is loaded.resolved: Optional[Dict[str, DiffusionResolvedControl]] = Field(None,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 9cb54abcfc1..4d467b7f6fb 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -50760,10 +50760,13 @@ async def generate_diffusion_image(if request.localized_edit is not Noneelse None)+ submitted = request# FLUX.3 prompt upsampling runs ahead of the run, so the sidecar can leave the VRAM before the DiT denoises.enhancement = await _enhance_generate_prompts(backend, request)result = Nonefor attempt in range(2):+ request = submitted+ status = Noneexpected_load = Noneif account_access.managed_account():status = backend.status()@@ -50774,6 +50777,23 @@ async def generate_diffusion_image(expected_load = load_identity(status.get("repo_id"), status.get("base_repo"), status.get("family"))+ # Omitted steps or guidance follow the loaded model, read again each attempt so a replacement brings its own.+ omitted = {"steps", "guidance"} - request.model_fields_set+ if omitted:+ if status is None:+ status = await asyncio.to_thread(backend.status)+ if status.get("loaded"):+ steps, guidance = await asyncio.to_thread(_image_generation_defaults, status)+ resolved = {"steps": steps, "guidance": guidance}+ request = request.model_copy(update = {key: resolved[key] for key in omitted})+ if expected_load is None:+ expected_load = load_identity(+ status.get("repo_id"), status.get("base_repo"), status.get("family")+ )+ elif expected_load is None:+ # A load in flight would admit this run on its new model with the schema's values.+ # Pin to "nothing loaded" so that model is refused and the retry reads its defaults.+ expected_load = load_identity(None, None, None)if enhancement.load is not None:# Captions are written for one family: a model swapped in since then retries with fresh ones.expected_load = enhancement.load@@ -52113,6 +52133,23 @@ async def openai_image_generations()+def _image_generation_defaults(status: dict) -> tuple[int, float]:+ """Steps and guidance for the loaded image model: the diffusers recipe when the status reports one, else the family table (sd.cpp and MLX report none). It reads checkpoint headers, so call it off the event loop."""+ from core.inference.diffusion_content import content_variant_hint+ from core.inference.diffusion_families import default_generation_params++ defaults = status.get("generation_defaults")+ if isinstance(defaults, dict) and defaults.get("steps"):+ return int(defaults["steps"]), float(defaults["guidance"])+ # Same order as the load (FLUX.1's base is schnell).+ return default_generation_params(+ status.get("gguf_filename"),+ content_variant_hint(status.get("repo_id"), status.get("gguf_filename")),+ status.get("repo_id"),+ status.get("base_repo"),+ )++# Split out so the monitor row can wrap the whole handler without reindenting it.async def _generate_openai_images(body: ImageGenerationRequest,@@ -52125,7 +52162,6 @@ async def _generate_openai_images():from core.inference import image_galleryfrom core.inference.diffusion_engine_router import get_active_diffusion_engine- from core.inference.diffusion_families import default_generation_paramsfrom core.inference.gpu_arbiter import DIFFUSIONfrom core.inference.media_auto_switch import maybe_auto_switch_media_model@@ -52171,22 +52207,7 @@ async def _generate_openai_images(),)- # Same order as the load (FLUX.1's base is schnell).- from core.inference.diffusion_content import content_variant_hint-- # Resolved by the diffusers status (a shipped grid's step count included).- defaults = status.get("generation_defaults")- if isinstance(defaults, dict) and defaults.get("steps"):- steps, guidance = int(defaults["steps"]), float(defaults["guidance"])- else:- steps, guidance = default_generation_params(- status.get("gguf_filename"),- await asyncio.to_thread(- content_variant_hint, status.get("repo_id"), status.get("gguf_filename")- ),- status.get("repo_id"),- status.get("base_repo"),- )+ steps, guidance = await asyncio.to_thread(_image_generation_defaults, status)reset_media_generation_progress("image")try:with account_access.media_generation("diffusion"):diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex 14f7ac86d5e..64ca977fb39 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -18,6 +18,7 @@ import asyncioimport base64import hashlib as _hashlibimport inspect+import jsonimport hmac as _hmacimport re as _reimport secrets as _secrets@@ -1160,7 +1161,29 @@ _MAX_REMEMBERED_JOBS = 256_VIDEO_POLL_AFTER_MS = "2000"_NO_VIDEO_MODEL_MSG = "No video model loaded. Load a video model first."_VIDEO_FAILED_CODE = "video_generation_failed"-_VIDEO_CREATE_FIELDS = ("prompt", "model", "seconds", "size")+_VIDEO_CREATE_FIELDS = (+ "prompt",+ "model",+ "seconds",+ "size",+ "seed",+ "negative_prompt",+ "steps",+ "guidance",+ "num_frames",+ "fps",+ "last_frame",+)+_VIDEO_CREATE_LISTS = ("reference_images", "reference_audios")+# VideoJobCreateRequest's list limits, checked before multipart files are encoded.+_VIDEO_CREATE_LIST_MAX = {"reference_images": 9, "reference_audios": 3}+# The OpenAI SDK flattens a list of objects to key[][field]; each such part is one item.+_OBJECT_PART = {+ "reference_images": _re.compile(r"reference_images(?:\[\d*\])?\[(image_url|file_id)\]"),+ "reference_audios": _re.compile(r"reference_audios(?:\[\d*\])?\[(input_id|clip_id|voice_id)\]"),+}+# A reference audio rides as base64 in a field capped at 32 MiB, which is 24 MiB of audio.+_VIDEO_REFERENCE_AUDIO_MAX_BYTES = 24 * 1024 * 1024# Upper bound on how long DELETE waits for a cancelled run to stop writing._DELETE_SETTLE_TIMEOUT_S = 10.0@@ -1173,6 +1196,7 @@ class _VideoJob:model: strsize: strseconds: str+ seed: Optional[int] = Nonestatus: str = "queued"progress: int = 0completed_at: Optional[int] = None@@ -1269,6 +1293,18 @@ def _frames_for_seconds(seconds: float, defaults: dict) -> int:return k * step + offset+def _refuse_fixed_fps(+ family: Optional[str], default_fps: Optional[int], fps: Optional[int]+) -> None:+ """MiniMax-H3 always writes its clip at the family rate, so another fps would only skew the frame count."""+ if family == "minimax-h3" and fps is not None and default_fps and fps != int(default_fps):+ raise _openai_video_error(+ 400,+ f"MiniMax-H3 renders at a fixed {int(default_fps)} fps; leave fps out.",+ param = "fps",+ )++def _format_seconds(value: float) -> str:return f"{round(float(value), 2):g}"@@ -1330,9 +1366,18 @@ def _record_to_job(record: dict, job: Optional[_VideoJob] = None) -> VideoJob:prompt = record.get("prompt"),size = f"{record.get('width')}x{record.get('height')}",seconds = _format_seconds(record.get("duration_s") or 0.0),+ seed = _record_seed(record, job),)+def _record_seed(record: dict, job: Optional[_VideoJob]) -> Optional[int]:+ """The seed the engine saved with the clip, else the one the job was created with."""+ seed = record.get("seed")+ if isinstance(seed, int) and not isinstance(seed, bool):+ return seed+ return job.seed if job is not None else None++def _job_to_openai(job: _VideoJob) -> VideoJob:return VideoJob(id = job.id,@@ -1344,6 +1389,7 @@ def _job_to_openai(job: _VideoJob) -> VideoJob:prompt = job.prompt,size = job.size,seconds = job.seconds,+ seed = job.seed,error = VideoJobError(**job.error) if job.error else None,)@@ -1543,6 +1589,12 @@ def _all_videos() -> list[VideoJob]:return listed+def _shape_error_param(exc: Exception, body) -> str:+ if "frame count" not in str(exc):+ return "size"+ return "num_frames" if body.num_frames is not None else "seconds"++async def _read_video_create_body(request: Request) -> tuple[dict, Any]:ctype = (request.headers.get("content-type") or "").lower()if ctype.startswith(("multipart/form-data", "application/x-www-form-urlencoded")):@@ -1551,26 +1603,150 @@ async def _read_video_create_body(request: Request) -> tuple[dict, Any]:except Exception: # noqa: BLE001raise _openai_video_error(400, "Could not parse the multipart form body.")fields = {key: form.get(key) for key in _VIDEO_CREATE_FIELDS if key in form}+ for key in _VIDEO_CREATE_LISTS:+ # In wire order across both spellings: <Picture n> follows the order sent.+ items = []+ for name, value in form.multi_items():+ if name in (key, f"{key}[]"):+ items.append(value)+ elif match := _OBJECT_PART[key].fullmatch(name):+ items.append({match.group(1): value})+ if len(items) > _VIDEO_CREATE_LIST_MAX[key]:+ raise _openai_video_error(+ 400, f"{key}: send at most {_VIDEO_CREATE_LIST_MAX[key]}.", param = key+ )+ if items:+ fields[key] = items+ if "last_frame" not in fields and (nested := _nested_image_ref(form, "last_frame")):+ fields["last_frame"] = nestedreference = form.get("input_reference")if reference is None:- nested_reference = {- key: form.get(f"input_reference[{key}]")- for key in ("image_url", "file_id")- if f"input_reference[{key}]" in form- }- reference = nested_reference or None- return fields, reference+ reference = _nested_image_ref(form, "input_reference")+ return await _media_fields(fields), referencetry:data = await request.json()except Exception: # noqa: BLE001raise _openai_video_error(400, "Request body must be JSON or multipart/form-data.")if not isinstance(data, dict):raise _openai_video_error(400, "Request body must be a JSON object.")- return {key: data.get(key) for key in _VIDEO_CREATE_FIELDS if key in data}, data.get(- "input_reference"+ fields = {+ key: data.get(key) for key in _VIDEO_CREATE_FIELDS + _VIDEO_CREATE_LISTS if key in data+ }+ return await _media_fields(fields), data.get("input_reference")+++def _nested_image_ref(form, key: str) -> Optional[dict]:+ nested = {+ field: form.get(f"{key}[{field}]")+ for field in ("image_url", "file_id")+ if f"{key}[{field}]" in form+ }+ return nested or None+++async def _media_fields(fields: dict) -> dict:+ """last_frame, reference_images and uploaded reference_audios as the data URLs the engine takes.+ Audio given as a string or an Unsloth Studio audio id is left for validation and resolution."""+ if fields.get("last_frame") is not None:+ fields["last_frame"] = await _reference_to_data_url(+ fields["last_frame"], param = "last_frame"+ )+ images = fields.get("reference_images")+ if isinstance(images, list):+ fields["reference_images"] = [+ await _reference_to_data_url(item, param = f"reference_images[{index}]")+ for index, item in enumerate(images)+ ]+ audios = fields.get("reference_audios")+ if isinstance(audios, list):+ for index, item in enumerate(audios):+ if isinstance(item, UploadFile):+ audios[index] = await _audio_upload_to_data_url(item, f"reference_audios[{index}]")+ elif isinstance(item, str) and item.lstrip().startswith("{"):+ # A multipart part can only carry an id object as JSON text.+ try:+ audios[index] = json.loads(item)+ except ValueError:+ pass+ return fields+++async def _audio_upload_to_data_url(upload: UploadFile, name: str) -> str:+ data = await upload.read()+ if not data:+ raise _openai_video_error(400, f"{name} is empty.", param = "reference_audios")+ if len(data) > _VIDEO_REFERENCE_AUDIO_MAX_BYTES:+ raise _openai_video_error(+ 400, f"{name} is too large; the limit is 24 MB.", param = "reference_audios"+ )+ content_type = (upload.content_type or "").split(";")[0].strip().lower()+ if not content_type.startswith("audio/"):+ content_type = "application/octet-stream"+ return f"data:{content_type};base64,{base64.b64encode(data).decode('ascii')}"+++def _audio_ref_data_url(ref) -> str:+ """An Unsloth Studio audio id as a data URL, resolved in the caller's account."""+ import mimetypes++ from core.inference import audio_inputs++ source = audio_inputs.resolve_source(ref.model_dump(exclude_none = True))+ # Stored audio can reach 200 MB, so size it before reading it into memory.+ if source.path.stat().st_size > _VIDEO_REFERENCE_AUDIO_MAX_BYTES:+ raise audio_inputs.AudioInputError(+ 400, "This audio is too large for a video reference; the limit is 24 MB."+ )+ data = source.path.read_bytes()+ suffix = source.path.suffix.lower()+ mime = "audio/wav" if suffix == ".wav" else mimetypes.guess_type(source.path.name)[0]+ return (+ f"data:{mime or 'application/octet-stream'};base64,{base64.b64encode(data).decode('ascii')}")+def _refuse_unreadable_audio(audios: Optional[list[str]]) -> None:+ """Decode each reference audio the engine would, refusing one it could not read."""+ if not audios:+ return+ from core.inference.video import _decode_b64_media++ try:+ from core.inference.video_minimax_h3 import decode_h3_reference_audio+ except ImportError: # no media decoder here; begin_generate reports it+ return+ for index, item in enumerate(audios):+ try:+ decode_h3_reference_audio(_decode_b64_media(item))+ except ImportError:+ return+ except Exception: # noqa: BLE001 -- any decode failure is client input feedback+ raise _openai_video_error(+ 400, f"reference_audios[{index}] is not readable audio.", param = "reference_audios"+ )+++def _conditioning_param(+ body: VideoJobCreateRequest,+ reference: Optional[str],+ default: Optional[str] = None,+) -> Optional[str]:+ """The one conditioning field a request carries, to name it in a refusal: ``default`` for none, None for several."""+ given = [+ name+ for name, value in (+ ("input_reference", reference),+ ("last_frame", body.last_frame),+ ("reference_images", body.reference_images),+ ("reference_audios", body.reference_audios),+ )+ if value+ ]+ if not given:+ return default+ return given[0] if len(given) == 1 else None++def _validate_create_fields(fields: dict) -> VideoJobCreateRequest:try:return VideoJobCreateRequest(**fields)@@ -1583,15 +1759,15 @@ def _validate_create_fields(fields: dict) -> VideoJobCreateRequest:raise _openai_video_error(400, f"{param}: {message}" if param else message, param = param)-async def _reference_to_data_url(reference: Any) -> Optional[str]:+async def _reference_to_data_url(reference: Any, param: str = "input_reference") -> Optional[str]:if reference is None:return Noneif isinstance(reference, dict):if reference.get("file_id"):raise _openai_video_error(400,- "input_reference.file_id is not supported; send the image as a file upload or a base64 data URL.",- param = "input_reference",+ f"{param}.file_id is not supported; send the image as a file upload or a base64 data URL.",+ param = param,)reference = reference.get("image_url")if reference is None:@@ -1599,20 +1775,18 @@ async def _reference_to_data_url(reference: Any) -> Optional[str]:if isinstance(reference, UploadFile):data = await reference.read()if not data:- raise _openai_video_error(400, "input_reference is empty.", param = "input_reference")+ raise _openai_video_error(400, f"{param} is empty.", param = param)if len(data) > VIDEO_INPUT_REFERENCE_MAX_BYTES:raise _openai_video_error(400,- f"input_reference is too large; the limit is {VIDEO_INPUT_REFERENCE_MAX_BYTES // (1024 * 1024)} MB.",- param = "input_reference",+ f"{param} is too large; the limit is {VIDEO_INPUT_REFERENCE_MAX_BYTES // (1024 * 1024)} MB.",+ param = param,)content_type = (reference.content_type or "").split(";")[0].strip().lower()sniffed = _sniff_image_type(data)if not content_type.startswith("image/"):if sniffed is None:- raise _openai_video_error(- 400, "input_reference must be an image.", param = "input_reference"- )+ raise _openai_video_error(400, f"{param} must be an image.", param = param)content_type = sniffedencoded = base64.b64encode(data).decode("ascii")return f"data:{content_type};base64,{encoded}"@@ -1623,12 +1797,12 @@ async def _reference_to_data_url(reference: Any) -> Optional[str]:if text.lower().startswith(("http://", "https://")):raise _openai_video_error(400,- "Remote input_reference URLs are not fetched; send the image as a file upload or a base64 data URL.",- param = "input_reference",+ f"Remote {param} URLs are not fetched; send the image as a file upload or a base64 data URL.",+ param = param,)return textraise _openai_video_error(- 400, "input_reference must be an image file or a base64 data URL.", param = "input_reference"+ 400, f"{param} must be an image file or a base64 data URL.", param = param)@@ -1690,7 +1864,37 @@ async def _create_openai_video(except ValueError as exc:raise _openai_video_error(400, str(exc), param = "seconds")width, height = size if size is not None else (None, None)- if reference is not None:+ if reference is not None and body.reference_images:+ raise _openai_video_error(+ 400,+ "input_reference cannot be combined with reference_images; send that image as a reference_images entry.",+ param = "reference_images",+ )+ if body.reference_audios and not body.reference_images and reference is None:+ raise _openai_video_error(+ 400,+ "reference audio needs at least one reference image or video to go with",+ param = "reference_audios",+ )+ reference_audios: Optional[list[str]] = None+ if body.reference_audios:+ from core.inference.audio_inputs import AudioInputError++ # Resolved while the resident model is still loaded, so a bad id costs no switch.+ try:+ reference_audios = [+ item+ if isinstance(item, str)+ else await asyncio.to_thread(_audio_ref_data_url, item)+ for item in body.reference_audios+ ]+ except AudioInputError as exc:+ raise _openai_video_error(exc.status, exc.detail, param = "reference_audios")+ images = [("input_reference", reference), ("last_frame", body.last_frame)]+ images += [("reference_images", item) for item in body.reference_images or []]+ for param, image in images:+ if image is None:+ continue# Check readability before a model switch. The conditioning path applies its own# keyframe or Ref2VA limit later, so this uses the broadest bounded source policy.from core.inference.diffusion import decode_b64_image@@ -1698,18 +1902,19 @@ async def _create_openai_video(H3_REF_IMAGE_SOURCE_MAX_PIXELS,H3_REF_IMAGE_SOURCE_MAX_SIDE,)+try:await asyncio.to_thread(decode_b64_image,- reference,+ image,mode = "RGB",max_side = H3_REF_IMAGE_SOURCE_MAX_SIDE,max_pixels = H3_REF_IMAGE_SOURCE_MAX_PIXELS,)except Exception: # noqa: BLE001 -- any decode failure is client input feedback- raise _openai_video_error(- 400, "input_reference is not a readable image.", param = "input_reference"- )+ raise _openai_video_error(400, f"{param} is not a readable image.", param = param)++ audio_checked = [False]def _refuse_unservable_request(pick) -> None:from core.inference.media_model_index import expected_partition@@ -1724,14 +1929,17 @@ async def _create_openai_video(fam = _detect_load_family(pick.model_path, pick.gguf_filename, None)if fam is None:return+ _refuse_fixed_fps(fam.name, fam.default_fps, body.fps)# Judge the duration against the family being switched TO, using its own lattice. Passing None here accepted any# seconds and only refused it in begin_generate, after the resident pipeline had been evicted and the target# fully loaded.want_frames = (- _frames_for_seconds(+ body.num_frames+ if body.num_frames is not None+ else _frames_for_seconds(seconds,{- "fps": fam.default_fps,+ "fps": body.fps or fam.default_fps,"frame_step": fam.frame_step,"frame_offset": fam.frame_offset,},@@ -1743,15 +1951,22 @@ async def _create_openai_video(h3_task = expected_partition(pick)ref2va = h3_task == H3_TASK_REFERENCESvalidate_video_keyframe_conditioning(- fam, h3_task, has_keyframes = reference is not None and not ref2va+ fam,+ h3_task,+ has_keyframes = (reference is not None and not ref2va) or bool(body.last_frame),+ has_last_frame = bool(body.last_frame),)if reference is not None and not ref2va:assert_first_frame_pipeline_available(fam)validate_video_reference_conditioning(fam,h3_task,- has_references = reference is not None and ref2va,+ has_references = (reference is not None and ref2va)+ or bool(body.reference_images or reference_audios),)+ # Decoded here, like the images above, so unreadable audio never costs a switch.+ _refuse_unreadable_audio(reference_audios)+ audio_checked[0] = Truepin_requested_model = bool(isinstance(body.model, str) and body.model.strip() and get_media_auto_switch_enabled()@@ -1766,17 +1981,23 @@ async def _create_openai_video(before_switch = _refuse_unservable_request,)except VideoShapeError as exc:+ raise _openai_video_error(400, str(exc), param = _shape_error_param(exc, body))+ except ValueError as exc:raise _openai_video_error(- 400, str(exc), param = "seconds" if "frame count" in str(exc) else "size"+ 400, str(exc), param = _conditioning_param(body, reference, "input_reference"))- except ValueError as exc:- raise _openai_video_error(400, str(exc), param = "input_reference")+ if not audio_checked[0]:+ # No switch ran the check, and the engine's own decode can fail with more than ValueError.+ await asyncio.to_thread(_refuse_unreadable_audio, reference_audios)backend = get_video_backend()video_id = _VIDEO_JOB_ID_PREFIX + uuid.uuid4().hex+ # Drawn once, outside the retry, so a model_changed retry renders the same take.+ seed = body.seed if body.seed is not None else _secrets.randbelow(2**53)# Managed callers are authorized against the exact resident state, pinned to the reservation;# on a mismatch, re-authorize once and retry, as /video/generate does.- pin_state = pin_requested_model or account_access.managed_account()+ # An explicit fps is judged against the family, so it is pinned to the state it was judged on.+ pin_state = pin_requested_model or account_access.managed_account() or body.fps is not Nonefor attempt in range(2):expected_state = Noneif pin_state:@@ -1797,7 +2018,14 @@ async def _create_openai_video(if account_access.managed_account():await asyncio.to_thread(account_access.require_media_generation_access, status, "video")defaults = status.get("defaults") or {}- num_frames = _frames_for_seconds(seconds, defaults) if seconds is not None else None+ # The pinned snapshot names no family, so read it off the state it pinned.+ family = status.get("family") or getattr(+ getattr(expected_state, "family", None), "name", None+ )+ _refuse_fixed_fps(family, defaults.get("fps"), body.fps)+ num_frames = (+ _frames_for_seconds(seconds, defaults) if seconds is not None else body.num_frames+ )try:generate_kwargs = dict(prompt = body.prompt,@@ -1806,18 +2034,26 @@ async def _create_openai_video(duration_s = seconds,input_reference = reference,video_id = video_id,+ seed = seed,+ )+ controls = dict(+ negative_prompt = body.negative_prompt,+ steps = body.steps,+ guidance = body.guidance,+ num_frames = body.num_frames,+ fps = body.fps,+ last_frame = body.last_frame,+ reference_images = body.reference_images,+ reference_audios = reference_audios,)+ generate_kwargs.update({k: v for k, v in controls.items() if v is not None})if expected_state is not None:generate_kwargs["expected_state"] = expected_stateresolved = await asyncio.to_thread(backend.begin_generate, **generate_kwargs)except VideoShapeError as exc:- raise _openai_video_error(- 400, str(exc), param = "seconds" if "frame count" in str(exc) else "size"- )+ raise _openai_video_error(400, str(exc), param = _shape_error_param(exc, body))except ValueError as exc:- raise _openai_video_error(- 400, str(exc), param = "input_reference" if reference is not None else None- )+ raise _openai_video_error(400, str(exc), param = _conditioning_param(body, reference))except RuntimeError as exc:msg = str(exc)if msg == VIDEO_NOT_LOADED_MSG:@@ -1865,6 +2101,7 @@ async def _create_openai_video(),size = f"{width}x{height}" if width and height else "auto",seconds = seconds_text,+ seed = seed,)_remember_job(job)return _job_to_openai(job)diff --git a/studio/backend/studio_mcp/outputs.py b/studio/backend/studio_mcp/outputs.pyindex 54cffba268f..eb1eec71f0d 100644--- a/studio/backend/studio_mcp/outputs.py+++ b/studio/backend/studio_mcp/outputs.py@@ -96,12 +96,29 @@ class ImageSlot(ToolOutput):loaded: bool = Falsemodel: Optional[RouteText] = Nonefamily: Optional[RouteText] = None+ # What the loaded model runs, e.g. txt2img, img2img, inpaint, edit, reference.+ workflows: list[RouteText] = []+ # The steps and guidance an omitted value resolves to.+ generation_defaults: Optional[dict[str, Union[StrictInt, StrictFloat]]] = None+ # Width and height must be multiples of this.+ dimension_multiple: Optional[int] = None+ # init_image plus reference_images together hold at most this many images.+ max_condition_images: Optional[int] = None+ # How the loaded model reads prompts, in one or two sentences.+ prompt_hint: Optional[RouteText] = Nonegenerating: bool = Falseclass VideoSlot(ToolOutput):loaded: bool = Falsemodel: Optional[RouteText] = None+ # How the loaded model reads prompts, in one or two sentences.+ prompt_hint: Optional[RouteText] = None+ supports_last_frame: bool = False+ # Whether the loaded model takes reference_images and reference_audios.+ references: bool = False+ # "WIDTHxHEIGHT" sizes the loaded model renders.+ size_presets: list[RouteText] = []generating: bool = False@@ -259,6 +276,9 @@ class ImageItem(ToolOutput):width: Optional[int] = Noneheight: Optional[int] = Noneseed: Optional[int] = None+ # Set on images from a seeds or prompts batch: the image's own seed and its place in the batch.+ batch_seed: Optional[int] = None+ batch_index: Optional[int] = Noneclass ImageResult(ToolOutput):@@ -302,6 +322,8 @@ class VideoJobRef(ToolOutput):model: Optional[RouteText] = Noneseconds: Optional[RouteText] = Nonesize: Optional[RouteText] = None+ # Pass it again with the same settings to repeat this take.+ seed: Optional[int] = Noneclass VideoInfo(ToolOutput):@@ -347,6 +369,8 @@ class ExportInfo(ToolOutput):class JobStatus(ToolOutput):kind: RouteTextid: Optional[RouteText] = None+ # A video job's seed.+ seed: Optional[int] = Nonestatus: Optional[RouteText] = Noneprogress_percent: Optional[float] = Noneerror: Optional[RouteText] = Nonediff --git a/studio/backend/studio_mcp/tools/images.py b/studio/backend/studio_mcp/tools/images.pyindex c1279f65c63..cce83384839 100644--- a/studio/backend/studio_mcp/tools/images.py+++ b/studio/backend/studio_mcp/tools/images.py@@ -94,7 +94,28 @@ async def _image_fields(init_image: Optional[ImageInput],mask_image: Optional[ImageInput],reference_images: Optional[list[ImageInput]],+ workflow: Optional[str] = None,+ upscale: Optional[float] = None,) -> dict[str, Any]:+ # Before any resolve_image: a gallery_id input calls a route.+ if init_image is None and (workflow == "reference" or reference_images):+ raise ToolError(+ "Reference needs init_image: pass the hero as init_image plus reference_images."+ )+ if init_image is None and workflow == "edit":+ raise ToolError(+ 'workflow="edit" needs init_image: it is the image the instruction changes.'+ )+ if init_image is None and workflow == "outpaint":+ raise ToolError('workflow="outpaint" needs init_image: it is the image to extend.')+ if workflow == "outpaint" and mask_image is None:+ raise ToolError(+ 'workflow="outpaint" needs mask_image: white marks the padded border to fill.'+ )+ if upscale is not None and upscale <= 1:+ raise ToolError(+ "upscale must be above 1 (up to 4); for a same-size redraw leave upscale out and set strength."+ )if mask_image is not None and init_image is None:raise ToolError("mask_image needs init_image: the mask marks what to repaint in it.")fields: dict[str, Any] = {}@@ -124,6 +145,22 @@ async def generate_image(steps: Optional[int] = None,guidance: Optional[float] = None,seed: Optional[int] = None,+ seeds: Annotated[+ Optional[list[Annotated[int, Field(ge = 0, le = 2**53 - 1)]]],+ Field(+ min_length = 1,+ max_length = 32,+ description = "One seed per image, at most 32: a batch in one call. With prompts, the same length.",+ ),+ ] = None,+ prompts: Annotated[+ Optional[list[str]],+ Field(+ min_length = 1,+ max_length = 32,+ description = "One prompt per image for plain text-to-image, at most 32; prompt is still required.",+ ),+ ] = None,batch_size: Optional[int] = None,init_image: Optional[ImageInput] = None,mask_image: Optional[ImageInput] = None,@@ -134,12 +171,29 @@ async def generate_image(allow_oversized: bool = False,ctx: Optional[Context] = None,) -> ToolResult:- """Generate or edit images with the image model loaded in Unsloth Studio (load_model(kind="image") first). Each image is saved to the Unsloth Studio Images gallery and returned with its id and URL; images up to 1.5 MiB come back inline, larger ones as a 1024 px preview plus a link. Width and height are pixels, multiples of 16; left out, the size is 1024x1024 with 9 steps and guidance 0, which suits turbo models (raise steps and guidance for others). With ``init_image`` it is img2img (``strength`` above 0 up to 1 sets how much is redrawn; left out, the model's default); add ``mask_image`` to inpaint (white is repainted); ``upscale`` 1 to 4 enlarges ``init_image`` and lightly redraws it, still guided by the prompt; ``workflow`` "edit" follows the prompt as an instruction over init_image and ``reference_images``, "reference" draws a new image guided by them, "outpaint" fills a padded init_image under its mask. A refusal on memory grounds can be overridden with ``allow_oversized``. Progress is reported while it runs."""+ """Generate or edit images with the image model loaded in Unsloth Studio (load_model(kind="image") first).+ Each image is saved to the Unsloth Studio Images gallery and returned with its id and URL; images up to 1.5 MiB come back inline, larger ones as a 1024 px preview plus a link.+ Width and height are pixels in multiples of studio_status image.dimension_multiple; left out, the size is 1024x1024 (an edit matches init_image).+ Left out, steps and guidance come from the loaded model's defaults (studio_status image.generation_defaults).+ studio_status image.prompt_hint says how the loaded model reads prompts.+ With ``init_image`` it is img2img (``strength`` above 0 up to 1 sets how much is redrawn; left out, the model's default); add ``mask_image`` to inpaint (white is repainted).+ ``upscale`` above 1 up to 4 enlarges ``init_image`` and lightly redraws it, still guided by the prompt.+ ``workflow`` "edit" follows the prompt as an instruction over init_image and ``reference_images``.+ ``workflow`` "reference" draws a new image from the hero in init_image plus ``reference_images``; it needs init_image.+ ``workflow`` "outpaint" fills a padded init_image under its mask_image; it needs both.+ studio_status image.workflows lists what the loaded model runs, and init_image plus reference_images hold at most image.max_condition_images images.+ ``seeds`` or ``prompts`` (one per image, prompts for plain text-to-image only) make a batch in one call; give both with the same length.+ A refusal on memory grounds can be overridden with ``allow_oversized``.+ Progress is reported while it runs."""if upscale is not None and init_image is None:raise ToolError("upscale needs init_image: it enlarges that image.")caller = current_caller()body: dict[str, Any] = {"prompt": prompt}- body.update(await _image_fields(caller, init_image, mask_image, reference_images))+ body.update(+ await _image_fields(+ caller, init_image, mask_image, reference_images, workflow = workflow, upscale = upscale+ )+ )body.update(present(negative_prompt = negative_prompt,@@ -148,6 +202,8 @@ async def generate_image(steps = steps,guidance = guidance,seed = seed,+ seeds = seeds,+ prompts = prompts,batch_size = batch_size,workflow = workflow,strength = strength,diff --git a/studio/backend/studio_mcp/tools/jobs.py b/studio/backend/studio_mcp/tools/jobs.pyindex 3c45e6f615d..a9662c83455 100644--- a/studio/backend/studio_mcp/tools/jobs.py+++ b/studio/backend/studio_mcp/tools/jobs.py@@ -57,6 +57,7 @@ async def _video_job(caller: Caller, video_id: str) -> ToolResult:progress_percent = number(job.get("progress")),error = opt_text(error.get("message")),video = video,+ seed = integer(job.get("seed")),)return media_result(contents, status)diff --git a/studio/backend/studio_mcp/tools/status.py b/studio/backend/studio_mcp/tools/status.pyindex 0c05b512e13..5edcc027ad6 100644--- a/studio/backend/studio_mcp/tools/status.py+++ b/studio/backend/studio_mcp/tools/status.py@@ -68,7 +68,33 @@ def _media(slot: type, payload: dict) -> Any:return slot()model = opt_text(payload.get("display_repo_id")) or opt_text(payload.get("repo_id"))family = {"family": opt_text(payload.get("family"))} if slot is ImageSlot else {}- return slot(loaded = True, model = model, **family)+ if slot is ImageSlot:+ conditioning = as_dict(payload.get("conditioning"))+ recipe = as_dict(payload.get("generation_defaults"))+ steps, guidance = number(recipe.get("steps")), number(recipe.get("guidance"))+ overrides = {+ # The status route types these as floats, so steps arrives as 8.0.+ "generation_defaults": (+ {"steps": int(steps), "guidance": guidance}+ if steps and guidance is not None+ else None+ ),+ "dimension_multiple": integer(conditioning.get("dimension_multiple")),+ "max_condition_images": integer(conditioning.get("max_condition_images")),+ }+ else:+ presets = as_dict(payload.get("defaults")).get("resolution_presets")+ overrides = {+ "references": payload.get("supports_references") is True,+ "size_presets": [+ f"{preset[0]}x{preset[1]}"+ for preset in (presets if isinstance(presets, list) else [])+ if isinstance(preset, list)+ and len(preset) == 2+ and all(integer(side) for side in preset)+ ],+ }+ return slot.from_route(payload, loaded = True, model = model, **family, **overrides)def _stt(payload: dict) -> SttSlot:diff --git a/studio/backend/studio_mcp/tools/video.py b/studio/backend/studio_mcp/tools/video.pyindex 6a48515ebdd..d527b572ffa 100644--- a/studio/backend/studio_mcp/tools/video.py+++ b/studio/backend/studio_mcp/tools/video.py@@ -5,16 +5,53 @@from __future__ import annotations-from typing import Any, Optional+import json+from pathlib import Path+from typing import Annotated, Any, Optional, Unionfrom fastmcp.exceptions import ToolError+from pydantic import Fieldfrom studio_mcp.caller import current_caller-from studio_mcp.inputs import ImageInput, data_url, resolve_image+from studio_mcp.inputs import (+ AudioInput,+ ImageInput,+ audio_ref,+ data_url,+ resolve_image,+ resolve_images,+)from studio_mcp.outputs import VideoJobReffrom studio_mcp.tools import WRITES, opt_text, present, route_json+from utils.upload_limits import (+ VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,+ VIDEO_INPUT_REFERENCE_MAX_BYTES,+)LOAD_VIDEO_HINT = "Load a video model with load_model(kind='video') first."+# /v1/videos takes a reference audio of at most 24 MB.+MAX_REFERENCE_AUDIO_BYTES = 24 * 1024 * 1024+# /v1/videos takes at most this many frames (MAX_VIDEO_NUM_FRAMES).+MAX_NUM_FRAMES = 1024+# One /v1/videos request carries about 32 MB of images once base64-encoded.+TOO_MANY_IMAGE_BYTES = (+ "The images together are larger than the 32 MB one video request takes; "+ "send fewer or smaller images."+)+++def _refuse_large_audio(caller: Any, audio: AudioInput) -> None:+ """Refuse audio over the video cap before audio_ref reads and stores it."""+ size = None+ if audio.path is not None and caller.direct_local:+ try:+ size = Path(audio.path).expanduser().stat().st_size+ except OSError:+ return # audio_ref reports the missing file+ elif audio.data_base64 is not None:+ size = len(audio.data_base64) * 3 // 4+ if size is not None and size > MAX_REFERENCE_AUDIO_BYTES:+ raise ToolError("Reference audio is larger than the 24 MB a video takes.")def job_ref(job: Any) -> VideoJobRef:@@ -25,17 +62,132 @@ def job_ref(job: Any) -> VideoJobRef:async def generate_video(prompt: str,- seconds: Optional[str] = None,+ seconds: Annotated[+ Optional[Union[int, float, str]],+ Field(+ description = "Clip length in seconds, a number or a string; left out, the model's default."+ ),+ ] = None,size: Optional[str] = None,first_frame: Optional[ImageInput] = None,model: Optional[str] = None,+ last_frame: Annotated[+ Optional[ImageInput],+ Field(description = "Image the clip ends on (studio_status video.supports_last_frame)."),+ ] = None,+ reference_images: Annotated[+ Optional[list[ImageInput]],+ Field(+ max_length = 9,+ description = "Up to 9 subject, style or scene references, called <Picture 1>, <Picture 2>, ... in the prompt (studio_status video.references).",+ ),+ ] = None,+ reference_audios: Annotated[+ Optional[list[AudioInput]],+ Field(+ max_length = 3,+ description = "Up to 3 voice or score references of up to 24 MB each, called <Audio 1>, ... in the prompt; they need reference_images.",+ ),+ ] = None,+ negative_prompt: Annotated[+ Optional[str], Field(description = "What the video should avoid.")+ ] = None,+ seed: Annotated[+ Optional[int],+ Field(+ ge = 0,+ le = 2**53 - 1,+ description = "Reuse a take's seed to repeat it; left out, Unsloth Studio picks one and returns it.",+ ),+ ] = None,+ steps: Annotated[+ Optional[int],+ Field(ge = 1, le = 100, description = "Denoising steps; left out, the model's default."),+ ] = None,+ guidance: Annotated[+ Optional[float],+ Field(ge = 0, le = 20, description = "Guidance scale; left out, the model's default."),+ ] = None,+ num_frames: Annotated[+ Optional[int],+ Field(+ ge = 1,+ le = MAX_NUM_FRAMES,+ description = "Frame count instead of seconds; send one of them.",+ ),+ ] = None,+ fps: Annotated[+ Optional[int],+ Field(ge = 1, le = 120, description = "Playback frame rate; left out, the model's default."),+ ] = None,) -> VideoJobRef:- """Start a video with the video model loaded in Unsloth Studio (load_model(kind="video") first) and return its job at once; poll get_job(kind="video", id=...) until it is completed, which returns a thumbnail and the video's URL. ``seconds`` and ``size`` ("WIDTHxHEIGHT") are strings, as in the OpenAI API; leave them out to use the model's defaults. Each video model takes only certain sizes, and an unsupported one is refused with the list it accepts. ``first_frame`` starts the video from an image."""+ """Start a video with the video model loaded in Unsloth Studio (load_model(kind="video") first) and return its job at once.+ Poll get_job(kind="video", id=...) until it is completed, which returns a thumbnail and the video's URL.+ Unsloth Studio renders one video at a time: while one runs, another call is refused with HTTP 409, so wait for the first to finish.+ ``seconds`` is a number or a string and ``size`` is "WIDTHxHEIGHT" from studio_status video.size_presets; leave them out to use the model's defaults.+ ``model`` names a video model for Unsloth Studio to switch to when its automatic model switching is on; otherwise the loaded model runs.+ ``first_frame`` starts the video from an image and ``last_frame`` ends it on one, where the model takes it.+ ``reference_images`` and ``reference_audios`` condition a references model (studio_status video.references).+ The job carries the ``seed`` it used; pass it again with the same settings to repeat a take.+ studio_status video.prompt_hint says how the loaded model reads prompts."""caller = current_caller()- body: dict[str, Any] = {"prompt": prompt, **present(seconds = seconds, size = size, model = model)}- if first_frame is not None:- data, mime = await resolve_image(caller, first_frame)- body["input_reference"] = data_url(data, mime)+ if isinstance(seconds, str) and seconds.strip().lower() in ("", "auto"):+ seconds = None # /v1/videos reads both as an omitted duration+ body: dict[str, Any] = {+ "prompt": prompt,+ **present(+ seconds = seconds,+ size = size,+ model = model,+ negative_prompt = negative_prompt,+ seed = seed,+ steps = steps,+ guidance = guidance,+ num_frames = num_frames,+ fps = fps,+ ),+ }+ if reference_audios and not reference_images and first_frame is None:+ raise ToolError("reference_audios need a reference image to go with: add reference_images.")+ # Refused here as /v1/videos would, so no audio is uploaded for a call that cannot run.+ if seconds is not None and num_frames is not None:+ raise ToolError("Send seconds or num_frames, not both.")+ if last_frame is not None and (reference_images or reference_audios):+ raise ToolError("last_frame cannot be combined with reference_images or reference_audios.")+ if first_frame is not None and reference_images:+ raise ToolError(+ "first_frame cannot be combined with reference_images; send that image as a reference_images entry."+ )+ for audio in reference_audios or []:+ _refuse_large_audio(caller, audio)+ budget = VIDEO_INPUT_REFERENCE_MAX_BYTES+ for key, image in (("input_reference", first_frame), ("last_frame", last_frame)):+ if image is not None:+ data, mime = await resolve_image(+ caller, image, max_bytes = VIDEO_INPUT_REFERENCE_MAX_BYTES+ )+ budget -= len(data)+ if budget < 0:+ raise ToolError(TOO_MANY_IMAGE_BYTES)+ body[key] = data_url(data, mime)+ if reference_images:+ body["reference_images"] = await resolve_images(+ caller,+ reference_images,+ total_cap = budget,+ too_large = TOO_MANY_IMAGE_BYTES,+ max_bytes = VIDEO_INPUT_REFERENCE_MAX_BYTES,+ )+ # The request size cap counts the encoded body, prompt included. Checked before any audio is+ # uploaded, with room for the short ids the uploads add, so a refused call stores nothing.+ sized = dict(body)+ if reference_audios:+ # An id is at most 128 characters.+ sized["reference_audios"] = [{"input_id": "x" * 128} for _ in reference_audios]+ if len(json.dumps(sized)) > VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES:+ raise ToolError(TOO_MANY_IMAGE_BYTES)+ if reference_audios:+ body["reference_audios"] = [await audio_ref(caller, audio) for audio in reference_audios]job = await route_json("POST","/v1/videos",diff --git a/studio/backend/tests/test_diffusion_prompt_hint.py b/studio/backend/tests/test_diffusion_prompt_hint.pynew file mode 100644index 00000000000..cd755e97735--- /dev/null+++ b/studio/backend/tests/test_diffusion_prompt_hint.py@@ -0,0 +1,94 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""``prompt_hint``: the per-family prompt tip, from the family row to every image engine's status.++Only vetted families carry a tip. Each engine's loaded status copies the family's value, and+``DiffusionStatusResponse`` has to declare the key, since the route builds it with ``**status``+and Pydantic drops undeclared keys.+"""++from __future__ import annotations++import dataclasses+import re+import sys+from pathlib import Path++import pytest++from core.inference.diffusion_families import _FAMILIES, DiffusionFamily, detect_family+from models.inference import DiffusionStatusResponse++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++# Reuse each engine's own fixtures so the status read here is the real one.+from test_diffusion_backend import ( # noqa: E402,F401+ _loaded_backend as _loaded_diffusers_backend,+ _unmeasured_torchao,+ fake_runtime,+)+from test_mlx_diffusion_backend import _load as _load_mlx, env # noqa: E402,F401+from test_sd_cpp_backend import _loaded_backend as _loaded_sd_cpp_backend # noqa: E402++_TIPPED = {"flux.1-kontext", "qwen-image-edit", "qwen-image-2.1", "ideogram-4"}+_HINT = "Describe the scene first."+++def test_prompt_hint_defaults_to_none():+ assert DiffusionFamily.__dataclass_fields__["prompt_hint"].default is None+++def test_only_the_vetted_families_carry_a_tip():+ assert {f.name for f in _FAMILIES if f.prompt_hint is not None} == _TIPPED++[email protected]("name", sorted(_TIPPED))+def test_each_tip_is_short_and_names_unsloth_studio_in_full(name):+ hint = detect_family(name).prompt_hint+ assert hint and len(hint) <= 240+ # One or two sentences.+ assert 1 <= len(re.findall(r"[.!?](?:\s|\"?$)", hint)) <= 2+ assert not re.search(r"(?<!Unsloth )\bStudio\b", hint)+++def _tipped_state(state, hint = _HINT):+ return dataclasses.replace(state, family = dataclasses.replace(state.family, prompt_hint = hint))+++def test_diffusers_status_carries_the_family_tip(fake_runtime, tmp_path):+ backend = _loaded_diffusers_backend(tmp_path)+ assert backend.status()["prompt_hint"] is None+ assert DiffusionStatusResponse(**backend.status()).prompt_hint is None++ backend._state = _tipped_state(backend._state)+ assert backend.status()["prompt_hint"] == _HINT+ assert DiffusionStatusResponse(**backend.status()).prompt_hint == _HINT++ backend.unload()+ assert DiffusionStatusResponse(**backend.status()).prompt_hint is None+++def test_sd_cpp_status_carries_the_family_tip():+ assert _loaded_sd_cpp_backend("z-image").status()["prompt_hint"] is None++ backend = _loaded_sd_cpp_backend("flux.1-kontext")+ hint = detect_family("flux.1-kontext").prompt_hint+ assert backend.status()["prompt_hint"] == hint+ assert DiffusionStatusResponse(**backend.status()).prompt_hint == hint++ backend._state = None+ assert DiffusionStatusResponse(**backend.status()).prompt_hint is None+++def test_mlx_status_carries_the_family_tip(env):+ backend, _runtime, _calls = env+ assert DiffusionStatusResponse(**backend.status()).prompt_hint is None+ assert _load_mlx(backend)["phase"] == "ready"+ assert backend.status()["prompt_hint"] is None++ backend._state = _tipped_state(backend._state)+ assert backend.status()["prompt_hint"] == _HINT+ assert DiffusionStatusResponse(**backend.status()).prompt_hint == _HINTdiff --git a/studio/backend/tests/test_image_generate_model_defaults.py b/studio/backend/tests/test_image_generate_model_defaults.pynew file mode 100644index 00000000000..653ffe49b6f--- /dev/null+++ b/studio/backend/tests/test_image_generate_model_defaults.py@@ -0,0 +1,158 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""/images/generate fills omitted steps and guidance from the loaded model, like /v1/images."""++from __future__ import annotations++from fastapi import HTTPException++import core.inference.diffusion as diffusion_module+import routes.inference as inference_routes+from core.inference.diffusion_families import DiffusionModelReplacedError, load_identity++from .test_diffusion_routes import _FakeBackend, _unloaded_status, client # noqa: F401 (fixture)++TURBO = {"repo_id": "unsloth/Z-Image-Turbo", "generation_defaults": {"steps": 8, "guidance": 0.0}}+DEV = {"repo_id": "unsloth/FLUX.1-dev", "generation_defaults": {"steps": 28, "guidance": 3.5}}+++class _ModelBackend(_FakeBackend):+ """Loaded with ``models[0]``; each generate swaps in the next one first, as a replacement landing mid-request would."""++ def __init__(+ self,+ *models,+ loaded = True,+ ) -> None:+ super().__init__()+ self.loaded = loaded+ self.models = [dict(m) for m in models]+ self.calls: list[dict] = []+ self.status_calls = 0++ def _identity(self):+ model = self.models[0]+ return load_identity(model.get("repo_id"), model.get("base_repo"), "z-image")++ def status(self):+ self.status_calls += 1+ if not self.loaded:+ return _unloaded_status()+ return {**_unloaded_status(), "loaded": True, "family": "z-image", **self.models[0]}++ def generate(self, **kwargs):+ self.calls.append(kwargs)+ if not self.loaded:+ return super().generate(**kwargs)+ if len(self.models) > 1:+ self.models.pop(0)+ expected = kwargs.get("expected_load")+ if expected is not None and expected != self._identity():+ raise DiffusionModelReplacedError(expected, self._identity())+ return super().generate(**kwargs)+++def _use(monkeypatch, backend):+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)+ return backend+++def _recipe(response):+ assert response.status_code == 200, response.text+ image = response.json()["images"][0]+ return image["steps"], image["guidance"]+++def test_omitted_steps_and_guidance_follow_the_status_recipe(client, monkeypatch):+ backend = _use(monkeypatch, _ModelBackend(DEV))+ response = client.post("/api/inference/images/generate", json = {"prompt": "a sloth"})+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (28, 3.5)+ assert _recipe(response) == (28, 3.5)+ assert backend.calls[0]["expected_load"] == load_identity("unsloth/FLUX.1-dev", None, "z-image")+++def test_without_a_status_recipe_the_family_table_decides(client, monkeypatch):+ # sd.cpp and MLX report no generation_defaults; base_repo names FLUX.1-dev for a local path.+ flux = {"repo_id": "/models/my-flux", "base_repo": "black-forest-labs/FLUX.1-dev"}+ backend = _use(monkeypatch, _ModelBackend(flux))+ response = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert _recipe(response) == (20, 3.5)+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (20, 3.5)++ backend = _use(monkeypatch, _ModelBackend({"repo_id": "/models/opaque"}))+ response = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert _recipe(response) == (9, 0.0)+++def test_only_the_omitted_value_is_filled(client, monkeypatch):+ backend = _use(monkeypatch, _ModelBackend(DEV))+ response = client.post("/api/inference/images/generate", json = {"prompt": "p", "steps": 12})+ assert _recipe(response) == (12, 3.5)+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (12, 3.5)+++def test_explicit_values_equal_to_the_schema_defaults_stay_and_skip_the_status_read(+ client, monkeypatch+):+ backend = _use(monkeypatch, _ModelBackend(DEV))+ response = client.post(+ "/api/inference/images/generate", json = {"prompt": "p", "steps": 9, "guidance": 0.0}+ )+ assert _recipe(response) == (9, 0.0)+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (9, 0.0)+ # The one read is FLUX.3 prompt upsampling's family probe (#14137); the defaults add none.+ assert backend.status_calls == 1+ assert backend.calls[0]["expected_load"] is None+++def test_a_replacement_retry_uses_the_new_models_defaults_and_pins_it(client, monkeypatch):+ # Turbo is swapped for FLUX.1-dev between the status read and generate (#9448).+ backend = _use(monkeypatch, _ModelBackend(TURBO, DEV))+ response = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert [(c["steps"], c["guidance"]) for c in backend.calls] == [(8, 0.0), (28, 3.5)]+ assert backend.calls[0]["expected_load"] == load_identity(+ "unsloth/Z-Image-Turbo", None, "z-image"+ )+ assert backend.calls[1]["expected_load"] == load_identity("unsloth/FLUX.1-dev", None, "z-image")+ assert _recipe(response) == (28, 3.5)+++def test_external_provider_requests_never_read_status(client, monkeypatch):+ backend = _use(monkeypatch, _ModelBackend(DEV))++ async def external(request, http_request):+ raise HTTPException(status_code = 418, detail = (request.steps, request.guidance))++ monkeypatch.setattr(inference_routes, "_external_image_generation", external)+ response = client.post(+ "/api/inference/images/generate", json = {"prompt": "p", "provider_id": "openai-1"}+ )+ assert response.status_code == 418+ assert response.json()["detail"] == [9, 0.0]+ assert backend.status_calls == 0 and backend.calls == []+++def test_an_unloaded_model_is_still_a_409_with_no_fill(client, monkeypatch):+ backend = _use(monkeypatch, _ModelBackend(DEV, loaded = False))+ response = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert response.status_code == 409+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (9, 0.0)+ assert backend.calls[0]["expected_load"] == load_identity(None, None, None)+++class _LoadingBackend(_ModelBackend):+ """Reads unloaded while another client's load runs; generate is admitted once it commits."""++ def generate(self, **kwargs):+ self.loaded = True+ return super().generate(**kwargs)+++def test_a_load_in_flight_hands_the_retry_the_new_models_defaults(client, monkeypatch):+ backend = _use(monkeypatch, _LoadingBackend(DEV, loaded = False))+ response = client.post("/api/inference/images/generate", json = {"prompt": "p"})+ assert [(c["steps"], c["guidance"]) for c in backend.calls] == [(9, 0.0), (28, 3.5)]+ assert backend.calls[0]["expected_load"] == load_identity(None, None, None)+ assert backend.calls[1]["expected_load"] == load_identity("unsloth/FLUX.1-dev", None, "z-image")+ assert _recipe(response) == (28, 3.5)diff --git a/studio/backend/tests/test_mcp_status_media_slots.py b/studio/backend/tests/test_mcp_status_media_slots.pynew file mode 100644index 00000000000..247984a41bc--- /dev/null+++ b/studio/backend/tests/test_mcp_status_media_slots.py@@ -0,0 +1,102 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""studio_status image and video slots carry what an agent needs to call the generate tools right: workflows, the defaults an omitted value resolves to, the size multiple, the image cap, the prompt tip and the video controls."""++from studio_mcp.outputs import ImageSlot, VideoSlot+from studio_mcp.tools.status import BUILDERS, _media++from .test_mcp_tools_status import PAYLOADS, _status++IMAGE_STATUS = {+ "loaded": True,+ "repo_id": "/srv/hf/qwen",+ "display_repo_id": "Qwen/Qwen-Image-2.1",+ "family": "qwen-image-2.1",+ "workflows": ["txt2img", "img2img", "edit", "reference"],+ # The status route types these as floats.+ "generation_defaults": {"steps": 8.0, "guidance": 4.0},+ "conditioning": {"dimension_multiple": 32, "max_condition_images": 10, "other": "x"},+ "prompt_hint": "Refer to inputs as Image 1, Image 2.",+}+LTX_STATUS = {+ "loaded": True,+ "repo_id": "Lightricks/LTX-2",+ "supports_last_frame": False,+ "supports_references": False,+ "defaults": {"resolution_presets": [[768, 512], [512, 768], ["x", 1], [640]]},+ "prompt_hint": None,+}+H3_STATUS = {+ "loaded": True,+ "repo_id": "MiniMax/H3",+ "supports_last_frame": True,+ "supports_references": True,+ "defaults": {"resolution_presets": [[1280, 720]]},+ "prompt_hint": "A tip.",+}+++def test_image_slot_reads_workflows_defaults_and_conditioning_limits():+ slot = _media(ImageSlot, IMAGE_STATUS)+ assert slot.model == "Qwen/Qwen-Image-2.1"+ assert slot.family == "qwen-image-2.1"+ assert slot.workflows == ["txt2img", "img2img", "edit", "reference"]+ assert slot.generation_defaults == {"steps": 8, "guidance": 4.0}+ assert type(slot.generation_defaults["steps"]) is int+ assert slot.dimension_multiple == 32+ assert slot.max_condition_images == 10+ assert slot.prompt_hint == "Refer to inputs as Image 1, Image 2."+++def test_image_slot_drops_malformed_fields():+ payload = {+ **IMAGE_STATUS,+ "generation_defaults": {"steps": None, "guidance": 1.0},+ "conditioning": {"dimension_multiple": True, "max_condition_images": "10"},+ "workflows": ["txt2img", 3],+ "prompt_hint": "",+ }+ slot = _media(ImageSlot, payload)+ assert slot.generation_defaults is None+ assert slot.dimension_multiple is None+ assert slot.max_condition_images is None+ assert slot.workflows == ["txt2img"]+ assert slot.prompt_hint is None+++def test_video_slot_reads_controls_and_size_presets():+ ltx = _media(VideoSlot, LTX_STATUS)+ assert ltx.model == "Lightricks/LTX-2"+ assert ltx.supports_last_frame is False+ assert ltx.references is False+ assert ltx.size_presets == ["768x512", "512x768"]+ assert ltx.prompt_hint is None+ h3 = _media(VideoSlot, H3_STATUS)+ assert (h3.supports_last_frame, h3.references, h3.size_presets) == (True, True, ["1280x720"])+ assert h3.prompt_hint == "A tip."+++def test_unloaded_slots_keep_their_defaults():+ assert _media(ImageSlot, {**IMAGE_STATUS, "loaded": False}) == ImageSlot()+ assert _media(VideoSlot, {**H3_STATUS, "loaded": False}) == VideoSlot()+++def test_builders_still_use_media():+ # Placement wraps these entries later, so they stay plain _media partials.+ for name, slot in (("image", ImageSlot), ("video", VideoSlot)):+ assert BUILDERS[name].func is _media+ assert BUILDERS[name].args == (slot,)+++def test_studio_status_reports_the_new_fields(monkeypatch):+ overrides = {+ ("GET", "/api/inference/images/status"): IMAGE_STATUS,+ ("GET", "/api/inference/video/status"): H3_STATUS,+ }+ status = _status(monkeypatch, {**PAYLOADS, **overrides})[0]["structuredContent"]+ assert status["image"]["generation_defaults"] == {"steps": 8, "guidance": 4.0}+ assert status["image"]["max_condition_images"] == 10+ assert status["image"]["prompt_hint"] == "Refer to inputs as Image 1, Image 2."+ assert status["video"]["references"] is True+ assert status["video"]["size_presets"] == ["1280x720"]diff --git a/studio/backend/tests/test_mcp_tools_images.py b/studio/backend/tests/test_mcp_tools_images.pyindex 29f07229b0d..d1fb5dcb96a 100644--- a/studio/backend/tests/test_mcp_tools_images.py+++ b/studio/backend/tests/test_mcp_tools_images.py@@ -95,7 +95,15 @@ def test_txt2img_returns_ids_urls_and_inline_images(monkeypatch):remote = "http://192.168.1.20:8888" + GALLERYassert result["structuredContent"] == {"images": [- {"id": i, "url": f"{remote}/{i}/file", "width": side, "height": side, "seed": seed}+ {+ "id": i,+ "url": f"{remote}/{i}/file",+ "width": side,+ "height": side,+ "seed": seed,+ "batch_seed": None,+ "batch_index": None,+ }for i, side, seed in (("img-small", 512, 1), ("img-large", 1024, 2))]}@@ -119,6 +127,81 @@ def test_txt2img_returns_ids_urls_and_inline_images(monkeypatch):assert headers["host"] == "unsloth-mcp.invalid"+REFUSALS = {+ "R1": "Reference needs init_image: pass the hero as init_image plus reference_images.",+ "R2": 'workflow="edit" needs init_image: it is the image the instruction changes.',+ "R3": 'workflow="outpaint" needs init_image: it is the image to extend.',+ "R4": 'workflow="outpaint" needs mask_image: white marks the padded border to fill.',+ "R5": "upscale must be above 1 (up to 4); for a same-size redraw leave upscale out and set strength.",+}+++ "refusal,args",+ [+ ("R1", {"reference_images": [PNG_URL]}),+ ("R1", {"reference_images": [{"gallery_id": "ref-1"}]}),+ ("R1", {"workflow": "reference"}),+ ("R1", {"workflow": "reference", "reference_images": [{"gallery_id": "ref-1"}]}),+ ("R2", {"workflow": "edit"}),+ ("R3", {"workflow": "outpaint"}),+ ("R4", {"workflow": "outpaint", "init_image": PNG_URL}),+ ("R4", {"workflow": "outpaint", "init_image": {"gallery_id": "src-1"}}),+ ("R5", {"init_image": PNG_URL, "upscale": 1}),+ ("R5", {"init_image": {"gallery_id": "src-1"}, "upscale": 0.5}),+ ],+)+def test_a_workflow_missing_its_images_is_refused_before_any_call(monkeypatch, refusal, args):+ result, studio = _generate(monkeypatch, {"prompt": "the same knight", **args})+ assert result["isError"] is True+ assert REFUSALS[refusal] in result["content"][0]["text"]+ # Refused before resolve_image, so a gallery_id input is never fetched.+ assert studio.state.calls == []+++def test_upscale_without_init_image_keeps_its_own_refusal(monkeypatch):+ result, studio = _generate(monkeypatch, {"prompt": "x", "upscale": 1})+ assert result["isError"] is True+ assert result["content"][0]["text"].startswith("upscale needs init_image")+ assert studio.state.calls == []+++ "args",+ [+ {"workflow": "reference", "init_image": PNG_URL, "reference_images": [PNG_URL]},+ {"init_image": PNG_URL, "reference_images": [PNG_URL, PNG_URL]},+ {"workflow": "outpaint", "init_image": PNG_URL, "mask_image": PNG_URL},+ {"init_image": PNG_URL, "mask_image": PNG_URL},+ {"workflow": "edit", "init_image": PNG_URL},+ {"init_image": PNG_URL, "upscale": 2},+ ],+)+def test_workflows_with_their_images_send_the_same_body(monkeypatch, args):+ result, studio = _generate(monkeypatch, {"prompt": "x", **args})+ assert result["isError"] is False+ png = data_url(PNG, "image/png")+ images = {+ key: [png] * len(value) if isinstance(value, list) else png+ for key, value in args.items()+ if key in ("init_image", "mask_image", "reference_images")+ }+ assert bodies(studio, "/api/inference/images/generate") == [{"prompt": "x", **args, **images}]+++def test_seeds_and_prompts_make_a_batch_and_rows_carry_their_batch_fields(monkeypatch):+ rows = [+ {**_image("img-small", 512, 11), "batch_seed": 11, "batch_index": 0},+ {**_image("img-large", 1024, 12), "batch_seed": 12, "batch_index": 1},+ ]+ args = {"prompt": "a fox", "seeds": [11, 12], "prompts": ["a fox", "a fox at night"]}+ result, studio = _generate(monkeypatch, args, {GENERATE: {"images": rows}})+ assert result["isError"] is False+ assert bodies(studio, "/api/inference/images/generate") == [args]+ images = result["structuredContent"]["images"]+ assert [(i["batch_seed"], i["batch_index"]) for i in images] == [(11, 0), (12, 1)]++def test_a_thumbnail_studio_could_not_make_keeps_its_png_type(monkeypatch):# The gallery route answers a failed thumbnail with the original PNG.result, _studio = _generate(diff --git a/studio/backend/tests/test_mcp_tools_status.py b/studio/backend/tests/test_mcp_tools_status.pyindex 1d3ef4f9b07..89b167a6456 100644--- a/studio/backend/tests/test_mcp_tools_status.py+++ b/studio/backend/tests/test_mcp_tools_status.py@@ -66,6 +66,21 @@ HARDWARE = {],}+# The image and video slot fields a payload without them leaves at their defaults.+IMAGE_EXTRAS = {+ "workflows": [],+ "generation_defaults": None,+ "dimension_multiple": None,+ "max_condition_images": None,+ "prompt_hint": None,+}+VIDEO_EXTRAS = {+ "prompt_hint": None,+ "supports_last_frame": False,+ "references": False,+ "size_presets": [],+}+PAYLOADS = {("GET", "/api/inference/status"): CHAT,("GET", "/api/inference/images/status"): {@@ -126,9 +141,15 @@ def test_every_slot_is_reported(monkeypatch):"loaded": True,"model": "black-forest-labs/FLUX.1-schnell","family": "flux",+ **IMAGE_EXTRAS,+ "generating": False,+ }+ assert status["video"] == {+ "loaded": True,+ "model": "Lightricks/LTX-Video",+ **VIDEO_EXTRAS,"generating": False,}- assert status["video"] == {"loaded": True, "model": "Lightricks/LTX-Video", "generating": False}assert status["stt"] == {"engine": "gguf","model": "whisper-large-v3-turbo-q5",@@ -203,7 +224,7 @@ def test_failing_and_owner_only_slots_do_not_fail_the_tool(monkeypatch):assert set(status["unavailable"]) == {"video"}assert "Video backend crashed" in status["unavailable"]["video"]assert "/srv/hf" not in status["unavailable"]["video"]- assert status["video"] == {"loaded": False, "model": None, "generating": False}+ assert status["video"] == {"loaded": False, "model": None, **VIDEO_EXTRAS, "generating": False}assert status["embedder"] == {"available": False, "loaded": False, "model": None}assert status["image"]["generating"] is Trueassert status["chat"]["loaded"]@@ -256,5 +277,11 @@ def test_unloaded_slots_name_no_model(monkeypatch):("GET", "/api/inference/video/status"): {"loaded": False},}status = _status(monkeypatch, overrides)[0]["structuredContent"]- assert status["image"] == {"loaded": False, "model": None, "family": None, "generating": False}- assert status["video"] == {"loaded": False, "model": None, "generating": False}+ assert status["image"] == {+ "loaded": False,+ "model": None,+ "family": None,+ **IMAGE_EXTRAS,+ "generating": False,+ }+ assert status["video"] == {"loaded": False, "model": None, **VIDEO_EXTRAS, "generating": False}diff --git a/studio/backend/tests/test_mcp_tools_video.py b/studio/backend/tests/test_mcp_tools_video.pyindex d3d6566d019..739239e5277 100644--- a/studio/backend/tests/test_mcp_tools_video.py+++ b/studio/backend/tests/test_mcp_tools_video.py@@ -79,6 +79,7 @@ def test_generate_video_starts_a_job_with_string_fields(monkeypatch):"model": "Lightricks/LTX-Video","seconds": "4","size": "704x480",+ "seed": None,}assert bodies(studio, "/v1/videos") == [{@@ -97,6 +98,7 @@ def test_a_completed_job_returns_its_thumbnail_and_a_link_never_the_mp4(monkeypaassert out == {"kind": "video","id": "video-1",+ "seed": None,"status": "completed","progress_percent": 100.0,"error": None,diff --git a/studio/backend/tests/test_mcp_tools_video_controls.py b/studio/backend/tests/test_mcp_tools_video_controls.pynew file mode 100644index 00000000000..9925173531c--- /dev/null+++ b/studio/backend/tests/test_mcp_tools_video_controls.py@@ -0,0 +1,231 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""generate_video's controls reach /v1/videos, and the job's seed comes back on generate_video and get_job."""++import base64++import pytest+from fastapi.responses import JSONResponse, Response++from .mcp_harness import PNG, PNG_URL, WEBP, b64, bodies, data_url, fake_studio, run_tool+from .test_mcp_tools_video import _job++_PNG_DATA_URL = data_url(PNG, "image/png")+_WAV = b"RIFF\x24\x00\x00\x00WAVEfmt fake"+++def _studio(job = None):+ job = job or _job("video-1", "queued", 0, seed = 1234)+ return fake_studio(+ {+ ("POST", "/v1/videos"): job,+ ("GET", "/v1/videos/video-1"): job,+ ("GET", "/v1/videos/video-1/content"): Response(WEBP, media_type = "image/webp"),+ ("POST", "/v1/audio/inputs"): JSONResponse({"id": "in-1"}, status_code = 201),+ }+ )+++def test_every_control_lands_in_the_body(monkeypatch):+ args = {+ "prompt": "a singer",+ "seconds": 4,+ "negative_prompt": "blur",+ "seed": 7,+ "steps": 20,+ "guidance": 4.5,+ "fps": 24,+ "reference_images": [PNG_URL, PNG_URL],+ "reference_audios": [+ {"data_base64": b64(_WAV), "filename": "voice.wav"},+ {"clip_id": "clip-1"},+ {"voice_id": "voice-1"},+ ],+ }+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is False, result+ (body,) = bodies(studio, "/v1/videos")+ assert body == {+ "prompt": "a singer",+ "seconds": 4,+ "negative_prompt": "blur",+ "seed": 7,+ "steps": 20,+ "guidance": 4.5,+ "fps": 24,+ "reference_images": [_PNG_DATA_URL, _PNG_DATA_URL],+ "reference_audios": [{"input_id": "in-1"}, {"clip_id": "clip-1"}, {"voice_id": "voice-1"}],+ }+ upload = next(c for c in studio.state.calls if c[1] == "/v1/audio/inputs")+ assert upload[3] == _WAV+++def test_last_frame_num_frames_and_a_string_seconds_are_forwarded(monkeypatch):+ args = {"prompt": "x", "seconds": "4", "first_frame": PNG_URL, "last_frame": PNG_URL}+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is False, result+ body = bodies(studio, "/v1/videos")[0]+ assert body["seconds"] == "4"+ assert body["last_frame"] == body["input_reference"] == _PNG_DATA_URL+ result, studio = run_tool(+ monkeypatch, _studio(), "generate_video", {"prompt": "x", "num_frames": 49}+ )+ assert bodies(studio, "/v1/videos") == [{"prompt": "x", "num_frames": 49}]+++def test_audio_without_a_reference_image_is_refused_before_any_call(monkeypatch):+ args = {"prompt": "x", "reference_audios": [{"data_base64": b64(_WAV), "filename": "v.wav"}]}+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is True+ assert "reference_audios need a reference image to go with" in result["content"][0]["text"]+ assert studio.state.calls == []+++ "args",+ [+ {"reference_images": [PNG_URL] * 10},+ {"reference_images": [PNG_URL], "reference_audios": [{"clip_id": "c"}] * 4},+ {"seed": 2**53},+ {"steps": 0},+ {"fps": 121},+ {"num_frames": 1025},+ ],+)+def test_out_of_range_controls_never_reach_a_route(monkeypatch, args):+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", {"prompt": "x", **args})+ assert result["isError"] is True+ assert studio.state.calls == []+++def test_the_seed_comes_back_on_the_job_and_on_get_job(monkeypatch):+ result, _studio_app = run_tool(monkeypatch, _studio(), "generate_video", {"prompt": "x"})+ assert result["structuredContent"]["seed"] == 1234+ done = _job("video-1", "completed", 100, seed = 1234)+ result, _studio_app = run_tool(+ monkeypatch, _studio(done), "get_job", {"kind": "video", "id": "video-1"}+ )+ assert result["structuredContent"]["seed"] == 1234+ assert base64.b64decode(result["content"][1]["data"]) == WEBP+++def test_images_share_the_one_request_budget_of_video_requests(monkeypatch):+ import studio_mcp.tools.video as video_tool++ # The budget covers first_frame, last_frame and reference_images together.+ monkeypatch.setattr(video_tool, "VIDEO_INPUT_REFERENCE_MAX_BYTES", 2 * len(PNG))+ for ok in (+ {"prompt": "x", "first_frame": PNG_URL, "last_frame": PNG_URL},+ {"prompt": "x", "reference_images": [PNG_URL] * 2},+ ):+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", ok)+ assert result["isError"] is False, result+ monkeypatch.setattr(video_tool, "VIDEO_INPUT_REFERENCE_MAX_BYTES", 2 * len(PNG) - 1)+ for args in (+ {"prompt": "x", "first_frame": PNG_URL, "last_frame": PNG_URL},+ {"prompt": "x", "reference_images": [PNG_URL] * 2},+ ):+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is True+ assert "larger than the 32 MB one video request takes" in result["content"][0]["text"]+ assert studio.state.calls == []+++def test_a_body_over_the_route_cap_is_refused_before_the_call(monkeypatch):+ import studio_mcp.tools.video as video_tool++ # The route counts the encoded body, so a long prompt beside the images counts too.+ monkeypatch.setattr(video_tool, "VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES", 1024)+ args = {"prompt": "x" * 2048, "reference_images": [PNG_URL]}+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is True+ assert studio.state.calls == []+++def test_reference_audio_over_the_video_cap_is_refused_before_any_upload(monkeypatch, tmp_path):+ import studio_mcp.tools.video as video_tool+ from fastmcp.exceptions import ToolError+ from studio_mcp.inputs import AudioInput++ from .mcp_harness import make_caller++ monkeypatch.setattr(video_tool, "MAX_REFERENCE_AUDIO_BYTES", len(_WAV) - 1)+ audio = {"data_base64": b64(_WAV), "filename": "v.wav"}+ args = {"prompt": "x", "reference_images": [PNG_URL], "reference_audios": [audio]}+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is True+ assert "larger than the 24 MB a video takes" in result["content"][0]["text"]+ assert studio.state.calls == []+ # A local file is sized from disk, before audio_ref reads or uploads it.+ clip = tmp_path / "voice.wav"+ clip.write_bytes(_WAV)+ with pytest.raises(ToolError, match = "24 MB"):+ video_tool._refuse_large_audio(make_caller(), AudioInput(path = str(clip)))+++ "args, text",+ [+ ({"seconds": 4, "num_frames": 49}, "not both"),+ ({"last_frame": PNG_URL}, "last_frame cannot be combined"),+ ({"first_frame": PNG_URL}, "first_frame cannot be combined"),+ ],+)+def test_combinations_the_route_refuses_never_upload_audio(monkeypatch, args, text):+ audio = {"data_base64": b64(_WAV), "filename": "v.wav"}+ body = {"prompt": "x", "reference_images": [PNG_URL], "reference_audios": [audio], **args}+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", body)+ assert result["isError"] is True+ assert text in result["content"][0]["text"]+ assert studio.state.calls == []+++def test_fractional_seconds_reach_the_route(monkeypatch):+ result, studio = run_tool(+ monkeypatch, _studio(), "generate_video", {"prompt": "x", "seconds": 2.5}+ )+ assert result["isError"] is False, result+ assert bodies(studio, "/v1/videos") == [{"prompt": "x", "seconds": 2.5}]+++def test_a_body_over_the_route_cap_uploads_no_audio(monkeypatch):+ import studio_mcp.tools.video as video_tool++ monkeypatch.setattr(video_tool, "VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES", 1024)+ audio = {"data_base64": b64(_WAV), "filename": "v.wav"}+ args = {"prompt": "x" * 2048, "reference_images": [PNG_URL], "reference_audios": [audio]}+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is True+ assert studio.state.calls == []++[email protected]("seconds", ["auto", " ", ""])+def test_seconds_auto_or_blank_beside_num_frames_is_omitted(monkeypatch, seconds):+ args = {"prompt": "x", "seconds": seconds, "num_frames": 49}+ result, studio = run_tool(monkeypatch, _studio(), "generate_video", args)+ assert result["isError"] is False, result+ assert bodies(studio, "/v1/videos") == [{"prompt": "x", "num_frames": 49}]++[email protected]("field", ["first_frame", "last_frame", "reference_images"])+def test_an_image_over_24_mib_fits_the_32_mb_video_budget(monkeypatch, field):+ # /v1/videos takes a 32 MB image; the general 24 MiB MCP image cap must not refuse it first.+ big = PNG + b"\0" * (25 * 1024 * 1024)+ studio = _studio()+ studio.add_api_route(+ "/api/inference/images/gallery/big/file",+ lambda: Response(big, media_type = "image/png"),+ methods = ["GET"],+ )+ image = {"gallery_id": "big"}+ args = {"prompt": "x", field: [image] if field == "reference_images" else image}+ result, studio = run_tool(monkeypatch, studio, "generate_video", args)+ assert result["isError"] is False, result["content"][0]["text"][:300]+ (body,) = bodies(studio, "/v1/videos")+ sent = (+ body[field][0]+ if field == "reference_images"+ else body[{"first_frame": "input_reference"}.get(field, field)]+ )+ assert base64.b64decode(sent.split(",", 1)[1]) == bigdiff --git a/studio/backend/tests/test_openai_videos_controls.py b/studio/backend/tests/test_openai_videos_controls.pynew file mode 100644index 00000000000..6c76bfd5623--- /dev/null+++ b/studio/backend/tests/test_openai_videos_controls.py@@ -0,0 +1,845 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""/v1/videos takes the Unsloth Studio controls, draws a seed when none is sent, and keeps it."""++from __future__ import annotations++import asyncio+import base64+import inspect+import json+import sys+import time+import types+from pathlib import Path++import pytest++import routes.video as video_routes+from core.inference import audio_gallery, audio_inputs, audio_voices, media_auto_switch+from core.inference.video_families import VIDEO_MODEL_CHANGED_MSG+from utils.account_context import AccountContext, arun_as, is_owner_context++_TESTS_DIR = Path(__file__).resolve().parent+if str(_TESTS_DIR) not in sys.path:+ sys.path.insert(0, str(_TESTS_DIR))++from test_openai_videos_route import ( # noqa: E402,F401 -- fixtures are found by name+ _create,+ _healthy_diffusers,+ _reference_data_url,+ _reference_image_bytes,+ _save_clip,+ _wait_terminal,+ backend,+ client,+)++# The keys a plain OpenAI request sent begin_generate before the controls existed.+_PLAIN_KWARGS = {"prompt", "width", "height", "duration_s", "input_reference", "video_id"}+# VideoJob's keys before seed was added.+_PLAIN_RESPONSE = {+ "id",+ "object",+ "model",+ "status",+ "progress",+ "created_at",+ "completed_at",+ "expires_at",+ "prompt",+ "size",+ "seconds",+ "error",+ "remixed_from_video_id",+}+++def _wav_bytes() -> bytes:+ import io+ import wave++ buf = io.BytesIO()+ with wave.open(buf, "wb") as out:+ out.setnchannels(1)+ out.setsampwidth(2)+ out.setframerate(16000)+ out.writeframes(b"\x00\x01" * 1600)+ return buf.getvalue()+++# Decodable, since /v1/videos reads each reference audio before rendering.+_WAV = _wav_bytes()+_OTHER = AccountContext("acct-other", "other", "user")+++def _capture(monkeypatch, backend) -> list[dict]:+ calls: list[dict] = []+ monkeypatch.setattr(backend, "begin_generate", lambda **kwargs: calls.append(kwargs))+ return calls+++def _decoded(data_url: str) -> bytes:+ return base64.b64decode(data_url.split(",", 1)[1])+++def _switch_to(+ monkeypatch,+ model_path: str,+ gguf_filename = None,+) -> dict:+ switched = {"completed": False}++ async def _fake_switch(+ model,+ *,+ before_switch = None,+ **_kwargs,+ ):+ pick = types.SimpleNamespace(+ model_path = model_path, gguf_filename = gguf_filename, model_kind = "auto"+ )+ if before_switch is not None:+ before_switch(pick)+ switched["completed"] = True++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _fake_switch)+ return switched+++def test_a_plain_openai_request_sends_the_old_kwargs_plus_a_seed(client, backend, monkeypatch):+ calls = _capture(monkeypatch, backend)+ png_url = _reference_data_url("PNG", "image/png")+ json_resp = client.post(+ "/v1/videos",+ json = {+ "prompt": "a fox",+ "model": "sora-2",+ "seconds": "4",+ "size": "768x512",+ "input_reference": png_url,+ },+ )+ png = _reference_image_bytes("PNG")+ form_resp = _create(+ client,+ {"prompt": "a fox", "model": "sora-2", "seconds": "4", "size": "768x512"},+ {"input_reference": ("frame.png", png, "image/png")},+ )+ for resp, kwargs in zip((json_resp, form_resp), calls, strict = True):+ assert resp.status_code == 200, resp.json()+ assert set(kwargs) - {"seed"} == _PLAIN_KWARGS+ assert isinstance(kwargs["seed"], int) and 0 <= kwargs["seed"] < 2**53+ job = resp.json()+ assert set(job) - {"seed"} == _PLAIN_RESPONSE+ assert job["seed"] == kwargs["seed"]+ assert job["size"] == "768x512" and job["prompt"] == "a fox"+++def test_every_control_reaches_begin_generate_from_json(client, backend, monkeypatch):+ calls = _capture(monkeypatch, backend)+ png_url = _reference_data_url("PNG", "image/png")+ jpeg_url = _reference_data_url("JPEG", "image/jpeg")+ wav_url = "data:audio/wav;base64," + base64.b64encode(_WAV).decode()+ scalars = {+ "seed": 5,+ "negative_prompt": "blur",+ "steps": 12,+ "guidance": 3.5,+ "num_frames": 49,+ "fps": 24,+ }+ resp = client.post(+ "/v1/videos", json = {"prompt": "x", **scalars, "last_frame": {"image_url": png_url}}+ )+ assert resp.status_code == 200, resp.json()+ assert resp.json()["seed"] == 5+ resp = client.post(+ "/v1/videos",+ json = {+ "prompt": "x",+ "reference_images": [png_url, jpeg_url],+ "reference_audios": [wav_url],+ },+ )+ assert resp.status_code == 200, resp.json()+ first, second = calls+ assert {key: first[key] for key in scalars} == scalars+ assert first["last_frame"] == png_url and first["duration_s"] is None+ assert "reference_images" not in first+ assert second["reference_images"] == [png_url, jpeg_url]+ assert second["reference_audios"] == [wav_url]+ assert "last_frame" not in second and "steps" not in second+++def test_every_control_reaches_begin_generate_from_multipart(client, backend, monkeypatch):+ calls = _capture(monkeypatch, backend)+ png, jpeg = _reference_image_bytes("PNG"), _reference_image_bytes("JPEG")+ fields = {+ "prompt": "x",+ "seed": "9",+ "steps": "8",+ "guidance": "",+ "fps": "25",+ "num_frames": "33",+ }+ resp = client.post(+ "/v1/videos", data = fields, files = [("last_frame", ("end.png", png, "image/png"))]+ )+ assert resp.status_code == 200, resp.json()+ resp = client.post(+ "/v1/videos",+ data = {"prompt": "x"},+ files = [+ ("reference_images", ("a.png", png, "image/png")),+ ("reference_images[]", ("b.jpg", jpeg, "image/jpeg")),+ ("reference_audios", ("voice.wav", _WAV, "audio/wav")),+ ("reference_audios", ("score.bin", _WAV, "application/x-unknown")),+ ],+ )+ assert resp.status_code == 200, resp.json()+ first, second = calls+ assert (first["seed"], first["steps"], first["fps"], first["num_frames"]) == (9, 8, 25, 33)+ assert "guidance" not in first, "a blank form field means omitted"+ assert first["last_frame"].startswith("data:image/png;base64,")+ assert _decoded(first["last_frame"]) == png+ assert [_decoded(url) for url in second["reference_images"]] == [png, jpeg]+ assert second["reference_images"][1].startswith("data:image/jpeg;base64,")+ assert [url.split(",")[0] for url in second["reference_audios"]] == [+ "data:audio/wav;base64",+ "data:application/octet-stream;base64",+ ]+ assert [_decoded(url) for url in second["reference_audios"]] == [_WAV, _WAV]+++def test_an_empty_audio_upload_is_refused(client, backend, monkeypatch):+ calls = _capture(monkeypatch, backend)+ resp = client.post(+ "/v1/videos",+ data = {"prompt": "x"},+ files = [+ ("reference_images", ("a.png", _reference_image_bytes("PNG"), "image/png")),+ ("reference_audios", ("voice.wav", b"", "audio/wav")),+ ],+ )+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["message"] == "reference_audios[0] is empty."+ assert resp.json()["error"]["param"] == "reference_audios"+ assert calls == []+++def test_an_omitted_seed_is_drawn_kept_and_survives_a_restart(client, backend):+ backend.gate.clear()+ job = _create(client, {"prompt": "seeded"}).json()+ seed = job["seed"]+ assert isinstance(seed, int) and 0 <= seed < 2**53+ running = client.get(f"/v1/videos/{job['id']}").json()+ assert running["status"] in ("queued", "in_progress") and running["seed"] == seed+ video_routes._jobs = {}+ restored = client.get(f"/v1/videos/{job['id']}").json()+ assert restored["status"] in ("queued", "in_progress") and restored["seed"] == seed+ backend.gate.set()+ done = _wait_terminal(client, job["id"])+ assert done["status"] == "completed" and done["seed"] == seed+ assert backend.last_generate_kwargs["seed"] == seed, "the engine rendered another seed"+ video_routes._jobs = {}+ assert client.get(f"/v1/videos/{job['id']}").json()["seed"] == seed+++def test_an_explicit_seed_passes_through_and_omitted_seeds_differ(client, backend, monkeypatch):+ calls = _capture(monkeypatch, backend)+ explicit = client.post("/v1/videos", json = {"prompt": "x", "seed": 2**53 - 1}).json()+ assert explicit["seed"] == calls[0]["seed"] == 2**53 - 1+ seeds = {client.post("/v1/videos", json = {"prompt": "x"}).json()["seed"] for _ in range(2)}+ assert len(seeds) == 2+++def test_a_model_changed_retry_reuses_the_seed(client, backend, monkeypatch):+ seeds: list[int] = []++ def _begin(**kwargs):+ seeds.append(kwargs["seed"])+ if len(seeds) == 1:+ raise RuntimeError(VIDEO_MODEL_CHANGED_MSG)+ return None++ monkeypatch.setattr(backend, "begin_generate", _begin)+ resp = client.post("/v1/videos", json = {"prompt": "x"})+ assert resp.status_code == 200, resp.json()+ assert len(seeds) == 2 and seeds[0] == seeds[1] == resp.json()["seed"]+++def test_a_completed_clip_reports_the_seed_the_engine_saved(client, backend):+ record = _save_clip("saved", "2026-01-01T00:00:00Z")+ assert client.get(f"/v1/videos/{record['id']}").json()["seed"] == 7+++def test_an_old_record_loads_without_a_seed_and_a_new_one_round_trips():+ job = video_routes._VideoJob(+ id = "video_old_record",+ created_at = 100,+ prompt = "old",+ model = "model",+ size = "768x512",+ seconds = "5",+ )+ old = {key: value for key, value in vars(job).items() if key != "seed"}+ loaded = video_routes._job_from_record(old)+ assert loaded is not None and loaded.seed is None+ assert video_routes._job_to_openai(loaded).seed is None+ seeded = video_routes._job_from_record({**old, "seed": 11})+ assert seeded is not None and video_routes._job_to_openai(seeded).seed == 11+++ "body, param, text",+ [+ (+ {"last_frame": "PNG"},+ "last_frame",+ "takes no last frame",+ ),+ (+ {"reference_images": ["PNG"]},+ "reference_images",+ "takes no reference images",+ ),+ ],+)[email protected]("switch", [True, False], ids = ["before-switch", "resident"])+def test_the_family_refuses_controls_it_cannot_take(+ client, backend, monkeypatch, body, param, text, switch+):+ png_url = _reference_data_url("PNG", "image/png")+ body = {key: ([png_url] if isinstance(value, list) else png_url) for key, value in body.items()}+ switched = _switch_to(monkeypatch, "Lightricks/LTX-2") if switch else None+ resp = client.post("/v1/videos", json = {"prompt": "x", "model": "LTX-2", **body})+ assert resp.status_code == 400, resp.json()+ assert text in resp.json()["error"]["message"]+ assert resp.json()["error"]["param"] == param+ if switched is not None:+ assert switched["completed"] is False, "the model was switched before the refusal"+++ "body, param, text",+ [+ ({"reference_audios": ["WAV"]}, "reference_audios", "reference audio needs at least one"),+ ({"seconds": "4", "num_frames": 33}, None, "Send seconds or num_frames, not both."),+ (+ {"input_reference": "PNG", "reference_images": ["PNG"]},+ "reference_images",+ "input_reference cannot be combined with reference_images",+ ),+ ({"reference_images": ["PNG"] * 10}, "reference_images", "reference_images"),+ (+ {"reference_images": ["PNG"], "reference_audios": ["WAV"] * 4},+ "reference_audios",+ "reference_audios",+ ),+ (+ {"last_frame": "data:image/png;base64,AAAA"},+ "last_frame",+ "last_frame is not a readable",+ ),+ ],+)+def test_shape_refusals_come_before_any_switch(client, backend, monkeypatch, body, param, text):+ calls = _capture(monkeypatch, backend)+ switched = _switch_to(monkeypatch, "Lightricks/LTX-2")+ media = {"PNG": _reference_data_url("PNG", "image/png"), "WAV": "data:audio/wav;base64,AAAA"}+ body = {+ key: [media.get(v, v) for v in value]+ if isinstance(value, list)+ else media.get(value, value)+ for key, value in body.items()+ }+ resp = client.post("/v1/videos", json = {"prompt": "x", **body})+ assert resp.status_code == 400, resp.json()+ error = resp.json()["error"]+ assert text in error["message"]+ if param is not None:+ assert error["param"] == param+ assert switched["completed"] is False and calls == []+++def audio_store(monkeypatch, tmp_path):+ """Each account's audio under its own folder of the test's root."""++ def _gallery_dir() -> Path:+ directory = tmp_path / ("audio-owner" if is_owner_context() else "audio-other")+ directory.mkdir(parents = True, exist_ok = True)+ return directory++ monkeypatch.setattr(audio_gallery, "gallery_dir", _gallery_dir)+++def _store_clip(prompt: str = "score") -> str:+ meta = {+ "prompt": prompt,+ "model": "audio-model",+ "audio_type": "snac",+ "sample_rate": 24000,+ "duration_s": 1.0,+ "created_at": "2026-10-17T00:00:00Z",+ }+ return audio_gallery.save(_WAV, meta)["id"]+++def _store_input() -> str:+ input_id = "input-1"+ directory = audio_inputs.inputs_dir()+ (directory / f"{input_id}.wav").write_bytes(_WAV)+ meta = {+ "name": "voice.wav",+ "duration_s": 1.0,+ "sample_rate": 16000,+ "channels": 1,+ "sha256": "0" * 64,+ "created_at": "2026-10-17T00:00:00Z",+ "touched_at": time.time(),+ }+ (directory / f"{input_id}.json").write_text(json.dumps(meta), encoding = "utf-8")+ return input_id+++def _store_voice() -> str:+ voice_id = "voice-1"+ directory = audio_voices.voices_dir()+ (directory / f"{voice_id}.wav").write_bytes(_WAV)+ meta = {"name": "Narrator", "duration_s": 1.0, "sample_rate": 16000, "created_at": "x"}+ (directory / f"{voice_id}.json").write_text(json.dumps(meta), encoding = "utf-8")+ return voice_id++[email protected]("kind", ["clip_id", "input_id", "voice_id"])+def test_an_audio_id_resolves_to_its_stored_wav_before_the_switch(+ client, backend, monkeypatch, audio_store, kind+):+ ids = {+ "clip_id": _store_clip,+ "input_id": _store_input,+ "voice_id": _store_voice,+ }+ ref = {kind: ids[kind]()}+ order: list[str] = []+ real_resolve = video_routes._audio_ref_data_url++ def _resolve(item):+ order.append("resolve")+ return real_resolve(item)++ async def _fake_switch(model, **_kwargs):+ order.append("switch")++ monkeypatch.setattr(video_routes, "_audio_ref_data_url", _resolve)+ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _fake_switch)+ calls = _capture(monkeypatch, backend)+ png_url = _reference_data_url("PNG", "image/png")+ resp = client.post(+ "/v1/videos", json = {"prompt": "x", "reference_images": [png_url], "reference_audios": [ref]}+ )+ assert resp.status_code == 200, resp.json()+ (audio,) = calls[0]["reference_audios"]+ assert audio.startswith("data:audio/wav;base64,") and _decoded(audio) == _WAV+ assert order == ["resolve", "switch"]+++ "ref, text",+ [+ ({"clip_id": "missing"}, "That clip is no longer in your history."),+ ({"input_id": "missing"}, "This reference expired. Add it again."),+ ({"voice_id": "missing"}, "That saved voice no longer exists."),+ ],+)+def test_an_unknown_audio_id_is_a_404_and_never_renders(+ client, backend, monkeypatch, audio_store, ref, text+):+ calls = _capture(monkeypatch, backend)+ switched = _switch_to(monkeypatch, "Lightricks/LTX-2")+ png_url = _reference_data_url("PNG", "image/png")+ resp = client.post(+ "/v1/videos", json = {"prompt": "x", "reference_images": [png_url], "reference_audios": [ref]}+ )+ assert resp.status_code == 404, resp.json()+ assert resp.json()["error"]["message"] == text+ assert resp.json()["error"]["param"] == "reference_audios"+ assert calls == [] and switched["completed"] is False+++def test_another_accounts_clip_is_a_404(client, backend, monkeypatch, audio_store):+ from utils.account_context import run_as++ calls = _capture(monkeypatch, backend)+ clip_id = run_as(_OTHER, _store_clip, "theirs")+ png_url = _reference_data_url("PNG", "image/png")+ resp = client.post(+ "/v1/videos",+ json = {+ "prompt": "x",+ "reference_images": [png_url],+ "reference_audios": [{"clip_id": clip_id}],+ },+ )+ assert resp.status_code == 404, resp.json()+ assert resp.json()["error"]["message"] == "That clip is no longer in your history."+ assert calls == []+++def test_audio_ids_resolve_in_the_callers_account_across_the_thread(audio_store):+ from models.inference import AudioSourceRef++ clip_id = _store_clip("owner's")+ ref = AudioSourceRef(clip_id = clip_id)+ assert _decoded(video_routes._audio_ref_data_url(ref)) == _WAV++ async def _as_other():+ return await asyncio.to_thread(video_routes._audio_ref_data_url, ref)++ with pytest.raises(audio_inputs.AudioInputError) as exc:+ asyncio.run(arun_as(_OTHER, _as_other()))+ assert exc.value.status == 404+++def test_create_openai_video_keeps_its_signature():+ assert list(inspect.signature(video_routes._create_openai_video).parameters) == [+ "body",+ "reference",+ "current_subject",+ "hf_token",+ ]++[email protected]("switch", [True, False], ids = ["before-switch", "resident"])+def test_minimax_h3_refuses_a_custom_fps(client, backend, monkeypatch, switch):+ from core.inference.video_families import detect_video_family++ # H3 always writes its clip at 24 fps, so 30 fps would only mislabel the clip's length.+ calls = _capture(monkeypatch, backend)+ if switch:+ switched = _switch_to(monkeypatch, "MiniMaxAI/MiniMax-H3", "minimax_h3_ref2va-Q4_K_M.gguf")+ else:+ switched = None+ resident = backend.status++ def _h3_status():+ status = resident()+ return {+ **status,+ "family": "minimax-h3",+ "defaults": {**(status.get("defaults") or {}), "fps": 24},+ }++ monkeypatch.setattr(backend, "status", _h3_status)+ # An explicit fps pins the request to the resident state, so that is H3 too.+ backend._state = types.SimpleNamespace(+ family = detect_video_family("MiniMaxAI/MiniMax-H3"),+ h3_task = None,+ engine = "diffusers",+ repo_id = "MiniMaxAI/MiniMax-H3",+ )+ resp = client.post("/v1/videos", json = {"prompt": "x", "model": "H3", "fps": 30})+ assert resp.status_code == 400, resp.json()+ error = resp.json()["error"]+ assert error["param"] == "fps" and "fixed 24 fps" in error["message"]+ assert calls == []+ if switched is not None:+ assert switched["completed"] is False+ else:+ resp = client.post("/v1/videos", json = {"prompt": "x", "fps": 24})+ assert resp.status_code == 200, resp.json()+++def test_minimax_h3_refuses_a_custom_fps_on_the_pinned_snapshot(client, backend, monkeypatch):+ # With auto-switch on, the route reads generation_snapshot(), which names no family.+ from core.inference.video_families import detect_video_family+ from utils import openai_auto_switch_settings++ calls = _capture(monkeypatch, backend)+ backend._state = types.SimpleNamespace(+ family = detect_video_family("MiniMaxAI/MiniMax-H3"),+ h3_task = None,+ engine = "diffusers",+ repo_id = "MiniMaxAI/MiniMax-H3",+ )++ async def _resident(*_args, **_kwargs):+ return None++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _resident)+ monkeypatch.setattr(media_auto_switch, "resident_answers_media_request", lambda *a, **k: True)+ monkeypatch.setattr(openai_auto_switch_settings, "get_media_auto_switch_enabled", lambda: True)+ resp = client.post("/v1/videos", json = {"prompt": "x", "model": "MiniMax-H3", "fps": 30})+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == "fps"+ assert calls == []+++def test_multipart_references_keep_their_wire_order_across_both_spellings(+ client, backend, monkeypatch+):+ calls = _capture(monkeypatch, backend)+ png, jpeg = _reference_image_bytes("PNG"), _reference_image_bytes("JPEG")+ resp = client.post(+ "/v1/videos",+ data = {"prompt": "<Picture 1> meets <Picture 2>"},+ files = [+ ("reference_images[]", ("first.jpg", jpeg, "image/jpeg")),+ ("reference_images", ("second.png", png, "image/png")),+ ],+ )+ assert resp.status_code == 200, resp.json()+ assert [_decoded(url) for url in calls[0]["reference_images"]] == [jpeg, png]+++def test_a_stored_audio_over_the_cap_is_refused_without_reading_it(audio_store, monkeypatch):+ from models.inference import AudioSourceRef++ ref = AudioSourceRef(clip_id = _store_clip())+ monkeypatch.setattr(video_routes, "_VIDEO_REFERENCE_AUDIO_MAX_BYTES", len(_WAV) - 1)++ def _no_read(self):+ raise AssertionError(f"{self} was read before its size was checked")++ monkeypatch.setattr(Path, "read_bytes", _no_read)+ with pytest.raises(audio_inputs.AudioInputError) as exc:+ video_routes._audio_ref_data_url(ref)+ assert exc.value.status == 400 and "24 MB" in exc.value.detail+++def test_a_32_mb_image_fits_last_frame_and_reference_images():+ from pydantic import ValidationError++ from models.inference import VideoJobCreateRequest+ from utils.upload_limits import VIDEO_INPUT_REFERENCE_MAX_BYTES++ # A 32 MB image is about 42.7 MB of base64, past the old 32 MiB character cap.+ header = "data:image/png;base64,"+ full = header + "A" * (((VIDEO_INPUT_REFERENCE_MAX_BYTES + 2) // 3) * 4)+ assert VideoJobCreateRequest(prompt = "x", last_frame = full).last_frame == full+ assert VideoJobCreateRequest(prompt = "x", reference_images = [full]).reference_images == [full]+ over = full + "A" * (64 * 1024)+ with pytest.raises(ValidationError, match = "last_frame"):+ VideoJobCreateRequest(prompt = "x", last_frame = over)+ with pytest.raises(ValidationError, match = "each reference image must be at most 32 MB"):+ VideoJobCreateRequest(prompt = "x", reference_images = [over])+ audio = "data:audio/wav;base64," + "A" * (33 * 1024 * 1024)+ with pytest.raises(ValidationError, match = "each reference audio must be at most 24 MB"):+ VideoJobCreateRequest(prompt = "x", reference_images = [header], reference_audios = [audio])+++def test_a_24_mb_audio_data_url_fits_reference_audios():+ from pydantic import ValidationError++ from models.inference import VideoJobCreateRequest++ # The full 24 MB the upload and id paths accept, plus its data URL header.+ audio = "data:audio/wav;base64," + "A" * (((24 * 1024 * 1024 + 2) // 3) * 4)+ image = _reference_data_url("PNG", "image/png")+ body = VideoJobCreateRequest(prompt = "x", reference_images = [image], reference_audios = [audio])+ assert body.reference_audios == [audio]+ with pytest.raises(ValidationError, match = "each reference audio must be at most 24 MB"):+ VideoJobCreateRequest(+ prompt = "x", reference_images = [image], reference_audios = [audio + "A" * 65536]+ )+++ "audio", ["data:audio/wav;base64,", "data:audio/wav;base64,AAAA"], ids = ["empty", "undecodable"]+)+def test_unreadable_reference_audio_is_refused_before_the_switch(+ client, backend, monkeypatch, audio+):+ from core.inference import video_minimax_h3++ def _decode(blob, **_kwargs):+ raise ValueError("That reference file carries no audio track.")++ monkeypatch.setattr(video_minimax_h3, "decode_h3_reference_audio", _decode)+ calls = _capture(monkeypatch, backend)+ switched = _switch_to(monkeypatch, "MiniMaxAI/MiniMax-H3", "minimax_h3_ref2va-Q4_K_M.gguf")+ body = {+ "prompt": "x",+ "model": "H3",+ "reference_images": [_reference_data_url("PNG", "image/png")],+ "reference_audios": [audio],+ }+ resp = client.post("/v1/videos", json = body)+ assert resp.status_code == 400, resp.json()+ error = resp.json()["error"]+ assert error["param"] == "reference_audios"+ assert "reference_audios[0] is not readable audio" in error["message"]+ assert switched["completed"] is False and calls == []+++def test_readable_reference_audio_goes_on_to_the_switch(client, backend, monkeypatch):+ from core.inference import video_minimax_h3++ seen = []+ monkeypatch.setattr(+ video_minimax_h3,+ "decode_h3_reference_audio",+ lambda blob, **_kwargs: seen.append(blob) or (None, 48000),+ )+ _capture(monkeypatch, backend)+ switched = _switch_to(monkeypatch, "MiniMaxAI/MiniMax-H3", "minimax_h3_ref2va-Q4_K_M.gguf")+ wav_url = "data:audio/wav;base64," + base64.b64encode(_WAV).decode()+ body = {+ "prompt": "x",+ "model": "H3",+ "reference_images": [_reference_data_url("PNG", "image/png")],+ "reference_audios": [wav_url],+ }+ client.post("/v1/videos", json = body)+ assert seen == [_WAV] and switched["completed"] is True++[email protected]("key, limit", [("reference_images", 9), ("reference_audios", 3)])+def test_too_many_multipart_references_are_refused_before_encoding(+ client, backend, monkeypatch, key, limit+):+ from models.inference import VideoJobCreateRequest++ assert VideoJobCreateRequest.model_fields[key].metadata[0].max_length == limit+ encoded = []++ async def _no_encode(*args, **kwargs):+ encoded.append(args)+ raise AssertionError("a file was encoded before the count check")++ monkeypatch.setattr(video_routes, "_reference_to_data_url", _no_encode)+ monkeypatch.setattr(video_routes, "_audio_upload_to_data_url", _no_encode)+ calls = _capture(monkeypatch, backend)+ png = _reference_image_bytes("PNG")+ files = [(key, (f"{i}.png", png, "image/png")) for i in range(limit + 1)]+ resp = client.post("/v1/videos", data = {"prompt": "x"}, files = files)+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == key+ assert encoded == [] and calls == []++[email protected]("spelling", ["sdk_brackets", "json_text"])+def test_a_multipart_audio_id_resolves_like_json(+ client, backend, monkeypatch, audio_store, spelling+):+ input_id = _store_input()++ async def _no_switch(model, **_kwargs):+ return None++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", _no_switch)+ calls = _capture(monkeypatch, backend)+ data = {"prompt": "x"}+ if spelling == "sdk_brackets":+ # What the OpenAI SDK sends for reference_audios=[{"input_id": ...}] beside a file.+ data["reference_audios[][input_id]"] = input_id+ else:+ data["reference_audios"] = json.dumps({"input_id": input_id})+ png = _reference_image_bytes("PNG")+ resp = client.post(+ "/v1/videos",+ data = data,+ files = [("reference_images[]", ("ref.png", png, "image/png"))],+ )+ assert resp.status_code == 200, resp.json()+ (audio,) = calls[0]["reference_audios"]+ assert _decoded(audio) == _WAV+++ "body, param", [({"num_frames": 50}, "num_frames"), ({"seconds": "4"}, "seconds")]+)+def test_a_frame_count_refusal_names_the_field_the_caller_sent(+ client, backend, monkeypatch, body, param+):+ from core.inference.video_families import VideoShapeError++ def _refuse(**_kwargs):+ raise VideoShapeError("LTX-2 needs a frame count of 8k+1.")++ monkeypatch.setattr(backend, "begin_generate", _refuse)+ resp = client.post("/v1/videos", json = {"prompt": "x", **body})+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == param+++def test_multipart_nested_image_references_are_kept(client, backend, monkeypatch):+ calls = _capture(monkeypatch, backend)+ png = _reference_data_url("PNG", "image/png")+ jpeg = _reference_data_url("JPEG", "image/jpeg")+ resp = client.post(+ "/v1/videos",+ data = {"prompt": "x", "reference_images[][image_url]": png},+ files = [+ ("reference_images[]", ("second.jpg", _reference_image_bytes("JPEG"), "image/jpeg"))+ ],+ )+ assert resp.status_code == 200, resp.json()+ assert len(calls[0]["reference_images"]) == 2+ resp = client.post("/v1/videos", data = {"prompt": "x", "last_frame[image_url]": jpeg})+ assert resp.status_code == 200, resp.json()+ assert _decoded(calls[1]["last_frame"]) == _decoded(jpeg)+++def test_seconds_auto_beside_num_frames_is_not_both(client, backend, monkeypatch):+ calls = _capture(monkeypatch, backend)+ resp = client.post("/v1/videos", json = {"prompt": "x", "seconds": "auto", "num_frames": 33})+ assert resp.status_code == 200, resp.json()+ assert calls[0]["num_frames"] == 33+++def test_a_custom_fps_is_judged_on_the_state_that_renders(client, backend, monkeypatch):+ # status() still reads LTX-2, but MiniMax-H3 committed before the reservation: the fps check+ # must judge the state begin_generate is pinned to, not the earlier read.+ from core.inference.video_families import detect_video_family++ calls = _capture(monkeypatch, backend)+ resident = backend.status++ def _ltx_status():+ return {**resident(), "family": "ltx-2"}++ monkeypatch.setattr(backend, "status", _ltx_status)+ backend._state = types.SimpleNamespace(+ family = detect_video_family("MiniMaxAI/MiniMax-H3"),+ h3_task = None,+ engine = "diffusers",+ repo_id = "MiniMaxAI/MiniMax-H3",+ )+ resp = client.post("/v1/videos", json = {"prompt": "x", "fps": 30})+ assert resp.status_code == 400, resp.json()+ assert resp.json()["error"]["param"] == "fps"+ assert calls == []+++def test_resident_audio_the_decoder_cannot_open_is_a_400(client, backend):+ # A WAV naming a codec FFmpeg has no decoder for fails with AttributeError, not ValueError,+ # inside begin_generate. No switch runs the preflight here, so the route must.+ import struct++ from core.inference.video_families import detect_video_family+ from core.inference.video_minimax_h3 import H3_TASK_REFERENCES++ pytest.importorskip("av")+ fmt = struct.pack("<HHIIHH", 0x1234, 1, 16000, 32000, 2, 16)+ data = b"\x00\x01" * 800+ chunks = b"WAVEfmt " + struct.pack("<I", len(fmt)) + fmt + b"data"+ chunks += struct.pack("<I", len(data)) + data+ wav = b"RIFF" + struct.pack("<I", len(chunks)) + chunks+ backend._state = types.SimpleNamespace(+ family = detect_video_family("MiniMaxAI/MiniMax-H3"),+ h3_task = H3_TASK_REFERENCES,+ engine = "diffusers",+ repo_id = "MiniMaxAI/MiniMax-H3",+ )+ body = {+ "prompt": "x",+ "reference_images": [_reference_data_url("PNG", "image/png")],+ "reference_audios": ["data:audio/wav;base64," + base64.b64encode(wav).decode()],+ }+ resp = client.post("/v1/videos", json = body)+ assert resp.status_code == 400, resp.text+ assert resp.json()["error"]["param"] == "reference_audios"diff --git a/studio/backend/tests/test_skills.py b/studio/backend/tests/test_skills.pyindex 3dcdf8e6d01..81bae70d189 100644--- a/studio/backend/tests/test_skills.py+++ b/studio/backend/tests/test_skills.py@@ -128,6 +128,24 @@ def test_bundled_skill_creator_is_enabled_and_user_override_wins(isolated_skills]+def test_bundled_image_prompting_skill_parses_and_ships_disabled(isolated_skills, monkeypatch):+ home, _ = isolated_skills+ roots = (+ ("agents", home / ".agents" / "skills"),+ ("claude", home / ".claude" / "skills"),+ ("bundled", Path(skills.__file__).with_name("bundled_skills")),+ )+ monkeypatch.setattr(skills, "_skill_roots", lambda home = None: roots)++ record = next(r for r in skills.list_skills() if r["name"] == "image-prompting")+ assert record["source"] == "bundled"+ assert record["enabled"] is False+ assert record["allowed_tools"] == "generate_image generate_video"+ assert "image-prompting" not in [r["name"] for r in skills.enabled_skills()]+ with pytest.raises(skills.SkillError, match = "disabled"):+ skills.read_skill_resource("image-prompting")++@pytest.mark.parametrize("directory,manifest",[@@ -693,14 +711,15 @@ def test_managed_account_never_sees_the_owners_home_skills(managed_accounts):_account_skill(studio, _ALICE_ID, "alice-skill", "ALICE_PRIVATE")owner_names = [record["name"] for record in skills.list_skills()]- assert owner_names == ["owner-only", "owner-claude", "skill-creator"]+ assert owner_names == ["owner-only", "owner-claude", "image-prompting", "skill-creator"]alice_records = run_as(alice, skills.list_skills)assert [(r["name"], r["source"]) for r in alice_records] == [("alice-skill", "agents"),+ ("image-prompting", "bundled"),("skill-creator", "bundled"),]- assert run_as(bob, skills.list_skills)[0]["name"] == "skill-creator"+ assert run_as(bob, skills.list_skills)[0]["name"] == "image-prompting"assert "ALICE_PRIVATE" not in str(run_as(bob, skills.list_skills))with pytest.raises(skills.SkillNotFoundError):diff --git a/studio/backend/tests/test_video_families.py b/studio/backend/tests/test_video_families.pyindex 274a19d5362..0742f4f82ab 100644--- a/studio/backend/tests/test_video_families.py+++ b/studio/backend/tests/test_video_families.py@@ -262,6 +262,35 @@ def test_generation_defaults_fallback_honors_family():assert default_video_generation_params("wan2.2-ti2v-5b", fallback = (8, 1.0)) == (20, 5.0)+def test_prompt_hint_defaults_none_and_reaches_video_status():+ import dataclasses++ import core.inference.video as video_module+ from core.inference import video_families+ from models.inference import VideoStatusResponse++ assert video_families.VideoFamily.__dataclass_fields__["prompt_hint"].default is None+ # No video family has a vetted prompt tip yet.+ assert [f.name for f in video_families._FAMILIES if f.prompt_hint is not None] == []++ fam = detect_video_family("", override = "ltx-2")+ backend = video_module.VideoBackend()+ for hint in (None, "Describe the motion first."):+ backend._state = video_module._VideoLoadState(+ pipe = object(),+ family = dataclasses.replace(fam, prompt_hint = hint),+ repo_id = "unsloth/ltx-2",+ base_repo = fam.base_repo,+ device = "cpu",+ dtype = "bfloat16",+ kind = "pipeline",+ )+ assert backend.status()["prompt_hint"] == hint+ assert VideoStatusResponse(**backend.status()).prompt_hint == hint+ backend._state = None+ assert VideoStatusResponse(**backend.status()).prompt_hint is None++def test_generation_defaults_wan_is_segment_not_substring():# "wan" must match as a name segment, not a raw substring, so an opaque repo/path ("swan", "taiwan") does not pick up Wan's 50-step/CFG-5 schedule.assert default_video_generation_params(diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex abe4ba05efb..9dc7052a8bc 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -83,6 +83,8 @@ export interface DiffusionStatus {// Whether the loaded model can apply a ControlNet. Diffusers only, for families with a ControlNet pipeline.supports_controlnet?: boolean;supports_negative_prompt?: boolean;+ // One or two sentences on how the loaded model reads prompts; null when it has no tip.+ prompt_hint?: string | null;// "default" first; empty or absent = no choice (flow models, native / MLX engines, older backend).samplers?: DiffusionSamplerOption[];// Per-Advanced-control provenance, keyed by control name. Present only when a model is loaded on adiff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 7520888b6d4..6ff0cbfeb6e 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -5703,7 +5703,10 @@ export function ImagesPage({</>)}- <Field label={workflow === "edit" ? "Instruction" : "Prompt"}>+ <Field+ label={workflow === "edit" ? "Instruction" : "Prompt"}+ hint={external ? undefined : status?.prompt_hint || undefined}+ ><Textareadata-type-to-activate="prompt"rows={4}diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex b371921de8d..542e2893c9a 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -106,6 +106,8 @@ export interface VideoStatus {h3_task?: string | null;// Per-family generation defaults + shape constraints; null when unloaded.defaults?: VideoGenerationDefaults | null;+ // One or two sentences on how the loaded model reads prompts; null when it has no tip.+ prompt_hint?: string | null;// Per-control provenance keyed by control name, read by the "Auto: X" badges. Null when// nothing is loaded or the backend does not record it.// The names are memory_mode, speed_mode, attention_backend and transformer_cache.diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex b16e2da78ff..f5f2e464695 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -3950,7 +3950,7 @@ function VideoGenerator({/></div>- <Field label="Prompt">+ <Field label="Prompt" hint={status?.prompt_hint || undefined}><Textareadata-type-to-activate="prompt"rows={4}diff --git a/studio/frontend/tests/images-prompt-hint.test.ts b/studio/frontend/tests/images-prompt-hint.test.tsnew file mode 100644index 00000000000..e196a42faf2--- /dev/null+++ b/studio/frontend/tests/images-prompt-hint.test.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import ts from "@typescript/typescript6";+import { readSrc } from "./helpers/kit.ts";++function parse(relative: string) {+ return ts.createSourceFile(+ relative,+ readSrc(relative),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );+}++// The `hint` expression on the Field wrapping the prompt Textarea.+function promptFieldHint(relative: string): string {+ const tree = parse(relative);+ const hints: string[] = [];+ const visit = (node: ts.Node) => {+ if (+ ts.isJsxElement(node) &&+ node.openingElement.tagName.getText(tree) === "Field" &&+ node.children.some(+ (child) =>+ (ts.isJsxSelfClosingElement(child) || ts.isJsxElement(child)) &&+ (ts.isJsxElement(child) ? child.openingElement : child)+ .getText(tree)+ .includes('data-type-to-activate="prompt"'),+ )+ ) {+ const hint = node.openingElement.attributes.properties.find(+ (prop) => ts.isJsxAttribute(prop) && prop.name.getText(tree) === "hint",+ );+ assert.ok(hint && ts.isJsxAttribute(hint) && hint.initializer, `${relative}: prompt Field has no hint`);+ const init = hint.initializer;+ assert.ok(ts.isJsxExpression(init) && init.expression);+ hints.push(init.expression.getText(tree));+ }+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.equal(hints.length, 1, `${relative}: expected one prompt Field`);+ return hints[0];+}++function evaluate(expression: string, scope: Record<string, unknown>): unknown {+ const { outputText } = ts.transpileModule(`return (${expression});`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ return new Function(...Object.keys(scope), outputText)(...Object.values(scope));+}++const TIP = "Write the change you want as an instruction.";++test("the Images prompt Field shows the loaded model's tip, but not for an external model", () => {+ const hint = promptFieldHint("features/images/images-page.tsx");+ assert.equal(evaluate(hint, { external: null, status: { prompt_hint: TIP } }), TIP);+ assert.equal(evaluate(hint, { external: null, status: { prompt_hint: null } }), undefined);+ assert.equal(evaluate(hint, { external: null, status: null }), undefined);+ assert.equal(+ evaluate(hint, { external: { provider: "x" }, status: { prompt_hint: TIP } }),+ undefined,+ );+});++test("the Video prompt Field shows the loaded model's tip", () => {+ const hint = promptFieldHint("features/video/video-page.tsx");+ assert.equal(evaluate(hint, { status: { prompt_hint: TIP } }), TIP);+ assert.equal(evaluate(hint, { status: { prompt_hint: null } }), undefined);+ assert.equal(evaluate(hint, { status: { prompt_hint: "" } }), undefined);+ assert.equal(evaluate(hint, { status: null }), undefined);+});++test("both status types declare prompt_hint", () => {+ for (const file of ["features/images/api.ts", "features/video/api.ts"]) {+ assert.match(readSrc(file), /^\s*prompt_hint\?: string \| null;$/m, file);+ }+});++test("each page's Field renders InfoHint only for a truthy hint", () => {+ for (const file of ["features/images/images-page.tsx", "features/video/video-page.tsx"]) {+ const tree = parse(file);+ let body = "";+ const visit = (node: ts.Node) => {+ if (ts.isFunctionDeclaration(node) && node.name?.getText(tree) === "Field") {+ body = node.getText(tree);+ }+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(body, `${file}: no local Field`);+ const infoHints = body.match(/<InfoHint>/g) ?? [];+ assert.equal(infoHints.length, 1, file);+ assert.match(body, /\{hint && <InfoHint>\{hint\}<\/InfoHint>\}/, file);+ }+});