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(webv2): preserve reference image crops
joshistoast63b33c6c4a6b
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 090b2d4f4f..6dc538670a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -1903,7 +1903,13 @@ describe('createCanvasEngine', () => {negativePrompt: 'negative',opacity: 0.8,positivePrompt: 'positive',- referenceImages: [{ config: { image: null, type: 'flux2_reference_image' }, id: 'reference', isEnabled: true }],+ referenceImages: [+ {+ config: { image: null, imageInfluence: 'highest', model: null, type: 'flux_redux' },+ id: 'reference',+ isEnabled: true,+ },+ ],transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'regional_guidance',};diff --git a/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.tsindex d53f49d8e8..53d2578fa4 100644--- a/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/baseGenerationPolicies.test.ts@@ -84,13 +84,7 @@ const sdxlIpAdapter: ComponentModelConfig = {type: 'ip_adapter',};const referenceImage = {- height: 768,- imageName: 'reference.png',- imageUrl: '/api/v1/images/i/reference.png/full',- queuedAt: '2026-01-01T00:00:00.000Z',- sourceQueueItemId: 'backend-gallery',- thumbnailUrl: '/api/v1/images/i/reference.png/thumbnail',- width: 512,+ original: { image: { height: 768, image_name: 'reference.png', width: 512 } },};const externalModel: GenerateModelConfig = {base: 'external',diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.test.tsindex 70747801e8..96e67feb94 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts@@ -109,13 +109,7 @@ const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateS});const refImage = {- height: 768,- imageName: 'reference.png',- imageUrl: '/api/v1/images/i/reference.png/full',- queuedAt: '2026-01-01T00:00:00.000Z',- sourceQueueItemId: 'backend-gallery',- thumbnailUrl: '/api/v1/images/i/reference.png/thumbnail',- width: 512,+ original: { image: { height: 768, image_name: 'reference.png', width: 512 } },};const compile = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}) =>@@ -377,6 +371,44 @@ describe('compileGenerateGraph', () => {expect(getEdge(graph, 'denoise_latents', 'ip_adapter')?.source.node_id).toContain('ip_adapter_collector');});+ it('generates from the crop while serializing complete original and crop metadata', () => {+ const croppedReferenceImage = {+ crop: {+ box: { height: 256, width: 320, x: 40, y: 50 },+ image: { height: 256, image_name: 'reference-crop.png', width: 320 },+ ratio: null,+ },+ original: { image: { height: 768, image_name: 'reference-original.png', width: 512 } },+ };+ const graph = compile(sd1Model, {+ referenceImages: [+ {+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: croppedReferenceImage,+ method: 'full',+ model: sd1IpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ id: 'cropped-ref',+ isEnabled: true,+ },+ ],+ });+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(getNodeByType(graph, 'ip_adapter')?.image).toEqual({ image_name: 'reference-crop.png' });+ expect(metadata?.ref_images).toMatchObject([+ {+ config: { image: croppedReferenceImage },+ id: 'cropped-ref',+ isEnabled: true,+ },+ ]);+ });+it('wires FLUX Redux reference images into denoise', () => {const graph = compile(fluxModel, {clipEmbedModel: clipEmbed,diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.tsindex 95054d3254..a07b9f82a1 100644--- a/invokeai/frontend/webv2/src/workbench/generation/graph.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.ts@@ -42,6 +42,7 @@ import {toModelIdentifier,toGraphContract,} from './graphBuilder';+import { getEffectiveReferenceImage } from './referenceImage';import { SEED_MAX } from './settings';const getCompatibleComponentSource = (@@ -52,7 +53,9 @@ const getCompatibleComponentSource = (const getCompatibleVae = (settings: GenerateSettings, bases: readonly string[]) =>settings.vae && isVaeForBases(bases)(settings.vae) ? settings.vae : null;-const toImageField = (image: GenerateReferenceImageAsset) => ({ image_name: image.imageName });+const toImageField = (image: GenerateReferenceImageAsset) => ({+ image_name: getEffectiveReferenceImage(image).image_name,+});const getEnabledReferenceImages = <T extends GenerateReferenceImageConfig['type']>(settings: GenerateSettings,diff --git a/invokeai/frontend/webv2/src/workbench/generation/referenceImage.test.ts b/invokeai/frontend/webv2/src/workbench/generation/referenceImage.test.tsnew file mode 100644index 0000000000..f6460bd4fb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/referenceImage.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from 'vitest';++import {+ applyReferenceImageCrop,+ clearReferenceImageCrop,+ cloneCroppableImage,+ FULL_REFERENCE_IMAGE_CROP_BOX,+ generatedImageToReferenceImage,+ getEffectiveReferenceImage,+ getReferenceImageCropBoxPct,+ isCanonicalCroppableImage,+ normalizeCroppableImage,+ resolveReferenceImageCrop,+} from './referenceImage';++const original = { height: 768, image_name: 'original.png', width: 1024 };+const crop = {+ box: { height: 400, width: 600, x: 100, y: 80 },+ image: { height: 400, image_name: 'crop.png', width: 600 },+ ratio: null,+};++describe('reference images', () => {+ it('normalizes canonical uncropped and cropped assets', () => {+ expect(normalizeCroppableImage({ original: { image: original } })).toEqual({ original: { image: original } });+ expect(normalizeCroppableImage({ crop, original: { image: original } })).toEqual({+ crop,+ original: { image: original },+ });+ });++ it('migrates pre-crop legacy and former flat webv2 assets', () => {+ expect(isCanonicalCroppableImage(original)).toBe(false);+ expect(normalizeCroppableImage(original)).toEqual({ original: { image: original } });+ expect(+ normalizeCroppableImage({+ height: 512,+ imageName: 'webv2.png',+ imageUrl: '/full',+ queuedAt: 'now',+ sourceQueueItemId: 'queue',+ thumbnailUrl: '/thumbnail',+ width: 640,+ })+ ).toEqual({ original: { image: { height: 512, image_name: 'webv2.png', width: 640 } } });+ expect(isCanonicalCroppableImage({ original: { image: original } })).toBe(true);+ expect(+ isCanonicalCroppableImage({+ original: { image: { height: 768, imageName: 'not-canonical.png', width: 1024 } },+ })+ ).toBe(false);+ });++ it('converts gallery results to uncropped canonical assets', () => {+ expect(generatedImageToReferenceImage({ height: 300, imageName: 'upload.png', width: 400 })).toEqual({+ original: { image: { height: 300, image_name: 'upload.png', width: 400 } },+ });+ });++ it('uses a crop when present and preserves nested provenance when cloning', () => {+ const asset = { crop, original: { image: original } };+ const cloned = cloneCroppableImage(asset);++ expect(getEffectiveReferenceImage(asset)).toEqual(crop.image);+ expect(cloned).toEqual(asset);+ expect(cloned).not.toBe(asset);+ expect(cloned.original).not.toBe(asset.original);+ expect(cloned.crop).not.toBe(asset.crop);+ expect(cloned.crop?.box).not.toBe(asset.crop.box);+ });++ it('applies, replaces, and clears crops without replacing the original', () => {+ const uncropped = { original: { image: original } };+ const cropped = applyReferenceImageCrop(uncropped, crop);+ const replacement = applyReferenceImageCrop(cropped, {+ box: { height: 256, width: 256, x: 0, y: 0 },+ image: { height: 256, image_name: 'replacement.png', width: 256 },+ ratio: 1,+ });++ expect(cropped.original.image).toEqual(original);+ expect(replacement.original.image).toEqual(original);+ expect(getEffectiveReferenceImage(replacement).image_name).toBe('replacement.png');+ expect(clearReferenceImageCrop(replacement)).toEqual(uncropped);+ });++ it('initializes the crop editor from the saved pixel box', () => {+ expect(getReferenceImageCropBoxPct({ crop, original: { image: original } })).toEqual({+ height: (400 / 768) * 100,+ width: (600 / 1024) * 100,+ x: (100 / 1024) * 100,+ y: (80 / 768) * 100,+ });+ });++ it('resolves a full-image edit by clearing the crop', () => {+ expect(+ resolveReferenceImageCrop({ crop, original: { image: original } }, FULL_REFERENCE_IMAGE_CROP_BOX, null)+ ).toEqual({ original: { image: original } });+ });++ it('records an uploaded crop against the unchanged original', () => {+ const uploadedCrop = { height: 384, image_name: 'uploaded-crop.png', width: 512 };+ const result = resolveReferenceImageCrop(+ { crop, original: { image: original } },+ { height: 50, width: 50, x: 25, y: 10 },+ uploadedCrop+ );++ expect(result).toEqual({+ crop: {+ box: { height: 384, width: 512, x: 256, y: 77 },+ image: uploadedCrop,+ ratio: null,+ },+ original: { image: original },+ });+ expect(getEffectiveReferenceImage(result)).toEqual(uploadedCrop);+ });++ it('rejects malformed originals and crops', () => {+ expect(+ normalizeCroppableImage({ original: { image: { image_name: 'bad.png', width: 0, height: 10 } } })+ ).toBeNull();+ expect(+ normalizeCroppableImage({+ crop: { ...crop, box: { ...crop.box, x: -1 } },+ original: { image: original },+ })+ ).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/referenceImage.ts b/invokeai/frontend/webv2/src/workbench/generation/referenceImage.tsnew file mode 100644index 0000000000..c9f61390eb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/referenceImage.ts@@ -0,0 +1,200 @@+import type { GeneratedImageContract } from '@workbench/types';++import { getImageFullUrl, getImageThumbnailUrl } from '@workbench/gallery/api';++import type { CroppableImageWithDims, ImageWithDims } from './types';++const isRecord = (value: unknown): value is Record<string, unknown> =>+ Boolean(value) && typeof value === 'object' && !Array.isArray(value);++const isPositiveFiniteNumber = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value) && value > 0;++export const isImageWithDims = (value: unknown): value is ImageWithDims =>+ isRecord(value) &&+ typeof value.image_name === 'string' &&+ value.image_name.length > 0 &&+ isPositiveFiniteNumber(value.width) &&+ isPositiveFiniteNumber(value.height);++const cloneImageWithDims = (image: ImageWithDims): ImageWithDims => ({ ...image });++const normalizeFlatImage = (value: unknown): ImageWithDims | null => {+ if (isImageWithDims(value)) {+ return cloneImageWithDims(value);+ }++ if (+ isRecord(value) &&+ typeof value.imageName === 'string' &&+ value.imageName.length > 0 &&+ isPositiveFiniteNumber(value.width) &&+ isPositiveFiniteNumber(value.height)+ ) {+ return { height: value.height, image_name: value.imageName, width: value.width };+ }++ return null;+};++const normalizeCrop = (value: unknown): CroppableImageWithDims['crop'] | undefined => {+ if (!isRecord(value) || !isRecord(value.box)) {+ return undefined;+ }++ const image = normalizeFlatImage(value.image);+ const { box } = value;+ const ratio = value.ratio;++ if (+ !image ||+ !isPositiveFiniteNumber(box.width) ||+ !isPositiveFiniteNumber(box.height) ||+ typeof box.x !== 'number' ||+ !Number.isFinite(box.x) ||+ box.x < 0 ||+ typeof box.y !== 'number' ||+ !Number.isFinite(box.y) ||+ box.y < 0 ||+ (ratio !== null && !isPositiveFiniteNumber(ratio))+ ) {+ return undefined;+ }++ return {+ box: { height: box.height, width: box.width, x: box.x, y: box.y },+ image,+ ratio: ratio as number | null,+ };+};++/** Converts a gallery/upload response into a canonical, uncropped reference asset. */+export const generatedImageToReferenceImage = (+ image: Pick<GeneratedImageContract, 'height' | 'imageName' | 'width'>+): CroppableImageWithDims => ({+ original: { image: { height: image.height, image_name: image.imageName, width: image.width } },+});++/**+ * Accepts canonical legacy data, pre-crop `{ image_name, width, height }`, and+ * webv2's former flat `GeneratedImageContract`. Flat webv2 crops are necessarily+ * migrated as a new original because their previous original was not retained.+ */+export const normalizeCroppableImage = (value: unknown): CroppableImageWithDims | null => {+ const flat = normalizeFlatImage(value);+ if (flat) {+ return { original: { image: flat } };+ }++ if (!isRecord(value) || !isRecord(value.original)) {+ return null;+ }++ const original = normalizeFlatImage(value.original.image);+ if (!original) {+ return null;+ }++ const crop = normalizeCrop(value.crop);+ if (value.crop !== undefined && !crop) {+ return null;+ }++ return { ...(crop ? { crop } : {}), original: { image: original } };+};++/** True only for the canonical nested representation, not accepted migration inputs. */+export const isCanonicalCroppableImage = (value: unknown): value is CroppableImageWithDims =>+ isRecord(value) &&+ isRecord(value.original) &&+ isImageWithDims(value.original.image) &&+ (value.crop === undefined ||+ (isRecord(value.crop) && isImageWithDims(value.crop.image) && normalizeCrop(value.crop) !== undefined));++export type ReferenceImageCropBoxPct = { height: number; width: number; x: number; y: number };++export const FULL_REFERENCE_IMAGE_CROP_BOX: ReferenceImageCropBoxPct = {+ height: 100,+ width: 100,+ x: 0,+ y: 0,+};++export const isFullReferenceImageCropBox = (cropBox: ReferenceImageCropBoxPct): boolean =>+ cropBox.x === 0 && cropBox.y === 0 && cropBox.width === 100 && cropBox.height === 100;++export const getReferenceImageCropBoxPct = (image: CroppableImageWithDims): ReferenceImageCropBoxPct => {+ if (!image.crop) {+ return FULL_REFERENCE_IMAGE_CROP_BOX;+ }++ return {+ height: (image.crop.box.height / image.original.image.height) * 100,+ width: (image.crop.box.width / image.original.image.width) * 100,+ x: (image.crop.box.x / image.original.image.width) * 100,+ y: (image.crop.box.y / image.original.image.height) * 100,+ };+};++export const resolveReferenceImageCrop = (+ image: CroppableImageWithDims,+ cropBox: ReferenceImageCropBoxPct,+ uploadedCrop: ImageWithDims | null+): CroppableImageWithDims => {+ if (isFullReferenceImageCropBox(cropBox)) {+ return clearReferenceImageCrop(image);+ }++ if (!uploadedCrop) {+ throw new Error('A cropped image is required for a partial crop.');+ }++ const original = image.original.image;+ return applyReferenceImageCrop(image, {+ box: {+ height: Math.max(1, Math.round((cropBox.height / 100) * original.height)),+ width: Math.max(1, Math.round((cropBox.width / 100) * original.width)),+ x: Math.round((cropBox.x / 100) * original.width),+ y: Math.round((cropBox.y / 100) * original.height),+ },+ image: uploadedCrop,+ ratio: null,+ });+};++export const cloneCroppableImage = (image: CroppableImageWithDims): CroppableImageWithDims => ({+ ...(image.crop+ ? {+ crop: {+ box: { ...image.crop.box },+ image: cloneImageWithDims(image.crop.image),+ ratio: image.crop.ratio,+ },+ }+ : {}),+ original: { image: cloneImageWithDims(image.original.image) },+});++export const getEffectiveReferenceImage = (image: CroppableImageWithDims): ImageWithDims =>+ image.crop?.image ?? image.original.image;++export const applyReferenceImageCrop = (+ image: CroppableImageWithDims,+ crop: NonNullable<CroppableImageWithDims['crop']>+): CroppableImageWithDims => ({+ crop: {+ box: { ...crop.box },+ image: cloneImageWithDims(crop.image),+ ratio: crop.ratio,+ },+ original: { image: cloneImageWithDims(image.original.image) },+});++export const clearReferenceImageCrop = (image: CroppableImageWithDims): CroppableImageWithDims => ({+ original: { image: cloneImageWithDims(image.original.image) },+});++export const getReferenceImageUrls = (image: CroppableImageWithDims) => {+ const { image_name } = getEffectiveReferenceImage(image);+ return { imageUrl: getImageFullUrl(image_name), thumbnailUrl: getImageThumbnailUrl(image_name) };+};diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts b/invokeai/frontend/webv2/src/workbench/generation/settings.test.tsindex 846d72943f..a55a77b965 100644--- a/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts@@ -70,8 +70,34 @@ describe('normalizeGenerateSettings', () => {expect(normalized?.referenceImages[0]).toMatchObject({id: 'ref-1',isEnabled: true,- config: { type: 'qwen_image_reference_image', image: { imageName: 'reference.png' } },+ config: {+ type: 'qwen_image_reference_image',+ image: { original: { image: { height: 768, image_name: 'reference.png', width: 512 } } },+ },});+ expect(normalized && isGenerateSettings(normalized)).toBe(true);+ expect(+ isGenerateSettings({+ ...normalized,+ referenceImages: [+ {+ ...normalized?.referenceImages[0],+ config: {+ ...normalized?.referenceImages[0]?.config,+ image: {+ height: 768,+ imageName: 'reference.png',+ imageUrl: '/full',+ queuedAt: 'now',+ sourceQueueItemId: 'queue',+ thumbnailUrl: '/thumbnail',+ width: 512,+ },+ },+ },+ ],+ })+ ).toBe(false);});it('keeps more than five valid persisted reference images for provider-specific caps', () => {diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.ts b/invokeai/frontend/webv2/src/workbench/generation/settings.tsindex 227b343b21..f98223beb2 100644--- a/invokeai/frontend/webv2/src/workbench/generation/settings.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/settings.ts@@ -16,6 +16,7 @@ import type {import { sanitizeBatchCount } from './batch';import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';+import { cloneCroppableImage, isCanonicalCroppableImage, normalizeCroppableImage } from './referenceImage';/** Preset ratios, with the preset to switch to when dimensions are swapped. */export const ASPECT_RATIO_MAP: Record<Exclude<AspectRatioId, 'Free'>, { ratio: number; inverseId: AspectRatioId }> = {@@ -189,20 +190,8 @@ const isIPAdapterMethod = (const isFluxReduxImageInfluence = (value: unknown): value is 'lowest' | 'low' | 'medium' | 'high' | 'highest' =>value === 'lowest' || value === 'low' || value === 'medium' || value === 'high' || value === 'highest';-export const isReferenceImageAsset = (value: unknown): value is GenerateReferenceImageAsset =>- isRecord(value) &&- typeof value.imageName === 'string' &&- typeof value.imageUrl === 'string' &&- typeof value.thumbnailUrl === 'string' &&- typeof value.queuedAt === 'string' &&- typeof value.sourceQueueItemId === 'string' &&- hasFiniteNumber(value, 'width') &&- hasFiniteNumber(value, 'height');--const cloneReferenceImageAsset = (image: GenerateReferenceImageAsset): GenerateReferenceImageAsset => ({ ...image });-const normalizeReferenceImageAsset = (value: unknown): GenerateReferenceImageAsset | null =>- value === null ? null : isReferenceImageAsset(value) ? cloneReferenceImageAsset(value) : null;+ value === null ? null : normalizeCroppableImage(value);const normalizeReferenceImageConfig = (value: unknown): GenerateReferenceImageConfig | null => {if (!isRecord(value) || typeof value.type !== 'string' || !REFERENCE_IMAGE_CONFIG_TYPES.has(value.type)) {@@ -273,23 +262,32 @@ export const normalizeReferenceImages = (value: unknown): GenerateReferenceImagereturn images;};+const areReferenceImagesCanonical = (value: unknown): boolean =>+ Array.isArray(value) &&+ value.every(+ (item) =>+ isRecord(item) &&+ isRecord(item.config) &&+ (item.config.image === null || isCanonicalCroppableImage(item.config.image))+ );+const cloneReferenceImageConfig = (config: GenerateReferenceImageConfig): GenerateReferenceImageConfig => {switch (config.type) {case 'external_reference_image':case 'flux2_reference_image':case 'qwen_image_reference_image':- return { ...config, image: config.image ? cloneReferenceImageAsset(config.image) : null };+ return { ...config, image: config.image ? cloneCroppableImage(config.image) : null };case 'flux_kontext_reference_image':return {...config,- image: config.image ? cloneReferenceImageAsset(config.image) : null,+ image: config.image ? cloneCroppableImage(config.image) : null,model: config.model ? { ...config.model } : null,};case 'flux_redux':case 'ip_adapter':return {...config,- image: config.image ? cloneReferenceImageAsset(config.image) : null,+ image: config.image ? cloneCroppableImage(config.image) : null,model: config.model ? { ...config.model } : null,};}@@ -628,6 +626,7 @@ export const isGenerateSettings = (values: unknown): values is GenerateSettingsvalues.loras.every(isGenerateLora) &&Array.isArray(values.referenceImages) &&normalizeReferenceImages(values.referenceImages).length === values.referenceImages.length &&+ areReferenceImagesCanonical(values.referenceImages) &&typeof values.seamlessXAxis === 'boolean' &&typeof values.seamlessYAxis === 'boolean' &&isVaePrecision(values.vaePrecision) &&diff --git a/invokeai/frontend/webv2/src/workbench/generation/types.ts b/invokeai/frontend/webv2/src/workbench/generation/types.tsindex 1906a0aae5..c70244814b 100644--- a/invokeai/frontend/webv2/src/workbench/generation/types.ts+++ b/invokeai/frontend/webv2/src/workbench/generation/types.ts@@ -69,7 +69,26 @@ export interface GenerateLora {weight: number;}-export type GenerateReferenceImageAsset = GeneratedImageContract;+export interface ImageWithDims {+ image_name: string;+ width: number;+ height: number;+}++export interface CroppableImageWithDims {+ original: { image: ImageWithDims };+ crop?: {+ image: ImageWithDims;+ box: { x: number; y: number; width: number; height: number };+ ratio: number | null;+ };+}++/** Canonical persisted/metadata asset for global Generate reference images. */+export type GenerateReferenceImageAsset = CroppableImageWithDims;++/** Canvas regional guidance intentionally keeps its flat, URL-bearing image contract. */+export type RegionalGuidanceReferenceImageAsset = GeneratedImageContract;export type ClipVisionModel = 'ViT-H' | 'ViT-G' | 'ViT-L';@@ -77,22 +96,26 @@ export type IPAdapterMethod = 'full' | 'style' | 'composition' | 'style_strong'export type FluxReduxImageInfluence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';+type IPAdapterReferenceImageConfig<TImage> = {+ type: 'ip_adapter';+ image: TImage | null;+ model: ComponentModelConfig | null;+ weight: number;+ beginEndStepPct: [number, number];+ method: IPAdapterMethod;+ clipVisionModel: ClipVisionModel;+};++type FluxReduxReferenceImageConfig<TImage> = {+ type: 'flux_redux';+ image: TImage | null;+ model: ComponentModelConfig | null;+ imageInfluence: FluxReduxImageInfluence;+};+export type GenerateReferenceImageConfig =- | {- type: 'ip_adapter';- image: GenerateReferenceImageAsset | null;- model: ComponentModelConfig | null;- weight: number;- beginEndStepPct: [number, number];- method: IPAdapterMethod;- clipVisionModel: ClipVisionModel;- }- | {- type: 'flux_redux';- image: GenerateReferenceImageAsset | null;- model: ComponentModelConfig | null;- imageInfluence: FluxReduxImageInfluence;- }+ | IPAdapterReferenceImageConfig<GenerateReferenceImageAsset>+ | FluxReduxReferenceImageConfig<GenerateReferenceImageAsset>| {type: 'flux_kontext_reference_image';image: GenerateReferenceImageAsset | null;@@ -108,6 +131,16 @@ export interface GenerateReferenceImage {config: GenerateReferenceImageConfig;}+export type RegionalGuidanceReferenceImageConfig =+ | IPAdapterReferenceImageConfig<RegionalGuidanceReferenceImageAsset>+ | FluxReduxReferenceImageConfig<RegionalGuidanceReferenceImageAsset>;++export interface RegionalGuidanceReferenceImage {+ id: string;+ isEnabled: boolean;+ config: RegionalGuidanceReferenceImageConfig;+}+export type VaePrecision = 'fp16' | 'fp32';export type AspectRatioId =diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.tsindex 5be89556b7..4773bbcb06 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({getGalleryImageMetadata: vi.fn(),+ getGalleryImagesByNames: vi.fn(),}));vi.mock('@workbench/gallery/api', () => galleryApi);@@ -40,6 +41,7 @@ const image: GalleryImage = {describe('executeImageRecall', () => {beforeEach(() => {galleryApi.getGalleryImageMetadata.mockReset();+ galleryApi.getGalleryImagesByNames.mockReset();});it('recalls remix settings into Generate values', async () => {@@ -90,4 +92,51 @@ describe('executeImageRecall', () => {values: expect.objectContaining({ positivePrompt: 'fresh prompt', height: image.height, width: image.width }),});});++ it('bulk-checks effective reference images and omits deleted entries before committing', async () => {+ const dispatch = vi.fn();+ const recallImage = { ...image, imageName: 'selected-with-references.png' };+ const makeReference = (id: string, imageName: string) => ({+ config: {+ image: {+ crop: {+ box: { height: 128, width: 128, x: 0, y: 0 },+ image: { height: 128, image_name: imageName, width: 128 },+ ratio: 1,+ },+ original: { image: { height: 256, image_name: `${id}-original.png`, width: 256 } },+ },+ type: 'qwen_image_reference_image',+ },+ id,+ isEnabled: true,+ });++ galleryApi.getGalleryImageMetadata.mockResolvedValue({+ positive_prompt: 'keep other fields',+ ref_images: [makeReference('valid', 'valid-crop.png'), makeReference('deleted', 'deleted-crop.png')],+ });+ galleryApi.getGalleryImagesByNames.mockResolvedValue([{ ...image, imageName: 'valid-crop.png' }]);++ await expect(+ executeImageRecall({+ dispatch,+ generateValues: { modelKey: model.key },+ image: recallImage,+ kind: 'all',+ models: [model],+ projectId: 'project-1',+ })+ ).resolves.toBe(true);++ expect(galleryApi.getGalleryImagesByNames).toHaveBeenCalledWith(['valid-crop.png', 'deleted-crop.png']);+ expect(dispatch).toHaveBeenCalledWith({+ projectId: 'project-1',+ type: 'setGenerateSettings',+ values: expect.objectContaining({+ positivePrompt: 'keep other fields',+ referenceImages: [expect.objectContaining({ id: 'valid' })],+ }),+ });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.tsindex 49ab18d057..93fb4f91f4 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts@@ -4,8 +4,9 @@ import type { ModelConfig } from '@workbench/models/types';import type { WorkbenchAction } from '@workbench/workbenchState';import type { Dispatch } from 'react';-import { getGalleryImageMetadata } from '@workbench/gallery/api';+import { getGalleryImageMetadata, getGalleryImagesByNames } from '@workbench/gallery/api';import { getDefaultGenerateSettings, isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';+import { getEffectiveReferenceImage } from '@workbench/generation/referenceImage';import { isVaeModelConfig, normalizeGenerateWidgetValues } from '@workbench/generation/settings';import {@@ -118,6 +119,33 @@ export const executeImageRecall = async ({return false;}+ if (result.fields.includes('referenceImages')) {+ const effectiveNames = result.values.referenceImages.flatMap((referenceImage) =>+ referenceImage.config.image ? [getEffectiveReferenceImage(referenceImage.config.image).image_name] : []+ );+ const availableNames = new Set(+ (await getGalleryImagesByNames([...new Set(effectiveNames)])).map((availableImage) => availableImage.imageName)+ );+ result.values.referenceImages = result.values.referenceImages.filter((referenceImage) => {+ const referenceAsset = referenceImage.config.image;+ return referenceAsset && availableNames.has(getEffectiveReferenceImage(referenceAsset).image_name);+ });++ if (result.values.referenceImages.length === 0) {+ result.fields = result.fields.filter((field) => field !== 'referenceImages');+ }+ }++ if (result.fields.length === 0) {+ dispatch({+ kind: 'info',+ message: 'This image does not include supported Generate metadata.',+ title: 'No recallable image data',+ type: 'recordNotice',+ });+ return false;+ }+dispatch({ projectId, type: 'setGenerateSettings', values: result.values });dispatch({kind: 'success',diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex 471eb5508a..48d66f5d98 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -163,12 +163,139 @@ describe('image recall', () => {expect(result?.values.referenceImages).toHaveLength(1);expect(result?.values.referenceImages[0]?.config).toMatchObject({- image: { imageName: 'reference.png' },+ image: { original: { image: { height: 770, image_name: 'reference.png', width: 513 } } },type: 'ip_adapter',});expect(result?.fields).toContain('referenceImages');});+ it('preserves canonical original and crop provenance from legacy metadata', () => {+ const crop = {+ box: { height: 256, width: 320, x: 12, y: 24 },+ image: { height: 256, image_name: 'crop.png', width: 320 },+ ratio: null,+ };+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: {+ ref_images: [+ {+ config: {+ image: {+ crop,+ original: { image: { height: 768, image_name: 'original.png', width: 512 } },+ },+ type: 'qwen_image_reference_image',+ },+ id: 'canonical-ref',+ isEnabled: false,+ },+ ],+ },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.referenceImages[0]).toMatchObject({+ id: 'canonical-ref',+ isEnabled: false,+ config: {+ image: {+ crop,+ original: { image: { height: 768, image_name: 'original.png', width: 512 } },+ },+ },+ });+ });++ it('falls back to pre-v6 canvas ipAdapter metadata when ref_images has no valid entries', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: {+ canvas_v2_metadata: {+ referenceImages: {+ entities: [+ {+ id: 'legacy-canvas-ref',+ ipAdapter: {+ beginEndStepPct: [0.2, 0.9],+ clipVisionModel: 'ViT-G',+ image: { height: 512, image_name: 'legacy.png', width: 512 },+ method: 'composition',+ model: { base: 'sdxl', key: 'adapter', name: 'Adapter', type: 'ip_adapter' },+ type: 'ip_adapter',+ weight: 0.7,+ },+ isEnabled: false,+ },+ ],+ },+ },+ ref_images: [+ { id: 'invalid' },+ {+ config: { image: null, type: 'qwen_image_reference_image' },+ id: 'incomplete-direct-ref',+ isEnabled: true,+ },+ ],+ },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.referenceImages).toHaveLength(1);+ expect(result?.values.referenceImages[0]).toMatchObject({+ id: 'legacy-canvas-ref',+ isEnabled: false,+ config: {+ image: { original: { image: { image_name: 'legacy.png' } } },+ type: 'ip_adapter',+ },+ });+ });++ it('prefers valid ref_images over canvas fallback entries', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: {+ canvas_v2_metadata: {+ referenceImages: {+ entities: [+ {+ id: 'fallback',+ ipAdapter: { image: { height: 1, image_name: 'fallback.png', width: 1 }, type: 'flux_redux' },+ },+ ],+ },+ },+ ref_images: [+ {+ config: {+ image: { height: 64, image_name: 'direct.png', width: 64 },+ type: 'qwen_image_reference_image',+ },+ id: 'direct',+ isEnabled: true,+ },+ ],+ },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.referenceImages.map((referenceImage) => referenceImage.id)).toEqual(['direct']);+ });+it('drops recalled reference images when the effective model does not support them', () => {const result = buildImageRecallSettings({currentValues: createValues({ model: animaModel, modelKey: animaModel.key }),diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex 122e7e7072..b388640479 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -314,8 +314,33 @@ const hasComponentModels = (metadata: unknown, models: readonly ComponentModelCogetMetadataComponent(metadata, 'qwen3_encoder', models) !== undefined ||getMetadataComponent(metadata, 'qwen_image_qwen_vl_encoder', models) !== undefined;-const getMetadataReferenceImages = (metadata: unknown) =>- isRecord(metadata) ? normalizeReferenceImages(metadata.ref_images) : [];+export const getMetadataReferenceImages = (metadata: unknown) => {+ if (!isRecord(metadata)) {+ return [];+ }++ const direct = normalizeReferenceImages(metadata.ref_images).filter(+ (referenceImage) => referenceImage.config.image !== null+ );+ if (direct.length > 0) {+ return direct;+ }++ const canvasMetadata = getRecord(metadata, 'canvas_v2_metadata');+ const referenceImages = getRecord(canvasMetadata, 'referenceImages');+ const legacyEntities = referenceImages?.entities;+ if (!Array.isArray(legacyEntities)) {+ return [];+ }++ return normalizeReferenceImages(+ legacyEntities.map((entry) =>+ isRecord(entry) && isRecord(entry.ipAdapter)+ ? { config: entry.ipAdapter, id: entry.id, isEnabled: entry.isEnabled }+ : entry+ )+ ).filter((referenceImage) => referenceImage.config.image !== null);+};const withDimensions = (values: GenerateWidgetValues,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex ea4b5d38f7..29eb1e976a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -22,6 +22,7 @@ import {isReferenceImageSupported,isSupportedGenerateModel,} from '@workbench/generation/baseGenerationPolicies';+import { generatedImageToReferenceImage } from '@workbench/generation/referenceImage';import { isVaeModelConfig } from '@workbench/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@workbench/models/modelsStore';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';@@ -324,7 +325,7 @@ export const useImageActions = ({}const referenceImage = {- config: getDefaultReferenceImageConfig(currentValues.model, models, image),+ config: getDefaultReferenceImageConfig(currentValues.model, models, generatedImageToReferenceImage(image)),id: createReferenceImageId(),isEnabled: true,};diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex b3d9be0fb3..6a7cbca6af 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -3,7 +3,7 @@ import type { ComponentType, ExoticComponent, JSXElementConstructor, SVGProps }// `generation/types.ts` imports value-less (`import type`) symbols back from this// module; both sides are type-only so this doesn't create a runtime cycle.-import type { GenerateReferenceImage, GenerateWidgetValues } from './generation/types';+import type { GenerateWidgetValues, RegionalGuidanceReferenceImage } from './generation/types';import type { WorkbenchLanguage } from './i18n/languages';import type { ProjectGraphState } from './workflows/types';@@ -599,7 +599,7 @@ export interface CanvasRegionalGuidanceLayerContract extends CanvasLayerBaseContpositivePrompt: string | null;negativePrompt: string | null;autoNegative: boolean;- referenceImages: GenerateReferenceImage[];+ referenceImages: RegionalGuidanceReferenceImage[];}export interface CanvasInpaintMaskLayerContract extends CanvasLayerBaseContract {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex 0e48fea1ad..2c2a0e0bfe 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -4,9 +4,9 @@ import type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import type {GenerateModelConfig,- GenerateReferenceImage,- GenerateReferenceImageAsset,MainModelConfig,+ RegionalGuidanceReferenceImage,+ RegionalGuidanceReferenceImageAsset,} from '@workbench/generation/types';import type {CanvasDocumentContractV2,@@ -918,11 +918,11 @@ describe('runCanvasInvocation — inpaint / outpaint dispatch', () => {// the resolver seam: refs without an image are dropped; refs with an image + a// compatible model survive into the graph inputs.describe('resolveRegionalReferenceImages', () => {- const asset = { imageName: 'ref.png' } as GenerateReferenceImageAsset;+ const asset = { imageName: 'ref.png' } as RegionalGuidanceReferenceImageAsset;const ipAdapterModel = { base: 'sd-1', key: 'ipa', name: 'IP Adapter', type: 'ip_adapter' };const fluxReduxModel = { base: 'flux', key: 'redux', name: 'FLUX Redux', type: 'flux_redux' };- const ipAdapterRef = (image: GenerateReferenceImageAsset | null): GenerateReferenceImage => ({+ const ipAdapterRef = (image: RegionalGuidanceReferenceImageAsset | null): RegionalGuidanceReferenceImage => ({config: {beginEndStepPct: [0, 1],clipVisionModel: 'ViT-H',@@ -936,7 +936,7 @@ describe('resolveRegionalReferenceImages', () => {isEnabled: true,});- const fluxReduxRef = (image: GenerateReferenceImageAsset | null): GenerateReferenceImage => ({+ const fluxReduxRef = (image: RegionalGuidanceReferenceImageAsset | null): RegionalGuidanceReferenceImage => ({config: { image, imageInfluence: 'highest', model: fluxReduxModel, type: 'flux_redux' },id: 'ref-redux',isEnabled: true,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex 2ba2cefa7b..74cbfdf7c3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -41,7 +41,7 @@ import type {RegionalReferenceImageInput,} from '@workbench/generation/canvas/addRegionalGuidance';import type { CanvasCompileMode } from '@workbench/generation/canvas/types';-import type { GenerateModelConfig, GenerateReferenceImage } from '@workbench/generation/types';+import type { GenerateModelConfig, RegionalGuidanceReferenceImage } from '@workbench/generation/types';import type { ModelConfig } from '@workbench/models/types';import type {CanvasDocumentContractV2,@@ -216,7 +216,7 @@ const FLUX_REDUX_INFLUENCE_SETTINGS = {/** Resolves a regional-guidance layer's reference images into graph inputs (drops incomplete/incompatible ones). */export const resolveRegionalReferenceImages = (- region: { referenceImages: GenerateReferenceImage[] },+ region: { referenceImages: RegionalGuidanceReferenceImage[] },base: string): RegionalReferenceImageInput[] => {const inputs: RegionalReferenceImageInput[] = [];diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/GenerateReferenceImagesSection.tsxindex aee0fbfaba..9654e043ec 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/GenerateReferenceImagesSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/GenerateReferenceImagesSection.tsx@@ -19,6 +19,7 @@ import {getMaxReferenceImages,isReferenceImageSupported,} from '@workbench/generation/baseGenerationPolicies';+import { generatedImageToReferenceImage, getEffectiveReferenceImage } from '@workbench/generation/referenceImage';import { clampDimension, deriveAspectRatioId } from '@workbench/generation/settings';import { isGalleryImageDragData } from '@workbench/widgets/gallery/galleryDnd';import { GenerateCollapsibleSection } from '@workbench/widgets/generate/shared/GenerateCollapsibleSection';@@ -117,8 +118,9 @@ export const GenerateReferenceImagesSection = ({}const grid = getGenerationDimensions(selectedModel).grid;- const width = clampDimension(image.width, grid);- const height = clampDimension(image.height, grid);+ const effectiveImage = getEffectiveReferenceImage(image);+ const width = clampDimension(effectiveImage.width, grid);+ const height = clampDimension(effectiveImage.height, grid);onCommitImmediate({aspectRatioId: deriveAspectRatioId(width, height),@@ -141,7 +143,7 @@ export const GenerateReferenceImagesSection = ({files.slice(0, maxReferenceImages - referenceImageCount).map((file) => uploadGalleryImage(file, 'none')));- appendReferenceImages(uploaded);+ appendReferenceImages(uploaded.map(generatedImageToReferenceImage));dispatch({ type: 'touchGalleryImagesRefresh' });} catch (error) {dispatch({@@ -177,7 +179,7 @@ export const GenerateReferenceImagesSection = ({const images = await getGalleryImagesByNames(imageNames.slice(0, maxReferenceImages - referenceImageCount));if (images.length > 0) {- appendReferenceImages(images);+ appendReferenceImages(images.map(generatedImageToReferenceImage));}};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCard.tsxindex 74c0cba950..81715e75a3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCard.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCard.tsx@@ -9,6 +9,7 @@ import type { CSSProperties } from 'react';import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { IconButton, ToggleDot, Tooltip } from '@workbench/components/ui';+import { getEffectiveReferenceImage, getReferenceImageUrls } from '@workbench/generation/referenceImage';import { ModelSelect } from '@workbench/models/components';import { ChevronDownIcon, CropIcon, ImageIcon, RulerIcon, Trash2Icon } from 'lucide-react';import { memo, useCallback, useState } from 'react';@@ -282,17 +283,22 @@ const ReferenceModelSelector = ({);};-const MiniThumbnail = ({ image }: { image: GenerateReferenceImageAsset | null }) => (- <Box bg="bg.muted" borderWidth="1px" flexShrink="0" h="6" overflow="hidden" rounded="sm" w="6">- {image ? (- <img alt={image.imageName} draggable={false} src={image.thumbnailUrl} style={COVER_IMG_STYLE} />- ) : (- <Box alignItems="center" color="fg.muted" display="flex" h="full" justifyContent="center" w="full">- <ImageIcon size="12" />- </Box>- )}- </Box>-);+const MiniThumbnail = ({ image }: { image: GenerateReferenceImageAsset | null }) => {+ const effectiveImage = image ? getEffectiveReferenceImage(image) : null;+ const urls = image ? getReferenceImageUrls(image) : null;++ return (+ <Box bg="bg.muted" borderWidth="1px" flexShrink="0" h="6" overflow="hidden" rounded="sm" w="6">+ {effectiveImage && urls ? (+ <img alt={effectiveImage.image_name} draggable={false} src={urls.thumbnailUrl} style={COVER_IMG_STYLE} />+ ) : (+ <Box alignItems="center" color="fg.muted" display="flex" h="full" justifyContent="center" w="full">+ <ImageIcon size="12" />+ </Box>+ )}+ </Box>+ );+};const ReferenceImageThumbnail = ({disabled,@@ -307,6 +313,8 @@ const ReferenceImageThumbnail = ({}) => {const { t } = useTranslation();const [isCropOpen, setIsCropOpen] = useState(false);+ const effectiveImage = image ? getEffectiveReferenceImage(image) : null;+ const urls = image ? getReferenceImageUrls(image) : null;const openCrop = useCallback(() => setIsCropOpen(true), []);const closeCrop = useCallback(() => setIsCropOpen(false), []);@@ -330,8 +338,8 @@ const ReferenceImageThumbnail = ({rounded="md"w="20">- {image ? (- <img alt={image.imageName} draggable={false} src={image.thumbnailUrl} style={COVER_IMG_STYLE} />+ {effectiveImage && urls ? (+ <img alt={effectiveImage.image_name} draggable={false} src={urls.thumbnailUrl} style={COVER_IMG_STYLE} />) : (<Box alignItems="center" color="fg.muted" display="flex" h="full" justifyContent="center" w="full"><ImageIcon size="24" />@@ -376,7 +384,7 @@ const ReferenceImageThumbnail = ({</HStack>) : null}</Box>- {image ? (+ {image && isCropOpen ? (<ReferenceImageCropDialog image={image} isOpen={isCropOpen} onApply={onCrop} onClose={closeCrop} />) : null}</>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageControls.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageControls.tsxindex f2979eec03..3ce35a2eac 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageControls.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageControls.tsx@@ -413,14 +413,14 @@ export const ClipVisionSelect = ({);};-export const FluxReduxControls = ({+export const FluxReduxControls = <T extends { imageInfluence: FluxReduxImageInfluence; type: 'flux_redux' }>({config,disabled,onChange,}: {- config: Extract<GenerateReferenceImageConfig, { type: 'flux_redux' }>;+ config: T;disabled: boolean;- onChange: (config: GenerateReferenceImageConfig) => void;+ onChange: (config: T) => void;}) => {const { t } = useTranslation();const imageInfluenceValue = useMemo(() => [config.imageInfluence], [config.imageInfluence]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.test.tsnew file mode 100644index 0000000000..5656472143--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.test.ts@@ -0,0 +1,88 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++const galleryApi = vi.hoisted(() => ({+ getImageFullUrl: vi.fn((imageName: string) => `/full/${imageName}`),+ getImageThumbnailUrl: vi.fn((imageName: string) => `/thumbnail/${imageName}`),+ uploadGalleryImage: vi.fn(),+}));++vi.mock('@workbench/gallery/api', () => galleryApi);++import { applyReferenceImageCropSelection, exportCroppedReferenceImage } from './ReferenceImageCropDialog';++const image = {+ crop: {+ box: { height: 200, width: 300, x: 10, y: 20 },+ image: { height: 200, image_name: 'previous-crop.png', width: 300 },+ ratio: null,+ },+ original: { image: { height: 600, image_name: 'original.png', width: 800 } },+};+const cropBox = { height: 50, width: 50, x: 25, y: 10 };++const stubCropBrowserApis = (onLoadUrl?: (url: string) => void) => {+ const drawImage = vi.fn();++ class TestImage {+ crossOrigin = '';+ naturalHeight = 600;+ naturalWidth = 800;+ onerror: (() => void) | null = null;+ onload: (() => void) | null = null;++ set src(value: string) {+ onLoadUrl?.(value);+ this.onload?.();+ }+ }++ vi.stubGlobal('Image', TestImage);+ vi.stubGlobal('document', {+ createElement: () => ({+ getContext: () => ({ drawImage }),+ height: 0,+ toBlob: (callback: (blob: Blob) => void) => callback(new Blob(['crop'], { type: 'image/png' })),+ width: 0,+ }),+ });++ return { drawImage, TestImage };+};++afterEach(() => {+ galleryApi.uploadGalleryImage.mockReset();+ vi.unstubAllGlobals();+});++describe('ReferenceImageCropDialog', () => {+ it('recrops from the original image rather than the previous crop', async () => {+ let loadedUrl = '';+ const { drawImage, TestImage } = stubCropBrowserApis((url) => {+ loadedUrl = url;+ });++ const file = await exportCroppedReferenceImage(image, cropBox);++ expect(loadedUrl).toBe('/full/original.png');+ expect(loadedUrl).not.toContain('previous-crop.png');+ expect(drawImage).toHaveBeenCalledWith(expect.any(TestImage), 200, 60, 400, 300, 0, 0, 400, 300);+ expect(file.name).toBe('original-crop.png');+ });++ it('uploads an applied crop as intermediate and preserves the original', async () => {+ stubCropBrowserApis();+ galleryApi.uploadGalleryImage.mockResolvedValue({ height: 300, imageName: 'new-crop.png', width: 400 });++ const result = await applyReferenceImageCropSelection(image, cropBox);++ expect(galleryApi.uploadGalleryImage).toHaveBeenCalledWith(expect.any(File), 'none', { isIntermediate: true });+ expect(result).toEqual({+ crop: {+ box: { height: 300, width: 400, x: 200, y: 60 },+ image: { height: 300, image_name: 'new-crop.png', width: 400 },+ ratio: null,+ },+ original: image.original,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.tsxindex 068f4d4241..ce14b1ba6b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/reference-images/ReferenceImageCropDialog.tsx@@ -4,19 +4,24 @@ import type { CSSProperties, PointerEvent } from 'react';import { Box, Dialog, Portal, Stack, Text } from '@chakra-ui/react';import { Button } from '@workbench/components/ui';import { uploadGalleryImage } from '@workbench/gallery/api';+import {+ FULL_REFERENCE_IMAGE_CROP_BOX,+ generatedImageToReferenceImage,+ getReferenceImageCropBoxPct,+ getReferenceImageUrls,+ isFullReferenceImageCropBox,+ resolveReferenceImageCrop,+ type ReferenceImageCropBoxPct,+} from '@workbench/generation/referenceImage';import { useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-type CropBoxPct = { height: number; width: number; x: number; y: number };-type HandleName = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';type DragMode = 'move' | HandleName;-type DragState = { box: CropBoxPct; mode: DragMode; x: number; y: number };--const FULL_CROP_BOX: CropBoxPct = { height: 100, width: 100, x: 0, y: 0 };+type DragState = { box: ReferenceImageCropBoxPct; mode: DragMode; x: number; y: number };/** Matches the legacy cropper's minimum crop dimension, in image pixels. */const MIN_CROP_DIMENSION_PX = 64;@@ -52,7 +57,7 @@ const resolveDrag = (point: { x: number; y: number },minWidth: number,minHeight: number-): CropBoxPct => {+): ReferenceImageCropBoxPct => {const dx = point.x - drag.x;const dy = point.y - drag.y;const box = drag.box;@@ -89,24 +94,25 @@ const resolveDrag = (return { height: bottom - top, width: right - left, x: left, y: top };};-const isFullCropBox = (cropBox: CropBoxPct): boolean =>- cropBox.x === 0 && cropBox.y === 0 && cropBox.width === 100 && cropBox.height === 100;-const isDragMode = (value: unknown): value is DragMode =>value === 'move' || HANDLES.some((handle) => handle.name === value);-const exportCroppedImage = async (image: GenerateReferenceImageAsset, cropBox: CropBoxPct): Promise<File> => {+export const exportCroppedReferenceImage = async (+ image: GenerateReferenceImageAsset,+ cropBox: ReferenceImageCropBoxPct+): Promise<File> => {+ const original = image.original.image;const img = new Image();img.crossOrigin = 'anonymous';await new Promise<void>((resolve, reject) => {img.onload = () => resolve();img.onerror = () => reject(new Error('Failed to load reference image for cropping.'));- img.src = image.imageUrl;+ img.src = getReferenceImageUrls({ original: image.original }).imageUrl;});- const sourceWidth = img.naturalWidth || image.width;- const sourceHeight = img.naturalHeight || image.height;+ const sourceWidth = img.naturalWidth || original.width;+ const sourceHeight = img.naturalHeight || original.height;const sx = Math.round((cropBox.x / 100) * sourceWidth);const sy = Math.round((cropBox.y / 100) * sourceHeight);const sw = Math.max(1, Math.round((cropBox.width / 100) * sourceWidth));@@ -124,7 +130,21 @@ const exportCroppedImage = async (image: GenerateReferenceImageAsset, cropBox: C);});- return new File([blob], `${image.imageName.replace(/\.[^.]+$/, '')}-crop.png`, { type: 'image/png' });+ return new File([blob], `${original.image_name.replace(/\.[^.]+$/, '')}-crop.png`, { type: 'image/png' });+};++export const applyReferenceImageCropSelection = async (+ image: GenerateReferenceImageAsset,+ cropBox: ReferenceImageCropBoxPct+): Promise<GenerateReferenceImageAsset> => {+ if (isFullReferenceImageCropBox(cropBox)) {+ return resolveReferenceImageCrop(image, cropBox, null);+ }++ const file = await exportCroppedReferenceImage(image, cropBox);+ const croppedImage = await uploadGalleryImage(file, 'none', { isIntermediate: true });++ return resolveReferenceImageCrop(image, cropBox, generatedImageToReferenceImage(croppedImage).original.image);};export const ReferenceImageCropDialog = ({@@ -140,15 +160,17 @@ export const ReferenceImageCropDialog = ({}) => {const { t } = useTranslation();const dispatch = useWorkbenchDispatch();- const [cropBox, setCropBox] = useState<CropBoxPct>(FULL_CROP_BOX);+ const [cropBox, setCropBox] = useState<ReferenceImageCropBoxPct>(() => getReferenceImageCropBoxPct(image));const [isApplying, setIsApplying] = useState(false);const containerRef = useRef<HTMLDivElement | null>(null);const dragRef = useRef<DragState | null>(null);- const ratio = image.height > 0 ? image.width / image.height : 1;- const minWidthPct = Math.min(100, (MIN_CROP_DIMENSION_PX / Math.max(1, image.width)) * 100);- const minHeightPct = Math.min(100, (MIN_CROP_DIMENSION_PX / Math.max(1, image.height)) * 100);- const cropWidthPx = Math.max(1, Math.round((cropBox.width / 100) * image.width));- const cropHeightPx = Math.max(1, Math.round((cropBox.height / 100) * image.height));+ const original = image.original.image;+ const imageUrl = getReferenceImageUrls({ original: image.original }).imageUrl;+ const ratio = original.height > 0 ? original.width / original.height : 1;+ const minWidthPct = Math.min(100, (MIN_CROP_DIMENSION_PX / Math.max(1, original.width)) * 100);+ const minHeightPct = Math.min(100, (MIN_CROP_DIMENSION_PX / Math.max(1, original.height)) * 100);+ const cropWidthPx = Math.max(1, Math.round((cropBox.width / 100) * original.width));+ const cropHeightPx = Math.max(1, Math.round((cropBox.height / 100) * original.height));const cropBoxStyle = useMemo<CSSProperties>(() => ({@@ -162,10 +184,10 @@ export const ReferenceImageCropDialog = ({const close = useCallback(() => {if (!isApplying) {- setCropBox(FULL_CROP_BOX);+ setCropBox(getReferenceImageCropBoxPct(image));onClose();}- }, [isApplying, onClose]);+ }, [image, isApplying, onClose]);const handleOpenChange = useCallback((event: Dialog.OpenChangeDetails) => {@@ -215,21 +237,20 @@ export const ReferenceImageCropDialog = ({}}, []);- const resetCrop = useCallback(() => setCropBox(FULL_CROP_BOX), []);+ const resetCrop = useCallback(() => setCropBox(FULL_REFERENCE_IMAGE_CROP_BOX), []);const applyCrop = useCallback(async () => {- if (isFullCropBox(cropBox)) {+ if (isFullReferenceImageCropBox(cropBox)) {+ onApply(await applyReferenceImageCropSelection(image, cropBox));close();return;}try {setIsApplying(true);- const file = await exportCroppedImage(image, cropBox);- const croppedImage = await uploadGalleryImage(file, 'none', { isIntermediate: true });+ const croppedImage = await applyReferenceImageCropSelection(image, cropBox);dispatch({ type: 'touchGalleryImagesRefresh' });onApply(croppedImage);- setCropBox(FULL_CROP_BOX);onClose();} catch (error) {dispatch({@@ -274,7 +295,7 @@ export const ReferenceImageCropDialog = ({onPointerMove={moveDrag}onPointerUp={endDrag}>- <img alt={image.imageName} draggable={false} src={image.imageUrl} style={CONTAIN_IMG_STYLE} />+ <img alt={original.image_name} draggable={false} src={imageUrl} style={CONTAIN_IMG_STYLE} /><BoxborderColor="accent.solid"borderWidth="1.5px"@@ -336,7 +357,12 @@ export const ReferenceImageCropDialog = ({</Stack></Dialog.Body><Dialog.Footer>- <Button disabled={isApplying || isFullCropBox(cropBox)} size="sm" variant="outline" onClick={resetCrop}>+ <Button+ disabled={isApplying || isFullReferenceImageCropBox(cropBox)}+ size="sm"+ variant="outline"+ onClick={resetCrop}+ >{t('common.reset')}</Button><Button disabled={isApplying} size="sm" variant="outline" onClick={close}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 36d1303cf7..f07aab7ca7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -1,6 +1,6 @@import type { BooleanRasterOperation } from '@workbench/canvas-engine/engine';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { GenerateReferenceImage } from '@workbench/generation/types';+import type { RegionalGuidanceReferenceImage } from '@workbench/generation/types';import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasMaskContract } from '@workbench/types';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { LucideIcon } from 'lucide-react';@@ -96,7 +96,7 @@ type LayerConfigPatch =positivePrompt?: string | null;negativePrompt?: string | null;autoNegative?: boolean;- referenceImages?: GenerateReferenceImage[];+ referenceImages?: RegionalGuidanceReferenceImage[];}| { layerType: 'inpaint_mask'; noiseLevel?: number; denoiseLimit?: number };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 33046c6fc7..43ce0bffc2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -1,5 +1,9 @@import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';-import type { GenerateReferenceImage, GenerateReferenceImageAsset, IPAdapterMethod } from '@workbench/generation/types';+import type {+ IPAdapterMethod,+ RegionalGuidanceReferenceImage,+ RegionalGuidanceReferenceImageAsset,+} from '@workbench/generation/types';import type { ModelConfig } from '@workbench/models/types';import type { CanvasMaskContract, CanvasMaskFillContract, CanvasRegionalGuidanceLayerContract } from '@workbench/types';import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';@@ -29,7 +33,7 @@ interface RegionalConfigPatch {positivePrompt?: string | null;negativePrompt?: string | null;autoNegative?: boolean;- referenceImages?: GenerateReferenceImage[];+ referenceImages?: RegionalGuidanceReferenceImage[];}/** The six mask fill styles, matching `CanvasMaskFillContract['style']` / legacy `zFillStyle`. */@@ -65,7 +69,8 @@ const referenceImageDropId = (layerId: string, refId: string): string => `region* A fresh regional reference image for the currently selected model's base. Shared* with the header add-layer menu via `layerOps.createRegionalReferenceImage`.*/-const createReferenceImage = (base: string | null): GenerateReferenceImage => createRegionalReferenceImage(base);+const createReferenceImage = (base: string | null): RegionalGuidanceReferenceImage =>+ createRegionalReferenceImage(base);interface RegionalGuidanceSettingsProps {engine: CanvasStructuralEngine | null;@@ -227,7 +232,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst referenceImages = layer.referenceImages;const commitReferenceImages = useCallback(- (next: GenerateReferenceImage[]) => {+ (next: RegionalGuidanceReferenceImage[]) => {commitConfig(t('widgets.layers.regionalGuidance.referenceImages'),{ referenceImages: next },@@ -247,7 +252,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett// (`commitReferenceImages` → `updateCanvasLayerConfig`), so a drop/upload/clear// is a single, undoable document change.const setReferenceImageAsset = useCallback(- (refId: string, image: GenerateReferenceImageAsset | null) => {+ (refId: string, image: RegionalGuidanceReferenceImageAsset | null) => {commitReferenceImages(referenceImages.map((ref) => (ref.id === refId ? { ...ref, config: { ...ref.config, image } } : ref)));@@ -438,14 +443,14 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettinterface ReferenceImageRowProps {dropId: string;index: number;- referenceImage: GenerateReferenceImage;- referenceImages: readonly GenerateReferenceImage[];+ referenceImage: RegionalGuidanceReferenceImage;+ referenceImages: readonly RegionalGuidanceReferenceImage[];ipAdapterModelCollection: ReturnType<typeof createListCollection<{ label: string; value: string }>>;fluxReduxModelCollection: ReturnType<typeof createListCollection<{ label: string; value: string }>>;methodCollection: ReturnType<typeof createListCollection<{ label: string; value: string }>>;models: readonly ModelConfig[];- onCommit: (next: GenerateReferenceImage[]) => void;- onSetImage: (refId: string, image: GenerateReferenceImageAsset | null) => void;+ onCommit: (next: RegionalGuidanceReferenceImage[]) => void;+ onSetImage: (refId: string, image: RegionalGuidanceReferenceImageAsset | null) => void;onUpload: (refId: string, file: File) => void;}@@ -474,7 +479,7 @@ const ReferenceImageRow = ({const { isOver, setNodeRef } = useDroppable({ data: { kind: 'regional-reference-image' }, id: dropId });const replaceRef = useCallback(- (next: GenerateReferenceImage) => {+ (next: RegionalGuidanceReferenceImage) => {onCommit(referenceImages.map((entry, i) => (i === index ? next : entry)));},[index, onCommit, referenceImages]@@ -558,7 +563,7 @@ const ReferenceImageRow = ({);const handleFluxReduxConfig = useCallback(- (nextConfig: GenerateReferenceImage['config']) => {+ (nextConfig: RegionalGuidanceReferenceImage['config']) => {replaceRef({ ...referenceImage, config: nextConfig });},[referenceImage, replaceRef]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 98ab7635fd..199e67c370 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -8,7 +8,7 @@import type { CanvasLayerCapability } from '@workbench/canvas-engine/api';import type { Rect } from '@workbench/canvas-engine/types';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { GenerateReferenceImage } from '@workbench/generation/types';+import type { RegionalGuidanceReferenceImage } from '@workbench/generation/types';import type {CanvasBlendMode,CanvasControlLayerContract,@@ -247,7 +247,7 @@ export const createReferenceImageId = (): string =>export const createRegionalReferenceImage = (base: string | null,id: string = createReferenceImageId()-): GenerateReferenceImage => {+): RegionalGuidanceReferenceImage => {if (base === 'flux') {return {config: { image: null, imageInfluence: 'highest', model: null, type: 'flux_redux' },