Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio Images: paste generation parameters, inpaint mask blur and only-masked area, seed buttons (#14508)
Daniel Han94a8bfacb33d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex cade476a53d..612d2d9fb9e 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -337,6 +337,14 @@ from .diffusion_flow_shift import (pipe_sample_sigmas,sample_sigmas_for_steps,)+from .diffusion_mask import (+ ONLY_MASKED_UNSUPPORTED_MSG,+ blur_mask,+ inpaint_class_accepts_padding_mask_crop,+ mask_is_empty,+ overlay_with_mask,+ resolve_padding,+)from .diffusion_sampler import (DEFAULT_SAMPLER,apply_checkpoint_prediction_type,@@ -12122,6 +12130,10 @@ class DiffusionBackend:live_preview: Optional[bool] = None,sampler: Optional[str] = None,schedule_type: Optional[str] = None,+ # Inpaint only: None / 0 / False keep the plain inpaint call.+ mask_blur: Optional[int] = None,+ inpaint_only_masked: Optional[bool] = None,+ inpaint_padding: Optional[int] = None,) -> dict[str, Any]:import torchfrom PIL import Image@@ -12437,6 +12449,26 @@ class DiffusionBackend:pipe.scheduler = swapped# Pipelines vary in accepted kwargs, so gate every optional one on the signature.call_params = inspect.signature(pipe.__call__).parameters+ mask_blur_applied = inpaint_padding_applied = None+ soft_overlay = None+ if workflow == "inpaint" and mask_pil is not None:+ inpaint_padding_applied = resolve_padding(inpaint_only_masked, inpaint_padding)+ if (+ inpaint_padding_applied is not None+ and "padding_mask_crop" not in call_params+ ):+ raise ValueError(ONLY_MASKED_UNSUPPORTED_MSG)+ if inpaint_padding_applied is not None and mask_is_empty(mask_pil):+ # diffusers' crop box needs a nonzero pixel; with none this is a plain inpaint.+ inpaint_padding_applied = None+ if mask_blur:+ # After the snap/resize above, so the radius is in source-image pixels.+ mask_pil = blur_mask(mask_pil, mask_blur)+ mask_blur_applied = int(mask_blur)+ # The pipeline binarizes the mask, so the blur only reaches the picture through this+ # overlay. padding_mask_crop already overlays with the blurred mask.+ if inpaint_padding_applied is None and init_pil is not None:+ soft_overlay = (init_pil, mask_pil)kwargs: dict[str, Any] = {# prompt / generator / num_images_per_prompt are set per chunk below, one torch.Generator PER@@ -12490,6 +12522,8 @@ class DiffusionBackend:kwargs["output_resolution"] = ref_resolutionif mask_pil is not None and "mask_image" in call_params:kwargs["mask_image"] = mask_pil+ if inpaint_padding_applied is not None:+ kwargs["padding_mask_crop"] = inpaint_padding_appliedif strength is not None and "strength" in call_params:kwargs["strength"] = strength# width/height: txt2img uses the slider; image-conditioned pipes must use the INPUT IMAGE's size or@@ -12931,6 +12965,8 @@ class DiffusionBackend:images.extend(layers_out)per_image_seeds.extend(s for _ in layers_out)else:+ if soft_overlay is not None:+ out = [overlay_with_mask(o, *soft_overlay) for o in out]images.extend(out)per_image_seeds.extend(s for _, s in chunk)chunk_shapes.append(len(chunk))@@ -13052,6 +13088,10 @@ class DiffusionBackend:if swapped is not None and sampler != DEFAULT_SAMPLERelse None,"schedule_type": resolved_schedule,+ # Recorded only when applied, so a plain inpaint recipe stays unchanged.+ "mask_blur": mask_blur_applied,+ "inpaint_only_masked": True if inpaint_padding_applied is not None else None,+ "inpaint_padding": inpaint_padding_applied,}logger.info("diffusion.generated: %s",@@ -13388,6 +13428,9 @@ class DiffusionBackend:# Workflows the loaded family supports, so the UI can gate its tabs."workflows": _family_workflows(state.family),"supports_negative_prompt": state.family.uses_negative_prompt,+ "supports_inpaint_only_masked": inpaint_class_accepts_padding_mask_crop(+ getattr(state.family, "inpaint_pipeline_class", None)+ ),"negative_prompt_min_guidance": _negative_prompt_guidance_threshold(state.family),"supports_guidance": _guidance_supported(state),"supports_live_preview": _live_preview_available(state),diff --git a/studio/backend/core/inference/diffusion_mask.py b/studio/backend/core/inference/diffusion_mask.pynew file mode 100644index 00000000000..d9236b6f6a0--- /dev/null+++ b/studio/backend/core/inference/diffusion_mask.py@@ -0,0 +1,80 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Inpaint mask settings: AUTOMATIC1111's "Mask blur" and "Inpaint area: Only masked" (diffusers padding_mask_crop).++Unset / 0 / False leave the request exactly as before."""++from __future__ import annotations++import inspect+from typing import Any, Optional++# A1111's "Only masked padding, pixels" default.+DEFAULT_INPAINT_PADDING = 32++ONLY_MASKED_UNSUPPORTED_MSG = (+ "Inpaint area 'Only masked' is not supported by this model's inpaint pipeline."+)+++def blur_mask(mask: Any, radius: Optional[int]) -> Any:+ """``mask`` blurred by ``radius`` px; the same object when the radius is unset or 0."""+ if not radius or int(radius) <= 0:+ return mask+ from PIL import ImageFilter++ return mask.filter(ImageFilter.GaussianBlur(int(radius)))+++def mask_is_empty(mask: Any) -> bool:+ """No nonzero pixel: diffusers' get_crop_region would find a zero-area box."""+ return mask.convert("L").getbbox() is None+++def overlay_with_mask(image: Any, source: Any, mask: Any) -> Any:+ """``image`` pasted over ``source`` through the (blurred) ``mask``, as A1111's apply_overlay does.++ Inpaint pipelines binarize the mask they are handed, so without this a blur only moves the hard edge.+ A non-PIL output (a latent or tensor return) is returned unchanged."""+ from PIL import Image++ if not isinstance(image, Image.Image):+ return image+ size = image.size+ if source.size != size:+ source = source.resize(size, Image.LANCZOS)+ if mask.size != size:+ mask = mask.resize(size, Image.BILINEAR)+ mode = image.mode+ out = Image.composite(image.convert("RGB"), source.convert("RGB"), mask.convert("L"))+ return out if mode == "RGB" else out.convert(mode)+++def resolve_padding(only_masked: Optional[bool], padding: Optional[int]) -> Optional[int]:+ """The ``padding_mask_crop`` value, or None when "Only masked" is off."""+ if not only_masked:+ return None+ return DEFAULT_INPAINT_PADDING if padding is None else int(padding)+++def pipeline_accepts_padding_mask_crop(pipeline_cls: Any) -> bool:+ call = getattr(pipeline_cls, "__call__", None)+ if call is None:+ return False+ try:+ return "padding_mask_crop" in inspect.signature(call).parameters+ except (TypeError, ValueError):+ return False+++def inpaint_class_accepts_padding_mask_crop(class_name: Optional[str]) -> bool:+ """Whether the diffusers inpaint pipeline named ``class_name`` takes ``padding_mask_crop``."""+ if not class_name:+ return False+ try:+ import diffusers+ cls = getattr(diffusers, class_name, None)+ except Exception: # noqa: BLE001 - a status read must not fail on an import+ return False+ return cls is not None and pipeline_accepts_padding_mask_crop(cls)diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.pyindex aa01968ef6a..bc5ee4179ea 100644--- a/studio/backend/core/inference/image_gallery.py+++ b/studio/backend/core/inference/image_gallery.py@@ -75,6 +75,13 @@ def _params_text(meta: dict[str, Any]) -> str:)if meta.get("workflow") in _IMG2IMG_WORKFLOWS and meta.get("strength") is not None:fields += f", Denoising strength: {meta['strength']}"+ # A1111 inpaint keys (modules/processing.py), only when this inpaint applied them.+ if meta.get("mask_blur"):+ fields += f", Mask blur: {meta['mask_blur']}"+ if meta.get("inpaint_only_masked"):+ fields += ", Inpaint area: Only masked"+ if meta.get("inpaint_padding") is not None:+ fields += f", Masked area padding: {meta['inpaint_padding']}"if meta.get("generator"):fields += f", Version: {meta['generator']}"lines.append(fields)diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 71f8b507ba7..ad2b7808d7c 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -5070,6 +5070,26 @@ class DiffusionGenerateRequest(BaseModel):description = "Noise schedule for the sampler. Omitted or 'automatic' uses the sampler's ""usual schedule (Karras for DPM++ 2M, Exponential for DPM++ 2M SDE, else the model's).",)+ mask_blur: Optional[int] = Field(+ None,+ ge = 0,+ le = 64,+ description = "Inpaint only: Gaussian blur radius (px) applied to the mask before inpainting "+ "(AUTOMATIC1111 'Mask blur'). Omitted or 0 uses the mask as painted.",+ )+ inpaint_only_masked: Optional[bool] = Field(+ None,+ description = "Inpaint only: render just the masked region (plus `inpaint_padding`) at full "+ "resolution and paste it back (AUTOMATIC1111 'Inpaint area: Only masked', diffusers "+ "padding_mask_crop). Requires status `supports_inpaint_only_masked`; omitted or false "+ "inpaints the whole picture.",+ )+ inpaint_padding: Optional[int] = Field(+ None,+ ge = 0,+ le = 256,+ description = "Padding (px) around the mask when `inpaint_only_masked` is set; omitted = 32.",+ )provider_id: Optional[str] = Field(None,description = "[x-unsloth] Saved connection ID. When set, the prompt goes to that "@@ -5262,6 +5282,16 @@ class GalleryImage(BaseModel):schedule_type: Optional[str] = Field(None, description = "Schedule type the sampler ran with (resolved); null = the config's")+ mask_blur: Optional[int] = Field(+ None, description = "Inpaint mask blur radius (px) applied; null = none"+ )+ inpaint_only_masked: Optional[bool] = Field(+ None,+ description = "True when the inpaint rendered only the masked area; null = whole picture",+ )+ inpaint_padding: Optional[int] = Field(+ None, description = "Padding (px) around the mask for an only-masked inpaint"+ )created_at: float = Field(..., description = "Creation time (epoch seconds)")# Library state, not recipe: stored beside the PNG, so older files simply read as unset.pinned: bool = Field(False, description = "Pinned to the front of the gallery")@@ -5693,6 +5723,12 @@ class DiffusionStatusResponse(BaseModel):"picker's enabled state). Diffusers only, for families with a ControlNet pipeline; False ""for the native engine, GGUF-via-diffusers, and torchao fp8/int8 dense.",)+ supports_inpaint_only_masked: bool = Field(+ False,+ description = "Whether the loaded model's inpaint pipeline can render only the masked area "+ "(`inpaint_only_masked`, diffusers padding_mask_crop). Diffusers only; False for the "+ "native and MLX engines and when nothing is loaded.",+ )supports_negative_prompt: bool = Field(True,description = "Whether the loaded model applies a negative prompt on this engine "diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex c6b8439d4c3..576fc7c0e2a 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -51905,6 +51905,21 @@ def _sampler_kwargs(generate: Any, sampler: Optional[str], schedule_type: Optionreturn {}+def _inpaint_mask_kwargs(generate: Any, request: Any) -> dict:+ """Inpaint mask kwargs generate() accepts; only the set ones, so an untouched request is unchanged."""+ try:+ import inspect+ params = inspect.signature(generate).parameters+ except (TypeError, ValueError):+ return {}+ out = {}+ for name in ("mask_blur", "inpaint_only_masked", "inpaint_padding"):+ value = getattr(request, name, None)+ if value is not None and name in params:+ out[name] = value+ return out++# Count of finished generations still writing their PNG/gallery records; generate-progress reports active while above 0. Mutated only on the event loop, so no lock._diffusion_persist_active = 0@@ -52008,6 +52023,9 @@ async def _external_image_generation(or body.localized_editor body.sampleror body.schedule_type+ or body.mask_blur is not None+ or body.inpaint_only_masked is not None+ or body.inpaint_padding is not None):raise HTTPException(status_code = 400,@@ -52347,6 +52365,7 @@ async def _generate_diffusion_image_run(),**_live_preview_kwarg(backend.generate, request.live_preview),**_sampler_kwargs(backend.generate, request.sampler, request.schedule_type),+ **_inpaint_mask_kwargs(backend.generate, request),)breakexcept ImageActivationShortfallError as exc:@@ -52464,6 +52483,11 @@ async def _generate_diffusion_image_run("localized_edit": result.get("localized_edit"),"sampler": result.get("sampler"),"schedule_type": result.get("schedule_type"),+ **{+ k: result[k]+ for k in ("mask_blur", "inpaint_only_masked", "inpaint_padding")+ if result.get(k) is not None+ },"created_at": created_at,},)diff --git a/studio/backend/tests/test_diffusion_inpaint_mask.py b/studio/backend/tests/test_diffusion_inpaint_mask.pynew file mode 100644index 00000000000..7966e32106c--- /dev/null+++ b/studio/backend/tests/test_diffusion_inpaint_mask.py@@ -0,0 +1,400 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Inpaint "Mask blur" and "Inpaint area: Only masked" (AUTOMATIC1111 semantics), no GPU."""++from __future__ import annotations++import inspect+import sys+import types+from pathlib import Path++import pytest+from pydantic import ValidationError++from core.inference import diffusion_mask+from models.inference import DiffusionGenerateRequest, DiffusionStatusResponse, GalleryImage++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++from test_diffusion_backend import ( # noqa: E402,F401+ _FakeInpaintPipe,+ _FakeInpaintPipeline,+ _loaded_backend,+ _tiny_mask_b64,+ _tiny_png_b64,+ fake_runtime,+)+from test_diffusion_routes import client # noqa: E402,F401 (fixture)+++def _mask():+ from PIL import Image++ img = Image.new("L", (64, 64), 0)+ img.paste(255, (16, 16, 48, 48))+ return img+++def test_blur_mask_none_and_zero_return_the_same_object():+ m = _mask()+ assert diffusion_mask.blur_mask(m, None) is m+ assert diffusion_mask.blur_mask(m, 0) is m+++def test_blur_mask_matches_diffusers_blur():+ from PIL import ImageFilter++ m = _mask()+ out = diffusion_mask.blur_mask(m, 4)+ assert out.size == m.size and out.mode == "L"+ # diffusers VaeImageProcessor.blur is exactly PIL GaussianBlur(radius).+ assert out.tobytes() == m.filter(ImageFilter.GaussianBlur(4)).tobytes()+ assert out.tobytes() != m.tobytes()+++def test_resolve_padding():+ assert diffusion_mask.resolve_padding(None, None) is None+ assert diffusion_mask.resolve_padding(False, 64) is None+ assert diffusion_mask.resolve_padding(True, None) == 32+ assert diffusion_mask.resolve_padding(True, 0) == 0+ assert diffusion_mask.resolve_padding(True, 100) == 100+++def test_padding_mask_crop_signature_probe():+ class With:+ def __call__(+ self,+ prompt = None,+ padding_mask_crop = None,+ ):+ pass++ class Without:+ def __call__(+ self,+ prompt = None,+ **kwargs,+ ):+ pass++ assert diffusion_mask.pipeline_accepts_padding_mask_crop(With)+ assert not diffusion_mask.pipeline_accepts_padding_mask_crop(Without)+ assert not diffusion_mask.inpaint_class_accepts_padding_mask_crop(None)+ assert not diffusion_mask.inpaint_class_accepts_padding_mask_crop("NoSuchPipelineClass")+++def test_request_fields_default_none_and_bounds():+ req = DiffusionGenerateRequest(prompt = "x")+ assert req.mask_blur is None and req.inpaint_only_masked is None and req.inpaint_padding is None+ ok = DiffusionGenerateRequest(+ prompt = "x", mask_blur = 64, inpaint_only_masked = True, inpaint_padding = 256+ )+ assert (ok.mask_blur, ok.inpaint_only_masked, ok.inpaint_padding) == (64, True, 256)+ DiffusionGenerateRequest(prompt = "x", mask_blur = 0, inpaint_padding = 0)+ for bad in (+ {"mask_blur": -1},+ {"mask_blur": 65},+ {"inpaint_padding": -1},+ {"inpaint_padding": 257},+ ):+ with pytest.raises(ValidationError):+ DiffusionGenerateRequest(prompt = "x", **bad)+++def test_status_and_gallery_models_carry_the_fields():+ assert DiffusionStatusResponse.model_fields["supports_inpaint_only_masked"].default is False+ for name in ("mask_blur", "inpaint_only_masked", "inpaint_padding"):+ assert GalleryImage.model_fields[name].default is None+++def test_route_forwards_only_set_fields():+ from routes.inference import _inpaint_mask_kwargs++ def diffusers_generate(+ prompt,+ mask_blur = None,+ inpaint_only_masked = None,+ inpaint_padding = None,+ ):+ pass++ def native_generate(prompt, mask_image = None):+ pass++ unset = DiffusionGenerateRequest(prompt = "x")+ assert _inpaint_mask_kwargs(diffusers_generate, unset) == {}+ full = DiffusionGenerateRequest(+ prompt = "x", mask_blur = 4, inpaint_only_masked = True, inpaint_padding = 16+ )+ assert _inpaint_mask_kwargs(diffusers_generate, full) == {+ "mask_blur": 4,+ "inpaint_only_masked": True,+ "inpaint_padding": 16,+ }+ assert _inpaint_mask_kwargs(native_generate, full) == {}+++def test_a1111_parameters_text():+ from core.inference.image_gallery import _params_text++ base = {+ "prompt": "p",+ "steps": 4,+ "guidance": 5,+ "seed": 1,+ "width": 64,+ "height": 64,+ "workflow": "inpaint",+ "strength": 0.8,+ }+ plain = _params_text(base)+ assert "Mask blur" not in plain and "Inpaint area" not in plain+ text = _params_text(+ {**base, "mask_blur": 4, "inpaint_only_masked": True, "inpaint_padding": 32}+ )+ assert "Mask blur: 4, Inpaint area: Only masked, Masked area padding: 32" in text+++class _CropInpaintPipe(_FakeInpaintPipe):+ def __call__(+ self,+ *,+ prompt = None,+ image = None,+ mask_image = None,+ padding_mask_crop = None,+ **kw,+ ):+ return super().__call__(+ prompt = prompt,+ image = image,+ mask_image = mask_image,+ padding_mask_crop = padding_mask_crop,+ **kw,+ )+++class _CropInpaintPipeline(_FakeInpaintPipeline):+ __call__ = _CropInpaintPipe.__call__++ @classmethod+ def from_pipe(cls, base_pipe, **kwargs):+ _FakeInpaintPipeline.from_pipe(base_pipe, **kwargs)+ return _CropInpaintPipe()+++def _inpaint(backend, **extra):+ return backend.generate(+ prompt = "a red door",+ steps = 4,+ guidance = 0.0,+ seed = 5,+ init_image = _tiny_png_b64(),+ mask_image = _tiny_mask_b64(),+ strength = 0.7,+ **extra,+ )+++def _call():+ call = dict(_FakeInpaintPipe.last_kwargs)+ return call, call["mask_image"].tobytes()+++def test_unset_none_zero_false_keep_the_plain_inpaint_call(fake_runtime, tmp_path):+ backend = _loaded_backend(tmp_path)+ out = _inpaint(backend)+ plain, plain_mask = _call()+ assert "padding_mask_crop" not in plain+ assert out["mask_blur"] is None and out["inpaint_only_masked"] is None+ assert out["inpaint_padding"] is None+ for extra in (+ {"mask_blur": None, "inpaint_only_masked": None, "inpaint_padding": None},+ {"mask_blur": 0, "inpaint_only_masked": False, "inpaint_padding": 64},+ ):+ out = _inpaint(backend, **extra)+ call, mask = _call()+ assert mask == plain_mask+ assert set(call) == set(plain)+ assert out["mask_blur"] is None and out["inpaint_padding"] is None+++def test_mask_blur_blurs_the_mask_handed_to_the_pipeline(fake_runtime, tmp_path):+ from PIL import ImageFilter++ backend = _loaded_backend(tmp_path)+ _inpaint(backend)+ _, plain_mask = _call()+ plain_img = _FakeInpaintPipe.last_kwargs["mask_image"]+ out = _inpaint(backend, mask_blur = 4)+ _, blurred = _call()+ assert blurred != plain_mask+ assert blurred == plain_img.filter(ImageFilter.GaussianBlur(4)).tobytes()+ assert out["mask_blur"] == 4+++def test_mask_settings_ignored_outside_inpaint(fake_runtime, tmp_path):+ backend = _loaded_backend(tmp_path)+ out = backend.generate(+ prompt = "x", steps = 4, mask_blur = 8, inpaint_only_masked = True, inpaint_padding = 8+ )+ assert out["mask_blur"] is None and out["inpaint_only_masked"] is None+++def test_only_masked_refused_when_the_pipeline_cannot_crop(fake_runtime, tmp_path):+ backend = _loaded_backend(tmp_path)+ assert "padding_mask_crop" not in inspect.signature(_FakeInpaintPipe.__call__).parameters+ assert backend.status()["supports_inpaint_only_masked"] is False+ with pytest.raises(ValueError, match = "Only masked"):+ _inpaint(backend, inpaint_only_masked = True)+++def test_only_masked_passes_padding_mask_crop(fake_runtime, tmp_path, monkeypatch):+ import diffusers++ # generate() resolves the family's inpaint class by name; the status probe reads its __call__.+ monkeypatch.setattr(diffusers, "ZImageInpaintPipeline", _CropInpaintPipeline, raising = False)+ backend = _loaded_backend(tmp_path)+ assert backend.status()["supports_inpaint_only_masked"] is True+ out = _inpaint(backend, inpaint_only_masked = True)+ assert _FakeInpaintPipe.last_kwargs["padding_mask_crop"] == 32+ assert (out["inpaint_only_masked"], out["inpaint_padding"]) == (True, 32)+ out = _inpaint(backend, inpaint_only_masked = True, inpaint_padding = 0)+ assert _FakeInpaintPipe.last_kwargs["padding_mask_crop"] == 0+ out = _inpaint(backend, inpaint_only_masked = False, inpaint_padding = 50)+ assert _FakeInpaintPipe.last_kwargs.get("padding_mask_crop") is None+ assert out["inpaint_only_masked"] is None+++def test_status_flag_false_when_nothing_loaded():+ from core.inference.diffusion import DiffusionBackend+ assert DiffusionBackend().status().get("supports_inpaint_only_masked", False) is False+++ "field", [{"mask_blur": 4}, {"inpaint_only_masked": True}, {"inpaint_padding": 48}]+)+def test_external_connection_refuses_inpaint_mask_fields(client, monkeypatch, field):+ import routes.inference as inference_routes++ looked_up = []+ monkeypatch.setattr(+ inference_routes.providers_db, "get_provider", lambda pid: looked_up.append(pid)+ )+ response = client.post(+ "/api/inference/images/generate",+ json = {"prompt": "p", "provider_id": "openai-1", "model": "gpt-image-1", **field},+ )+ assert response.status_code == 400, response.text+ assert response.json()["detail"] == "An external image connection only supports text to image."+ assert looked_up == []+++class _PilInpaintPipe(_FakeInpaintPipe):+ """Returns a solid green picture over the whole canvas, as a pipeline with no overlay does."""++ def __call__(self, **kw):+ from PIL import Image++ super().__call__(**kw)+ n = kw.get("num_images_per_prompt", 1)+ size = kw["image"].size+ return types.SimpleNamespace(images = [Image.new("RGB", size, (0, 200, 0)) for _ in range(n)])+++class _PilInpaintPipeline(_FakeInpaintPipeline):+ __call__ = _PilInpaintPipe.__call__++ @classmethod+ def from_pipe(cls, base_pipe, **kwargs):+ _FakeInpaintPipeline.from_pipe(base_pipe, **kwargs)+ return _PilInpaintPipe()+++class _PilCropInpaintPipe(_PilInpaintPipe):+ def __call__(+ self,+ *,+ padding_mask_crop = None,+ **kw,+ ):+ return super().__call__(padding_mask_crop = padding_mask_crop, **kw)+++class _PilCropInpaintPipeline(_FakeInpaintPipeline):+ __call__ = _PilCropInpaintPipe.__call__++ @classmethod+ def from_pipe(cls, base_pipe, **kwargs):+ _FakeInpaintPipeline.from_pipe(base_pipe, **kwargs)+ return _PilCropInpaintPipe()+++def test_mask_blur_pastes_the_render_back_through_the_soft_mask(+ fake_runtime, tmp_path, monkeypatch+):+ import diffusers++ # Real inpaint pipelines binarize mask_image, so the soft edge only reaches the picture through the overlay.+ monkeypatch.setattr(diffusers, "ZImageInpaintPipeline", _PilInpaintPipeline, raising = False)+ backend = _loaded_backend(tmp_path)+ out = _inpaint(backend, mask_blur = 4)+ img = out["images"][0]+ source, render = (120, 30, 30), (0, 200, 0)+ # Mask square is x, y in [16, 48): far outside keeps the source, the centre is the render.+ assert img.getpixel((2, 2)) == source+ assert img.getpixel((32, 32)) == render+ edge = img.getpixel((15, 32))+ assert edge not in (source, render)+ assert render[1] > edge[1] > source[1] and source[0] > edge[0] > render[0]+ assert out["mask_blur"] == 4+ # Unblurred inpaint is unchanged: the pipeline's own output comes back as is.+ plain = _inpaint(backend)["images"][0]+ assert plain.getpixel((2, 2)) == render+++def test_only_masked_with_blur_is_not_overlaid_twice(fake_runtime, tmp_path, monkeypatch):+ import diffusers++ # padding_mask_crop already pastes back through the blurred mask inside the pipeline.+ monkeypatch.setattr(diffusers, "ZImageInpaintPipeline", _PilCropInpaintPipeline, raising = False)+ backend = _loaded_backend(tmp_path)+ out = _inpaint(backend, mask_blur = 4, inpaint_only_masked = True)+ assert _FakeInpaintPipe.last_kwargs["padding_mask_crop"] == 32+ assert out["images"][0].getpixel((2, 2)) == (0, 200, 0)+++def test_only_masked_with_an_empty_mask_runs_as_a_plain_inpaint(+ fake_runtime, tmp_path, monkeypatch+):+ import base64+ import io++ import diffusers+ from PIL import Image++ # diffusers' crop region needs a nonzero mask pixel; an all-black mask would fail before denoising.+ monkeypatch.setattr(diffusers, "ZImageInpaintPipeline", _CropInpaintPipeline, raising = False)+ backend = _loaded_backend(tmp_path)+ buf = io.BytesIO()+ Image.new("L", (64, 64), 0).save(buf, format = "PNG")+ out = backend.generate(+ prompt = "a red door",+ steps = 4,+ guidance = 0.0,+ seed = 5,+ init_image = _tiny_png_b64(),+ mask_image = base64.b64encode(buf.getvalue()).decode(),+ strength = 0.7,+ inpaint_only_masked = True,+ mask_blur = 4,+ )+ assert _FakeInpaintPipe.last_kwargs.get("padding_mask_crop") is None+ assert out["inpaint_only_masked"] is None and out["inpaint_padding"] is None+ # A painted mask still crops.+ _inpaint(backend, inpaint_only_masked = True)+ assert _FakeInpaintPipe.last_kwargs["padding_mask_crop"] == 32diff --git a/studio/backend/tests/test_diffusion_inpaint_mask_sdxl.py b/studio/backend/tests/test_diffusion_inpaint_mask_sdxl.pynew file mode 100644index 00000000000..23880398076--- /dev/null+++ b/studio/backend/tests/test_diffusion_inpaint_mask_sdxl.py@@ -0,0 +1,205 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Inpaint "Mask blur" / "Only masked" through Studio's real diffusers backend with tiny SDXL."""++from __future__ import annotations++import base64+import functools+import io+import sys+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")+diffusers = pytest.importorskip("diffusers")+np = pytest.importorskip("numpy")++from PIL import Image, ImageFilter # noqa: E402++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++TINY_SDXL = "hf-internal-testing/tiny-stable-diffusion-xl-pipe"+SIZE = 128+++def _b64(img) -> str:+ buf = io.BytesIO()+ img.save(buf, format = "PNG")+ return base64.b64encode(buf.getvalue()).decode()+++def _source():+ arr = np.zeros((SIZE, SIZE, 3), dtype = np.uint8)+ arr[..., 0] = np.linspace(0, 255, SIZE, dtype = np.uint8)[None, :]+ arr[..., 1] = np.linspace(255, 0, SIZE, dtype = np.uint8)[:, None]+ arr[..., 2] = 90+ return Image.fromarray(arr, "RGB")+++def _mask():+ m = Image.new("L", (SIZE, SIZE), 0)+ m.paste(255, (40, 48, 72, 80))+ return m++[email protected](scope = "module")+def backend():+ from conftest import allow_outbound+ from huggingface_hub import snapshot_download++ try:+ path = snapshot_download(TINY_SDXL, local_files_only = True)+ except Exception: # noqa: BLE001+ try:+ with allow_outbound():+ path = snapshot_download(TINY_SDXL)+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"tiny SDXL pipeline not reachable: {exc}")+ from core.inference.diffusion import DiffusionBackend++ b = DiffusionBackend()+ # Eager: Speed=Auto compiles from the 3rd image, whose kernels round differently from eager.+ b.load_pipeline(path, family_override = "sdxl", speed_mode = "off")+ yield b+ b.unload()+++def spy(monkeypatch):+ """Record every StableDiffusionXLInpaintPipeline call's mask + padding_mask_crop; wraps keeps the signature."""+ calls = []+ cls = diffusers.StableDiffusionXLInpaintPipeline+ original = cls.__call__++ @functools.wraps(original)+ def recording(self, *args, **kwargs):+ calls.append(+ {+ "mask": np.array(kwargs.get("mask_image")).copy(),+ "padding_mask_crop": kwargs.get("padding_mask_crop", "absent"),+ }+ )+ return original(self, *args, **kwargs)++ monkeypatch.setattr(cls, "__call__", recording)+ return calls+++def _render(backend, **extra):+ out = backend.generate(+ prompt = "a red door",+ steps = 3,+ guidance = 5.0,+ seed = 7,+ init_image = _b64(_source()),+ mask_image = _b64(_mask()),+ strength = 0.9,+ **extra,+ )+ assert out["workflow"] == "inpaint"+ return out, np.asarray(out["images"][0].convert("RGB"), dtype = np.int16)+++def test_status_reports_only_masked(backend):+ st = backend.status()+ assert "inpaint" in st["workflows"]+ assert st["supports_inpaint_only_masked"] is True+++def test_unset_none_zero_false_are_bit_identical(backend, spy):+ out, ref = _render(backend)+ assert out["mask_blur"] is None and out["inpaint_only_masked"] is None+ assert spy[-1]["padding_mask_crop"] == "absent"+ ref_mask = spy[-1]["mask"]+ # A/A: the same request twice is bit-identical, so any difference below is the setting.+ _, again = _render(backend)+ assert np.array_equal(again, ref)+ for extra in (+ {"mask_blur": None, "inpaint_only_masked": None, "inpaint_padding": None},+ {"mask_blur": 0, "inpaint_only_masked": False, "inpaint_padding": 64},+ ):+ _, img = _render(backend, **extra)+ assert np.array_equal(img, ref), extra+ assert np.array_equal(spy[-1]["mask"], ref_mask)+ assert spy[-1]["padding_mask_crop"] == "absent"+++def test_mask_blur_changes_mask_and_output(backend, spy):+ _, ref = _render(backend)+ ref_mask = spy[-1]["mask"]+ out, img = _render(backend, mask_blur = 8)+ blurred = spy[-1]["mask"]+ assert out["mask_blur"] == 8+ assert not np.array_equal(blurred, ref_mask)+ assert len(np.unique(ref_mask)) == 2 and len(np.unique(blurred)) > 2+ assert img.shape == ref.shape+ assert int(np.abs(img - ref).max()) > 0+++def test_only_masked_crops_and_keeps_source_size(backend, spy):+ _, ref = _render(backend)+ out, img = _render(backend, inpaint_only_masked = True)+ assert spy[-1]["padding_mask_crop"] == 32+ assert (out["inpaint_only_masked"], out["inpaint_padding"]) == (True, 32)+ assert img.shape == (SIZE, SIZE, 3)+ assert int(np.abs(img - ref).max()) > 0+ src = np.asarray(_source(), dtype = np.int16)+ assert int(np.abs(img[:8, :8] - src[:8, :8]).max()) <= 2+ _, img16 = _render(backend, inpaint_only_masked = True, inpaint_padding = 16)+ assert spy[-1]["padding_mask_crop"] == 16+ assert not np.array_equal(img16, img)+++def test_only_masked_refused_when_pipeline_lacks_padding_mask_crop(backend, monkeypatch):+ cls = diffusers.StableDiffusionXLInpaintPipeline+ original = cls.__call__++ def no_crop(+ self,+ prompt = None,+ image = None,+ mask_image = None,+ **kwargs,+ ):+ return original(self, prompt = prompt, image = image, mask_image = mask_image, **kwargs)++ monkeypatch.setattr(cls, "__call__", no_crop)+ assert backend.status()["supports_inpaint_only_masked"] is False+ with pytest.raises(ValueError, match = "Only masked"):+ _render(backend, inpaint_only_masked = True)+++def test_mask_blur_feathers_the_render_into_the_source(backend, monkeypatch):+ # The pipeline binarizes mask_image, so the blur reaches the picture only through the overlay back onto the source.+ cls = diffusers.StableDiffusionXLInpaintPipeline+ original = cls.__call__+ raw = []++ @functools.wraps(original)+ def recording(self, *args, **kwargs):+ result = original(self, *args, **kwargs)+ raw.append(np.asarray(result.images[0].convert("RGB"), dtype = np.float64))+ return result++ monkeypatch.setattr(cls, "__call__", recording)+ _, ref = _render(backend)+ _, img = _render(backend, mask_blur = 8)+ src = np.asarray(_source(), dtype = np.float64)+ # Far from the mask the source survives; the plain render re-encodes it through the VAE.+ assert int(np.abs(img[:8, :8] - src[:8, :8]).max()) <= 2+ assert int(np.abs(ref[:8, :8] - src[:8, :8]).max()) > 2+ # Everywhere, A1111's apply_overlay: the render pasted over the source through the blurred mask.+ m = (np.asarray(_mask().filter(ImageFilter.GaussianBlur(8)), dtype = np.float64) / 255.0)[+ ..., None+ ]+ expected = m * raw[-1] + (1 - m) * src+ assert float(np.abs(img - expected).max()) <= 1.5+ # Just outside the painted square the mask is partial, so the pixel is a real mix of the two.+ y, x = 64, 36+ assert 0.05 < m[y, x, 0] < 0.5+ assert float(np.abs(raw[-1][y, x] - src[y, x]).max()) > 10diff --git a/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsxindex eb47c1f3f90..40fefbc1cf2 100644--- a/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx+++ b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx@@ -9,7 +9,14 @@ import {PopoverTrigger,} from "@/components/ui/popover";import { cn } from "@/lib/utils";-import { Bookmark, Check, ChevronDown, ImageUp, Trash2 } from "lucide-react";+import {+ Bookmark,+ Check,+ ChevronDown,+ ClipboardPaste,+ ImageUp,+ Trash2,+} from "lucide-react";import { Fragment, useState } from "react";import { DEFAULT_PRESET_NAME } from "./preset-policy";@@ -23,6 +30,7 @@ interface MediaGenerationPresetControlProps {onSave: (name: string) => Promise<string | null>;onDelete: () => Promise<boolean>;onImportFromImage?: () => void;+ onPasteParameters?: () => void;}export function MediaGenerationPresetControl({@@ -35,6 +43,7 @@ export function MediaGenerationPresetControl({onSave,onDelete,onImportFromImage,+ onPasteParameters,}: MediaGenerationPresetControlProps) {const [open, setOpen] = useState(false);const [draftName, setDraftName] = useState<string | null>(null);@@ -230,6 +239,20 @@ export function MediaGenerationPresetControl({Load settings from an image</button>) : null}+ {onPasteParameters ? (+ <button+ type="button"+ disabled={saving}+ onClick={() => {+ changeOpen(false);+ onPasteParameters();+ }}+ className="mt-1 flex h-8 w-full items-center justify-center gap-1.5 rounded-lg text-xs text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"+ >+ <ClipboardPaste className="size-3.5" />+ Paste generation parameters+ </button>+ ) : null}{activeIsCustom ? (<buttontype="button"diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex ab32b97f0f2..9f4186b480b 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -90,6 +90,8 @@ export interface DiffusionStatus {// Whether the loaded model can apply a ControlNet. Diffusers only, for families with a ControlNet pipeline.supports_controlnet?: boolean;supports_negative_prompt?: boolean;+ // Whether the loaded model's inpaint pipeline can crop to the mask (diffusers padding_mask_crop).+ supports_inpaint_only_masked?: boolean;// The guidance a negative prompt is used above; null when guidance does not gate it, absent on older backends.negative_prompt_min_guidance?: number | null;// False when the loaded model ignores guidance on this engine (FLUX.3 distilled on diffusers).@@ -242,6 +244,10 @@ export interface DiffusionGenerateRequest {init_image?: string;mask_image?: string;strength?: number;+ // Absent = today's behaviour; only_masked is refused (400) unless supports_inpaint_only_masked.+ mask_blur?: number;+ inpaint_only_masked?: boolean;+ inpaint_padding?: number;// Upscale (hires fix): factor > 1 with an init_image enlarges the source and re-denoises at low strength.upscale?: number;allow_oversized?: boolean;@@ -352,6 +358,9 @@ export interface GalleryImage {// The caption the prompt upsampler wrote and the model actually ran; `prompt` stays the user's text.enhanced_prompt?: string | null;prompt_enhancement?: PromptEnhancement | null;+ mask_blur?: number | null;+ inpaint_only_masked?: boolean | null;+ inpaint_padding?: number | null;created_at: number;// Library state, not recipe: stored beside the PNG, absent on records written before this existed.pinned?: boolean;diff --git a/studio/frontend/src/features/images/image-generation-defaults.ts b/studio/frontend/src/features/images/image-generation-defaults.tsindex a5c218a0a5b..31847f6ee10 100644--- a/studio/frontend/src/features/images/image-generation-defaults.ts+++ b/studio/frontend/src/features/images/image-generation-defaults.ts@@ -64,6 +64,17 @@ const MODEL_DEFAULTS: Array<{{ match: "sdxl", steps: 25, guidance: 7 },];+// The Steps slider's usual top, and the request's (DiffusionGenerateRequest.steps is 1-100).+export const STEPS_SLIDER_MAX = 50;+export const STEPS_REQUEST_MAX = 100;++/** Steps slider top: 50, widened to twice the model's default (Krea-2-raw ships 52) and to the+ * current value (an import or restore), never past what the request accepts. */+export function stepsSliderMax(modelDefault: number, current: number): number {+ const wanted = Math.max(STEPS_SLIDER_MAX, modelDefault * 2, current);+ return Math.min(STEPS_REQUEST_MAX, Number.isFinite(wanted) ? Math.ceil(wanted) : STEPS_SLIDER_MAX);+}+export function defaultsFor(repoId: string): {steps: number;guidance: number;diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 90a5d7be5d0..31b9b9100d8 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -20,6 +20,7 @@ import {ArrowUpDownIcon,Refresh01Icon,Delete02Icon,+ DiceFaces03Icon,Download01Icon,Edit03Icon,FolderAddIcon,@@ -138,6 +139,7 @@ import {restorePinOrder,serializeById,sortGalleryItems,+ subscribeArchiveChanged,subscribeGalleryChanged,} from "@/lib/gallery-flags";import {@@ -173,7 +175,7 @@ import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";import { formatBytes, formatEta } from "@/features/hub/lib/format";import { OnDeviceFoldersDialog } from "@/features/hub/catalog/on-device-folders-dialog";import { generatePhaseLabel, sameGenerateProgress } from "@/lib/media-generate-phase";-import { ChevronDown } from "lucide-react";+import { ChevronDown, Recycle } from "lucide-react";import { NegativePromptField, PROMPT_BOX_CLASS } from "@/components/negative-prompt-field";import {ASPECT_RATIOS,@@ -229,6 +231,7 @@ import {residentDefaultsKey,residentRecipeFor,resolutionFor,+ stepsSliderMax,} from "./image-generation-defaults";import {MIN_DIM,@@ -299,10 +302,30 @@ import {stopButtonLabel,} from "./lib/generation-stop";import { drawInfoStamp, infoStampText } from "./lib/info-stamp";+import { lastSeedOf, reusableSeed } from "./lib/seed-controls";+import { PasteParametersDialog } from "./paste-parameters-dialog";+import {+ INPAINT_PADDING_DEFAULT,+ INPAINT_PADDING_MAX,+ type InpaintMaskRequestFields,+ inpaintMaskRequestFields,+ MASK_BLUR_DEFAULT,+ MASK_BLUR_MAX,+ inpaintOptionsNotApplied,+ restoredInpaintMaskOptions,+} from "./lib/inpaint-options";import {copyPngTextChunks,+ type ImportedRecipe,importedRecipe,+ importNotApplied,+ isGenerationParametersPaste,+ loraTagNames,+ matchLoraTagsForImport,+ MAX_LORAS,+ lorasOverLimit,newerRecipeSchema,+ pastedParameters,pngRecipe,readEmbeddedRecipe,recipeSettings,@@ -419,6 +442,25 @@ function useImageModels(const labelOf = (labels: Record<string, string>, id: string) =>Object.hasOwn(labels, id) ? labels[id] : id;+// Identifies a loaded model for the once-per-model Only masked notice.+const onlyMaskedKeyOf = (s: DiffusionStatus): string => `${s.repo_id ?? ""}|${s.family ?? ""}`;+// The load an import started under: model plus the engine and build, so a reload of the same repo on+// another engine or quant counts as a change. Status carries no per-load id; an identical reload leaves+// the same LoRA catalog, so its matches stay valid.+const loadedModelKey = (s: DiffusionStatus | null): string | null =>+ s?.loaded+ ? JSON.stringify([+ s.repo_id,+ s.base_repo,+ s.family,+ s.engine,+ s.gguf_filename,+ s.dtype,+ s.transformer_quant,+ s.text_encoder_quant,+ ])+ : null;+const CONDITIONED_WORKFLOW_INPUTS: Record<string, string> = {img2img: "the source image",inpaint: "the source image and mask",@@ -1642,6 +1684,11 @@ export function ImagesPage({guidance: number;} | null>(null);const [seed, setSeed] = useState("");+ const [maskBlur, setMaskBlur] = useState(MASK_BLUR_DEFAULT);+ const [inpaintOnlyMasked, setInpaintOnlyMasked] = useState(false);+ const [inpaintPadding, setInpaintPadding] = useState(INPAINT_PADDING_DEFAULT);+ const [pasteOpen, setPasteOpen] = useState(false);+ const [pasteText, setPasteText] = useState("");// Batch size = images per forward pass (VRAM-heavy); count = sequential loops.const [batchSize, setBatchSize] = useState(1);const [count, setCount] = useState(1);@@ -1691,6 +1738,8 @@ export function ImagesPage({// LoRA adapters selected for the next generation (id + weight), plus the list the picker offers.const [loras, setLoras] = useState<LoraSpecInput[]>([]);const [availableLoras, setAvailableLoras] = useState<DiffusionLoraInfo[]>([]);+ // The family availableLoras was fetched for; undefined while none is current (loading, failed, no model).+ const [loraCatalogFamily, setLoraCatalogFamily] = useState<string | null | undefined>(undefined);// Fine-tuned (trained in Unsloth) first, for both the suggestions and the Add LoRA prefill.const sortedLoras = useMemo(() => [...availableLoras].sort((a, b) => Number(Boolean(b.fine_tuned)) - Number(Boolean(a.fine_tuned))),@@ -1817,6 +1866,35 @@ export function ImagesPage({const [images, setImages] = useState<GalleryImage[]>(() => galleryCache.images);const [hasMore, setHasMore] = useState(() => galleryCache.hasMore);const [selectedId, setSelectedId] = useState<string | null>(() => galleryCache.selectedId);+ // The base seed of this session's last run, for "Reuse last seed"; before one, the newest record's.+ const [sessionSeed, setSessionSeed] = useState<number | null>(null);+ // The strip lists active images only, so the gallery fallback also needs the archive to be empty: an+ // archived image may be the newest. Checked again whenever the strip changes (an archive drops a row).+ const [archivedEmpty, setArchivedEmpty] = useState<boolean | null>(null);+ // Bumped when the archive changes elsewhere (Settings restore or delete), which the strip may not show.+ const [archiveChangeKey, setArchiveChangeKey] = useState(0);+ useEffect(+ () => subscribeArchiveChanged("images", () => setArchiveChangeKey((k) => k + 1)),+ [],+ );+ useEffect(() => {+ if (sessionSeed !== null || hasMore) return;+ let cancelled = false;+ getGallery(0, 1, true)+ .then((page) => {+ if (!cancelled) setArchivedEmpty(page.images.length === 0);+ })+ .catch(() => {+ if (!cancelled) setArchivedEmpty(false);+ });+ return () => {+ cancelled = true;+ };+ }, [sessionSeed, hasMore, images.length, archiveChangeKey]);+ const lastSeed = useMemo(+ () => reusableSeed(sessionSeed, images, hasMore || archivedEmpty !== true),+ [sessionSeed, images, hasMore, archivedEmpty],+ );const [srcById, setSrcById] = useState<Record<string, string>>(() =>galleryCache.srcById.toRecord(),);@@ -2040,6 +2118,7 @@ export function ImagesPage({// Whether the load in flight baked the LoRA selection into the build (see handleLoad).const bakedLorasOnLoad = useRef(false);useEffect(() => {+ setLoraCatalogFamily(undefined);if (!loraCapable) {// Options are gone with the model, but keep the selection: it may have just been restored.setAvailableLoras([]);@@ -2067,7 +2146,9 @@ export function ImagesPage({let cancelled = false;listDiffusionLoras(status?.family ?? undefined).then((list) => {- if (!cancelled) setAvailableLoras(list);+ if (cancelled) return;+ setAvailableLoras(list);+ setLoraCatalogFamily(fam);}).catch(() => {// Clear only the OPTIONS on a failed catalog refresh: this free-text picker holds selections@@ -2717,6 +2798,10 @@ export function ImagesPage({else setStrength(image.strength);}if (typeof image.upscale === "number") setUpscaleFactor(image.upscale);+ const maskOptions = restoredInpaintMaskOptions(image);+ if (maskOptions.maskBlur !== undefined) setMaskBlur(maskOptions.maskBlur);+ if (maskOptions.onlyMasked !== undefined) setInpaintOnlyMasked(maskOptions.onlyMasked);+ if (maskOptions.padding !== undefined) setInpaintPadding(maskOptions.padding);// Conditioning images are not persisted, so every upload is cleared. Edit and Reference reopen// their own workflow, so Generate stays blocked until the inputs are supplied again instead of// replaying as text-to-image; the others return to Create.@@ -2761,22 +2846,59 @@ export function ImagesPage({// Like dropping an image on ComfyUI: Unsloth's recipe first, else AUTOMATIC1111 / ComfyUI metadata.const importFileRef = useRef<HTMLInputElement>(null);- const importSettingsFromFile = useCallback(- async (file: File | Uint8Array) => {- let recipe = null;- try {- const bytes = file instanceof Uint8Array ? file : new Uint8Array(await file.arrayBuffer());- recipe = importedRecipe(readEmbeddedRecipe(bytes));- } catch {- recipe = null;- }- if (!recipe) {- toast.error("No generation settings found in this image", {- description: "Images saved by Unsloth, ComfyUI, or tools that write a parameters block can be loaded.",- });- return;+ // Notified once per loaded model while Only masked is on but that model's pipeline cannot crop, so+ // the hidden switch never drops the setting silently, whatever turned it on or switched the model.+ const onlyMaskedNotified = useRef<string | null>(null);+ useEffect(() => {+ const key =+ status?.loaded && inpaintOnlyMasked && status.supports_inpaint_only_masked !== true+ ? onlyMaskedKeyOf(status)+ : null;+ if (key === null) {+ onlyMaskedNotified.current = null;+ return;+ }+ if (onlyMaskedNotified.current === key) return;+ onlyMaskedNotified.current = key;+ const missed = inpaintOptionsNotApplied(+ { inpaint_only_masked: true, inpaint_padding: inpaintPadding },+ false,+ );+ toast.warning("Some settings were not applied", {+ description: `Not applied: ${missed.join(", ")}. This model or build does not support them.`,+ });+ }, [status, inpaintOnlyMasked, inpaintPadding]);+ // A later import supersedes one still waiting on the LoRA lookup.+ const importSeq = useRef(0);+ // The status as of now, for an import resuming after its LoRA lookup.+ const statusRef = useRef(status);+ statusRef.current = status;+ const applyImportedRecipe = useCallback(+ async (recipe: ImportedRecipe): Promise<boolean> => {+ const seq = ++importSeq.current;+ const modelBefore = loadedModelKey(status);+ let tagged = await matchLoraTagsForImport(+ recipe.lora_tags,+ // Only a finished fetch for the loaded family: right after a load or family switch it is empty or stale.+ loraCapable && loraCatalogFamily === (status?.family ?? null),+ availableLoras,+ // A LoRA is family-specific, so a loaded model narrows the lookup like the picker does.+ () => listDiffusionLoras(status?.loaded ? (status.family ?? undefined) : undefined),+ );+ if (seq !== importSeq.current) return false;+ // A load or family switch landed during the lookup: its matches are for the old model.+ if (loadedModelKey(statusRef.current) !== modelBefore) {+ tagged = {+ loras: [],+ unmatched: [],+ notes: loraTagNames(recipe.lora_tags).map((n) => `LoRA ${n} (model changed during import)`),+ };}- const settings = recipeSettings(recipe, { width, height, steps, guidance });+ const merged =+ tagged.loras.length > 0+ ? { ...recipe, loras: [...(Array.isArray(recipe.loras) ? recipe.loras : []), ...tagged.loras] }+ : recipe;+ const settings = recipeSettings(merged, { width, height, steps, guidance });const localized = settings.localized_edit;restoreSettings({...settings,@@ -2811,7 +2933,17 @@ export function ImagesPage({);}}- const notApplied = unknownRecipeKeys(recipe);+ const notApplied = [+ ...importNotApplied(+ recipe,+ status?.loaded ? status.family : null,+ Boolean(status?.loaded && isNativeEngineStatus(status)),+ ),+ ...tagged.unmatched.map((name) => `LoRA ${name} (not installed)`),+ ...lorasOverLimit(merged).map((id) => `LoRA ${id} (over the ${MAX_LORAS} adapter limit)`),+ ...tagged.notes,+ ...unknownRecipeKeys(recipe),+ ];const baked = Array.isArray(recipe.baked_loras)? recipe.baked_loras.filter((x): x is string => typeof x === "string"): [];@@ -2822,6 +2954,12 @@ export function ImagesPage({if (status?.loaded && status.supports_lora === false && settings.loras.length > 0) {notApplied.unshift("LoRAs");}+ if (status?.loaded) {+ const missed = inpaintOptionsNotApplied(settings, status.supports_inpaint_only_masked === true);+ notApplied.unshift(...missed);+ // Named in this toast, so the Only masked effect does not repeat it for this model.+ if (missed.length > 0) onlyMaskedNotified.current = onlyMaskedKeyOf(status);+ }if (status?.supports_negative_prompt === false && settings.negative_prompt && settings.guidance > 0) {notApplied.unshift("negative prompt");}@@ -2852,8 +2990,41 @@ export function ImagesPage({: "This model or build does not support them."),});}+ return true;},- [restoreSettings, width, height, steps, guidance, status, samplerOptions],+ [restoreSettings, width, height, steps, guidance, status, samplerOptions, availableLoras, loraCapable, loraCatalogFamily],+ );+ const importSettingsFromFile = useCallback(+ async (file: File | Uint8Array) => {+ let recipe = null;+ try {+ const bytes = file instanceof Uint8Array ? file : new Uint8Array(await file.arrayBuffer());+ recipe = importedRecipe(readEmbeddedRecipe(bytes));+ } catch {+ recipe = null;+ }+ if (!recipe) {+ toast.error("No generation settings found in this image", {+ description: "Images saved by Unsloth, ComfyUI, or tools that write a parameters block can be loaded.",+ });+ return;+ }+ await applyImportedRecipe(recipe);+ },+ [applyImportedRecipe],+ );+ const importSettingsFromText = useCallback(+ async (text: string): Promise<boolean> => {+ const recipe = pastedParameters(text);+ if (!recipe) {+ toast.error("No generation parameters found in that text", {+ description: "Paste the prompt, the Negative prompt: line and the Steps: ... line as AUTOMATIC1111, Forge or Civitai copy them.",+ });+ return false;+ }+ return applyImportedRecipe(recipe);+ },+ [applyImportedRecipe],);// Desktop: Tauri delivers OS drops as paths and suppresses the DOM drop event.const importNativePath = useCallback(@@ -4908,6 +5079,7 @@ export function ImagesPage({let condStrength: number | undefined;let condUpscale: number | undefined;let condFields: ReturnType<typeof conditionedRequestFields> | undefined;+ let condInpaint: InpaintMaskRequestFields = {};try {if (isTransform) {condInit = initImage ?? undefined;@@ -4916,6 +5088,10 @@ export function ImagesPage({condInit = initImage ?? undefined;condMask = maskImage ?? undefined;condStrength = strength;+ condInpaint = inpaintMaskRequestFields(+ { maskBlur, onlyMasked: inpaintOnlyMasked, padding: inpaintPadding },+ status?.supports_inpaint_only_masked === true,+ );} else if (isExtend) {const built = await buildOutpaint(initImage!, extendSides, extendPct);condInit = built.image;@@ -5048,6 +5224,9 @@ export function ImagesPage({galleryCache.hasMore,knownIds,);+ // Offset runs by the batch size: the native engine seeds image j at seed+j, so a +1 offset+ // would regenerate batch-mates.+ const runBaseSeed = baseSeed + i * batchSize;let res: DiffusionGenerateResponse;try {res = await generateDiffusionImage({@@ -5058,15 +5237,14 @@ export function ImagesPage({height: h,steps,guidance: effectiveGuidance,- // Offset runs by the batch size: the native engine seeds image j at seed+j, so a +1 offset- // would regenerate batch-mates.- seed: baseSeed + i * batchSize,+ seed: runBaseSeed,batch_size: batchSize,// Transform/Inpaint/Extend send the source image (and mask) with a strength; the backend// derives output size from the image.init_image: condInit,mask_image: condMask,strength: condStrength,+ ...condInpaint,upscale: condUpscale,allow_oversized: allowOversizedSent ? true : undefined,live_preview: livePreview,@@ -5106,6 +5284,8 @@ export function ImagesPage({// loadGallery refreshes the module cache synchronously, so this run's records are folded in// before the next run.galleryCache.images.forEach((image) => knownIds.add(image.id));+ // The run landed without its records, so Reuse last seed takes the seed it was sent.+ if (!external) setSessionSeed(runBaseSeed);setGenDone(i + 1);continue;}@@ -5118,6 +5298,8 @@ export function ImagesPage({setImages((prev) => mergeGenerated(prev, res.images));res.images.forEach((image) => knownIds.add(image.id));if (res.images[0]) setSelectedId(res.images[0].id);+ const runSeed = lastSeedOf(res.images);+ if (runSeed !== null) setSessionSeed(runSeed);// Asked for enhancement and did not get it: say so once, without blocking the result.if (enhanceOn && upsamplerCapability.supported) {const notice = enhancementNotice(res.images[0]?.prompt_enhancement);@@ -5164,7 +5346,7 @@ export function ImagesPage({setGenStep(null);setStopping(false);}- }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeEngaged, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, width, height, steps, effectiveGuidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, multiImageEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);+ }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeEngaged, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, width, height, steps, effectiveGuidance, seed, batchSize, count, workflow, initImage, maskImage, strength, maskBlur, inpaintOnlyMasked, inpaintPadding, status?.supports_inpaint_only_masked, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, multiImageEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);// Stop the in-flight generation. Latch FIRST, so a multi-run request stops even if the POST// races the run that is already finishing.@@ -5717,8 +5899,16 @@ export function ImagesPage({onSave={imagePresets.savePreset}onDelete={imagePresets.deletePreset}onImportFromImage={() => importFileRef.current?.click()}+ onPasteParameters={() => setPasteOpen(true)}/>)}+ <PasteParametersDialog+ open={pasteOpen}+ onOpenChange={setPasteOpen}+ text={pasteText}+ onTextChange={setPasteText}+ onApply={importSettingsFromText}+ /></div>{workflow === "transform" && (@@ -5819,6 +6009,43 @@ export function ImagesPage({step={0.05}onChange={setStrength}/>+ <SliderField+ label="Mask blur"+ hint="Softens the mask edge by this many pixels so the repainted region blends into the source. 0 keeps the hard edge."+ value={maskBlur}+ min={0}+ max={MASK_BLUR_MAX}+ step={1}+ onChange={setMaskBlur}+ />+ {status?.supports_inpaint_only_masked && (+ <>+ <div className="flex items-center justify-between">+ <span className="flex items-center gap-1 text-xs font-medium text-muted-foreground">+ Only masked+ <InfoHint>+ Repaint just the masked area plus padding at full resolution, then paste it back. Sharper small edits on big images; the model sees less of the surroundings.+ </InfoHint>+ </span>+ <Switch+ checked={inpaintOnlyMasked}+ onCheckedChange={setInpaintOnlyMasked}+ aria-label="Only masked"+ />+ </div>+ {inpaintOnlyMasked && (+ <SliderField+ label="Padding"+ hint="Pixels of context kept around the mask when repainting only the masked area."+ value={inpaintPadding}+ min={0}+ max={INPAINT_PADDING_MAX}+ step={4}+ onChange={setInpaintPadding}+ />+ )}+ </>+ )}</>)}</>@@ -6157,6 +6384,14 @@ export function ImagesPage({setExamplesDismissed((prev) => ({ ...prev, [workflow]: true }));}}onChange={(e) => setPrompt(e.target.value)}+ onPaste={(e) => {+ // A whole AUTOMATIC1111 / Forge / Civitai block fills the form instead of the prompt.+ const text = e.clipboardData.getData("text/plain");+ if (isGenerationParametersPaste(text)) {+ e.preventDefault();+ void importSettingsFromText(text);+ }+ }}/></Field>{upsamplerCapability.supported && (@@ -6379,7 +6614,7 @@ export function ImagesPage({hint="Number of denoising steps. Start with the selected model's default; more steps take longer and may not improve quality."value={steps}min={1}- max={50}+ max={stepsSliderMax(pendingModelDefaults?.steps ?? residentSteps, steps)}step={1}onChange={setSteps}/>@@ -6469,11 +6704,40 @@ export function ImagesPage({hint="Leave empty for a fresh random seed each run."className="pt-2">- <Input- placeholder="Random if empty"- value={seed}- onChange={(e) => setSeed(e.target.value)}- />+ <div className="flex items-center gap-1.5">+ <Input+ placeholder="Random if empty"+ value={seed}+ onChange={(e) => setSeed(e.target.value)}+ className="flex-1"+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-8 shrink-0"+ aria-label="Random seed"+ title="Random seed each run"+ disabled={seed === ""}+ onClick={() => setSeed("")}+ >+ <HugeiconsIcon icon={DiceFaces03Icon} className="size-4" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-8 shrink-0"+ aria-label="Reuse last seed"+ title={lastSeed === null ? "No image generated yet" : `Reuse last seed (${lastSeed})`}+ disabled={lastSeed === null}+ onClick={() => {+ if (lastSeed !== null) setSeed(String(lastSeed));+ }}+ >+ <Recycle className="size-4" strokeWidth={1.5} />+ </Button>+ </div></Field><AdvancedDisclosure open={advancedOpen} onOpenChange={setAdvancedOpen}>diff --git a/studio/frontend/src/features/images/lib/image-metadata.ts b/studio/frontend/src/features/images/lib/image-metadata.tsindex e466d1c0c8b..2315765f925 100644--- a/studio/frontend/src/features/images/lib/image-metadata.ts+++ b/studio/frontend/src/features/images/lib/image-metadata.ts@@ -484,22 +484,247 @@ export interface ImportedRecipe {[key: string]: unknown;}-const A1111_FIELD =- /\s*([A-Za-z][A-Za-z0-9 _-]*):\s*("(?:\\.|[^"\\])*"|[^,]*)(?:,|$)/g;const SIZE = /^(\d+)\s*x\s*(\d+)$/i;+const A1111_KEY = /^([A-Za-z][\w \-/]*):\s*/;// An unknown label stays as written, so the import can name what it could not apply.const labelId = (labels: Record<string, string>, label: string) =>Object.keys(labels).find((id) => labels[id] === label) ?? label;-/** AUTOMATIC1111 `parameters` text: prompt, optional `Negative prompt:` line, then `Key: value, ...`. */+/** End of a JSON object / list starting at `at` (Civitai writes `Hashes: {...}` and+ * `Civitai resources: [...]` unquoted, commas inside), or -1 when it never closes. */+function jsonEnd(line: string, at: number): number {+ let depth = 0;+ let inString = false;+ for (let i = at; i < line.length; i++) {+ const c = line[i];+ if (inString) {+ if (c === "\\") i++;+ else if (c === '"') inString = false;+ } else if (c === '"') inString = true;+ else if (c === "{" || c === "[") depth++;+ else if (c === "}" || c === "]") {+ depth--;+ if (depth === 0) return i + 1;+ }+ }+ return -1;+}++/** `Key: value, ...` pairs of AUTOMATIC1111's settings line (`re_param`, modules/infotext_utils.py:16):+ * a quoted value is unquoted and may hold commas (`Lora hashes: "a: 1, b: 2"`); so may a JSON value. */+export function a1111Fields(line: string): Array<[string, string]> {+ const out: Array<[string, string]> = [];+ let i = 0;+ while (i < line.length) {+ while (i < line.length && (line[i] === "," || /\s/.test(line[i]))) i++;+ if (i >= line.length) break;+ const key = A1111_KEY.exec(line.slice(i));+ if (!key) {+ // Not a field (A1111's findall skips it too): resume after the next comma.+ const comma = line.indexOf(",", i);+ if (comma < 0) break;+ i = comma + 1;+ continue;+ }+ i += key[0].length;+ let value: string;+ if (line[i] === '"') {+ let j = i + 1;+ while (j < line.length && line[j] !== '"') j += line[j] === "\\" ? 2 : 1;+ const raw = line.slice(i, Math.min(j + 1, line.length));+ try {+ value = JSON.parse(raw) as string;+ } catch {+ value = raw.replace(/^"|"$/g, "");+ }+ i = j + 1;+ } else {+ const close = line[i] === "{" || line[i] === "[" ? jsonEnd(line, i) : -1;+ const comma = line.indexOf(",", i);+ const stop = close > 0 ? close : comma < 0 ? line.length : comma;+ value = line.slice(i, stop);+ i = stop;+ }+ out.push([key[1].trim(), value.trim()]);+ }+ return out;+}++// Keys that identify a file or the writer and set nothing: read, never reported as not applied.+export const A1111_INFO_KEYS: ReadonlySet<string> = new Set([+ "model hash",+ "vae hash",+ "lora hashes",+ "hashes",+ "version",+ "user",+ "civitai resources",+ "civitai metadata",+ "created date",+ "init image hash",+]);+// The names CFG rescale (Lin et al. 2023, diffusers guidance_rescale) is written under: the+// sd-webui-cfg-rescale extension, ComfyUI's RescaleCFG node, Forge's latent modifier field.+const CFG_RESCALE_KEYS = new Set([+ "cfg rescale",+ "cfg rescale phi",+ "rescalecfg",+ "rescale cfg",+ "cfg rescale multiplier",+ "cfgrescale",+ "latent_modifier_rescale_cfg_phi",+]);+// Extra-network tags AUTOMATIC1111 strips from the prompt before encoding (`re_extra_net`,+// modules/extra_networks.py:175); lora / lyco carry a LoRA, the rest Studio cannot load.+const EXTRA_NETWORK = /<(lora|lyco|locon|loha|lokr|hypernet):([^>]+)>/gi;++/** A `<lora:name:weight>` tag: positional `name[:te[:unet]]` or named `te=` / `unet=`+ * (extensions-builtin/Lora/extra_networks_lora.py:30-36, default weight 1). */+export interface LoraTag {+ name: string;+ weight: number;+ // Set when the U-Net multiplier differs from the text-encoder one: Studio has one weight.+ unet_weight?: number;+ // DyLoRA's dimension (`<lora:name:te:unet:dyn>` / `dyn=`): Studio cannot choose one.+ dyn_dim?: number;+}++function loraTag(body: string): LoraTag | null {+ const positional: string[] = [];+ const named: Record<string, string> = {};+ for (const item of body.split(":")) {+ const eq = item.indexOf("=");+ if (eq > 0) named[item.slice(0, eq).trim()] = item.slice(eq + 1).trim();+ else positional.push(item.trim());+ }+ const name = positional[0];+ if (!name) return null;+ const te = Number(named.te ?? positional[1] ?? 1);+ const weight = Number.isFinite(te) ? te : 1;+ const unet = Number(named.unet ?? positional[2] ?? weight);+ const tag: LoraTag =+ Number.isFinite(unet) && unet !== weight+ ? { name, weight, unet_weight: unet }+ : { name, weight };+ const dyn = Number(named.dyn ?? positional[3]);+ if (Number.isInteger(dyn) && dyn > 0) tag.dyn_dim = dyn;+ return tag;+}++export function extractExtraNetworks(prompt: string): {+ prompt: string;+ loras: LoraTag[];+ other: string[];+} {+ const loras: LoraTag[] = [];+ const other: string[] = [];+ let found = false;+ const stripped = prompt.replace(+ EXTRA_NETWORK,+ (tag, kind: string, body: string) => {+ found = true;+ const lower = kind.toLowerCase();+ const parsed = lower === "hypernet" ? null : loraTag(body);+ if (parsed) loras.push(parsed);+ else other.push(tag);+ return "";+ },+ );+ if (!found) return { prompt, loras, other };+ const tidy = stripped+ .split("\n")+ .map((line) =>+ line+ .replace(/[ \t]{2,}/g, " ")+ .replace(/\s*,(\s*,)+/g, ",")+ .replace(/^[\s,]+|[\s,]+$/g, ""),+ )+ .join("\n")+ .trim();+ return { prompt: tidy, loras, other };+}++const numberOf = (value: string): number | undefined => {+ const n = Number(value);+ return value !== "" && Number.isFinite(n) ? n : undefined;+};++const SETTINGS_KEYS = new Set([+ "steps",+ "sampler",+ "cfg scale",+ "seed",+ "size",+ "schedule type",+]);++// AUTOMATIC1111 takes the last line as settings when it has 3+ fields (infotext_utils.py:254-257);+// a known key is also required here, so a prompt line like "style: a, mood: b, light: c" stays a prompt.+function isSettingsLine(+ line: string,+ fields: Array<[string, string]>,+): boolean {+ return (+ /(^|,\s*)Steps:\s*\d+/.test(line) ||+ (fields.length >= 3 &&+ fields.some(([k]) => SETTINGS_KEYS.has(k.toLowerCase())))+ );+}++/** Requires A1111's settings line, else any text would parse as a bare prompt. */+export function pastedParameters(text: string): ImportedRecipe | null {+ const trimmed = text.trim();+ // A dynamic-prompts prompt (`{red|blue} car`) also starts with "{", so a failed JSON parse falls through.+ const json = trimmed.startsWith("{") ? recipeJson(trimmed) : null;+ if (json) return json;+ const last = trimmed.replace(/\r\n?/g, "\n").split("\n").pop() ?? "";+ return isSettingsLine(last, a1111Fields(last))+ ? parseA1111Parameters(trimmed)+ : null;+}++/** A prompt-box paste that is a whole parameters block (Steps line with seed, sampler or CFG). */+export function isGenerationParametersPaste(text: string): boolean {+ const last = text.trim().replace(/\r\n?/g, "\n").split("\n").pop() ?? "";+ const keys = new Set(a1111Fields(last).map(([k]) => k.toLowerCase()));+ return (+ /(^|,\s*)Steps:\s*\d+/.test(last) &&+ (keys.has("seed") || keys.has("sampler") || keys.has("cfg scale")) &&+ pastedParameters(text) !== null+ );+}++/** AUTOMATIC1111 / Forge / Civitai `parameters` text (modules/infotext_utils.py:234). */+/** The unescaped A1111 attention groups in `text`: `(x)`, `(x:1.2)`, `[x]`; `\(` and `\[` are literal. */+export function promptEmphasisGroups(text: string): string[] {+ const groups: string[] = [];+ const open: Array<{ ch: string; at: number }> = [];+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (ch === "\\") {+ i++;+ continue;+ }+ if (ch === "(" || ch === "[") open.push({ ch, at: i });+ else if ((ch === ")" || ch === "]") && open.length > 0) {+ const top = open[open.length - 1];+ if ((ch === ")") !== (top.ch === "(")) continue;+ open.pop();+ if (open.length === 0) groups.push(text.slice(top.at, i + 1));+ }+ }+ return groups;+}+export function parseA1111Parameters(text: string): ImportedRecipe | null {- const lines = text.replace(/\r\n/g, "\n").trim().split("\n");+ const lines = text.replace(/\r\n?/g, "\n").trim().split("\n");if (lines.length === 0) {return null;}const last = lines[lines.length - 1];- const hasSettings = /(^|,\s*)Steps:\s*\d+/.test(last);- const settingsLine = hasSettings ? (lines.pop() ?? "") : "";+ const fields = a1111Fields(last);+ const hasSettings = isSettingsLine(last, fields);+ if (hasSettings) lines.pop();const negativeAt = lines.findIndex((l) => l.startsWith("Negative prompt:"));const promptLines = negativeAt >= 0 ? lines.slice(0, negativeAt) : lines;const negative =@@ -509,23 +734,68 @@ export function parseA1111Parameters(text: string): ImportedRecipe | null {.join("\n").replace(/^Negative prompt:\s*/, ""): null;+ const networks = extractExtraNetworks(promptLines.join("\n").trim());const out: ImportedRecipe = {- prompt: promptLines.join("\n").trim(),+ prompt: networks.prompt,negative_prompt: negative,};+ if (networks.loras.length > 0) out.lora_tags = networks.loras;+ // Kept in the prompt as written; importNotApplied names it for an engine without an A1111 parser.+ const emphasis = [+ ...promptEmphasisGroups(networks.prompt),+ ...promptEmphasisGroups(negative ?? ""),+ ];+ if (emphasis.length > 0) out.prompt_emphasis = emphasis;+ // A1111 reads \( \) \[ \] as literal brackets; an engine without its parser keeps the backslash.+ const escaped = [+ ...new Set(`${networks.prompt}\n${negative ?? ""}`.match(/\\[()[\]]/g) ?? []),+ ];+ if (escaped.length > 0) out.prompt_escaped_brackets = escaped;+ const notApplied: string[] = networks.other.slice();+ const hires: Record<string, string> = {};let legacySchedule: string | undefined;- let hires = false;- for (const m of settingsLine.matchAll(A1111_FIELD)) {- const key = m[1].trim().toLowerCase();- const value = m[2].trim();- const num = Number(value);- if (key === "steps" && Number.isInteger(num)) out.steps = num;- else if (key === "cfg scale" && Number.isFinite(num)) out.guidance = num;- else if (key === "seed" && Number.isSafeInteger(num)) out.seed = num;+ for (const [label, value] of hasSettings ? fields : []) {+ const key = label.toLowerCase();+ const n = numberOf(value);+ if (key === "steps" && n !== undefined && Number.isInteger(n))+ out.steps = n;+ else if (key === "cfg scale" && n !== undefined) out.guidance = n;+ else if (key === "seed" && n !== undefined && Number.isSafeInteger(n))+ out.seed = n;else if (key === "model" && value) out.model = value;- else if (key === "denoising strength" && Number.isFinite(num))- out.strength = num;- else if (key.startsWith("hires")) hires = true;+ else if (key === "denoising strength" && n !== undefined) out.strength = n;+ // A1111 numbering (1 = last layer); infotext omits it at 1 (modules/processing.py:790).+ else if (key === "clip skip" && n !== undefined && Number.isInteger(n))+ out.clip_skip = n;+ else if (CFG_RESCALE_KEYS.has(key) && n !== undefined) out.cfg_rescale = n;+ else if (+ key === "variation seed" &&+ n !== undefined &&+ Number.isSafeInteger(n)+ )+ out.variation_seed = n;+ else if (key === "variation seed strength" && n !== undefined)+ out.variation_strength = n;+ else if (key === "mask blur" && n !== undefined) out.mask_blur = n;+ else if (key === "inpaint area")+ out.inpaint_only_masked = /only masked/i.test(value);+ else if (+ (key === "masked area padding" || key === "only masked padding") &&+ n !== undefined+ )+ out.inpaint_padding = n;+ // `TI hashes: "name: hash, ..."` lists the embeddings the prompt used; Studio loads none.+ else if (key === "ti hashes") {+ for (const item of value.split(",")) {+ const name = item.slice(0, item.lastIndexOf(":") > 0 ? item.lastIndexOf(":") : undefined).trim();+ if (name) notApplied.push(`textual inversion ${name}`);+ }+ }+ // A1111 writes Emphasis only when it is not the default; "Original" is what Studio's prompt encoding does.+ else if (key === "emphasis") {+ if (value && value.toLowerCase() !== "original")+ notApplied.push(`${label}: ${value}`);+ } else if (key.startsWith("hires")) hires[label] = value;else if (key === "sampler") {out.sampler = labelId(SAMPLER_LABELS, value);// Before AUTOMATIC1111 1.9 the schedule rode on the sampler name: `DPM++ 2M Karras`.@@ -547,14 +817,25 @@ export function parseA1111Parameters(text: string): ImportedRecipe | null {out.width = Number(size[1]);out.height = Number(size[2]);}- }+ } else if (!A1111_INFO_KEYS.has(key) && value)+ notApplied.push(`${label}: ${value}`);}out.schedule_type ??= legacySchedule;- // txt2img hires fix also writes a denoising strength; without it the strength means img2img.+ const hiresKeys = Object.keys(hires);+ if (hiresKeys.length > 0) out.hires = hires;+ // txt2img hires fix also writes a denoising strength; without it the strength means img2img,+ // or inpaint when A1111 wrote its mask-only fields.if (out.strength !== undefined) {- if (hires) delete out.strength;- else out.workflow ??= "img2img";+ if (hiresKeys.length > 0) delete out.strength;+ else+ out.workflow ??=+ out.mask_blur !== undefined ||+ out.inpaint_only_masked !== undefined ||+ out.inpaint_padding !== undefined+ ? "inpaint"+ : "img2img";}+ if (notApplied.length > 0) out.parameters_not_applied = notApplied;return out.prompt || hasSettings ? out : null;}@@ -622,6 +903,9 @@ export interface RestorableRecipe {// The prompt upsampler's caption and outcome; restore decides the Enhance prompt toggle from them.enhanced_prompt?: string | null;prompt_enhancement?: "applied" | "off" | "unavailable" | "failed" | null;+ mask_blur?: number;+ inpaint_only_masked?: boolean;+ inpaint_padding?: number;}export const APPLIED_RECIPE_KEYS = [@@ -645,6 +929,9 @@ export const APPLIED_RECIPE_KEYS = ["schedule_type","enhanced_prompt","prompt_enhancement",+ "mask_blur",+ "inpaint_only_masked",+ "inpaint_padding",] as const;/** Known but not applied: loading a model or a ControlNet image stays the user's call. */@@ -673,9 +960,23 @@ export const INFO_RECIPE_KEYS = [/** Matches RECIPE_SCHEMA_VERSION in core/inference/image_gallery.py. */export const RECIPE_SCHEMA_VERSION = 1;+/** Read from AUTOMATIC1111 text but not sent by this build. */+export const PENDING_RECIPE_KEYS = [+ "clip_skip",+ "cfg_rescale",+ "variation_seed",+ "variation_strength",+ "hires",+ "lora_tags",+ "prompt_emphasis",+ "prompt_escaped_brackets",+ "parameters_not_applied",+] as const;+const KNOWN_RECIPE_KEYS = new Set<string>([...APPLIED_RECIPE_KEYS,...INFO_RECIPE_KEYS,+ ...PENDING_RECIPE_KEYS,]);/** Non-empty keys this build does not know (newer Unsloth, other tools), named instead of dropped. */@@ -694,6 +995,81 @@ export function unknownRecipeKeys(r: ImportedRecipe): string[] {});}+// The request's bounds for each clamped recipe number (DiffusionGenerateRequest; steps is+// STEPS_REQUEST_MAX in image-generation-defaults): recipeSettings clamps, importNotApplied says so.+const RECIPE_BOUNDS = {+ steps: { lo: 1, hi: 100, label: "Steps", integer: true },+ guidance: { lo: 0, hi: 20, label: "CFG scale", integer: false },+ batch_size: { lo: 1, hi: 32, label: "batch size", integer: true },+ strength: { lo: 0, hi: 1, label: "denoising strength", integer: false },+ mask_blur: { lo: 0, hi: 64, label: "Mask blur", integer: true },+ inpaint_padding: { lo: 0, hi: 256, label: "masked area padding", integer: true },+} as const;+const bounded = (r: ImportedRecipe, key: keyof typeof RECIPE_BOUNDS): number | undefined => {+ const b = RECIPE_BOUNDS[key];+ return clamp(b.integer ? int(r[key]) : num(r[key]), b.lo, b.hi);+};++/** `family`: the loaded model's family, when one is loaded. `parsesEmphasis`: the loaded engine reads+ * A1111 attention syntax itself (sd.cpp's parse_prompt_attention); diffusers and MLX do not. */+export function importNotApplied(+ r: ImportedRecipe,+ family?: string | null,+ parsesEmphasis = false,+): string[] {+ const out: string[] = [];+ if (!parsesEmphasis && Array.isArray(r.prompt_emphasis) && r.prompt_emphasis.length > 0) {+ const groups = r.prompt_emphasis.filter((g): g is string => typeof g === "string");+ const shown = groups.slice(0, 3).join(", ") + (groups.length > 3 ? ", ..." : "");+ out.push(`prompt emphasis (${shown}) is passed as plain text`);+ }+ if (+ !parsesEmphasis &&+ Array.isArray(r.prompt_escaped_brackets) &&+ r.prompt_escaped_brackets.length > 0+ ) {+ const tokens = r.prompt_escaped_brackets.filter((t): t is string => typeof t === "string");+ out.push(`escaped brackets (${tokens.join(" ")}) are passed with their backslashes`);+ }+ for (const key of Object.keys(RECIPE_BOUNDS) as (keyof typeof RECIPE_BOUNDS)[]) {+ const b = RECIPE_BOUNDS[key];+ const raw = b.integer ? int(r[key]) : num(r[key]);+ const sent = bounded(r, key);+ if (raw !== undefined && sent !== raw)+ out.push(`${b.label} ${raw} (clamped to ${sent})`);+ }+ const clipSkip = num(r.clip_skip);+ // SDXL already encodes from the penultimate layer, which is what A1111 / Forge render for Clip skip+ // 1 and 2 (Forge minimal_clip_skip=2; A1111 skips CLIP-G never, CLIP-L only with sdxl_clip_l_skip).+ // Elsewhere Studio applies no clip skip, so anything past A1111's default 1 is not applied.+ if (clipSkip !== undefined && clipSkip > (family === "sdxl" ? 2 : 1))+ out.push(`Clip skip ${clipSkip}`);+ const rescale = num(r.cfg_rescale);+ if (rescale !== undefined && rescale !== 0)+ out.push(`CFG rescale ${rescale}`);+ const variation = num(r.variation_seed);+ const variationStrength = num(r.variation_strength);+ if (variation !== undefined && variationStrength !== 0) {+ out.push(+ `variation seed ${variation}${variationStrength !== undefined ? ` (strength ${variationStrength})` : ""}`,+ );+ } else if (variation === undefined && variationStrength !== undefined && variationStrength !== 0) {+ // A strength with no seed still varies the image (A1111 then draws a random variation seed).+ out.push(`variation strength ${variationStrength}`);+ }+ if (r.hires && typeof r.hires === "object" && !Array.isArray(r.hires)) {+ const parts = Object.entries(r.hires as Record<string, unknown>)+ .filter(([, v]) => typeof v === "string" && v !== "")+ .map(([k, v]) => `${k}: ${String(v)}`);+ if (parts.length > 0) out.push(`hires fix (${parts.join(", ")})`);+ }+ if (Array.isArray(r.parameters_not_applied)) {+ for (const item of r.parameters_not_applied)+ if (typeof item === "string") out.push(item);+ }+ return out;+}+export function newerRecipeSchema(r: ImportedRecipe): boolean {return (typeof r.schema_version === "number" &&@@ -740,6 +1116,17 @@ const uniqueLoras = (loras: string[]): string[] => {const str = (v: unknown): string | undefined =>typeof v === "string" ? v : undefined;+/** The request's adapter limit (DiffusionGenerateRequest.loras). */+export const MAX_LORAS = 8;++/** The recipe's LoRA ids recipeSettings drops for being past MAX_LORAS. */+export function lorasOverLimit(r: ImportedRecipe): string[] {+ if (!Array.isArray(r.loras)) return [];+ return uniqueLoras(r.loras.flatMap(loraOf))+ .slice(MAX_LORAS)+ .map((l) => l.slice(0, l.lastIndexOf(":")));+}+export function recipeSettings(r: ImportedRecipe,d: RecipeDefaults,@@ -752,18 +1139,18 @@ export function recipeSettings(width: width && width > 0 ? width : d.width,height: height && height > 0 ? height : d.height,// Clamped to the request's bounds: other tools allow more (AUTOMATIC1111 goes to 150 steps).- steps: clamp(int(r.steps), 1, 100) ?? d.steps,- guidance: clamp(num(r.guidance), 0, 20) ?? d.guidance,+ steps: bounded(r, "steps") ?? d.steps,+ guidance: bounded(r, "guidance") ?? d.guidance,seed: seedOf(r.seed),batch_seed: seedOf(r.batch_seed),- batch_size: clamp(int(r.batch_size), 1, 32) ?? 1,+ batch_size: bounded(r, "batch_size") ?? 1,model: str(r.model) ?? null,workflow: str(r.workflow),loras: Array.isArray(r.loras)- ? uniqueLoras(r.loras.flatMap(loraOf)).slice(0, 8)+ ? uniqueLoras(r.loras.flatMap(loraOf)).slice(0, MAX_LORAS): [],// The request takes strength in (0, 1]: 0 leaves no denoising steps, so it is not restored.- strength: positive(clamp(num(r.strength), 0, 1)),+ strength: positive(bounded(r, "strength")),upscale: clamp(num(r.upscale), 1, 4),// The request caps reference images at 9; restore builds an array of this length.reference_image_count: clamp(int(r.reference_image_count), 0, 9),@@ -780,9 +1167,115 @@ export function recipeSettings(r.prompt_enhancement === "failed"? r.prompt_enhancement: null,+ mask_blur: bounded(r, "mask_blur"),+ inpaint_only_masked:+ typeof r.inpaint_only_masked === "boolean"+ ? r.inpaint_only_masked+ : undefined,+ inpaint_padding: bounded(r, "inpaint_padding"),};}+const LORA_EXTENSIONS = /\.(safetensors|gguf|ckpt|pt|bin)$/i;+const loraKey = (name: string) =>+ name+ .trim()+ .replace(LORA_EXTENSIONS, "")+ .split(/[\\/:]/)+ .pop()+ ?.toLowerCase() ?? "";++// The tag's whole relative path, for an exact match before falling back to the bare stem.+const loraPathKey = (name: string) =>+ name+ .trim()+ .replace(LORA_EXTENSIONS, "")+ .replace(/\\/g, "/")+ .replace(/^\.\//, "")+ .toLowerCase();++/** Resolve `<lora:name:weight>` tags against the installed LoRAs: the exact relative path first, else a+ * file stem only one adapter has; returns unmatched names. */+export function matchLoraTags(+ tags: unknown,+ available: readonly { id: string; display_name: string; source?: string }[],+): { loras: string[]; unmatched: string[]; notes: string[] } {+ const loras: string[] = [];+ const unmatched: string[] = [];+ const notes: string[] = [];+ if (!Array.isArray(tags)) return { loras, unmatched, notes };+ const local = available.filter(+ (a) => a.source === undefined || a.source === "local",+ );+ for (const tag of tags as unknown[]) {+ if (!tag || typeof tag !== "object") continue;+ const { name, weight, unet_weight, dyn_dim } = tag as Partial<LoraTag>;+ if (typeof name !== "string" || typeof weight !== "number") continue;+ const path = loraPathKey(name);+ const key = loraKey(name);+ // An id is unique, so its exact path decides; a display name or bare stem must name one adapter only.+ const byId = local.filter((a) => loraPathKey(a.id) === path);+ const candidates =+ byId.length > 0+ ? byId+ : local.filter(+ (a) =>+ loraPathKey(a.display_name) === path ||+ loraKey(a.id) === key ||+ loraKey(a.display_name) === key,+ );+ if (candidates.length > 1) {+ notes.push(`LoRA ${name} (ambiguous: ${candidates.length} adapters named ${key})`);+ continue;+ }+ const hit = candidates[0];+ if (!hit) {+ unmatched.push(name);+ continue;+ }+ const w = Math.min(2, Math.max(0, weight));+ loras.push(`${hit.id}:${w}`);+ if (w !== weight)+ notes.push(`LoRA ${name} weight ${weight} (clamped to ${w})`);+ if (typeof unet_weight === "number")+ notes.push(`LoRA ${name} U-Net weight ${unet_weight}`);+ if (typeof dyn_dim === "number")+ notes.push(`LoRA ${name} dynamic dim ${dyn_dim}`);+ }+ return { loras, unmatched, notes };+}++/** The names of a recipe's `<lora:...>` tags. */+export function loraTagNames(tags: unknown): string[] {+ if (!Array.isArray(tags)) return [];+ return (tags as unknown[])+ .map((t) => (t && typeof t === "object" ? (t as Partial<LoraTag>).name : undefined))+ .filter((n): n is string => typeof n === "string");+}++/** matchLoraTags against the catalog a paste can see. Without a LoRA-capable model resident the page holds+ * no catalog, so the whole local list is fetched rather than reporting every installed adapter missing. */+export async function matchLoraTagsForImport<+ T extends { id: string; display_name: string; source?: string },+>(+ tags: unknown,+ catalogLoaded: boolean,+ loaded: readonly T[],+ fetchAll: () => Promise<readonly T[]>,+): Promise<{ loras: string[]; unmatched: string[]; notes: string[] }> {+ if (catalogLoaded || !Array.isArray(tags) || tags.length === 0)+ return matchLoraTags(tags, loaded);+ try {+ return matchLoraTags(tags, await fetchAll());+ } catch {+ return {+ loras: [],+ unmatched: [],+ notes: loraTagNames(tags).map((n) => `LoRA ${n} (the installed LoRAs could not be listed)`),+ };+ }+}+type ComfyGraph = Record<string,{ class_type?: unknown; inputs?: Record<string, unknown> }diff --git a/studio/frontend/src/features/images/lib/inpaint-options.ts b/studio/frontend/src/features/images/lib/inpaint-options.tsnew file mode 100644index 00000000000..7c4c4998b07--- /dev/null+++ b/studio/frontend/src/features/images/lib/inpaint-options.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A1111 inpaint mask options (modules/processing.py:1563-1569); the defaults send nothing.+export const MASK_BLUR_DEFAULT = 0;+export const MASK_BLUR_MAX = 64;+export const INPAINT_PADDING_DEFAULT = 32;+export const INPAINT_PADDING_MAX = 256;++export interface InpaintMaskOptions {+ maskBlur: number;+ onlyMasked: boolean;+ padding: number;+}++export interface InpaintMaskRequestFields {+ mask_blur?: number;+ inpaint_only_masked?: boolean;+ inpaint_padding?: number;+}++/** Only non-default fields; "Only masked" only when the pipeline supports it. */+export function inpaintMaskRequestFields(+ options: InpaintMaskOptions,+ supportsOnlyMasked: boolean,+): InpaintMaskRequestFields {+ const out: InpaintMaskRequestFields = {};+ const blur = Math.round(+ Math.min(MASK_BLUR_MAX, Math.max(0, options.maskBlur)),+ );+ if (Number.isFinite(blur) && blur > 0) out.mask_blur = blur;+ if (options.onlyMasked && supportsOnlyMasked) {+ out.inpaint_only_masked = true;+ const padding = Math.round(+ Math.min(INPAINT_PADDING_MAX, Math.max(0, options.padding)),+ );+ out.inpaint_padding = Number.isFinite(padding)+ ? padding+ : INPAINT_PADDING_DEFAULT;+ }+ return out;+}++interface InpaintMaskRecord {+ workflow?: string | null;+ mask_blur?: number | null;+ inpaint_only_masked?: boolean | null;+ inpaint_padding?: number | null;+}++/** The mask options a restore applies. An inpaint record omits its defaults, so an absent field resets to it. */+export function restoredInpaintMaskOptions(+ image: InpaintMaskRecord,+): Partial<InpaintMaskOptions> {+ const inpaint = image.workflow === "inpaint";+ const out: Partial<InpaintMaskOptions> = {};+ if (typeof image.mask_blur === "number") out.maskBlur = image.mask_blur;+ else if (inpaint) out.maskBlur = MASK_BLUR_DEFAULT;+ if (typeof image.inpaint_only_masked === "boolean")+ out.onlyMasked = image.inpaint_only_masked;+ else if (inpaint) out.onlyMasked = false;+ if (typeof image.inpaint_padding === "number")+ out.padding = image.inpaint_padding;+ else if (inpaint) out.padding = INPAINT_PADDING_DEFAULT;+ return out;+}++/** A restored "Only masked" a pipeline that cannot crop will silently drop, for the not-applied toast. */+export function inpaintOptionsNotApplied(+ settings: { inpaint_only_masked?: boolean | null; inpaint_padding?: number | null },+ supportsOnlyMasked: boolean,+): string[] {+ if (settings.inpaint_only_masked !== true || supportsOnlyMasked) return [];+ const padding =+ typeof settings.inpaint_padding === "number"+ ? settings.inpaint_padding+ : INPAINT_PADDING_DEFAULT;+ return [`inpaint area only masked (padding ${padding})`];+}diff --git a/studio/frontend/src/features/images/lib/seed-controls.ts b/studio/frontend/src/features/images/lib/seed-controls.tsnew file mode 100644index 00000000000..bea5dac63eb--- /dev/null+++ b/studio/frontend/src/features/images/lib/seed-controls.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++interface SeededImage {+ seed: number;+ batch_seed?: number | null;+ created_at: number;+ model_kind?: string | null;+}++const seedOf = (image: SeededImage): number | null => {+ // Connection runs never sent a seed, so theirs reproduces nothing.+ if (image.model_kind === "connection") return null;+ const seed = image.batch_seed ?? image.seed;+ return Number.isSafeInteger(seed) && seed >= 0 ? seed : null;+};++/** The base seed one run used: its batch's shared seed, so replaying the batch gives the same images. */+export function lastSeedOf(run: readonly SeededImage[]): number | null {+ for (const image of run) {+ const seed = seedOf(image);+ if (seed !== null) return seed;+ }+ return null;+}++/** `hasMore`: the gallery is only partly loaded, or may hold records it does not show (archived ones). Pages follow the pin and manual order, not creation+ * time, so the newest record may be unseen and no gallery seed is offered. */+export function reusableSeed(+ sessionSeed: number | null,+ gallery: readonly SeededImage[],+ hasMore = false,+): number | null {+ if (sessionSeed !== null) return sessionSeed;+ if (hasMore) return null;+ let newest: SeededImage | null = null;+ for (const image of gallery) {+ if (+ seedOf(image) !== null &&+ (newest === null || image.created_at > newest.created_at)+ )+ newest = image;+ }+ return newest ? seedOf(newest) : null;+}diff --git a/studio/frontend/src/features/images/paste-parameters-dialog.tsx b/studio/frontend/src/features/images/paste-parameters-dialog.tsxnew file mode 100644index 00000000000..a14349d5ea2--- /dev/null+++ b/studio/frontend/src/features/images/paste-parameters-dialog.tsx@@ -0,0 +1,91 @@+// 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 {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Textarea } from "@/components/ui/textarea";++const EXAMPLE =+ "a sloth hiking, <lora:sloth-style:0.8>\nNegative prompt: blurry\nSteps: 28, Sampler: DPM++ 2M, Schedule type: Karras, CFG scale: 6, Seed: 12345, Size: 832x1216";++/** Paste generation parameters: AUTOMATIC1111 / Forge / Civitai text (or an Unsloth recipe). */+export function PasteParametersDialog({+ open,+ onOpenChange,+ text,+ onTextChange,+ onApply,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ text: string;+ onTextChange: (text: string) => void;+ onApply: (text: string) => Promise<boolean>;+}) {+ // Closes only once the settings are applied; a failed or superseded paste keeps the text.+ const apply = async () => {+ if (text.trim() && (await onApply(text))) {+ onTextChange("");+ onOpenChange(false);+ }+ };+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="corner-squircle dialog-soft-surface gap-5 sm:max-w-lg">+ <form+ className="grid gap-5"+ onSubmit={(event) => {+ event.preventDefault();+ void apply();+ }}+ >+ <DialogHeader>+ <DialogTitle className="text-ui-21">+ Paste generation parameters+ </DialogTitle>+ <DialogDescription>+ The text AUTOMATIC1111, Forge or Civitai copy: prompt, Negative+ prompt and the Steps line. LoRA tags pick installed LoRAs;+ settings this model cannot use are listed as not applied.+ </DialogDescription>+ </DialogHeader>+ <Textarea+ aria-label="Generation parameters"+ autoFocus+ rows={8}+ spellCheck={false}+ placeholder={EXAMPLE}+ value={text}+ onChange={(e) => onTextChange(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ void apply();+ }+ }}+ className="max-h-[50dvh] min-h-40 resize-y font-mono text-xs"+ />+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={!text.trim()}>+ Apply+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx b/studio/frontend/src/features/settings/components/archived-media-dialog.tsxindex 5c8b279dae3..c9b2a3f9abe 100644--- a/studio/frontend/src/features/settings/components/archived-media-dialog.tsx+++ b/studio/frontend/src/features/settings/components/archived-media-dialog.tsx@@ -49,7 +49,7 @@ import {} from "@/features/video/api";import { videoThumbnailQueue } from "@/features/video/thumbnail-request-queue";import { BlobUrlCache } from "@/lib/blob-url-cache";-import { notifyGalleryChanged } from "@/lib/gallery-flags";+import { notifyArchiveChanged, notifyGalleryChanged } from "@/lib/gallery-flags";import { translate, useLocale, useT } from "@/i18n";import { toast } from "@/lib/toast";@@ -522,6 +522,7 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {running.current = true;setBusy(true);let restored = false;+ let changed = false;try {for (const row of targets) {const succeeded =@@ -529,11 +530,14 @@ export function ArchivedMediaView({ kind }: { kind: ArchivedMediaKind }) {? await handleDelete(row): await handleRestore(row);if (!succeeded) break;+ changed = true;if (action === "restore") restored = true;}} finally {// refresh the persistent gallery once, including after a partially successful batch.if (restored) notifyGalleryChanged(kind);+ // A delete leaves the strip as it was, but the Images page tracks whether the archive is empty.+ if (changed) notifyArchiveChanged(kind);running.current = false;setBusy(false);setConfirming(null);diff --git a/studio/frontend/src/lib/gallery-flags.ts b/studio/frontend/src/lib/gallery-flags.tsindex f62342a6833..951544c36cc 100644--- a/studio/frontend/src/lib/gallery-flags.ts+++ b/studio/frontend/src/lib/gallery-flags.ts@@ -36,6 +36,26 @@ export function subscribeGalleryChanged(kind: GalleryKind, onChanged: () => voidreturn () => window.removeEventListener(GALLERY_CHANGED_EVENT, handler);}+export const ARCHIVE_CHANGED_EVENT = "unsloth:archive-changed";++/** Announce that the archived shelf of `kind` changed from Settings (a restore or a delete). Kept apart+ * from the gallery event so a delete, which leaves the active strip as it was, does not refetch it. */+export function notifyArchiveChanged(kind: GalleryKind): void {+ if (typeof window === "undefined") return;+ window.dispatchEvent(new CustomEvent(ARCHIVE_CHANGED_EVENT, { detail: { kind } }));+}++/** Calls back when the archive of `kind` changed elsewhere. Returns an unsubscriber. */+export function subscribeArchiveChanged(kind: GalleryKind, onChanged: () => void): () => void {+ if (typeof window === "undefined") return () => {};+ const handler = (event: Event) => {+ const detail = (event as CustomEvent<{ kind?: string }>).detail;+ if (detail?.kind === kind) onChanged();+ };+ window.addEventListener(ARCHIVE_CHANGED_EVENT, handler);+ return () => window.removeEventListener(ARCHIVE_CHANGED_EVENT, handler);+}+/** The two fields these helpers care about; both gallery record types structurally satisfy it. */export interface FlaggableItem {id: string;diff --git a/studio/frontend/tests/image-a1111-infotext-keys.test.ts b/studio/frontend/tests/image-a1111-infotext-keys.test.tsnew file mode 100644index 00000000000..40dc69b79e5--- /dev/null+++ b/studio/frontend/tests/image-a1111-infotext-keys.test.ts@@ -0,0 +1,189 @@+// 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 {+ A1111_INFO_KEYS,+ importNotApplied,+ parseA1111Parameters,+ promptEmphasisGroups,+} from "../src/features/images/lib/image-metadata.ts";++type Handling = "applied" | "reported" | "ignored";++// Every key AUTOMATIC1111 (create_infotext, extra_generation_params, the `infotext=` options) and Forge+// write, with a value that changes the image where one exists. "ignored" is only for keys that set+// nothing: hashes, the writer, the version. Anything not handled falls through to "reported".+const KEYS: Array<[string, string, Handling]> = [+ // create_infotext+ ["Steps", "30", "applied"],+ ["Sampler", "Euler a", "applied"],+ ["Schedule type", "Karras", "applied"],+ ["CFG scale", "6", "applied"],+ ["Image CFG scale", "1.5", "reported"],+ ["Seed", "7", "applied"],+ ["Face restoration", "CodeFormer", "reported"],+ ["Size", "832x1216", "applied"],+ ["Model hash", "31e35c80fc", "ignored"],+ ["Model", "ponyDiffusionV6XL", "applied"],+ ["FP8 weight", "Enable", "reported"],+ ["Cache FP16 weight for LoRA", "True", "reported"],+ ["VAE hash", "235745af8d", "ignored"],+ ["VAE", "sdxl_vae.safetensors", "reported"],+ ["Variation seed", "99", "reported"],+ ["Variation seed strength", "0.3", "reported"],+ ["Seed resize from", "512x512", "reported"],+ ["Denoising strength", "0.5", "applied"],+ ["Conditional mask weight", "0.5", "reported"],+ ["Clip skip", "3", "reported"],+ ["ENSD", "31337", "reported"],+ ["Tiling", "True", "reported"],+ ["Token merging ratio", "0.3", "reported"],+ ["Token merging ratio hr", "0.3", "reported"],+ ["Init image hash", "abc", "ignored"],+ ["RNG", "CPU", "reported"],+ ["Version", "v1.10.1", "ignored"],+ ["User", "someone", "ignored"],+ // extra_generation_params (modules, scripts, extensions-builtin)+ ["Hires upscale", "2", "reported"],+ ["Hires steps", "10", "reported"],+ ["Hires upscaler", "Latent", "reported"],+ ["Hires resize", "1024x1024", "reported"],+ ["Hires checkpoint", "other.safetensors", "reported"],+ ["Hires sampler", "Euler", "reported"],+ ["Hires schedule type", "Karras", "reported"],+ ["Hires prompt", "x", "reported"],+ ["Hires negative prompt", "y", "reported"],+ ["Hires CFG Scale", "5", "reported"],+ ["Hires Distilled CFG Scale", "3.5", "reported"],+ ["Hires Module 1", "Built-in", "reported"],+ ["Hires refiner", "r.safetensors", "reported"],+ ["Refiner", "sd_xl_refiner_1.0", "reported"],+ ["Refiner switch at", "0.8", "reported"],+ ["Refiner switch by sampling steps", "True", "reported"],+ ["Mask blur", "4", "applied"],+ ["Inpaint area", "Only masked", "applied"],+ ["Masked area padding", "48", "applied"],+ ["Masked content", "fill", "reported"],+ ["Mask mode", "Inpaint not masked", "reported"],+ ["Mask rounding", "False", "reported"],+ ["Emphasis", "No norm", "reported"],+ ["Pad conds", "True", "reported"],+ ["Pad conds v0", "True", "reported"],+ ["Downcast alphas_cumprod", "True", "reported"],+ ["Old prompt editing timelines", "True", "reported"],+ ["Discard penultimate sigma", "True", "reported"],+ ["Noise multiplier", "1.05", "reported"],+ ["Extra noise", "0.1", "reported"],+ ["SGM noise multiplier", "True", "reported"],+ ["NGMS", "0.5", "reported"],+ ["NGMS all steps", "True", "reported"],+ ["Skip Early CFG", "0.2", "reported"],+ ["Noise Schedule", "Zero Terminal SNR", "reported"],+ ["Schedule max sigma", "14", "reported"],+ ["Schedule min sigma", "0.03", "reported"],+ ["Schedule rho", "7", "reported"],+ ["Beta schedule alpha", "0.6", "reported"],+ ["Beta schedule beta", "0.6", "reported"],+ ["Sigma churn", "0.1", "reported"],+ ["Sigma tmin", "0.1", "reported"],+ ["Sigma tmax", "10", "reported"],+ ["Sigma noise", "1.01", "reported"],+ ["Eta", "0.67", "reported"],+ ["Eta DDIM", "0.1", "reported"],+ ["UniPC variant", "bh1", "reported"],+ ["UniPC skip type", "time_uniform", "reported"],+ ["UniPC order", "2", "reported"],+ ["UniPC lower order final", "False", "reported"],+ ["VAE Encoder", "TAESD", "reported"],+ ["VAE Decoder", "TAESD", "reported"],+ ["Hypertile U-Net", "True", "reported"],+ ["Hypertile VAE", "True", "reported"],+ ["SD upscale overlap", "64", "reported"],+ ["SD upscale upscaler", "R-ESRGAN 4x+", "reported"],+ ["Script", "X/Y/Z plot", "reported"],+ ["Lora hashes", '"add-detail-xl: 9c783c8ce46c"', "ignored"],+ ["TI hashes", '"easynegative: c74b4e810b03"', "reported"],+ // Forge+ ["Distilled CFG Scale", "3.5", "reported"],+ ["Module 1", "ae", "reported"],+ ["Diffusion in Low Bits", "bnb-nf4", "reported"],+ ["Original Size", "1024x1024", "reported"],+ // Civitai and other writers+ ["Hashes", '{"model": "31e35c80fc"}', "ignored"],+ ["Civitai resources", '[{"type": "checkpoint"}]', "ignored"],+ ["Civitai metadata", "{}", "ignored"],+ ["Created Date", "2024-05-01T00:00:00.000Z", "ignored"],+ // A key nobody lists yet still falls through to "reported", never silently.+ ["Some future setting", "on", "reported"],+];++const BASE = "a cat\nSteps: 20, Seed: 1";++function handling(key: string, value: string): Handling {+ const base = parseA1111Parameters(BASE);+ const r = parseA1111Parameters(`${BASE}, ${key}: ${value}`);+ assert.ok(base && r, key);+ const reported = importNotApplied(r, "sdxl").filter(+ (item) => !importNotApplied(base, "sdxl").includes(item),+ );+ if (reported.length > 0) return "reported";+ const { parameters_not_applied: _a, ...rest } = r;+ const { parameters_not_applied: _b, ...baseRest } = base;+ return JSON.stringify(rest) === JSON.stringify(baseRest) ? "ignored" : "applied";+}++for (const [key, value, expected] of KEYS) {+ test(`A1111 infotext ${key} is ${expected}`, () => {+ assert.equal(handling(key, value), expected);+ });+}++test("only the keys the table calls ignored are skipped silently", () => {+ const ignored = KEYS.filter(([, , h]) => h === "ignored").map(([k]) => k.toLowerCase());+ assert.deepEqual([...A1111_INFO_KEYS].sort(), [...ignored].sort());+ assert.equal(new Set(KEYS.map(([k]) => k.toLowerCase())).size, KEYS.length);+});++test("numbers past the request bounds are reported as clamped", () => {+ const r = parseA1111Parameters(+ "a cat\nSteps: 150, CFG scale: 30, Seed: 1, Denoising strength: 0.5, Mask blur: 99, Masked area padding: 300",+ );+ assert.ok(r);+ assert.deepEqual(importNotApplied(r, "sdxl"), [+ "Steps 150 (clamped to 100)",+ "CFG scale 30 (clamped to 20)",+ "Mask blur 99 (clamped to 64)",+ "masked area padding 300 (clamped to 256)",+ ]);+});++// Prompt content, not a key: A1111 attention syntax and its escaped literal brackets are kept in the+// prompt as written and named unless the engine (sd.cpp) parses A1111 syntax itself.+const PROMPT_CONTENT: Array<[string, string[], string[]]> = [+ ["a (red:1.2) car", ["(red:1.2)"], []],+ ["a ((red)) car, [blurry]", ["((red))", "[blurry]"], []],+ ["a \\(literal\\) car \\[x\\]", [], ["\\(", "\\)", "\\[", "\\]"]],+ ["a (red car", [], []],+ ["plain text", [], []],+];++for (const [prompt, groups, escaped] of PROMPT_CONTENT) {+ test(`prompt content in ${JSON.stringify(prompt)}`, () => {+ assert.deepEqual(promptEmphasisGroups(prompt), groups);+ const r = parseA1111Parameters(`${prompt}\nNegative prompt: (worst quality:1.4)\n${BASE.split("\n")[1]}`);+ assert.ok(r);+ assert.equal(r.prompt, prompt);+ const all = [...groups, "(worst quality:1.4)"];+ const expected = [+ `prompt emphasis (${all.slice(0, 3).join(", ")}${all.length > 3 ? ", ..." : ""}) is passed as plain text`,+ ];+ if (escaped.length > 0)+ expected.push(`escaped brackets (${escaped.join(" ")}) are passed with their backslashes`);+ assert.deepEqual(importNotApplied(r, "sdxl"), expected);+ // The native sd.cpp engine reads A1111 syntax itself.+ assert.deepEqual(importNotApplied(r, "sdxl", true), []);+ });+}diff --git a/studio/frontend/tests/image-metadata.test.ts b/studio/frontend/tests/image-metadata.test.tsindex f232ea3c2da..b935d2c4e25 100644--- a/studio/frontend/tests/image-metadata.test.ts+++ b/studio/frontend/tests/image-metadata.test.ts@@ -8,12 +8,14 @@ import {buildExif,copyPngTextChunks,importedRecipe,+ importNotApplied,parseA1111Parameters,parseComfyPrompt,pngTextChunks,APPLIED_RECIPE_KEYS,INFO_RECIPE_KEYS,newerRecipeSchema,+ PENDING_RECIPE_KEYS,readEmbeddedRecipe,recipeSettings,unknownRecipeKeys,@@ -665,13 +667,15 @@ test("a newer recipe loads what this build knows and names what it does not", ()assert.ok(recipe);const settings = recipeSettings(recipe, defaults);assert.equal(settings.seed, 6630007);- assert.deepEqual(unknownRecipeKeys(recipe), ["cfg_rescale", "tiling"]);+ assert.deepEqual(unknownRecipeKeys(recipe), ["tiling"]);+ // A setting this build parses but cannot send yet is named by label, not by key.+ assert.deepEqual(importNotApplied(recipe), ["CFG rescale 0.7"]);assert.equal(newerRecipeSchema(recipe), true);// Every key today's recipe writes is known, so a current image reports nothing.assert.deepEqual(unknownRecipeKeys(JSON.parse(RECIPE)), []);assert.equal(- new Set([...APPLIED_RECIPE_KEYS, ...INFO_RECIPE_KEYS]).size,- APPLIED_RECIPE_KEYS.length + INFO_RECIPE_KEYS.length,+ new Set([...APPLIED_RECIPE_KEYS, ...INFO_RECIPE_KEYS, ...PENDING_RECIPE_KEYS]).size,+ APPLIED_RECIPE_KEYS.length + INFO_RECIPE_KEYS.length + PENDING_RECIPE_KEYS.length,);});@@ -693,7 +697,9 @@ test("an unmapped ComfyUI sampler is kept by name; prototype names map to nothintest("the import names a sampler or schedule the loaded model does not offer", () => {const page = readSrc("features/images/images-page.tsx");- const start = page.indexOf("const notApplied = unknownRecipeKeys(recipe);");+ const start = page.indexOf(+ "const notApplied = [\n ...importNotApplied(\n recipe,\n status?.loaded ? status.family : null,",+ );assert.ok(start > 0);const block = page.slice(start, page.indexOf("[restoreSettings,", start));assert.match(block, /notApplied\.unshift\(`sampler \$\{labelOf\(SAMPLER_LABELS, settings\.sampler\)\}`\)/);diff --git a/studio/frontend/tests/image-paste-parameters.test.ts b/studio/frontend/tests/image-paste-parameters.test.tsnew file mode 100644index 00000000000..df6715be1fc--- /dev/null+++ b/studio/frontend/tests/image-paste-parameters.test.ts@@ -0,0 +1,496 @@+// 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 {+ a1111Fields,+ extractExtraNetworks,+ importNotApplied,+ importedRecipe,+ isGenerationParametersPaste,+ matchLoraTags,+ loraTagNames,+ matchLoraTagsForImport,+ MAX_LORAS,+ lorasOverLimit,+ parseA1111Parameters,+ pastedParameters,+ recipeSettings,+ unknownRecipeKeys,+} from "../src/features/images/lib/image-metadata.ts";+import { readSrc } from "./helpers/kit.ts";++const DEFAULTS = { width: 1024, height: 1024, steps: 8, guidance: 3.5 };++// What Civitai's "Copy generation data" gives for an SDXL Pony image (shape of a real one).+const CIVITAI = [+ "score_9, score_8_up, 1girl, solo, <lora:add-detail-xl:0.8>, (masterpiece:1.2), <lora:missing_style:1>, smile",+ "Negative prompt: score_4, lowres, bad hands",+ 'Steps: 30, Sampler: DPM++ 2M Karras, CFG scale: 7, Seed: 3812461337, Size: 832x1216, Clip skip: 2, Created Date: 2024-05-01T10:00:00.000Z, Civitai resources: [{"type":"checkpoint","modelVersionId":290640,"modelName":"Pony Diffusion V6 XL, final"},{"type":"lora","weight":0.8,"modelVersionId":1}], Civitai metadata: {}, Model hash: 67ab2fd8ec, Model: ponyDiffusionV6XL, Lora hashes: "add-detail-xl: 9c783c8ce46c, missing_style: abc"',+].join("\n");++test("a Civitai block parses: legacy sampler name, JSON values with commas, quoted hashes", () => {+ const r = parseA1111Parameters(CIVITAI);+ assert.ok(r);+ assert.equal(+ r.prompt,+ "score_9, score_8_up, 1girl, solo, (masterpiece:1.2), smile",+ );+ assert.equal(r.negative_prompt, "score_4, lowres, bad hands");+ assert.equal(r.steps, 30);+ assert.equal(r.sampler, "dpmpp_2m");+ assert.equal(r.schedule_type, "karras");+ assert.equal(r.guidance, 7);+ assert.equal(r.seed, 3812461337);+ assert.equal(r.width, 832);+ assert.equal(r.height, 1216);+ assert.equal(r.model, "ponyDiffusionV6XL");+ assert.equal(r.clip_skip, 2);+ assert.deepEqual(r.lora_tags, [+ { name: "add-detail-xl", weight: 0.8 },+ { name: "missing_style", weight: 1 },+ ]);+ assert.equal(r.parameters_not_applied, undefined);+ // The (masterpiece:1.2) weight stays in the prompt; only sd.cpp parses it.+ const emphasis = "prompt emphasis ((masterpiece:1.2)) is passed as plain text";+ assert.equal(r.prompt.includes("(masterpiece:1.2)"), true);+ // Clip skip 2 is what SDXL already renders, so nothing is reported for it there.+ assert.deepEqual(importNotApplied(r, "sdxl"), [emphasis]);+ assert.deepEqual(importNotApplied(r, "sdxl", true), []);+ // Any other family (or none loaded) applies no clip skip, so it is named.+ assert.deepEqual(importNotApplied(r), [emphasis, "Clip skip 2"]);+ assert.deepEqual(importNotApplied(r, "flux", true), ["Clip skip 2"]);+ assert.deepEqual(importNotApplied({ prompt: "p", clip_skip: 1 }, "flux"), []);+ assert.deepEqual(unknownRecipeKeys(r), []);+});++test("the fields reader unquotes, keeps JSON whole and skips non-fields like re_param", () => {+ assert.deepEqual(+ a1111Fields(+ 'Steps: 20, Lora hashes: "a: 1, b: \\"2\\"", Hashes: {"model": "x, y"}, junk, Seed: 5',+ ),+ [+ ["Steps", "20"],+ ["Lora hashes", 'a: 1, b: "2"'],+ ["Hashes", '{"model": "x, y"}'],+ ["Seed", "5"],+ ],+ );+ // An unclosed JSON value falls back to the next comma rather than eating the line.+ assert.deepEqual(a1111Fields("Resources: [oops, Seed: 5"), [+ ["Resources", "[oops"],+ ["Seed", "5"],+ ]);+});++test("Clip skip, CFG rescale, variation seed and hires keys are read and named as not applied", () => {+ const r = parseA1111Parameters(+ "a cat\nSteps: 25, Sampler: Euler a, CFG scale: 5, Seed: 1, Size: 1024x1024, Clip skip: 3, CFG Rescale: 0.7, Variation seed: 99, Variation seed strength: 0.3, Hires upscale: 1.5, Hires steps: 10, Hires upscaler: R-ESRGAN 4x+, Denoising strength: 0.4, VAE: sdxl_vae.safetensors, ADetailer model: face_yolov8n.pt",+ );+ assert.ok(r);+ assert.equal(r.clip_skip, 3);+ assert.equal(r.cfg_rescale, 0.7);+ assert.equal(r.variation_seed, 99);+ assert.equal(r.variation_strength, 0.3);+ assert.deepEqual(r.hires, {+ "Hires upscale": "1.5",+ "Hires steps": "10",+ "Hires upscaler": "R-ESRGAN 4x+",+ });+ assert.equal(r.strength, undefined);+ assert.equal(r.workflow, undefined);+ assert.deepEqual(importNotApplied(r), [+ "Clip skip 3",+ "CFG rescale 0.7",+ "variation seed 99 (strength 0.3)",+ "hires fix (Hires upscale: 1.5, Hires steps: 10, Hires upscaler: R-ESRGAN 4x+)",+ "VAE: sdxl_vae.safetensors",+ "ADetailer model: face_yolov8n.pt",+ ]);+ assert.deepEqual(unknownRecipeKeys(r), []);+ for (const label of [+ "RescaleCFG: 0.5",+ "CFG rescale phi: 0.5",+ "latent_modifier_rescale_cfg_phi: 0.5",+ ]) {+ assert.equal(+ parseA1111Parameters(`a\nSteps: 20, Seed: 1, ${label}`)?.cfg_rescale,+ 0.5,+ label,+ );+ }+ // A1111 omits Clip skip at 1 and writes no variation strength 0 (modules/processing.py:785-790).+ assert.deepEqual(+ importNotApplied(+ parseA1111Parameters("a\nSteps: 20, Clip skip: 1, Seed: 1") ?? {+ prompt: "",+ },+ ),+ [],+ );+ assert.deepEqual(+ importNotApplied({ prompt: "p", variation_seed: 4, variation_strength: 0 }),+ [],+ );+});++test("inpaint mask blur, only-masked area and padding restore within the request bounds", () => {+ const r = parseA1111Parameters(+ "a cat\nSteps: 20, CFG scale: 7, Seed: 1, Denoising strength: 0.75, Mask blur: 4, Inpaint area: Only masked, Masked area padding: 48",+ );+ assert.ok(r);+ assert.equal(r.mask_blur, 4);+ assert.equal(r.inpaint_only_masked, true);+ assert.equal(r.inpaint_padding, 48);+ assert.equal(r.workflow, "inpaint");+ assert.equal(+ parseA1111Parameters("a\nSteps: 20, Seed: 1, Denoising strength: 0.5, Mask blur: 4")+ ?.workflow,+ "inpaint",+ );+ const settings = recipeSettings(r, DEFAULTS);+ assert.equal(settings.mask_blur, 4);+ assert.equal(settings.inpaint_only_masked, true);+ assert.equal(settings.inpaint_padding, 48);+ assert.equal(+ parseA1111Parameters("a\nSteps: 20, Seed: 1, Inpaint area: Whole picture")+ ?.inpaint_only_masked,+ false,+ );+ const wild = recipeSettings(+ {+ prompt: "p",+ mask_blur: 500,+ inpaint_padding: -3,+ inpaint_only_masked: "yes",+ },+ DEFAULTS,+ );+ assert.equal(wild.mask_blur, 64);+ assert.equal(wild.inpaint_padding, 0);+ assert.equal(wild.inpaint_only_masked, undefined);+ const old = recipeSettings({ prompt: "p" }, DEFAULTS);+ assert.equal(old.mask_blur, undefined);+ assert.equal(old.inpaint_only_masked, undefined);+});++test("LoRA tags: positional and named weights, other networks stripped and reported", () => {+ const r = extractExtraNetworks(+ "<lora:a:0.5>, cat, <lora:b>, <LORA:c:0.4:0.9>, <lora:d:te=0.3:unet=0.6>, <hypernet:h:1>, dog,",+ );+ assert.equal(r.prompt, "cat, dog");+ assert.deepEqual(r.loras, [+ { name: "a", weight: 0.5 },+ { name: "b", weight: 1 },+ { name: "c", weight: 0.4, unet_weight: 0.9 },+ { name: "d", weight: 0.3, unet_weight: 0.6 },+ ]);+ assert.deepEqual(r.other, ["<hypernet:h:1>"]);+ const plain = "a cat ,, on a mat";+ assert.equal(extractExtraNetworks(plain).prompt, plain);+ const parsed = parseA1111Parameters("cat <hypernet:h:1>\nSteps: 20, Seed: 1");+ assert.deepEqual(importNotApplied(parsed ?? { prompt: "" }), [+ "<hypernet:h:1>",+ ]);+});++test("LoRA tags select installed LoRAs by file name; the rest are named", () => {+ const available = [+ { id: "add-detail-xl", display_name: "add-detail-xl", source: "local" },+ {+ id: "styles/Pixel_Art.safetensors",+ display_name: "Pixel_Art",+ source: "local",+ },+ {+ id: "unsloth/krea2-retroanime",+ display_name: "Retro anime",+ source: "hub",+ },+ ];+ const m = matchLoraTags(+ [+ { name: "add-detail-xl", weight: 0.8 },+ { name: "pixel_art", weight: 3 },+ { name: "krea2-retroanime", weight: 1 },+ { name: "missing", weight: 1 },+ { name: "two", weight: 1, unet_weight: 0.5 },+ ],+ available,+ );+ assert.deepEqual(m.loras, [+ "add-detail-xl:0.8",+ "styles/Pixel_Art.safetensors:2",+ ]);+ assert.deepEqual(m.unmatched, ["krea2-retroanime", "missing", "two"]);+ assert.deepEqual(m.notes, ["LoRA pixel_art weight 3 (clamped to 2)"]);+ assert.deepEqual(matchLoraTags(undefined, available), {+ loras: [],+ unmatched: [],+ notes: [],+ });+ const settings = recipeSettings({ prompt: "p", loras: m.loras }, DEFAULTS);+ assert.deepEqual(settings.loras, [+ "add-detail-xl:0.8",+ "styles/Pixel_Art.safetensors:2",+ ]);+});++test("pasted text needs a settings line; a bare prompt is not parameters", () => {+ assert.equal(pastedParameters("just a cat on a mat"), null);+ assert.equal(pastedParameters("style: noir, mood: dark, light: low"), null);+ assert.equal(pastedParameters("a cat\nSteps: 20")?.steps, 20);+ assert.equal(+ pastedParameters("a cat\nSampler: Euler, CFG scale: 7, Seed: 3")?.seed,+ 3,+ );+ const crlf = pastedParameters(+ "a cat\r\nNegative prompt: dog\r\nSteps: 12, Seed: 9",+ );+ assert.equal(crlf?.negative_prompt, "dog");+ assert.equal(crlf?.steps, 12);+ assert.equal(+ pastedParameters(JSON.stringify({ prompt: "x", steps: 4 }))?.steps,+ 4,+ );+ assert.equal(pastedParameters("{not json"), null);+ assert.deepEqual(+ pastedParameters(CIVITAI),+ importedRecipe({ parameters: CIVITAI }),+ );+});++test("only a whole parameters block pasted into the prompt box is taken over", () => {+ assert.equal(isGenerationParametersPaste(CIVITAI), true);+ assert.equal(isGenerationParametersPaste("a cat\nSteps: 20, Seed: 1"), true);+ assert.equal(+ isGenerationParametersPaste("a cat, Steps: 20 of a staircase"),+ false,+ );+ assert.equal(isGenerationParametersPaste("a cat\nSteps: 20"), false);+ assert.equal(isGenerationParametersPaste("masterpiece, (cat:1.2)"), false);+});++test("the Images page wires paste into the same restore path as a drop", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /const applyImportedRecipe = useCallback\(/);+ assert.match(+ page,+ /const importSettingsFromText = useCallback\(\n\s+async \(text: string\): Promise<boolean> => \{\n\s+const recipe = pastedParameters\(text\);[\s\S]*?return applyImportedRecipe\(recipe\);\n\s+\},\n\s+\[applyImportedRecipe\],/,+ );+ assert.match(page, /const recipe = pastedParameters\(text\);/);+ assert.match(page, /onPasteParameters=\{\(\) => setPasteOpen\(true\)\}/);+ assert.match(+ page,+ /if \(isGenerationParametersPaste\(text\)\) \{\n\s+e\.preventDefault\(\);\n\s+void importSettingsFromText\(text\);/,+ );+ assert.match(+ page,+ /\.\.\.importNotApplied\(\n\s+recipe,\n\s+status\?\.loaded \? status\.family : null,\n\s+Boolean\(status\?\.loaded && isNativeEngineStatus\(status\)\),\n\s+\),/,+ );+ assert.match(+ page,+ /tagged\.unmatched\.map\(\(name\) => `LoRA \$\{name\} \(not installed\)`\)/,+ );+ const control = readSrc(+ "features/generation-presets/media-generation-preset-control.tsx",+ );+ assert.match(control, /Paste generation parameters/);+});++test("LoRA tags pasted before a LoRA-capable model is resident match the whole local catalog", async () => {+ const local = [{ id: "add-detail-xl", display_name: "Add detail", source: "local" }];+ const tags = [+ { name: "add-detail-xl", weight: 0.8 },+ { name: "missing", weight: 1 },+ ];+ let fetched = 0;+ const fetchAll = async () => {+ fetched += 1;+ return local;+ };+ // No catalog on the page yet: the installed adapter is found, not reported missing.+ assert.deepEqual(await matchLoraTagsForImport(tags, false, [], fetchAll), {+ loras: ["add-detail-xl:0.8"],+ unmatched: ["missing"],+ notes: [],+ });+ assert.equal(fetched, 1);+ // A resident catalog is used as is, with no extra request.+ assert.deepEqual(+ await matchLoraTagsForImport(tags, true, local, fetchAll),+ matchLoraTags(tags, local),+ );+ assert.deepEqual(await matchLoraTagsForImport(undefined, false, [], fetchAll), {+ loras: [],+ unmatched: [],+ notes: [],+ });+ assert.equal(fetched, 1);+ // The list cannot be read: nothing is called missing.+ const failed = await matchLoraTagsForImport(tags, false, [], async () => {+ throw new Error("offline");+ });+ assert.deepEqual(failed.unmatched, []);+ assert.deepEqual(failed.notes, [+ "LoRA add-detail-xl (the installed LoRAs could not be listed)",+ "LoRA missing (the installed LoRAs could not be listed)",+ ]);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /let tagged = await matchLoraTagsForImport\(\n\s+recipe\.lora_tags,\n\s+\/\/[^\n]*\n\s+loraCapable && loraCatalogFamily === \(status\?\.family \?\? null\),\n\s+availableLoras,\n\s+\/\/[^\n]*\n\s+\(\) => listDiffusionLoras\(status\?\.loaded \? \(status\.family \?\? undefined\) : undefined\),\n\s+\);/,+ );+ // The resident catalog counts only once the fetch for the current family has landed.+ assert.match(+ page,+ /setLoraCatalogFamily\(undefined\);\n\s+if \(!loraCapable\) \{/,+ );+ assert.match(+ page,+ /if \(cancelled\) return;\n\s+setAvailableLoras\(list\);\n\s+setLoraCatalogFamily\(fam\);/,+ );+});++test("LoRAs past the request's adapter limit are named as not applied", () => {+ const loras = Array.from({ length: MAX_LORAS + 2 }, (_, i) => `lora${i}:1`);+ const settings = recipeSettings({ prompt: "p", loras }, DEFAULTS);+ assert.equal(settings.loras.length, MAX_LORAS);+ assert.deepEqual(lorasOverLimit({ prompt: "p", loras }), [+ `lora${MAX_LORAS}`,+ `lora${MAX_LORAS + 1}`,+ ]);+ // Duplicates and invalid rows are not counted against the limit.+ assert.deepEqual(+ lorasOverLimit({ prompt: "p", loras: [...loras.slice(0, MAX_LORAS), "lora0:0.5", "bad"] }),+ [],+ );+ assert.deepEqual(lorasOverLimit({ prompt: "p" }), []);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /const settings = recipeSettings\(merged, \{ width, height, steps, guidance \}\);/);+ assert.match(+ page,+ /\.\.\.lorasOverLimit\(merged\)\.map\(\(id\) => `LoRA \$\{id\} \(over the \$\{MAX_LORAS\} adapter limit\)`\),/,+ );+});++test("a dynamic-prompts prompt starting with { still parses as A1111 parameters", () => {+ const text = "{red|blue} car\nSteps: 20, Sampler: Euler a, CFG scale: 7, Seed: 5, Size: 512x512";+ const r = pastedParameters(text);+ assert.ok(r);+ assert.equal(r.prompt, "{red|blue} car");+ assert.equal(r.seed, 5);+ assert.equal(isGenerationParametersPaste(text), true);+ assert.equal(pastedParameters("{not json"), null);+});++test("a DyLoRA dimension is named as not applied rather than dropped", () => {+ const positional = extractExtraNetworks("a cat <lora:dy:0.8:0.8:16>");+ assert.deepEqual(positional.loras, [{ name: "dy", weight: 0.8, dyn_dim: 16 }]);+ const named = extractExtraNetworks("a cat <lora:dy:te=0.5:unet=0.7:dyn=8>");+ assert.deepEqual(named.loras, [{ name: "dy", weight: 0.5, unet_weight: 0.7, dyn_dim: 8 }]);+ assert.deepEqual(extractExtraNetworks("<lora:dy:1>").loras, [{ name: "dy", weight: 1 }]);+ const m = matchLoraTags(positional.loras, [{ id: "dy", display_name: "dy" }]);+ assert.deepEqual(m.loras, ["dy:0.8"]);+ assert.deepEqual(m.notes, ["LoRA dy dynamic dim 16"]);+});++test("a non-default A1111 Emphasis mode is named as not applied; Original stays silent", () => {+ const parse = (emphasis: string) =>+ importNotApplied(+ parseA1111Parameters(`a cat\nSteps: 20, Seed: 1, Emphasis: ${emphasis}`) ?? { prompt: "" },+ "sdxl",+ );+ assert.deepEqual(parse("No norm"), ["Emphasis: No norm"]);+ assert.deepEqual(parse("Ignore"), ["Emphasis: Ignore"]);+ assert.deepEqual(parse("Original"), []);+});++test("a paste is reported applied only once its settings land, and a later import wins", () => {+ const page = readSrc("features/images/images-page.tsx");+ // A sequence token taken before the LoRA lookup: an earlier import finishing late changes nothing.+ assert.match(+ page,+ /async \(recipe: ImportedRecipe\): Promise<boolean> => \{\n\s+const seq = \+\+importSeq\.current;\n\s+const modelBefore = loadedModelKey\(status\);\n\s+let tagged = await matchLoraTagsForImport\(/,+ );+ assert.match(+ page,+ /\(\) => listDiffusionLoras\([^\n]*\),\n\s+\);\n\s+if \(seq !== importSeq\.current\) return false;/,+ );+ assert.match(page, /\n\s+return true;\n\s+\},\n\s+\[restoreSettings, width, height,/);+ assert.match(page, /await applyImportedRecipe\(recipe\);\n\s+\},\n\s+\[applyImportedRecipe\],/);+ // The dialog clears and closes only after the awaited apply succeeded.+ const dialog = readSrc("features/images/paste-parameters-dialog.tsx");+ assert.match(dialog, /onApply: \(text: string\) => Promise<boolean>;/);+ assert.match(+ dialog,+ /const apply = async \(\) => \{\n\s+if \(text\.trim\(\) && \(await onApply\(text\)\)\) \{\n\s+onTextChange\(""\);\n\s+onOpenChange\(false\);/,+ );+});++test("LoRA matches from before a model switch during the lookup are not restored", () => {+ assert.deepEqual(loraTagNames([{ name: "a", weight: 1 }, { weight: 1 }, null, { name: "b", weight: 0.5 }]), [+ "a",+ "b",+ ]);+ assert.deepEqual(loraTagNames(undefined), []);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /const statusRef = useRef\(status\);\n\s+statusRef\.current = status;/);+ assert.match(+ page,+ /const seq = \+\+importSeq\.current;\n\s+const modelBefore = loadedModelKey\(status\);\n\s+let tagged = await matchLoraTagsForImport\(/,+ );+ assert.match(+ page,+ /if \(seq !== importSeq\.current\) return false;\n[^\n]*\n\s+if \(loadedModelKey\(statusRef\.current\) !== modelBefore\) \{\n\s+tagged = \{\n\s+loras: \[\],\n\s+unmatched: \[\],\n\s+notes: loraTagNames\(recipe\.lora_tags\)\.map\(\(n\) => `LoRA \$\{n\} \(model changed during import\)`\),/,+ );+});++test("steps past the request limit are reported as clamped", () => {+ const r = parseA1111Parameters("a cat\nSteps: 150, Seed: 1");+ assert.ok(r);+ assert.equal(recipeSettings(r, DEFAULTS).steps, 100);+ assert.deepEqual(importNotApplied(r, "sdxl"), ["Steps 150 (clamped to 100)"]);+ assert.deepEqual(importNotApplied({ prompt: "p", steps: 0 }, "sdxl"), ["Steps 0 (clamped to 1)"]);+ assert.deepEqual(importNotApplied({ prompt: "p", steps: 100 }, "sdxl"), []);+});++test("a LoRA tag takes the exact path first and never guesses between same-named adapters", () => {+ const available = [+ { id: "sdxl/detail.safetensors", display_name: "detail", source: "local" },+ { id: "flux/detail.safetensors", display_name: "detail", source: "local" },+ { id: "styles/Pixel_Art.safetensors", display_name: "Pixel_Art", source: "local" },+ ];+ const m = matchLoraTags(+ [+ { name: "flux\\detail", weight: 1 },+ { name: "detail", weight: 0.5 },+ { name: "pixel_art", weight: 1 },+ ],+ available,+ );+ assert.deepEqual(m.loras, ["flux/detail.safetensors:1", "styles/Pixel_Art.safetensors:1"]);+ assert.deepEqual(m.unmatched, []);+ assert.deepEqual(m.notes, ["LoRA detail (ambiguous: 2 adapters named detail)"]);+});++test("each textual-inversion embedding in TI hashes is named as not applied", () => {+ const r = parseA1111Parameters(+ 'a cat, easynegative\nSteps: 20, Seed: 1, TI hashes: "easynegative: c74b4e810b03, badhandv4: 5e40d722fc3d"',+ );+ assert.ok(r);+ assert.deepEqual(importNotApplied(r, "sdxl"), [+ "textual inversion easynegative",+ "textual inversion badhandv4",+ ]);+});++test("the model identity an import checks covers the engine and build, not only repo and family", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /const loadedModelKey = \(s: DiffusionStatus \| null\): string \| null =>\n\s+s\?\.loaded\n\s+\? JSON\.stringify\(\[\n\s+s\.repo_id,\n\s+s\.base_repo,\n\s+s\.family,\n\s+s\.engine,\n\s+s\.gguf_filename,\n\s+s\.dtype,\n\s+s\.transformer_quant,\n\s+s\.text_encoder_quant,\n\s+\]\)\n\s+: null;/,+ );+});diff --git a/studio/frontend/tests/image-restore-negative-prompt.test.ts b/studio/frontend/tests/image-restore-negative-prompt.test.tsindex baed9c65431..f2bece39bdf 100644--- a/studio/frontend/tests/image-restore-negative-prompt.test.ts+++ b/studio/frontend/tests/image-restore-negative-prompt.test.ts@@ -6,6 +6,7 @@ import test from "node:test";import ts from "@typescript/typescript6";import { readSrc } from "./helpers/kit.ts";import { enhanceRestoreFor } from "../src/features/images/lib/prompt-enhance.ts";+import { restoredInpaintMaskOptions } from "../src/features/images/lib/inpaint-options.ts";function restoreSettingsWith(negativeCapable: boolean) {const source = readSrc("features/images/images-page.tsx");@@ -49,6 +50,7 @@ function restoreSettingsWith(negativeCapable: boolean) {changeSamplerChoice: () => {},// Its return value is read, so it cannot be a recording no-op.enhanceRestoreFor,+ restoredInpaintMaskOptions,toast: { success: () => {} },};// Every closure name the callback reads that is not a real global resolves to a recording no-op,diff --git a/studio/frontend/tests/image-seed-inpaint-steps.test.ts b/studio/frontend/tests/image-seed-inpaint-steps.test.tsnew file mode 100644index 00000000000..968e6f36d5a--- /dev/null+++ b/studio/frontend/tests/image-seed-inpaint-steps.test.ts@@ -0,0 +1,268 @@+// 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 {+ defaultsFor,+ STEPS_REQUEST_MAX,+ STEPS_SLIDER_MAX,+ stepsSliderMax,+} from "../src/features/images/image-generation-defaults.ts";+import {+ INPAINT_PADDING_DEFAULT,+ inpaintMaskRequestFields,+ MASK_BLUR_DEFAULT,+ inpaintOptionsNotApplied,+ restoredInpaintMaskOptions,+} from "../src/features/images/lib/inpaint-options.ts";+import {+ lastSeedOf,+ reusableSeed,+} from "../src/features/images/lib/seed-controls.ts";+import { readSrc } from "./helpers/kit.ts";++test("the Steps slider reaches every model's default: Krea-2-raw ships 52", () => {+ const krea2Raw = defaultsFor("krea/Krea-2-raw").steps;+ assert.equal(krea2Raw, 52);+ assert.ok(stepsSliderMax(krea2Raw, krea2Raw) >= krea2Raw);+ assert.equal(stepsSliderMax(krea2Raw, krea2Raw), STEPS_REQUEST_MAX);+ assert.equal(+ stepsSliderMax(defaultsFor("black-forest-labs/FLUX.1-schnell").steps, 4),+ STEPS_SLIDER_MAX,+ );+ assert.equal(stepsSliderMax(25, 25), 50);+ assert.equal(stepsSliderMax(30, 30), 60);+ assert.equal(stepsSliderMax(8, 80), 80);+ assert.equal(stepsSliderMax(8, 150), STEPS_REQUEST_MAX);+ assert.equal(stepsSliderMax(Number.NaN, 4), STEPS_SLIDER_MAX);+ for (const id of [+ "krea-2-raw",+ "lumina",+ "hunyuanimage",+ "hidream",+ "qwen-image-2512",+ "flux.3-klein-base",+ ]) {+ const d = defaultsFor(id).steps;+ assert.ok(stepsSliderMax(d, d) >= d, id);+ }+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /max=\{stepsSliderMax\(pendingModelDefaults\?\.steps \?\? residentSteps, steps\)\}/,+ );+ assert.doesNotMatch(page, /label="Steps"[\s\S]{0,300}max=\{50\}/);+});++test("Reuse last seed takes this session's run base seed, else the newest record's", () => {+ const run = [+ { seed: 101, batch_seed: 100, created_at: 5 },+ { seed: 102, batch_seed: 100, created_at: 5 },+ ];+ assert.equal(lastSeedOf(run), 100);+ assert.equal(lastSeedOf([{ seed: 7, created_at: 1 }]), 7);+ assert.equal(+ lastSeedOf([{ seed: 7, created_at: 1, model_kind: "connection" }]),+ null,+ );+ assert.equal(lastSeedOf([]), null);+ const gallery = [+ { seed: 1, created_at: 10 },+ { seed: 2, batch_seed: 20, created_at: 30 },+ { seed: 3, created_at: 40, model_kind: "connection" },+ ];+ assert.equal(reusableSeed(null, gallery), 20);+ assert.equal(reusableSeed(555, gallery), 555);+ assert.equal(reusableSeed(null, []), null);+ // Seed 0 is a real seed, not "none".+ assert.equal(reusableSeed(0, gallery), 0);+});++test("the Seed field has Random and Reuse last seed buttons", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /aria-label="Random seed"[\s\S]{0,200}onClick=\{\(\) => setSeed\(""\)\}/,+ );+ assert.match(+ page,+ /aria-label="Reuse last seed"[\s\S]{0,300}if \(lastSeed !== null\) setSeed\(String\(lastSeed\)\);/,+ );+ assert.match(+ page,+ /const runSeed = lastSeedOf\(res\.images\);\n\s+if \(runSeed !== null\) setSessionSeed\(runSeed\);/,+ );+ // A HugeIcons glyph only this lazy page uses still lands in the eager icon chunk via the barrel+ // and pushed the startup budget over, so Reuse last seed draws lucide's Recycle.+ assert.match(page, /<Recycle className="size-4" strokeWidth=\{1\.5\} \/>/);+ assert.doesNotMatch(page, /Recycle01Icon/);+});++test("inpaint mask options send nothing at their defaults", () => {+ const defaults = {+ maskBlur: MASK_BLUR_DEFAULT,+ onlyMasked: false,+ padding: INPAINT_PADDING_DEFAULT,+ };+ assert.deepEqual(inpaintMaskRequestFields(defaults, true), {});+ assert.deepEqual(inpaintMaskRequestFields(defaults, false), {});+ assert.deepEqual(+ inpaintMaskRequestFields({ ...defaults, maskBlur: 4 }, false),+ { mask_blur: 4 },+ );+ assert.deepEqual(+ inpaintMaskRequestFields({ ...defaults, maskBlur: 99.6 }, false),+ { mask_blur: 64 },+ );+ assert.deepEqual(+ inpaintMaskRequestFields({ ...defaults, onlyMasked: true }, true),+ {+ inpaint_only_masked: true,+ inpaint_padding: 32,+ },+ );+ // A model whose inpaint pipeline cannot crop never gets the field (the backend would refuse it).+ assert.deepEqual(+ inpaintMaskRequestFields({ ...defaults, onlyMasked: true }, false),+ {},+ );+ assert.deepEqual(+ inpaintMaskRequestFields(+ { maskBlur: 8, onlyMasked: true, padding: 900 },+ true,+ ),+ {+ mask_blur: 8,+ inpaint_only_masked: true,+ inpaint_padding: 256,+ },+ );+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /condStrength = strength;\n\s+condInpaint = inpaintMaskRequestFields\(/,+ );+ assert.match(page, /\.\.\.condInpaint,/);+ assert.match(page, /\{status\?\.supports_inpaint_only_masked && \(/);+});++test("restoring an inpaint record resets mask options it omitted at their defaults", () => {+ assert.deepEqual(restoredInpaintMaskOptions({ workflow: "inpaint" }), {+ maskBlur: MASK_BLUR_DEFAULT,+ onlyMasked: false,+ padding: INPAINT_PADDING_DEFAULT,+ });+ assert.deepEqual(+ restoredInpaintMaskOptions({+ workflow: "inpaint",+ mask_blur: 6,+ inpaint_only_masked: true,+ inpaint_padding: 48,+ }),+ { maskBlur: 6, onlyMasked: true, padding: 48 },+ );+ // Other workflows carry no mask options, so they leave the controls alone.+ assert.deepEqual(restoredInpaintMaskOptions({ workflow: "img2img" }), {});+ assert.deepEqual(restoredInpaintMaskOptions({ workflow: null }), {});+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /const maskOptions = restoredInpaintMaskOptions\(image\);\n\s+if \(maskOptions\.maskBlur !== undefined\) setMaskBlur\(maskOptions\.maskBlur\);/,+ );+});++test("a run whose response was lost still becomes the seed Reuse last seed picks", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /const runBaseSeed = baseSeed \+ i \* batchSize;/);+ assert.match(page, /seed: runBaseSeed,/);+ assert.match(+ page,+ /if \(!\(err instanceof GenerateResponseLostError\)\) throw err;[\s\S]*?if \(!external\) setSessionSeed\(runBaseSeed\);\n\s+setGenDone\(i \+ 1\);\n\s+continue;/,+ );+});++test("with more gallery pages unloaded, only this session's seed is offered", () => {+ const pinned = Array.from({ length: 50 }, (_, i) => ({+ seed: i,+ created_at: i,+ pinned: true,+ }));+ assert.equal(reusableSeed(null, pinned, true), null);+ // The whole gallery is loaded: the newest record by creation time is the newest.+ assert.equal(reusableSeed(null, pinned, false), 49);+ assert.equal(+ reusableSeed(null, [...pinned, { seed: 7, created_at: 100 }], false),+ 7,+ );+ // Unpinned rows page in manual (drag) order, so a loaded unpinned row does not prove the newest is loaded.+ assert.equal(+ reusableSeed(null, [...pinned, { seed: 7, created_at: 100 }], true),+ null,+ );+ assert.equal(reusableSeed(null, [{ seed: 7, created_at: 100 }], true), null);+ assert.equal(reusableSeed(3, pinned, true), 3);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /reusableSeed\(sessionSeed, images, hasMore \|\| archivedEmpty !== true\)/);+});++test("an imported Only masked the loaded pipeline cannot crop is reported as not applied", () => {+ assert.deepEqual(+ inpaintOptionsNotApplied({ inpaint_only_masked: true, inpaint_padding: 48 }, false),+ ["inpaint area only masked (padding 48)"],+ );+ assert.deepEqual(+ inpaintOptionsNotApplied({ inpaint_only_masked: true }, false),+ [`inpaint area only masked (padding ${INPAINT_PADDING_DEFAULT})`],+ );+ assert.deepEqual(+ inpaintOptionsNotApplied({ inpaint_only_masked: true, inpaint_padding: 48 }, true),+ [],+ );+ assert.deepEqual(inpaintOptionsNotApplied({ inpaint_only_masked: false }, false), []);+ assert.deepEqual(inpaintOptionsNotApplied({}, false), []);+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /const missed = inpaintOptionsNotApplied\(settings, status\.supports_inpaint_only_masked === true\);\n\s+notApplied\.unshift\(\.\.\.missed\);/,+ );+});++test("Only masked on with a model that cannot crop is reported once per model, however it got there", () => {+ const page = readSrc("features/images/images-page.tsx");+ // One effect over the status and the switch: an import, a restore, a toggle or a model switch.+ assert.match(+ page,+ /const key =\n\s+status\?\.loaded && inpaintOnlyMasked && status\.supports_inpaint_only_masked !== true\n\s+\? onlyMaskedKeyOf\(status\)\n\s+: null;\n\s+if \(key === null\) \{\n\s+onlyMaskedNotified\.current = null;\n\s+return;\n\s+\}\n\s+if \(onlyMaskedNotified\.current === key\) return;\n\s+onlyMaskedNotified\.current = key;/,+ );+ assert.match(page, /\}, \[status, inpaintOnlyMasked, inpaintPadding\]\);/);+ // The import names it in its own toast, so the effect does not repeat it.+ assert.match(+ page,+ /if \(missed\.length > 0\) onlyMaskedNotified\.current = onlyMaskedKeyOf\(status\);/,+ );+ assert.doesNotMatch(page, /onlyMaskedRecheck/);+});++test("the gallery seed fallback waits until the archive is known to be empty", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(+ page,+ /if \(sessionSeed !== null \|\| hasMore\) return;\n\s+let cancelled = false;\n\s+getGallery\(0, 1, true\)\n\s+\.then\(\(page\) => \{\n\s+if \(!cancelled\) setArchivedEmpty\(page\.images\.length === 0\);/,+ );+ assert.match(page, /if \(!cancelled\) setArchivedEmpty\(false\);/);+ assert.match(page, /\}, \[sessionSeed, hasMore, images\.length, archiveChangeKey\]\);/);+ // An archive change made elsewhere (Settings) re-runs the check even when the strip is unchanged.+ assert.match(+ page,+ /subscribeArchiveChanged\("images", \(\) => setArchiveChangeKey\(\(k\) => k \+ 1\)\)/,+ );+ const dialog = readSrc("features/settings/components/archived-media-dialog.tsx");+ assert.match(dialog, /if \(!succeeded\) break;\n\s+changed = true;/);+ assert.match(dialog, /if \(changed\) notifyArchiveChanged\(kind\);/);+ // The gallery event (which refetches the active strip) still fires only for a restore.+ assert.match(dialog, /if \(restored\) notifyGalleryChanged\(kind\);/);+ // Unknown or non-empty archive: no gallery seed, so an archived newest image is never skipped.+ assert.equal(reusableSeed(null, [{ seed: 7, created_at: 1 }], true), null);+});