Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(krea2): add edit reference images to Generate and Canvas
Alexander Eichhorne2221340807a
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdxindex 7bb08971ca..3814859286 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx@@ -141,9 +141,9 @@ driving the content. There is **no adapter model and no LoRA**: the reference'sare spliced into the target's, so it works with any Krea-2 checkpoint out of the box.In the Generate panel, add a **Reference Image** while a Krea-2 model is selected, pick an image (cropping-it if you like), and set **Style strength**. The reference applies to Generate and to every Canvas mode. In-the workflow editor the same thing is the **Style Reference - Krea-2** node, feeding the **Style Reference**-input of **Denoise - Krea-2**.+it if you like), leave its **Mode** on **Style** and set **Style strength**. The reference applies to Generate+and to every Canvas mode. In the workflow editor the same thing is the **Style Reference - Krea-2** node,+feeding the **Style Reference** input of **Denoise - Krea-2**.- **Style strength** is the one knob you need. `1.0` is the recommended setting; the slider goes to `2.0`for a heavier effect. `0` disables the reference entirely and costs nothing.@@ -153,7 +153,8 @@ input of **Denoise - Krea-2**.Image** restore them along with the rest of the recipe.:::caution[One reference, matching size, roughly 2x runtime]-- **Exactly one** reference image is used; the Generate panel accepts a single Krea-2 reference.+- **Exactly one** reference image is used. The Generate panel runs one enabled Style reference at a time and+ does not combine it with Edit references.- The reference must be encoded at **the same width and height as the denoise node** — its image tokens areappended to the target's. On the canvas this is wired up for you. In the workflow editor, set the samewidth and height on both nodes, or the denoise node will refuse the reference.@@ -195,7 +196,30 @@ A reference image reaches the model twice, and both are needed:Both keep the image's RGB and drop its alpha channel, as in ai-toolkit training: a transparent PNG showsthe colors hidden under its transparent areas, not a background.-Reference images are set up in the workflow editor:+### In the Generate panel and on the Canvas++1. Add the edit LoRA under **Concepts**.+2. Add the reference images, up to three. Several added at once, or added beside an enabled reference, start+ as **Edit**; a single first reference starts as **Style**, so switch its **Mode** to **Edit**. The enabled+ references are read in card order, which is the order the LoRA's prompt refers to ("Picture 1",+ "Picture 2", ...); use the arrows on each card to reorder them.+3. Describe the result in the prompt, as the LoRA's model card suggests, and press **Invoke**.++To make a control image from a photo, put the photo on the Canvas as a raster layer and filter it with+**DW Openpose** (pose skeleton) or **Depth Anything** (depth map). Then right-click the canvas and choose+**Create From BBox** › **New Global Reference Image**, or save the result to the Gallery and choose **Use as+Reference Image** from the image's right-click menu. Hide or delete the filtered layer afterwards if it should+not be part of the canvas image. On the Canvas the Edit references apply to every mode, including+image-to-image and inpainting.++With CFG above 1 the negative prompt reads the same references. Invoke stays disabled, and says why, while+Edit references are combined with a Style reference or with a [GGUF Qwen3-VL encoder](#qwen3-vl-gguf-encoders).+A Canvas Invoke with enabled regional guidance layers stops with a message instead, since Edit references+cannot be combined with regional prompts. **Reference K/V cache** under **Advanced** sets the+[K/V cache](#reference-kv-cache) below. The references and the K/V cache setting are recorded in image+metadata, so **Recall All** and **Remix Image** restore them.++### In the workflow editor1. For each reference, an **Image to Latents - Qwen Image** node (`qwen_image_i2l`) with **Reference**(`reference`) enabled and width and height left unset. It applies the transformer sizing above.@@ -210,11 +234,13 @@ Reference images are set up in the workflow editor:### Reference K/V cacheEdit LoRAs come in two kinds, and the **Reference K/V Cache** input (`krea2_denoise.reference_kv_cache`)-of **Denoise - Krea-2** has to match how the LoRA was trained:+of **Denoise - Krea-2** has to match how the LoRA was trained. In the Generate panel it is **Reference K/V+cache** under **Advanced**:- **Off** (the default) is for normal edit LoRAs, such as the depth LoRAs. The references join everytransformer pass, and everything attends to everything.-- **On** is for LoRAs trained with ai-toolkit's `kv_cache` option, such as the Krea-2 pose ControlNet LoRA.+- **On** is for LoRAs trained with ai-toolkit's `kv_cache` option, such as the thedeoxen Krea-2 pose+ ControlNet LoRA.They were trained with reference images that only attend to each other. The references then runthrough the transformer once per generation, at the start, and every step reuses what they computed,so generation is faster than with the cache off.@@ -223,7 +249,8 @@ Nothing in a LoRA file says which kind it is. Use what its model card says. Darkfigures with reference images can mean the LoRA was trained with isolated references: turn the cache on.:::caution[Limits]-- At most **3** reference images. Both the prompt node and the denoise node refuse more.+- At most **3** reference images. Both the prompt node and the denoise node refuse more, and the Generate+ panel accepts three.- The denoise node refuses a prompt that was encoded with a different number of reference images than ithas reference latents, for the positive prompt and, when CFG is above 1, the negative prompt.- With the K/V cache off, every reference adds about **4096 tokens per megapixel** to every transformerdiff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdxindex 1ec9cbe574..1d4940b0dc 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx@@ -1,7 +1,7 @@---title: Generate Panel Referencedescription: Every section of the Generate panel in detail — size, render settings, negative prompts, advanced options, resetting to defaults, concepts, reference images and the prompt tools.-lastUpdated: 2026-09-30+lastUpdated: 2026-10-18sidebar:order: 1---@@ -75,6 +75,7 @@ The **Advanced** section appears for models with extra options, and its header c* **Color compensation** — SDXL only.* **PiD Decode** — decodes the image at up to four times its size; see [PiD Super-Resolution Decode](/users-guide/image-generation/advanced-topics/pid-decode/).* **Encoder quantization** — Qwen Image only; quantizes the Qwen VL text encoder to 8-bit or 4-bit on load to save VRAM. A quantized encoder cannot stay in the model cache, so it is loaded from disk on every generation, twice when CFG is above 1.+* **Reference K/V cache** — Krea-2 only, and only with **Edit** references. Turn it on for edit LoRAs trained with isolated references (ai-toolkit's `kv_cache` option), such as the thedeoxen Krea-2 pose LoRA; the references then run through the model once per generation, which is faster. Leave it off for other edit LoRAs. See [Krea-2](/users-guide/models/local-models/krea-2/#reference-kv-cache).* **Seamless tiling** — makes the image tile along the X axis, the Y axis, or both.Two output filters live in **Settings** under **Project** rather than in the panel, because they apply to every image the project's Generate panel and Canvas produce: the **NSFW checker** blurs images it flags as explicit, and the **Invisible watermark** stamps every saved image. Both are off by default. Upscale results, workflow runs and images from external models are not filtered.@@ -121,10 +122,12 @@ What a reference does, and what options it has, depends on the model family:| **FLUX.1** | An IP-Adapter, or a **FLUX Redux** model, which transfers the reference's content. | IP-Adapter options as above, or **Image influence** (Lowest to Highest) for Redux. || **FLUX.1 Kontext** | Kontext edits or recombines the reference images according to your prompt. | None beyond the model. || **FLUX.2, Qwen Image Edit** | The model reads the references directly and uses them as your prompt instructs, for example *put the jacket from the first image on the person in the second*. | None. |-| **Krea-2** | One reference's look — palette, texture, rendering — is transferred into the image while the prompt keeps driving the content; see [Krea-2](/users-guide/models/local-models/krea-2/#style-reference). | **Style strength** (0–2; 0 turns the reference off). |+| **Krea-2** | **Style**: one reference's look — palette, texture, rendering — is transferred into the image while the prompt keeps driving the content. **Edit**: up to three references for an edit LoRA, such as a pose skeleton or a depth map, read in card order. See [Krea-2 style reference](/users-guide/models/local-models/krea-2/#style-reference) and [edit LoRAs](/users-guide/models/local-models/krea-2/#edit-loras-and-reference-images). | **Mode**: **Style** or **Edit**. **Style strength** (0–2; 0 turns the reference off) for Style. |Reference images require an extra model for SD 1.5, SDXL and FLUX.1 (an IP-Adapter or FLUX Redux model). These are available as starter models in the Model Manager, and an installed IP-Adapter is selected automatically.+A new Krea-2 reference starts as **Style** when it is the only enabled one; added beside other enabled references, or several at once, it starts as **Edit**. Adding never changes the mode of a card already in the list. Krea-2 runs either one Style reference or up to three Edit references, never both, and a Style reference at strength 0 is off and does not count; Invoke stays disabled and says why until the enabled references fit. Switching a card back to Style resets its strength to 1.+## Prompt toolsThe toolbar above the prompt box holds tools that help you write prompts. From left to right: **Templates**, **Dynamic**, **Add prompt trigger**, **Expand prompt**, **Image to prompt** and **Prompt history**.diff --git a/invokeai/backend/architectures/defs/krea_2.py b/invokeai/backend/architectures/defs/krea_2.pyindex cb6074ef52..ffc2d65dac 100644--- a/invokeai/backend/architectures/defs/krea_2.py+++ b/invokeai/backend/architectures/defs/krea_2.py@@ -34,9 +34,9 @@ register(dimension_grid=16,guidance_label="CFG",scheduler_set="flow",- # Training-free style reference: shared-KV attention splices one reference's keys and- # values into the target, so there is no adapter model and exactly one image.- max_reference_images=1,+ # Either one training-free style reference (shared-KV attention, no adapter model) or up to+ # three edit references for ai-toolkit edit LoRAs; `krea2_denoise` refuses more than three.+ max_reference_images=3,supports_regional_guidance=True,),VaeFacet(diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 7188c71fc4..f24e782861 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -880,6 +880,21 @@"How strongly the reference's look is transferred. 1.0 is the recommended setting; 2.0 is a heavier effect and 0 turns the reference off."]},+ "krea2ReferenceMode": {+ "heading": "Reference Mode",+ "paragraphs": [+ "Style transfers one reference's look (palette, texture, rendering) while the prompt keeps driving the content. It needs no LoRA.",+ "Edit is for Krea-2 edit LoRAs, such as the pose and depth LoRAs: the model reads up to three enabled references in card order and the prompt describes what to make of them. Edit references cannot be combined with a style reference or with regional guidance.",+ "Some edit LoRAs, such as pose LoRAs trained with isolated references, also need Reference K/V cache under Advanced. Check the LoRA's model card."+ ]+ },+ "krea2ReferenceKvCache": {+ "heading": "Reference K/V Cache",+ "paragraphs": [+ "For Krea-2 edit LoRAs trained with isolated references (ai-toolkit's kv_cache option), such as the thedeoxen Krea-2 pose LoRA. The references then run through the model once per generation instead of in every step, which is faster.",+ "Leave it off for normal edit LoRAs. The LoRA file does not say which kind it is; check its model card. It only applies while edit references are enabled."+ ]+ },"timestepShift": {"heading": "Timestep Shift","paragraphs": [@@ -1002,7 +1017,8 @@"qwen3VlEncoder": {"heading": "Qwen3-VL Encoder","paragraphs": [- "Krea-2 reads your prompt with the Qwen3-VL 4B text encoder. A single-file or GGUF checkpoint does not carry one, so it has to be selected here."+ "Krea-2 reads your prompt with the Qwen3-VL 4B text encoder. A single-file or GGUF checkpoint does not carry one, so it has to be selected here.",+ "Krea-2 edit references are read by the encoder's vision weights, which a GGUF encoder does not have."]},"referenceImage": {@@ -2573,6 +2589,8 @@"encoderQuantizationNone": "None (bf16)","encoderQuantizationInt8": "8-bit (int8)","encoderQuantizationNf4": "4-bit (nf4)",+ "krea2ReferenceKvCache": "Reference K/V cache",+ "krea2ReferenceKvCacheHelp": "For edit LoRAs trained with isolated references. Only applies with edit references.","styleStrength": "Style strength","timestepShift": "Shift","timestepShiftHelp": "Auto derives the schedule shift from the image size.",@@ -2592,6 +2610,7 @@"mode": "Mode","modeBoth": "Both","modeComposition": "Composition",+ "modeEdit": "Edit","modeStyle": "Style","model": "Model","modelDefault": "Model default",diff --git a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.jsonindex 005e93e496..ab96c58ce3 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json@@ -563,7 +563,7 @@"scheduler_set": "flow","scheduler_applies_to_graph": false,"control_kinds": [],- "max_reference_images": 1,+ "max_reference_images": 3,"reference_images_require_variant": null,"supports_regional_guidance": true,"regional_negative": false,@@ -615,7 +615,7 @@"scheduler_set": "flow","scheduler_applies_to_graph": false,"control_kinds": [],- "max_reference_images": 1,+ "max_reference_images": 3,"reference_images_require_variant": null,"supports_regional_guidance": true,"regional_negative": false,diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.jsonindex b27beed635..4fba7e30ec 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json@@ -240,7 +240,8 @@"standalone-components": ["qwen3VLEncoderModel","vae"- ]+ ],+ "diffusers-with-edit-references": []},"nodeTypes": ["collect",@@ -252,6 +253,7 @@"krea2_model_loader","krea2_style_reference","krea2_text_encoder",+ "qwen_image_i2l","qwen_image_l2i","string"]@@ -528,6 +530,7 @@},"collect": {"inputs": [+ "collection","item"],"literalInputs": {@@ -647,6 +650,9 @@"krea2_rebalance_weights": ["1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,5.0,1.1,4.0,1.0"],+ "krea2_reference_kv_cache": [+ true+ ],"krea2_seed_variance_enabled": [false],@@ -1299,14 +1305,17 @@},"krea2_denoise": {"inputs": [+ "negative_conditioning","positive_conditioning",+ "reference_latents","seed","style_reference","transformer"],"literalInputs": {"cfg_scale": [- 1+ 1,+ 4.5],"height": [1024@@ -1314,6 +1323,9 @@"is_intermediate": [true],+ "reference_kv_cache": [+ true+ ],"steps": [8],@@ -1382,6 +1394,7 @@"is_intermediate": [true],+ "reference_images": [],"use_cache": [true]@@ -1580,6 +1593,26 @@"latents"]},+ "qwen_image_i2l": {+ "inputs": [+ "vae"+ ],+ "literalInputs": {+ "image": [],+ "is_intermediate": [+ true+ ],+ "reference": [+ true+ ],+ "use_cache": [+ true+ ]+ },+ "outputs": [+ "latents"+ ]+ },"qwen_image_l2i": {"inputs": ["latents",diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex d4b75ad47a..51703b56d3 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -22,7 +22,7 @@ import {getComponentSectionPolicy,getAutoFlux2ComponentSourceModel,getDefaultGenerateSettings,- getDefaultReferenceImageConfig,+ getDefaultReferenceImageConfigs,getGenerateModelSelectionResult,getGenerationDimensions,getGenerationModelAvailabilityReasons,@@ -981,17 +981,16 @@ describe('component policies', () => {expect(result.clearedLabels).not.toContain('Reference Images');});- it('routes Krea-2 to its single style reference and re-targets other kinds to it', () => {+ it('starts a Krea-2 reference list with a style reference and re-targets other kinds to it', () => {// A Diffusers bundle needs no standalone components, which keeps the reasons to the reference check.const krea2 = createModel('krea-2', { format: 'diffusers' });expect(isReferenceImageSupported(krea2)).toBe(true);- expect(getMaxReferenceImages(krea2)).toBe(1);- expect(getDefaultReferenceImageConfig(krea2, [sdxlIpAdapter], referenceImage)).toEqual({- image: referenceImage,- styleStrength: 1,- type: 'krea2_reference_image',- });+ // One style reference, or up to three edit references.+ expect(getMaxReferenceImages(krea2)).toBe(3);+ expect(+ getDefaultReferenceImageConfigs(krea2, [sdxlIpAdapter], [{ image: referenceImage, isEnabled: true }])+ ).toEqual([{ image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' }]);const fromSdxl = getGenerateModelSelectionResult({currentValues: createSettings(createModel('sdxl'), {@@ -1040,7 +1039,10 @@ describe('component policies', () => {});it('switches off the enabled references a newly selected model has no room for, keeping every reference', () => {- const krea2 = createModel('krea-2', { format: 'diffusers' });+ const singleReferenceModel: GenerateModelConfig = {+ ...externalModel,+ capabilities: { ...externalModel.capabilities, max_reference_images: 1, supports_reference_images: true },+ };const ipAdapter = (id: string, isEnabled: boolean) => ({id,isEnabled,@@ -1062,7 +1064,7 @@ describe('component policies', () => {currentValues: createSettings(createModel('sdxl'), {referenceImages: [ipAdapter('bypassed', false), ipAdapter('used', true), ipAdapter('extra', true)],}),- model: krea2,+ model: singleReferenceModel,models: [sdxlIpAdapter],});@@ -1070,25 +1072,244 @@ describe('component policies', () => {expect(result.settings.referenceImages.map(({ config, id, isEnabled }) => ({ id, isEnabled, type: config.type }))).toEqual([- { id: 'bypassed', isEnabled: false, type: 'krea2_reference_image' },- { id: 'used', isEnabled: true, type: 'krea2_reference_image' },- { id: 'extra', isEnabled: false, type: 'krea2_reference_image' },+ { id: 'bypassed', isEnabled: false, type: 'external_reference_image' },+ { id: 'used', isEnabled: true, type: 'external_reference_image' },+ { id: 'extra', isEnabled: false, type: 'external_reference_image' },]);expect(result.clearedLabels).toContain('Reference Images');- expect(getGenerationValidationReasons(krea2, result.settings)).toEqual([]);+ expect(+ getGenerationValidationReasons(singleReferenceModel, result.settings).filter((reason) =>+ reason.includes('reference')+ )+ ).toEqual([]);});it('names a limit of one reference in the singular', () => {- const krea2 = createModel('krea-2', { format: 'diffusers' });- const style = (id: string) => ({+ const singleReferenceModel: GenerateModelConfig = {+ ...externalModel,+ capabilities: { ...externalModel.capabilities, max_reference_images: 1, supports_reference_images: true },+ };+ const external = (id: string) => ({id,isEnabled: true,- config: { image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' as const },+ config: { image: referenceImage, type: 'external_reference_image' as const },});expect(- getGenerationValidationReasons(krea2, createSettings(krea2, { referenceImages: [style('a'), style('b')] }))- ).toContain(`Generate supports at most 1 reference image for ${krea2.name}.`);+ getGenerationValidationReasons(+ singleReferenceModel,+ createSettings(singleReferenceModel, { referenceImages: [external('a'), external('b')] })+ )+ ).toContain(`Generate supports at most 1 reference image for ${singleReferenceModel.name}.`);+ });++ describe('Krea-2 style and edit references', () => {+ const krea2 = createModel('krea-2', { format: 'diffusers' });+ const style = (id: string, isEnabled = true) => ({+ id,+ isEnabled,+ config: { image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' as const },+ });+ const edit = (id: string, isEnabled = true) => ({+ id,+ isEnabled,+ config: { image: referenceImage, type: 'krea2_edit_reference_image' as const },+ });+ const reasonsFor = (model: MainModelConfig, overrides: Partial<GenerateSettings>) =>+ getGenerationValidationReasons(model, createSettings(model, overrides));+ const ggufEncoder: ComponentModelConfig = {+ base: 'any',+ format: 'gguf_quantized',+ key: 'qwen3-vl-gguf',+ name: 'Qwen3-VL 4B Q4_K_M',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_4b',+ };+ const ggufReason = `Krea-2 edit references need a Qwen3-VL encoder with vision weights, which the GGUF encoder "${ggufEncoder.name}" does not have. Select a safetensors or Diffusers encoder.`;++ it('types a new Krea-2 reference as style only when it is the one running reference', () => {+ const styleConfig = { image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' };+ const editConfig = { image: referenceImage, type: 'krea2_edit_reference_image' };+ const added = (count: number, referenceImages: GenerateSettings['referenceImages'] = [], isEnabled = true) =>+ getDefaultReferenceImageConfigs(+ krea2,+ [],+ Array.from({ length: count }, () => ({ image: referenceImage, isEnabled })),+ referenceImages+ );++ expect(added(1)).toEqual([styleConfig]);+ // Several images at once are an edit set, never a pile of style references.+ expect(added(3)).toEqual([editConfig, editConfig, editConfig]);+ expect(added(1, [edit('a')])).toEqual([editConfig]);+ // Beside a style reference too; the list keeps its style card, so the mix is reported, not hidden.+ expect(added(1, [style('s')])).toEqual([editConfig]);+ expect(+ reasonsFor(krea2, { referenceImages: [style('s'), { ...edit('new'), config: added(1, [style('s')])[0]! }] })+ ).toEqual([+ 'Krea-2 cannot combine a style reference with edit references. Switch the style reference to Edit, or turn off one kind.',+ ]);+ // Switched-off and zero-strength references do not run, so they leave the newcomer alone.+ expect(+ added(1, [edit('a', false), { ...style('s'), config: { ...style('s').config, styleStrength: 0 } }])+ ).toEqual([styleConfig]);+ // A switched-off addition is typed for the moment it is switched on beside the others.+ expect(added(1, [], false)).toEqual([styleConfig]);+ expect(added(1, [edit('a')], false)).toEqual([editConfig]);+ });++ it('treats a zero-strength style reference as off in every check', () => {+ const bypassed = { ...style('bypassed'), config: { ...style('bypassed').config, styleStrength: 0 } };++ expect(reasonsFor(krea2, { referenceImages: [bypassed, style('a')] })).toEqual([]);+ expect(reasonsFor(krea2, { referenceImages: [bypassed, edit('a'), edit('b'), edit('c')] })).toEqual([]);++ // It does not take precedence over the edit set when the model changes.+ const otherKrea2 = createModel('krea-2', { format: 'diffusers', key: 'krea2-other' });+ const switched = getGenerateModelSelectionResult({+ currentValues: createSettings(krea2, { referenceImages: [bypassed, edit('a'), edit('b')] }),+ model: otherKrea2,+ models: [],+ }).settings.referenceImages;++ expect(switched.map(({ id, isEnabled }) => [id, isEnabled])).toEqual([+ ['bypassed', true],+ ['a', true],+ ['b', true],+ ]);+ });++ it('accepts up to three edit references and counts only enabled ones', () => {+ expect(reasonsFor(krea2, { referenceImages: [edit('a'), edit('b'), edit('c')] })).toEqual([]);+ expect(reasonsFor(krea2, { referenceImages: [edit('a'), edit('b'), edit('c'), edit('d', false)] })).toEqual([]);+ expect(reasonsFor(krea2, { referenceImages: [edit('a'), edit('b'), edit('c'), edit('d')] })).toContain(+ `Generate supports at most 3 reference images for ${krea2.name}.`+ );+ });++ it('runs one enabled style reference at a time and never mixes style with edit references', () => {+ const styleReason =+ 'Krea-2 uses one style reference at a time. Turn off all but one, or switch all of them to Edit.';+ const mixReason =+ 'Krea-2 cannot combine a style reference with edit references. Switch the style reference to Edit, or turn off one kind.';++ expect(reasonsFor(krea2, { referenceImages: [style('a'), style('b')] })).toEqual([styleReason]);+ expect(reasonsFor(krea2, { referenceImages: [style('a'), edit('b')] })).toEqual([mixReason]);+ // A switched-off reference of the other kind stays out of the check.+ expect(reasonsFor(krea2, { referenceImages: [style('a', false), style('b'), edit('c', false)] })).toEqual([]);+ expect(reasonsFor(krea2, { referenceImages: [style('a', false), edit('b'), edit('c')] })).toEqual([]);+ });++ it('blocks edit references on a GGUF encoder, which has no vision tower, and only then', () => {+ const checkpoint = createModel('krea-2', { format: 'checkpoint', key: 'krea2-checkpoint' });+ const vae: VaeModelConfig = { base: 'qwen-image', key: 'krea2-vae', name: 'Qwen VAE', type: 'vae' };+ const safetensorsEncoder: ComponentModelConfig = { ...ggufEncoder, format: 'checkpoint', key: 'qwen3-vl-st' };++ expect(reasonsFor(checkpoint, { qwen3VLEncoderModel: ggufEncoder, referenceImages: [edit('a')], vae })).toEqual([+ ggufReason,+ ]);+ // A Diffusers main reads with the GGUF override too, when one is selected.+ expect(reasonsFor(krea2, { qwen3VLEncoderModel: ggufEncoder, referenceImages: [edit('a')] })).toEqual([+ ggufReason,+ ]);+ expect(reasonsFor(krea2, { referenceImages: [edit('a')] })).toEqual([]);+ expect(+ reasonsFor(checkpoint, { qwen3VLEncoderModel: safetensorsEncoder, referenceImages: [edit('a')], vae })+ ).toEqual([]);+ // Style transfer and switched-off edit references never reach the vision tower.+ expect(+ reasonsFor(checkpoint, {+ qwen3VLEncoderModel: ggufEncoder,+ referenceImages: [style('a'), edit('b', false)],+ vae,+ })+ ).toEqual([]);+ });++ it('re-targets references into Krea-2 as one set and switches off the ones that cannot run together', () => {+ const flux2 = createModel('flux2', { format: 'diffusers' });+ const flux2Reference = (id: string, isEnabled = true) => ({+ id,+ isEnabled,+ config: { image: referenceImage, type: 'flux2_reference_image' as const },+ });+ const select = (+ model: MainModelConfig,+ current: MainModelConfig,+ referenceImages: GenerateSettings['referenceImages']+ ) =>+ getGenerateModelSelectionResult({+ currentValues: createSettings(current, { referenceImages }),+ model,+ models: [],+ }).settings.referenceImages;++ // An edit set survives a trip through another family and back.+ const viaFlux2 = select(flux2, krea2, [edit('a'), edit('b'), edit('c')]);+ const backToKrea2 = select(krea2, flux2, viaFlux2);++ expect(backToKrea2.map(({ config, id, isEnabled }) => ({ id, isEnabled, type: config.type }))).toEqual([+ { id: 'a', isEnabled: true, type: 'krea2_edit_reference_image' },+ { id: 'b', isEnabled: true, type: 'krea2_edit_reference_image' },+ { id: 'c', isEnabled: true, type: 'krea2_edit_reference_image' },+ ]);+ expect(getGenerationValidationReasons(krea2, createSettings(krea2, { referenceImages: backToKrea2 }))).toEqual(+ []+ );++ // The one running reference becomes the style reference, and a switched-off one would join it as an edit+ // reference. Past the limit of three, the extra edit reference stops.+ expect(select(krea2, flux2, [flux2Reference('a')]).map(({ config }) => config.type)).toEqual([+ 'krea2_reference_image',+ ]);+ expect(+ select(krea2, flux2, [flux2Reference('a'), flux2Reference('b', false)]).map(({ config }) => config.type)+ ).toEqual(['krea2_reference_image', 'krea2_edit_reference_image']);+ expect(+ select(+ krea2,+ flux2,+ ['a', 'b', 'c', 'd'].map((id) => flux2Reference(id))+ ).map(({ id, isEnabled }) => [id, isEnabled])+ ).toEqual([+ ['a', true],+ ['b', true],+ ['c', true],+ ['d', false],+ ]);++ // An edit set keeps running on another Krea-2 model; a mixed list keeps its first kind.+ const editSet = [edit('a'), edit('b'), edit('c')];+ const otherKrea2 = createModel('krea-2', { format: 'diffusers', key: 'krea2-other' });++ expect(+ getGenerateModelSelectionResult({+ currentValues: createSettings(krea2, { referenceImages: editSet }),+ model: otherKrea2,+ models: [],+ }).settings.referenceImages+ ).toBe(editSet);+ expect(+ getGenerateModelSelectionResult({+ currentValues: createSettings(krea2, { referenceImages: [edit('a'), style('b'), edit('c')] }),+ model: otherKrea2,+ models: [],+ }).settings.referenceImages.map(({ id, isEnabled }) => [id, isEnabled])+ ).toEqual([+ ['a', true],+ ['b', false],+ ['c', true],+ ]);++ // Leaving Krea-2 re-targets both kinds, keeping their images and enabled state.+ const toFlux2 = getGenerateModelSelectionResult({+ currentValues: createSettings(krea2, { referenceImages: [edit('a'), style('b', false)] }),+ model: flux2,+ models: [],+ });++ expect(toFlux2.settings.referenceImages).toEqual([flux2Reference('a'), flux2Reference('b', false)]);+ });});it('reports reference image support per model', () => {diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex c70f7ca260..93ecef8c4e 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -377,6 +377,7 @@ export const getGenerationUiPolicy = (model: GenerateModelConfig | undefined) =>refinerVisible: isRefinerSupported(model),// Both Qwen-Image text encoders take the quantization choice; no other family's encoder does.encoderQuantizationVisible: model?.type === 'main' && model.base === 'qwen-image',+ krea2ReferenceKvCacheVisible: model?.type === 'main' && model.base === 'krea-2',};};@@ -496,6 +497,7 @@ export const getDefaultGenerateSettings = (model?: GenerateModelConfig): Generatkrea2SeedVarianceEnabled: false,krea2SeedVarianceStrength: DEFAULT_KREA2_SEED_VARIANCE_STRENGTH,krea2SeedVarianceRandomizePercent: DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT,+ krea2ReferenceKvCache: false,fluxDypePreset: 'off',fluxDypeScale: DEFAULT_FLUX_DYPE_SCALE,fluxDypeExponent: DEFAULT_FLUX_DYPE_EXPONENT,@@ -1329,10 +1331,22 @@ export const getMaxReferenceImages = (model: GenerateModelConfig | undefined): nexport const createReferenceImageId = (): string =>`reference_image_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;-export const getDefaultReferenceImageConfig = (+/** Edit references switch Krea-2 into edit mode, which excludes style references and regional prompts. */+export const hasEnabledKrea2EditReferences = (referenceImages: readonly GenerateReferenceImage[]): boolean =>+ referenceImages.some(+ (referenceImage) => referenceImage.isEnabled && referenceImage.config.type === 'krea2_edit_reference_image'+ );++/** A Krea-2 style reference at zero strength is bypassed, so it neither runs nor counts against the others. */+const isReferenceImageActive = (referenceImage: GenerateReferenceImage): boolean =>+ referenceImage.isEnabled &&+ !(referenceImage.config.type === 'krea2_reference_image' && referenceImage.config.styleStrength <= 0);++/** The family's one reference kind; Krea-2's choice between style and edit is `getDefaultReferenceImageConfigs`'s. */+const getFamilyDefaultReferenceImageConfig = (model: GenerateModelConfig | undefined,models: readonly ReferenceModelCandidate[],- image: GenerateReferenceImageAsset | null = null+ image: GenerateReferenceImageAsset | null): GenerateReferenceImageConfig => {const modelBase: string | undefined = model?.base;@@ -1348,10 +1362,6 @@ export const getDefaultReferenceImageConfig = (return { image, type: 'qwen_image_reference_image' };}- if (modelBase === 'krea-2') {- return { image, styleStrength: DEFAULT_KREA2_STYLE_STRENGTH, type: 'krea2_reference_image' };- }-if (isFluxKontextModel(model)) {return { image, model, type: 'flux_kontext_reference_image' };}@@ -1381,6 +1391,7 @@ const getReferenceImageConfigSupported = (return model.type !== 'external_image_generator' && model.base === 'flux2';case 'qwen_image_reference_image':return model.type !== 'external_image_generator' && model.base === 'qwen-image' && model.variant === 'edit';+ case 'krea2_edit_reference_image':case 'krea2_reference_image':return model.type !== 'external_image_generator' && model.base === 'krea-2';case 'flux_kontext_reference_image':@@ -1413,14 +1424,70 @@ export const isReferenceImageCompatibleWithModel = (return true;};+/** A new or re-targeted reference, typed for the model; existing references keep theirs. */+export interface ReferenceImageAddition {+ image: GenerateReferenceImageAsset | null;+ isEnabled: boolean;+}+/**- * Drop unsupported references; retarget incompatible ones while preserving image/enabled state. No changes return- * the same array.+ * Configs for `additions` joining `referenceImages`, which may also hold references a re-target will turn into the+ * model's kind. A Krea-2 addition is the style reference only when it would be the sole running Krea-2 reference,+ * counting the other additions and itself as switched on; arriving with or beside others, it is an edit reference.+ */+export const getDefaultReferenceImageConfigs = (+ model: GenerateModelConfig | undefined,+ models: readonly ReferenceModelCandidate[],+ additions: readonly ReferenceImageAddition[],+ referenceImages: readonly GenerateReferenceImage[] = []+): GenerateReferenceImageConfig[] => {+ if (model?.type !== 'main' || model.base !== 'krea-2') {+ return additions.map(({ image }) => getFamilyDefaultReferenceImageConfig(model, models, image));+ }++ const runningElsewhere = referenceImages.filter((referenceImage) =>+ isReferenceImageCompatibleWithModel(model, referenceImage)+ ? isReferenceImageActive(referenceImage)+ : referenceImage.isEnabled+ ).length;+ const enabledAdditions = additions.filter((addition) => addition.isEnabled).length;++ return additions.map(({ image, isEnabled }) =>+ runningElsewhere + enabledAdditions + (isEnabled ? 0 : 1) === 1+ ? { image, styleStrength: DEFAULT_KREA2_STYLE_STRENGTH, type: 'krea2_reference_image' }+ : { image, type: 'krea2_edit_reference_image' }+ );+};++/** Within the model's limit; Krea-2 runs either one style reference or a set of edit references, never both. */+const canRunWithEnabledReferenceImages = (+ model: GenerateModelConfig,+ enabled: readonly GenerateReferenceImage[],+ referenceImage: GenerateReferenceImage+): boolean => {+ if (enabled.length >= getMaxReferenceImages(model)) {+ return false;+ }++ if (model.base !== 'krea-2') {+ return true;+ }++ return referenceImage.config.type === 'krea2_reference_image'+ ? enabled.length === 0+ : enabled.every((kept) => kept.config.type !== 'krea2_reference_image');+};++/**+ * Drop unsupported references; retarget incompatible ones while preserving image/enabled state. The re-targeted ones+ * are typed together, beside the compatible ones and `joining`, the list they are appended to. No changes return the+ * same array.*/export const getCompatibleReferenceImages = (referenceImages: GenerateReferenceImage[],model: GenerateModelConfig,- models: readonly ReferenceModelCandidate[]+ models: readonly ReferenceModelCandidate[],+ joining: readonly GenerateReferenceImage[] = []): GenerateReferenceImage[] => {if (referenceImages.length === 0) {return referenceImages;@@ -1430,17 +1497,26 @@ export const getCompatibleReferenceImages = (return [];}- let didChange = false;- const next = referenceImages.map((referenceImage) => {- if (isReferenceImageCompatibleWithModel(model, referenceImage)) {- return referenceImage;- }+ const isCompatible = referenceImages.map((referenceImage) =>+ isReferenceImageCompatibleWithModel(model, referenceImage)+ );+ const retargeted = referenceImages.filter((_, index) => !isCompatible[index]);- didChange = true;- return { ...referenceImage, config: getDefaultReferenceImageConfig(model, models, referenceImage.config.image) };- });+ if (retargeted.length === 0) {+ return referenceImages;+ }- return didChange ? next : referenceImages;+ const configs = getDefaultReferenceImageConfigs(+ model,+ models,+ retargeted.map(({ config, isEnabled }) => ({ image: config.image, isEnabled })),+ [...joining, ...referenceImages.filter((_, index) => isCompatible[index])]+ );+ let retargetIndex = 0;++ return referenceImages.map((referenceImage, index) =>+ isCompatible[index] ? referenceImage : { ...referenceImage, config: configs[retargetIndex++]! }+ );};const getSettingsWithCompatibleModelSelections = (@@ -1468,22 +1544,25 @@ const getSettingsWithCompatibleModelSelections = (addClearedLabel(clearedLabels, 'LoRAs');}- // Enabled references beyond the new family's limit are switched off rather than deleted: Invoke is not left+ // Enabled references the new family cannot run together are switched off rather than deleted: Invoke is not left// blocked, the first enabled ones keep running, and switching back can turn the rest on again.const retargetedReferenceImages = getCompatibleReferenceImages(settings.referenceImages, model, models);- const maxReferenceImages = getMaxReferenceImages(model);- let enabledKept = 0;- const compatibleReferenceImages =- retargetedReferenceImages.filter((referenceImage) => referenceImage.isEnabled).length > maxReferenceImages- ? retargetedReferenceImages.map((referenceImage) => {- if (!referenceImage.isEnabled) {- return referenceImage;- }-- enabledKept += 1;- return enabledKept > maxReferenceImages ? { ...referenceImage, isEnabled: false } : referenceImage;- })- : retargetedReferenceImages;+ const enabledKept: GenerateReferenceImage[] = [];+ let didSwitchOff = false;+ const keptOrSwitchedOff = retargetedReferenceImages.map((referenceImage) => {+ if (!isReferenceImageActive(referenceImage)) {+ return referenceImage;+ }++ if (canRunWithEnabledReferenceImages(model, enabledKept, referenceImage)) {+ enabledKept.push(referenceImage);+ return referenceImage;+ }++ didSwitchOff = true;+ return { ...referenceImage, isEnabled: false };+ });+ const compatibleReferenceImages = didSwitchOff ? keptOrSwitchedOff : retargetedReferenceImages;if (compatibleReferenceImages !== settings.referenceImages) {nextSettings.referenceImages = compatibleReferenceImages;@@ -1684,7 +1763,10 @@ const getReferenceImageValidationReasons = (model: GenerateModelConfig, settings// zero.const maxReferenceImages = getMaxReferenceImages(model);- if (isReferenceImageSupported(model) && enabled.length > maxReferenceImages) {+ if (+ isReferenceImageSupported(model) &&+ settings.referenceImages.filter(isReferenceImageActive).length > maxReferenceImages+ ) {reasons.push(`Generate supports at most ${maxReferenceImages} reference image${maxReferenceImages === 1 ? '' : 's'} for ${model.name}.`);@@ -1742,10 +1824,46 @@ export const getGuidanceBoundReason = (return null;};+/**+ * Combinations the backend refuses only after queueing. The encoder reads edit references with its vision tower, which+ * a GGUF Qwen3-VL encoder does not carry; a Diffusers main without an encoder override uses its bundled one.+ */+const getKrea2ReferenceValidationReasons = (settings: GenerateSettings): string[] => {+ const styleCount = settings.referenceImages.filter(+ (referenceImage) => isReferenceImageActive(referenceImage) && referenceImage.config.type === 'krea2_reference_image'+ ).length;+ const hasEditReferences = hasEnabledKrea2EditReferences(settings.referenceImages);+ const reasons: string[] = [];++ if (styleCount > 1) {+ reasons.push('Krea-2 uses one style reference at a time. Turn off all but one, or switch all of them to Edit.');+ }++ if (styleCount > 0 && hasEditReferences) {+ reasons.push(+ 'Krea-2 cannot combine a style reference with edit references. Switch the style reference to Edit, or turn off one kind.'+ );+ }++ const encoder = settings.qwen3VLEncoderModel;++ if (hasEditReferences && encoder && isKrea2Qwen3VlEncoder(encoder) && encoder.format === 'gguf_quantized') {+ reasons.push(+ `Krea-2 edit references need a Qwen3-VL encoder with vision weights, which the GGUF encoder "${encoder.name}" does not have. Select a safetensors or Diffusers encoder.`+ );+ }++ return reasons;+};+/** Scalar/LoRA family rules are separate from component-slot validation. */const getModelFamilyValidationReasons = (model: MainModelConfig, settings: GenerateSettings): string[] => {const reasons: string[] = [];+ if (model.base === 'krea-2') {+ reasons.push(...getKrea2ReferenceValidationReasons(settings));+ }+// Parse raw rebalance strings before forwarding them to the backend.if (model.base === 'krea-2' &&diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex 661cc95bd7..e7fd11897d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@ -1743,3 +1743,64 @@ describe('compileCanvasGraph — Krea-2 style reference', () => {);});});++describe('compileCanvasGraph — Krea-2 edit references', () => {+ const editReference = (imageName: string, isEnabled = true) => ({+ config: {+ image: { original: { image: { height: 768, image_name: imageName, width: 512 } } },+ type: 'krea2_edit_reference_image' as const,+ },+ id: imageName,+ isEnabled,+ });+ const region: RegionalGuidanceInput = {+ autoNegative: false,+ id: 'r1',+ maskImageName: 'r1-mask.png',+ negativePrompt: null,+ positivePrompt: 'a cat',+ referenceImages: [],+ };++ it('inpaints with the edit references alongside the encoded canvas image', () => {+ const { backendGraph } = compile(krea2Model, 'inpaint', {+ settings: { referenceImages: [editReference('pose.png'), editReference('depth.png')] },+ });+ const referenceEncoders = Object.values(backendGraph.nodes).filter(+ (node) => node.type === 'qwen_image_i2l' && node.reference === true+ );++ // The canvas image is still what gets denoised under the mask; the references only join as clean tokens.+ expect(getEdge(backendGraph, 'denoise_latents', 'latents')?.source.node_id).toBe('canvas_i2l');+ expect(backendGraph.nodes.canvas_i2l).not.toHaveProperty('reference');+ expect(getEdge(backendGraph, 'denoise_latents', 'denoise_mask')).toBeDefined();+ expect(referenceEncoders.map((node) => node.image)).toEqual([+ { image_name: 'pose.png' },+ { image_name: 'depth.png' },+ ]);+ expect(getEdge(backendGraph, 'denoise_latents', 'reference_latents')).toBeDefined();+ expect(backendGraph.nodes.pos_cond?.reference_images).toEqual([+ { image_name: 'pose.png' },+ { image_name: 'depth.png' },+ ]);+ });++ it('refuses edit references together with regional guidance, which the denoise cannot place them in', () => {+ expect(() =>+ compile(krea2Model, 'txt2img', {+ regionalGuidance: [region],+ settings: { referenceImages: [editReference('pose.png')] },+ })+ ).toThrow(+ 'Krea-2 edit references cannot be combined with regional guidance. Turn off the edit references or disable the regional guidance layers.'+ );++ const { backendGraph } = compile(krea2Model, 'txt2img', {+ regionalGuidance: [region],+ settings: { referenceImages: [editReference('pose.png', false)] },+ });++ expect(backendGraph.nodes.rg_pos_cond_r1).toBeDefined();+ expect(getEdge(backendGraph, 'denoise_latents', 'reference_latents')).toBeUndefined();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex 029ccde6d4..e3e278315d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -7,7 +7,10 @@ import type { SupportedGenerateBase } from '@features/generation/core/baseGeneraimport type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';import type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { getGenerationValidationReasons } from '@features/generation/core/baseGenerationPolicies';+import {+ getGenerationValidationReasons,+ hasEnabledKrea2EditReferences,+} from '@features/generation/core/baseGenerationPolicies';import { findVaeSource, GRAPH_BUILDERS } from '@features/generation/core/graph';import {addEdge,@@ -138,6 +141,17 @@ const getCanvasValidationReasons = (input: CompileCanvasGraphInput, processingSi}}+ // A regional mask covers the prompt and target tokens only; edit references add image tokens it cannot place.+ if (+ model.base === 'krea-2' &&+ (input.regionalGuidance?.length ?? 0) > 0 &&+ hasEnabledKrea2EditReferences(settings.referenceImages)+ ) {+ reasons.push(+ 'Krea-2 edit references cannot be combined with regional guidance. Turn off the edit references or disable the regional guidance layers.'+ );+ }+if (!Number.isFinite(bbox.width) || !Number.isFinite(bbox.height) || bbox.width <= 0 || bbox.height <= 0) {reasons.push('Canvas bounding box must have a positive area.');} else if (!Number.isInteger(bbox.width) || !Number.isInteger(bbox.height)) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex a70cebf808..516a10b648 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -1706,6 +1706,117 @@ describe('model-family tuning', () => {expect(getEdge(graph, 'denoise_latents', 'style_reference')).toBeUndefined();expect(getNodeByType(graph, 'core_metadata')).not.toHaveProperty('krea2_style_strength');});++ const editReference = (imageName: string, isEnabled = true) => ({+ config: {+ image: { original: { image: { height: 640, image_name: imageName, width: 480 } } },+ type: 'krea2_edit_reference_image' as const,+ },+ id: imageName,+ isEnabled,+ });++ /** The encode nodes behind `denoise_latents.reference_latents`, read back through the chained collects. */+ const getReferenceLatentEncoders = (graph: ReturnType<typeof compile>) => {+ const encoders: Array<ReturnType<typeof compile>['nodes'][string] | undefined> = [];+ let collectId = getEdge(graph, 'denoise_latents', 'reference_latents')?.source.node_id;++ while (collectId) {+ const encoderId = getEdge(graph, collectId, 'item')?.source.node_id;++ encoders.unshift(encoderId ? graph.nodes[encoderId] : undefined);+ collectId = getEdge(graph, collectId, 'collection')?.source.node_id;+ }++ return encoders;+ };++ it('reads the enabled Krea-2 edit references, in list order, into the prompt and the denoise', () => {+ const cropped = {+ config: {+ image: {+ crop: {+ box: { height: 256, width: 256, x: 0, y: 0 },+ image: { height: 256, image_name: 'pose-crop.png', width: 256 },+ ratio: 1,+ },+ original: { image: { height: 1024, image_name: 'pose.png', width: 1024 } },+ },+ type: 'krea2_edit_reference_image' as const,+ },+ id: 'pose',+ isEnabled: true,+ };+ const graph = compile(krea2Model, {+ referenceImages: [+ editReference('depth.png'),+ editReference('off.png', false),+ cropped,+ editReference('room.png'),+ ],+ });+ const expectedImages = [{ image_name: 'depth.png' }, { image_name: 'pose-crop.png' }, { image_name: 'room.png' }];+ const encoders = getReferenceLatentEncoders(graph);++ expect(graph.nodes.pos_cond?.reference_images).toEqual(expectedImages);+ // CFG off: the negative prompt is not built, so nothing else needs the references.+ expect(graph.nodes.neg_cond).toBeUndefined();+ expect(encoders.map((encoder) => encoder?.image)).toEqual(expectedImages);+ for (const encoder of encoders) {+ // `reference` sizes the image itself; the node refuses a width or height alongside it.+ expect(encoder).toMatchObject({ reference: true, type: 'qwen_image_i2l' });+ expect(encoder).not.toHaveProperty('width');+ expect(encoder).not.toHaveProperty('height');+ expect(getEdge(graph, encoder!.id, 'vae')?.source).toEqual({ field: 'vae', node_id: 'model_loader' });+ }+ expect(graph.nodes.denoise_latents?.reference_kv_cache).toBe(false);+ expect(getNodeByType(graph, 'krea2_style_reference')).toBeUndefined();++ const metadata = getNodeByType(graph, 'core_metadata')!;++ expect(metadata.krea2_reference_kv_cache).toBe(false);+ expect((metadata.ref_images as { id: string }[]).map((entry) => entry.id)).toEqual([+ 'depth.png',+ 'pose',+ 'room.png',+ ]);+ });++ it('gives the negative prompt the same edit references under CFG and sends the K/V cache switch', () => {+ const graph = compile(krea2Model, {+ cfgScale: 4.5,+ krea2RebalanceEnabled: true,+ krea2ReferenceKvCache: true,+ krea2SeedVarianceEnabled: true,+ krea2SeedVarianceStrength: 0.2,+ referenceImages: [editReference('a.png'), editReference('b.png')],+ });++ expect(graph.nodes.neg_cond?.reference_images).toEqual([{ image_name: 'a.png' }, { image_name: 'b.png' }]);+ expect(graph.nodes.pos_cond?.reference_images).toEqual(graph.nodes.neg_cond?.reference_images);+ // The enhancers still sit between the encoder that read the references and the denoise.+ expect(getEdge(graph, 'krea2_rebalance', 'conditioning')?.source.node_id).toBe('pos_cond');+ expect(getEdge(graph, 'pos_cond_collect', 'item')?.source.node_id).toBe('krea2_seed_variance');+ expect(getReferenceLatentEncoders(graph)).toHaveLength(2);+ expect(graph.nodes.denoise_latents?.reference_kv_cache).toBe(true);+ expect(getNodeByType(graph, 'core_metadata')?.krea2_reference_kv_cache).toBe(true);+ });++ it('keeps the style path and leaves the edit inputs unset without enabled edit references', () => {+ const graph = compile(krea2Model, {+ cfgScale: 4.5,+ krea2ReferenceKvCache: true,+ referenceImages: [styleReference(1), editReference('off.png', false)],+ });++ expect(getNodeByType(graph, 'krea2_style_reference')).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'reference_latents')).toBeUndefined();+ expect(graph.nodes.denoise_latents).not.toHaveProperty('reference_kv_cache');+ expect(graph.nodes.pos_cond).not.toHaveProperty('reference_images');+ expect(graph.nodes.neg_cond).not.toHaveProperty('reference_images');+ expect(getNodeByType(graph, 'qwen_image_i2l')).toBeUndefined();+ expect(getNodeByType(graph, 'core_metadata')).not.toHaveProperty('krea2_reference_kv_cache');+ });});describe('output filters', () => {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex 8b6ec98744..ec0d56a0f5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -1286,6 +1286,52 @@ const buildAnimaGraph = (return graph;};+/**+ * Edit references reach the model twice, in the same order: each prompt the denoise checks reads them through the+ * encoder's vision tower, and their latents join the denoise as clean image tokens. Chained collects keep that order,+ * which a single collect would take from execution order.+ */+const addKrea2EditReferences = (+ graph: BackendGraphContract,+ {+ denoise,+ prompts,+ referenceImages,+ referenceKvCache,+ vaeSource,+ }: {+ denoise: BackendInvocationContract;+ prompts: readonly BackendInvocationContract[];+ referenceImages: readonly { image_name: string }[];+ referenceKvCache: boolean;+ vaeSource: BackendInvocationContract;+ }+) => {+ for (const prompt of prompts) {+ prompt.reference_images = referenceImages.map((image) => ({ ...image }));+ }++ let previousCollect: BackendInvocationContract | null = null;++ for (const image of referenceImages) {+ // `reference` sizes the image as ai-toolkit trains edit LoRAs, so width and height stay unset.+ const encode = addNode(graph, { id: createId('krea2_ref_i2l'), image, reference: true, type: 'qwen_image_i2l' });+ const collect = addNode(graph, { id: createId('krea2_ref_latents_collect'), type: 'collect' });++ addEdge(graph, vaeSource, 'vae', encode, 'vae');+ addEdge(graph, encode, 'latents', collect, 'item');+ if (previousCollect) {+ addEdge(graph, previousCollect, 'collection', collect, 'collection');+ }+ previousCollect = collect;+ }++ if (previousCollect) {+ addEdge(graph, previousCollect, 'collection', denoise, 'reference_latents');+ }+ denoise.reference_kv_cache = referenceKvCache;+};+const buildKrea2Graph = (settings: GenerateSettings,model: MainModelConfig,@@ -1357,11 +1403,27 @@ const buildKrea2Graph = (addEdge(graph, seed, 'value', denoise, 'seed');addEdge(graph, denoise, 'latents', output, 'latents');- // Shared-KV reference attention takes exactly one reference; zero strength is a full bypass, so it is not run.- const styleReference = getEnabledReferenceImages(settings, 'krea2_reference_image').find(- (referenceImage) => referenceImage.config.styleStrength > 0+ // Validation keeps edit and style references apart; the denoise refuses the two together.+ const editReferenceImages = getEnabledReferenceImages(settings, 'krea2_edit_reference_image').flatMap(({ config }) =>+ config.image ? [toImageField(config.image)] : []);- if (styleReference?.config.image) {+ // Shared-KV reference attention takes exactly one reference; zero strength is a full bypass, so it is not run.+ const styleReference =+ editReferenceImages.length > 0+ ? undefined+ : getEnabledReferenceImages(settings, 'krea2_reference_image').find(+ (referenceImage) => referenceImage.config.styleStrength > 0+ );++ if (editReferenceImages.length > 0) {+ addKrea2EditReferences(graph, {+ denoise,+ prompts: negCond ? [posCond, negCond] : [posCond],+ referenceImages: editReferenceImages,+ referenceKvCache: settings.krea2ReferenceKvCache,+ vaeSource: modelLoader,+ });+ } else if (styleReference?.config.image) {const styleReferenceNode = addNode(graph, {// The reference's image tokens are appended to the target's, so both must be the same size.height: settings.height,@@ -1383,6 +1445,7 @@ const buildKrea2Graph = (krea2_seed_variance_randomize_percent: settings.krea2SeedVarianceRandomizePercent,krea2_seed_variance_strength: settings.krea2SeedVarianceStrength,...(styleReference ? { krea2_style_strength: styleReference.config.styleStrength } : {}),+ ...(editReferenceImages.length > 0 ? { krea2_reference_kv_cache: settings.krea2ReferenceKvCache } : {}),qwen3_vl_encoder: qwen3VlEncoderModel ?? undefined,vae: vaeModel ?? undefined,});diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.tsindex ee15380530..bd1bc725aa 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts@@ -44,6 +44,7 @@ const compileForShape = (};const SDXL_REFINER_SHAPE: ModelShape = { label: 'diffusers-with-refiner', overrides: { format: 'diffusers' } };+const KREA2_EDIT_SHAPE: ModelShape = { label: 'diffusers-with-edit-references', overrides: { format: 'diffusers' } };const SDXL_REFINER_MODEL: MainModelConfig = {base: 'sdxl-refiner',key: 'sdxl-refiner',@@ -197,12 +198,41 @@ describe('generate graph coverage', () => {shape: SDXL_REFINER_SHAPE,};};+ // Edit references replace the style reference the tuned Krea-2 recipe carries, so they need their own case.+ const krea2EditCase = () => {+ const { filled, model, settings } = satisfiedSettingsFor('krea-2', KREA2_EDIT_SHAPE);+ const image = { original: { image: { height: 1024, image_name: 'edit-reference.png', width: 1024 } } };+ const withEditReferences = {+ ...settings,+ // CFG builds the negative prompt, which reads the references too.+ cfgScale: 4.5,+ krea2ReferenceKvCache: true,+ referenceImages: [+ { config: { image, type: 'krea2_edit_reference_image' as const }, id: 'edit-1', isEnabled: true },+ { config: { image, type: 'krea2_edit_reference_image' as const }, id: 'edit-2', isEnabled: true },+ ],+ };++ expect(getGenerationValidationReasons(model, withEditReferences)).toEqual([]);++ return {+ base: 'krea-2' as const,+ filled,+ graph: compileGenerateGraph(withEditReferences, model, 'gallery', {+ useCpuNoise: true,+ useNsfwChecker: false,+ useWatermark: false,+ }).backendGraph,+ shape: KREA2_EDIT_SHAPE,+ };+ };// Each shape compiles twice: at its defaults, and with every optional tuning and output filter switched on.const compilations = [...generateGraphCases.flatMap(({ base, shape }) =>[false, true].map((tuned) => ({ base, shape, ...compileForShape(base, shape, tuned) }))),refinerCase(),+ krea2EditCase(),];for (const { base, filled, graph, shape } of compilations) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex db1cef340a..30edaf310e 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@ -335,6 +335,30 @@ describe('normalizeGenerateSettings', () => {expect(normalized && isGenerateSettings(normalized)).toBe(true);});+ it('keeps a Krea-2 edit reference as its image alone and reads the K/V cache switch only when true', () => {+ const image = { original: { image: { height: 512, image_name: 'pose.png', width: 512 } } };+ const normalized = normalizeGenerateSettings({+ ...legacyStoredValues,+ krea2ReferenceKvCache: true,+ referenceImages: [+ // A style strength carried over from the other mode does not belong to an edit reference.+ { config: { image, styleStrength: 1.5, type: 'krea2_edit_reference_image' }, id: 'pose', isEnabled: true },+ { config: { image: null, type: 'krea2_edit_reference_image' }, id: 'empty', isEnabled: false },+ ],+ });++ expect(normalized?.referenceImages).toEqual([+ { config: { image, type: 'krea2_edit_reference_image' }, id: 'pose', isEnabled: true },+ { config: { image: null, type: 'krea2_edit_reference_image' }, id: 'empty', isEnabled: false },+ ]);+ expect(normalized?.krea2ReferenceKvCache).toBe(true);+ expect(normalized && isGenerateSettings(normalized)).toBe(true);+ expect(+ normalizeGenerateSettings({ ...legacyStoredValues, krea2ReferenceKvCache: 'yes' })?.krea2ReferenceKvCache+ ).toBe(false);+ expect(normalizeGenerateSettings(legacyStoredValues)?.krea2ReferenceKvCache).toBe(false);+ });+it('drops malformed persisted model identifiers missing a base', () => {const normalized = normalizeGenerateSettings({...legacyStoredValues,diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex 4135ee9791..002b5bc391 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -305,6 +305,7 @@ const REFERENCE_IMAGE_CONFIG_TYPES = new Set(['flux_kontext_reference_image','flux_redux','ip_adapter',+ 'krea2_edit_reference_image','krea2_reference_image','qwen_image_reference_image',]);@@ -341,6 +342,7 @@ const normalizeReferenceImageConfig = (value: unknown): GenerateReferenceImageCoswitch (value.type) {case 'external_reference_image':case 'flux2_reference_image':+ case 'krea2_edit_reference_image':case 'qwen_image_reference_image':return { image, type: value.type };case 'flux_kontext_reference_image':@@ -412,6 +414,7 @@ const cloneReferenceImageConfig = (config: GenerateReferenceImageConfig): Generaswitch (config.type) {case 'external_reference_image':case 'flux2_reference_image':+ case 'krea2_edit_reference_image':case 'krea2_reference_image':case 'qwen_image_reference_image':return { ...config, image: config.image ? cloneCroppableImage(config.image) : null };@@ -582,6 +585,7 @@ const syncReferenceImageConfigWithModels = (}case 'external_reference_image':case 'flux2_reference_image':+ case 'krea2_edit_reference_image':case 'krea2_reference_image':case 'qwen_image_reference_image':return config;@@ -885,6 +889,7 @@ export const normalizeGenerateSettings = (values: unknown): GenerateSettings | n100,DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT),+ krea2ReferenceKvCache: values.krea2ReferenceKvCache === true,fluxDypePreset: isFluxDypePreset(values.fluxDypePreset) ? values.fluxDypePreset : 'off',fluxDypeScale: getClampedNumber(values, 'fluxDypeScale', 0, MAX_FLUX_DYPE_SCALE, DEFAULT_FLUX_DYPE_SCALE),fluxDypeExponent: getClampedNumber(diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex a2ba70b472..de9ad9c5ef 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -142,6 +142,11 @@ export type GenerateReferenceImageConfig =| { type: 'qwen_image_reference_image'; image: GenerateReferenceImageAsset | null }/** Krea-2 training-free style transfer: no adapter model, a single reference, `styleStrength` 0–2 (0 bypasses). */| { type: 'krea2_reference_image'; image: GenerateReferenceImageAsset | null; styleStrength: number }+ /**+ * Krea-2 edit reference for ai-toolkit edit LoRAs, read by the encoder's vision tower and joined to the denoise as+ * clean image tokens. Up to three, in list order; never combined with a style reference.+ */+ | { type: 'krea2_edit_reference_image'; image: GenerateReferenceImageAsset | null }| { type: 'external_reference_image'; image: GenerateReferenceImageAsset | null };export interface GenerateReferenceImage {@@ -270,6 +275,8 @@ export interface GenerateSettings {krea2SeedVarianceEnabled: boolean;krea2SeedVarianceStrength: number;krea2SeedVarianceRandomizePercent: number;+ /** Runs Krea-2 edit references once through the transformer, for edit LoRAs trained with isolated references. */+ krea2ReferenceKvCache: boolean;/** FLUX.1 DyPE position extrapolation for sizes above the training resolution. `off` sends nothing. */fluxDypePreset: FluxDypePreset;/** DyPE magnitude (λs) and decay speed (λt); the denoise node reads them only under the `manual` preset. */diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 26baa28537..3f5b82e9b9 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -44,7 +44,7 @@ export {createReferenceImageId,getCompatibleReferenceImages,getDefaultGenerateSettings,- getDefaultReferenceImageConfig,+ getDefaultReferenceImageConfigs,getGenerateModelSelectionResult,isComponentCompatibleWithModel,getDimensionGrid,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsxindex e62179851b..6cd3b6a68c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx@@ -1,5 +1,5 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */-import type { MainModelConfig } from '@features/generation/core/types';+import type { GenerateSettings, MainModelConfig } from '@features/generation/core/types';import { ChakraProvider } from '@chakra-ui/react';import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';@@ -43,6 +43,10 @@ void i18n.use(initReactI18next).init({hiDiffusionT1Ratio: 'HiDiffusion: T1 Ratio',hiDiffusionT2Ratio: 'HiDiffusion: T2 Ratio',hiDiffusionWindowAttn: 'HiDiffusion: Window Attention',+ krea2ReferenceKvCache: 'Reference K/V cache',+ krea2ReferenceKvCacheHelp: 'Only applies with edit references.',+ overridesCount_one: '{{count}} override',+ overridesCount_other: '{{count}} overrides',pid: 'PiD Decode',pidHelp: 'Replaces the VAE decode with a 4x super-resolution decode.',pidFit: 'Fit to size',@@ -73,6 +77,13 @@ const qwenImageModel: MainModelConfig = {name: 'Qwen Image',type: 'main',};+const krea2Model: MainModelConfig = {+ base: 'krea-2',+ format: 'diffusers',+ key: 'krea2',+ name: 'Krea-2 Turbo',+ type: 'main',+};let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -85,11 +96,15 @@ const settle = (action: () => void): Promise<void> =>});});-const render = async (model: MainModelConfig, hiDiffusionEnabled: boolean) => {+const render = async (+ model: MainModelConfig,+ hiDiffusionEnabled: boolean,+ overrides: Partial<GenerateSettings> = {}+) => {host = document.createElement('div');document.body.append(host);root = createRoot(host);- const settings = { ...getDefaultGenerateSettings(model), hiDiffusionEnabled };+ const settings = { ...getDefaultGenerateSettings(model), hiDiffusionEnabled, ...overrides };const onCommit = vi.fn();await settle(() => {@@ -185,3 +200,41 @@ describe('GenerateAdvancedFields encoder quantization', () => {expect(selectByLabel('Encoder quantization')).toBeNull();});});++describe('GenerateAdvancedFields Krea-2 reference K/V cache', () => {+ // Krea-2 has no other advanced field, so the section must not hide itself.+ it('offers the reference K/V cache for Krea-2 and commits the switch', async () => {+ const onCommit = await render(krea2Model, false);+ const kvCache = switchByLabel('Reference K/V cache');++ expect(kvCache).not.toBeNull();+ expect(host?.textContent).toContain('Only applies with edit references.');++ await settle(() => kvCache?.querySelector<HTMLElement>('[data-part="control"]')?.click());+ expect(onCommit).toHaveBeenCalledWith({ krea2ReferenceKvCache: true });+ });++ it('counts the switched-on K/V cache as an override only while edit references exist', async () => {+ const editReference = {+ config: {+ image: { original: { image: { height: 512, image_name: 'pose.png', width: 512 } } },+ type: 'krea2_edit_reference_image' as const,+ },+ id: 'pose',+ isEnabled: true,+ };++ await render(krea2Model, false, { krea2ReferenceKvCache: true });+ expect(host?.textContent).not.toContain('1 override');++ await settle(() => root?.unmount());+ await render(krea2Model, false, { krea2ReferenceKvCache: true, referenceImages: [editReference] });+ expect(host?.textContent).toContain('1 override');+ });++ it('omits the reference K/V cache for other families', async () => {+ await render(qwenImageModel, false);++ expect(switchByLabel('Reference K/V cache')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsxindex 3973fbaeb7..c07e536039 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx@@ -6,7 +6,11 @@ import type {} from '@features/generation/core/types';import { Badge, createListCollection, HStack, Stack } from '@chakra-ui/react';-import { getDefaultGenerateSettings, getGenerationUiPolicy } from '@features/generation/core/baseGenerationPolicies';+import {+ getDefaultGenerateSettings,+ getGenerationUiPolicy,+ hasEnabledKrea2EditReferences,+} from '@features/generation/core/baseGenerationPolicies';import { isPidMode, MAX_PID_STEPS, MIN_PID_STEPS } from '@features/generation/core/pid';import {DEFAULT_HIDIFFUSION_T1_RATIO,@@ -59,6 +63,7 @@ const selectAdvancedSettings = pickGenerateSettings(['hiDiffusionT1Ratio','hiDiffusionT2Ratio','hiDiffusionWindowAttentionEnabled',+ 'krea2ReferenceKvCache','pidMode','pidSteps','qwenImageEncoderQuantization',@@ -68,6 +73,10 @@ const selectAdvancedSettings = pickGenerateSettings(['vaePrecision',]);+/** A boolean, so editing a reference re-renders this section only when edit references come or go. */+const selectHasKrea2EditReferences = (settings: GenerateSettings): boolean =>+ hasEnabledKrea2EditReferences(settings.referenceImages);+export const GenerateAdvancedFields = ({draft,onCommit,@@ -76,6 +85,11 @@ export const GenerateAdvancedFields = ({}: GenerateAdvancedFieldsProps) => {const { t } = useTranslation();const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectAdvancedSettings);+ const hasKrea2EditReferences = useExternalStoreSelector(+ draft.subscribe,+ draft.getSnapshot,+ selectHasKrea2EditReferences+ );const modelBase = selectedModel?.base;const modelDefaults = selectedModel ? getDefaultGenerateSettings(selectedModel) : null;const policy = getGenerationUiPolicy(selectedModel);@@ -133,7 +147,8 @@ export const GenerateAdvancedFields = ({!policy.clipSkipMax &&!policy.cfgRescaleVisible &&!policy.pidVisible &&- !policy.encoderQuantizationVisible+ !policy.encoderQuantizationVisible &&+ !policy.krea2ReferenceKvCacheVisible) {return null;}@@ -149,6 +164,8 @@ export const GenerateAdvancedFields = ({policy.hiDiffusionVisible && settings.hiDiffusionEnabled,policy.pidVisible && settings.pidMode !== 'off',policy.encoderQuantizationVisible && settings.qwenImageEncoderQuantization !== 'none',+ // The switch only acts on edit references, so it is no override without them.+ policy.krea2ReferenceKvCacheVisible && hasKrea2EditReferences && settings.krea2ReferenceKvCache,].filter(Boolean).length;const badges =@@ -386,6 +403,21 @@ export const GenerateAdvancedFields = ({</Field>) : null}+ {policy.krea2ReferenceKvCacheVisible ? (+ <Field+ helpText={t('widgets.generate.krea2ReferenceKvCacheHelp')}+ hint="krea2ReferenceKvCache"+ label={t('widgets.generate.krea2ReferenceKvCache')}+ p="2"+ >+ <GenerateToggleSwitch+ checked={settings.krea2ReferenceKvCache}+ label={t('widgets.generate.krea2ReferenceKvCache')}+ onCheckedChange={(checked) => onCommit({ krea2ReferenceKvCache: checked })}+ />+ </Field>+ ) : null}+{policy.seamlessVisible ? (<Field hint="seamlessTiling" label={t('widgets.generate.seamlessTiling')} p="2"><HStack gap="4">diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsxindex 5ac47f0b06..4b0359d97c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx@@ -16,7 +16,7 @@ import { GalleryPickerPopover } from '@features/gallery/picker';import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';import {createReferenceImageId,- getDefaultReferenceImageConfig,+ getDefaultReferenceImageConfigs,getGenerationDimensions,getMaxReferenceImages,isReferenceImageSupported,@@ -73,12 +73,19 @@ export const GenerateReferenceImagesContent = ({return currentSettings;}+ const configs = getDefaultReferenceImageConfigs(+ selectedModel,+ models,+ images.slice(0, remaining).map((image) => ({ image, isEnabled: true })),+ currentSettings.referenceImages+ );+return {...currentSettings,referenceImages: [...currentSettings.referenceImages,- ...images.slice(0, remaining).map((image, index) => ({- config: getDefaultReferenceImageConfig(selectedModel, models, image),+ ...configs.map((config, index) => ({+ config,id: ids[index] ?? createReferenceImageId(),isEnabled: true,})),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsxindex fb89a3e164..199beb8b22 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx@@ -24,6 +24,7 @@ import {FieldHeader,FluxReduxControls,IPAdapterControls,+ Krea2ReferenceModeControl,Krea2StyleReferenceControls,} from './ReferenceImageControls';import { ReferenceImageCropDialog } from './ReferenceImageCropDialog';@@ -162,6 +163,11 @@ const ReferenceImageCardBase = ({{formatWeight(config.styleStrength)}</Text></>+ ) : config.type === 'krea2_edit_reference_image' ? (+ <>+ {' · '}+ {t('widgets.generate.modeEdit')}+ </>) : null}</Text></HStack>@@ -272,8 +278,13 @@ const ReferenceImageCardBase = ({selectedBase={selectedBase}onConfigChange={changeConfig}/>- ) : config.type === 'krea2_reference_image' ? (- <Krea2StyleReferenceControls config={config} disabled={!isEnabled} onChange={changeConfig} />+ ) : config.type === 'krea2_reference_image' || config.type === 'krea2_edit_reference_image' ? (+ <>+ <Krea2ReferenceModeControl config={config} disabled={!isEnabled} onChange={changeConfig} />+ {config.type === 'krea2_reference_image' ? (+ <Krea2StyleReferenceControls config={config} disabled={!isEnabled} onChange={changeConfig} />+ ) : null}+ </>) : null}</Stack></HStack>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsxindex c963445f3f..ddd24a1ecd 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx@@ -32,6 +32,10 @@ import {} from './referenceImageConfig';type IPAdapterConfig = Extract<GenerateReferenceImageConfig, { type: 'ip_adapter' }>;+type Krea2ReferenceConfig = Extract<+ GenerateReferenceImageConfig,+ { type: 'krea2_reference_image' | 'krea2_edit_reference_image' }+>;type ClipVisionOption = { label: ClipVisionModel; value: ClipVisionModel };type StyleVariantOption = { description: string; label: string; value: StyleMethod };type FluxReduxImageInfluenceOption = { label: string; value: FluxReduxImageInfluence };@@ -382,6 +386,60 @@ export const FluxReduxControls = <T extends { imageInfluence: FluxReduxImageInflconst STYLE_STRENGTH_MARKS = [DEFAULT_KREA2_STYLE_STRENGTH];+const KREA2_MODE_SEGMENTS = [+ { labelKey: 'widgets.generate.modeStyle', value: 'style' },+ { labelKey: 'widgets.generate.modeEdit', value: 'edit' },+] as const;++/** Switches a Krea-2 reference between Style and Edit; the image stays and Style restarts at its default strength. */+export const Krea2ReferenceModeControl = ({+ config,+ disabled,+ onChange,+}: {+ config: Krea2ReferenceConfig;+ disabled: boolean;+ onChange: (config: Krea2ReferenceConfig) => void;+}) => {+ const { t } = useTranslation();+ const mode = config.type === 'krea2_edit_reference_image' ? 'edit' : 'style';+ const handleModeChange = useCallback(+ ({ value }: SegmentGroup.ValueChangeDetails) => {+ if (value === mode) {+ return;+ }++ if (value === 'edit') {+ onChange({ image: config.image, type: 'krea2_edit_reference_image' });+ } else if (value === 'style') {+ onChange({ image: config.image, styleStrength: DEFAULT_KREA2_STYLE_STRENGTH, type: 'krea2_reference_image' });+ }+ },+ [config.image, mode, onChange]+ );++ return (+ <Stack gap="1">+ <FieldHeader hint="krea2ReferenceMode" label={t('widgets.generate.mode')} />+ <SegmentGroup.Root+ aria-label={t('widgets.generate.mode')}+ disabled={disabled}+ value={mode}+ w="full"+ onValueChange={handleModeChange}+ >+ <SegmentGroup.Indicator />+ {KREA2_MODE_SEGMENTS.map((segment) => (+ <SegmentGroup.Item key={segment.value} flex="1" justifyContent="center" value={segment.value}>+ <SegmentGroup.ItemText fontSize="xs">{t(segment.labelKey)}</SegmentGroup.ItemText>+ <SegmentGroup.ItemHiddenInput />+ </SegmentGroup.Item>+ ))}+ </SegmentGroup.Root>+ </Stack>+ );+};+/** Krea-2 style transfer has one knob; 0 bypasses the reference entirely. */export const Krea2StyleReferenceControls = <T extends { styleStrength: number; type: 'krea2_reference_image' }>({config,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageKrea2Mode.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageKrea2Mode.browser.test.tsxnew file mode 100644index 0000000000..bcc9fbfbdc--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageKrea2Mode.browser.test.tsx@@ -0,0 +1,165 @@+import type { GenerateReferenceImage } from '@features/generation/core/types';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import i18next from 'i18next';+import { act, useCallback, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import { ReferenceImageCard } from './ReferenceImageCard';++const i18n = i18next.createInstance();+await i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ lng: 'en',+ resources: {+ en: {+ translation: {+ widgets: {+ generate: {+ collapseReferenceImage: 'Collapse reference image',+ disableReferenceImage: 'Disable reference image',+ enableReferenceImage: 'Enable reference image',+ expandReferenceImage: 'Expand reference image',+ mode: 'Mode',+ modeEdit: 'Edit',+ modeStyle: 'Style',+ referenceImage: 'Reference Image',+ styleStrength: 'Style strength',+ },+ },+ },+ },+ },+});++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const onPatch = vi.fn();+const image = { original: { image: { height: 512, image_name: 'pose.png', width: 512 } } };+const STYLE_REFERENCE: GenerateReferenceImage = {+ config: { image, styleStrength: 1.6, type: 'krea2_reference_image' },+ id: 'pose',+ isEnabled: true,+};++/** Mirrors the section: each patch lands back on the rendered reference. */+const Card = ({ initial }: { initial: GenerateReferenceImage }) => {+ const [referenceImage, setReferenceImage] = useState(initial);+ const handlePatch = useCallback((id: string, patch: Partial<GenerateReferenceImage>) => {+ onPatch(id, patch);+ setReferenceImage((current) => ({ ...current, ...patch }));+ }, []);++ return (+ <ReferenceImageCard+ count={1}+ index={0}+ referenceImage={referenceImage}+ selectedModel={undefined}+ onFindInGallery={vi.fn()}+ onMove={vi.fn()}+ onPatch={handlePatch}+ onRemove={vi.fn()}+ onUseSize={vi.fn()}+ />+ );+};++const renderCard = async (initial: GenerateReferenceImage) => {+ await act(() =>+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <Card initial={initial} />+ </ChakraProvider>+ </I18nextProvider>+ )+ );+};++const modeGroup = () => host?.querySelector<HTMLElement>('[data-scope="segment-group"][data-part="root"]');+const modeRadio = (label: 'Edit' | 'Style') =>+ [...(modeGroup()?.querySelectorAll<HTMLElement>('[data-part="item"]') ?? [])]+ .find((item) => item.textContent === label)+ ?.querySelector<HTMLInputElement>('input[type="radio"]') ?? null;+const clickMode = async (label: 'Edit' | 'Style') => {+ const item = [...(modeGroup()?.querySelectorAll<HTMLElement>('[data-part="item"]') ?? [])].find(+ (candidate) => candidate.textContent === label+ );++ await act(async () => {+ await userEvent.click(item!);+ });+};+const hasStrengthControl = () => host?.textContent?.includes('Style strength') ?? false;++beforeEach(() => {+ host = document.createElement('div');+ host.style.width = '360px';+ document.body.append(host);+ root = createRoot(host);+ onPatch.mockClear();+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+});++describe('Krea-2 reference mode switch', () => {+ it('switches a reference to Edit and back to Style, keeping its image and restarting the strength', async () => {+ await renderCard(STYLE_REFERENCE);++ expect(modeGroup()?.getAttribute('aria-label')).toBe('Mode');+ expect(modeRadio('Style')?.checked).toBe(true);+ expect(hasStrengthControl()).toBe(true);++ await clickMode('Edit');++ expect(onPatch).toHaveBeenLastCalledWith('pose', {+ config: { image, type: 'krea2_edit_reference_image' },+ });+ expect(modeRadio('Edit')?.checked).toBe(true);+ // Edit references have no strength; the card shows only the mode.+ expect(hasStrengthControl()).toBe(false);++ await clickMode('Style');++ expect(onPatch).toHaveBeenLastCalledWith('pose', {+ config: { image, styleStrength: 1, type: 'krea2_reference_image' },+ });+ expect(hasStrengthControl()).toBe(true);+ });++ it('switches with the arrow keys from the focused mode', async () => {+ await renderCard(STYLE_REFERENCE);++ await act(() => modeRadio('Style')?.focus());+ await act(async () => {+ await userEvent.keyboard('{ArrowRight}');+ });++ expect(onPatch).toHaveBeenLastCalledWith('pose', {+ config: { image, type: 'krea2_edit_reference_image' },+ });+ expect(document.activeElement).toBe(modeRadio('Edit'));+ });++ it('locks the mode while the reference is switched off', async () => {+ await renderCard({ ...STYLE_REFERENCE, isEnabled: false });++ expect(modeRadio('Edit')?.disabled).toBe(true);++ // The pointer cannot reach a disabled segment, so dispatch the click directly.+ await act(() => modeRadio('Edit')?.closest('label')?.click());++ expect(onPatch).not.toHaveBeenCalled();+ expect(modeRadio('Style')?.checked).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.tsindex dc39ce67ed..340ebf03ea 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts+++ b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts@@ -38,6 +38,8 @@ export const FEATURE_HINTS = {imageInfluence: {href: 'https://support.invoke.ai/support/solutions/articles/151000094998-image-to-image',},+ krea2ReferenceKvCache: {},+ krea2ReferenceMode: {},layerStackControl: {},layerStackInpaintMask: {},layerStackRaster: {},diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex 95b68ba6d4..23cd966e61 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -128,6 +128,7 @@ const setModel = (project: Project, base: GenerateWidgetValues['model']['base'])krea2SeedVarianceEnabled: false,krea2SeedVarianceStrength: 0.1,krea2SeedVarianceRandomizePercent: 50,+ krea2ReferenceKvCache: false,fluxDypePreset: 'off',fluxDypeScale: 2,fluxDypeExponent: 2,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.tsindex 694d509196..e06b830077 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts@@ -83,6 +83,55 @@ describe('appendReferenceImage', () => {});});+ it('adds a Krea-2 image as the style reference only when no other reference runs', () => {+ const krea2Model: MainModelConfig = {+ base: 'krea-2',+ format: 'diffusers',+ key: 'krea2-key',+ name: 'Krea-2',+ type: 'main',+ };+ const krea2Values = (referenceImages: unknown[]) => ({+ ...getDefaultGenerateSettings(krea2Model),+ model: krea2Model,+ modelKey: krea2Model.key,+ referenceImages,+ });+ const pose = {+ config: {+ image: { original: { image: { height: 512, image_name: 'pose.png', width: 512 } } },+ type: 'krea2_edit_reference_image',+ },+ id: 'pose',+ isEnabled: true,+ };+ const appendedType = (referenceImages: unknown[]) => {+ const result = appendReferenceImage({+ generateValues: krea2Values(referenceImages),+ image,+ models: [krea2Model] as ModelConfig[],+ });++ if (result.status !== 'appended') {+ throw new Error(`Expected appended, got ${result.status}`);+ }++ return result.referenceImages.at(-1)?.config.type;+ };++ const style = {+ config: { image: pose.config.image, styleStrength: 1, type: 'krea2_reference_image' },+ id: 'style',+ isEnabled: true,+ };++ expect(appendedType([pose])).toBe('krea2_edit_reference_image');+ // Beside a style reference it does not become a second style reference; the card already there keeps its mode.+ expect(appendedType([style])).toBe('krea2_edit_reference_image');+ expect(appendedType([{ ...pose, isEnabled: false }])).toBe('krea2_reference_image');+ expect(appendedType([])).toBe('krea2_reference_image');+ });+it('returns unsupported when the model cannot take reference images', () => {const unsupportedModel = { base: 'sd-2', hash: 'hash-2', key: 'sd2-key', name: 'SD2', type: 'main' };diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.tsindex cc966a5ae6..ed54801688 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts@@ -5,7 +5,7 @@ import type { ModelConfig } from '@features/models';import {createReferenceImageId,generatedImageToReferenceImage,- getDefaultReferenceImageConfig,+ getDefaultReferenceImageConfigs,getMaxReferenceImages,isReferenceImageSupported,isSupportedGenerateModel,@@ -36,11 +36,13 @@ export const appendReferenceImage = ({return { status: 'full' };}- const referenceImage = {- config: getDefaultReferenceImageConfig(currentValues.model, models, generatedImageToReferenceImage(image)),- id: createReferenceImageId(),- isEnabled: true,- };+ const [config] = getDefaultReferenceImageConfigs(+ currentValues.model,+ models,+ [{ image: generatedImageToReferenceImage(image), isEnabled: true }],+ currentValues.referenceImages+ );+ const referenceImage = { config: config!, id: createReferenceImageId(), isEnabled: true };return { referenceImages: [...currentValues.referenceImages, referenceImage], status: 'appended' };};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex f73f392294..3ab4d8e711 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -159,6 +159,7 @@ const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWikrea2SeedVarianceEnabled: false,krea2SeedVarianceStrength: 0.1,krea2SeedVarianceRandomizePercent: 50,+ krea2ReferenceKvCache: false,fluxDypePreset: 'off',fluxDypeScale: 2,fluxDypeExponent: 2,@@ -1263,6 +1264,27 @@ describe('model-family tuning recall', () => {expect(unchanged?.fields).not.toContain('modelTuning');});+ it('restores the Krea-2 reference K/V cache, reading a Krea-2 record without it as off', () => {+ const krea2: MainModelConfig = { base: 'krea-2', key: 'krea2-tuning', name: 'Krea-2', type: 'main' };+ const krea2Record = (extra: Record<string, unknown> = {}) => ({+ generation_mode: 'krea2_txt2img',+ model: { base: 'krea-2', key: krea2.key, name: krea2.name, type: 'main' },+ ...extra,+ });+ const restored = recall(krea2Record({ krea2_reference_kv_cache: true }), krea2);++ expect(restored?.values.krea2ReferenceKvCache).toBe(true);+ expect(restored?.fields).toContain('modelTuning');+ // Graphs record the switch only with edit references, so its absence means the cache did not run.+ expect(recall(krea2Record(), krea2, 'all', { krea2ReferenceKvCache: true })?.values.krea2ReferenceKvCache).toBe(+ false+ );+ expect(+ recall({ krea2_reference_kv_cache: true }, qwenModel, 'all', { krea2ReferenceKvCache: false })?.values+ .krea2ReferenceKvCache+ ).toBe(false);+ });+it('restores the Qwen-Image shift and encoder quantization', () => {const result = recall({ qwen_image_quantization: 'nf4', qwen_image_shift: 3 }, qwenModel);@@ -1433,6 +1455,45 @@ describe('model-family tuning recall', () => {]);expect(result?.fields).toContain('referenceImages');});++ it('restores Krea-2 edit references and the K/V cache from the metadata their graph recorded', () => {+ const krea2Diffusers: MainModelConfig = { ...krea2Model, format: 'diffusers' };+ const editReference = (imageName: string) => ({+ config: {+ image: { original: { image: { height: 640, image_name: imageName, width: 480 } } },+ type: 'krea2_edit_reference_image' as const,+ },+ id: imageName,+ isEnabled: true,+ });+ const referenceImages = [editReference('pose.png'), editReference('room.png')];+ const graph = compileGenerateGraph(+ {+ ...createValues({ model: krea2Diffusers, modelKey: krea2Diffusers.key }),+ krea2ReferenceKvCache: true,+ referenceImages,+ },+ krea2Diffusers,+ 'gallery',+ { useCpuNoise: true, useNsfwChecker: false, useWatermark: false }+ ).backendGraph;+ const metadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');++ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata,+ models: [],+ supportedModels: [krea2Diffusers],+ vaeModels: [],+ });++ expect(result?.values.model).toEqual(krea2Diffusers);+ expect(result?.values.referenceImages).toEqual(referenceImages);+ expect(result?.values.krea2ReferenceKvCache).toBe(true);+ expect(result?.fields).toEqual(expect.arrayContaining(['referenceImages', 'modelTuning']));+ });});describe('Krea-2 style reference without an image', () => {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex 969b347fb3..7796b915df 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -563,6 +563,17 @@ const getMetadataModelTuning = (};}+ if (model.base === 'krea-2') {+ // Recorded only with edit references; a Krea-2 image without them ran with the cache off.+ const referenceKvCache = recordedOrDefault(+ 'krea2_reference_kv_cache',+ getBoolean(metadata, 'krea2_reference_kv_cache') ?? undefined,+ false+ );++ return referenceKvCache === undefined ? {} : { krea2ReferenceKvCache: referenceKvCache };+ }+return {};};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.tsindex 2fa06ee3a4..e62780b74a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts@@ -495,6 +495,49 @@ describe('buildRecallParametersSettings', () => {expect(untouched.values.referenceImages).toEqual(current.referenceImages);});+ it('types recalled Krea-2 references as one set: a lone one is style, several or appended ones are edit', () => {+ const krea2 = makeModel('krea2-main', 'krea-2', 'main', { format: 'diffusers' });+ const krea2Supported = [krea2].filter(isSupportedGenerateModel) as GenerateModelConfig[];+ const krea2Values = getCurrentGenerateValues({+ generateValues: { modelKey: krea2.key },+ supportedModels: krea2Supported,+ });++ if (!krea2Values) {+ throw new Error('fixture model is not a supported Generate model');+ }++ const currentValues = {+ ...krea2Values,+ referenceImages: [+ {+ config: { image: { original: { image: image('pose.png') } }, type: 'krea2_edit_reference_image' as const },+ id: 'pose',+ isEnabled: true,+ },+ ],+ };+ const recalledTypes = (parameters: Record<string, unknown>) =>+ buildRecallParametersSettings({+ currentValues,+ models: [krea2],+ parameters,+ supportedModels: krea2Supported,+ vaeModels: [],+ }).values.referenceImages.map((reference) => reference.config.type);++ expect(recalledTypes({ append: true, reference_images: [{ image: image('depth.png') }] })).toEqual([+ 'krea2_edit_reference_image',+ 'krea2_edit_reference_image',+ ]);+ expect(recalledTypes({ reference_images: [{ image: image('depth.png') }] })).toEqual(['krea2_reference_image']);+ expect(+ recalledTypes({+ reference_images: [{ image: image('pose.png') }, { image: image('depth.png') }, { image: image('room.png') }],+ })+ ).toEqual(['krea2_edit_reference_image', 'krea2_edit_reference_image', 'krea2_edit_reference_image']);+ });+it('drops reference images for a model without reference image support and says so', () => {const result = build(currentFor(sd3), { reference_images: [{ image: image('subject.png') }] });diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.tsindex 251ed16e97..278fb2e867 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts@@ -18,7 +18,7 @@ import {getCompatibleReferenceImages,getDefaultGenerateSettings,getDefaultLoraWeight,- getDefaultReferenceImageConfig,+ getDefaultReferenceImageConfigs,getGenerateModelSelectionResult,getGenerationUiPolicy,getMaxReferenceImages,@@ -587,6 +587,8 @@ export const buildRecallParametersSettings = ({}}+ const recalledImages: GenerateReferenceImageAsset[] = [];+for (const entry of referenceImages ?? []) {const image = isRecord(entry) ? toReferenceAsset(entry.image) : null;@@ -595,9 +597,21 @@ export const buildRecallParametersSettings = ({continue;}- recalled.push(toReferenceImage(getDefaultReferenceImageConfig(values.model, models, image)));+ recalledImages.push(image);}+ // Typed as one set beside the list they join, so a Krea-2 recall of several images is an edit set.+ const joining = append ? values.referenceImages : [];++ recalled.push(+ ...getDefaultReferenceImageConfigs(+ values.model,+ models,+ recalledImages.map((image) => ({ image, isEnabled: true })),+ [...joining, ...recalled]+ ).map(toReferenceImage)+ );+if (recalled.length > 0 && !isReferenceImageSupported(values.model)) {if (ipAdapters?.length) {skip('ip_adapters', 'incompatible', values.model.name);@@ -607,7 +621,7 @@ export const buildRecallParametersSettings = ({}}- const compatible = getCompatibleReferenceImages(recalled, values.model, models);+ const compatible = getCompatibleReferenceImages(recalled, values.model, models, joining);let next = append ? [...values.referenceImages, ...compatible] : compatible;const limit = getMaxReferenceImages(values.model);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 80c9f9b140..56fc0a2d93 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -263,6 +263,7 @@ const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): Gekrea2SeedVarianceEnabled: false,krea2SeedVarianceStrength: 0.1,krea2SeedVarianceRandomizePercent: 50,+ krea2ReferenceKvCache: false,fluxDypePreset: 'off',fluxDypeScale: 2,fluxDypeExponent: 2,