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: hide the negative prompt on image models that ignore it (#12914)
Nilay996a03fd5b3d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 001aac67d85..9be35e8001c 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -346,6 +346,20 @@ from utils.paths.path_utils import (logger = get_logger(__name__)+_ZERO_THRESHOLD_NEGATIVE_PROMPT_FAMILIES = frozenset(("z-image", KREA2_FAMILY_NAME))+++def _negative_prompt_engaged(family: DiffusionFamily, guidance: float) -> bool:+ if not family.uses_negative_prompt:+ return False+ if family.cfg_kwarg == "true_cfg_scale":+ return float(guidance) > 1.0+ if family.cfg_kwarg == "guidance_scale":+ threshold = 0.0 if family.name in _ZERO_THRESHOLD_NEGATIVE_PROMPT_FAMILIES else 1.0+ return float(guidance) > threshold+ return True++# Every `import diffusers` below is lazy, so this runs first. On Windows ROCm both reach an absent distributed# backend: diffusers imports xformers on sight, its quantizers torchao.install_xformers_windows_rocm_stub()@@ -9948,7 +9962,11 @@ class DiffusionBackend:kwargs["width"] = iwif "height" in call_params:kwargs["height"] = ih- if negative_prompt and "negative_prompt" in call_params:+ if (+ negative_prompt+ and _negative_prompt_engaged(state.family, guidance)+ and "negative_prompt" in call_params+ ):kwargs["negative_prompt"] = negative_promptelif "negative_prompt" in call_params and true_cfg_needs_empty_negative(state.family.cfg_kwarg, guidance@@ -10422,6 +10440,7 @@ class DiffusionBackend:"images": list(images),"seed": int(seed),"seeds": [int(s) for s in per_image_seeds],+ "negative_prompt": kwargs.get("negative_prompt") or None,"repo_id": state.display_repo_id or state.repo_id,# The BUILD this ran on, not just the repo id: a GGUF quant and a torchao scheme each change the# pixels.@@ -10750,6 +10769,7 @@ class DiffusionBackend:"resolved": resolved,# 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,"conditioning": conditioning_capabilities(state.family, _family_workflows(state.family)),diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 1c292c5c3d4..100e7975504 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -79,6 +79,8 @@ class DiffusionFamily:base_repo: str# Pipeline kwarg carrying guidance. Most use "guidance_scale"; Qwen-Image real CFG is "true_cfg_scale".cfg_kwarg: str = "guidance_scale"+ # False when the diffusers pipeline ignores a negative prompt; the native engine decides on its own.+ uses_negative_prompt: bool = True# The pipe attribute holding the denoiser: ``pipe.transformer`` for DiT families, ``pipe.unet`` for SDXL.denoiser_attr: str = "transformer"# True when a single-file ``.safetensors`` is the WHOLE pipeline (SDXL), so the loader calls ``from_single_file``.@@ -230,6 +232,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (filter_reduction_configs_archs = _REDUCTION_RACE_ARCHS,cudnn_benchmark = False,pipeline_class = "FluxPipeline",+ uses_negative_prompt = False,transformer_class = "FluxTransformer2DModel",base_repo = "black-forest-labs/FLUX.1-schnell",# ComfyUI fixed mu 1.15 for dev / Krea; schnell first (a dev GGUF may resolve to its base). Keys name the model: paths match too.@@ -279,6 +282,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (DiffusionFamily(name = "flux.2-klein",pipeline_class = "Flux2KleinPipeline",+ uses_negative_prompt = False,transformer_class = "Flux2Transformer2DModel",base_repo = "black-forest-labs/FLUX.2-klein-4B",prequant_repos = (@@ -325,6 +329,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (DiffusionFamily(name = "flux.2-dev",pipeline_class = "Flux2Pipeline",+ uses_negative_prompt = False,transformer_class = "Flux2Transformer2DModel",base_repo = "black-forest-labs/FLUX.2-dev",prequant_repos = (@@ -355,6 +360,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (1.15), # ComfyUI ModelSamplingFlux fixed mu 1.15 (Kontext template)pipeline_class = "FluxKontextPipeline",+ uses_negative_prompt = False,transformer_class = "FluxTransformer2DModel",base_repo = "black-forest-labs/FLUX.1-Kontext-dev",aliases = ("flux.1-kontext-dev", "flux1-kontext", "flux-kontext", "kontext"),@@ -728,6 +734,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (DiffusionFamily(name = "ideogram-4",pipeline_class = "Ideogram4Pipeline",+ uses_negative_prompt = False,transformer_class = "Ideogram4Transformer2DModel",base_repo = "ideogram-ai/ideogram-4-fp8",aliases = ("ideogram4", "ideogram-v4", "ideogram"),diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 3c7d6f653a5..2e1936f29f3 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -2276,12 +2276,15 @@ def _estimate_eta(total_steps: int, step: int, first_step_at: float, now: float)return max(0.0, (total_steps - step) * per_step)+_EMBEDDED_GUIDANCE_FAMILIES = ("flux.1", "flux.1-kontext", "flux.2-dev")++def _map_guidance(fam: DiffusionFamily, guidance: Optional[float]) -> tuple[Optional[float], Optional[float]]:"""(cfg_scale, guidance) for sd-cli. Guidance-distilled FLUX runs cfg 1.0 plus the embedded guidance; the rest(FLUX.2-klein included: no guidance embedder) use real CFG, 1.0 when <= 1. Always explicit: sd.cpp defaults to 7.0."""- if fam.name in ("flux.1", "flux.1-kontext", "flux.2-dev"):+ if fam.name in _EMBEDDED_GUIDANCE_FAMILIES:return 1.0, (float(guidance) if guidance is not None else None)if fam.name == "z-image":# diffusers Z-Image computes pos + g * (pos - neg), so its g is standard CFG minus 1 (sd.cpp's cfg 4 == g 3).@@ -3825,6 +3828,8 @@ class SdCppDiffusionBackend:else:seed = int(seed)cfg_scale, flux_guidance = _map_guidance(state.family, guidance)+ if cfg_scale <= 1.0:+ negative_prompt = None# Resolve selected LoRAs up front (a bad id gives a clear 400). Drop weight-0 rows BEFORE the support# gate so an only-disabled request stays a no-op.lora_resolved: list = []@@ -3910,6 +3915,7 @@ class SdCppDiffusionBackend:"images": images,"seed": int(seed),"seeds": seeds,+ "negative_prompt": negative_prompt or None,"repo_id": state.display_repo_id or state.repo_id,# The BUILD, for the recipe: the repo id alone does not say WHICH GGUF quant ran, and two quants# make different pixels.@@ -4479,6 +4485,7 @@ class SdCppDiffusionBackend:transformer_quant = None,),"supports_controlnet": False,+ "supports_negative_prompt": state.family.name not in _EMBEDDED_GUIDANCE_FAMILIES,# "server" = resident sd-server (load once); "oneshot" = legacy per-image sd-cli."native_mode": state.mode,# txt2img always; reference and edit only where this build and its loaded assets run them.diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex f780c0309fe..e9d7f8fc994 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -5101,7 +5101,13 @@ 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.",)- # Additive per-control provenance {control: {value, source, reason}}; null when nothing is loaded. Declared explicitly so pydantic extra='ignore' keeps it.+ supports_negative_prompt: bool = Field(+ True,+ description = "Whether the loaded model applies a negative prompt on this engine "+ "(drives the Negative prompt field). False for FLUX and Ideogram 4 on diffusers, and "+ "for FLUX.1 / Kontext / FLUX.2-dev on the native engine.",+ )+ # declare provenance explicitly because Pydantic extra="ignore" would otherwise discard it.resolved: Optional[Dict[str, DiffusionResolvedControl]] = Field(None,description = "Per-control resolved value + provenance (source auto|explicit + reason), "@@ -5110,11 +5116,7 @@ class DiffusionStatusResponse(BaseModel):class DiffusionInferenceInfo(BaseModel):- """One family's bf16 component sizes + estimated resident footprint per quant scheme.-- Mirrors the dicts ``family_inference_infos()`` returns: the bf16-resident transformer /- text-encoder / VAE sizes, and the estimated resident GB under bf16 and each dense- transformer-quant scheme (transformer * factor + companions), rounded to 1 decimal."""+ """bf16 component sizes and 0.1 GB resident estimates by transformer quantization scheme."""family: str = Field(..., description = "Diffusion family name (auto-policy table key).")transformer_bf16_gb: float = Field(..., description = "bf16-resident transformer size in GB.")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex e95e6cb8c88..95185c0cc9e 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -46394,7 +46394,7 @@ async def generate_diffusion_image(if request.prompts and index < len(request.prompts)else request.prompt),- "negative_prompt": request.negative_prompt,+ "negative_prompt": result.get("negative_prompt"),# Persist the ACTUAL output size, not the request sliders: the conditioned workflows derive it from the upload."width": getattr(image, "width", None) or request.width,"height": getattr(image, "height", None) or request.height,diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 34586d1916a..54f713b8287 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -8172,30 +8172,33 @@ def test_generate_reclaims_model_offload_memory_once_after_success(def test_generate_broadcasts_negative_prompt_across_a_mixed_prompt_batch(fake_runtime, tmp_path):- # A prompt list needs a matching negative list: encode_prompt asserts equal lengths, and pipes that encode the negative separately would build batch-1 embeds against batch-N latents.+ # encode_prompt requires matching lengths to avoid batch-1 embeds with batch-N latents.backend = _load_zimage_backend(tmp_path)- backend.generate(prompt = "fallback", prompts = ["a", "b", "c"], negative_prompt = "blurry")+ backend.generate(+ prompt = "fallback",+ prompts = ["a", "b", "c"],+ negative_prompt = "blurry",+ guidance = 0.5,+ )call = backend._state.pipe.last_kwargsassert call["prompt"] == ["a", "b", "c"]assert call["negative_prompt"] == ["blurry", "blurry", "blurry"]- # An empty negative prompt is still omitted entirely (never sent as [""] * n).+ # empty negatives remain omitted instead of expanding to [""] * n.backend.generate(prompt = "fallback", prompts = ["a", "b"])assert backend._state.pipe.last_kwargs["negative_prompt"] is Nonedef test_generate_keeps_a_scalar_negative_prompt_off_the_list_paths(fake_runtime, tmp_path):- # Uniform-prompt and single-image forwards pass a SCALAR prompt, so the negative prompt must stay scalar too.+ # scalar prompts require scalar negatives on uniform-prompt and single-image paths.backend = _load_zimage_backend(tmp_path)- backend.generate(prompt = "a sloth", seeds = [1, 2, 3], negative_prompt = "blurry")+ backend.generate(prompt = "a sloth", seeds = [1, 2, 3], negative_prompt = "blurry", guidance = 0.5)assert backend._state.pipe.last_kwargs["prompt"] == "a sloth"assert backend._state.pipe.last_kwargs["negative_prompt"] == "blurry"- backend.generate(prompt = "a sloth", seed = 1, negative_prompt = "blurry")+ backend.generate(prompt = "a sloth", seed = 1, negative_prompt = "blurry", guidance = 0.5)assert backend._state.pipe.last_kwargs["negative_prompt"] == "blurry"class _TracingPipe(_CountingPipe):- """Appends ``("call", n)`` to a shared trace so resets can be interleaved with forwards."""-def __init__(self,trace,@@ -14618,7 +14621,7 @@ def test_qwen_true_cfg_gets_an_empty_negative_like_comfy(fake_runtime, tmp_path,backend.generate(prompt = "a sloth", steps = 4, guidance = 4.0)call = backend._state.pipe.last_kwargsassert call["true_cfg_scale"] == 4.0 and call["negative_prompt"] == ""- # An explicit negative is kept; guidance <= 1 never asks for CFG.+ # true CFG engages only above guidance 1 and preserves explicit negatives when engaged.backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 4.0)assert backend._state.pipe.last_kwargs["negative_prompt"] == "blurry"backend.generate(prompt = "a sloth", steps = 4, guidance = 1.0)@@ -14626,11 +14629,62 @@ def test_qwen_true_cfg_gets_an_empty_negative_like_comfy(fake_runtime, tmp_path,def test_guidance_scale_families_get_no_injected_negative(fake_runtime, tmp_path):- backend = _loaded_backend(tmp_path) # z-image: guidance_scale, its own CFG handling+ backend = _loaded_backend(tmp_path) # z-image owns guidance_scale CFG handlingbackend.generate(prompt = "a sloth", steps = 4, guidance = 4.0)assert backend._state.pipe.last_kwargs["negative_prompt"] is None+def test_flux_neither_receives_nor_reports_a_negative_prompt(fake_runtime, tmp_path, monkeypatch):+ diffusers = sys.modules["diffusers"]+ monkeypatch.setattr(diffusers, "FluxPipeline", _FakePipeline, raising = False)+ monkeypatch.setattr(diffusers, "FluxTransformer2DModel", _FakeTransformer, raising = False)+ _no_cache(monkeypatch)+ backend = _loaded_backend(tmp_path, family_override = "flux.1")+ assert backend.status()["supports_negative_prompt"] is False+ out = backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 3.5)+ assert backend._state.pipe.last_kwargs["negative_prompt"] is None+ assert out["negative_prompt"] is None+++def test_qwen_reports_no_negative_when_true_cfg_is_off(fake_runtime, tmp_path, monkeypatch):+ diffusers = sys.modules["diffusers"]+ monkeypatch.setattr(diffusers, "QwenImagePipeline", _FakePipeline, raising = False)+ monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _FakeTransformer, raising = False)+ _no_cache(monkeypatch)+ backend = _loaded_backend(tmp_path, family_override = "qwen-image")+ out = backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 1.0)+ assert backend._state.pipe.last_kwargs["negative_prompt"] is None+ assert out["negative_prompt"] is None+ out = backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 4.0)+ assert out["negative_prompt"] == "blurry"+++def test_sdxl_reports_no_negative_when_cfg_is_off(fake_runtime, tmp_path):+ backend = _loaded_backend(+ tmp_path,+ gguf_filename = "sdxl.safetensors",+ base_repo = None,+ family_override = "sdxl",+ )+ out = backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 1.0)+ assert backend._state.pipe.last_kwargs["negative_prompt"] is None+ assert out["negative_prompt"] is None+ out = backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 1.5)+ assert backend._state.pipe.last_kwargs["negative_prompt"] == "blurry"+ assert out["negative_prompt"] == "blurry"+++def test_cfg_family_reports_the_negative_prompt_it_applied(fake_runtime, tmp_path):+ backend = _loaded_backend(tmp_path)+ assert backend.status()["supports_negative_prompt"] is True+ out = backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 0.0)+ assert backend._state.pipe.last_kwargs["negative_prompt"] is None+ assert out["negative_prompt"] is None+ out = backend.generate(prompt = "a sloth", negative_prompt = "blurry", steps = 4, guidance = 0.5)+ assert backend._state.pipe.last_kwargs["negative_prompt"] == "blurry"+ assert out["negative_prompt"] == "blurry"++class _IdeogramScheduleFakePipe(_FakePipe):def __call__(self,diff --git a/studio/backend/tests/test_saved_image_metadata_precision_contract.py b/studio/backend/tests/test_saved_image_metadata_precision_contract.pyindex f49ead04870..3a9ac021f8f 100644--- a/studio/backend/tests/test_saved_image_metadata_precision_contract.py+++ b/studio/backend/tests/test_saved_image_metadata_precision_contract.py@@ -494,9 +494,7 @@ def test_the_persisted_recipe_records_the_engaged_build_not_the_load_request(engassert meta["model_kind"] == "gguf"assert meta["gguf_filename"] == "z-image-Q4_K_M.gguf"- # ...and again through the response model, because that is what the Recipe popover reads.- # The dict above is pre-serialization: a GalleryImage that stops declaring these fields has- # FastAPI silently strip them from the wire while every assertion above still passes.+ # the Recipe popover reads GalleryImage fields that FastAPI strips when undeclared.body = gen.json()["images"][0]for field, expected in (("transformer_quant", _EngagedBackend.engaged),@@ -509,13 +507,34 @@ def test_the_persisted_recipe_records_the_engaged_build_not_the_load_request(eng)-def test_the_openai_route_persists_the_same_build(engaged_client):- """The other supported way to make an image.+def test_the_recipe_records_only_the_negative_prompt_the_backend_applied(+ engaged_client, monkeypatch+):+ client, backend, saved = engaged_client+ load = client.post(+ "/api/inference/images/load",+ json = {"model_path": "unsloth/Z-Image-Turbo-GGUF", "gguf_filename": "z-image-Q4_K_M.gguf"},+ )+ assert load.status_code == 200, load.text+ body = {"prompt": "a sloth", "negative_prompt": "text, watermark", "guidance": 4.0, "seed": 7}- /v1/images/generations goes through the same backend and the same gallery, and its recipe- was missing every build key -- so an image made through an OpenAI client listed with no- quant, no kind and no filename while the contract above stayed green.- """+ gen = client.post("/api/inference/images/generate", json = body)+ assert gen.status_code == 200, gen.text+ assert saved[-1]["negative_prompt"] is None+ assert gen.json()["images"][0].get("negative_prompt") is None++ ignoring = backend.generate+ monkeypatch.setattr(+ backend,+ "generate",+ lambda **kw: {**ignoring(**kw), "negative_prompt": kw["negative_prompt"]},+ )+ gen = client.post("/api/inference/images/generate", json = body)+ assert gen.status_code == 200, gen.text+ assert saved[-1]["negative_prompt"] == "text, watermark"+++def test_the_openai_route_persists_the_same_build(engaged_client):client, backend, saved = engaged_clientload = client.post("/api/inference/images/load",diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex d46fd69caea..f2c93417cfb 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -2114,7 +2114,7 @@ def test_generate_treats_zero_strength_controlnet_as_disabled(cn_strength):def test_generate_rejects_image_conditioned_on_native_engine():- # img2img / inpaint / reference / upscale are diffusers-only; a native call with an init image gets a clean ValueError, not a silent txt2img.+ # image-conditioned generation is diffusers-only; native calls must fail, not use txt2img.b = _loaded_backend(engine = _FakeEngine())with pytest.raises(ValueError, match = "not yet supported on the native"):b.generate(prompt = "x", steps = 4, seed = 1, init_image = "data:image/png;base64,AAAA")@@ -2125,14 +2125,28 @@ def test_status_native_reports_supports_controlnet_false():assert b.status()["supports_controlnet"] is False+def test_native_negative_prompt_reaches_sd_cli_only_when_cfg_runs():+ klein = _loaded_backend("flux.2-klein")+ assert klein.status()["supports_negative_prompt"] is True+ kw = dict(prompt = "a fox", negative_prompt = "text", width = 256, height = 256, steps = 4, seed = 1)+ out = klein.generate(guidance = 4.0, **kw)+ assert klein._engine.calls[-1][1].negative_prompt == "text"+ assert out["negative_prompt"] == "text"+ out = klein.generate(guidance = 1.0, **kw)+ assert klein._engine.calls[-1][1].negative_prompt is None+ assert out["negative_prompt"] is None++ flux = _loaded_backend("flux.1")+ assert flux.status()["supports_negative_prompt"] is False+ out = flux.generate(guidance = 3.5, **kw)+ assert flux._engine.calls[-1][1].negative_prompt is None+ assert out["negative_prompt"] is None++def test_a_cached_community_repack_is_reused_instead_of_re_downloading_the_mirror(monkeypatch, tmp_path):- """Repointing the tables at unsloth mirrors would re-pull tens of GB on upgrade.-- The HF cache is keyed by repo id, so an install that already holds the byte-identical repack- has it filed under the OLD id: the mirror's namespace is empty, the fetch re-downloads, and an- offline load fails outright over bytes already on disk."""+ """reuse repo-id-keyed legacy caches to avoid redownloads and keep offline loads working."""from core.inference.diffusion_families import prefer_cached_legacy_sourcefrom core.inference.sd_cpp_backend import _fetch_repo_mapdiff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex d27dd16818f..1b621b4cff6 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -71,6 +71,7 @@ export interface DiffusionStatus {supports_lora?: boolean;// Whether the loaded model can apply a ControlNet. Diffusers only, for families with a ControlNet pipeline.supports_controlnet?: boolean;+ supports_negative_prompt?: boolean;// Per-Advanced-control provenance, keyed by control name. Present only when a model is loaded on a// backend that records it; absent on older backends.resolved?: Record<string, DiffusionResolvedControl> | null;diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 307c9393cc6..a0d1e691d70 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -1844,6 +1844,7 @@ export function ImagesPage({// Refresh the ControlNet options when the loaded family changes, and clear a stale selection.const controlnetCapable = Boolean(status?.loaded && status?.supports_controlnet);+ const negativeCapable = status?.supports_negative_prompt !== false;useEffect(() => {if (!controlnetCapable) {setAvailableControlNets([]);@@ -4292,7 +4293,8 @@ export function ImagesPage({res = await generateDiffusionImage({prompt: prompt.trim(),// Only send a negative prompt when guidance uses it, so the recipe does not record one the model ignored.- negative_prompt: guidance > 0 ? negativePrompt.trim() || undefined : undefined,+ negative_prompt:+ negativeCapable && guidance > 0 ? negativePrompt.trim() || undefined : undefined,width: w,height: h,steps,@@ -4395,7 +4397,7 @@ export function ImagesPage({setGenStep(null);setStopping(false);}- }, [allowOversized, livePreview, prompt, negativePrompt, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);+ }, [allowOversized, livePreview, prompt, negativePrompt, negativeCapable, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, 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.@@ -5295,14 +5297,16 @@ export function ImagesPage({onChange={(e) => setPrompt(e.target.value)}/></Field>- <NegativePromptField- value={negativePrompt}- onChange={setNegativePrompt}- open={negativeOpen}- onOpenChange={setNegativeOpen}- hint="What to steer the image away from. Only used when guidance is above 0."- textareaClassName={IMAGE_PROMPT_BOX}- />+ {negativeCapable && (+ <NegativePromptField+ value={negativePrompt}+ onChange={setNegativePrompt}+ open={negativeOpen}+ onOpenChange={setNegativeOpen}+ hint="What to steer the image away from. Only used when guidance is above 0."+ textareaClassName={IMAGE_PROMPT_BOX}+ />+ )}{/* LoRA adapters: shown whenever the loaded model + quant can apply them. Each carries a 0-2 weight. */}{loraCapable && (<Fielddiff --git a/studio/frontend/tests/image-restore-negative-prompt.test.ts b/studio/frontend/tests/image-restore-negative-prompt.test.tsnew file mode 100644index 00000000000..ddcadb5a9bf--- /dev/null+++ b/studio/frontend/tests/image-restore-negative-prompt.test.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import ts from "typescript";+import { readSrc } from "./helpers/kit.ts";++function restoreSettingsWith(negativeCapable: boolean) {+ const source = readSrc("features/images/images-page.tsx");+ const tree = ts.createSourceFile(+ "images-page.tsx",+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );+ let declaration = "";+ const visit = (node: ts.Node) => {+ if (+ ts.isVariableDeclaration(node) &&+ node.name.getText(tree) === "restoreSettings"+ )+ declaration = `const ${node.getText(tree)};`;+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(declaration);+ const { outputText } = ts.transpileModule(+ `${declaration}\nreturn restoreSettings;`,+ {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ },+ );+ const state: Record<string, unknown> = {};+ const known: Record<string, unknown> = {+ useCallback: (fn: unknown) => fn,+ negativeCapable,+ sizeLimits: { maxSide: 2048 },+ MIN_DIM: 256,+ restorableSize: (width: number, height: number) => ({ width, height }),+ matchAspect: () => ({ key: "1:1", portrait: false }),+ restoreInputsNote: () => null,+ CONDITIONED_WORKFLOW_INPUTS: {},+ toast: { success: () => {} },+ };+ const scope = new Proxy(known, {+ has: (target, key) =>+ typeof key === "string" && (key in target || /^set[A-Z]/.test(key)),+ get: (target, key) =>+ typeof key === "string" && key in target+ ? target[key]+ : (...args: unknown[]) => {+ state[key as string] = args.length > 1 ? args : args[0];+ },+ });+ const restore = new Function("scope", `with (scope) { ${outputText} }`)(+ scope,+ );+ return { restore, state };+}++test("restoring an image keeps its negative prompt while a model that ignores one is loaded", () => {+ const { restore, state } = restoreSettingsWith(false);+ restore({+ prompt: "a lighthouse",+ negative_prompt: "blurry, text",+ guidance: 5,+ steps: 30,+ seed: 7,+ width: 1024,+ height: 1024,+ workflow: "create",+ });+ assert.equal(state.setNegativePrompt, "blurry, text");+});