Skip to content

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

Studio: add image and video generation presets (#8390)

oobabooga4ca3836deab3
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 69a7539c433..eb204db3e71 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -4,11 +4,11 @@
import functools
import re
import threading
-from typing import Any, Literal, Optional
+from typing import Any, Literal, Optional, get_args
from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, Depends, HTTPException, Request
-from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator
+from pydantic import BaseModel, ConfigDict, Field, StrictBool, ValidationError, field_validator
from auth.authentication import (
authenticated_via_api_key,
@@ -107,12 +107,354 @@ from utils.embedding_model_settings import (
validate_embedding_model,
)
from utils.hf_cache_settings import cache_status, get_hf_cache_paths, set_hf_cache_home
+from utils.media_generation_preset_settings import (
+ delete_media_generation_preset,
+ get_media_generation_preset_settings,
+ set_media_generation_preset_settings,
+ upsert_media_generation_preset,
+)
router = APIRouter()
logger = get_logger(__name__)
+class ImageGenerationPresetParams(BaseModel):
+ """Bounds track DiffusionGenerateRequest. A preset the generate endpoint would refuse is not
+ a usable preset: selecting it would make every following Generate fail validation."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ negativePrompt: str = ""
+ width: int = Field(default = 1024, ge = 256, le = 2048, multiple_of = 16)
+ height: int = Field(default = 1024, ge = 256, le = 2048, multiple_of = 16)
+ steps: int = Field(default = 9, ge = 1, le = 100)
+ guidance: float = Field(default = 0, ge = 0, le = 20)
+ batchSize: int = Field(default = 1, ge = 1, le = 32)
+ runs: int = Field(default = 1, ge = 1)
+
+
+class VideoGenerationPresetParams(BaseModel):
+ """Bounds track VideoGenerateRequest, as the image params track theirs."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ negativePrompt: str = ""
+ width: int = Field(default = 768, ge = 32, le = 2048)
+ height: int = Field(default = 512, ge = 32, le = 2048)
+ durationSeconds: float = Field(default = 3, gt = 0, le = 3600)
+ steps: int = Field(default = 8, ge = 1, le = 100)
+ guidance: float = Field(default = 1, ge = 0, le = 20)
+ flowShift: Optional[float] = Field(default = None, gt = 0, le = 100)
+ audioFlowShift: Optional[float] = Field(default = None, gt = 0, le = 100)
+
+
+class MediaGenerationPreset(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ name: str = Field(..., min_length = 1, max_length = 80)
+
+ @field_validator("name")
+ @classmethod
+ def normalize_name(cls, value: str) -> str:
+ name = value.strip()
+ if not name or name == "Default":
+ raise ValueError("Preset name is reserved or empty")
+ return name
+
+
+class ImageGenerationPreset(MediaGenerationPreset):
+ params: ImageGenerationPresetParams
+
+
+class VideoGenerationPreset(MediaGenerationPreset):
+ params: VideoGenerationPresetParams
+
+
+class MediaGenerationPresetState(BaseModel):
+ """A saved generation recipe and the selection that owns it.
+
+ Model-load options are deliberately not here: they take effect only on a reload, they follow
+ the hardware and the checkpoint rather than the recipe, and the resident build already reports
+ them, so a second stored copy would only ever compete with it.
+ """
+
+ model_config = ConfigDict(extra = "forbid")
+
+ activePreset: str = Field(default = "Default", min_length = 1, max_length = 80)
+
+
+class ImageGenerationPresetState(MediaGenerationPresetState):
+ currentParams: ImageGenerationPresetParams = Field(default_factory = ImageGenerationPresetParams)
+
+
+class VideoGenerationPresetState(MediaGenerationPresetState):
+ currentParams: VideoGenerationPresetParams = Field(default_factory = VideoGenerationPresetParams)
+
+
+class ImageGenerationPresetSettings(ImageGenerationPresetState):
+ # No cap on the read: upsert_media_generation_preset owns the limit, and refusing to
+ # report a store that somehow exceeds it would only turn a GET into a 500.
+ customPresets: list[ImageGenerationPreset] = Field(default_factory = list)
+ saved: bool = False
+
+
+class VideoGenerationPresetSettings(VideoGenerationPresetState):
+ # No cap on the read: upsert_media_generation_preset owns the limit, and refusing to
+ # report a store that somehow exceeds it would only turn a GET into a 500.
+ customPresets: list[VideoGenerationPreset] = Field(default_factory = list)
+ saved: bool = False
+
+
+def _nested_model(annotation: Any) -> Optional[type[BaseModel]]:
+ for candidate in (annotation, *get_args(annotation)):
+ if isinstance(candidate, type) and issubclass(candidate, BaseModel):
+ return candidate
+ return None
+
+
+def _readable(model: type[BaseModel], value: Any) -> Any:
+ """Drop what this build's schema does not define, keeping every field it does.
+
+ `extra = "forbid"` is right for a submitted payload but wrong for reading storage back: a blob
+ holding one field from a newer build would otherwise fail validation, and a stored recipe the
+ user can no longer read is worse than one missing a field this build cannot render anyway.
+ """
+ if isinstance(value, list):
+ return [_readable(model, item) for item in value]
+ if not isinstance(value, dict):
+ return value
+ readable = {}
+ for name, field in model.model_fields.items():
+ if name not in value:
+ continue
+ nested = _nested_model(field.annotation)
+ readable[name] = _readable(nested, value[name]) if nested else value[name]
+ return readable
+
+
+def _without_field_at_location(value: Any, location: tuple[Any, ...]) -> tuple[Any, bool]:
+ """Return a copy with one invalid leaf removed from a nested model payload."""
+ if not location:
+ return value, False
+ key, *rest = location
+ if not isinstance(value, dict) or key not in value:
+ return value, False
+ result = dict(value)
+ if not rest:
+ result.pop(key)
+ return result, True
+ nested, removed = _without_field_at_location(result[key], tuple(rest))
+ if removed:
+ result[key] = nested
+ return result, removed
+
+
+def _validated_without_invalid_fields(
+ schema: type[BaseModel], payload: dict
+) -> tuple[BaseModel, list[tuple[Any, ...]]]:
+ """Validate, dropping only the fields that fail.
+
+ Resetting the whole recipe over one unreadable field would hand the client schema defaults,
+ which it then autosaves over the rest of a perfectly good stored recipe.
+ """
+ remaining = payload
+ removed_locations = []
+ while True:
+ try:
+ return schema.model_validate(remaining), removed_locations
+ except ValidationError as exc:
+ for error in exc.errors():
+ location = tuple(error.get("loc", ()))
+ remaining, removed = _without_field_at_location(remaining, location)
+ if removed:
+ removed_locations.append(location)
+ break
+ else:
+ return schema(), removed_locations
+
+
+_MISSING = object()
+
+
+def _value_at_location(value: Any, location: tuple[Any, ...]) -> Any:
+ for key in location:
+ if not isinstance(value, dict) or key not in value:
+ return _MISSING
+ value = value[key]
+ return value
+
+
+def _with_value_at_location(
+ value: Any, location: tuple[Any, ...], replacement: Any
+) -> tuple[Any, bool]:
+ if not location:
+ return replacement, True
+ key, *rest = location
+ if not isinstance(value, dict) or key not in value:
+ return value, False
+ result = dict(value)
+ nested, replaced = _with_value_at_location(result[key], tuple(rest), replacement)
+ if replaced:
+ result[key] = nested
+ return result, replaced
+
+
+def _preserve_recovered_defaults(schema: type[BaseModel], stored: dict, submitted: dict) -> dict:
+ """Do not mistake a recovery default for an edit to an unreadable stored field.
+
+ A downgraded GET omits known fields whose values this schema cannot validate, then Pydantic
+ supplies their defaults in the response. The client cannot tell those defaults from stored
+ values and echoes them in its next state write. Preserve the raw leaf only while the submitted
+ value is still the synthesized value; a real edit remains authoritative.
+ """
+ recovered, locations = _validated_without_invalid_fields(schema, _readable(schema, stored))
+ recovered_values = recovered.model_dump()
+ merged = submitted
+ for location in locations:
+ previous = _value_at_location(stored, location)
+ submitted_value = _value_at_location(submitted, location)
+ recovered_value = _value_at_location(recovered_values, location)
+ if (
+ previous is not _MISSING
+ and submitted_value is not _MISSING
+ and recovered_value is not _MISSING
+ and submitted_value == recovered_value
+ ):
+ merged, _ = _with_value_at_location(merged, location, previous)
+ return merged
+
+
+def _validated_readable_model(schema: type[BaseModel], payload: Any) -> Optional[BaseModel]:
+ try:
+ return schema.model_validate(_readable(schema, payload))
+ except ValidationError:
+ return None
+
+
+def _get_generation_preset_settings(kind, schema):
+ stored = get_media_generation_preset_settings(kind)
+ try:
+ response = schema.model_validate(_readable(schema, stored))
+ except ValidationError:
+ # A value this build cannot represent at all. Drop only what fails: one unreadable entry
+ # costs neither the rest of the list nor the state, which is validated on its own here.
+ logger.warning("Dropping unreadable %s generation preset entries", kind)
+ presets = schema.model_fields["customPresets"].annotation
+ item = _nested_model(get_args(presets)[0] if get_args(presets) else presets)
+ readable = []
+ # Only a list is a preset collection. Recovery exists so a store this build cannot
+ # represent still reads; iterating a scalar here would answer 500 instead, which is the
+ # one outcome it is meant to prevent. _custom_presets takes the same view on the write.
+ raw_presets = stored.get("customPresets")
+ for raw in raw_presets if isinstance(raw_presets, list) else []:
+ validated = _validated_readable_model(item, raw)
+ if validated is not None:
+ readable.append(validated)
+ state = {
+ key: value for key, value in _readable(schema, stored).items() if key != "customPresets"
+ }
+ response, _ = _validated_without_invalid_fields(
+ schema, {**state, "customPresets": readable}
+ )
+ # Saved means the store owns the CURRENT recipe, not merely that something is stored. A blob
+ # holding named presets but no recipe -- a preset write that landed while the state write did
+ # not -- would otherwise hand back schema defaults dressed as the user's own choice, and the
+ # client suppresses the resident model's defaults for exactly as long as it believes that.
+ response.saved = isinstance(stored.get("currentParams"), dict)
+ return response
+
+
+ "/generation-presets/image",
+ response_model = ImageGenerationPresetSettings,
+)
+def get_image_generation_preset_settings(
+ current_subject: str = Depends(get_current_subject),
+) -> ImageGenerationPresetSettings:
+ return _get_generation_preset_settings("image", ImageGenerationPresetSettings)
+
+
[email protected]("/generation-presets/image")
+def update_image_generation_preset_settings(
+ payload: ImageGenerationPresetState, current_subject: str = Depends(get_current_subject)
+) -> dict[str, bool]:
+ set_media_generation_preset_settings(
+ "image",
+ payload.model_dump(),
+ lambda stored, submitted: _preserve_recovered_defaults(
+ ImageGenerationPresetState, stored, submitted
+ ),
+ )
+ return {"saved": True}
+
+
+ "/generation-presets/video",
+ response_model = VideoGenerationPresetSettings,
+)
+def get_video_generation_preset_settings(
+ current_subject: str = Depends(get_current_subject),
+) -> VideoGenerationPresetSettings:
+ return _get_generation_preset_settings("video", VideoGenerationPresetSettings)
+
+
[email protected]("/generation-presets/video")
+def update_video_generation_preset_settings(
+ payload: VideoGenerationPresetState, current_subject: str = Depends(get_current_subject)
+) -> dict[str, bool]:
+ set_media_generation_preset_settings(
+ "video",
+ payload.model_dump(),
+ lambda stored, submitted: _preserve_recovered_defaults(
+ VideoGenerationPresetState, stored, submitted
+ ),
+ )
+ return {"saved": True}
+
+
+def _upsert_custom_generation_preset(
+ kind: Literal["image", "video"], payload: ImageGenerationPreset | VideoGenerationPreset
+) -> dict[str, bool]:
+ try:
+ schema = type(payload)
+ upsert_media_generation_preset(
+ kind,
+ payload.model_dump(),
+ lambda stored: _validated_readable_model(schema, stored) is not None,
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+ return {"saved": True}
+
+
[email protected]("/generation-presets/image/custom")
+def upsert_custom_image_generation_preset(
+ payload: ImageGenerationPreset, current_subject: str = Depends(get_current_subject)
+) -> dict[str, bool]:
+ return _upsert_custom_generation_preset("image", payload)
+
+
[email protected]("/generation-presets/video/custom")
+def upsert_custom_video_generation_preset(
+ payload: VideoGenerationPreset, current_subject: str = Depends(get_current_subject)
+) -> dict[str, bool]:
+ return _upsert_custom_generation_preset("video", payload)
+
+
[email protected]("/generation-presets/{kind}/custom")
+def delete_custom_generation_preset(
+ kind: Literal["image", "video"],
+ name: str,
+ current_subject: str = Depends(get_current_subject),
+) -> dict[str, bool]:
+ name = name.strip()
+ if not name or name == "Default" or len(name) > 80:
+ raise HTTPException(status_code = 422, detail = "Invalid preset name")
+ delete_media_generation_preset(kind, name)
+ return {"deleted": True}
+
+
class UploadLimitPayload(BaseModel):
max_upload_size_mb: int = Field(..., ge = MIN_UPLOAD_LIMIT_MB, le = MAX_UPLOAD_LIMIT_MB)
diff --git a/studio/backend/tests/test_media_generation_preset_settings.py b/studio/backend/tests/test_media_generation_preset_settings.py
new file mode 100644
index 00000000000..ca9d67cebcd
--- /dev/null
+++ b/studio/backend/tests/test_media_generation_preset_settings.py
@@ -0,0 +1,527 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+import pytest
+
+from auth.authentication import get_current_subject
+from routes import settings as settings_routes
+from storage import studio_db
+
+
+def _client(monkeypatch, stored = None) -> TestClient:
+ stored = {} if stored is None else stored
+ monkeypatch.setattr(
+ studio_db,
+ "get_app_setting",
+ lambda key, default = None: stored.get(key, default),
+ )
+ monkeypatch.setattr(studio_db, "upsert_app_settings", stored.update)
+ app = FastAPI()
+ app.include_router(settings_routes.router, prefix = "/api/settings")
+ app.dependency_overrides[get_current_subject] = lambda: "preset-test-user"
+ return TestClient(app)
+
+
+def test_image_and_video_presets_persist_independently(monkeypatch):
+ client = _client(monkeypatch)
+ image_state = {
+ "currentParams": {"negativePrompt": "blurry", "width": 1280, "steps": 24},
+ "activePreset": "Landscape",
+ }
+ image_preset = {
+ "name": "Landscape",
+ "params": image_state["currentParams"],
+ }
+ video_state = {
+ "currentParams": {"negativePrompt": "flicker", "steps": 40},
+ "activePreset": "Default",
+ }
+
+ assert client.put("/api/settings/generation-presets/image", json = image_state).status_code == 200
+ assert (
+ client.put("/api/settings/generation-presets/image/custom", json = image_preset).status_code
+ == 200
+ )
+ assert client.put("/api/settings/generation-presets/video", json = video_state).status_code == 200
+ image = client.get("/api/settings/generation-presets/image").json()
+ video = client.get("/api/settings/generation-presets/video").json()
+ assert image["saved"] is True
+ assert image["currentParams"]["steps"] == 24
+ assert image["customPresets"][0]["name"] == "Landscape"
+ assert video["saved"] is True
+ assert video["currentParams"]["steps"] == 40
+ assert video["customPresets"] == []
+
+
+def test_preset_payload_rejects_per_run_or_unknown_fields(monkeypatch):
+ client = _client(monkeypatch)
+ payload = {
+ "currentParams": {"prompt": "must not be persisted"},
+ "activePreset": "Default",
+ }
+ response = client.put("/api/settings/generation-presets/image", json = payload)
+ assert response.status_code == 422
+
+
+def test_preset_payload_bounds_names_and_values(monkeypatch):
+ client = _client(monkeypatch)
+ response = client.put(
+ "/api/settings/generation-presets/video",
+ json = {
+ "currentParams": {"durationSeconds": 0},
+ "activePreset": "Default",
+ },
+ )
+ assert response.status_code == 422
+
+
+def test_image_preset_payload_accepts_generation_control_limits(monkeypatch):
+ client = _client(monkeypatch)
+ response = client.put(
+ "/api/settings/generation-presets/image",
+ json = {
+ "currentParams": {"batchSize": 32, "runs": 129},
+ "activePreset": "Default",
+ },
+ )
+ assert response.status_code == 200
+
+
+def test_preset_negative_prompts_match_the_unbounded_generation_contract(monkeypatch):
+ client = _client(monkeypatch)
+ negative_prompt = "x" * 20_001
+ for kind in ("image", "video"):
+ response = client.put(
+ f"/api/settings/generation-presets/{kind}",
+ json = {
+ "currentParams": {"negativePrompt": negative_prompt},
+ "activePreset": "Default",
+ },
+ )
+ assert response.status_code == 200
+
+
+def test_state_writes_cannot_add_or_remove_named_presets(monkeypatch):
+ client = _client(monkeypatch)
+ params = {"steps": 9}
+ settings = {
+ "currentParams": params,
+ "activePreset": "Default",
+ }
+ preset_x = {"name": "X", "params": params}
+
+ assert client.put("/api/settings/generation-presets/image", json = settings).status_code == 200
+ assert (
+ client.put("/api/settings/generation-presets/image/custom", json = preset_x).status_code
+ == 200
+ )
+ stale_snapshot = {**settings, "customPresets": []}
+ assert (
+ client.put("/api/settings/generation-presets/image", json = stale_snapshot).status_code == 422
+ )
+ saved = client.get("/api/settings/generation-presets/image").json()
+ assert [preset["name"] for preset in saved["customPresets"]] == ["X"]
+
+
+def test_custom_preset_schema_is_selected_from_the_path_kind(monkeypatch):
+ client = _client(monkeypatch)
+ assert (
+ client.put(
+ "/api/settings/generation-presets/video/custom",
+ json = {"name": "Video", "params": {}},
+ ).status_code
+ == 200
+ )
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "Image", "params": {}},
+ ).status_code
+ == 200
+ )
+ video = client.get("/api/settings/generation-presets/video").json()
+ image = client.get("/api/settings/generation-presets/image").json()
+ assert video["customPresets"][0]["params"]["durationSeconds"] == 3
+ assert image["customPresets"][0]["params"]["batchSize"] == 1
+
+
+def test_custom_preset_names_are_canonical_and_cannot_replace_default(monkeypatch):
+ client = _client(monkeypatch)
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": " Landscape ", "params": {}},
+ ).status_code
+ == 200
+ )
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "Default", "params": {}},
+ ).status_code
+ == 422
+ )
+ saved = client.get("/api/settings/generation-presets/image").json()
+ assert [preset["name"] for preset in saved["customPresets"]] == ["Landscape"]
+
+
+def test_the_preset_list_is_capped_and_says_why(monkeypatch):
+ client = _client(monkeypatch)
+ for index in range(100):
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": f"P{index}", "params": {}},
+ ).status_code
+ == 200
+ )
+
+ refused = client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "P100", "params": {}},
+ )
+ assert refused.status_code == 409
+ assert refused.json()["detail"] == "Delete a preset before saving another one"
+
+ # Overwriting one of the existing entries is not a new entry, so it still goes through.
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "P0", "params": {"steps": 24}},
+ ).status_code
+ == 200
+ )
+
+
+def test_a_store_larger_than_the_write_cap_still_reads(monkeypatch):
+ # The cap belongs to the write path, which answers 409. Refusing to report a store that
+ # somehow holds more would turn the GET into a 500 and take the whole preset UI with it.
+ client = _client(
+ monkeypatch,
+ {
+ "image_generation_presets": {
+ "activePreset": "Default",
+ "currentParams": {"steps": 24},
+ "customPresets": [
+ {"name": f"P{index}", "params": {"steps": 20}} for index in range(101)
+ ],
+ }
+ },
+ )
+
+ body = client.get("/api/settings/generation-presets/image").json()
+
+ assert len(body["customPresets"]) == 101
+ assert body["currentParams"]["steps"] == 24
+
+
+def test_unreadable_presets_do_not_consume_the_write_cap(monkeypatch):
+ stored = {
+ "image_generation_presets": {
+ "activePreset": "Default",
+ "currentParams": {"steps": 24},
+ "customPresets": [
+ {"name": f"Unreadable {index}", "params": {"steps": 999_999}}
+ for index in range(100)
+ ],
+ }
+ }
+ client = _client(monkeypatch, stored)
+
+ response = client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "Readable", "params": {"steps": 20}},
+ )
+
+ assert response.status_code == 200
+ body = client.get("/api/settings/generation-presets/image").json()
+ assert [preset["name"] for preset in body["customPresets"]] == ["Readable"]
+ assert len(stored["image_generation_presets"]["customPresets"]) == 101
+
+
+def test_unreadable_presets_do_not_expand_the_readable_write_cap(monkeypatch):
+ stored = {
+ "image_generation_presets": {
+ "activePreset": "Default",
+ "currentParams": {"steps": 24},
+ "customPresets": [
+ {"name": f"Readable {index}", "params": {"steps": 20}} for index in range(100)
+ ]
+ + [{"name": "Unreadable", "params": {"steps": 999_999}}],
+ }
+ }
+ client = _client(monkeypatch, stored)
+
+ response = client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "One too many", "params": {"steps": 20}},
+ )
+
+ assert response.status_code == 409
+
+
+def test_a_blob_written_by_another_build_still_reads(monkeypatch):
+ # extra = "forbid" is right for a submitted payload and wrong for reading storage back: a single
+ # field from a newer build must not cost the user every recipe this build can still render.
+ client = _client(
+ monkeypatch,
+ {
+ "image_generation_presets": {
+ "activePreset": "Landscape",
+ "currentParams": {"steps": 24, "aFieldFromLater": 1},
+ "somethingElseEntirely": True,
+ "customPresets": [
+ {
+ "name": "Landscape",
+ "params": {"steps": 24, "aFieldFromLater": 1},
+ "alsoNew": "x",
+ }
+ ],
+ }
+ },
+ )
+
+ body = client.get("/api/settings/generation-presets/image").json()
+
+ assert body["saved"] is True
+ assert body["activePreset"] == "Landscape"
+ assert body["currentParams"]["steps"] == 24
+ assert [preset["name"] for preset in body["customPresets"]] == ["Landscape"]
+ assert body["customPresets"][0]["params"]["steps"] == 24
+
+
+def test_one_unreadable_preset_does_not_discard_the_rest(monkeypatch):
+ client = _client(
+ monkeypatch,
+ {
+ "image_generation_presets": {
+ "activePreset": "Broken",
+ "currentParams": {"steps": 24},
+ "customPresets": [
+ {"name": "Broken", "params": {"steps": 999_999}},
+ {"name": "Readable", "params": {"steps": 24}},
+ ],
+ }
+ },
+ )
+
+ body = client.get("/api/settings/generation-presets/image").json()
+
+ # Still "saved", so the client does not mistake this for a fresh install and overwrite it.
+ assert body["saved"] is True
+ assert [preset["name"] for preset in body["customPresets"]] == ["Readable"]
+ # The state validated on its own, so one bad entry in the list does not reset it.
+ assert body["activePreset"] == "Broken"
+ assert body["currentParams"]["steps"] == 24
+
+
+def test_a_store_holding_only_presets_is_not_a_saved_recipe(monkeypatch):
+ # A named-preset write can land while the debounced state write does not. Reporting that as
+ # saved hands the client schema defaults as if the user had chosen them, and the client stops
+ # seeding the resident model's own defaults for as long as it believes that.
+ client = _client(
+ monkeypatch,
+ {
+ "image_generation_presets": {
+ "customPresets": [{"name": "Landscape", "params": {"steps": 24}}],
+ }
+ },
+ )
+
+ body = client.get("/api/settings/generation-presets/image").json()
+
+ assert body["saved"] is False
+ # The library is still the user's; only the recipe falls back to the model's defaults.
+ assert [preset["name"] for preset in body["customPresets"]] == ["Landscape"]
+
+
+def test_a_preset_collection_that_is_not_a_list_reads_as_empty(monkeypatch):
+ # Recovery exists so a store this build cannot represent still reads. Iterating a scalar here
+ # would answer 500 and take the whole preset UI down with it.
+ client = _client(
+ monkeypatch,
+ {
+ "image_generation_presets": {
+ "activePreset": "Default",
+ "currentParams": {"steps": 24},
+ "customPresets": 42,
+ }
+ },
+ )
+
+ body = client.get("/api/settings/generation-presets/image").json()
+
+ assert body["saved"] is True
+ assert body["customPresets"] == []
+ assert body["currentParams"]["steps"] == 24
+
+
+def test_one_unreadable_state_field_does_not_reset_the_recipe(monkeypatch):
+ # The response is still "saved", so the client applies and autosaves it. Handing back schema
+ # defaults for a recipe that read fine would overwrite the stored one.
+ stored = {
+ "image_generation_presets": {
+ "activePreset": "X" * 200,
+ "currentParams": {"steps": 24, "guidance": 3.5},
+ "customPresets": [{"name": "Keep", "params": {"steps": 20}}],
+ }
+ }
+ client = _client(monkeypatch, stored)
+
+ body = client.get("/api/settings/generation-presets/image").json()
+
+ assert body["activePreset"] == "Default"
+ assert body["currentParams"]["steps"] == 24
+ assert body["currentParams"]["guidance"] == 3.5
+ assert [preset["name"] for preset in body["customPresets"]] == ["Keep"]
+
+ echoed = {"activePreset": body["activePreset"], "currentParams": body["currentParams"]}
+ assert client.put("/api/settings/generation-presets/image", json = echoed).status_code == 200
+ assert stored["image_generation_presets"]["activePreset"] == "X" * 200
+
+ echoed["activePreset"] = "Keep"
+ assert client.put("/api/settings/generation-presets/image", json = echoed).status_code == 200
+ assert stored["image_generation_presets"]["activePreset"] == "Keep"
+
+
[email protected](("kind", "recovered_guidance"), (("image", 0), ("video", 1)))
+def test_one_unreadable_nested_recipe_field_does_not_reset_its_siblings(
+ monkeypatch, kind, recovered_guidance
+):
+ stored = {
+ f"{kind}_generation_presets": {
+ "activePreset": "Keep",
+ "currentParams": {"steps": 24, "guidance": 100},
+ "customPresets": [{"name": "Keep", "params": {"steps": 24}}],
+ }
+ }
+ client = _client(monkeypatch, stored)
+
+ body = client.get(f"/api/settings/generation-presets/{kind}").json()
+
+ assert body["activePreset"] == "Keep"
+ assert body["currentParams"]["steps"] == 24
+ assert body["currentParams"]["guidance"] == recovered_guidance
+ assert [preset["name"] for preset in body["customPresets"]] == ["Keep"]
+
+ # The client echoes the recovered representation after any recipe change. Its synthesized
+ # guidance default must not replace the raw value merely because this older schema was opened.
+ body["currentParams"]["steps"] = 30
+ echoed = {"activePreset": body["activePreset"], "currentParams": body["currentParams"]}
+ assert client.put(f"/api/settings/generation-presets/{kind}", json = echoed).status_code == 200
+ kept = stored[f"{kind}_generation_presets"]["currentParams"]
+ assert kept["steps"] == 30
+ assert kept["guidance"] == 100
+
+ # An actual edit to the recovered field still replaces the unreadable value.
+ echoed["currentParams"]["guidance"] = 5
+ assert client.put(f"/api/settings/generation-presets/{kind}", json = echoed).status_code == 200
+ assert stored[f"{kind}_generation_presets"]["currentParams"]["guidance"] == 5
+
+
+def test_preset_bounds_match_the_generation_request(monkeypatch):
+ # A preset the generate endpoint would refuse is not usable: selecting it would make every
+ # following Generate fail validation.
+ client = _client(monkeypatch)
+ for params in (
+ {"steps": 500},
+ {"guidance": 100},
+ {"width": 8192},
+ {"height": 64},
+ {"width": 257},
+ {"height": 257},
+ ):
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "Out of bounds", "params": params},
+ ).status_code
+ == 422
+ ), params
+ for params in ({"steps": 100}, {"guidance": 20}, {"width": 2048}, {"height": 256}):
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image/custom",
+ json = {"name": "In bounds", "params": params},
+ ).status_code
+ == 200
+ ), params
+ assert (
+ client.put(
+ "/api/settings/generation-presets/video/custom",
+ json = {"name": "Video bounds", "params": {"steps": 500}},
+ ).status_code
+ == 422
+ )
+
+
+def test_a_downgraded_read_does_not_erase_newer_stored_fields(monkeypatch):
+ # The GET drops what this build cannot validate, so the state the client echoes back is lossy.
+ # Opening the store with an older build must not cost the newer build its fields.
+ stored = {
+ "image_generation_presets": {
+ "activePreset": "Default",
+ "currentParams": {"steps": 24, "aFieldFromLater": 7},
+ "somethingElseEntirely": {"nested": True},
+ "customPresets": [],
+ }
+ }
+ client = _client(monkeypatch, stored)
+
+ body = client.get("/api/settings/generation-presets/image").json()
+ assert "aFieldFromLater" not in body["currentParams"]
+
+ # The client autosaves the representation it was given.
+ echoed = {
+ "activePreset": body["activePreset"],
+ "currentParams": body["currentParams"],
+ }
+ assert client.put("/api/settings/generation-presets/image", json = echoed).status_code == 200
+
+ kept = stored["image_generation_presets"]
+ assert kept["currentParams"]["aFieldFromLater"] == 7
+ assert kept["somethingElseEntirely"] == {"nested": True}
+ assert kept["currentParams"]["steps"] == 24
+
+
+def test_a_store_holding_load_options_is_read_without_them_and_keeps_them(monkeypatch):
+ """Presets are a generation recipe; load options belong to the resident build.
+
+ A store written before that split still holds them, so the read must ignore them and the
+ write must not throw them away.
+ """
+ stored = {
+ "image_generation_presets": {
+ "activePreset": "Landscape",
+ "currentParams": {"steps": 24},
+ "currentLoadConfig": {"speedMode": "max"},
+ "customPresets": [
+ {
+ "name": "Landscape",
+ "params": {"steps": 24},
+ "loadConfig": {"memoryMode": "low_vram"},
+ }
+ ],
+ }
+ }
+ client = _client(monkeypatch, stored)
+
+ body = client.get("/api/settings/generation-presets/image").json()
+ assert "currentLoadConfig" not in body
+ assert "loadConfig" not in body["customPresets"][0]
+ assert body["activePreset"] == "Landscape"
+ assert body["currentParams"]["steps"] == 24
+
+ assert (
+ client.put(
+ "/api/settings/generation-presets/image",
+ json = {"activePreset": "Landscape", "currentParams": body["currentParams"]},
+ ).status_code
+ == 200
+ )
+
+ kept = stored["image_generation_presets"]
+ assert kept["currentLoadConfig"] == {"speedMode": "max"}
+ assert kept["customPresets"][0]["loadConfig"] == {"memoryMode": "low_vram"}
diff --git a/studio/backend/utils/media_generation_preset_settings.py b/studio/backend/utils/media_generation_preset_settings.py
new file mode 100644
index 00000000000..dcc3b9b37b6
--- /dev/null
+++ b/studio/backend/utils/media_generation_preset_settings.py
@@ -0,0 +1,96 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from threading import RLock
+from typing import Callable, Literal, Optional
+
+
+MediaGenerationKind = Literal["image", "video"]
+_settings_lock = RLock()
+_MAX_PRESETS = 100
+
+
+def _setting_key(kind: MediaGenerationKind) -> str:
+ return f"{kind}_generation_presets"
+
+
+def _stored_settings(kind: MediaGenerationKind) -> dict:
+ from storage.studio_db import get_app_setting
+ stored = get_app_setting(_setting_key(kind), {})
+ return dict(stored) if isinstance(stored, dict) else {}
+
+
+def _with_unknown_preserved(stored, updated):
+ """Carry forward what the writing build does not model.
+
+ A GET drops fields the reading build cannot validate, so the state it sends back is a lossy
+ view of the store. Without this, opening a store once with an older build would erase every
+ field a newer one had written. Only a background state write goes through here; replacing a
+ named preset is a deliberate whole-value overwrite by the user.
+ """
+ if not isinstance(stored, dict) or not isinstance(updated, dict):
+ return updated
+ merged = dict(updated)
+ for key, value in stored.items():
+ merged[key] = value if key not in merged else _with_unknown_preserved(value, merged[key])
+ return merged
+
+
+def _custom_presets(stored: dict) -> list:
+ presets = stored.get("customPresets", [])
+ return [item for item in presets if isinstance(item, dict)] if isinstance(presets, list) else []
+
+
+def get_media_generation_preset_settings(kind: MediaGenerationKind) -> dict:
+ with _settings_lock:
+ return _stored_settings(kind)
+
+
+def set_media_generation_preset_settings(
+ kind: MediaGenerationKind,
+ settings: dict,
+ preserve_recovered: Optional[Callable[[dict, dict], dict]] = None,
+) -> None:
+ """Write the page's current recipe and selection, never the named presets.
+
+ Those have their own endpoints so a debounced state write can never race a save or a delete
+ into clobbering the list.
+ """
+ from storage.studio_db import upsert_app_settings
+ with _settings_lock:
+ stored = _stored_settings(kind)
+ submitted = {**settings, "customPresets": stored.get("customPresets", [])}
+ if preserve_recovered is not None:
+ submitted = preserve_recovered(stored, submitted)
+ updated = _with_unknown_preserved(
+ stored,
+ submitted,
+ )
+ upsert_app_settings({_setting_key(kind): updated})
+
+
+def upsert_media_generation_preset(
+ kind: MediaGenerationKind, preset: dict, is_readable: Callable[[dict], bool]
+) -> None:
+ from storage.studio_db import upsert_app_settings
+ with _settings_lock:
+ stored = _stored_settings(kind)
+ presets = _custom_presets(stored)
+ readable = [item for item in presets if is_readable(item)]
+ replacing = any(item.get("name") == preset["name"] for item in readable)
+ if not replacing and len(readable) >= _MAX_PRESETS:
+ raise ValueError("Delete a preset before saving another one")
+ stored["customPresets"] = [
+ item for item in presets if item.get("name") != preset["name"]
+ ] + [preset]
+ upsert_app_settings({_setting_key(kind): stored})
+
+
+def delete_media_generation_preset(kind: MediaGenerationKind, name: str) -> None:
+ from storage.studio_db import upsert_app_settings
+ with _settings_lock:
+ stored = _stored_settings(kind)
+ stored["customPresets"] = [
+ item for item in _custom_presets(stored) if item.get("name") != name
+ ]
+ upsert_app_settings({_setting_key(kind): stored})
diff --git a/studio/frontend/src/components/negative-prompt-field.tsx b/studio/frontend/src/components/negative-prompt-field.tsx
index d2682122a8e..a4e29d9a4b0 100644
--- a/studio/frontend/src/components/negative-prompt-field.tsx
+++ b/studio/frontend/src/components/negative-prompt-field.tsx
@@ -8,6 +8,10 @@ import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
/** Collapsible negative prompt, shared by the Images and Video Create panels. */
+// Keep normal input below the unload request budget. Restored legacy recipes may be longer, and
+// the preset API accepts them because the generation contract does too.
+export const NEGATIVE_PROMPT_MAX_LENGTH = 20_000;
+
export function NegativePromptField({
value,
onChange,
@@ -54,6 +58,7 @@ export function NegativePromptField({
{open && (
<Textarea
rows={2}
+ maxLength={NEGATIVE_PROMPT_MAX_LENGTH}
placeholder="What to avoid (optional)"
value={value}
onChange={(e) => onChange(e.target.value)}
diff --git a/studio/frontend/src/features/generation-presets/api.ts b/studio/frontend/src/features/generation-presets/api.ts
new file mode 100644
index 00000000000..4e4525105bb
--- /dev/null
+++ b/studio/frontend/src/features/generation-presets/api.ts
@@ -0,0 +1,77 @@
+// 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 { authFetch } from "@/features/auth";
+import type {
+ MediaGenerationKind,
+ MediaGenerationPreset,
+ MediaGenerationPresetSettings,
+ MediaGenerationPresetState,
+} from "./types";
+
+/** A refusal the server explained in words, so the caller can show it instead of a generic toast. */
+export class PresetWriteRefused extends Error {}
+
+async function parseResponse<Result>(response: Response) {
+ const body = await response.json().catch(() => null);
+ if (!response.ok) {
+ const detail =
+ body && typeof body === "object" && "detail" in body ? body.detail : null;
+ if (typeof detail === "string" && detail) {
+ throw new PresetWriteRefused(detail);
+ }
+ throw new Error(
+ detail ? JSON.stringify(detail) : `Request failed (${response.status})`,
+ );
+ }
+ return body as Result;
+}
+
+export async function getMediaGenerationPresetSettings<Params>(
+ kind: MediaGenerationKind,
+) {
+ return parseResponse<MediaGenerationPresetSettings<Params>>(
+ await authFetch(`/api/settings/generation-presets/${kind}`),
+ );
+}
+
+export async function saveMediaGenerationPresetSettings<Params>(
+ kind: MediaGenerationKind,
+ settings: MediaGenerationPresetState<Params>,
+ keepalive = false,
+) {
+ return parseResponse<{ saved: boolean }>(
+ await authFetch(`/api/settings/generation-presets/${kind}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(settings),
+ keepalive,
+ }),
+ );
+}
+
+export async function upsertMediaGenerationPreset<Params>(
+ kind: MediaGenerationKind,
+ preset: MediaGenerationPreset<Params>,
+) {
+ return parseResponse<{ saved: boolean }>(
+ await authFetch(`/api/settings/generation-presets/${kind}/custom`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(preset),
+ }),
+ );
+}
+
+export async function deleteMediaGenerationPreset(
+ kind: MediaGenerationKind,
+ name: string,
+) {
+ const query = new URLSearchParams({ name });
+ return parseResponse<{ deleted: boolean }>(
+ await authFetch(
+ `/api/settings/generation-presets/${kind}/custom?${query}`,
+ { method: "DELETE", keepalive: true },
+ ),
+ );
+}
diff --git a/studio/frontend/src/features/generation-presets/index.ts b/studio/frontend/src/features/generation-presets/index.ts
new file mode 100644
index 00000000000..e94866222f8
--- /dev/null
+++ b/studio/frontend/src/features/generation-presets/index.ts
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export { MediaGenerationPresetControl } from "./media-generation-preset-control";
+export { useMediaGenerationPresets } from "./use-media-generation-presets";
+export {
+ closestDurationIndex,
+ closestResolutionIndex,
+ shouldApplyModelDefaults,
+} from "./preset-policy";
+export type {
+ ImageGenerationPresetParams,
+ VideoGenerationPresetParams,
+} from "./types";
diff --git a/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
new file mode 100644
index 00000000000..f9edd30c8b1
--- /dev/null
+++ b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
@@ -0,0 +1,230 @@
+// 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 { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { cn } from "@/lib/utils";
+import { Bookmark, Check, ChevronDown, Trash2 } from "lucide-react";
+import { Fragment, useState } from "react";
+import { DEFAULT_PRESET_NAME } from "./preset-policy";
+
+interface MediaGenerationPresetControlProps {
+ kind: "image" | "video";
+ presets: readonly { name: string }[];
+ activePreset: string;
+ ready: boolean;
+ hasUnsavedChanges: boolean;
+ onSelect: (name: string) => void;
+ onSave: (name: string) => Promise<string | null>;
+ onDelete: () => Promise<boolean>;
+}
+
+export function MediaGenerationPresetControl({
+ kind,
+ presets,
+ activePreset,
+ ready,
+ hasUnsavedChanges,
+ onSelect,
+ onSave,
+ onDelete,
+}: MediaGenerationPresetControlProps) {
+ const [open, setOpen] = useState(false);
+ const [draftName, setDraftName] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const name = draftName ?? activePreset;
+ const trimmed = name.trim();
+ const matching = presets.find((preset) => preset.name === trimmed);
+ const activeIsCustom =
+ activePreset !== DEFAULT_PRESET_NAME &&
+ presets.some((preset) => preset.name === activePreset);
+ const canSave =
+ ready &&
+ !saving &&
+ trimmed.length > 0 &&
+ (trimmed !== activePreset ||
+ hasUnsavedChanges ||
+ !matching ||
+ trimmed === DEFAULT_PRESET_NAME);
+ let saveLabel = "Saved";
+ if (trimmed === DEFAULT_PRESET_NAME) {
+ saveLabel = "Save copy";
+ } else if (!matching) {
+ saveLabel = "Save";
+ } else if (matching.name !== activePreset) {
+ saveLabel = "Overwrite";
+ } else if (hasUnsavedChanges) {
+ saveLabel = "Update";
+ }
+ const changeOpen = (nextOpen: boolean) => {
+ setOpen(nextOpen);
+ if (!nextOpen) setDraftName(null);
+ };
+
+ const save = async () => {
+ setSaving(true);
+ try {
+ const saved = await onSave(name);
+ if (saved) {
+ changeOpen(false);
+ }
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const remove = async () => {
+ setSaving(true);
+ try {
+ if (await onDelete()) {
+ changeOpen(false);
+ }
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Popover open={open} onOpenChange={changeOpen}>
+ <PopoverTrigger asChild={true}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!ready || saving}
+ aria-label={`Manage ${kind} generation presets`}
+ className={cn(
+ "relative size-8 shrink-0 gap-1.5 rounded-full border-border/60 bg-background/70 p-0 text-xs font-medium shadow-none backdrop-blur-sm hover:bg-muted/70 sm:h-8 sm:w-auto sm:max-w-40 sm:px-2.5",
+ open && "border-border bg-muted/70",
+ )}
+ data-testid={`${kind}-generation-presets`}
+ >
+ <Bookmark className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="hidden min-w-0 truncate sm:block">
+ {activePreset}
+ </span>
+ {hasUnsavedChanges ? (
+ <span
+ className="absolute right-1 top-1 size-1.5 shrink-0 rounded-full bg-amber-500 ring-2 ring-background sm:static sm:ring-0"
+ aria-label="Modified"
+ />
+ ) : null}
+ <ChevronDown
+ className={cn(
+ "hidden size-3.5 shrink-0 text-muted-foreground transition-transform sm:block",
+ open && "rotate-180",
+ )}
+ />
+ </Button>
+ </PopoverTrigger>
+
+ <PopoverContent
+ align="end"
+ sideOffset={8}
+ collisionPadding={12}
+ className="max-h-[var(--radix-popover-content-available-height)] w-[min(320px,calc(100vw-24px))] gap-0 overflow-x-hidden overflow-y-auto overscroll-contain rounded-xl border-border/70 p-0 shadow-xl"
+ >
+ <div className="shrink-0 border-b border-border/60 px-4 py-3.5">
+ <div className="flex items-center justify-between gap-3">
+ <p className="font-heading text-sm font-medium">
+ Generation presets
+ </p>
+ {hasUnsavedChanges ? (
+ <span className="rounded-full bg-amber-500/10 px-2 py-0.5 text-ui-10 font-medium text-amber-700 dark:text-amber-300">
+ Modified
+ </span>
+ ) : null}
+ </div>
+ </div>
+
+ <div className="max-h-48 shrink-0 overflow-y-auto p-2">
+ {presets.map((preset, index) => {
+ const isActive = preset.name === activePreset;
+
+ return (
+ <Fragment key={preset.name}>
+ {index === 1 ? (
+ <div className="mx-2 my-1 h-px bg-border/60" />
+ ) : null}
+ <button
+ type="button"
+ disabled={saving}
+ onClick={() => {
+ onSelect(preset.name);
+ changeOpen(false);
+ }}
+ className={cn(
+ "flex h-9 w-full items-center gap-2 rounded-lg px-2.5 text-left text-xs transition-colors hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ isActive && "bg-muted font-medium",
+ )}
+ >
+ <span className="min-w-0 flex-1 truncate">{preset.name}</span>
+ {preset.name === DEFAULT_PRESET_NAME ? (
+ <span className="text-ui-10 font-normal text-muted-foreground">
+ Built-in
+ </span>
+ ) : null}
+ {isActive ? (
+ <Check className="size-3.5 shrink-0 text-primary" />
+ ) : null}
+ </button>
+ </Fragment>
+ );
+ })}
+ </div>
+
+ <div className="shrink-0 border-t border-border/60 bg-muted/20 p-3">
+ <label
+ htmlFor={`${kind}-generation-preset-name`}
+ className="mb-2 block text-xs font-medium"
+ >
+ Save current settings
+ </label>
+ <div className="flex gap-2">
+ <Input
+ id={`${kind}-generation-preset-name`}
+ value={name}
+ disabled={saving}
+ onChange={(event) => setDraftName(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && canSave) {
+ event.preventDefault();
+ save().catch(() => undefined);
+ }
+ }}
+ placeholder="Preset name"
+ maxLength={80}
+ autoComplete="off"
+ className="h-9 min-w-0 rounded-lg bg-background"
+ />
+ <Button
+ type="button"
+ size="sm"
+ disabled={!canSave}
+ onClick={() => save().catch(() => undefined)}
+ className="h-9 shrink-0 rounded-lg px-3"
+ >
+ {saveLabel}
+ </Button>
+ </div>
+ {activeIsCustom ? (
+ <button
+ type="button"
+ disabled={saving}
+ onClick={() => remove().catch(() => undefined)}
+ className="mt-3 flex h-8 w-full items-center justify-center gap-1.5 rounded-lg text-xs text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <Trash2 className="size-3.5" />
+ Delete preset
+ </button>
+ ) : null}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/studio/frontend/src/features/generation-presets/preset-policy.ts b/studio/frontend/src/features/generation-presets/preset-policy.ts
new file mode 100644
index 00000000000..8c304e00a2a
--- /dev/null
+++ b/studio/frontend/src/features/generation-presets/preset-policy.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const DEFAULT_PRESET_NAME = "Default";
+
+export function configKey(value: unknown): string {
+ return JSON.stringify(value ?? null);
+}
+
+export function getBuiltinVariantName(usedNames: Set<string>): string {
+ let suffix = 1;
+ let candidate = `${DEFAULT_PRESET_NAME} ${suffix}`;
+ while (usedNames.has(candidate)) {
+ suffix += 1;
+ candidate = `${DEFAULT_PRESET_NAME} ${suffix}`;
+ }
+ return candidate;
+}
+
+export function closestResolutionIndex(
+ presets: [number, number][],
+ targetWidth: number,
+ targetHeight: number,
+): number {
+ if (presets.length === 0) {
+ return 0;
+ }
+ const targetAspect = targetWidth / targetHeight;
+ const targetArea = targetWidth * targetHeight;
+ let bestIndex = 0;
+ let bestScore = Number.POSITIVE_INFINITY;
+ presets.forEach(([width, height], index) => {
+ const aspectDistance = Math.abs(Math.log(width / height / targetAspect));
+ const areaDistance = Math.abs(Math.log((width * height) / targetArea));
+ const score = aspectDistance * 4 + areaDistance;
+ if (score < bestScore) {
+ bestScore = score;
+ bestIndex = index;
+ }
+ });
+ return bestIndex;
+}
+
+export function closestDurationIndex(
+ durations: Array<{ seconds: number }>,
+ targetSeconds: number,
+): number {
+ if (durations.length === 0) {
+ return 0;
+ }
+ let bestIndex = 0;
+ let bestDistance = Number.POSITIVE_INFINITY;
+ durations.forEach(({ seconds }, index) => {
+ const distance = Math.abs(seconds - targetSeconds);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestIndex = index;
+ }
+ });
+ return bestIndex;
+}
+
+/**
+ * A stored recipe owns the first status seed. Later model changes apply their own defaults, unless
+ * the user claimed the form after the pick that is being confirmed: their choice is the newer one.
+ */
+export function shouldApplyModelDefaults(
+ alreadySeeded: boolean,
+ storedRecipe: boolean,
+ supersededByUser = false,
+): boolean {
+ return !supersededByUser && (alreadySeeded || !storedRecipe);
+}
diff --git a/studio/frontend/src/features/generation-presets/types.ts b/studio/frontend/src/features/generation-presets/types.ts
new file mode 100644
index 00000000000..857faa48cea
--- /dev/null
+++ b/studio/frontend/src/features/generation-presets/types.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type MediaGenerationKind = "image" | "video";
+
+// A preset is a generation recipe and nothing else. Model-load options are deliberately absent:
+// they apply only on a reload, follow the hardware and checkpoint rather than the recipe, and the
+// resident build already owns them (see features/resident-load).
+export interface MediaGenerationPreset<Params> {
+ name: string;
+ params: Params;
+}
+
+export interface MediaGenerationPresetState<Params> {
+ currentParams: Params;
+ activePreset: string;
+}
+
+export interface MediaGenerationPresetSettings<Params>
+ extends MediaGenerationPresetState<Params> {
+ customPresets: MediaGenerationPreset<Params>[];
+ saved?: boolean;
+}
+
+export interface ImageGenerationPresetParams {
+ negativePrompt: string;
+ width: number;
+ height: number;
+ steps: number;
+ guidance: number;
+ batchSize: number;
+ runs: number;
+}
+
+export interface VideoGenerationPresetParams {
+ negativePrompt: string;
+ width: number;
+ height: number;
+ durationSeconds: number;
+ steps: number;
+ guidance: number;
+ flowShift: number | null;
+ audioFlowShift: number | null;
+}
diff --git a/studio/frontend/src/features/generation-presets/use-media-generation-presets.ts b/studio/frontend/src/features/generation-presets/use-media-generation-presets.ts
new file mode 100644
index 00000000000..dd2adeb6c66
--- /dev/null
+++ b/studio/frontend/src/features/generation-presets/use-media-generation-presets.ts
@@ -0,0 +1,457 @@
+// 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 { toast } from "@/lib/toast";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import {
+ PresetWriteRefused,
+ deleteMediaGenerationPreset,
+ getMediaGenerationPresetSettings,
+ saveMediaGenerationPresetSettings,
+ upsertMediaGenerationPreset,
+} from "./api";
+import {
+ DEFAULT_PRESET_NAME,
+ configKey,
+ getBuiltinVariantName,
+} from "./preset-policy";
+import type {
+ MediaGenerationKind,
+ MediaGenerationPreset,
+ MediaGenerationPresetSettings,
+ MediaGenerationPresetState,
+} from "./types";
+
+function refusalMessage(error: unknown, fallback: string) {
+ return error instanceof PresetWriteRefused ? error.message : fallback;
+}
+
+function claimForm(claim: { current: number }) {
+ claim.current += 1;
+ return claim.current;
+}
+
+export interface MediaGenerationPresetsOptions<Params extends object> {
+ kind: MediaGenerationKind;
+ defaultParams: Params;
+ currentParams: Params;
+ applyParams: (params: Params) => Params;
+ normalizeParams?: (params: Params) => unknown;
+}
+
+export function useMediaGenerationPresets<Params extends object>({
+ kind,
+ defaultParams,
+ currentParams,
+ applyParams,
+ normalizeParams,
+}: MediaGenerationPresetsOptions<Params>) {
+ const paramsKey = useCallback(
+ (params: Params) =>
+ configKey(normalizeParams ? normalizeParams(params) : params),
+ [normalizeParams],
+ );
+ const [customPresets, setCustomPresets] = useState<
+ MediaGenerationPreset<Params>[]
+ >([]);
+ const [activePreset, setActivePreset] = useState(DEFAULT_PRESET_NAME);
+ const [hydrationSource, setHydrationSource] = useState<
+ "pending" | "fresh" | "saved" | "claiming" | "claimed" | "unreadable"
+ >("pending");
+ // Settled, not readable: an unreadable store still answers "stored settings do not own the form",
+ // which is what the load-state controls wait for. Only the preset UI itself needs a readable store.
+ const hydrated = hydrationSource !== "pending";
+ // Whether the store supplied the recipe. Model defaults must not seed over it. This is the
+ // opposite of the rule for load options, which the resident build owns (features/resident-load).
+ const storedRecipe = hydrationSource === "saved";
+ const presetsReady =
+ hydrationSource === "fresh" ||
+ hydrationSource === "saved" ||
+ hydrationSource === "claimed";
+ const currentParamsRef = useRef(currentParams);
+ const latestSettingsRef = useRef<MediaGenerationPresetState<Params> | null>(
+ null,
+ );
+ const deferredSavedSettingsRef =
+ useRef<MediaGenerationPresetSettings<Params> | null>(null);
+ const deferredFreshSettingsRef = useRef(false);
+ const inflightWriteRef = useRef<Promise<unknown>>(Promise.resolve());
+ const baselineParamsRef = useRef(defaultParams);
+ const activePresetRef = useRef(activePreset);
+ // Bumped by every action that takes over the form, so a write that resolves late can still
+ // update the list without moving a selection the user made while it was in flight.
+ const formClaim = useRef(0);
+ const committedRecipeClaim = useRef(0);
+ const defaultParamsRef = useRef(defaultParams);
+ const applyParamsRef = useRef(applyParams);
+ const paramsKeyRef = useRef(paramsKey);
+ useLayoutEffect(() => {
+ currentParamsRef.current = currentParams;
+ activePresetRef.current = activePreset;
+ applyParamsRef.current = applyParams;
+ defaultParamsRef.current = defaultParams;
+ paramsKeyRef.current = paramsKey;
+ }, [
+ activePreset,
+ applyParams,
+ currentParams,
+ defaultParams,
+ hydrated,
+ paramsKey,
+ ]);
+
+ const presets = useMemo(
+ () => [
+ { name: DEFAULT_PRESET_NAME, params: defaultParams },
+ ...customPresets,
+ ],
+ [customPresets, defaultParams],
+ );
+
+ // `custom` for a store that holds named presets but no recipe of its own: the library is still
+ // the user's, and only the recipe falls back to the model's defaults.
+ const hydrateLocalSettings = useCallback(
+ (
+ source: "fresh" | "unreadable",
+ custom: MediaGenerationPreset<Params>[] = [],
+ ) => {
+ deferredSavedSettingsRef.current = null;
+ deferredFreshSettingsRef.current = false;
+ baselineParamsRef.current = defaultParamsRef.current;
+ setCustomPresets(custom);
+ setActivePreset(DEFAULT_PRESET_NAME);
+ if (source === "fresh" && formClaim.current !== 0) {
+ const committed = committedRecipeClaim.current === formClaim.current;
+ deferredFreshSettingsRef.current = !committed;
+ setHydrationSource(committed ? "claimed" : "claiming");
+ return;
+ }
+ setHydrationSource(source);
+ },
+ [],
+ );
+
+ const hydrateSavedSettings = useCallback(
+ (settings: MediaGenerationPresetSettings<Params>) => {
+ const custom = settings.customPresets ?? [];
+ deferredFreshSettingsRef.current = false;
+ setCustomPresets(custom);
+ // A model pick made while the request was in flight is newer than storage. Keep its form
+ // values, but still hydrate the named presets so the user's library remains available.
+ if (formClaim.current !== 0) {
+ const committed = committedRecipeClaim.current === formClaim.current;
+ deferredSavedSettingsRef.current = committed ? null : settings;
+ setHydrationSource(committed ? "claimed" : "claiming");
+ return;
+ }
+ deferredSavedSettingsRef.current = null;
+ const available = new Set([
+ DEFAULT_PRESET_NAME,
+ ...custom.map((preset) => preset.name),
+ ]);
+ const selected = available.has(settings.activePreset)
+ ? settings.activePreset
+ : DEFAULT_PRESET_NAME;
+ // The baseline owns model defaults applied before hydration; the resident prop can be stale.
+ const currentDefaultParams = baselineParamsRef.current;
+ const definition = custom.find((preset) => preset.name === selected) ?? {
+ name: DEFAULT_PRESET_NAME,
+ params: currentDefaultParams,
+ };
+ baselineParamsRef.current = definition.params;
+ setActivePreset(definition.name);
+ // Unconditional: comparing against the mount-time value cannot tell a user edit from a
+ // model-driven one, and guessing wrong autosaved a resident model's defaults over the
+ // stored recipe. Ordering settles it -- the store answers, then defaults fill the rest.
+ applyParamsRef.current(settings.currentParams);
+ setHydrationSource("saved");
+ },
+ [],
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ getMediaGenerationPresetSettings<Params>(kind)
+ .then((settings) => {
+ if (cancelled) {
+ return;
+ }
+ if (!settings.saved) {
+ hydrateLocalSettings("fresh", settings.customPresets ?? []);
+ return;
+ }
+ hydrateSavedSettings(settings);
+ })
+ .catch(() => {
+ if (cancelled) {
+ return;
+ }
+ // Only the read failed. Settle on local defaults so the controls waiting on hydration
+ // still work, but never write back over a store this session could not read.
+ hydrateLocalSettings("unreadable");
+ toast.error(`Could not load ${kind} presets`);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [hydrateLocalSettings, hydrateSavedSettings, kind]);
+
+ // Explicit model picks own the form over a settings request that was already in flight. A load
+ // that fails gives that ownership back, provided no newer form action superseded the pick.
+ const claimRecipe = useCallback(() => {
+ const previousClaim = formClaim.current;
+ const previousCommittedClaim = committedRecipeClaim.current;
+ const claim = claimForm(formClaim);
+ let settled = false;
+ const ownsClaim = () => !settled && formClaim.current === claim;
+ return {
+ commit: () => {
+ if (!ownsClaim()) {
+ return;
+ }
+ settled = true;
+ committedRecipeClaim.current = claim;
+ deferredSavedSettingsRef.current = null;
+ deferredFreshSettingsRef.current = false;
+ setHydrationSource((source) =>
+ source === "claiming" ? "claimed" : source,
+ );
+ },
+ release: () => {
+ if (!ownsClaim()) {
+ return;
+ }
+ settled = true;
+ committedRecipeClaim.current = previousCommittedClaim;
+ formClaim.current = previousClaim;
+ if (previousClaim !== 0 && previousCommittedClaim === previousClaim) {
+ deferredSavedSettingsRef.current = null;
+ deferredFreshSettingsRef.current = false;
+ setHydrationSource((source) =>
+ source === "claiming" ? "claimed" : source,
+ );
+ return;
+ }
+ if (previousClaim !== 0 || !deferredSavedSettingsRef.current) {
+ if (previousClaim === 0 && deferredFreshSettingsRef.current) {
+ deferredFreshSettingsRef.current = false;
+ setHydrationSource("fresh");
+ }
+ return;
+ }
+ const deferred = deferredSavedSettingsRef.current;
+ deferredSavedSettingsRef.current = null;
+ hydrateSavedSettings(deferred);
+ },
+ };
+ }, [hydrateSavedSettings]);
+
+ // How many actions have taken the form so far. A pick records it and compares later: a different
+ // value means something newer owns the form, so the pick's defaults must not land on top of it
+ // and its rollback is not the one to restore. Read per pick, so each baselines on itself.
+ const formClaimId = useCallback(() => formClaim.current, []);
+
+ const settings = useMemo<MediaGenerationPresetState<Params>>(
+ () => ({
+ currentParams,
+ activePreset,
+ }),
+ [activePreset, currentParams],
+ );
+ useLayoutEffect(() => {
+ latestSettingsRef.current = settings;
+ }, [settings]);
+
+ // One state write at a time. Two in flight and the store keeps whichever the backend saw LAST,
+ // so an older snapshot could win and the newest recipe come back changed on the next read.
+ // Same chain the chat settings path keeps, for the same reason.
+ const queueWrite = useCallback((write: () => Promise<unknown>) => {
+ inflightWriteRef.current = inflightWriteRef.current
+ .catch(() => undefined)
+ .then(write);
+ }, []);
+
+ useEffect(() => {
+ if (!presetsReady) {
+ return;
+ }
+ const timer = window.setTimeout(() => {
+ queueWrite(() =>
+ saveMediaGenerationPresetSettings(kind, settings).catch(() => {
+ toast.error(`Could not save ${kind} presets`);
+ }),
+ );
+ }, 400);
+ return () => window.clearTimeout(timer);
+ }, [kind, presetsReady, queueWrite, settings]);
+
+ useEffect(() => {
+ if (!presetsReady) {
+ return;
+ }
+ const flush = () => {
+ const latest = latestSettingsRef.current;
+ if (latest) {
+ queueWrite(() =>
+ saveMediaGenerationPresetSettings(kind, latest, true).catch(
+ () => undefined,
+ ),
+ );
+ }
+ };
+ window.addEventListener("beforeunload", flush);
+ return () => {
+ window.removeEventListener("beforeunload", flush);
+ flush();
+ };
+ }, [kind, presetsReady, queueWrite]);
+
+ const selectPreset = useCallback(
+ (name: string) => {
+ if (!presetsReady) {
+ return;
+ }
+ const preset =
+ name === DEFAULT_PRESET_NAME
+ ? { name, params: defaultParamsRef.current }
+ : customPresets.find((candidate) => candidate.name === name);
+ if (!preset) {
+ return;
+ }
+ claimForm(formClaim);
+ baselineParamsRef.current = applyParamsRef.current(preset.params);
+ setActivePreset(preset.name);
+ },
+ [customPresets, presetsReady],
+ );
+
+ const savePreset = useCallback(
+ async (rawName: string): Promise<string | null> => {
+ if (!presetsReady) {
+ return null;
+ }
+ const trimmed = rawName.trim();
+ if (!trimmed) {
+ toast.error("Enter a preset name");
+ return null;
+ }
+ const usedNames = new Set([
+ DEFAULT_PRESET_NAME,
+ ...customPresets.map((preset) => preset.name),
+ ]);
+ const name =
+ trimmed === DEFAULT_PRESET_NAME
+ ? getBuiltinVariantName(usedNames)
+ : trimmed;
+ const overwriting = customPresets.some((preset) => preset.name === name);
+ if (!overwriting && customPresets.length >= 100) {
+ toast.error("Delete a preset before saving another one");
+ return null;
+ }
+ const preset: MediaGenerationPreset<Params> = {
+ name,
+ params: currentParamsRef.current,
+ };
+ const previousClaim = formClaim.current;
+ const claim = claimForm(formClaim);
+ try {
+ await upsertMediaGenerationPreset(kind, preset);
+ } catch (error) {
+ // A refused write took nothing over, so it must not keep the claim it made: a pending
+ // model pick would go on reading the form as claimed by something newer than itself.
+ if (formClaim.current === claim) formClaim.current = previousClaim;
+ toast.error(refusalMessage(error, `Could not save ${kind} preset`));
+ return null;
+ }
+ setCustomPresets((current) => [
+ ...current.filter((candidate) => candidate.name !== name),
+ preset,
+ ]);
+ if (formClaim.current !== claim) {
+ return name;
+ }
+ baselineParamsRef.current = preset.params;
+ setActivePreset(name);
+ return name;
+ },
+ [customPresets, kind, presetsReady],
+ );
+
+ // A delete always leaves Default selected: the preset is gone whoever owns the form, and naming
+ // it would point the control at a definition that no longer exists. The form VALUES follow only
+ // when this delete still owns the form; an edit made while the request was in flight owns it.
+ const restoreDefaultAfterDelete = useCallback(
+ (paramsBeforeDelete: Params, ownsForm: boolean) => {
+ const formUnchanged =
+ ownsForm &&
+ paramsKeyRef.current(currentParamsRef.current) ===
+ paramsKeyRef.current(paramsBeforeDelete);
+ baselineParamsRef.current = formUnchanged
+ ? applyParamsRef.current(defaultParamsRef.current)
+ : defaultParamsRef.current;
+ setActivePreset(DEFAULT_PRESET_NAME);
+ },
+ [],
+ );
+
+ const deletePreset = useCallback(async (): Promise<boolean> => {
+ if (!presetsReady || activePreset === DEFAULT_PRESET_NAME) {
+ return false;
+ }
+ if (!customPresets.some((preset) => preset.name === activePreset)) {
+ return false;
+ }
+ const deletedName = activePreset;
+ const paramsBeforeDelete = currentParamsRef.current;
+ const previousClaim = formClaim.current;
+ const claim = claimForm(formClaim);
+ try {
+ await deleteMediaGenerationPreset(kind, deletedName);
+ } catch (error) {
+ // Same as a refused save: a delete that did not happen has not taken the form.
+ if (formClaim.current === claim) formClaim.current = previousClaim;
+ toast.error(refusalMessage(error, `Could not delete ${kind} preset`));
+ return false;
+ }
+ setCustomPresets((current) =>
+ current.filter((preset) => preset.name !== deletedName),
+ );
+ restoreDefaultAfterDelete(paramsBeforeDelete, formClaim.current === claim);
+ return true;
+ }, [
+ activePreset,
+ customPresets,
+ kind,
+ presetsReady,
+ restoreDefaultAfterDelete,
+ ]);
+
+ const activeDefinition =
+ activePreset === DEFAULT_PRESET_NAME
+ ? { name: DEFAULT_PRESET_NAME, params: defaultParams }
+ : customPresets.find((preset) => preset.name === activePreset);
+ const hasUnsavedChanges = activeDefinition
+ ? paramsKey(currentParams) !== paramsKey(activeDefinition.params)
+ : false;
+
+ return {
+ activePreset,
+ presets,
+ hydrated,
+ storedRecipe,
+ presetsReady,
+ claimRecipe,
+ formClaimId,
+ hasUnsavedChanges,
+ selectPreset,
+ savePreset,
+ deletePreset,
+ };
+}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 1dd6ab67954..4419486877a 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -88,6 +88,11 @@ import { useImageWorkflowStore } from "./stores/image-workflow-store";
import { WORKFLOW_TABS } from "./workflows";
import { ParamSlider } from "@/features/chat";
import { ModelLoadDescription } from "@/features/chat/components/model-load-status";
+import {
+ type ImageGenerationPresetParams,
+ MediaGenerationPresetControl,
+ useMediaGenerationPresets,
+} from "@/features/generation-presets";
import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";
import { formatBytes, formatEta } from "@/features/hub/lib/format";
import { ChevronDown } from "lucide-react";
@@ -1130,7 +1135,16 @@ type Busy = "loading" | "unloading" | "generating" | null;
// What a pick optimistically replaced, so a load that never takes can put all of it back. The quant
// label and the generation recipe move together at pick time, so they have to roll back together too.
-type PickRevert = { prev: string | null; steps: number; guidance: number };
+type PickRevert = {
+ prev: string | null;
+ steps: number;
+ guidance: number;
+ commitRecipeClaim?: () => void;
+ releaseRecipeClaim?: () => void;
+ // What the pick applied. A field the user changed after that is theirs, not ours to put back.
+ appliedSteps?: number;
+ appliedGuidance?: number;
+};
// The Advanced controls a load sends, with "auto" sentinels resolved to omitted. A staged download pins one at pick time.
type LoadAdvanced = Pick<
@@ -1167,12 +1181,30 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// Z-Image-Turbo official defaults: 9 steps (= 8 DiT forwards), guidance 0 (distilled, CFG-free).
const [steps, setSteps] = useState(DEFAULT_GEN.steps);
const [guidance, setGuidance] = useState(DEFAULT_GEN.guidance);
+ // Whether the user has taken the recipe since the pick that is still waiting for its status: a
+ // preset selected while the model downloaded is newer than that pick, so its rollback is not the
+ // one to restore.
+ const pickRecipeSuperseded = useRef<(() => boolean) | null>(null);
// Put back everything a pick optimistically applied. Setters are stable, so this never re-renders on its own.
const revertPick = useCallback((r: PickRevert) => {
setQuant(r.prev);
- setSteps(r.steps);
- setGuidance(r.guidance);
+ setPendingModelDefaults(null);
+ // Equality alone cannot tell "nobody touched this" from "the user chose the same number": a
+ // preset selected after the pick owns these fields even where it matches what the pick applied.
+ if (!pickRecipeSuperseded.current?.()) {
+ setSteps((cur) => (cur === r.appliedSteps ? r.steps : cur));
+ setGuidance((cur) => (cur === r.appliedGuidance ? r.guidance : cur));
+ }
+ pickRecipeSuperseded.current = null;
+ r.releaseRecipeClaim?.();
+ r.releaseRecipeClaim = undefined;
}, []);
+ // The recipe a pick optimistically claimed, until status confirms it or a failed load reverts
+ // it. Without this the Default preset would read as "modified" for the whole download.
+ const [pendingModelDefaults, setPendingModelDefaults] = useState<{
+ steps: number;
+ guidance: number;
+ } | null>(null);
const [seed, setSeed] = useState("");
// Batch size = images per forward pass (VRAM-heavy); count = sequential loops.
const [batchSize, setBatchSize] = useState(1);
@@ -1242,8 +1274,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const lastLoad = useRef<{ repoId: string; kind: "gguf" | "single_file" | "pipeline"; filename?: string } | null>(
null,
);
- // Render-safe mirror of "lastLoad.current was set by a user-initiated load": a resident GGUF discovered by refresh carries
- // no filename, so lastLoad stays null and Reapply would be dead. Set only from handlers; the resident case derives from status.
+ // Render-safe mirror of whether a page-initiated load supplied a complete Reapply target.
const [canReapply, setCanReapply] = useState(false);
// Repo id whose defaults were already seeded from a discovered resident model, so we seed once and never clobber a manual edit.
const seededResident = useRef<string | null>(null);
@@ -1320,6 +1351,80 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// one. Lazy state, not a ref: a ref cannot be written during render.
const [pickGuard] = useState(createPickGuard);
+ const imagePresetParams = useMemo<ImageGenerationPresetParams>(
+ () => ({
+ negativePrompt,
+ width,
+ height,
+ steps,
+ guidance,
+ batchSize,
+ runs: count,
+ }),
+ [batchSize, count, guidance, height, negativePrompt, steps, width],
+ );
+ const imageDefaultRecipe = useMemo<ImageGenerationPresetParams>(() => {
+ const recommended =
+ pendingModelDefaults ??
+ defaultsFor(status?.base_repo ?? status?.repo_id ?? "");
+ return {
+ negativePrompt: "",
+ width: 1024,
+ height: 1024,
+ steps: recommended.steps,
+ guidance: recommended.guidance,
+ batchSize: 1,
+ runs: 1,
+ };
+ }, [pendingModelDefaults, status?.base_repo, status?.repo_id]);
+ const applyImagePresetParams = useCallback((params: ImageGenerationPresetParams) => {
+ setNegativePrompt(params.negativePrompt);
+ // Same rule restoreSettings follows: a negative prompt that is in effect has to be visible, or
+ // the user generates against a setting the collapsed field is hiding.
+ if (params.negativePrompt) setNegativeOpen(true);
+ setWidth(params.width);
+ setHeight(params.height);
+ const matched = matchAspect(params.width, params.height);
+ setAspect(matched.key);
+ setPortrait(matched.portrait);
+ setSteps(params.steps);
+ setGuidance(params.guidance);
+ setBatchSize(params.batchSize);
+ setCount(params.runs);
+ return params;
+ }, []);
+ const imagePresets = useMediaGenerationPresets({
+ kind: "image",
+ defaultParams: imageDefaultRecipe,
+ currentParams: imagePresetParams,
+ applyParams: applyImagePresetParams,
+ });
+ const claimImageRecipe = imagePresets.claimRecipe;
+ const imageFormClaimId = imagePresets.formClaimId;
+ const applyImageModelDefaults = useCallback(
+ (repoId: string) => {
+ const revert = quantRevert.current;
+ if (revert && !revert.releaseRecipeClaim) {
+ const claim = claimImageRecipe();
+ revert.commitRecipeClaim = claim.commit;
+ revert.releaseRecipeClaim = claim.release;
+ }
+ // Baselined per pick, including a pick that inherits an earlier one's rollback: the question
+ // is whether the user takes the form after THIS pick, not after the one it replaced.
+ const claimedAt = imageFormClaimId();
+ pickRecipeSuperseded.current = () => imageFormClaimId() !== claimedAt;
+ const recommended = defaultsFor(repoId);
+ setPendingModelDefaults(recommended);
+ setSteps(recommended.steps);
+ setGuidance(recommended.guidance);
+ if (revert) {
+ revert.appliedSteps = recommended.steps;
+ revert.appliedGuidance = recommended.guidance;
+ }
+ },
+ [claimImageRecipe, imageFormClaimId],
+ );
+
const dismissLoadToast = useCallback(() => {
if (loadToastId.current != null) toast.dismiss(loadToastId.current);
loadToastId.current = null;
@@ -1373,7 +1478,15 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// Leaving this set would let Reapply reload the model that was just freed.
lastLoad.current = null;
setCanReapply(false);
- }, [dismissLoadToast, pickGuard]);
+ // Stopping the poll above also stops its "the load was cancelled or evicted" branch, which is
+ // what hands back a pick that never became resident. Do it here, exactly as that branch would:
+ // an unreleased recipe claim leaves hydration parked behind a load that is never coming, and a
+ // rollback left behind is one a later pick would inherit in place of its own.
+ if (quantRevert.current) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ }, [dismissLoadToast, pickGuard, revertPick]);
// Mirror to the module cache so a tab switch re-renders instantly.
useEffect(() => {
@@ -2022,7 +2135,10 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
toast.success("Model loaded");
setBusy(null);
// Load succeeded: the optimistic quant is now the real one, so drop the pending revert.
+ quantRevert.current?.commitRecipeClaim?.();
quantRevert.current = null;
+ // Status owns the recipe from here, so the pick's claim on Default expires with it.
+ setPendingModelDefaults(null);
// lastLoad.current already holds the now-resident pick, so drop its revert too.
lastLoadRevert.current = null;
return;
@@ -2175,23 +2291,34 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// Seed the generation sliders from a resident model's recipe when the page finds one it did not load itself, else they keep the
// unrecognised-model fallback and a resident flux.1-dev generates garbage at 9 steps. Guarded by lastLoad.current === null and a per-repo ref.
+ const residentSeeded = useRef(false);
useEffect(() => {
const repoId = status?.loaded ? status.repo_id : null;
if (!repoId) return;
if (lastLoad.current) return;
if (seededResident.current === repoId) return;
seededResident.current = repoId;
+ // Wire Reapply to the resident model too, so an advanced-option reload works without
+ // re-picking. Only a full pipeline is reloadable by repo id alone; a resident GGUF/single_file
+ // carries no checkpoint filename, so leave the target null for those and the button hidden.
+ // Set before the recipe decision below: whether Reapply has a target is a separate question
+ // from whether the model's defaults should seed the form.
+ if (status?.model_kind === "pipeline") {
+ lastLoad.current = { repoId, kind: "pipeline" };
+ }
+ // A stored recipe is the user's own choice, so it outranks the resident model's defaults on
+ // the first seed. Later resident changes still seed, as picking a model always has.
+ if (!residentSeeded.current) {
+ residentSeeded.current = true;
+ if (imagePresets.storedRecipe) return;
+ }
// Seed from base_repo (the resolved diffusers base, holding the family), not repo_id: a GGUF resident has no family substring.
+ // Status is the authority for a resident model, so this is not a pick's optimistic claim.
const d = defaultsFor(status?.base_repo ?? repoId);
+ setPendingModelDefaults(null);
setSteps(d.steps);
setGuidance(d.guidance);
- // Wire "Reapply" to the resident model too, so an advanced-option reload works without re-picking. Only a full pipeline
- // needs no checkpoint filename; a resident GGUF/single_file carries none, so leave lastLoad null for those.
- const kind = status?.model_kind;
- if (kind === "pipeline") {
- lastLoad.current = { repoId, kind };
- }
- }, [status?.loaded, status?.repo_id, status?.base_repo, status?.model_kind]);
+ }, [imagePresets.storedRecipe, status?.loaded, status?.repo_id, status?.base_repo, status?.model_kind]);
// Reseed the Advanced selects from the LOADED build, so they stop being pure local request state.
// An honored request re-selects itself (a no-op); a declined one snaps to what actually engaged,
@@ -2225,8 +2352,6 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
// eslint-disable-next-line react-hooks/exhaustive-deps -- resolvedKey stands for the record
}, [resolvedKey]);
- // The adapter list a load of *repoId* would BAKE into the build, shared by the load and the download plan: a torchao int8/fp8 transformer
- // takes adapters only before quantize_ + compile. Only a reload of the SAME target bakes, and it reads lastLoad.current, so call it first.
const bakedLorasFor = useCallback(
(repoId: string): LoraSpecInput[] => {
const sameTarget = repoId === (lastLoad.current?.repoId ?? status?.repo_id ?? null);
@@ -2603,9 +2728,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
onResolved: (filename) => {
quantRevert.current = revert;
setQuant(quantHint ?? filename);
- const d = defaultsFor(repoId);
- setSteps(d.steps);
- setGuidance(d.guidance);
+ applyImageModelDefaults(repoId);
},
onNotStarted: () => {
if (quantRevert.current === revert) {
@@ -2617,7 +2740,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
loadOrStage(repoId, { kind: "gguf", filename }, source, token),
});
},
- [guidance, loadOrStage, pickGuard, quant, revertPick, steps],
+ [applyImageModelDefaults, loadOrStage, pickGuard, quant, revertPick],
);
// A hidden page owns nothing: both stay mounted, so a resolution started here must not load after the user switched.
@@ -2634,6 +2757,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
useEffect(() => {
// A hidden page owns no query: both diffusion pages stay mounted.
if (!active) return;
+ if (!imagePresets.hydrated) return;
const wanted = routeSearch?.model;
// Key on the model AND the quant, and release the marker once the query is gone: this page stays mounted, so a marker that
// outlived the query made re-picking the same checkpoint a click that neither loaded nor cleared the URL.
@@ -2672,9 +2796,22 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub"));
return;
}
- void loadOrStage(pick.repoId, pick.opts, "hub", token);
+ // Match every direct picker branch: the routed intent owns both the visible build label and
+ // the model-specific Default recipe, and a load that never becomes resident rolls both back.
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
+ setQuant(pick.opts.kind === "pipeline" ? null : (pick.opts.filename ?? null));
+ applyImageModelDefaults(wanted);
+ void loadOrStage(pick.repoId, pick.opts, "hub", token).then((started) => {
+ if (!started && pickGuard.holds(token) && quantRevert.current === revert) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ });
}, [
active,
+ applyImageModelDefaults,
+ imagePresets.hydrated,
routeSearch?.model,
routeSearch?.quant,
routeSearch?.ggufQuant,
@@ -2682,6 +2819,8 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
loadGgufRepoPick,
navigateSelf,
pickGuard,
+ quant,
+ revertPick,
]);
// Reload the current model with the current advanced options.
@@ -2732,9 +2871,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(null);
- const d = defaultsFor(id);
- setSteps(d.steps);
- setGuidance(d.guidance);
+ applyImageModelDefaults(id);
void loadOrStage(
id,
{ kind: spec.kind, filename: spec.filename },
@@ -2754,9 +2891,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(meta.ggufVariant);
- const dq = defaultsFor(id);
- setSteps(dq.steps);
- setGuidance(dq.guidance);
+ applyImageModelDefaults(id);
void loadOrStage(
id,
{ kind: "gguf", filename: meta.ggufFilename },
@@ -2793,9 +2928,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(filename);
- const dq2 = defaultsFor(id);
- setSteps(dq2.steps);
- setGuidance(dq2.guidance);
+ applyImageModelDefaults(id);
void handleLoad(dir, { kind: "gguf", filename }).then((started) => {
if (!started) {
revertPick(revert);
@@ -2814,9 +2947,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(filename);
- const dsf = defaultsFor(id);
- setSteps(dsf.steps);
- setGuidance(dsf.guidance);
+ applyImageModelDefaults(id);
void handleLoad(dir, { kind: "single_file", filename }).then((started) => {
if (!started) {
revertPick(revert);
@@ -2847,9 +2978,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(null);
- const d = defaultsFor(id);
- setSteps(d.steps);
- setGuidance(d.guidance);
+ applyImageModelDefaults(id);
void loadOrStage(id, { kind: "pipeline" }, meta.source, token).then((started) => {
if (!started && pickGuard.holds(token)) {
revertPick(revert);
@@ -2859,16 +2988,15 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
},
[
abandonPick,
+ applyImageModelDefaults,
beginPick,
busy,
- guidance,
handleLoad,
loadGgufRepoPick,
loadOrStage,
pickGuard,
quant,
revertPick,
- steps,
],
);
@@ -2891,15 +3019,21 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
pendingDeploy.current = { loraId: stem, family: args.family };
if (args.trigger.trim()) setPrompt(args.trigger.trim());
setPageMode("create");
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
setQuant(null);
- const d = defaultsFor(args.baseRepo);
- setSteps(d.steps);
- setGuidance(d.guidance);
+ applyImageModelDefaults(args.baseRepo);
void handleLoad(args.baseRepo, { kind: "pipeline" }).then((started) => {
- if (!started) pendingDeploy.current = null;
+ if (!started) {
+ pendingDeploy.current = null;
+ if (quantRevert.current === revert) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ }
});
},
- [busy, handleLoad, pickGuard, setPageMode],
+ [applyImageModelDefaults, busy, handleLoad, pickGuard, quant, revertPick, setPageMode],
);
// Resolves true when the backend accepted the unload; handleCancelLoad reports the cancel only then.
@@ -3536,18 +3670,33 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
{/* The sidebar submenu is the switcher, so name the active workflow over its controls. */}
{/* Icon rides the heading; the line below runs the full width.
Same shape on the Video page, so the two stay level. */}
- <div className="mb-2 grid gap-1.5">
- <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none text-foreground">
- {/* Same icon the sidebar submenu uses for this workflow. */}
- <HugeiconsIcon
- icon={activeWorkflowTab.icon}
- className="size-[18px] shrink-0"
+ <div className="mb-2 flex items-start justify-between gap-3">
+ <div className="min-w-0 grid gap-1.5">
+ <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none text-foreground">
+ {/* Same icon the sidebar submenu uses for this workflow. */}
+ <HugeiconsIcon
+ icon={activeWorkflowTab.icon}
+ className="size-[18px] shrink-0"
+ />
+ {activeWorkflowTab.heading ?? activeWorkflowTab.label}
+ </h2>
+ <p className="text-xs leading-snug text-muted-foreground">
+ {activeWorkflowTab.hint}
+ </p>
+ </div>
+
+ {workflow === "create" && (
+ <MediaGenerationPresetControl
+ kind="image"
+ presets={imagePresets.presets}
+ activePreset={imagePresets.activePreset}
+ ready={imagePresets.presetsReady}
+ hasUnsavedChanges={imagePresets.hasUnsavedChanges}
+ onSelect={imagePresets.selectPreset}
+ onSave={imagePresets.savePreset}
+ onDelete={imagePresets.deletePreset}
/>
- {activeWorkflowTab.heading ?? activeWorkflowTab.label}
- </h2>
- <p className="text-xs leading-snug text-muted-foreground">
- {activeWorkflowTab.hint}
- </p>
+ )}
</div>
{workflow === "transform" && (
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 47d24030591..0188129960d 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -92,6 +92,14 @@ import type {
} from "@/features/model-picker/components/model-selector/types";
import { ParamSlider } from "@/features/chat";
import { ModelLoadDescription } from "@/features/chat/components/model-load-status";
+import {
+ MediaGenerationPresetControl,
+ type VideoGenerationPresetParams,
+ closestDurationIndex,
+ closestResolutionIndex,
+ shouldApplyModelDefaults,
+ useMediaGenerationPresets,
+} from "@/features/generation-presets";
import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";
import { formatBytes, formatEta } from "@/features/hub/lib/format";
import { useNavigate, useSearch } from "@tanstack/react-router";
@@ -733,7 +741,18 @@ function isH3PipelinePick(repoId: string, kind: VideoLoadOptions["kind"]): boole
// What a pick optimistically replaced, so a load that never takes can put all of it back. The quant
// label and the generation recipe move together at pick time, so they have to roll back together too.
-type PickRevert = { prev: string | null; steps: number; guidance: number };
+type PickRevert = {
+ prev: string | null;
+ steps: number;
+ guidance: number;
+ commitRecipeClaim?: () => void;
+ releaseRecipeClaim?: () => void;
+ // What the pick applied. A field the user changed after that is theirs, not ours to put back.
+ appliedSteps?: number;
+ appliedGuidance?: number;
+ modelSeeded?: boolean;
+ familySeeded?: boolean;
+};
// Resolved Advanced controls pinned across preflight, staging, and load.
type VideoLoadAdvanced = Pick<
VideoLoadRequest,
@@ -805,15 +824,40 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const [negativeOpen, setNegativeOpen] = useState(false);
const [steps, setSteps] = useState(DEFAULT_GEN.steps);
const [guidance, setGuidance] = useState(DEFAULT_GEN.guidance);
+ const modelSeeded = useRef(false);
+ const familySeeded = useRef(false);
+ // Whether the user has taken the recipe since the pick that is still waiting for its status.
+ // Both the seeding effects and the rollback below ask: a preset selected while the model
+ // downloaded is newer than that pick, so neither its defaults nor its rollback may land on top.
+ const pickRecipeSuperseded = useRef<(() => boolean) | null>(null);
// Put back everything a pick optimistically applied. Setters are stable, so this never re-renders on its own.
const revertPick = useCallback((r: PickRevert) => {
setQuant(r.prev);
- setSteps(r.steps);
- setGuidance(r.guidance);
+ setPendingModelDefaults(null);
+ // Equality alone cannot tell "nobody touched this" from "the user chose the same number": a
+ // preset selected after the pick owns these fields even where it matches what the pick applied.
+ if (!pickRecipeSuperseded.current?.()) {
+ setSteps((cur) => (cur === r.appliedSteps ? r.steps : cur));
+ setGuidance((cur) => (cur === r.appliedGuidance ? r.guidance : cur));
+ }
+ if (r.modelSeeded != null) modelSeeded.current = r.modelSeeded;
+ if (r.familySeeded != null) familySeeded.current = r.familySeeded;
+ pickRecipeSuperseded.current = null;
+ r.releaseRecipeClaim?.();
+ r.releaseRecipeClaim = undefined;
}, []);
+ // The recipe a pick optimistically claimed, until status confirms it or a failed load reverts
+ // it. Without this the Default preset would read as "modified" for the whole download.
+ const [pendingModelDefaults, setPendingModelDefaults] = useState<{
+ steps: number;
+ guidance: number;
+ } | null>(null);
const [seed, setSeed] = useState("");
// Preset index, or MATCH_SOURCE_RESOLUTION for a keyframe-derived canvas.
const [resolutionIdx, setResolutionIdx] = useState(0);
+ const [resolutionIntent, setResolutionIntent] = useState<[number, number]>(
+ FALLBACK_RESOLUTION_PRESETS[0]!,
+ );
// 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);
@@ -833,6 +877,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const [numFrames, setNumFrames] = useState(
FALLBACK_FRAME_STEP * 3 + FALLBACK_FRAME_OFFSET,
);
+ const [durationIntentSeconds, setDurationIntentSeconds] = useState(
+ numFrames / FALLBACK_FPS,
+ );
// Advanced options live in a right-docked panel, closed by default; a single fixed top-bar toggle opens it.
// Sits inline under Seed; the open state is remembered across visits.
const [advancedOpen, setAdvancedOpen] = usePersistedToggle(
@@ -850,7 +897,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
>("auto");
// The last load descriptor, so "Reapply" can reload the same model with new advanced options.
const lastLoad = useRef<({ repoId: string } & VideoLoadOptions) | null>(null);
- // Whether this session holds a reapply descriptor: with a model already resident, lastLoad is null, so hide the button rather than offer a dead control.
+ // Render-safe mirror of whether a page-initiated load supplied a complete Reapply target.
const [canReapply, setCanReapply] = useState(false);
const [busy, setBusy] = useState<Busy>(null);
@@ -968,7 +1015,15 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Leaving this set would let Reapply reload the model that was just freed.
lastLoad.current = null;
setCanReapply(false);
- }, [dismissLoadToast, pickGuard]);
+ // Stopping the poll above also stops its "the load was cancelled or evicted" branch, which is
+ // what hands back a pick that never became resident. Do it here, exactly as that branch would:
+ // an unreleased recipe claim leaves hydration parked behind a load that is never coming, and a
+ // rollback left behind is one a later pick would inherit in place of its own.
+ if (quantRevert.current) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ }, [dismissLoadToast, pickGuard, revertPick]);
// Mirror to the module cache so a tab switch re-renders instantly.
useEffect(() => {
@@ -1082,6 +1137,148 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
[keyframeAspect, status?.defaults],
);
+ const videoPresetParams = useMemo<VideoGenerationPresetParams>(() => {
+ const resolution =
+ resolutionIdx === MATCH_SOURCE_RESOLUTION && matchedResolution
+ ? matchedResolution
+ : resolutionIntent;
+ return {
+ negativePrompt,
+ width: resolution[0],
+ height: resolution[1],
+ durationSeconds: durationIntentSeconds,
+ steps,
+ guidance,
+ flowShift,
+ audioFlowShift,
+ };
+ }, [audioFlowShift, durationIntentSeconds, flowShift, guidance, matchedResolution, negativePrompt, resolutionIdx, resolutionIntent, steps]);
+ const defaultSteps = status?.defaults?.steps;
+ const defaultGuidance = status?.defaults?.guidance;
+ const familyDefaultFrames = status?.defaults?.num_frames;
+ const defaultFlowShift = status?.defaults?.flow_shift ?? null;
+ const defaultAudioFlowShift = status?.defaults?.audio_flow_shift ?? null;
+ const presetRepoId = status?.repo_id ?? "";
+ const videoDefaultRecipe = useMemo<VideoGenerationPresetParams>(() => {
+ const resolution = resolutionPresets[0] ?? [768, 512];
+ const recommended =
+ pendingModelDefaults ??
+ (defaultSteps != null && defaultGuidance != null
+ ? { steps: defaultSteps, guidance: defaultGuidance }
+ : defaultsFor(presetRepoId));
+ const defaultDuration = familyDefaultFrames
+ ? durationOptions[
+ closestDurationIndex(durationOptions, familyDefaultFrames / fps)
+ ]?.seconds
+ : status?.loaded
+ ? durationOptions[2]?.seconds ?? durationOptions[0]?.seconds ?? 3
+ : durationOptions[0]?.seconds ?? 1;
+ return {
+ negativePrompt: "",
+ width: resolution[0],
+ height: resolution[1],
+ durationSeconds: defaultDuration,
+ steps: recommended.steps,
+ guidance: recommended.guidance,
+ flowShift: defaultFlowShift,
+ audioFlowShift: defaultAudioFlowShift,
+ };
+ }, [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 durationIndex = closestDurationIndex(durationOptions, params.durationSeconds);
+ const durationFrames =
+ durationOptions[durationIndex]?.frames ?? durationOptions[0]?.frames ?? numFrames;
+ setResolutionIntent([params.width, params.height]);
+ setDurationIntentSeconds(params.durationSeconds);
+ setNegativePrompt(params.negativePrompt);
+ // Same rule restoreSettings follows: a negative prompt that is 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);
+ setFlowShift(params.flowShift);
+ setAudioFlowShift(params.audioFlowShift);
+ return params;
+ },
+ [durationOptions, numFrames, resolutionPresets],
+ );
+ const normalizeVideoPresetParams = useCallback(
+ (params: VideoGenerationPresetParams) => {
+ const resolution =
+ resolutionPresets[
+ closestResolutionIndex(resolutionPresets, params.width, params.height)
+ ] ?? resolutionPresets[0] ?? [768, 512];
+ const duration =
+ durationOptions[
+ closestDurationIndex(durationOptions, params.durationSeconds)
+ ]?.seconds ?? params.durationSeconds;
+ return {
+ ...params,
+ width: resolution[0],
+ height: resolution[1],
+ durationSeconds: duration,
+ };
+ },
+ [durationOptions, resolutionPresets],
+ );
+ const videoPresets = useMediaGenerationPresets({
+ kind: "video",
+ defaultParams: videoDefaultRecipe,
+ currentParams: videoPresetParams,
+ applyParams: applyVideoPresetParams,
+ normalizeParams: normalizeVideoPresetParams,
+ });
+ const claimVideoRecipe = videoPresets.claimRecipe;
+ const videoFormClaimId = videoPresets.formClaimId;
+ const applyVideoModelDefaults = useCallback(
+ (repoId: string) => {
+ const revert = quantRevert.current;
+ if (revert && !revert.releaseRecipeClaim) {
+ const claim = claimVideoRecipe();
+ revert.commitRecipeClaim = claim.commit;
+ revert.releaseRecipeClaim = claim.release;
+ }
+ // Baselined per pick, including a pick that inherits an earlier one's rollback: the question
+ // is whether the user takes the form after THIS pick, not after the one it replaced.
+ const claimedAt = videoFormClaimId();
+ pickRecipeSuperseded.current = () => videoFormClaimId() !== claimedAt;
+ const recommended = defaultsFor(repoId);
+ setPendingModelDefaults(recommended);
+ setSteps(recommended.steps);
+ setGuidance(recommended.guidance);
+ if (revert) {
+ revert.modelSeeded ??= modelSeeded.current;
+ revert.familySeeded ??= familySeeded.current;
+ revert.appliedSteps = recommended.steps;
+ revert.appliedGuidance = recommended.guidance;
+ }
+ // This explicit pick owns the first status confirmation. On failure, revertPick restores
+ // both markers so a previously saved recipe can still outrank a merely discovered resident.
+ modelSeeded.current = true;
+ familySeeded.current = true;
+ },
+ [claimVideoRecipe, 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(() => {
@@ -1091,60 +1288,98 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
hadKeyframeRef.current = has;
setResolutionIdx((idx) => {
if (has) return MATCH_SOURCE_RESOLUTION;
- return idx === MATCH_SOURCE_RESOLUTION ? 0 : idx;
+ return idx === MATCH_SOURCE_RESOLUTION
+ ? closestResolutionIndex(
+ resolutionPresets,
+ resolutionIntent[0],
+ resolutionIntent[1],
+ )
+ : idx;
});
- }, [canvasKeyframe, matchedResolution]);
+ }, [canvasKeyframe, matchedResolution, resolutionIntent, resolutionPresets]);
const loadedFamily = status?.loaded ? status.family : null;
- const familyDefaultFrames = status?.defaults?.num_frames;
const prevFamilyRef = useRef<string | null>(null);
useEffect(() => {
const familyChanged = loadedFamily !== prevFamilyRef.current;
prevFamilyRef.current = loadedFamily;
- setNumFrames((cur) => {
- // A newly loaded family brings its own default clip length; without this the pre-load fallback sticks and every default run is a ~1s clip.
- if (familyChanged && loadedFamily && familyDefaultFrames) {
- const best = durationOptions.reduce((a, b) =>
- Math.abs(b.frames - familyDefaultFrames) < Math.abs(a.frames - familyDefaultFrames)
- ? b
- : a,
- );
- return best?.frames ?? cur;
+ // A newly loaded family brings its own default clip length; without this the pre-load fallback
+ // sticks and every default run is a ~1s clip. Intent moves with it, so the recipe a preset is
+ // compared against and the frame count generation sends never disagree.
+ const applyFamilyDefault = shouldApplyModelDefaults(
+ familySeeded.current,
+ videoPresets.storedRecipe,
+ pickRecipeSuperseded.current?.() ?? false,
+ );
+ if (familyChanged && loadedFamily) familySeeded.current = true;
+ if (familyChanged && loadedFamily && familyDefaultFrames && applyFamilyDefault) {
+ const option =
+ durationOptions[
+ closestDurationIndex(durationOptions, familyDefaultFrames / fps)
+ ];
+ if (option) {
+ setDurationIntentSeconds(option.seconds);
+ setNumFrames(option.frames);
+ return;
}
- if (durationOptions.some((o) => o.frames === cur)) return cur;
- // Prefer the ~3s preset (index 2) as a sensible default, else the first.
- return durationOptions[2]?.frames ?? durationOptions[0]?.frames ?? cur;
+ }
+ setNumFrames((cur) => {
+ if (!familyChanged && durationOptions.some((o) => o.frames === cur)) return cur;
+ return (
+ durationOptions[
+ closestDurationIndex(durationOptions, durationIntentSeconds)
+ ]?.frames ?? cur
+ );
});
- }, [durationOptions, loadedFamily, familyDefaultFrames]);
+ }, [
+ durationIntentSeconds,
+ durationOptions,
+ familyDefaultFrames,
+ fps,
+ loadedFamily,
+ videoPresets.storedRecipe,
+ ]);
// Seed steps/guidance from the loaded model's backend defaults: on mount with a model already loaded only refreshStatus runs, so the
// controls would stick at the pre-load DEFAULT_GEN and a base checkpoint wanting 40/4 generates a degraded clip. Keyed on the resolved
// schedule, not the repo alone: a GGUF repo holds several variants, so another client swapping builds changes the defaults in place.
- const defaultSteps = status?.defaults?.steps;
- const defaultGuidance = status?.defaults?.guidance;
const loadedModelKey = status?.loaded
- ? `${status.repo_id ?? ""}|${defaultSteps ?? ""}|${defaultGuidance ?? ""}`
+ ? `${status.repo_id ?? ""}|${defaultSteps ?? ""}|${defaultGuidance ?? ""}|${defaultFlowShift ?? ""}|${defaultAudioFlowShift ?? ""}`
: null;
const prevLoadedModelRef = useRef<string | null>(null);
useEffect(() => {
const modelChanged = loadedModelKey !== prevLoadedModelRef.current;
prevLoadedModelRef.current = loadedModelKey;
if (modelChanged && loadedModelKey && defaultSteps != null && defaultGuidance != null) {
+ // Status is the authority now, so the recipe a pick claimed has served its purpose.
+ setPendingModelDefaults(null);
+ // A stored recipe is the user's own choice, so it outranks the model's defaults on the first
+ // seed. Every later model change still seeds, as picking a model always has.
+ const applyDefaults = shouldApplyModelDefaults(
+ modelSeeded.current,
+ videoPresets.storedRecipe,
+ pickRecipeSuperseded.current?.() ?? false,
+ );
+ // This status IS the pending pick's confirmation, so the question is answered for good. Read
+ // after the family effect above, which runs first on the same status and asks the same thing.
+ pickRecipeSuperseded.current = null;
+ modelSeeded.current = true;
+ if (!applyDefaults) return;
setSteps(defaultSteps);
setGuidance(defaultGuidance);
+ setFlowShift(defaultFlowShift);
+ setAudioFlowShift(defaultAudioFlowShift);
}
- }, [loadedModelKey, defaultSteps, defaultGuidance]);
+ }, [
+ defaultAudioFlowShift,
+ defaultFlowShift,
+ defaultGuidance,
+ defaultSteps,
+ loadedModelKey,
+ videoPresets.storedRecipe,
+ ]);
- // Reset schedule shifts when the loaded model changes.
- const defaultFlowShift = status?.defaults?.flow_shift ?? null;
- const defaultAudioFlowShift = status?.defaults?.audio_flow_shift ?? null;
const canPickAudioFlowShift = status?.defaults?.supports_audio_flow_shift === true;
- useEffect(() => {
- setFlowShift(defaultFlowShift);
- }, [defaultFlowShift, loadedModelKey]);
- useEffect(() => {
- setAudioFlowShift(defaultAudioFlowShift);
- }, [defaultAudioFlowShift, loadedModelKey]);
// Reseed the Advanced selects from the LOADED build, so they stop being pure local request state.
// An honored request re-selects itself; a declined one snaps to what actually engaged, so the
@@ -1176,8 +1411,6 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// eslint-disable-next-line react-hooks/exhaustive-deps -- resolvedKey stands for the record
}, [resolvedKey]);
- // Mint (once) a playable link for a record's MP4, cached across remounts. Unlike the images gallery this does NOT download
- // the file: the link goes straight into the <video> element, which streams ranges, so playback starts and seeking works.
const ensureSrc = useCallback(async (video: GalleryVideo) => {
const cached = galleryCache.srcById.get(video.id);
if (cached && Date.now() - cached.mintedAt < VIDEO_LINK_REFRESH_MS) return;
@@ -1588,14 +1821,18 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const presetIdx = resolutionPresets.findIndex(
([w, h]) => w === video.width && h === video.height,
);
- if (presetIdx >= 0) setResolutionIdx(presetIdx);
+ if (presetIdx >= 0) {
+ setResolutionIntent([video.width, video.height]);
+ setResolutionIdx(presetIdx);
+ }
// 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);
setNumFrames(video.num_frames);
}
toast.success("Settings restored to inputs");
},
- [resolutionPresets, durationOptions],
+ [resolutionPresets, durationOptions, fps],
);
// A status read started before an eject can answer after the one that
@@ -1696,6 +1933,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
setStatusIfNewest(ticket, loaded);
toast.success("Model loaded");
setBusy(null);
+ quantRevert.current?.commitRecipeClaim?.();
quantRevert.current = null;
// lastLoad.current already holds the now-resident pick, so drop its revert too.
lastLoadRevert.current = null;
@@ -2232,9 +2470,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
quantRevert.current = revert;
setQuant(quantHint ?? filename);
// Filename-qualified like the expander branch: the LTX variant lives in the checkpoint name, not the repo id.
- const d = defaultsFor(`${repoId}/${filename}`);
- setSteps(d.steps);
- setGuidance(d.guidance);
+ applyVideoModelDefaults(`${repoId}/${filename}`);
},
onNotStarted: () => {
if (quantRevert.current === revert) {
@@ -2246,7 +2482,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
loadOrStage(repoId, { kind: "gguf", filename }, source, token),
});
},
- [guidance, loadOrStage, pickGuard, quant, revertPick, steps],
+ [applyVideoModelDefaults, loadOrStage, pickGuard, quant, revertPick],
);
// A pick that is rejected after beginPick() has already retired the staged pick it replaced, so
@@ -2284,6 +2520,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
useEffect(() => {
// A hidden page owns no query: both diffusion pages stay mounted.
if (!active) return;
+ if (!videoPresets.hydrated) return;
const wanted = routeSearch?.model;
// Model AND quant, released once the query is gone: this page stays mounted, so a marker that outlived the query made re-picking a dead click.
if (!wanted) {
@@ -2321,6 +2558,14 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub"));
return;
}
+ // Match every direct picker branch: the routed intent owns both the visible build label and
+ // the model-specific Default recipe, and a load that never becomes resident rolls both back.
+ const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
+ quantRevert.current = revert;
+ setQuant(pick.opts.kind === "pipeline" ? null : (pick.opts.filename ?? null));
+ applyVideoModelDefaults(
+ pick.opts.filename ? `${pick.repoId}/${pick.opts.filename}` : pick.repoId,
+ );
// A routed pick owns the page exactly like a direct one, so it has to offer the same choice.
if (isH3PipelinePick(pick.repoId, pick.opts.kind)) {
setPendingH3Load({
@@ -2331,9 +2576,15 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
});
return;
}
- void loadOrStage(pick.repoId, pick.opts, "hub", token);
+ void loadOrStage(pick.repoId, pick.opts, "hub", token).then((started) => {
+ if (!started && pickGuard.holds(token) && quantRevert.current === revert) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ });
}, [
active,
+ applyVideoModelDefaults,
routeSearch?.model,
routeSearch?.quant,
routeSearch?.ggufQuant,
@@ -2341,6 +2592,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
loadGgufRepoPick,
navigateSelf,
pickGuard,
+ quant,
+ revertPick,
+ videoPresets.hydrated,
]);
@@ -2377,6 +2631,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Reload the current model with the current advanced options.
const handleReapply = useCallback(() => {
+ // Status is authoritative when another client replaced the resident model. The ref remains
+ // the fallback while this page's own load is committing and status has not caught up yet.
const l = lastLoad.current;
if (l) {
void handleLoad(l.repoId, {
@@ -2421,9 +2677,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
setQuant(null);
// The distilled variant lives in the checkpoint name, not the repo id, so include the filename when seeding defaults.
// Without it these distilled entries fall through to the generic LTX 40-step/CFG-4 defaults instead of the 8-step schedule.
- const d = defaultsFor(spec.filename ? `${id}/${spec.filename}` : id);
- setSteps(d.steps);
- setGuidance(d.guidance);
+ applyVideoModelDefaults(spec.filename ? `${id}/${spec.filename}` : id);
if (isH3PipelinePick(id, spec.kind)) {
setPendingH3Load({
repoId: id,
@@ -2452,9 +2706,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
quantRevert.current = revert;
setQuant(meta.ggufVariant);
// Include the picked filename: the variant (distilled vs dev) lives there, not in the repo id.
- const dq = defaultsFor(`${id}/${meta.ggufFilename}`);
- setSteps(dq.steps);
- setGuidance(dq.guidance);
+ applyVideoModelDefaults(`${id}/${meta.ggufFilename}`);
void loadOrStage(
id,
{ kind: "gguf", filename: meta.ggufFilename },
@@ -2489,9 +2741,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(filename);
- const dq2 = defaultsFor(id);
- setSteps(dq2.steps);
- setGuidance(dq2.guidance);
+ applyVideoModelDefaults(id);
void handleLoad(dir, { kind: "gguf", filename }).then((started) => {
if (!started) {
revertPick(revert);
@@ -2509,9 +2759,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(filename);
- const dsf = defaultsFor(id);
- setSteps(dsf.steps);
- setGuidance(dsf.guidance);
+ applyVideoModelDefaults(id);
void handleLoad(dir, { kind: "single_file", filename }).then((started) => {
if (!started) {
revertPick(revert);
@@ -2543,9 +2791,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const revert: PickRevert = quantRevert.current ?? { prev: quant, steps, guidance };
quantRevert.current = revert;
setQuant(null);
- const d = defaultsFor(id);
- setSteps(d.steps);
- setGuidance(d.guidance);
+ applyVideoModelDefaults(id);
// The on-device copy of the H3 pipeline lands here rather than in the curated branch, and
// it needs the same partition question: without it the load silently takes fl2va.
if (isH3PipelinePick(id, "pipeline")) {
@@ -2566,16 +2812,15 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
},
[
abandonPick,
+ applyVideoModelDefaults,
beginPick,
busy,
- guidance,
handleLoad,
loadGgufRepoPick,
loadOrStage,
pickGuard,
quant,
revertPick,
- steps,
],
);
@@ -2717,7 +2962,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
reference_image_size: canPickReferenceSize ? referenceImageSize : undefined,
// Send only overrides of the released schedule.
flow_shift:
- flowShift != null && flowShift !== defaultFlowShift ? flowShift : undefined,
+ defaultFlowShift != null && flowShift != null && flowShift !== defaultFlowShift
+ ? flowShift
+ : undefined,
audio_flow_shift:
canPickAudioFlowShift && audioFlowShift != null && audioFlowShift !== defaultAudioFlowShift
? audioFlowShift
@@ -3017,19 +3264,32 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
>
{/* Names the pane, as the Images column does. Same shape there, so
the two pages stay level. */}
- <div className="mb-2 grid gap-1.5">
- <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none text-foreground">
- {/* The app's Video icon, same as the sidebar row. */}
- <HugeiconsIcon icon={FlimSlateIcon} className="size-[18px] shrink-0" />
- Create videos
- </h2>
- <p className="text-xs leading-snug text-muted-foreground">
- {supportsReferences
- ? "Generate a video from a prompt and reference pictures, videos or audio"
- : supportsKeyframes
- ? "Generate a video from a prompt, or from a start and end frame"
- : "Generate a video from a prompt"}
- </p>
+ <div className="mb-2 flex items-start justify-between gap-3">
+ <div className="min-w-0 grid gap-1.5">
+ <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none text-foreground">
+ {/* The app's Video icon, same as the sidebar row. */}
+ <HugeiconsIcon icon={FlimSlateIcon} className="size-[18px] shrink-0" />
+ Create videos
+ </h2>
+ <p className="text-xs leading-snug text-muted-foreground">
+ {supportsReferences
+ ? "Generate a video from a prompt and reference pictures, videos or audio"
+ : supportsKeyframes
+ ? "Generate a video from a prompt, or from a start and end frame"
+ : "Generate a video from a prompt"}
+ </p>
+ </div>
+
+ <MediaGenerationPresetControl
+ kind="video"
+ presets={videoPresets.presets}
+ activePreset={videoPresets.activePreset}
+ ready={videoPresets.presetsReady}
+ hasUnsavedChanges={videoPresets.hasUnsavedChanges}
+ onSelect={videoPresets.selectPreset}
+ onSave={videoPresets.savePreset}
+ onDelete={videoPresets.deletePreset}
+ />
</div>
<Field label="Prompt">
@@ -3250,7 +3510,12 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
>
<Select
value={String(resolutionIdx)}
- onValueChange={(v) => setResolutionIdx(Number(v))}
+ onValueChange={(v) => {
+ const index = Number(v);
+ const resolution = resolutionPresets[index];
+ if (resolution) setResolutionIntent(resolution);
+ setResolutionIdx(index);
+ }}
>
<SelectTrigger>
<SelectValue />
@@ -3280,7 +3545,11 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
>
<Select
value={String(numFrames)}
- onValueChange={(v) => setNumFrames(Number(v))}
+ onValueChange={(v) => {
+ const frames = Number(v);
+ setDurationIntentSeconds(frames / fps);
+ setNumFrames(frames);
+ }}
>
<SelectTrigger>
<SelectValue />
@@ -3323,22 +3592,22 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
onChange={setGuidance}
/>
)}
- {flowShift != null && (
+ {defaultFlowShift != null && (
<SliderField
label="Motion shift"
hint="Sigma shift of the video schedule. Higher spends more of the schedule at high noise, which reads as more motion and less fine detail. MiniMax-H3 ships 12."
- value={flowShift}
+ value={flowShift ?? defaultFlowShift}
min={1}
max={30}
step={0.5}
onChange={setFlowShift}
/>
)}
- {canPickAudioFlowShift && audioFlowShift != null && (
+ {canPickAudioFlowShift && defaultAudioFlowShift != null && (
<SliderField
label="Audio shift"
hint="Sigma shift of the audio schedule, which MiniMax-H3 runs alongside the video one. Ships at 3."
- value={audioFlowShift}
+ value={audioFlowShift ?? defaultAudioFlowShift}
min={1}
max={30}
step={0.5}
diff --git a/studio/frontend/tests/image-generation-defaults.test.ts b/studio/frontend/tests/image-generation-defaults.test.ts
index cad3b57f7ab..233ff15f351 100644
--- a/studio/frontend/tests/image-generation-defaults.test.ts
+++ b/studio/frontend/tests/image-generation-defaults.test.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
import test from "node:test";
import { defaultsFor } from "../src/features/images/image-generation-defaults.ts";
@@ -33,3 +34,74 @@ test("keeps the existing family defaults and fallback", () => {
guidance: 0,
});
});
+
+test("routed image picks apply and transactionally roll back model defaults", () => {
+ const source = readFileSync(
+ new URL("../src/features/images/images-page.tsx", import.meta.url),
+ "utf8",
+ );
+ const routeStart = source.indexOf(
+ "const pick = diffusionRoutePick(",
+ source.indexOf("const handledRouteModel"),
+ );
+ const routeEnd = source.indexOf(
+ "// Reload the current model with the current advanced options.",
+ routeStart,
+ );
+ assert.ok(routeStart >= 0 && routeEnd > routeStart);
+ const routeBlock = source.slice(routeStart, routeEnd);
+ assert.match(routeBlock, /imagePresets\.hydrated/);
+ assert.match(routeBlock, /quantRevert\.current = revert/);
+ assert.match(routeBlock, /applyImageModelDefaults\(wanted\)/);
+ assert.match(routeBlock, /!started[\s\S]*revertPick\(revert\)/);
+});
+
+test("routed video picks apply and transactionally roll back model defaults", () => {
+ const source = readFileSync(
+ new URL("../src/features/video/video-page.tsx", import.meta.url),
+ "utf8",
+ );
+ const routeStart = source.indexOf(
+ "const pick = diffusionRoutePick(",
+ source.indexOf("const handledRouteModel"),
+ );
+ const routeEnd = source.indexOf(
+ "// The task dialog defers the load",
+ routeStart,
+ );
+ assert.ok(routeStart >= 0 && routeEnd > routeStart);
+ const routeBlock = source.slice(routeStart, routeEnd);
+ assert.match(routeBlock, /videoPresets\.hydrated/);
+ assert.match(routeBlock, /quantRevert\.current = revert/);
+ assert.match(routeBlock, /applyVideoModelDefaults\(/);
+ assert.match(routeBlock, /!started[\s\S]*revertPick\(revert\)/);
+});
+
+test("failed image and video picks release their recipe hydration claims", () => {
+ for (const path of [
+ "../src/features/images/images-page.tsx",
+ "../src/features/video/video-page.tsx",
+ ]) {
+ const source = readFileSync(new URL(path, import.meta.url), "utf8");
+ assert.match(source, /const claim = claim\w+Recipe\(\)/);
+ assert.match(source, /commitRecipeClaim = claim\.commit/);
+ assert.match(source, /releaseRecipeClaim = claim\.release/);
+ assert.match(source, /quantRevert\.current\?\.commitRecipeClaim\?\.\(\)/);
+ assert.match(source, /revertPick[\s\S]*r\.releaseRecipeClaim\?\.\(\)/);
+ }
+
+ const hook = readFileSync(
+ new URL(
+ "../src/features/generation-presets/use-media-generation-presets.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ hook,
+ /deferredSavedSettingsRef\.current = committed \? null : settings/,
+ );
+ assert.match(hook, /formClaim\.current = previousClaim/);
+ assert.match(hook, /hydrateSavedSettings\(deferred\)/);
+ assert.match(hook, /source === "claiming"\s*\? "claimed" : source/);
+});
diff --git a/studio/frontend/tests/media-eject-busy-state.test.ts b/studio/frontend/tests/media-eject-busy-state.test.ts
index b32a8d6c624..1d0d30be0ed 100644
--- a/studio/frontend/tests/media-eject-busy-state.test.ts
+++ b/studio/frontend/tests/media-eject-busy-state.test.ts
@@ -52,7 +52,11 @@ for (const [page, runtime, path] of PAGES) {
const drop = SOURCE.slice(
SOURCE.indexOf("const dropResidentState = useCallback("),
// To the end of the callback, not a fixed window: the body grew a cancel fence.
- SOURCE.indexOf("}, [dismissLoadToast, pickGuard]);"),
+ // Anchored from the opening, so the deps can grow without silently widening this slice.
+ SOURCE.indexOf(
+ "}, [dismissLoadToast,",
+ SOURCE.indexOf("const dropResidentState = useCallback("),
+ ),
);
assert.match(drop, /clearTimeout\(pollTimer\.current\)/);
assert.doesNotMatch(
diff --git a/studio/frontend/tests/media-generation-preset-claims.test.ts b/studio/frontend/tests/media-generation-preset-claims.test.ts
new file mode 100644
index 00000000000..6f0bff9773e
--- /dev/null
+++ b/studio/frontend/tests/media-generation-preset-claims.test.ts
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A model pick claims the generation recipe before the settings GET has necessarily answered, so
+// the claim has to be settled on every way out of that load. The progress poll covers the endings
+// it sees; a cancel or an eject tears the poll down first, so the pages hand the pick back
+// themselves. Without that, hydration parked behind the pick never resolves (the stored recipe is
+// never applied and the preset controls stay disabled), and the rollback left behind is the one a
+// later pick inherits in place of its own.
+//
+// The wiring lives inside two ~3000-line page components with no renderer in this suite, so these
+// assert on the source, like the other page-wiring tests here.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+function read(path: string) {
+ return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");
+}
+
+const IMAGES = read("../src/features/images/images-page.tsx");
+const VIDEO = read("../src/features/video/video-page.tsx");
+const HOOK = read(
+ "../src/features/generation-presets/use-media-generation-presets.ts",
+);
+
+function dropResidentState(source: string) {
+ const start = source.indexOf("const dropResidentState = useCallback(");
+ assert.ok(start > 0, "dropResidentState must exist");
+ return source.slice(start, source.indexOf("]);", start));
+}
+
+for (const [page, source] of [
+ ["images", IMAGES],
+ ["video", VIDEO],
+] as const) {
+ test(`${page}: cancelling or ejecting a load hands the pick back`, () => {
+ const body = dropResidentState(source);
+ // The same two lines the poll's cancelled/evicted branch runs, which this tears down first.
+ assert.match(body, /revertPick\(quantRevert\.current\);/);
+ assert.match(body, /quantRevert\.current = null;/);
+ });
+
+ test(`${page}: every pick baselines supersession on itself`, () => {
+ // A second pick reuses the first one's rollback object, so the claim block is skipped. Reading
+ // the counter outside it is what stops the second pick from inheriting the first's answer.
+ const apply = source.slice(
+ source.indexOf("ModelDefaults = useCallback("),
+ source.indexOf("const recommended = defaultsFor(repoId);"),
+ );
+ assert.match(apply, /const claimedAt = \w+FormClaimId\(\);/);
+ assert.match(
+ apply,
+ /pickRecipeSuperseded\.current = \(\) => \w+FormClaimId\(\) !== claimedAt;/,
+ );
+ const claimBlock = apply.slice(
+ apply.indexOf("if (revert && !revert.releaseRecipeClaim) {"),
+ apply.indexOf("const claimedAt"),
+ );
+ assert.doesNotMatch(claimBlock, /claimedAt/, "the baseline must survive a reused rollback");
+ });
+
+ test(`${page}: a superseded pick does not roll the recipe back`, () => {
+ const revert = source.slice(
+ source.indexOf("const revertPick = useCallback("),
+ source.indexOf("r.releaseRecipeClaim?.();"),
+ );
+ const guard = revert.indexOf("if (!pickRecipeSuperseded.current?.()) {");
+ assert.ok(guard > 0, "the value restore must sit behind the supersession guard");
+ assert.ok(guard < revert.indexOf("cur === r.appliedSteps"));
+ assert.ok(guard < revert.indexOf("cur === r.appliedGuidance"));
+ });
+
+ test(`${page}: a preset's negative prompt is revealed, not applied behind a closed field`, () => {
+ const apply = source.slice(source.indexOf("PresetParams = useCallback("));
+ const setter = apply.indexOf("setNegativePrompt(params.negativePrompt);");
+ assert.ok(setter > 0);
+ assert.match(
+ apply.slice(setter, setter + 400),
+ /if \(params\.negativePrompt\) setNegativeOpen\(true\);/,
+ );
+ });
+}
+
+test("the form claim counter is readable, so a pick can tell it was superseded", () => {
+ assert.match(HOOK, /const formClaimId = useCallback\(\(\) => formClaim\.current, \[\]\);/);
+ assert.match(HOOK, /^\s+formClaimId,$/m, "and returned from the hook");
+});
+
+test("a preset write that failed gives its form claim back", () => {
+ // Otherwise a rejected save reads as "something newer owns the form" for the rest of the
+ // session, and a pending pick's model defaults are skipped over a change that never happened.
+ for (const name of ["const savePreset = useCallback(", "const deletePreset = useCallback("]) {
+ const body = HOOK.slice(HOOK.indexOf(name));
+ const failure = body.slice(body.indexOf("} catch (error) {"));
+ assert.match(
+ failure.slice(0, failure.indexOf("toast.error")),
+ /if \(formClaim\.current === claim\) formClaim\.current = previousClaim;/,
+ `${name} must restore the claim before reporting the failure`,
+ );
+ }
+});
+
+test("state writes go out one at a time, newest last", () => {
+ // Two PUTs in flight land in whatever order the backend sees them, and the store keeps the last
+ // one, so an older snapshot could outlive the newest recipe.
+ assert.match(
+ HOOK,
+ /inflightWriteRef\.current = inflightWriteRef\.current\s*\n?\s*\.catch\(\(\) => undefined\)\s*\n?\s*\.then\(write\);/,
+ );
+ for (const site of [
+ "saveMediaGenerationPresetSettings(kind, settings)",
+ "saveMediaGenerationPresetSettings(kind, latest, true)",
+ ]) {
+ const at = HOOK.indexOf(site);
+ assert.ok(at > 0, site);
+ assert.match(
+ HOOK.slice(at - 120, at),
+ /queueWrite\(\(\) =>\s*$/,
+ `${site} must go through the queue`,
+ );
+ }
+});
+
+test("a delete clears the selection even when a pick took the form meanwhile", () => {
+ // The preset is gone either way, and a selection naming it leaves the control on a definition
+ // that no longer exists (and persists that name on the next debounced write).
+ const del = HOOK.slice(
+ HOOK.indexOf("const deletePreset = useCallback("),
+ HOOK.indexOf("const activeDefinition ="),
+ );
+ assert.match(
+ del,
+ /restoreDefaultAfterDelete\(paramsBeforeDelete, formClaim\.current === claim\);/,
+ );
+ const restore = HOOK.slice(
+ HOOK.indexOf("const restoreDefaultAfterDelete = useCallback("),
+ HOOK.indexOf("const deletePreset = useCallback("),
+ );
+ // Only the form VALUES are conditional; the selection reset is not.
+ assert.match(restore, /ownsForm &&/);
+ assert.match(restore, /setActivePreset\(DEFAULT_PRESET_NAME\);/);
+});
+
+test("a store with presets but no recipe still hydrates the library", () => {
+ // saved:false means the recipe falls back to the model's defaults, not that the user's named
+ // presets are gone; dropping them would hide a library the response is carrying.
+ assert.match(
+ HOOK,
+ /hydrateLocalSettings\("fresh", settings\.customPresets \?\? \[\]\)/,
+ );
+ const hydrate = HOOK.slice(HOOK.indexOf("const hydrateLocalSettings = useCallback("));
+ assert.match(hydrate.slice(0, hydrate.indexOf("setActivePreset")), /setCustomPresets\(custom\);/);
+});
+
+test("video defers both status seeds to a preset picked during the load", () => {
+ // The duration branch and the steps/guidance branch seed independently, so both have to ask.
+ const asks = VIDEO.match(/pickRecipeSuperseded\.current\?\.\(\) \?\? false,/g) ?? [];
+ assert.equal(asks.length, 2);
+ const seed = VIDEO.slice(VIDEO.indexOf("const applyDefaults = shouldApplyModelDefaults("));
+ assert.ok(
+ seed.indexOf("pickRecipeSuperseded.current = null;") <
+ seed.indexOf("modelSeeded.current = true;"),
+ "the confirmed pick's question is answered once, in the later of the two effects",
+ );
+});
diff --git a/studio/frontend/tests/media-generation-preset-policy.test.ts b/studio/frontend/tests/media-generation-preset-policy.test.ts
new file mode 100644
index 00000000000..dc114e0ad7e
--- /dev/null
+++ b/studio/frontend/tests/media-generation-preset-policy.test.ts
@@ -0,0 +1,51 @@
+// 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 {
+ closestDurationIndex,
+ closestResolutionIndex,
+ getBuiltinVariantName,
+ shouldApplyModelDefaults,
+} from "../src/features/generation-presets/preset-policy.ts";
+
+test("saving over Default creates a protected custom variant", () => {
+ const used = new Set(["Default", "Default 1", "Portrait"]);
+ assert.equal(getBuiltinVariantName(used), "Default 2");
+});
+
+test("video resolution mapping prioritizes aspect before area", () => {
+ const options: [number, number][] = [
+ [1024, 1024],
+ [1216, 704],
+ [704, 1216],
+ ];
+ assert.equal(closestResolutionIndex(options, 1920, 1080), 1);
+ assert.equal(closestResolutionIndex(options, 1080, 1920), 2);
+});
+
+test("video duration mapping uses the closest supported temporal lattice", () => {
+ const options = [
+ { seconds: 1.04 },
+ { seconds: 2.08 },
+ { seconds: 3.12 },
+ { seconds: 5.2 },
+ ];
+ assert.equal(closestDurationIndex(options, 4.9), 3);
+ assert.equal(closestDurationIndex(options, 2.4), 1);
+});
+
+test("a stored recipe owns only the first model-default seed", () => {
+ assert.equal(shouldApplyModelDefaults(false, true), false);
+ assert.equal(shouldApplyModelDefaults(false, false), true);
+ assert.equal(shouldApplyModelDefaults(true, true), true);
+});
+
+test("a preset selected while the model loaded outranks that load's defaults", () => {
+ // The pick claimed the recipe, so every other input says "seed". Only the newer claim stops it.
+ assert.equal(shouldApplyModelDefaults(true, false, true), false);
+ assert.equal(shouldApplyModelDefaults(true, true, true), false);
+ assert.equal(shouldApplyModelDefaults(true, false, false), true);
+});
diff --git a/studio/frontend/tests/media-load-cancel.test.ts b/studio/frontend/tests/media-load-cancel.test.ts
index 43b648cf752..916c50af950 100644
--- a/studio/frontend/tests/media-load-cancel.test.ts
+++ b/studio/frontend/tests/media-load-cancel.test.ts
@@ -245,7 +245,11 @@ for (const [page, path] of PAGES) {
test(`the ${page} cancel counter is bumped by every teardown`, () => {
const drop = SOURCE.slice(
SOURCE.indexOf("const dropResidentState = useCallback("),
- SOURCE.indexOf("}, [dismissLoadToast, pickGuard]);"),
+ // Anchored from the opening, so the deps can grow without silently widening this slice.
+ SOURCE.indexOf(
+ "}, [dismissLoadToast,",
+ SOURCE.indexOf("const dropResidentState = useCallback("),
+ ),
);
assert.match(
drop,
@@ -346,7 +350,11 @@ test("cancelling a deploy does not leave the adapter queued", () => {
const SOURCE = read("../src/features/images/images-page.tsx");
const drop = SOURCE.slice(
SOURCE.indexOf("const dropResidentState = useCallback("),
- SOURCE.indexOf("}, [dismissLoadToast, pickGuard]);"),
+ // Anchored from the opening, so the deps can grow without silently widening this slice.
+ SOURCE.indexOf(
+ "}, [dismissLoadToast,",
+ SOURCE.indexOf("const dropResidentState = useCallback("),
+ ),
);
assert.match(drop, /pendingDeploy\.current = null;/);
});
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 1a5a5cf3090..98b1de2810a 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -1322,18 +1322,26 @@ def test_a_pick_that_never_loads_restores_its_generation_recipe():
the label leaves a distilled model's low-step, guidance-0 recipe pointed at a non-distilled
model, and the next generation silently runs with the wrong settings.
- So the rollback token carries the recipe and every rollback path puts all of it back."""
+ So the rollback token carries the recipe and every rollback path puts all of it back.
+
+ The token may carry more than the recipe (a preset claim, what the pick applied), so the
+ fields are matched inside the declaration rather than against one exact line."""
for rel in ("features/images/images-page.tsx", "features/video/video-page.tsx"):
src = _read(rel)
- assert (
- "type PickRevert = { prev: string | null; steps: number; guidance: number };" in src
- ), f"{rel}: the rollback token does not carry the generation recipe"
+ token = re.search(r"type PickRevert = \{(.*?)\n\};", src, re.S) or re.search(
+ r"type PickRevert = \{(.*?)\};", src, re.S
+ )
+ assert token, f"{rel}: no PickRevert rollback token"
+ for field in ("prev: string | null", "steps: number", "guidance: number"):
+ assert field in token.group(1), f"{rel}: the rollback token does not carry {field}"
revert = re.search(
r"const revertPick = useCallback\(\(r: PickRevert\) => \{(.*?)\}, \[\]\);", src, re.S
)
assert revert, f"{rel}: no shared rollback helper"
body = revert.group(1)
- for setter in ("setQuant(r.prev)", "setSteps(r.steps)", "setGuidance(r.guidance)"):
+ # The recipe may be restored conditionally (a preset chosen after the pick owns those
+ # fields), but the rollback still has to read it off the token.
+ for setter in ("setQuant(r.prev)", "setSteps(", "r.steps", "setGuidance(", "r.guidance"):
assert setter in body, f"{rel}: rollback does not restore {setter}"
# No rollback path may still put back the label alone.
assert (