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: custom video sizes and Images-style prompt fields on Create videos (#14050)
Michael Han222418213381
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 1619ab708df..5227c7f1ecd 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -221,6 +221,7 @@ from .video_families import (validate_video_keyframe_conditioning,validate_video_reference_conditioning,validate_video_request_shape,+ video_custom_size_bounds,video_family_prequant_available,video_family_prequant_repo,video_family_prequant_resident_gb,@@ -11766,6 +11767,7 @@ class VideoBackend:"duration_presets": list(fam.duration_presets),"resolution_multiple": fam.resolution_multiple,"resolution_presets": [list(p) for p in fam.resolution_presets],+ **_custom_size_defaults(fam),# Let the frontend preview the backend-owned "match source" rule."canvas_short_edge": _keyframe_canvas(fam)[0],"canvas_max_pixels": _keyframe_canvas(fam)[1],@@ -11780,6 +11782,17 @@ class VideoBackend:}+def _custom_size_defaults(fam: Any) -> dict[str, Any]:+ bounds = video_custom_size_bounds(fam)+ if bounds is None:+ return {}+ return {+ "custom_size_min_pixels": bounds[0],+ "custom_size_max_pixels": bounds[1],+ "custom_size_max_aspect": bounds[2],+ }++def _keyframe_canvas(fam: Any) -> tuple[Optional[int], Optional[int]]:"""(short edge, max pixels) of the family's "match source" keyframe canvas, or (None, None)."""if not getattr(fam, "supports_keyframes", False):diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.pyindex aee56a5f8fd..5fe2f00472a 100644--- a/studio/backend/core/inference/video_families.py+++ b/studio/backend/core/inference/video_families.py@@ -1219,6 +1219,21 @@ def format_video_resolution_presets(fam: VideoFamily) -> str:return ", ".join(f"{w}x{h}" for w, h in fam.resolution_presets)+# Ceiling = largest preset area, not more: MiniMax-H3 budgets denoiser residency at that preset. Floor = smallest preset+# area (relaxed to half the largest), which keeps 256x256 refused and honours UNSLOTH_VIDEO_H3_480P=0.+CUSTOM_VIDEO_MAX_ASPECT = 4.0+++def video_custom_size_bounds(fam: VideoFamily) -> Optional[tuple[int, int, float]]:+ """(min_pixels, max_pixels, max_aspect) a custom size must fit, or None for a family without presets."""+ presets = [(int(w), int(h)) for w, h in fam.resolution_presets if int(w) > 0 and int(h) > 0]+ if not presets:+ return None+ areas = [w * h for w, h in presets]+ max_aspect = max([CUSTOM_VIDEO_MAX_ASPECT] + [max(w, h) / min(w, h) for w, h in presets])+ return min(min(areas), max(areas) // 2), max(areas), max_aspect++class VideoShapeError(ValueError):"""A shape this family cannot render. A ValueError subclass so the existing``except ValueError`` callers keep catching it, and a distinct type so the generate@@ -1226,6 +1241,32 @@ class VideoShapeError(ValueError):widening the 400 it gives every other bad-input ValueError."""+def _validate_custom_video_size(fam: VideoFamily, width: int, height: int) -> None:+ bounds = video_custom_size_bounds(fam)+ if bounds is None:+ return+ min_pixels, max_pixels, max_aspect = bounds+ multiple = max(1, fam.resolution_multiple)+ presets = format_video_resolution_presets(fam)+ if width <= 0 or height <= 0 or width % multiple or height % multiple:+ raise VideoShapeError(+ f"{width}x{height} is not a supported resolution for {fam.name}: width and height must "+ f"be multiples of {multiple}. Trained resolutions: {presets}."+ )+ area = width * height+ if area < min_pixels or area > max_pixels:+ raise VideoShapeError(+ f"{width}x{height} is not a supported resolution for {fam.name}: the frame must hold "+ f"between {min_pixels:,} and {max_pixels:,} pixels, near the sizes it was trained at. "+ f"Trained resolutions: {presets}."+ )+ if max(width, height) / min(width, height) > max_aspect + 1e-9:+ raise VideoShapeError(+ f"{width}x{height} is not a supported resolution for {fam.name}: the aspect ratio "+ f"must stay within {max_aspect:g}:1. Trained resolutions: {presets}."+ )++def validate_video_request_shape(fam: VideoFamily,width: Optional[int] = None,@@ -1234,35 +1275,21 @@ def validate_video_request_shape() -> None:"""Raise ``ValueError`` when a request asks for a shape ``fam`` does not support.- The generate route calls this at the API boundary so HTTP enforces exactly the rules the Desktop- interface offers: its resolution select lists only ``resolution_presets`` and its duration- select only lattice frame counts, while the API took anything inside the coarse request bounds- and then SNAPPED it. The snap is silent and floors, so a 256x256 request survived untouched and- denoised at a size no checkpoint was ever trained for.-- This is a separate, explicit check rather than a change to ``snap_video_size`` /- ``snap_num_frames``, which internal callers still need. It stays silent for anything it cannot- judge (a family that declares no presets keeps the old SIZE snapping), and ``None`` means "use- the family default". The frame lattice is deliberately NOT part of that escape hatch: every- family declares a ``frame_step``, so an off-lattice count is always refused.+ The generate route calls this at the API boundary. A size is accepted when both sides sit on the+ family's ``resolution_multiple`` and the frame stays inside ``video_custom_size_bounds``: the+ old silent floor snap let 256x256 through to a size no checkpoint was trained for, so sizes far+ from the presets are refused rather than snapped. A family that declares no presets keeps the+ old SIZE snapping, and ``None`` means "use the family default". The frame lattice has no escape+ hatch: every family declares a ``frame_step``, so an off-lattice count is always refused."""- # Normalised to int pairs so membership holds however a family spelled its presets (the status payload hands them- # out as lists, and a round-trip through it must not silently stop matching).presets = tuple((int(w), int(h)) for w, h in fam.resolution_presets)- # No declared presets: no table to judge a SIZE against, so leave that to the snap (unusual/custom families). The- # frame check below still runs either way -- frame_step is always declared.if presets and (width is not None or height is not None):- # Resolve a half-specified request against the default preset first, as generate() does, then judge the pair.- # Keyed on None, where generate() keys on falsiness: a 0 is judged as 0 here rather than replaced by the- # default. The route cannot deliver one (the request model bounds it at 32), and refusing an explicit 0 beats- # silently rendering something else, so the two agree on every value that can arrive.+ # A half-specified request resolves against the default preset, as generate() does. Keyed on None, not+ # falsiness: an explicit 0 is refused rather than replaced (the request model bounds it at 32 anyway).want_w = presets[0][0] if width is None else int(width)want_h = presets[0][1] if height is None else int(height)if (want_w, want_h) not in presets:- raise VideoShapeError(- f"{want_w}x{want_h} is not a supported resolution for {fam.name}. "- f"Supported resolutions: {format_video_resolution_presets(fam)}."- )+ _validate_custom_video_size(fam, want_w, want_h)if num_frames is not None:# The lattice is k * frame_step + frame_offset, NOT a hardcoded k * step + 1: most families do sit at offset 1,# but MiniMax-H3 is 17k + 5, and judging it against 17k + 1 would refuse every count its own duration selectdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex d17b9dca3b0..85655c2f62e 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -6288,19 +6288,19 @@ class VideoGenerateRequest(BaseModel):)# Width/height/num_frames/fps default per loaded family, so they are optional here. These bounds# stay a COARSE family-agnostic outer guard: the enforced rule is the LOADED family's own- # (resolution presets and the k * frame_step + frame_offset lattice), which the route checks with+ # (sizes near its presets and the k * frame_step + frame_offset lattice), which the route checks with# validate_video_request_shape. With no model loaded there is no family to judge against.width: Optional[int] = Field(None,ge = 32,le = 2048,- description = "Frame width in pixels (a resolution preset of the loaded family)",+ description = "Frame width in pixels (a multiple of the loaded family's resolution_multiple near its presets)",)height: Optional[int] = Field(None,ge = 32,le = 2048,- description = "Frame height in pixels (a resolution preset of the loaded family)",+ description = "Frame height in pixels (see width)",)num_frames: Optional[int] = Field(None,@@ -6589,6 +6589,18 @@ class VideoGenerationDefaults(BaseModel):resolution_presets: list[list[int]] = Field(default_factory = list, description = "(width, height) presets the UI offers, default first")+ custom_size_min_pixels: Optional[int] = Field(+ None,+ description = "Smallest width * height accepted off the presets, or null when only the snap applies",+ )+ custom_size_max_pixels: Optional[int] = Field(+ None,+ description = "Largest width * height accepted off the presets (see custom_size_min_pixels)",+ )+ custom_size_max_aspect: Optional[float] = Field(+ None,+ description = "Widest long:short ratio accepted off the presets (see custom_size_min_pixels)",+ )canvas_short_edge: Optional[int] = Field(None,description = "Short edge a source-derived canvas aims for, or null when the family "diff --git a/studio/backend/tests/test_video_resolution_preset_contract.py b/studio/backend/tests/test_video_resolution_preset_contract.pyindex 3aac0a44ce8..4b2b4c2695b 100644--- a/studio/backend/tests/test_video_resolution_preset_contract.py+++ b/studio/backend/tests/test_video_resolution_preset_contract.py@@ -164,9 +164,10 @@ def test_the_frontend_fallback_is_a_usable_default_for_the_family_it_mirrors():), f"the fallback leads with {fallback[0]}, which is not the default preset of any family"-def test_the_resolution_select_renders_the_backend_presets_not_a_hardcoded_list():- """The select must map over the memo fed by ``status.defaults.resolution_presets``;- if it were rebound to the fallback the backend's per-family list would never show."""+def test_the_size_controls_follow_the_backend_presets_not_a_hardcoded_list():+ """The trained-size select and the size limits must read the memo fed by+ ``status.defaults.resolution_presets``; if they were rebound to the fallback the backend's+ per-family list would never show."""src = _VIDEO_PAGE.read_text(encoding = "utf-8")memo = src[src.index("const resolutionPresets = useMemo<") :]memo = memo[: memo.index("\n }, [")]@@ -174,6 +175,6 @@ def test_the_resolution_select_renders_the_backend_presets_not_a_hardcoded_list(assert "FALLBACK_RESOLUTION_PRESETS" in memo# Only the empty/absent case falls back.assert "presets && presets.length > 0" in memo- assert "{resolutionPresets.map(([w, h], i) => (" in src- # And the generate call sends the SELECTED preset, so the offered pair is the one rendered.- assert "const preset = resolutionPresets[resolutionIdx] ?? resolutionPresets[0];" in src+ assert "{resolutionPresets.map(([w, h]) => (" in src+ assert "videoSizeLimits(status?.defaults, resolutionPresets)" in src+ assert "width: sourceSized ? undefined : videoSize[0]," in srcdiff --git a/studio/backend/tests/test_video_shape_validation.py b/studio/backend/tests/test_video_shape_validation.pyindex 34c0e0fb4da..23f191ed293 100644--- a/studio/backend/tests/test_video_shape_validation.py+++ b/studio/backend/tests/test_video_shape_validation.py@@ -39,6 +39,7 @@ from core.inference.video_families import (snap_num_frames,snap_video_size,validate_video_request_shape,+ video_custom_size_bounds,)from core.inference.video_minimax_h3 import h3_conditioning_modefrom models.inference import VideoReferenceVideo@@ -46,7 +47,7 @@ from routes.video import router as video_router# LTX-2 is the reference family for the single-family cases: 4 presets and frame_step 8.LTX2 = detect_video_family("Lightricks/LTX-2")-# Wan is the contrast family: 704x1216 is an LTX-2 preset and is not one of Wan's.+# Wan is the contrast family: 768x512 is an LTX-2 preset and below Wan TI2V's trained area.WAN_TI2V_5B = detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers")@@ -195,13 +196,59 @@ def test_omitted_fields_are_always_valid():def test_a_half_specified_size_resolves_against_the_default_preset():"""generate() fills a missing side from presets[0], so the check must judge thesame pair it will actually denoise."""- # 768 alone resolves to 768x512, the default preset.validate_video_request_shape(LTX2, width = 768)validate_video_request_shape(LTX2, height = 512)- # 1216 alone resolves to 1216x512, which is NOT a preset (1216 only pairs with 704).+ # 1216 alone resolves to 1216x512: off the presets but on /32 and inside the area band.+ validate_video_request_shape(LTX2, width = 1216)with pytest.raises(ValueError) as excinfo:- validate_video_request_shape(LTX2, width = 1216)- assert "1216x512" in str(excinfo.value)+ validate_video_request_shape(LTX2, width = 2048)+ assert "2048x512" in str(excinfo.value)+++def test_a_custom_size_on_the_multiple_and_inside_the_band_is_accepted():+ validate_video_request_shape(LTX2, width = 1024, height = 576, num_frames = 97)+ validate_video_request_shape(LTX2, width = 576, height = 1024)+ validate_video_request_shape(LTX2, width = 640, height = 640)+ validate_video_request_shape(+ replace(LTX2, resolution_multiple = 16), width = 848, height = 480, num_frames = 97+ )+++def test_a_size_off_the_multiple_is_refused_with_the_multiple_named():+ with pytest.raises(ValueError) as excinfo:+ validate_video_request_shape(LTX2, width = 1000, height = 576)+ message = str(excinfo.value)+ assert "1000x576" in message and "multiples of 32" in message+ assert "768x512" in message+ with pytest.raises(ValueError):+ validate_video_request_shape(LTX2, width = 848, height = 480)+++def test_a_size_outside_the_area_band_or_too_narrow_is_refused():+ min_pixels, max_pixels, max_aspect = video_custom_size_bounds(LTX2)+ assert max_pixels == 1216 * 704+ assert min_pixels == 768 * 512+ assert max_aspect == 4.0+ with pytest.raises(ValueError, match = "pixels"):+ validate_video_request_shape(LTX2, width = 1280, height = 1024)+ with pytest.raises(ValueError, match = "pixels"):+ validate_video_request_shape(LTX2, width = 512, height = 512)+ # A family trained at one area still gets a band down to half of it.+ single = replace(LTX2, resolution_presets = ((832, 480), (480, 832)))+ assert video_custom_size_bounds(single)[0] == 832 * 480 // 2+ validate_video_request_shape(single, width = 512, height = 512)+ with pytest.raises(ValueError, match = "aspect ratio"):+ validate_video_request_shape(LTX2, width = 1536, height = 352)+++def test_the_status_payload_reports_the_custom_size_bounds():+ defaults = video_module._custom_size_defaults(LTX2)+ assert defaults == {+ "custom_size_min_pixels": 768 * 512,+ "custom_size_max_pixels": 1216 * 704,+ "custom_size_max_aspect": 4.0,+ }+ assert video_module._custom_size_defaults(replace(LTX2, resolution_presets = ())) == {}def test_presets_spelled_as_lists_still_match():@@ -378,6 +425,17 @@ def test_generate_accepts_every_declared_preset_of_the_loaded_family(client, bacassert (record["width"], record["height"]) == (width, height)+def test_generate_renders_a_custom_size_and_refuses_one_off_the_multiple(client, backend):+ backend.load_as(LTX2)+ resp = client.post("/api/inference/video/generate", json = _payload(width = 1024, height = 576))+ assert resp.status_code == 200, resp.text+ record = _wait_terminal(client)["video"]+ assert (record["width"], record["height"]) == (1024, 576)+ resp = client.post("/api/inference/video/generate", json = _payload(width = 1000, height = 576))+ assert resp.status_code == 422, resp.text+ assert "multiples of 32" in resp.json()["detail"]++def test_generate_rejects_an_off_lattice_frame_count_with_422(client, backend):backend.load_as(LTX2)resp = client.post("/api/inference/video/generate", json = _payload(num_frames = 100))@@ -471,18 +529,18 @@ def test_the_shape_is_judged_under_the_lock_that_reserves_the_state(backend, mondef test_a_family_swap_cannot_slip_between_the_check_and_the_job(backend):- """The consequence, end to end rather than by construction. 704x1216 is a real LTX-2 preset- and is not one of Wan's, so whichever family is resident when the lock is taken decides the- outcome -- and the job that runs afterwards is the one that was judged."""+ """The consequence, end to end rather than by construction. 768x512 is a real LTX-2 preset+ and is smaller than Wan TI2V's trained frames, so whichever family is resident when the lock+ is taken decides the outcome -- and the job that runs afterwards is the one that was judged."""backend.load_as(LTX2)- backend.begin_generate(prompt = "a cat", width = 704, height = 1216) # accepted for LTX-2+ backend.begin_generate(prompt = "a cat", width = 768, height = 512) # accepted for LTX-2backend.cancel_generate()# The worker clears the slot asynchronously and this test is about the check, not the job.backend._generate_job_active = Falsebackend.load_as(WAN_TI2V_5B)with pytest.raises(ValueError):- backend.begin_generate(prompt = "a cat", width = 704, height = 1216)+ backend.begin_generate(prompt = "a cat", width = 768, height = 512)assert not backend._generate_job_active, "a refused shape must not reserve the job slot"diff --git a/studio/frontend/src/components/media-size-controls.tsx b/studio/frontend/src/components/media-size-controls.tsxnew file mode 100644index 00000000000..84dc05e294d--- /dev/null+++ b/studio/frontend/src/components/media-size-controls.tsx@@ -0,0 +1,207 @@+// 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 { ArrowLeftRightIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";+import { ChevronDown } from "lucide-react";+import { type ReactNode, useState } from "react";++import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";++/** Output size controls shared by the Images and Video Create panels. */++// Landscape ratios; Flip mirrors them to portrait.+export const ASPECT_RATIOS: Record<string, [number, number]> = {+ "1:1": [1, 1],+ "3:2": [3, 2],+ "4:3": [4, 3],+ "16:9": [16, 9],+ "21:9": [21, 9],+};+export const ASPECT_OPTIONS = ["custom", ...Object.keys(ASPECT_RATIOS)];+export const ASPECT_LABELS: Record<string, string> = {+ "1:1": "Square",+ "3:2": "Photo",+ "4:3": "Landscape",+ "16:9": "Widescreen",+ "21:9": "Ultrawide",+};++// The ratio key is compared long:short, so it survives orientation.+export function matchAspect(+ width: number,+ height: number,+): { key: string; portrait: boolean } {+ const target = Math.max(width, height) / Math.min(width, height);+ const found = Object.entries(ASPECT_RATIOS).find(+ ([, [a, b]]) => Math.abs(target - a / b) < 0.01,+ );+ return { key: found ? found[0] : "custom", portrait: height > width };+}++/** Aspect ratio select with the flip-orientation button beside it. */+export function AspectRatioSelect({+ value,+ onValueChange,+ portrait,+ onFlip,+ open,+ onOpenChange,+ extraItems,+}: {+ value: string;+ onValueChange: (key: string) => void;+ portrait: boolean;+ onFlip: () => void;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ // Items listed ahead of the ratios (Video's "Match source").+ extraItems?: ReactNode;+}) {+ return (+ <div className="flex items-center gap-2">+ <Select+ value={value}+ onValueChange={onValueChange}+ open={open}+ onOpenChange={onOpenChange}+ >+ <SelectTrigger className="flex-1" aria-label="Aspect ratio">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {extraItems}+ {ASPECT_OPTIONS.map((key) => (+ <SelectItem key={key} value={key}>+ {key === "custom" ? "Custom" : `${ASPECT_LABELS[key]} (${key})`}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <Button+ type="button"+ variant="secondary"+ size="icon"+ aria-label="Flip width and height"+ onClick={onFlip}+ >+ {/* Arrows turn with the orientation, showing which way it flips. */}+ <HugeiconsIcon+ icon={ArrowLeftRightIcon}+ className={cn(+ "size-4 transition-transform duration-200",+ portrait && "rotate-90",+ )}+ />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {portrait ? "Switch to landscape" : "Switch to portrait"}+ </TooltipContent>+ </Tooltip>+ </div>+ );+}++/** A width or height box: type a value, or pick one of `options` from the chevron menu. */+export function DimensionSelect({+ icon,+ label,+ value,+ open,+ onOpenChange,+ onChange,+ options,+ snap,+}: {+ icon: IconSvgElement;+ label: string;+ value: number;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ onChange: (value: number) => void;+ options: number[];+ snap: (value: number) => number;+}) {+ // Typing is held in a draft so a half-entered number is not snapped mid-keystroke.+ const [draft, setDraft] = useState(String(value));+ const [lastValue, setLastValue] = useState(value);+ if (value !== lastValue) {+ setLastValue(value);+ setDraft(String(value));+ }+ const commit = () => {+ const typed = Number(draft);+ const next = snap(Number.isFinite(typed) && typed > 0 ? typed : value);+ setDraft(String(next));+ setLastValue(next);+ if (next !== value) onChange(next);+ };+ const pick = (n: number) => {+ setDraft(String(n));+ setLastValue(n);+ onChange(n);+ };+ return (+ <div className="flex h-9 flex-1 items-center gap-2 rounded-full border border-border bg-background px-3.5 transition-colors focus-within:border-ring dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:focus-within:bg-[rgb(255_255_255_/_calc(0.12*var(--contrast-wash-gain,1)))]">+ <HugeiconsIcon+ icon={icon}+ strokeWidth={1.75}+ className="size-4 shrink-0 text-muted-foreground"+ />+ <input+ aria-label={label}+ inputMode="numeric"+ value={draft}+ onChange={(e) => setDraft(e.target.value.replace(/[^0-9]/g, ""))}+ onBlur={commit}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commit();+ }+ }}+ className="w-full min-w-0 bg-transparent text-sm tabular-nums outline-none"+ />+ <DropdownMenu open={open} onOpenChange={onOpenChange}>+ <DropdownMenuTrigger+ aria-label={`${label} presets`}+ className="-mr-1 shrink-0 cursor-pointer rounded-full p-1 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <ChevronDown className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="max-h-[min(--spacing(72),var(--radix-dropdown-menu-content-available-height))] overflow-y-auto"+ >+ {options.map((n) => (+ <DropdownMenuItem key={n} onSelect={() => pick(n)}>+ <span className="tabular-nums">{n}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}diff --git a/studio/frontend/src/components/negative-prompt-field.tsx b/studio/frontend/src/components/negative-prompt-field.tsxindex 7d4a8b5708a..8539e7c7712 100644--- a/studio/frontend/src/components/negative-prompt-field.tsx+++ b/studio/frontend/src/components/negative-prompt-field.tsx@@ -12,13 +12,16 @@ import { cn } from "@/lib/utils";// the preset API accepts them because the generation contract does too.export const NEGATIVE_PROMPT_MAX_LENGTH = 20_000;+// Prompt boxes: smaller radius, scrollbar inset from the corners.+export const PROMPT_BOX_CLASS = "image-prompt-box rounded-lg";+export function NegativePromptField({value,onChange,open,onOpenChange,hint,- textareaClassName,+ textareaClassName = PROMPT_BOX_CLASS,}: {value: string;onChange: (value: string) => void;diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 25b83a45a91..c6e9977660d 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -172,7 +172,13 @@ import { formatBytes, formatEta } from "@/features/hub/lib/format";import { OnDeviceFoldersDialog } from "@/features/hub/catalog/on-device-folders-dialog";import { generatePhaseLabel, sameGenerateProgress } from "@/lib/media-generate-phase";import { ChevronDown } from "lucide-react";-import { NegativePromptField } from "@/components/negative-prompt-field";+import { NegativePromptField, PROMPT_BOX_CLASS } from "@/components/negative-prompt-field";+import {+ ASPECT_RATIOS,+ AspectRatioSelect,+ DimensionSelect,+ matchAspect,+} from "@/components/media-size-controls";import { cn } from "@/lib/utils";import { isTauri } from "@/lib/api-base";import { BlobUrlCache } from "@/lib/blob-url-cache";@@ -376,24 +382,6 @@ const CONDITIONED_WORKFLOW_INPUTS: Record<string, string> = {controlnet: "the control image",};-// Common aspect ratios (landscape; Flip mirrors to portrait). Picking one locks W:H; the-// sliders set the size.-const ASPECT_RATIOS: Record<string, [number, number]> = {- "1:1": [1, 1],- "3:2": [3, 2],- "4:3": [4, 3],- "16:9": [16, 9],- "21:9": [21, 9],-};-const ASPECT_OPTIONS = ["custom", ...Object.keys(ASPECT_RATIOS)];-const ASPECT_LABELS: Record<string, string> = {- "1:1": "Square",- "3:2": "Photo",- "4:3": "Landscape",- "16:9": "Widescreen",- "21:9": "Ultrawide",-};-// Friendly labels for ControlNet control types; unknown types fall back to a capitalized "(map)" label.const CONTROL_TYPE_LABELS: Record<string, string> = {passthrough: "Passthrough (already a map)",@@ -417,90 +405,6 @@ function dimOptions(limits: SizeLimits): number[] {return DIM_OPTIONS.filter((n) => n <= limits.maxSide && n % limits.multiple === 0);}-function DimensionSelect({- icon,- label,- value,- open,- onOpenChange,- onChange,- limits = DEFAULT_SIZE_LIMITS,-}: {- icon: IconSvgElement;- label: string;- value: number;- open: boolean;- onOpenChange: (open: boolean) => void;- onChange: (value: number) => void;- limits?: SizeLimits;-}) {- // Typing is held in a draft so a half-entered number is not snapped mid-keystroke.- const [draft, setDraft] = useState(String(value));- const [lastValue, setLastValue] = useState(value);- if (value !== lastValue) {- setLastValue(value);- setDraft(String(value));- }- const commit = () => {- const typed = Number(draft);- const next = snapDim(Number.isFinite(typed) && typed > 0 ? typed : value, limits);- setDraft(String(next));- setLastValue(next);- if (next !== value) onChange(next);- };- const pick = (n: number) => {- setDraft(String(n));- setLastValue(n);- onChange(n);- };- return (- <div className="flex h-9 flex-1 items-center gap-2 rounded-full border border-border bg-background px-3.5 transition-colors focus-within:border-ring dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:focus-within:bg-[rgb(255_255_255_/_calc(0.12*var(--contrast-wash-gain,1)))]">- <HugeiconsIcon- icon={icon}- strokeWidth={1.75}- className="size-4 shrink-0 text-muted-foreground"- />- <input- aria-label={label}- inputMode="numeric"- value={draft}- onChange={(e) => setDraft(e.target.value.replace(/[^0-9]/g, ""))}- onBlur={commit}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- commit();- }- }}- className="w-full min-w-0 bg-transparent text-sm tabular-nums outline-none"- />- <DropdownMenu open={open} onOpenChange={onOpenChange}>- <DropdownMenuTrigger- aria-label={`${label} presets`}- className="-mr-1 shrink-0 cursor-pointer rounded-full p-1 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <ChevronDown className="size-4" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="max-h-[min(--spacing(72),var(--radix-dropdown-menu-content-available-height))] overflow-y-auto">- {dimOptions(limits).map((n) => (- <DropdownMenuItem key={n} onSelect={() => pick(n)}>- <span className="tabular-nums">{n}</span>- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- </div>- );-}--// Hidden until the row is hovered or focused. The ratio key is compared long:short, so it survives orientation.-function matchAspect(width: number, height: number): { key: string; portrait: boolean } {- const target = Math.max(width, height) / Math.min(width, height);- const found = Object.entries(ASPECT_RATIOS).find(- ([, [a, b]]) => Math.abs(target - a / b) < 0.01,- );- return { key: found ? found[0] : "custom", portrait: height > width };-}// Module cache of the backend-persisted gallery, so a tab switch re-renders instantly; object// URLs are revoked only on delete. The 192 MB blob budget (~100-200 images) never evicts a@@ -822,8 +726,6 @@ function SliderField({}// Matches the field-label style used across Unsloth.-// Prompt boxes: smaller radius, scrollbar inset from the corners.-const IMAGE_PROMPT_BOX = "image-prompt-box rounded-lg";function Field({label,@@ -4384,50 +4286,14 @@ export function ImagesPage({label="Aspect ratio"hint="Pick a ratio to lock the proportions, then set the size below. Flip swaps width and height.">- <div className="flex items-center gap-2">- <Select- value={aspect}- onValueChange={changeAspect}- open={active && aspectOpen}- onOpenChange={(o) => setAspectOpen(active && o)}- >- <SelectTrigger className="flex-1">- <SelectValue />- </SelectTrigger>- <SelectContent>- {ASPECT_OPTIONS.map((key) => (- <SelectItem key={key} value={key}>- {key === "custom"- ? "Custom"- : `${ASPECT_LABELS[key]} (${key})`}- </SelectItem>- ))}- </SelectContent>- </Select>- <Tooltip>- <TooltipTrigger asChild={true}>- <Button- type="button"- variant="secondary"- size="icon"- aria-label="Flip width and height"- onClick={flipDimensions}- >- {/* Arrows turn with the orientation, showing which way it flips. */}- <HugeiconsIcon- icon={ArrowLeftRightIcon}- className={cn(- "size-4 transition-transform duration-200",- portrait && "rotate-90",- )}- />- </Button>- </TooltipTrigger>- <TooltipContent>- {portrait ? "Switch to landscape" : "Switch to portrait"}- </TooltipContent>- </Tooltip>- </div>+ <AspectRatioSelect+ value={aspect}+ onValueChange={changeAspect}+ open={active && aspectOpen}+ onOpenChange={(o) => setAspectOpen(active && o)}+ portrait={portrait}+ onFlip={flipDimensions}+ /></Field><Fieldlabel="Resolution"@@ -4452,7 +4318,8 @@ export function ImagesPage({open={active && widthOpen}onOpenChange={(o) => setWidthOpen(active && o)}onChange={changeWidth}- limits={sizeLimits}+ options={dimOptions(sizeLimits)}+ snap={(n) => snapDim(n, sizeLimits)}/><DimensionSelecticon={ArrowUpDownIcon}@@ -4461,7 +4328,8 @@ export function ImagesPage({open={active && heightOpen}onOpenChange={(o) => setHeightOpen(active && o)}onChange={changeHeight}- limits={sizeLimits}+ options={dimOptions(sizeLimits)}+ snap={(n) => snapDim(n, sizeLimits)}/></div></Field>@@ -5763,7 +5631,7 @@ export function ImagesPage({<Textareadata-type-to-activate="prompt"rows={4}- className={cn(IMAGE_PROMPT_BOX, "min-h-32")}+ className={cn(PROMPT_BOX_CLASS, "min-h-32")}placeholder={examplesDismissed[workflow] ? undefined : WORKFLOW_EXAMPLE_PROMPTS[workflow]}@@ -5783,7 +5651,6 @@ export function ImagesPage({open={negativeOpen}onOpenChange={setNegativeOpen}hint="What to steer the image away from. Only used when guidance is above 0."- textareaClassName={IMAGE_PROMPT_BOX}/>)}{/* LoRA adapters: shown whenever the loaded model + quant can apply them. Each carries a 0-2 weight. */}diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex ff447c451b0..4ebd7482dc3 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -38,6 +38,10 @@ export interface VideoGenerationDefaults {resolution_multiple: number;// (width, height) presets the UI offers, default first.resolution_presets: Array<[number, number]>;+ // Bounds a size off the presets must fit; absent on backends that accept only the presets.+ custom_size_min_pixels?: number | null;+ custom_size_max_pixels?: number | null;+ custom_size_max_aspect?: number | null;// Backend-owned keyframe canvas rule, or null when unsupported.canvas_short_edge?: number | null;canvas_max_pixels?: number | null;@@ -194,9 +198,9 @@ export interface VideoGenerateRequest {live_preview?: boolean;negative_prompt?: string;// Width/height/num_frames/fps default per loaded family, so they are optional. When sent they- // must match that family's rules -- a resolution preset, and num_frames on the+ // must match that family's rules -- a size near its presets, and num_frames on the// k*frame_step+1 lattice -- or the backend answers 422 with the supported shapes.- // Width/height must be one of status.defaults.resolution_presets.+ // Width/height sit on resolution_multiple inside the custom_size_* bounds, or are a preset.width?: number;height?: number;num_frames?: number;diff --git a/studio/frontend/src/features/video/keyframe-canvas.ts b/studio/frontend/src/features/video/keyframe-canvas.tsindex 820e63c8938..f96fb7d5baa 100644--- a/studio/frontend/src/features/video/keyframe-canvas.ts+++ b/studio/frontend/src/features/video/keyframe-canvas.ts@@ -3,9 +3,6 @@import type { VideoGenerationDefaults, VideoStatus } from "./api";-/** Sentinel for deriving resolution from the keyframe aspect ratio. */-export const MATCH_SOURCE_RESOLUTION = -1;-/** The preset whose aspect ratio is nearest the picture's, compared in log space so 2:1 and 1:2 are* equally far from square; ties keep the list order, so the family default wins. Mirrors the* backend's first_frame_canvas. */diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex 3a0e19ad3ca..b16e2da78ff 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -5,6 +5,8 @@ import { generationFailureLogsAction } from "@/features/settings/lib/view-logs-aimport { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import {ArrowExpand01Icon,+ ArrowLeftRightIcon,+ ArrowUpDownIcon,Refresh01Icon,Cancel01Icon,Delete02Icon,@@ -106,7 +108,20 @@ import {import { InfoHint } from "@/components/ui/info-hint";import { Switch } from "@/components/ui/switch";import { useSidebar } from "@/components/ui/sidebar";-import { NegativePromptField } from "@/components/negative-prompt-field";+import { NegativePromptField, PROMPT_BOX_CLASS } from "@/components/negative-prompt-field";+import {+ ASPECT_RATIOS,+ AspectRatioSelect,+ DimensionSelect,+ matchAspect,+} from "@/components/media-size-controls";+import {+ fitVideoSize,+ isPresetSize,+ snapVideoDim,+ videoDimOptions,+ videoSizeLimits,+} from "./video-size";import { usePersistedChoice } from "@/hooks/use-persisted-choice";import { useScrollFades } from "@/hooks/use-scroll-fades";import { ModelSelector } from "@/features/model-picker/components/model-selector";@@ -142,7 +157,6 @@ import {MediaGenerationPresetControl,type VideoGenerationPresetParams,closestDurationIndex,- closestResolutionIndex,shouldApplyModelDefaults,useMediaGenerationPresets,} from "@/features/generation-presets";@@ -183,7 +197,7 @@ import { loadGalleryUntil } from "@/lib/gallery-deep-link";import { subscribeModelEjected } from "@/lib/model-lifecycle-events";import { BlobUrlCache } from "@/lib/blob-url-cache";-import { MATCH_SOURCE_RESOLUTION, keyframeSupport, matchedCanvas } from "./keyframe-canvas";+import { keyframeSupport, matchedCanvas } from "./keyframe-canvas";import { hasReferenceCapacity } from "./reference-budget";import {applyReferenceImageCrop,@@ -327,6 +341,8 @@ const FALLBACK_RESOLUTION_PRESETS: Array<[number, number]> = [[704, 1216],];+const MATCH_SOURCE = "match";+// Fallbacks for the duration presets before a model is loaded, so the select is populated and valid on first paint.const FALLBACK_FRAME_STEP = 8;const FALLBACK_FRAME_OFFSET = 1;@@ -1041,11 +1057,13 @@ function VideoGenerator({guidance: number;} | null>(null);const [seed, setSeed] = useState("");- // Preset index, or MATCH_SOURCE_RESOLUTION for a keyframe-derived canvas.- const [resolutionIdx, setResolutionIdx] = useState(0);+ // True while a staged keyframe sizes the canvas ("Match source"); else resolutionIntent does.+ const [matchSource, setMatchSource] = useState(false);const [resolutionIntent, setResolutionIntent] = useState<[number, number]>(FALLBACK_RESOLUTION_PRESETS[0]!,);+ const [aspect, setAspect] = useState(() => matchAspect(...FALLBACK_RESOLUTION_PRESETS[0]!).key);+ const [portrait, setPortrait] = useState(false);// MiniMax-H3 keyframes as data URLs: the frame the clip starts from, the frame it ends on, or both.const [firstFrame, setFirstFrame] = useState<string | null>(null);const [lastFrame, setLastFrame] = useState<string | null>(null);@@ -1311,10 +1329,15 @@ function VideoGenerator({}return FALLBACK_RESOLUTION_PRESETS;}, [status?.defaults?.resolution_presets]);- const livePreviewPreset = resolutionPresets[resolutionIdx] ?? resolutionPresets[0];- const livePreviewBox = livePreviewPreset- ? { maxWidth: livePreviewPreset[0], maxHeight: livePreviewPreset[1] }- : undefined;+ const sizeLimits = useMemo(+ () => videoSizeLimits(status?.defaults, resolutionPresets),+ [status?.defaults, resolutionPresets],+ );+ // The intent survives a family swap; what is shown and sent is its nearest size the family accepts.+ const videoSize = useMemo(+ () => fitVideoSize(resolutionIntent[0], resolutionIntent[1], sizeLimits),+ [resolutionIntent, sizeLimits],+ );const frameStep = status?.defaults?.frame_step ?? FALLBACK_FRAME_STEP;const frameOffset = status?.defaults?.frame_offset ?? FALLBACK_FRAME_OFFSET;@@ -1337,13 +1360,6 @@ function VideoGenerator({return out;}, [frameStep, frameOffset, fps, durationTargets]);- // Keep the resolution / frame-count selections valid when the loaded family changes.- useEffect(() => {- setResolutionIdx((idx) =>- idx === MATCH_SOURCE_RESOLUTION || idx < resolutionPresets.length ? idx : 0,- );- }, [resolutionPresets.length]);-const { first: supportsFirstFrame, last: supportsLastFrame } = keyframeSupport(status);const supportsKeyframes = supportsFirstFrame || supportsLastFrame;// The keyframe the canvas follows: the first when there is one, else the last, matching the backend.@@ -1407,11 +1423,12 @@ function VideoGenerator({[keyframeAspect, status?.defaults],);+ const sourceSized = matchSource && canvasKeyframe != null && matchedResolution != null;+ const shownSize = sourceSized ? matchedResolution : videoSize;+ const livePreviewBox = { maxWidth: shownSize[0], maxHeight: shownSize[1] };+const videoPresetParams = useMemo<VideoGenerationPresetParams>(() => {- const resolution =- resolutionIdx === MATCH_SOURCE_RESOLUTION && matchedResolution- ? matchedResolution- : resolutionIntent;+ const resolution = sourceSized ? matchedResolution : videoSize;return {negativePrompt,width: resolution[0],@@ -1422,7 +1439,7 @@ function VideoGenerator({flowShift,audioFlowShift,};- }, [audioFlowShift, durationIntentSeconds, flowShift, guidance, matchedResolution, negativePrompt, resolutionIdx, resolutionIntent, steps]);+ }, [audioFlowShift, durationIntentSeconds, flowShift, guidance, matchedResolution, negativePrompt, sourceSized, videoSize, steps]);const defaultSteps = status?.defaults?.steps;const defaultGuidance = status?.defaults?.guidance;const familyDefaultFrames = status?.defaults?.num_frames;@@ -1456,21 +1473,20 @@ function VideoGenerator({}, [defaultAudioFlowShift, defaultFlowShift, defaultGuidance, defaultSteps, durationOptions, familyDefaultFrames, fps, pendingModelDefaults, presetRepoId, resolutionPresets, status?.loaded]);const applyVideoPresetParams = useCallback((params: VideoGenerationPresetParams) => {- const resolutionIndex = closestResolutionIndex(- resolutionPresets,- params.width,- params.height,- );+ const size = fitVideoSize(params.width, params.height, sizeLimits);const durationIndex = closestDurationIndex(durationOptions, params.durationSeconds);const durationFrames =durationOptions[durationIndex]?.frames ?? durationOptions[0]?.frames ?? numFrames;- setResolutionIntent([params.width, params.height]);+ setResolutionIntent(size);+ const matched = matchAspect(size[0], size[1]);+ setAspect(matched.key);+ setPortrait(matched.portrait);+ setMatchSource(false);setDurationIntentSeconds(params.durationSeconds);setNegativePrompt(params.negativePrompt);// Same rule restoreSettings follows: a negative prompt in effect has to be visible, or the// user generates against a setting the collapsed field is hiding.if (params.negativePrompt) setNegativeOpen(true);- setResolutionIdx(resolutionIndex);setNumFrames(durationFrames);setSteps(params.steps);setGuidance(params.guidance);@@ -1478,14 +1494,11 @@ function VideoGenerator({setAudioFlowShift(params.audioFlowShift);return params;},- [durationOptions, numFrames, resolutionPresets],+ [durationOptions, numFrames, sizeLimits],);const normalizeVideoPresetParams = useCallback((params: VideoGenerationPresetParams) => {- const resolution =- resolutionPresets[- closestResolutionIndex(resolutionPresets, params.width, params.height)- ] ?? resolutionPresets[0] ?? [768, 512];+ const resolution = fitVideoSize(params.width, params.height, sizeLimits);const duration =durationOptions[closestDurationIndex(durationOptions, params.durationSeconds)@@ -1497,7 +1510,7 @@ function VideoGenerator({durationSeconds: duration,};},- [durationOptions, resolutionPresets],+ [durationOptions, sizeLimits],);const videoPresets = useMediaGenerationPresets({kind: "video",@@ -1541,17 +1554,6 @@ function VideoGenerator({[claimVideoRecipe, familyOverride, videoFormClaimId],);- useEffect(() => {- setResolutionIdx((current) => {- if (current === MATCH_SOURCE_RESOLUTION) return current;- return closestResolutionIndex(- resolutionPresets,- resolutionIntent[0],- resolutionIntent[1],- );- });- }, [resolutionIntent, resolutionPresets]);-// Select "match source" only after the staged keyframe passes the aspect-ratio check.const hadKeyframeRef = useRef(false);useEffect(() => {@@ -1559,17 +1561,8 @@ function VideoGenerator({if (has === hadKeyframeRef.current) return;if (has && !matchedResolution) return;hadKeyframeRef.current = has;- setResolutionIdx((idx) => {- if (has) return MATCH_SOURCE_RESOLUTION;- return idx === MATCH_SOURCE_RESOLUTION- ? closestResolutionIndex(- resolutionPresets,- resolutionIntent[0],- resolutionIntent[1],- )- : idx;- });- }, [canvasKeyframe, matchedResolution, resolutionIntent, resolutionPresets]);+ setMatchSource(has);+ }, [canvasKeyframe, matchedResolution]);const loadedFamily = status?.loaded ? status.family : null;const prevFamilyRef = useRef<string | null>(null);@@ -2261,14 +2254,12 @@ function VideoGenerator({if (video.flow_shift != null) setFlowShift(video.flow_shift);if (video.audio_flow_shift != null) setAudioFlowShift(video.audio_flow_shift);setSeed(String(video.seed));- // Snap the resolution to the matching preset when one exists; else leave as is.- const presetIdx = resolutionPresets.findIndex(- ([w, h]) => w === video.width && h === video.height,- );- if (presetIdx >= 0) {- setResolutionIntent([video.width, video.height]);- setResolutionIdx(presetIdx);- }+ const size = fitVideoSize(video.width, video.height, sizeLimits);+ setResolutionIntent(size);+ const matched = matchAspect(size[0], size[1]);+ setAspect(matched.key);+ setPortrait(matched.portrait);+ setMatchSource(false);// Restore the frame count when it lies on the current lattice.if (durationOptions.some((o) => o.frames === video.num_frames)) {setDurationIntentSeconds(video.num_frames / fps);@@ -2276,7 +2267,7 @@ function VideoGenerator({}toast.success("Settings restored to inputs");},- [resolutionPresets, durationOptions, fps],+ [sizeLimits, durationOptions, fps],);// A status read started before an eject can answer after the one that followed it, and this@@ -3438,6 +3429,54 @@ function VideoGenerator({}}, []);+ // As on Images: a locked ratio keeps the paired side in step; every pair is fitted to the family.+ const dimOptions = useMemo(() => videoDimOptions(sizeLimits), [sizeLimits]);+ const applySize = (width: number, height: number, keepAspect = false) => {+ const size = fitVideoSize(width, height, sizeLimits);+ setResolutionIntent(size);+ setMatchSource(false);+ if (keepAspect) return;+ const matched = matchAspect(size[0], size[1]);+ setAspect(matched.key);+ setPortrait(matched.portrait);+ };+ const ratioHW = (key: string, isPortrait: boolean) => {+ const [a, b] = ASPECT_RATIOS[key] ?? [1, 1];+ return isPortrait ? a / b : b / a;+ };+ const changeAspect = (key: string) => {+ if (key === MATCH_SOURCE) {+ setMatchSource(true);+ return;+ }+ setAspect(key);+ const [w, h] = shownSize;+ // Leaving Match source takes the keyframe's orientation with its size.+ const isPortrait = sourceSized ? h > w : portrait;+ setPortrait(isPortrait);+ if (key === "custom") {+ applySize(w, h, true);+ return;+ }+ applySize(w, snapVideoDim(w * ratioHW(key, isPortrait), sizeLimits), true);+ };+ const changeWidth = (v: number) => {+ const locked = !sourceSized && aspect !== "custom";+ applySize(v, locked ? snapVideoDim(v * ratioHW(aspect, portrait), sizeLimits) : shownSize[1], locked);+ };+ const changeHeight = (v: number) => {+ const locked = !sourceSized && aspect !== "custom";+ applySize(locked ? snapVideoDim(v / ratioHW(aspect, portrait), sizeLimits) : shownSize[0], v, locked);+ };+ const flipDimensions = () => {+ if (sourceSized) {+ applySize(shownSize[1], shownSize[0]);+ return;+ }+ applySize(shownSize[1], shownSize[0], true);+ setPortrait((p) => !p);+ };+const handleGenerate = useCallback(async () => {if (!prompt.trim()) {toast.error("Prompt is empty");@@ -3475,8 +3514,6 @@ function VideoGenerator({}// Omitting both dimensions delegates "match source" to the backend.- const matchSource = resolutionIdx === MATCH_SOURCE_RESOLUTION;- const preset = resolutionPresets[resolutionIdx] ?? resolutionPresets[0];// Saved only once the request passes validation, so a rejected attempt is not kept.saveLastPrompt("video", prompt);@@ -3492,8 +3529,8 @@ function VideoGenerator({status?.supports_cfg !== false && guidance > 0? negativePrompt.trim() || undefined: undefined,- width: matchSource ? undefined : preset[0],- height: matchSource ? undefined : preset[1],+ width: sourceSized ? undefined : videoSize[0],+ height: sourceSized ? undefined : videoSize[1],num_frames: numFrames,fps,steps,@@ -3550,8 +3587,8 @@ function VideoGenerator({negativePrompt,guidance,seed,- resolutionPresets,- resolutionIdx,+ videoSize,+ sourceSized,numFrames,fps,steps,@@ -3917,6 +3954,7 @@ function VideoGenerator({<Textareadata-type-to-activate="prompt"rows={4}+ className={cn(PROMPT_BOX_CLASS, "min-h-32")}placeholder={exampleDismissed ? undefined : VIDEO_EXAMPLE_PROMPT}value={prompt}onFocus={() => {@@ -3927,6 +3965,15 @@ function VideoGenerator({onChange={(e) => setPrompt(e.target.value)}/></Field>+ {status?.supports_cfg !== false && (+ <NegativePromptField+ value={negativePrompt}+ onChange={setNegativePrompt}+ open={negativeOpen}+ onOpenChange={setNegativeOpen}+ hint="What to steer the video away from. Only used when guidance is above 0."+ />+ )}{supportsKeyframes && (<div className="grid gap-2" data-testid="video-keyframes">@@ -4268,43 +4315,69 @@ function VideoGenerator({/>)}- {status?.supports_cfg !== false && (- <NegativePromptField- value={negativePrompt}- onChange={setNegativePrompt}- open={negativeOpen}- onOpenChange={setNegativeOpen}- hint="What to steer the video away from. Only used when guidance is above 0."+ <Field+ label="Aspect ratio"+ hint="Pick a ratio to lock the proportions, then set the size below. Flip swaps width and height. With a keyframe staged, Match source keeps the picture's own shape."+ >+ <AspectRatioSelect+ value={sourceSized ? MATCH_SOURCE : aspect}+ onValueChange={changeAspect}+ portrait={sourceSized ? shownSize[1] > shownSize[0] : portrait}+ onFlip={flipDimensions}+ extraItems={+ canvasKeyframe && matchedResolution ? (+ <SelectItem value={MATCH_SOURCE}>Match source</SelectItem>+ ) : null+ }/>- )}+ </Field><Fieldlabel="Resolution"- hint="The frame size. Presets come from the loaded model; portrait presets are marked. With a keyframe staged, Match source keeps the picture's own shape."+ hint={`Width and height in pixels, in steps of ${sizeLimits.multiple}. The model was trained at ${resolutionPresets.map(([w, h]) => `${w} × ${h}`).join(", ")}; other sizes keep about the same pixel count and may lower quality.`}+ >+ <div className="flex items-center gap-2">+ <DimensionSelect+ icon={ArrowLeftRightIcon}+ label="Width"+ value={shownSize[0]}+ onChange={changeWidth}+ options={dimOptions}+ snap={(n) => snapVideoDim(n, sizeLimits)}+ />+ <DimensionSelect+ icon={ArrowUpDownIcon}+ label="Height"+ value={shownSize[1]}+ onChange={changeHeight}+ options={dimOptions}+ snap={(n) => snapVideoDim(n, sizeLimits)}+ />+ </div>+ {!sourceSized && !isPresetSize(videoSize[0], videoSize[1], sizeLimits) && (+ <p className="text-ui-11 leading-snug text-muted-foreground">+ Not one of the model's trained sizes, so quality may be lower.+ </p>+ )}+ </Field>++ <Field+ label="Trained sizes"+ hint="The sizes the loaded model was trained at, which give the best quality. Portrait sizes are marked."><Select- value={String(resolutionIdx)}+ value=""onValueChange={(v) => {- const index = Number(v);- const resolution = resolutionPresets[index];- if (resolution) setResolutionIntent(resolution);- setResolutionIdx(index);+ const preset = resolutionPresets.find(([w, h]) => `${w}x${h}` === v);+ if (preset) applySize(preset[0], preset[1]);}}>- <SelectTrigger>- <SelectValue />+ <SelectTrigger aria-label="Trained sizes">+ <SelectValue placeholder="Choose a trained size" /></SelectTrigger><SelectContent>- {canvasKeyframe && (- <SelectItem value={String(MATCH_SOURCE_RESOLUTION)}>- Match source- {matchedResolution- ? ` · ${matchedResolution[0]} × ${matchedResolution[1]}`- : ""}- </SelectItem>- )}- {resolutionPresets.map(([w, h], i) => (- <SelectItem key={`${w}x${h}`} value={String(i)}>+ {resolutionPresets.map(([w, h]) => (+ <SelectItem key={`${w}x${h}`} value={`${w}x${h}`}>{w} × {h}{h > w ? " (portrait)" : ""}</SelectItem>diff --git a/studio/frontend/src/features/video/video-size.ts b/studio/frontend/src/features/video/video-size.tsnew file mode 100644index 00000000000..edad514a704--- /dev/null+++ b/studio/frontend/src/features/video/video-size.ts@@ -0,0 +1,163 @@+// 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 { closestResolutionIndex } from "../generation-presets/preset-policy.ts";+import type { VideoGenerationDefaults } from "./api";++const MAX_VIDEO_SIDE = 2048;+const MAX_ASPECT = 4;++/** What validate_video_request_shape accepts for the loaded family. */+export interface VideoSizeLimits {+ multiple: number;+ minPixels: number;+ maxPixels: number;+ maxAspect: number;+ presets: Array<[number, number]>;+ // An older backend refuses anything off the presets.+ presetsOnly: boolean;+}++/** Mirrors the backend's video_custom_size_bounds for the pre-load fallback presets. */+function boundsFromPresets(presets: Array<[number, number]>) {+ const areas = presets.map(([w, h]) => w * h);+ const smallest = Math.min(...areas);+ const largest = Math.max(...areas);+ return {+ minPixels: Math.min(smallest, Math.floor(largest / 2)),+ maxPixels: largest,+ maxAspect: Math.max(+ MAX_ASPECT,+ ...presets.map(([w, h]) => Math.max(w, h) / Math.min(w, h)),+ ),+ };+}++export function videoSizeLimits(+ defaults: VideoGenerationDefaults | null | undefined,+ presets: Array<[number, number]>,+): VideoSizeLimits {+ const multiple = defaults?.resolution_multiple || 32;+ if (defaults?.custom_size_max_pixels && defaults.custom_size_min_pixels) {+ return {+ multiple,+ minPixels: defaults.custom_size_min_pixels,+ maxPixels: defaults.custom_size_max_pixels,+ maxAspect: defaults.custom_size_max_aspect || MAX_ASPECT,+ presets,+ presetsOnly: false,+ };+ }+ return {+ multiple,+ ...boundsFromPresets(presets),+ presets,+ presetsOnly: defaults != null,+ };+}++export function isPresetSize(+ width: number,+ height: number,+ limits: VideoSizeLimits,+): boolean {+ return limits.presets.some(([w, h]) => w === width && h === height);+}++export function isValidVideoSize(+ width: number,+ height: number,+ limits: VideoSizeLimits,+): boolean {+ if (isPresetSize(width, height, limits)) return true;+ if (limits.presetsOnly) return false;+ const m = limits.multiple;+ if (width <= 0 || height <= 0 || width % m || height % m) return false;+ if (width > MAX_VIDEO_SIDE || height > MAX_VIDEO_SIDE) return false;+ const area = width * height;+ if (area < limits.minPixels || area > limits.maxPixels) return false;+ return (+ Math.max(width, height) / Math.min(width, height) <= limits.maxAspect + 1e-9+ );+}++function closestPreset(+ width: number,+ height: number,+ limits: VideoSizeLimits,+): [number, number] {+ return (+ limits.presets[closestResolutionIndex(limits.presets, width, height)] ??+ limits.presets[0] ?? [768, 512]+ );+}++/** One side on the family grid and inside the request bounds. */+export function snapVideoDim(value: number, limits: VideoSizeLimits): number {+ const m = limits.multiple;+ if (!Number.isFinite(value) || value <= 0) return m;+ return Math.min(+ Math.floor(MAX_VIDEO_SIDE / m) * m,+ Math.max(m, Math.round(value / m) * m),+ );+}++/** The nearest size the backend accepts: kept when valid, else rescaled into the area band at the+ * nearest ratio (clamped to the aspect cap), else the closest trained preset. */+export function fitVideoSize(+ width: number,+ height: number,+ limits: VideoSizeLimits,+): [number, number] {+ if (isValidVideoSize(width, height, limits)) return [width, height];+ if (limits.presetsOnly || width <= 0 || height <= 0)+ return closestPreset(width, height, limits);+ const m = limits.multiple;+ const ratio = Math.min(+ limits.maxAspect,+ Math.max(1 / limits.maxAspect, width / height),+ );+ const area = Math.min(+ limits.maxPixels,+ Math.max(limits.minPixels, width * height),+ );+ // Grid search, ratio weighted over area.+ let best: [number, number] | null = null;+ let bestScore = Number.POSITIVE_INFINITY;+ for (let h = m; h <= MAX_VIDEO_SIDE; h += m) {+ for (const w of [+ Math.floor((h * ratio) / m) * m,+ Math.ceil((h * ratio) / m) * m,+ ]) {+ if (!isValidVideoSize(w, h, limits)) continue;+ const score =+ Math.abs(Math.log(w / h / ratio)) * 4 ++ Math.abs(Math.log((w * h) / area));+ if (score < bestScore) {+ best = [w, h];+ bestScore = score;+ }+ }+ }+ if (best) return best;+ return closestPreset(width, height, limits);+}++const DIM_CANDIDATES = [+ 384, 448, 480, 512, 544, 576, 640, 704, 720, 768, 832, 864, 896, 960, 1024,+ 1088, 1152, 1216, 1280, 1344, 1408, 1536, 1664, 1792, 1920, 2048,+];++/** Sides offered in the width/height menus: common sizes on the grid that some valid frame can use. */+export function videoDimOptions(limits: VideoSizeLimits): number[] {+ const sides = new Set(limits.presets.flat());+ if (!limits.presetsOnly) {+ const longest = Math.sqrt(limits.maxPixels * limits.maxAspect);+ const shortest = Math.sqrt(limits.minPixels / limits.maxAspect);+ for (const n of DIM_CANDIDATES) {+ if (n % limits.multiple === 0 && n <= longest && n >= shortest)+ sides.add(n);+ }+ }+ return [...sides].sort((a, b) => a - b);+}diff --git a/studio/frontend/tests/video-custom-size.test.ts b/studio/frontend/tests/video-custom-size.test.tsnew file mode 100644index 00000000000..434ee41e2d9--- /dev/null+++ b/studio/frontend/tests/video-custom-size.test.ts@@ -0,0 +1,88 @@+// 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 type { VideoGenerationDefaults } from "../src/features/video/api.ts";+import {+ fitVideoSize,+ isValidVideoSize,+ videoDimOptions,+ videoSizeLimits,+} from "../src/features/video/video-size.ts";++const LTX2_PRESETS: Array<[number, number]> = [+ [768, 512],+ [1216, 704],+ [704, 1216],+ [512, 768],+];++function ltx2Defaults(extra: Partial<VideoGenerationDefaults> = {}): VideoGenerationDefaults {+ return {+ steps: 8,+ guidance: 1,+ num_frames: 121,+ fps: 24,+ frame_step: 8,+ frame_offset: 1,+ duration_presets: [1, 2, 3, 5],+ resolution_multiple: 32,+ resolution_presets: LTX2_PRESETS,+ custom_size_min_pixels: 768 * 512,+ custom_size_max_pixels: 1216 * 704,+ custom_size_max_aspect: 4,+ ...extra,+ };+}++test("custom sizes on the grid inside the backend band are kept as typed", () => {+ const limits = videoSizeLimits(ltx2Defaults(), LTX2_PRESETS);+ assert.deepEqual(fitVideoSize(1024, 576, limits), [1024, 576]);+ assert.deepEqual(fitVideoSize(768, 512, limits), [768, 512]);+ assert.equal(isValidVideoSize(1000, 576, limits), false);+});++test("sizes outside the band are rescaled into it at the same ratio", () => {+ const limits = videoSizeLimits(ltx2Defaults(), LTX2_PRESETS);+ const [w, h] = fitVideoSize(1920, 1080, limits);+ assert.ok(isValidVideoSize(w, h, limits));+ assert.ok(Math.abs(w / h - 16 / 9) < 0.1, `${w}x${h} drifted from 16:9`);+ const [sw, sh] = fitVideoSize(256, 256, limits);+ assert.ok(isValidVideoSize(sw, sh, limits) && sw === sh, `${sw}x${sh}`);+});++test("a backend without custom-size bounds keeps the presets only", () => {+ const limits = videoSizeLimits(+ ltx2Defaults({+ custom_size_min_pixels: undefined,+ custom_size_max_pixels: undefined,+ custom_size_max_aspect: undefined,+ }),+ LTX2_PRESETS,+ );+ assert.equal(limits.presetsOnly, true);+ assert.deepEqual(fitVideoSize(1920, 1080, limits), [1216, 704]);+ assert.deepEqual(videoDimOptions(limits), [512, 704, 768, 1216]);+});++test("before a model loads the fallback presets bound the size like the backend would", () => {+ const limits = videoSizeLimits(null, LTX2_PRESETS.slice(0, 3));+ assert.equal(limits.presetsOnly, false);+ assert.equal(limits.minPixels, 768 * 512);+ assert.equal(limits.maxPixels, 1216 * 704);+ assert.ok(videoDimOptions(limits).every((n) => n % 32 === 0));+});++test("an extreme valid ratio stays near its shape instead of snapping to a preset", () => {+ const limits = videoSizeLimits(ltx2Defaults(), LTX2_PRESETS);+ for (const [w0, h0] of [+ [1920, 480],+ [2048, 512],+ ]) {+ const [w, h] = fitVideoSize(w0, h0, limits);+ assert.ok(isValidVideoSize(w, h, limits), `${w}x${h}`);+ assert.ok(w / h > 3.5, `${w0}x${h0} fitted to ${w}x${h}`);+ }+});