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
refactor(generation): add reference images through one Generation operation (#10311)
Josh Corbettc94de152ccb8
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex e4b979ea55..db6b5ae799 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -19,6 +19,7 @@ import type {} from './types';import {+ addReferenceImages,coerceSchedulerForGraph,getComponentPolicyContext,getComponentSectionPolicy,@@ -30,7 +31,7 @@ import {getGenerationValidationIssues,getGenerationValidationReasons,getCompatibleReferenceImages,- getMaxReferenceImages,+ getReferenceImageRoom,getReferenceImageUnavailableReason,getPromptPolicy,getSchedulerOptions,@@ -41,7 +42,8 @@ import {isLossyModelSwitch,isModelFromRepo,isSupportedGenerateModel,- withAddedReferenceImages,+ type NewReferenceImage,+ type ReferenceVisionComponents,} from './baseGenerationPolicies';import { getGenerationIssueFixPatch } from './generationIssues';import { SUPPORTED_GENERATE_BASES } from './supportedBases';@@ -126,6 +128,13 @@ const externalModel: GenerateModelConfig = {type: 'external_image_generator',};+const addTo = (+ model: GenerateModelConfig,+ models: readonly ComponentModelConfig[],+ referenceImages: GenerateReferenceImage[],+ additions: readonly NewReferenceImage[]+) => addReferenceImages({ additions, components: {}, mode: 'strict', model, models, referenceImages }).referenceImages;+seedArchitectureCapabilities();describe('architecture policy, read from the backend capability table', () => {@@ -922,7 +931,7 @@ describe('component policies', () => {getGenerationValidationReasons(model, createSettings(model, overrides));it('types a new Krea-2 reference as style only when it is the one running reference', () => {const typesAfterAdding = (count: number, referenceImages: GenerateSettings['referenceImages'] = []) =>- withAddedReferenceImages(+ addTo(krea2,[],referenceImages,@@ -994,7 +1003,7 @@ describe('component policies', () => {expect(isReferenceImageSupported(checkpoint, encoder('checkpoint'))).toBe(true);expect(isReferenceImageSupported(gguf, encoder('checkpoint'))).toBe(true);expect(isReferenceImageSupported(checkpoint, encoder('qwen3_vl_encoder'))).toBe(true);- expect(getMaxReferenceImages(checkpoint, encoder('checkpoint'))).toBe(4);+ expect(getReferenceImageRoom(checkpoint, encoder('checkpoint'), []).limit).toBe(4);expect(getReferenceImageUnavailableReason(checkpoint, encoder('checkpoint'))).toBeNull();});@@ -1013,19 +1022,24 @@ describe('component policies', () => {});it('derives the reference image limit from external provider capabilities', () => {- expect(getMaxReferenceImages(createModel('sdxl'))).toBe(5);- expect(getMaxReferenceImages(createModel('cogview4'))).toBe(0);+ expect(getReferenceImageRoom(createModel('sdxl'), {}, []).limit).toBe(5);+ expect(getReferenceImageRoom(createModel('cogview4'), {}, []).limit).toBe(0);expect(- getMaxReferenceImages({- ...externalModel,- capabilities: { ...externalModel.capabilities, max_reference_images: 14, supports_reference_images: true },- })+ getReferenceImageRoom(+ {+ ...externalModel,+ capabilities: { ...externalModel.capabilities, max_reference_images: 14, supports_reference_images: true },+ },+ {},+ []+ ).limit).toBe(14);expect(- getMaxReferenceImages({- ...externalModel,- capabilities: { ...externalModel.capabilities, supports_reference_images: true },- })+ getReferenceImageRoom(+ { ...externalModel, capabilities: { ...externalModel.capabilities, supports_reference_images: true } },+ {},+ []+ ).limit).toBe(5);});@@ -1075,6 +1089,133 @@ describe('component policies', () => {});});+describe('adding reference images', () => {+ const sdxl = createModel('sdxl');+ const krea2 = createModel('krea-2', { format: 'diffusers' });+ const qwen21 = createModel('qwen-image-2-1', { format: 'checkpoint' });+ const images = (...ids: string[]): NewReferenceImage[] => ids.map((id) => ({ id, image: referenceImage }));+ const adapter = (id: string, model: ComponentModelConfig = sdxlIpAdapter): GenerateReferenceImage => ({+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'full',+ model,+ type: 'ip_adapter',+ weight: 1,+ },+ id,+ isEnabled: true,+ });+ const style = (id: string): GenerateReferenceImage => ({+ config: { image: referenceImage, styleStrength: 1, type: 'krea2_reference_image' },+ id,+ isEnabled: true,+ });+ const edit = (id: string, isEnabled = true): GenerateReferenceImage => ({+ config: { image: referenceImage, type: 'krea2_edit_reference_image' },+ id,+ isEnabled,+ });+ const strict = (+ model: GenerateModelConfig,+ referenceImages: GenerateReferenceImage[],+ additions: NewReferenceImage[],+ components: ReferenceVisionComponents = {}+ ) => addReferenceImages({ additions, components, mode: 'strict', model, models: [sdxlIpAdapter], referenceImages });+ const keep = (+ model: GenerateModelConfig,+ referenceImages: GenerateReferenceImage[],+ additions: NewReferenceImage[],+ recalled: GenerateReferenceImage[] = []+ ) => addReferenceImages({ additions, mode: 'keep', model, models: [sdxlIpAdapter], recalled, referenceImages });++ it('places a user add in the free slots, or refuses it with a reason and leaves the list as it was', () => {+ const four = ['a', 'b', 'c', 'd'].map((id) => adapter(id));+ const partly = strict(sdxl, four, images('x', 'y', 'z'));++ expect(partly).toMatchObject({ added: 1, dropped: 2, limit: 5, refusal: null });+ expect(partly.referenceImages.map(({ id }) => id)).toEqual(['a', 'b', 'c', 'd', 'x']);++ const full = [...four, adapter('e')];++ expect(strict(sdxl, full, images('x'))).toEqual({+ added: 0,+ dropped: 1,+ limit: 5,+ referenceImages: full,+ refusal: 'full',+ unavailableReason: null,+ });+ expect(strict(createModel('cogview4'), [], images('x')).refusal).toBe('unsupported');+ expect(strict(qwen21, [], images('x'))).toMatchObject({ refusal: 'visionTower', unavailableReason: 'visionTower' });+ expect(+ strict(qwen21, [], images('x'), {+ qwen3VLEncoderModel: {+ base: 'any',+ format: 'gguf_quantized',+ key: 'qwen3-vl-8b-gguf',+ name: 'Qwen3-VL 8B',+ type: 'qwen3_vl_encoder',+ variant: 'qwen3_vl_8b',+ },+ })+ ).toMatchObject({+ added: 0,+ referenceImages: [],+ refusal: 'ggufVisionTower',+ unavailableReason: 'ggufVisionTower',+ });+ });++ it('keeps a recall whatever the encoder, retargets recalled adapters with the list, and cuts it to the limit', () => {+ // Validation flags the missing tower; recall keeps the references.+ expect(keep(qwen21, [], images('x'))).toMatchObject({+ added: 1,+ referenceImages: [{ config: { type: 'qwen_image_2_1_reference_image' }, id: 'x' }],+ refusal: null,+ });+ // Left as is, with nothing counted as dropped.+ const kept = [adapter('a')];++ expect(keep(createModel('cogview4'), kept, images('x'))).toEqual({+ added: 0,+ dropped: 0,+ limit: 0,+ referenceImages: kept,+ refusal: 'unsupported',+ unavailableReason: null,+ });++ const fluxAdapter = adapter('flux', { base: 'flux', key: 'flux-ip-adapter', name: 'FLUX IP', type: 'ip_adapter' });+ const recalled = keep(sdxl, [adapter('a'), adapter('b'), adapter('c')], images('x', 'y'), [fluxAdapter]);++ expect(recalled).toMatchObject({ added: 1, dropped: 1, limit: 5, refusal: null });+ expect(+ recalled.referenceImages.map(({ config, id }) => [id, config.type === 'ip_adapter' ? config.model?.key : null])+ ).toEqual([+ ['a', 'sdxl-ip-adapter'],+ ['b', 'sdxl-ip-adapter'],+ ['c', 'sdxl-ip-adapter'],+ ['flux', 'sdxl-ip-adapter'],+ ['x', 'sdxl-ip-adapter'],+ ]);+ });++ it('cuts additions past the limit before typing them, so a Krea-2 style reference stays when none lands', () => {+ const fullSet = [style('s'), edit('a', false), edit('b', false)];++ expect(keep(krea2, fullSet, images('x'))).toMatchObject({ dropped: 1, referenceImages: fullSet });+ expect(strict(krea2, fullSet, images('x'))).toMatchObject({ referenceImages: fullSet, refusal: 'full' });+ // A landing addition turns the lone style reference into edit.+ expect(strict(krea2, [style('s'), edit('a', false)], images('x', 'y')).referenceImages).toEqual([+ edit('s'),+ edit('a', false),+ edit('x'),+ ]);+ });+});+describe('Anima inpaint adapter slot', () => {const anima = createModel('anima');const inpaintAdapter: ComponentModelConfig = {diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 2501c982ba..09f519435d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -1727,11 +1727,13 @@ export const isReferenceImageSupported = ();};+export type ReferenceImageUnavailableReason = 'ggufVisionTower' | 'visionTower';+/** Why references are unavailable although the base takes them; null otherwise. */export const getReferenceImageUnavailableReason = (model: GenerateModelConfig | undefined,components: ReferenceVisionComponents = {}-): 'visionTower' | 'ggufVisionTower' | null => {+): ReferenceImageUnavailableReason | null => {if (!model || model.type === 'external_image_generator' || isReferenceImageSupported(model, components)) {return null;}@@ -1745,7 +1747,7 @@ export const getReferenceImageUnavailableReason = (: 'visionTower';};-export const getReferenceImageLimit = (model: GenerateModelConfig | undefined): number => {+const getReferenceImageLimit = (model: GenerateModelConfig | undefined): number => {if (!model || !takesReferenceImages(model)) {return 0;}@@ -1757,10 +1759,32 @@ export const getReferenceImageLimit = (model: GenerateModelConfig | undefined):return getArchitectureFeatures(model.base)?.max_reference_images ?? DEFAULT_REFERENCE_IMAGE_LIMIT;};-export const getMaxReferenceImages = (+export type ReferenceImageRefusal = 'full' | 'unsupported' | ReferenceImageUnavailableReason;++export interface ReferenceImageRoom {+ free: number;+ isSupported: boolean;+ limit: number;+ refusal: ReferenceImageRefusal | null;+ unavailableReason: ReferenceImageUnavailableReason | null;+}++export const getReferenceImageRoom = (model: GenerateModelConfig | undefined,- components: ReferenceVisionComponents = {}-): number => (isReferenceImageSupported(model, components) ? getReferenceImageLimit(model) : 0);+ components: ReferenceVisionComponents,+ referenceImages: readonly GenerateReferenceImage[]+): ReferenceImageRoom => {+ if (!isReferenceImageSupported(model, components)) {+ const unavailableReason = getReferenceImageUnavailableReason(model, components);++ return { free: 0, isSupported: false, limit: 0, refusal: unavailableReason ?? 'unsupported', unavailableReason };+ }++ const limit = getReferenceImageLimit(model);+ const free = Math.max(0, limit - referenceImages.length);++ return { free, isSupported: true, limit, refusal: free > 0 ? null : 'full', unavailableReason: null };+};const IP_ADAPTER_BASES: ReadonlySet<string> = new Set(['sd-1', 'sdxl', 'flux', 'anima']);@@ -1950,12 +1974,17 @@ const getLoneDefaultStyleReference = (: null;};-/** Every way of adding a reference goes through here. A changed strength marks a lone Krea-2 reference as style. */-export const withAddedReferenceImages = (+export interface NewReferenceImage {+ id: string;+ image: GenerateReferenceImageAsset | null;+}++// A lone first Krea-2 reference starts as style; the next addition turns it into edit unless its strength was tuned.+const withAddedReferenceImages = (model: GenerateModelConfig | undefined,models: readonly ReferenceModelCandidate[],referenceImages: GenerateReferenceImage[],- additions: readonly { id: string; image: GenerateReferenceImageAsset | null }[]+ additions: readonly NewReferenceImage[]): GenerateReferenceImage[] => {if (additions.length === 0) {return referenceImages;@@ -2097,6 +2126,71 @@ export const reconcileReferenceImagesWithModel = (};};+export type ReferenceImageAddRequest = {+ model: GenerateModelConfig | undefined;+ models: readonly ReferenceModelCandidate[];+ referenceImages: GenerateReferenceImage[];+ additions: readonly NewReferenceImage[];+} & (+ | { mode: 'strict'; components: ReferenceVisionComponents }+ | { mode: 'keep'; recalled?: readonly GenerateReferenceImage[] }+);++export interface ReferenceImageAddResult {+ referenceImages: GenerateReferenceImage[];+ added: number;+ dropped: number;+ limit: number;+ refusal: ReferenceImageRefusal | null;+ unavailableReason: ReferenceImageUnavailableReason | null;+}++/** `strict`: a user add, gated on vision components. `keep`: a recall; validation flags a missing encoder. */+export const addReferenceImages = (request: ReferenceImageAddRequest): ReferenceImageAddResult => {+ const { additions, model, models, referenceImages } = request;++ if (request.mode === 'strict') {+ const { free, isSupported, limit, refusal, unavailableReason } = getReferenceImageRoom(+ model,+ request.components,+ referenceImages+ );++ if (!isSupported) {+ return { added: 0, dropped: 0, limit, referenceImages, refusal, unavailableReason };+ }++ const fitting = additions.slice(0, free);++ return {+ added: fitting.length,+ dropped: additions.length - fitting.length,+ limit,+ referenceImages: withAddedReferenceImages(model, models, referenceImages, fitting),+ refusal,+ unavailableReason: null,+ };+ }++ if (!model || !takesReferenceImages(model)) {+ return { added: 0, dropped: 0, limit: 0, referenceImages, refusal: 'unsupported', unavailableReason: null };+ }++ const limit = getReferenceImageLimit(model);+ const joined = getCompatibleReferenceImages([...referenceImages, ...(request.recalled ?? [])], model, models);+ const fitting = additions.slice(0, Math.max(0, limit - joined.length));+ const placed = withAddedReferenceImages(model, models, joined, fitting).slice(0, limit);++ return {+ added: fitting.length,+ dropped: joined.length + additions.length - placed.length,+ limit,+ referenceImages: placed,+ refusal: null,+ unavailableReason: null,+ };+};+const getSettingsWithCompatibleModelSelections = (settings: GenerateSettings,model: GenerateModelConfig,diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.tsindex b0ca05d007..8b1b674a0d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts@@ -7,12 +7,11 @@ import type { GenerateComponentValueKey, SupportedGenerateBase } from './baseGenimport type { MainModelConfig, ModelIdentifierConfig, VaeModelConfig } from './types';import {+ addReferenceImages,getComponentSectionPolicy,getGenerationValidationReasons,isLoraSupported,- isReferenceImageSupported,SUPPORTED_GENERATE_BASES,- withAddedReferenceImages,} from './baseGenerationPolicies';import { compileCanvasGraph } from './canvas/compileCanvasGraph';import { compileGenerateGraph, GRAPH_BUILDERS } from './graph';@@ -43,22 +42,22 @@ const compileForShape = (...satisfiedSettingsFor(base, shape),projectSettings: { useCpuNoise: true, useNsfwChecker: false, useWatermark: false },};- const settings = isReferenceImageSupported(model, satisfied)- ? {- ...satisfied,- referenceImages: withAddedReferenceImages(- model,- [{ base, key: `${base}-ip-adapter`, name: `${base} IP Adapter`, type: 'ip_adapter' }],- [],- [- {- id: 'coverage-reference',- image: { original: { image: { height: 512, image_name: 'reference.png', width: 512 } } },- },- ]- ),- }- : satisfied;+ const settings = {+ ...satisfied,+ referenceImages: addReferenceImages({+ additions: [+ {+ id: 'coverage-reference',+ image: { original: { image: { height: 512, image_name: 'reference.png', width: 512 } } },+ },+ ],+ components: satisfied,+ mode: 'strict',+ model,+ models: [{ base, key: `${base}-ip-adapter`, name: `${base} IP Adapter`, type: 'ip_adapter' }],+ referenceImages: satisfied.referenceImages,+ }).referenceImages,+ };expect(getGenerationValidationReasons(model, settings), `${base}/${shape.label} is not satisfiable`).toEqual([]);diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.tsindex 0d0c02feda..0fbccd3c93 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts@@ -20,6 +20,7 @@ import type {} from './types';import {+ addReferenceImages,GENERATE_COMPONENT_VALUE_KEYS,getComponentSectionPolicy,getDefaultGenerateSettings,@@ -29,7 +30,6 @@ import {isLoraSupported,isReferenceImageSupported,SUPPORTED_GENERATE_BASES,- withAddedReferenceImages,} from './baseGenerationPolicies';import { getIsPidSupportedBase } from './pid';import { clampDimension, deriveAspectRatioId } from './settings';@@ -396,14 +396,16 @@ const recallReferenceImagesFor = (model: MainModelConfig, settings: GenerateSett];}- return isReferenceImageSupported(model, settings)- ? withAddedReferenceImages(- model,- [{ base: model.base, key: `${model.base}-ip-adapter`, name: `${model.base} IP Adapter`, type: 'ip_adapter' }],- [],- [{ id: 'reference', image: RECALL_REFERENCE_IMAGE }]- )- : [];+ return addReferenceImages({+ additions: [{ id: 'reference', image: RECALL_REFERENCE_IMAGE }],+ components: settings,+ mode: 'strict',+ model,+ models: [+ { base: model.base, key: `${model.base}-ip-adapter`, name: `${model.base} IP Adapter`, type: 'ip_adapter' },+ ],+ referenceImages: [],+ }).referenceImages;};/** Everything filled and tuned; the size is off default and not square (Z-Image PiD is native, others fit). */diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts b/invokeai/frontend/webv2/src/features/generation/core/graphExport.tsindex 349fde1ad3..ee566926a2 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts@@ -17,21 +17,19 @@ import type { ComponentModelConfig, GenerateModelConfig, GenerateWidgetValues }import { resetArchitectureCapabilities, setArchitectureCapabilities } from './architectureCapabilities';import {+ addReferenceImages,coerceSchedulerForGraph,GENERATE_COMPONENT_VALUE_KEYS,getComponentPolicyContext,getComponentSectionPolicy,getDefaultGenerateSettings,getGenerateModelSelectionResult,- getReferenceImageUnavailableReason,getSchedulerOptions,isArchitectureDescribed,isGenerateModelSelectable,isLoraSupported,- isReferenceImageSupported,getRecallDefaultVae,resolveModelDefaultVae,- withAddedReferenceImages,} from './baseGenerationPolicies';import { compileCanvasGraph } from './canvas/compileCanvasGraph';import {@@ -323,30 +321,34 @@ const withReferenceImages = (}const { model } = values;+ const { dropped, limit, referenceImages, refusal, unavailableReason } = addReferenceImages({+ additions: input.referenceImages.map((imageName, index) => ({+ id: `reference_image_${index + 1}`,+ // Cases name images only; the output size stands in for dimensions that reach metadata, not inference.+ image: { original: { image: { height: input.height, image_name: imageName, width: input.width } } },+ })),+ components: values,+ mode: 'strict',+ model,+ models,+ referenceImages: values.referenceImages,+ });- if (!isReferenceImageSupported(model, values)) {+ if (refusal && refusal !== 'full') {throw new Error(`reference_images: ${model.name} takes no reference images${- getReferenceImageUnavailableReason(model, values)+ unavailableReason? ' without a vision tower (a Diffusers model, a safetensors Qwen3-VL 8B encoder, or a GGUF one with its Vision Tower)': ''}.`);}- return {- ...values,- referenceImages: withAddedReferenceImages(- model,- models,- values.referenceImages,- input.referenceImages.map((imageName, index) => ({- id: `reference_image_${index + 1}`,- // Cases name images only; the output size stands in for dimensions that reach metadata, not inference.- image: { original: { image: { height: input.height, image_name: imageName, width: input.width } } },- }))- ),- };+ if (dropped > 0) {+ throw new Error(`reference_images: ${model.name} takes at most ${limit} reference image${limit === 1 ? '' : 's'}.`);+ }++ return { ...values, referenceImages };};/** The widget reconciles after every commit; reconciliation can pick a FLUX.2 component source. */diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex 47743b3dd2..61a2d63567 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -377,17 +377,21 @@ const isGenerateLora = (value: unknown): value is GenerateLora =>export const DEFAULT_REFERENCE_IMAGE_LIMIT = 5;-const REFERENCE_IMAGE_CONFIG_TYPES = new Set([- 'external_reference_image',- 'flux2_reference_image',- 'flux_kontext_reference_image',- 'flux_redux',- 'ip_adapter',- 'krea2_edit_reference_image',- 'krea2_reference_image',- 'qwen_image_reference_image',- 'qwen_image_2_1_reference_image',-]);+// Keyed by kind, so a new kind fails to compile until the reader below handles it.+const REFERENCE_IMAGE_CONFIG_TYPES: Record<GenerateReferenceImageConfig['type'], true> = {+ external_reference_image: true,+ flux2_reference_image: true,+ flux_kontext_reference_image: true,+ flux_redux: true,+ ip_adapter: true,+ krea2_edit_reference_image: true,+ krea2_reference_image: true,+ qwen_image_reference_image: true,+ qwen_image_2_1_reference_image: true,+};++const isReferenceImageConfigType = (value: unknown): value is GenerateReferenceImageConfig['type'] =>+ typeof value === 'string' && Object.hasOwn(REFERENCE_IMAGE_CONFIG_TYPES, value);const isClipVisionModel = (value: unknown): value is 'ViT-H' | 'ViT-G' | 'ViT-L' =>value === 'ViT-H' || value === 'ViT-G' || value === 'ViT-L';@@ -408,7 +412,7 @@ const normalizeReferenceImageAsset = (value: unknown): GenerateReferenceImageAssvalue === null ? null : normalizeCroppableImage(value);const normalizeReferenceImageConfig = (value: unknown): GenerateReferenceImageConfig | null => {- if (!isRecord(value) || typeof value.type !== 'string' || !REFERENCE_IMAGE_CONFIG_TYPES.has(value.type)) {+ if (!isRecord(value) || !isReferenceImageConfigType(value.type)) {return null;}@@ -462,8 +466,6 @@ const normalizeReferenceImageConfig = (value: unknown): GenerateReferenceImageCoweight: hasFiniteNumber(value, 'weight') ? (value.weight as number) : 1,};}-- return null;};/** Long enough for a descriptive label, short enough to stay one line in metadata and recall notices. */diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex 5c8ff332fd..23c849c142 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -52,7 +52,7 @@ export {createReferenceImageId,getCompatibleReferenceImages,getDefaultGenerateSettings,- withAddedReferenceImages,+ addReferenceImages,getGenerateModelSelectionResult,isComponentCompatibleWithModel,getDimensionGrid,@@ -60,9 +60,8 @@ export {getGenerateInvocationIssues,getGenerationModelAvailabilityReasons,getGenerationUiPolicy,- getMaxReferenceImages,getPromptHistoryRecallPatch,- getReferenceImageLimit,+ getReferenceImageRoom,getSchedulerOptions,getSettingsWithModelDefaults,getRecallDefaultVae,@@ -71,7 +70,6 @@ export {isGenerateModelSelectable,isKnownScheduler,isLossyModelSwitch,- isReferenceImageSupported,isSupportedGenerateModel,takesReferenceImages,NO_GENERATE_MODEL_ISSUE,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 4cb3ce60e2..3f65a6f455 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@@ -17,13 +17,11 @@ import { galleryImages, toGalleryItemKey } from '@features/gallery';import { GalleryPickerPopover } from '@features/gallery/picker';import { isGalleryImageDragData, useGalleryImageDroppable } from '@features/gallery/utility';import {+ addReferenceImages,createReferenceImageId,getGenerationDimensions,- getMaxReferenceImages,- getReferenceImageUnavailableReason,- isReferenceImageSupported,+ getReferenceImageRoom,reconcileReferenceImagesWithModel,- withAddedReferenceImages,} from '@features/generation/core/baseGenerationPolicies';import {generatedImageToReferenceImage,@@ -93,11 +91,13 @@ export const GenerateReferenceImagesContent = ({const { gallery, models: uiModels, notifications, project, settings } = useGenerationUi();const { openManager, readCatalog } = uiModels;const openModelManager = useCallback((modelType: string) => openManager({ modelType }), [openManager]);- const isSupported = isReferenceImageSupported(selectedModel, visionComponents);- const unavailableReason = getReferenceImageUnavailableReason(selectedModel, visionComponents);- const maxReferenceImages = getMaxReferenceImages(selectedModel, visionComponents);+ const {+ free: freeSlots,+ isSupported,+ limit: maxReferenceImages,+ unavailableReason,+ } = getReferenceImageRoom(selectedModel, visionComponents, referenceImages);const referenceImageCount = referenceImages.length;- const freeSlots = Math.max(0, maxReferenceImages - referenceImageCount);const canAdd = freeSlots > 0;// Still a target when full, so a drop there says why nothing was added instead of doing nothing.const { acceptsActiveDrag, isOver, setNodeRef } = useGalleryImageDroppable({@@ -114,29 +114,23 @@ export const GenerateReferenceImagesContent = ({const appendReferenceImages = useCallback((images: GenerateReferenceImageAsset[]): number => {// Mint IDs outside replayed updaters so draft and flushed identities match.- const ids = images.map(() => createReferenceImageId());+ const additions = images.map((image) => ({ id: createReferenceImageId(), image }));let added = 0;// The commit applies the update at once (a later flush may replay it), so `added` is set when this returns.onCommit((currentSettings) => {- const remaining =- getMaxReferenceImages(selectedModel, currentSettings) - currentSettings.referenceImages.length;-- added = Math.max(0, Math.min(remaining, images.length));-- if (added === 0) {- return currentSettings;- }-- return {- ...currentSettings,- referenceImages: withAddedReferenceImages(- selectedModel,- models,- currentSettings.referenceImages,- images.slice(0, remaining).map((image, index) => ({ id: ids[index] ?? createReferenceImageId(), image }))- ),- };+ const result = addReferenceImages({+ additions,+ components: currentSettings,+ mode: 'strict',+ model: selectedModel,+ models,+ referenceImages: currentSettings.referenceImages,+ });++ added = result.added;++ return added === 0 ? currentSettings : { ...currentSettings, referenceImages: result.referenceImages };});return added;@@ -275,9 +269,9 @@ export const GenerateReferenceImagesContent = ({)),mode: 'multiple',- remaining: { image: Math.max(0, maxReferenceImages - referenceImageCount) },+ remaining: { image: freeSlots },}),- [maxReferenceImages, referenceImageCount, referenceImages]+ [freeSlots, referenceImages]);const handlePick = useCallback(diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsxindex a530a7da51..6cafd2890b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsx@@ -9,7 +9,7 @@ import { seedArchitectureCapabilities } from '@features/generation/core/architecimport {getDefaultGenerateSettings,getGenerateInvocationIssues,- getMaxReferenceImages,+ getReferenceImageRoom,} from '@features/generation/core/baseGenerationPolicies';import { type GenerationUiAdapter, GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';import { GenerateIssuesProvider } from '@features/generation/ui/shared/GenerateIssues';@@ -49,7 +49,7 @@ await i18n.use(initReactI18next).init({seedArchitectureCapabilities();const SDXL: GenerateModelConfig = { base: 'sdxl', format: 'diffusers', key: 'sdxl', name: 'SDXL', type: 'main' };-const max = () => getMaxReferenceImages(SDXL);+const max = () => getReferenceImageRoom(SDXL, {}, []).limit;const NO_MODELS: [] = [];const NO_VISION_COMPONENTS = {};const reference = (id: string): GenerateReferenceImage => ({diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.tsindex f2da0f3d32..1aca3e0747 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts@@ -2,7 +2,7 @@ import type { MainModelConfig } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';-import { getDefaultGenerateSettings, getMaxReferenceImages } from '@features/generation/settings';+import { getDefaultGenerateSettings } from '@features/generation/settings';import { describe, expect, it } from 'vitest';import { appendReferenceImage, type AppendReferenceImageResult } from './appendReferenceImage';@@ -43,27 +43,9 @@ describe('appendReferenceImage', () => {});});- it('preserves existing reference images and appends after them', () => {- const first = appendReferenceImage({ generateValues: generateValuesFor(), image, models });- if (first.status !== 'appended') {- throw new Error('Expected first append to succeed');- }-- const second = appendReferenceImage({- generateValues: generateValuesFor(first.referenceImages as unknown[]),- image: { ...image, imageName: 'second.png' },- models,- });-- if (second.status !== 'appended') {- throw new Error('Expected second append to succeed');- }- expect(second.referenceImages).toHaveLength(2);- expect(second.referenceImages[0]).toEqual(first.referenceImages[0]);- });-it('returns full once the model reference image limit is reached', () => {- const limit = getMaxReferenceImages(sd1Model);+ // SD 1's served limit.+ const limit = 5;let referenceImages: unknown[] = [];for (let index = 0; index < limit; index += 1) {@@ -83,63 +65,6 @@ describe('appendReferenceImage', () => {});});- 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',- 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 appendedTypes = (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.map(({ config }) => config.type);- };-- const style = {- config: { image: pose.config.image, styleStrength: 1, type: 'krea2_reference_image' },- id: 'style',- isEnabled: true,- };-- 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', () => {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 40edffb7eb..df737c8703 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts@@ -3,12 +3,10 @@ import type { GenerateWidgetValues } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import {+ addReferenceImages,createReferenceImageId,generatedImageToReferenceImage,- getMaxReferenceImages,- isReferenceImageSupported,isSupportedGenerateModel,- withAddedReferenceImages,} from '@features/generation/settings';import { getCurrentGenerateValues } from './executeImageRecall';@@ -29,17 +27,22 @@ export const appendReferenceImage = ({const supportedModels = models.filter(isSupportedGenerateModel);const currentValues = getCurrentGenerateValues({ generateValues, supportedModels });- if (!currentValues || !isReferenceImageSupported(currentValues.model, currentValues)) {+ if (!currentValues) {return { status: 'unsupported' };}- if (currentValues.referenceImages.length >= getMaxReferenceImages(currentValues.model, currentValues)) {- return { status: 'full' };++ const { referenceImages, refusal } = addReferenceImages({+ additions: [{ id: createReferenceImageId(), image: generatedImageToReferenceImage(image) }],+ components: currentValues,+ mode: 'strict',+ model: currentValues.model,+ models,+ referenceImages: currentValues.referenceImages,+ });++ if (refusal) {+ return { status: refusal === 'full' ? 'full' : 'unsupported' };}- return {- referenceImages: withAddedReferenceImages(currentValues.model, models, currentValues.referenceImages, [- { id: createReferenceImageId(), image: generatedImageToReferenceImage(image) },- ]),- status: 'appended',- };+ return { referenceImages, status: 'appended' };};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.tsindex 78c053fdbe..61bef52934 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts@@ -2,12 +2,7 @@ import type { ComponentModelConfig, GenerateModelConfig, VaeModelConfig } from 'import type { TFunction } from 'i18next';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';-import {- getDefaultGenerateSettings,- getMaxReferenceImages,- isSupportedGenerateModel,- isVaeModelConfig,-} from '@features/generation/settings';+import { getDefaultGenerateSettings, isSupportedGenerateModel, isVaeModelConfig } from '@features/generation/settings';import i18n from 'i18next';import { beforeAll, describe, expect, it } from 'vitest';@@ -516,7 +511,8 @@ describe('buildRecallParametersSettings', () => {appended.values.referenceImages.map((reference) => reference.config.image?.original.image.image_name)).toEqual(['existing.png', 'new.png']);- const limit = getMaxReferenceImages(sdxl as GenerateModelConfig);+ // SDXL's served limit.+ const limit = 5;const overLimit = build(current, {append: true,reference_images: Array.from({ length: limit }, (_, index) => ({ image: image(`extra-${index}.png`) })),@@ -530,38 +526,6 @@ describe('buildRecallParametersSettings', () => {expect(untouched.values.referenceImages).toEqual(current.referenceImages);});- it('keeps recalled Qwen-Image-2.1 references whichever encoder is selected, leaving the tower check to validation', () => {- const qwen21 = makeModel('q21-main', 'qwen-image-2-1', 'main', { format: 'checkpoint' });- const q21Supported = [qwen21].filter(isSupportedGenerateModel) as GenerateModelConfig[];- const values = getCurrentGenerateValues({- generateValues: { modelKey: qwen21.key },- supportedModels: q21Supported,- });-- if (!values) {- throw new Error('fixture model is not a supported Generate model');- }-- const encoder = (format: string) => makeModel('enc', 'any', 'qwen3_vl_encoder', { format, variant: 'qwen3_vl_8b' });- const recall = (qwen3VLEncoderModel: ComponentModelConfig | null) =>- buildRecallParametersSettings({- currentValues: { ...values, qwen3VLEncoderModel },- models: [qwen21],- parameters: { reference_images: [{ image: image('edit.png') }] },- supportedModels: q21Supported,- vaeModels: [],- });-- for (const selected of [encoder('checkpoint'), encoder('gguf_quantized'), null]) {- const result = recall(selected);-- expect(result.values.referenceImages.map((reference) => reference.config.type)).toEqual([- 'qwen_image_2_1_reference_image',- ]);- expect(result.skipped).toEqual([]);- }- });-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[];@@ -605,44 +569,6 @@ 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 02fb299a65..a7c8078662 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts@@ -13,15 +13,14 @@ import type {import type { TFunction } from 'i18next';import {+ addReferenceImages,cloneGenerateWidgetValues,createReferenceImageId,DEFAULT_LORA_WEIGHT_CONFIG,- getCompatibleReferenceImages,getDefaultGenerateSettings,getDefaultLoraWeight,getGenerateModelSelectionResult,getGenerationUiPolicy,- getReferenceImageLimit,getSettingsWithModelDefaults,hasArchitectureCapabilities,isLoraCompatibleWithModel,@@ -29,7 +28,6 @@ import {isMainModelConfig,isRefinerModel,isRefinerSupported,- takesReferenceImages,isVaeCompatibleWithGenerateModel,MAX_REFINER_AESTHETIC_SCORE,MAX_REFINER_START,@@ -39,7 +37,6 @@ import {MIN_REFINER_STEPS,getRecallDefaultVae,resolveModelDefaultVae,- withAddedReferenceImages,} from '@features/generation/settings';import {@@ -601,10 +598,18 @@ export const buildRecallParametersSettings = ({recalledImages.push(image);}- // The base alone decides: an encoder without a vision tower is flagged by validation, not recalled away.- const isSupported = takesReferenceImages(values.model);+ // Typed as one set, so a multi-image Krea-2 recall is an edit set.+ const placed = addReferenceImages({+ additions: recalledImages.map((image) => ({ id: createReferenceImageId(), image })),+ mode: 'keep',+ model: values.model,+ models,+ recalled,+ referenceImages: append ? values.referenceImages : [],+ });+ const recalledCount = placed.refusal ? 0 : recalled.length + recalledImages.length;- if (recalled.length + recalledImages.length > 0 && !isSupported) {+ if (placed.refusal && recalled.length + recalledImages.length > 0) {if (ipAdapters?.length) {skip('ip_adapters', 'incompatible', values.model.name);}@@ -613,32 +618,12 @@ export const buildRecallParametersSettings = ({}}- 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 = getReferenceImageLimit(values.model);-- if (withAdapters.length + addedImages.length > limit) {- skip('reference_images', 'limit', String(limit));+ if (placed.dropped > 0) {+ skip('reference_images', 'limit', String(placed.limit));}- // 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 };+ values = { ...values, referenceImages: placed.referenceImages };fields.add('referenceImages');}}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex ecb841be5a..09b6fa70a6 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -39,7 +39,7 @@ import {} from '@features/gallery/queries';import { setPendingPromptTemplateDraft } from '@features/generation/react';import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';-import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';+import { getReferenceImageRoom, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';import { submitUtilityGraph, type UtilityGraphSubmission, UtilityQueueError } from '@features/queue/utility';import { copyImage } from '@platform/browser/clipboard';@@ -264,7 +264,7 @@ export const useImageActions = ({return {canUseAsReferenceImage: Boolean(- values && values.referenceImages.length < getMaxReferenceImages(values.model, values)+ values && getReferenceImageRoom(values.model, values, values.referenceImages).free > 0),currentGenerateValues: values,};