Skip to content

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

Studio: multi-image editing for Qwen-Image-Edit (#14230)

Daniel Hane2b42752bd68
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index ed000e9ecaa..72c27134b38 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -83,6 +83,7 @@ from .diffusion_families import (
resolve_base_repo,
resolve_local_gguf_child,
supported_family_names,
+ family_for_checkpoint,
transformer_config_overrides_for,
transformer_variant_differs_from_base,
)
@@ -111,7 +112,9 @@ from .diffusion_conditioning import (
check_conditioned_fields,
check_output_size,
conditioning_capabilities,
+ EDIT_EXTRA_IMAGE_AREA,
decode_condition_images,
+ edit_takes_extra_images,
effective_reference_resolution,
match_source_size,
)
@@ -9421,7 +9424,9 @@ class DiffusionBackend:
te_releaser = te_release.maybe_install(pipe, plan, logger = logger)
state = _LoadState(
pipe = pipe,
- family = fam,
+ family = family_for_checkpoint(
+ fam, gguf_filename, repo_id, display_repo_id, base
+ ),
repo_id = repo_id,
display_repo_id = display_repo_id,
base_repo = base,
@@ -11660,7 +11665,11 @@ class DiffusionBackend:
controlnet = controlnet,
localized_edit = localized_edit,
)
- if reference_images and not getattr(fam, "reference", False):
+ if (
+ reference_images
+ and not getattr(fam, "reference", False)
+ and not edit_takes_extra_images(fam)
+ ):
raise ValueError(
f"Reference images are not supported for the '{fam.name}' model family."
)
@@ -11681,10 +11690,16 @@ class DiffusionBackend:
"support masks (mask_image)."
)
workflow = "edit"
- # RGB for the instruction editors; the layered VAE reads the alpha as a fourth channel.
- init_pil = decode_b64_image(
- init_image, mode = getattr(fam, "condition_image_mode", "RGB") or "RGB"
- )
+ if any(reference_images or ()):
+ # Multi-image edit (Qwen-Image-Edit-Plus): the source, then each extra image in request order,
+ # bounded and budgeted like the reference workflow's. The output still takes the source's size.
+ images_in = decode_condition_images(fam, init_image, reference_images)
+ init_pil, ref_extra = images_in[0], images_in[1:]
+ else:
+ # RGB for the instruction editors; the layered VAE reads the alpha as a fourth channel.
+ init_pil = decode_b64_image(
+ init_image, mode = getattr(fam, "condition_image_mode", "RGB") or "RGB"
+ )
elif requested_workflow == "edit":
if not getattr(fam, "unified_edit", False):
raise ValueError(
@@ -11977,7 +11992,12 @@ class DiffusionBackend:
* getattr(fam, "condition_pixel_weight", 1.0)
)
if is_flux3_family(fam) and init_pil is not None
- else 0
+ # A multi-image edit VAE-encodes each extra image at ~1 MP beside the source.
+ else int(
+ len(ref_extra)
+ * EDIT_EXTRA_IMAGE_AREA
+ * getattr(fam, "condition_pixel_weight", 1.0)
+ )
)
)
if layer_count:
diff --git a/studio/backend/core/inference/diffusion_conditioning.py b/studio/backend/core/inference/diffusion_conditioning.py
index 807819e0f5d..d833f9ee081 100644
--- a/studio/backend/core/inference/diffusion_conditioning.py
+++ b/studio/backend/core/inference/diffusion_conditioning.py
@@ -232,6 +232,18 @@ def decode_condition_images(
return images
+# QwenImageEditPlusPipeline's VAE_IMAGE_SIZE: each image of a multi-image edit is VAE-encoded at this area (pixels).
+EDIT_EXTRA_IMAGE_AREA = 1024 * 1024
+
+
+def edit_takes_extra_images(fam: Any) -> bool:
+ """An instruction-edit family that reads more than the source in one edit (Qwen-Image-Edit-Plus): its edit
+ workflow takes ``reference_images`` after ``init_image``, up to ``max_condition_images`` in total."""
+ return (
+ bool(getattr(fam, "edit", False)) and int(getattr(fam, "max_condition_images", 4) or 4) > 1
+ )
+
+
def conditioning_capabilities(fam: Any, workflows: Sequence[str]) -> dict[str, Any]:
"""What the UI may offer for ``fam`` given the ``workflows`` the active engine runs for it.
Localized editing is advertised only where the unified edit workflow itself is."""
@@ -244,5 +256,7 @@ def conditioning_capabilities(fam: Any, workflows: Sequence[str]) -> dict[str, A
"max_output_pixels": int(getattr(fam, "max_output_pixels", 2048 * 2048) or 2048 * 2048),
"reference_resolutions": list(getattr(fam, "reference_resolutions", ()) or ()),
"unified_edit": unified,
+ # Edit-only families whose edit takes the extra images too (the UI shows them on the Edit tab).
+ "multi_image_edit": edit_takes_extra_images(fam) and "edit" in workflows,
"localized_edit_modes": list(LOCALIZED_EDIT_MODES) if unified else [],
}
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index ea7f7c17442..ba3e0884516 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -17,7 +17,7 @@ import os
import re
import sys
import tempfile
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from pathlib import Path, PurePosixPath
from typing import Any, Iterable, Mapping, NamedTuple, Optional, Sequence
from utils.paths.path_utils import is_appledouble_metadata
@@ -140,6 +140,9 @@ class DiffusionFamily:
transformer_config_variants: tuple[tuple[str, tuple[tuple[str, Any], ...]], ...] = field(
default_factory = tuple
)
+ # (lowercased id substring, max_condition_images) for a family whose checkpoints take different counts; first
+ # match wins, none keeps ``max_condition_images``.
+ max_condition_images_variants: tuple[tuple[str, int], ...] = field(default_factory = tuple)
# Same config, different weights: a GGUF of one must never get the base's transformer of another.
checkpoint_variants: tuple[str, ...] = field(default_factory = tuple)
# Activation-guard cost of one condition pixel relative to one output pixel.
@@ -655,6 +658,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
te_quant_auto = "fp8",
aliases = ("flux.1-kontext-dev", "flux1-kontext", "flux-kontext", "kontext"),
edit = True,
+ # FluxKontextPipeline conditions on one image.
+ max_condition_images = 1,
# Native: FLUX.1's VAE + CLIP-L / T5-XXL, the source as a reference image (sd.cpp docs/kontext.md).
sd_cpp_vae = ("black-forest-labs/FLUX.1-schnell", "ae.safetensors"),
sd_cpp_text_encoders = _FLUX1_SD_CPP_TEXT_ENCODERS,
@@ -703,6 +708,16 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
"qwenimageedit",
),
edit = True,
+ # The source plus up to two more images in one edit (2509 / 2511 multi-image editing): the Plus pipeline reads
+ # each through the VLM as "Picture N" and VAE-encodes it beside the source. ComfyUI's TextEncodeQwenImageEditPlus
+ # node takes image1..image3, so 3 in total.
+ max_condition_images = 3,
+ # The original Qwen-Image-Edit was trained on the source alone: it keeps the single-image edit.
+ max_condition_images_variants = (
+ ("qwen-image-edit-2511", 3),
+ ("qwen-image-edit-2509", 3),
+ ("qwen-image-edit", 1),
+ ),
prompt_hint = (
"Write the change you want as an instruction, not a description of the whole picture."
" With several input images, refer to them as Image 1, Image 2 and so on."
@@ -2004,6 +2019,15 @@ def _first_variant(rows: Any, identifiers: tuple[Optional[str], ...]) -> Optiona
return None
+def family_for_checkpoint(fam: Any, *identifiers: Optional[str]) -> Any:
+ """``fam`` with the condition-image limit of the checkpoint ``identifiers`` name (``max_condition_images_variants``),
+ so status, admission and both engines read the loaded checkpoint's limit off the family they hold."""
+ row = _first_variant(getattr(fam, "max_condition_images_variants", ()), identifiers)
+ if row is None or row[1] == getattr(fam, "max_condition_images", None):
+ return fam
+ return replace(fam, max_condition_images = row[1])
+
+
def comfy_flow_shift_for(fam: Any, *identifiers: Optional[str]) -> Optional[float]:
row = _first_variant(getattr(fam, "comfy_flow_shift_variants", ()), identifiers)
return row[1] if row else getattr(fam, "comfy_flow_shift", None)
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 99d7a28c140..c98c395fe6a 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -45,6 +45,7 @@ from core.inference.diffusion_families import (
DIFFUSION_NOT_LOADED_MSG,
DiffusionFamily,
DiffusionModelReplacedError,
+ family_for_checkpoint,
LoadIdentity,
detect_family_for_pick,
load_identity,
@@ -3575,7 +3576,9 @@ class SdCppDiffusionBackend:
display_repo_id = display_repo_id,
# The card's base when it shipped the grid, as the diffusers route reports it.
base_repo = grid_base if sample_sigmas else base,
- family = fam,
+ family = family_for_checkpoint(
+ fam, gguf_filename, repo_id, display_repo_id, base
+ ),
device = device,
files = files,
vae_format = fam.sd_cpp_vae_format,
@@ -4266,7 +4269,15 @@ class SdCppDiffusionBackend:
f"The reference workflow is not supported for the '{state.family.name}' "
"model family."
)
- if reference_images and not getattr(state.family, "reference", False):
+ from core.inference.diffusion_conditioning import edit_takes_extra_images
+
+ # sd.cpp's Qwen-Image-Edit conditioner reads every ref image as "Picture N", so a multi-image edit runs
+ # natively too.
+ if (
+ reference_images
+ and not getattr(state.family, "reference", False)
+ and not edit_takes_extra_images(state.family)
+ ):
raise ValueError(
f"Reference images are not supported for the '{state.family.name}' "
"model family."
diff --git a/studio/backend/tests/test_diffusion_qwen_edit_multi_image.py b/studio/backend/tests/test_diffusion_qwen_edit_multi_image.py
new file mode 100644
index 00000000000..21a2cdaa4de
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_qwen_edit_multi_image.py
@@ -0,0 +1,143 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Qwen-Image-Edit multi-image editing on the diffusers engine: the source plus up to two more images reach
+QwenImageEditPlusPipeline as one ordered list, a single-image edit is unchanged, and Kontext keeps one image."""
+
+from __future__ import annotations
+
+import base64
+import io
+
+import pytest
+from PIL import Image
+
+from core.inference import diffusion_conditioning as cond
+from core.inference.diffusion import DiffusionBackend
+from core.inference.diffusion_families import detect_family, family_for_checkpoint
+
+from .test_diffusion_backend import _FakePipeline, _FakeTransformer, _load_into, fake_runtime # noqa: F401
+
+COLORS = [(200, 10, 10), (10, 200, 10), (10, 10, 200)]
+
+
+def _png(size = (64, 48), color = (200, 10, 10)) -> str:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, format = "PNG")
+ return base64.b64encode(buf.getvalue()).decode()
+
+
+def qwen_edit(fake_runtime, tmp_path):
+ (tmp_path / "model.gguf").write_bytes(b"x")
+ backend = DiffusionBackend()
+ _load_into(
+ backend, tmp_path, base_repo = "Qwen/Qwen-Image-Edit-2511", family_override = "qwen-image-edit"
+ )
+ return backend
+
+
+def test_qwen_edit_takes_three_images_and_kontext_and_layered_one():
+ qwen = detect_family("unsloth/Qwen-Image-Edit-2511-GGUF")
+ kontext = detect_family("black-forest-labs/FLUX.1-Kontext-dev")
+ layered = detect_family("unsloth/Qwen-Image-Layered-GGUF")
+ assert qwen.max_condition_images == 3 and cond.edit_takes_extra_images(qwen)
+ assert kontext.max_condition_images == 1 and not cond.edit_takes_extra_images(kontext)
+ assert layered.max_condition_images == 1 and not cond.edit_takes_extra_images(layered)
+ # Reference / unified-edit families are not edit-only: they keep their own paths.
+ assert not cond.edit_takes_extra_images(detect_family("unsloth/FLUX.2-klein-4B-GGUF"))
+
+
+def test_only_the_plus_checkpoints_take_extra_images():
+ fam = detect_family("unsloth/Qwen-Image-Edit-2511-GGUF")
+ for ids, limit in (
+ (("qwen-image-edit-2511-Q4_K_M.gguf", "unsloth/Qwen-Image-Edit-2511-GGUF"), 3),
+ (("Qwen/Qwen-Image-Edit-2509",), 3),
+ (("qwen_image_edit_2509_fp8_e4m3fn.safetensors",), 3),
+ (("Qwen/Qwen-Image-Edit",), 1),
+ (("qwen-image-edit-Q4_K_M.gguf", "Qwen/Qwen-Image-Edit-2511"), 1),
+ # A local folder naming no checkpoint keeps the family's (2511) limit.
+ (("/models/my_edit", None, "Qwen/Qwen-Image-Edit-2511"), 3),
+ ):
+ scoped = family_for_checkpoint(fam, *ids)
+ assert scoped.max_condition_images == limit, ids
+ assert cond.edit_takes_extra_images(scoped) is (limit > 1)
+ assert family_for_checkpoint(fam, "Qwen/Qwen-Image-Edit-2511") is fam
+
+
+def test_the_original_edit_checkpoint_keeps_one_image(fake_runtime, tmp_path):
+ (tmp_path / "model.gguf").write_bytes(b"x")
+ backend = DiffusionBackend()
+ _load_into(
+ backend, tmp_path, base_repo = "Qwen/Qwen-Image-Edit", family_override = "qwen-image-edit"
+ )
+ c = backend.status()["conditioning"]
+ assert c["max_condition_images"] == 1 and c["multi_image_edit"] is False
+ with pytest.raises(ValueError, match = "Reference images are not supported"):
+ backend.generate(prompt = "x", steps = 4, seed = 1, init_image = _png(), reference_images = [_png()])
+
+
+def test_status_advertises_the_multi_image_edit(qwen_edit):
+ c = qwen_edit.status()["conditioning"]
+ assert c["max_condition_images"] == 3 and c["multi_image_edit"] is True
+ assert c["unified_edit"] is False and c["localized_edit_modes"] == []
+
+
+def test_extra_images_reach_the_pipeline_in_request_order(qwen_edit):
+ pipe = qwen_edit._state.pipe
+ qwen_edit.generate(
+ prompt = "the person in image 1 holds the cup from image 2 in the room of image 3",
+ steps = 4,
+ guidance = 4.0,
+ seed = 1,
+ init_image = _png((64, 48), COLORS[0]),
+ reference_images = [_png((32, 32), COLORS[1]), _png((40, 24), COLORS[2])],
+ )
+ images = pipe.last_kwargs["image"]
+ assert isinstance(images, list) and len(images) == 3
+ assert [img.getpixel((0, 0)) for img in images] == COLORS
+ # The output takes the source's size, not the last image's.
+ assert (pipe.last_kwargs.get("width"), pipe.last_kwargs.get("height")) in (
+ (64, 48),
+ (None, None),
+ )
+
+
+def test_a_single_image_edit_still_passes_the_bare_image(qwen_edit):
+ pipe = qwen_edit._state.pipe
+ for refs in (None, [], [""]):
+ qwen_edit.generate(
+ prompt = "make it night",
+ steps = 4,
+ guidance = 4.0,
+ seed = 1,
+ init_image = _png(),
+ reference_images = refs,
+ )
+ image = pipe.last_kwargs["image"]
+ assert isinstance(image, Image.Image) and image.size == (64, 48)
+
+
+def test_a_fourth_image_is_refused_not_truncated(qwen_edit):
+ with pytest.raises(ValueError, match = "at most 3 input images"):
+ qwen_edit.generate(
+ prompt = "x", steps = 4, seed = 1, init_image = _png(), reference_images = [_png()] * 3
+ )
+
+
+def test_kontext_refuses_extra_images(fake_runtime, tmp_path):
+ import sys
+
+ sys.modules["diffusers"].FluxKontextPipeline = _FakePipeline
+ sys.modules["diffusers"].FluxTransformer2DModel = _FakeTransformer
+ (tmp_path / "model.gguf").write_bytes(b"x")
+ backend = DiffusionBackend()
+ _load_into(
+ backend,
+ tmp_path,
+ base_repo = "black-forest-labs/FLUX.1-Kontext-dev",
+ family_override = "flux.1-kontext",
+ )
+ assert backend.status()["conditioning"]["multi_image_edit"] is False
+ with pytest.raises(ValueError, match = "Reference images are not supported"):
+ backend.generate(prompt = "x", steps = 4, seed = 1, init_image = _png(), reference_images = [_png()])
diff --git a/studio/backend/tests/test_sd_cpp_edit_families.py b/studio/backend/tests/test_sd_cpp_edit_families.py
index 5d1cd884b20..ee081373965 100644
--- a/studio/backend/tests/test_sd_cpp_edit_families.py
+++ b/studio/backend/tests/test_sd_cpp_edit_families.py
@@ -298,8 +298,6 @@ def test_edit_only_families_refuse_what_the_diffusers_engine_refuses(fam, files)
b.generate(prompt = "p", steps = 2, width = 512, height = 512)
with pytest.raises(ValueError, match = "reference workflow is not supported"):
b.generate(prompt = "p", steps = 2, init_image = _png(), workflow = "reference")
- with pytest.raises(ValueError, match = "Reference images are not supported"):
- b.generate(prompt = "p", steps = 2, init_image = _png(), reference_images = [_png()])
with pytest.raises(ValueError, match = "mask_image is not supported"):
b.generate(prompt = "p", steps = 2, init_image = _png(), mask_image = _png())
@@ -408,3 +406,60 @@ def test_an_uncached_projector_fails_an_offline_edit_only_load(monkeypatch, tmp_
assert SdCppDiffusionBackend(engine = None)._fetch_assets(
assets, None, local_files_only = True
) == {"qwen2vl": str(cached)}
+
+
+# -- multi-image edit -------------------------------------------------------------------------------
+
+
+def test_kontext_still_refuses_extra_images():
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ b._state = _state(KONTEXT, KONTEXT_FILES)
+ with pytest.raises(ValueError, match = "Reference images are not supported"):
+ b.generate(prompt = "p", steps = 2, init_image = _png(), reference_images = [_png()])
+
+
+def test_qwen_edit_sends_every_image_as_a_ref_image_in_order():
+ """sd.cpp's Qwen-Image-Edit conditioner reads each ref image as "Picture N": the source first, then the extras."""
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ b._state, server = _server_state(QWEN_EDIT, QWEN_FILES)
+ colors = [(200, 10, 10), (10, 200, 10), (10, 10, 200)]
+ b.generate(
+ prompt = "p",
+ steps = 20,
+ guidance = 4.0,
+ seed = 3,
+ init_image = _png(color = colors[0]),
+ reference_images = [_png((512, 512), colors[1]), _png((640, 480), colors[2])],
+ workflow = "edit",
+ )
+ body = server.payloads[-1]
+ # The output still takes the source's size.
+ assert (body["width"], body["height"]) == (768, 496)
+ assert len(body["ref_images"]) == 3
+ seen = []
+ for ref in body["ref_images"]:
+ img = Image.open(io.BytesIO(base64.b64decode(ref.split(",", 1)[1]))).convert("RGB")
+ seen.append(img.getpixel((img.width // 2, img.height // 2)))
+ assert seen == colors
+
+
+def test_qwen_edit_refuses_more_than_three_images():
+ b = SdCppDiffusionBackend(engine = _FakeEngine())
+ b._state = _state(QWEN_EDIT, QWEN_FILES)
+ with pytest.raises(ValueError, match = "at most 3 input images"):
+ b.generate(prompt = "p", steps = 2, init_image = _png(), reference_images = [_png()] * 3)
+
+
+def test_native_status_advertises_a_multi_image_edit_only_for_qwen_edit(monkeypatch):
+ from core.inference.diffusion_conditioning import conditioning_capabilities
+
+ assert conditioning_capabilities(QWEN_EDIT, ["edit"])["multi_image_edit"] is True
+ assert conditioning_capabilities(QWEN_EDIT, ["edit"])["max_condition_images"] == 3
+ # Not edit-ready (no projector): no edit, so no extra images either.
+ assert conditioning_capabilities(QWEN_EDIT, [])["multi_image_edit"] is False
+ assert conditioning_capabilities(KONTEXT, ["edit"])["multi_image_edit"] is False
+ assert conditioning_capabilities(KONTEXT, ["edit"])["max_condition_images"] == 1
+ layered = detect_family("unsloth/Qwen-Image-Layered-GGUF")
+ assert conditioning_capabilities(layered, ["edit"])["multi_image_edit"] is False
+ flux2 = detect_family("unsloth/FLUX.2-klein-4B-GGUF")
+ assert conditioning_capabilities(flux2, ["txt2img", "reference"])["multi_image_edit"] is False
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 170d0836bba..94ad3a68e43 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -108,6 +108,9 @@ export interface DiffusionConditioning {
max_output_pixels: number;
reference_resolutions: number[];
unified_edit: boolean;
+ // An edit-only family whose Edit takes more images after the source (Qwen-Image-Edit-Plus, up to
+ // max_condition_images in total). Absent on older backends.
+ multi_image_edit?: boolean;
localized_edit_modes: LocalizedEditMode[];
// Engine-specific caveats shown next to the inputs.
notes?: string[];
diff --git a/studio/frontend/src/features/images/edit-conditioning.ts b/studio/frontend/src/features/images/edit-conditioning.ts
index 8d153d22a23..7d6af05ee34 100644
--- a/studio/frontend/src/features/images/edit-conditioning.ts
+++ b/studio/frontend/src/features/images/edit-conditioning.ts
@@ -151,7 +151,7 @@ export function resolveEditSize(
return fitSize(custom.width, custom.height, limits);
}
-/** The conditioned half of a Reference / unified Edit request. Empty slots are dropped in order. */
+/** The conditioned half of a Reference / unified or multi-image Edit request. Empty slots are dropped in order. */
export function conditionedRequestFields(opts: {
workflow: "edit" | "reference";
initImage: string;
@@ -170,6 +170,7 @@ export function conditionedRequestFields(opts: {
const allowed = opts.conditioning?.reference_resolutions ?? [];
const extras = opts.extras.filter(Boolean);
const unified = Boolean(opts.conditioning?.unified_edit);
+ const multiEdit = Boolean(opts.conditioning?.multi_image_edit);
const localized =
opts.workflow === "edit" && unified && opts.localized
? opts.localized
@@ -178,7 +179,7 @@ export function conditionedRequestFields(opts: {
workflow: opts.workflow,
init_image: opts.initImage,
reference_images:
- extras.length && (opts.workflow === "reference" || unified)
+ extras.length && (opts.workflow === "reference" || unified || multiEdit)
? extras
: undefined,
reference_resolution:
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 1152f63e38e..97cde4738d4 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -1724,6 +1724,8 @@ export function ImagesPage({
const conditioning = !external && status?.loaded ? (status.conditioning ?? null) : null;
const sizeLimits = useMemo(() => sizeLimitsFrom(conditioning), [conditioning]);
const unifiedEdit = Boolean(conditioning?.unified_edit);
+ // Edit-only model whose Edit takes more images after the source (Qwen-Image-Edit-Plus).
+ const multiImageEdit = !unifiedEdit && Boolean(conditioning?.multi_image_edit);
const referenceResolutions = conditioning?.reference_resolutions ?? [];
const maxExtras = maxAdditionalImages(conditioning, workflow === "edit" && unifiedEdit ? localizedMode : null);
// Controlled so the body-portaled overlays force-close while this page is mounted but off-tab.
@@ -4627,13 +4629,14 @@ export function ImagesPage({
);
return;
}
- const emptySlot = (isReference || unifiedEditRun) ? referenceImages.findIndex((img) => !img) : -1;
+ const multiEditRun = isEdit && multiImageEdit;
+ const emptySlot = (isReference || unifiedEditRun || multiEditRun) ? referenceImages.findIndex((img) => !img) : -1;
if (emptySlot >= 0) {
- const n = isReference ? emptySlot + 2 : additionalImageNumber(emptySlot, localizedMode);
+ const n = unifiedEditRun ? additionalImageNumber(emptySlot, localizedMode) : emptySlot + 2;
toast.error(`Image ${n} is empty. Add it, or remove that slot.`);
return;
}
- if ((isReference || unifiedEditRun) && referenceImages.filter(Boolean).length > maxExtras) {
+ if ((isReference || unifiedEditRun || multiEditRun) && referenceImages.filter(Boolean).length > maxExtras) {
toast.error(
`This model takes at most ${maxExtras + 1 + (unifiedEditRun && localizedMode === "mask" ? 1 : 0)} input images in total. Remove ${referenceImages.filter(Boolean).length - maxExtras}.`,
);
@@ -4672,7 +4675,7 @@ export function ImagesPage({
condInit = initImage ?? undefined;
condUpscale = upscaleFactor;
condStrength = upscaleStrength;
- } else if (isReference || unifiedEditRun) {
+ } else if (isReference || unifiedEditRun || multiEditRun) {
condFields = conditionedRequestFields({
workflow: isReference ? "reference" : "edit",
initImage: initImage!,
@@ -4908,7 +4911,7 @@ export function ImagesPage({
setGenStep(null);
setStopping(false);
}
- }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeCapable, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, 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]);
+ }, [external, allowOversized, livePreview, enhanceOn, upsamplerCapability, prompt, negativePrompt, negativeCapable, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, 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, 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.
@@ -5646,12 +5649,23 @@ export function ImagesPage({
)}
{workflow === "edit" && !unifiedEdit && (
- <Field
- label="Source image"
- hint="The image to edit. Describe the change in the prompt below (e.g. 'make it night', 'add a red hat', 'change the background to a beach')."
- >
- <ImageDropzone value={initImage} onChange={handleInitChange} cropSubject="Source image" />
- </Field>
+ <>
+ <Field
+ label={multiImageEdit ? "Image 1 (source)" : "Source image"}
+ hint="The image to edit. Describe the change in the prompt below (e.g. 'make it night', 'add a red hat', 'change the background to a beach')."
+ >
+ <ImageDropzone
+ value={initImage}
+ onChange={handleInitChange}
+ cropSubject={multiImageEdit ? "Image 1" : "Source image"}
+ />
+ </Field>
+ {multiImageEdit &&
+ renderAdditionalImages(
+ (i) => i + 2,
+ "Another input the instruction can refer to by its number, such as a person, product or style to bring into the source. The output keeps the source's size.",
+ )}
+ </>
)}
{unifiedEditActive && (
diff --git a/studio/frontend/tests/image-multi-image-edit.test.ts b/studio/frontend/tests/image-multi-image-edit.test.ts
new file mode 100644
index 00000000000..027d2b9b91a
--- /dev/null
+++ b/studio/frontend/tests/image-multi-image-edit.test.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Multi-image editing for edit-only models (Qwen-Image-Edit-Plus): the Edit tab offers extra image
+// slots up to the backend's limit, the request sends them after the source in order, and models
+// that take one image (Kontext, Layered, an older backend) keep the single-source Edit request.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { DiffusionConditioning } from "../src/features/images/api.ts";
+import {
+ conditionedRequestFields,
+ maxAdditionalImages,
+ restoreInputsNote,
+} from "../src/features/images/edit-conditioning.ts";
+
+import { readSrc } from "./helpers/kit.ts";
+
+const QWEN_EDIT: DiffusionConditioning = {
+ max_condition_images: 3,
+ alpha: false,
+ dimension_multiple: 16,
+ max_output_side: 2048,
+ max_output_pixels: 2048 * 2048,
+ reference_resolutions: [],
+ unified_edit: false,
+ multi_image_edit: true,
+ localized_edit_modes: [],
+};
+const KONTEXT: DiffusionConditioning = {
+ ...QWEN_EDIT,
+ max_condition_images: 1,
+ multi_image_edit: false,
+};
+
+test("Qwen-Image-Edit takes two images after the source, Kontext none", () => {
+ assert.equal(maxAdditionalImages(QWEN_EDIT, null), 2);
+ assert.equal(maxAdditionalImages(KONTEXT, null), 0);
+});
+
+test("a multi-image edit sends the extras after the source, empty slots dropped in order", () => {
+ const fields = conditionedRequestFields({
+ workflow: "edit",
+ initImage: "SRC",
+ extras: ["A", "", "B"],
+ referenceResolution: 1024,
+ conditioning: QWEN_EDIT,
+ localized: { mode: "mask", image: "M" },
+ });
+ assert.deepEqual(JSON.parse(JSON.stringify(fields)), {
+ workflow: "edit",
+ init_image: "SRC",
+ reference_images: ["A", "B"],
+ });
+});
+
+test("a single-image edit request is unchanged", () => {
+ for (const conditioning of [QWEN_EDIT, KONTEXT, null]) {
+ const fields = conditionedRequestFields({
+ workflow: "edit",
+ initImage: "SRC",
+ extras: [],
+ referenceResolution: null,
+ conditioning,
+ localized: null,
+ });
+ assert.deepEqual(JSON.parse(JSON.stringify(fields)), {
+ workflow: "edit",
+ init_image: "SRC",
+ });
+ }
+ // A family that does not advertise it never sends extras on Edit, even when slots are filled.
+ const older = { ...QWEN_EDIT, multi_image_edit: undefined };
+ const stale = conditionedRequestFields({
+ workflow: "edit",
+ initImage: "SRC",
+ extras: ["A"],
+ referenceResolution: null,
+ conditioning: older,
+ localized: null,
+ });
+ assert.equal(stale.reference_images, undefined);
+});
+
+test("a restored multi-image edit asks for its extras again", () => {
+ assert.equal(
+ restoreInputsNote({ workflow: "edit", reference_image_count: 2 }),
+ "the source image and 2 additional images in the same order",
+ );
+});
+
+test("the Edit tab shows and validates the extra slots for a multi-image edit model", () => {
+ // Structural: the page component is not renderable under node:test.
+ const src = readSrc("features/images/images-page.tsx");
+ assert.match(
+ src,
+ /const multiImageEdit = !unifiedEdit && Boolean\(conditioning\?\.multi_image_edit\)/,
+ );
+ const editTab = src.slice(src.indexOf('{workflow === "edit" && !unifiedEdit && ('));
+ assert.match(
+ editTab.slice(0, 1500),
+ /\{multiImageEdit &&\s*renderAdditionalImages\(\s*\(i\) => i \+ 2,/,
+ );
+ assert.match(src, /const multiEditRun = isEdit && multiImageEdit;/);
+ assert.match(
+ src,
+ /\(isReference \|\| unifiedEditRun \|\| multiEditRun\) \? referenceImages\.findIndex/,
+ );
+ assert.match(
+ src,
+ /\(isReference \|\| unifiedEditRun \|\| multiEditRun\) && referenceImages\.filter\(Boolean\)\.length > maxExtras/,
+ );
+ assert.match(
+ src,
+ /\} else if \(isReference \|\| unifiedEditRun \|\| multiEditRun\) \{\s*condFields = conditionedRequestFields\(/,
+ );
+});