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
fix(krea2): guide edit references toward edit LoRAs and keep Style/Edit cards consistent
Alexander Eichhorn5e7f6f6e4e7c
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 3814859286..01ff6d8919 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@@ -153,7 +153,7 @@ feeding the **Style Reference** 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 runs one enabled Style reference at a time and+- **Exactly one** reference image is used. The Generate panel runs one active Style reference at a time anddoes 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 same@@ -177,7 +177,9 @@ Some Krea-2 LoRAs are trained to transform one or more input images rather thanalone. They come from ai-toolkit's Krea-2 edit training (`edit: true`) and include the pose and depth"controlnet" LoRAs: you give them a pose skeleton or a depth map as a reference image, and the promptdescribes the result. Such a LoRA does nothing useful without its reference images, and an ordinary Krea-2-LoRA gains nothing from them.+LoRA gains nothing from them. Edit mode is not a general instruction editor: without a matching edit LoRA,+prompts such as "replace the dog with a cat" are not carried out, and the model copies the reference instead.+The Generate panel shows a note while Edit references are active and no LoRA is enabled in **Concepts**.A reference image reaches the model twice, and both are needed:@@ -199,8 +201,10 @@ the colors hidden under its transparent areas, not a background.### In the Generate panel and on the Canvas1. 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+2. Add the reference images, up to three. Several added at once, or added beside an active reference, start+ as **Edit**. A single first reference starts as **Style**; adding a second image turns it into **Edit** as+ long as its strength is still the default. For a LoRA that takes one reference, such as a pose skeleton,+ switch its **Mode** to **Edit** yourself. A Style reference at strength 0 is not active. The enabledreferences 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**.@@ -216,8 +220,9 @@ With CFG above 1 the negative prompt reads the same references. Invoke stays disEdit 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 referencescannot 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.+[K/V cache](#reference-kv-cache) below; it can be switched only while Edit references are active and a LoRA is+enabled in **Concepts**, and is not sent otherwise. The references and, when it was sent, the K/V cache setting+are recorded in image metadata, so **Recall All** and **Remix Image** restore them.### In the workflow editordiff --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 1d4940b0dc..eda1fb3922 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@@ -75,7 +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).+* **Reference K/V cache** — Krea-2 only, and only with active **Edit** references and an enabled LoRA in **Concepts**. 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.@@ -126,7 +126,7 @@ What a reference does, and what options it has, depends on the model family: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.+A new Krea-2 reference starts as **Style** when it is the only active one; added beside other active references, or several at once, it starts as **Edit**. A Style reference at strength 0 is not active. Adding an image beside a lone Style reference still at its default strength turns that card into **Edit** too; one whose strength was changed keeps its mode. Krea-2 runs either one Style reference or up to three Edit references, never both; Invoke stays disabled and says why until the active references fit. The **Mode** can be changed while a card is switched off. Switching a card back to Style resets its strength to 1.## Prompt toolsdiff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 0727ae4ca8..1e8ebabd14 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -919,7 +919,8 @@"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.",+ "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. Without such a LoRA in Concepts the model copies the references. Edit references cannot be combined with a style reference or with regional guidance.",+ "A single reference starts as Style. For an edit LoRA that takes one reference, such as a pose skeleton, switch it to Edit. Adding a second image turns a Style reference still at its default strength into Edit as well.","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."]},@@ -927,7 +928,7 @@"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."+ "Leave it off for normal edit LoRAs. The LoRA file does not say which kind it is; check its model card. It applies only with Edit references and an edit LoRA in Concepts; otherwise it keeps its setting but is not used."]},"timestepShift": {@@ -2704,7 +2705,10 @@"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.",+ "krea2ReferenceKvCacheHelp": "For edit LoRAs trained with isolated references.",+ "krea2ReferenceKvCacheNeedsEditReferences": "Applies only with Edit references and an edit LoRA in Concepts.",+ "krea2ReferenceKvCacheNeedsLora": "Applies only with an edit LoRA enabled in Concepts.",+ "krea2EditReferencesNeedLora": "Edit references need an edit LoRA (pose, depth, …); without one the model copies the reference.","styleStrength": "Style strength","timestepShift": "Shift","timestepShiftHelp": "Auto derives the schedule shift from the image size.",diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.jsonindex c69f2079c5..dd26322fec 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json@@ -250,9 +250,11 @@"img_watermark","integer","krea2_denoise",+ "krea2_lora_collection_loader","krea2_model_loader","krea2_style_reference","krea2_text_encoder",+ "lora_selector","qwen_image_i2l","qwen_image_l2i","string"@@ -665,6 +667,7 @@"krea2_style_strength": [1],+ "loras": [],"mistral_encoder": [],"model": [],"qwen_image_quantization": [@@ -1340,6 +1343,25 @@"latents"]},+ "krea2_lora_collection_loader": {+ "inputs": [+ "loras",+ "qwen3_vl_encoder",+ "transformer"+ ],+ "literalInputs": {+ "is_intermediate": [+ true+ ],+ "use_cache": [+ true+ ]+ },+ "outputs": [+ "qwen3_vl_encoder",+ "transformer"+ ]+ },"krea2_model_loader": {"inputs": [],"literalInputs": {@@ -1428,6 +1450,24 @@"image"]},+ "lora_selector": {+ "inputs": [],+ "literalInputs": {+ "is_intermediate": [+ true+ ],+ "lora": [],+ "use_cache": [+ true+ ],+ "weight": [+ 1+ ]+ },+ "outputs": [+ "lora"+ ]+ },"main_model_loader": {"inputs": [],"literalInputs": {diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex 6ef196cefd..d221ec340f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -22,12 +22,12 @@ import {getComponentSectionPolicy,getAutoFlux2ComponentSourceModel,getDefaultGenerateSettings,- getDefaultReferenceImageConfigs,getGenerateModelSelectionResult,getGenerationDimensions,getGenerationModelAvailabilityReasons,getGenerationUiPolicy,getGenerationValidationReasons,+ getKrea2EditLoraState,getMaxReferenceImages,getPromptPolicy,getSchedulerOptions,@@ -35,6 +35,7 @@ import {isReferenceImageSupported,isGenerateModelSelectable,isSupportedGenerateModel,+ withAddedReferenceImages,} from './baseGenerationPolicies';import { SUPPORTED_GENERATE_BASES } from './supportedBases';@@ -1031,8 +1032,8 @@ describe('component policies', () => {// 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' }]);+ withAddedReferenceImages(krea2, [sdxlIpAdapter], [], [{ id: 'new', image: referenceImage }])[0]?.config+ ).toEqual({ image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' });const fromSdxl = getGenerateModelSelectionResult({currentValues: createSettings(createModel('sdxl'), {@@ -1167,37 +1168,74 @@ describe('component policies', () => {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.`;+ 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 file or Diffusers folder that includes the vision weights.`;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(+ const typesAfterAdding = (count: number, referenceImages: GenerateSettings['referenceImages'] = []) =>+ withAddedReferenceImages(krea2,[],- Array.from({ length: count }, () => ({ image: referenceImage, isEnabled })),- referenceImages- );+ referenceImages,+ Array.from({ length: count }, (_, index) => ({ id: `new-${index}`, image: referenceImage }))+ ).map(({ config, id, isEnabled }) => [id, config.type, isEnabled]);- expect(added(1)).toEqual([styleConfig]);+ expect(typesAfterAdding(1)).toEqual([['new-0', 'krea2_reference_image', true]]);// 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.',+ expect(typesAfterAdding(3).map(([, type]) => type)).toEqual([+ 'krea2_edit_reference_image',+ 'krea2_edit_reference_image',+ 'krea2_edit_reference_image',+ ]);+ expect(typesAfterAdding(1, [edit('a')])).toEqual([+ ['a', 'krea2_edit_reference_image', true],+ ['new-0', 'krea2_edit_reference_image', true],]);// 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]);+ const bypassed = { ...style('s'), config: { ...style('s').config, styleStrength: 0 } };++ expect(typesAfterAdding(1, [edit('a', false), bypassed])).toEqual([+ ['a', 'krea2_edit_reference_image', false],+ ['s', 'krea2_reference_image', true],+ ['new-0', 'krea2_reference_image', true],+ ]);+ });++ it('turns a lone untouched style reference into an edit reference when another image is added', () => {+ const added = (referenceImages: GenerateSettings['referenceImages']) =>+ withAddedReferenceImages(krea2, [], referenceImages, [{ id: 'new', image: referenceImage }]);++ // Building an edit set one image at a time: the first card started as Style at its default strength.+ expect(added([style('s')])).toEqual([edit('s'), edit('new')]);+ expect(reasonsFor(krea2, { referenceImages: added([style('s')]) })).toEqual([]);+ // Picking three images one by one, as the gallery picker hands them over, ends as an edit set.+ const picked = ['a', 'b', 'c'].reduce<GenerateSettings['referenceImages']>(+ (list, id) => withAddedReferenceImages(krea2, [], list, [{ id, image: referenceImage }]),+ []+ );++ expect(picked).toEqual([edit('a'), edit('b'), edit('c')]);++ // A changed strength marks the card as meant for style: it stays, and the mix is reported, not hidden.+ const tuned = { ...style('s'), config: { ...style('s').config, styleStrength: 1.4 } };++ expect(added([tuned])).toEqual([tuned, edit('new')]);+ expect(reasonsFor(krea2, { referenceImages: added([tuned]) })).toEqual([+ 'Krea-2 cannot combine a style reference with edit references. Switch the style reference to Edit, or turn off one kind.',+ ]);+ // Only a lone running style reference flips; a switched-off one stays as it is.+ expect(added([style('off', false), edit('a')])).toEqual([style('off', false), edit('a'), edit('new')]);+ // Other families have one kind, so nothing changes mode.+ const flux2 = createModel('flux2', { format: 'diffusers' });+ const flux2Reference = {+ config: { image: referenceImage, type: 'flux2_reference_image' as const },+ id: 'f',+ isEnabled: true,+ };++ expect(withAddedReferenceImages(flux2, [], [flux2Reference], [{ id: 'new', image: referenceImage }])).toEqual([+ flux2Reference,+ { ...flux2Reference, id: 'new' },+ ]);});it('treats a zero-strength style reference as off in every check', () => {@@ -1242,6 +1280,23 @@ describe('component policies', () => {expect(reasonsFor(krea2, { referenceImages: [style('a', false), edit('b'), edit('c')] })).toEqual([]);});+ it('says whether running edit references have an enabled Krea-2 LoRA to read them', () => {+ const krea2Lora: LoraModelConfig = { base: 'krea-2', key: 'pose-lora', name: 'Pose LoRA', type: 'lora' };+ const lora = (model: LoraModelConfig, isEnabled = true) => ({ isEnabled, model, weight: 1 });+ const state = (overrides: Partial<GenerateSettings>, model: MainModelConfig = krea2) =>+ getKrea2EditLoraState(model, createSettings(model, overrides));++ expect(state({ loras: [lora(krea2Lora)], referenceImages: [edit('a')] })).toBe('ready');+ // A disabled LoRA or one for another family does not reach the graph.+ expect(state({ loras: [lora(krea2Lora, false), lora(sdxlLora)], referenceImages: [edit('a')] })).toBe('noLora');+ expect(state({ loras: [lora(krea2Lora)], referenceImages: [edit('a', false), style('s')] })).toBe(+ 'noEditReferences'+ );+ expect(state({ loras: [lora(krea2Lora)], referenceImages: [edit('a')] }, createModel('flux2'))).toBe(+ 'noEditReferences'+ );+ });+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' };@@ -1343,6 +1398,19 @@ describe('component policies', () => {['c', true],]);+ // An edit reference after the style reference stops too, and the switch names what it changed.+ const styleFirst = getGenerateModelSelectionResult({+ currentValues: createSettings(krea2, { referenceImages: [style('s'), edit('e')] }),+ model: otherKrea2,+ models: [],+ });++ expect(styleFirst.settings.referenceImages.map(({ id, isEnabled }) => [id, isEnabled])).toEqual([+ ['s', true],+ ['e', false],+ ]);+ expect(styleFirst.clearedLabels).toContain('Reference Images');+// 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)] }),diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 1e83e3a4ed..4da4b16318 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -1353,6 +1353,24 @@ export const hasEnabledKrea2EditReferences = (referenceImages: readonly Generate(referenceImage) => referenceImage.isEnabled && referenceImage.config.type === 'krea2_edit_reference_image');+/**+ * Whether running Krea-2 edit references have an active LoRA to read them. The base model is no instruction editor:+ * without an edit LoRA it copies the references, and the graph leaves the reference K/V cache, which only such a LoRA+ * reads, at the denoise default. A LoRA counts as the graph counts it: enabled and compatible with the model.+ */+export const getKrea2EditLoraState = (+ model: GenerateModelConfig | undefined,+ settings: Pick<GenerateSettings, 'loras' | 'referenceImages'>+): 'noEditReferences' | 'noLora' | 'ready' => {+ if (model?.base !== 'krea-2' || !hasEnabledKrea2EditReferences(settings.referenceImages)) {+ return 'noEditReferences';+ }++ return settings.loras.some((lora) => lora.isEnabled && isLoraCompatibleWithModel(lora.model, model))+ ? 'ready'+ : 'noLora';+};+/** 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 &&@@ -1441,31 +1459,27 @@ export const isReferenceImageCompatibleWithModel = (};/** A new or re-targeted reference, typed for the model; existing references keep theirs. */-export interface ReferenceImageAddition {+interface ReferenceImageAddition {image: GenerateReferenceImageAsset | null;isEnabled: boolean;}/**- * 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.+ * Configs for `additions` joining `referenceImages`. 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 = (+const getDefaultReferenceImageConfigs = (model: GenerateModelConfig | undefined,models: readonly ReferenceModelCandidate[],additions: readonly ReferenceImageAddition[],- referenceImages: readonly GenerateReferenceImage[] = []+ 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 runningElsewhere = referenceImages.filter(isReferenceImageActive).length;const enabledAdditions = additions.filter((addition) => addition.isEnabled).length;return additions.map(({ image, isEnabled }) =>@@ -1494,16 +1508,65 @@ const canRunWithEnabledReferenceImages = (: enabled.every((kept) => kept.config.type !== 'krea2_reference_image');};+/**+ * The list's one running reference when it is a Krea-2 style reference still at its default strength, which an+ * addition turns into an edit reference.+ */+const getLoneDefaultStyleReference = (+ referenceImages: readonly GenerateReferenceImage[]+): GenerateReferenceImage | null => {+ const active = referenceImages.filter(isReferenceImageActive);+ const [lone] = active;++ return active.length === 1 &&+ lone?.config.type === 'krea2_reference_image' &&+ lone.config.styleStrength === DEFAULT_KREA2_STYLE_STRENGTH+ ? lone+ : null;+};++/**+ * `referenceImages` with `additions` appended as enabled references typed for the model; every way of adding a+ * reference goes through here. A lone first Krea-2 reference starts as the style reference, so an edit set built one+ * image at a time begins with one: the next addition turns it into an edit reference too, unless its strength was+ * changed, which marks it as meant for style. Validation then reports the mix.+ */+export const withAddedReferenceImages = (+ model: GenerateModelConfig | undefined,+ models: readonly ReferenceModelCandidate[],+ referenceImages: GenerateReferenceImage[],+ additions: readonly { id: string; image: GenerateReferenceImageAsset | null }[]+): GenerateReferenceImage[] => {+ if (additions.length === 0) {+ return referenceImages;+ }++ const lone = model?.type === 'main' && model.base === 'krea-2' ? getLoneDefaultStyleReference(referenceImages) : null;+ const kept = lone+ ? referenceImages.map((referenceImage): GenerateReferenceImage =>+ referenceImage === lone+ ? { ...referenceImage, config: { image: referenceImage.config.image, type: 'krea2_edit_reference_image' } }+ : referenceImage+ )+ : referenceImages;+ const configs = getDefaultReferenceImageConfigs(+ model,+ models,+ additions.map(({ image }) => ({ image, isEnabled: true })),+ kept+ );++ return [...kept, ...additions.map(({ id }, index) => ({ config: configs[index]!, id, isEnabled: true }))];+};+/*** 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.+ * are typed together, beside the compatible ones. No changes return the same array.*/export const getCompatibleReferenceImages = (referenceImages: GenerateReferenceImage[],model: GenerateModelConfig,- models: readonly ReferenceModelCandidate[],- joining: readonly GenerateReferenceImage[] = []+ models: readonly ReferenceModelCandidate[]): GenerateReferenceImage[] => {if (referenceImages.length === 0) {return referenceImages;@@ -1526,7 +1589,7 @@ export const getCompatibleReferenceImages = (model,models,retargeted.map(({ config, isEnabled }) => ({ image: config.image, isEnabled })),- [...joining, ...referenceImages.filter((_, index) => isCompatible[index])]+ referenceImages.filter((_, index) => isCompatible[index]));let retargetIndex = 0;@@ -1842,7 +1905,9 @@ export const getGuidanceBoundReason = (/*** 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.+ * a GGUF Qwen3-VL encoder does not carry; a Diffusers main without an encoder override uses its bundled one. A+ * standalone encoder folder may lack the vision weights too, but its config does not say so, so the message names+ * what the encoder needs rather than a format that always has it.*/const getKrea2ReferenceValidationReasons = (settings: GenerateSettings): string[] => {const styleCount = settings.referenceImages.filter(@@ -1865,7 +1930,7 @@ const getKrea2ReferenceValidationReasons = (settings: GenerateSettings): string[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.`+ `Krea-2 edit references need a Qwen3-VL encoder with vision weights, which the GGUF encoder "${encoder.name}" does not have. Select a safetensors file or Diffusers folder that includes the vision weights.`);}diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex ff0eeda8a3..f1d930582c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -1730,6 +1730,7 @@ describe('model-family tuning', () => {expect(getNodeByType(graph, 'core_metadata')).not.toHaveProperty('krea2_style_strength');});+ const krea2EditLora: LoraModelConfig = { base: 'krea-2', key: 'krea2-pose', name: 'Krea-2 Pose', type: 'lora' };const editReference = (imageName: string, isEnabled = true) => ({config: {image: { original: { image: { height: 640, image_name: imageName, width: 480 } } },@@ -1792,12 +1793,13 @@ describe('model-family tuning', () => {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);+ // No LoRA: the K/V cache switch is not sent, and the record says nothing about it.+ expect(graph.nodes.denoise_latents).not.toHaveProperty('reference_kv_cache');expect(getNodeByType(graph, 'krea2_style_reference')).toBeUndefined();const metadata = getNodeByType(graph, 'core_metadata')!;- expect(metadata.krea2_reference_kv_cache).toBe(false);+ expect(metadata).not.toHaveProperty('krea2_reference_kv_cache');expect((metadata.ref_images as { id: string }[]).map((entry) => entry.id)).toEqual(['depth.png','pose',@@ -1805,9 +1807,10 @@ describe('model-family tuning', () => {]);});- it('gives the negative prompt the same edit references under CFG and sends the K/V cache switch', () => {+ it('gives the negative prompt the same edit references under CFG and sends the K/V cache switch with a LoRA', () => {const graph = compile(krea2Model, {cfgScale: 4.5,+ loras: [{ isEnabled: true, model: krea2EditLora, weight: 1 }],krea2RebalanceEnabled: true,krea2ReferenceKvCache: true,krea2SeedVarianceEnabled: true,@@ -1825,6 +1828,21 @@ describe('model-family tuning', () => {expect(getNodeByType(graph, 'core_metadata')?.krea2_reference_kv_cache).toBe(true);});+ it('sends the K/V cache switch only while a Krea-2 LoRA is enabled, keeping the stored value otherwise', () => {+ const kvCacheFor = (loras: GenerateSettings['loras'], krea2ReferenceKvCache: boolean) => {+ const graph = compile(krea2Model, { krea2ReferenceKvCache, loras, referenceImages: [editReference('pose.png')] });++ return [+ graph.nodes.denoise_latents?.reference_kv_cache,+ getNodeByType(graph, 'core_metadata')?.krea2_reference_kv_cache,+ ];+ };++ expect(kvCacheFor([{ isEnabled: true, model: krea2EditLora, weight: 1 }], false)).toEqual([false, false]);+ expect(kvCacheFor([{ isEnabled: false, model: krea2EditLora, weight: 1 }], true)).toEqual([undefined, undefined]);+ expect(kvCacheFor([{ isEnabled: true, model: sdxlLora, weight: 1 }], true)).toEqual([undefined, undefined]);+ });+it('keeps the style path and leaves the edit inputs unset without enabled edit references', () => {const graph = compile(krea2Model, {cfgScale: 4.5,diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex 61e8d6e8a9..c723769266 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -1304,7 +1304,8 @@ const addKrea2EditReferences = (denoise: BackendInvocationContract;prompts: readonly BackendInvocationContract[];referenceImages: readonly { image_name: string }[];- referenceKvCache: boolean;+ /** Unset leaves the denoise default. */+ referenceKvCache: boolean | undefined;vaeSource: BackendInvocationContract;}) => {@@ -1330,7 +1331,9 @@ const addKrea2EditReferences = (if (previousCollect) {addEdge(graph, previousCollect, 'collection', denoise, 'reference_latents');}- denoise.reference_kv_cache = referenceKvCache;+ if (referenceKvCache !== undefined) {+ denoise.reference_kv_cache = referenceKvCache;+ }};const buildKrea2Graph = (@@ -1416,12 +1419,18 @@ const buildKrea2Graph = ((referenceImage) => referenceImage.config.styleStrength > 0);+ // The cache changes how edit references run, and only an edit LoRA trained with it (ai-toolkit's `kv_cache`) reads+ // them that way; the base model alone sees them through attention it never learned. Without a LoRA the stored+ // switch is kept but not sent, so the denoise runs its default and the record says nothing about it.+ const referenceKvCache =+ editReferenceImages.length > 0 && activeLoras.length > 0 ? settings.krea2ReferenceKvCache : undefined;+if (editReferenceImages.length > 0) {addKrea2EditReferences(graph, {denoise,prompts: negCond ? [posCond, negCond] : [posCond],referenceImages: editReferenceImages,- referenceKvCache: settings.krea2ReferenceKvCache,+ referenceKvCache,vaeSource: modelLoader,});} else if (styleReference?.config.image) {@@ -1446,7 +1455,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 } : {}),+ ...(referenceKvCache === undefined ? {} : { krea2_reference_kv_cache: referenceKvCache }),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 41fe35df6f..a8b34d7f9b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts@@ -82,6 +82,14 @@ const krea2EditCase = () => {// CFG builds the negative prompt, which reads the references too.cfgScale: 4.5,krea2ReferenceKvCache: true,+ // The K/V cache switch is sent only while a LoRA reads the references.+ loras: [+ {+ isEnabled: true,+ model: { base: 'krea-2', key: 'edit-lora', name: 'edit-lora', type: 'lora' as const },+ weight: 1,+ },+ ],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 },diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 7dff651aa3..b2a10fc82a 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -45,7 +45,7 @@ export {createReferenceImageId,getCompatibleReferenceImages,getDefaultGenerateSettings,- getDefaultReferenceImageConfigs,+ withAddedReferenceImages,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 6cd3b6a68c..eb53080ddf 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@@ -20,51 +20,12 @@ vi.mock('./GenerationUiContext', () => ({}),}));+// The real catalog, so a mistyped key shows up as the key and fails the label lookups below.const i18n = createInstance();-void i18n.use(initReactI18next).init({- fallbackLng: 'en',- initAsync: false,+await i18n.use(initReactI18next).init({+ interpolation: { escapeValue: false },lng: 'en',- resources: {- en: {- translation: {- widgets: {- generate: {- advanced: 'Advanced',- cfgRescale: 'CFG rescale',- clipSkip: 'CLIP skip',- encoderQuantization: 'Encoder quantization',- encoderQuantizationHelp: 'Quantizes the Qwen VL encoder on load to save VRAM.',- encoderQuantizationInt8: '8-bit (int8)',- encoderQuantizationNf4: '4-bit (nf4)',- encoderQuantizationNone: 'None (bf16)',- hiDiffusion: 'HiDiffusion',- hiDiffusionRauNet: 'HiDiffusion: RAU-Net',- 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',- pidNative: 'Native 4x',- pidOff: 'Off',- seamlessTiling: 'Seamless tiling',- tileX: 'Tile X',- tileY: 'Tile Y',- usingBundledVae: 'Using bundled VAE',- vae: 'VAE',- vaePrecision: 'VAE precision',- xAxis: 'X axis',- yAxis: 'Y axis',- },- },- },- },- },+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },});const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1', name: 'SD 1.5', type: 'main' };@@ -202,33 +163,65 @@ describe('GenerateAdvancedFields encoder quantization', () => {});describe('GenerateAdvancedFields Krea-2 reference K/V cache', () => {+ 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,+ };+ const poseLora = {+ isEnabled: true,+ model: { base: 'krea-2', key: 'pose-lora', name: 'Pose LoRA', type: 'lora' as const },+ weight: 1,+ };+ const kvCacheInput = () => switchByLabel('Reference K/V cache')?.querySelector<HTMLInputElement>('input') ?? null;+// 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');+ it('offers the switch with edit references and a LoRA, and commits it', async () => {+ const onCommit = await render(krea2Model, false, { loras: [poseLora], referenceImages: [editReference] });- expect(kvCache).not.toBeNull();- expect(host?.textContent).toContain('Only applies with edit references.');+ expect(kvCacheInput()?.disabled).toBe(false);+ expect(host?.textContent).toContain('For edit LoRAs trained with isolated references.');- await settle(() => kvCache?.querySelector<HTMLElement>('[data-part="control"]')?.click());+ await settle(() =>+ switchByLabel('Reference K/V cache')?.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 });+ it('disables the switch, shows it off and says why without edit references or a LoRA, keeping the stored value', async () => {+ await render(krea2Model, false, { krea2ReferenceKvCache: true, loras: [poseLora] });++ expect(kvCacheInput()?.disabled).toBe(true);+ // Shown off while it is not sent.+ expect(kvCacheInput()?.checked).toBe(false);+ expect(host?.textContent).toContain('Applies only with Edit references and an edit LoRA in Concepts.');+ // Not sent, so not counted as an override.+ expect(host?.textContent).not.toContain('1 override');++ await settle(() => root?.unmount());+ await render(krea2Model, false, {+ krea2ReferenceKvCache: true,+ loras: [{ ...poseLora, isEnabled: false }],+ referenceImages: [editReference],+ });++ expect(kvCacheInput()?.disabled).toBe(true);+ expect(host?.textContent).toContain('Applies only with an edit LoRA enabled in Concepts.');expect(host?.textContent).not.toContain('1 override');await settle(() => root?.unmount());- await render(krea2Model, false, { krea2ReferenceKvCache: true, referenceImages: [editReference] });+ await render(krea2Model, false, {+ krea2ReferenceKvCache: true,+ loras: [poseLora],+ referenceImages: [editReference],+ });++ // The stored value is back once the references and the LoRA are.+ expect(kvCacheInput()?.disabled).toBe(false);+ expect(kvCacheInput()?.checked).toBe(true);expect(host?.textContent).toContain('1 override');});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsxindex c07e536039..b1918e552b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx@@ -9,7 +9,7 @@ import { Badge, createListCollection, HStack, Stack } from '@chakra-ui/react';import {getDefaultGenerateSettings,getGenerationUiPolicy,- hasEnabledKrea2EditReferences,+ getKrea2EditLoraState,} from '@features/generation/core/baseGenerationPolicies';import { isPidMode, MAX_PID_STEPS, MIN_PID_STEPS } from '@features/generation/core/pid';import {@@ -73,9 +73,11 @@ 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);+const KREA2_REFERENCE_KV_CACHE_HELP_KEYS = {+ noEditReferences: 'widgets.generate.krea2ReferenceKvCacheNeedsEditReferences',+ noLora: 'widgets.generate.krea2ReferenceKvCacheNeedsLora',+ ready: 'widgets.generate.krea2ReferenceKvCacheHelp',+} as const;export const GenerateAdvancedFields = ({draft,@@ -85,11 +87,12 @@ export const GenerateAdvancedFields = ({}: GenerateAdvancedFieldsProps) => {const { t } = useTranslation();const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectAdvancedSettings);- const hasKrea2EditReferences = useExternalStoreSelector(- draft.subscribe,- draft.getSnapshot,- selectHasKrea2EditReferences+ // A string, so editing a reference or a concept re-renders this section only when the K/V cache starts or stops+ // applying.+ const krea2EditLoraState = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, (current: GenerateSettings) =>+ getKrea2EditLoraState(selectedModel, current));+ const krea2ReferenceKvCacheApplies = krea2EditLoraState === 'ready';const modelBase = selectedModel?.base;const modelDefaults = selectedModel ? getDefaultGenerateSettings(selectedModel) : null;const policy = getGenerationUiPolicy(selectedModel);@@ -164,8 +167,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,+ // The graph sends the switch only with edit references and a LoRA, so it is no override without them.+ policy.krea2ReferenceKvCacheVisible && krea2ReferenceKvCacheApplies && settings.krea2ReferenceKvCache,].filter(Boolean).length;const badges =@@ -405,13 +408,16 @@ export const GenerateAdvancedFields = ({{policy.krea2ReferenceKvCacheVisible ? (<Field- helpText={t('widgets.generate.krea2ReferenceKvCacheHelp')}+ disabled={!krea2ReferenceKvCacheApplies}+ helpText={t(KREA2_REFERENCE_KV_CACHE_HELP_KEYS[krea2EditLoraState])}hint="krea2ReferenceKvCache"label={t('widgets.generate.krea2ReferenceKvCache')}p="2">+ {/* Shown off while it is not sent; the stored value stays and is back once it applies again. */}<GenerateToggleSwitch- checked={settings.krea2ReferenceKvCache}+ checked={krea2ReferenceKvCacheApplies && settings.krea2ReferenceKvCache}+ disabled={!krea2ReferenceKvCacheApplies}label={t('widgets.generate.krea2ReferenceKvCache')}onCheckedChange={(checked) => onCommit({ krea2ReferenceKvCache: checked })}/>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsxindex 5bc8723152..b759f5aec9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx@@ -1,8 +1,8 @@import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';-import { Badge, Separator, Stack } from '@chakra-ui/react';-import { isReferenceImageSupported } from '@features/generation/core/baseGenerationPolicies';+import { Badge, Separator, Stack, Text } from '@chakra-ui/react';+import { getKrea2EditLoraState, isReferenceImageSupported } from '@features/generation/core/baseGenerationPolicies';import {type GenerateDraft,type GenerateSettingsUpdate,@@ -85,6 +85,12 @@ export const GenerateGuidanceSection = ({onCommit={onReferenceCommit}onCommitImmediate={onCommitImmediate}/>+ {/* Not blocking: the run works, but without an edit LoRA it only copies the references. */}+ {getKrea2EditLoraState(selectedModel, settings) === 'noLora' ? (+ <Text color="fg.warning" fontSize="xs" role="status" textWrap="pretty">+ {t('widgets.generate.krea2EditReferencesNeedLora')}+ </Text>+ ) : null}{referenceImagesSupported || referenceImageCount > 0 ? <Separator borderColor="bg.subtle" /> : null}<GenerateConceptsContentloraModels={loraModels}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 4b0359d97c..309cf4c978 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,10 +16,10 @@ import { GalleryPickerPopover } from '@features/gallery/picker';import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';import {createReferenceImageId,- getDefaultReferenceImageConfigs,getGenerationDimensions,getMaxReferenceImages,isReferenceImageSupported,+ withAddedReferenceImages,} from '@features/generation/core/baseGenerationPolicies';import { generatedImageToReferenceImage, getEffectiveReferenceImage } from '@features/generation/core/referenceImage';import { clampDimension, deriveAspectRatioId, moveReferenceImage } from '@features/generation/core/settings';@@ -73,23 +73,14 @@ 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,- ...configs.map((config, index) => ({- config,- id: ids[index] ?? createReferenceImageId(),- isEnabled: true,- })),- ],+ referenceImages: withAddedReferenceImages(+ selectedModel,+ models,+ currentSettings.referenceImages,+ images.slice(0, remaining).map((image, index) => ({ id: ids[index] ?? createReferenceImageId(), image }))+ ),};});},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 199beb8b22..ee7132fe50 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@@ -280,7 +280,7 @@ const ReferenceImageCardBase = ({/>) : config.type === 'krea2_reference_image' || config.type === 'krea2_edit_reference_image' ? (<>- <Krea2ReferenceModeControl config={config} disabled={!isEnabled} onChange={changeConfig} />+ <Krea2ReferenceModeControl config={config} onChange={changeConfig} />{config.type === 'krea2_reference_image' ? (<Krea2StyleReferenceControls config={config} disabled={!isEnabled} onChange={changeConfig} />) : null}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 a38ac9a92a..3098e930a0 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@@ -391,14 +391,15 @@ const KREA2_MODE_SEGMENTS = [{ 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. */+/**+ * Switches a Krea-2 reference between Style and Edit; the image stays and Style restarts at its default strength. It+ * stays live while the card is off, so switched-off cards can be turned into the set they will join before they run.+ */export const Krea2ReferenceModeControl = ({config,- disabled,onChange,}: {config: Krea2ReferenceConfig;- disabled: boolean;onChange: (config: Krea2ReferenceConfig) => void;}) => {const { t } = useTranslation();@@ -421,13 +422,7 @@ export const Krea2ReferenceModeControl = ({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.Root aria-label={t('widgets.generate.mode')} 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}>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.tsxindex bcc9fbfbdc..308bfec11b 100644--- 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.tsx@@ -11,29 +11,12 @@ import { userEvent } from 'vitest/browser';import { ReferenceImageCard } from './ReferenceImageCard';+// The real catalog, so a mistyped key shows up as the key and fails the label lookups below.const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({- fallbackLng: 'en',+ interpolation: { escapeValue: false },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',- },- },- },- },- },+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },});let host: HTMLDivElement | null = null;@@ -151,15 +134,16 @@ describe('Krea-2 reference mode switch', () => {expect(document.activeElement).toBe(modeRadio('Edit'));});- it('locks the mode while the reference is switched off', async () => {+ it('switches the mode of a switched-off reference, so it can join an edit set before it runs', async () => {await renderCard({ ...STYLE_REFERENCE, isEnabled: false });- expect(modeRadio('Edit')?.disabled).toBe(true);+ expect(modeRadio('Edit')?.disabled).toBe(false);- // The pointer cannot reach a disabled segment, so dispatch the click directly.- await act(() => modeRadio('Edit')?.closest('label')?.click());+ await clickMode('Edit');- expect(onPatch).not.toHaveBeenCalled();- expect(modeRadio('Style')?.checked).toBe(true);+ expect(onPatch).toHaveBeenLastCalledWith('pose', {+ config: { image, type: 'krea2_edit_reference_image' },+ });+ expect(modeRadio('Edit')?.checked).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.tsindex e06b830077..f2da0f3d32 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts@@ -83,7 +83,7 @@ describe('appendReferenceImage', () => {});});- it('adds a Krea-2 image as the style reference only when no other reference runs', () => {+ it('adds a Krea-2 image as the style reference only when no other reference runs, joining a lone untouched one to Edit', () => {const krea2Model: MainModelConfig = {base: 'krea-2',format: 'diffusers',@@ -105,7 +105,7 @@ describe('appendReferenceImage', () => {id: 'pose',isEnabled: true,};- const appendedType = (referenceImages: unknown[]) => {+ const appendedTypes = (referenceImages: unknown[]) => {const result = appendReferenceImage({generateValues: krea2Values(referenceImages),image,@@ -116,7 +116,7 @@ describe('appendReferenceImage', () => {throw new Error(`Expected appended, got ${result.status}`);}- return result.referenceImages.at(-1)?.config.type;+ return result.referenceImages.map(({ config }) => config.type);};const style = {@@ -125,11 +125,19 @@ describe('appendReferenceImage', () => {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');+ expect(appendedTypes([pose])).toEqual(['krea2_edit_reference_image', 'krea2_edit_reference_image']);+ // A second image turns a lone style reference the user never adjusted into an edit reference too.+ expect(appendedTypes([style])).toEqual(['krea2_edit_reference_image', 'krea2_edit_reference_image']);+ // One at another strength is meant for style: it stays, and validation reports the mix.+ expect(appendedTypes([{ ...style, config: { ...style.config, styleStrength: 1.5 } }])).toEqual([+ 'krea2_reference_image',+ 'krea2_edit_reference_image',+ ]);+ expect(appendedTypes([{ ...pose, isEnabled: false }])).toEqual([+ 'krea2_edit_reference_image',+ 'krea2_reference_image',+ ]);+ expect(appendedTypes([])).toEqual(['krea2_reference_image']);});it('returns unsupported when the model cannot take reference images', () => {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.tsindex ed54801688..455662af9d 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts@@ -5,10 +5,10 @@ import type { ModelConfig } from '@features/models';import {createReferenceImageId,generatedImageToReferenceImage,- getDefaultReferenceImageConfigs,getMaxReferenceImages,isReferenceImageSupported,isSupportedGenerateModel,+ withAddedReferenceImages,} from '@features/generation/settings';import { getCurrentGenerateValues } from './executeImageRecall';@@ -36,13 +36,10 @@ export const appendReferenceImage = ({return { status: 'full' };}- 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' };+ return {+ referenceImages: withAddedReferenceImages(currentValues.model, models, currentValues.referenceImages, [+ { id: createReferenceImageId(), image: generatedImageToReferenceImage(image) },+ ]),+ 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 7d47865b04..371d62d3c3 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -1265,7 +1265,7 @@ 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', () => {+ it('restores the Krea-2 reference K/V cache only from a record that has it', () => {const krea2: MainModelConfig = { base: 'krea-2', key: 'krea2-tuning', name: 'Krea-2', type: 'main' };const krea2Record = (extra: Record<string, unknown> = {}) => ({generation_mode: 'krea2_txt2img',@@ -1276,10 +1276,16 @@ describe('model-family tuning recall', () => {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(krea2Record({ krea2_reference_kv_cache: false }), krea2, 'all', { krea2ReferenceKvCache: true })?.values+ .krea2ReferenceKvCache+ ).toBe(false);+ // Graphs record the switch only when they send it (edit references and a LoRA), so a record without it leaves the+ // user's setting alone and does not count as a recalled field.+ const unrecorded = recall(krea2Record(), krea2, 'all', { krea2ReferenceKvCache: true });++ expect(unrecorded?.values.krea2ReferenceKvCache).toBe(true);+ expect(unrecorded?.fields).not.toContain('modelTuning');expect(recall({ krea2_reference_kv_cache: true }, qwenModel, 'all', { krea2ReferenceKvCache: false })?.values.krea2ReferenceKvCache@@ -1458,6 +1464,7 @@ describe('model-family tuning recall', () => {});it('restores Krea-2 edit references and the K/V cache from the metadata their graph recorded', () => {+ const krea2PoseLora: LoraModelConfig = { base: 'krea-2', key: 'krea2-pose', name: 'Krea-2 Pose', type: 'lora' };const krea2Diffusers: MainModelConfig = { ...krea2Model, format: 'diffusers' };const editReference = (imageName: string) => ({config: {@@ -1472,6 +1479,8 @@ describe('model-family tuning recall', () => {{...createValues({ model: krea2Diffusers, modelKey: krea2Diffusers.key }),krea2ReferenceKvCache: true,+ // The graph records the switch only while a LoRA reads the references.+ loras: [{ isEnabled: true, model: krea2PoseLora, weight: 1 }],referenceImages,},krea2Diffusers,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex b917ee0a7a..747f893bf9 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -564,14 +564,11 @@ 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- );+ // Recorded only when the switch was sent: with edit references and a LoRA. A record without it says nothing+ // about the switch, so the user's setting stays.+ const referenceKvCache = getBoolean(metadata, 'krea2_reference_kv_cache');- return referenceKvCache === undefined ? {} : { krea2ReferenceKvCache: referenceKvCache };+ return referenceKvCache === null ? {} : { 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 e62780b74a..e24921d43a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts@@ -538,6 +538,44 @@ describe('buildRecallParametersSettings', () => {).toEqual(['krea2_edit_reference_image', 'krea2_edit_reference_image', 'krea2_edit_reference_image']);});+ it('leaves a Krea-2 style card alone when the appended image does not fit the limit', () => {+ 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 card = (id: string, isEnabled: boolean) => ({+ config: {+ image: { original: { image: image(`${id}.png`) } },+ styleStrength: 1,+ type: 'krea2_reference_image' as const,+ },+ id,+ isEnabled,+ });+ // Three cards fill Krea-2's limit; only the first runs, as a style reference at its default strength.+ const currentValues = {+ ...krea2Values,+ referenceImages: [card('style', true), card('a', false), card('b', false)],+ };+ const result = buildRecallParametersSettings({+ currentValues,+ models: [krea2],+ parameters: { append: true, reference_images: [{ image: image('pose.png') }] },+ supportedModels: krea2Supported,+ vaeModels: [],+ });++ expect(result.values.referenceImages).toEqual(currentValues.referenceImages);+ expect(result.skipped).toContainEqual({ detail: '3', key: 'reference_images', reason: 'limit' });+ });+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 278fb2e867..312ef34495 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts@@ -18,7 +18,6 @@ import {getCompatibleReferenceImages,getDefaultGenerateSettings,getDefaultLoraWeight,- getDefaultReferenceImageConfigs,getGenerateModelSelectionResult,getGenerationUiPolicy,getMaxReferenceImages,@@ -39,6 +38,7 @@ import {MIN_REFINER_CFG_SCALE,MIN_REFINER_START,MIN_REFINER_STEPS,+ withAddedReferenceImages,} from '@features/generation/settings';import {@@ -600,19 +600,9 @@ export const buildRecallParametersSettings = ({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 : [];+ const isSupported = isReferenceImageSupported(values.model);- recalled.push(- ...getDefaultReferenceImageConfigs(- values.model,- models,- recalledImages.map((image) => ({ image, isEnabled: true })),- [...joining, ...recalled]- ).map(toReferenceImage)- );-- if (recalled.length > 0 && !isReferenceImageSupported(values.model)) {+ if (recalled.length + recalledImages.length > 0 && !isSupported) {if (ipAdapters?.length) {skip('ip_adapters', 'incompatible', values.model.name);}@@ -621,16 +611,31 @@ export const buildRecallParametersSettings = ({}}- const compatible = getCompatibleReferenceImages(recalled, values.model, models, joining);- let next = append ? [...values.referenceImages, ...compatible] : compatible;+ const kept = append ? values.referenceImages : [];+ // Adapters recorded for another family are re-targeted beside the list they join; the images are then added as any+ // new reference is, typed beside both, so a Krea-2 recall of several images is an edit set.+ const withAdapters = isSupported+ ? getCompatibleReferenceImages([...kept, ...recalled], values.model, models)+ : kept;+ const addedImages = isSupported ? recalledImages : [];+ const recalledCount = withAdapters.length + addedImages.length - kept.length;const limit = getMaxReferenceImages(values.model);- if (next.length > limit) {+ if (withAdapters.length + addedImages.length > limit) {skip('reference_images', 'limit', String(limit));- next = next.slice(0, limit);}- if (!append || compatible.length > 0) {+ // Images past the limit are cut before they are added, so one that never lands cannot turn a style card to Edit.+ const next = withAddedReferenceImages(+ values.model,+ models,+ withAdapters,+ addedImages+ .slice(0, Math.max(0, limit - withAdapters.length))+ .map((image) => ({ id: createReferenceImageId(), image }))+ ).slice(0, limit);++ if (!append || recalledCount > 0) {values = { ...values, referenceImages: next };fields.add('referenceImages');}