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(webv2): extract image recall helpers
joshistoast9f04435b8ccd
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.tsnew file mode 100644index 0000000000..de0b599671--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts@@ -0,0 +1,69 @@+import type { GalleryImage } from '@workbench/gallery/api';+import type { ModelConfig } from '@workbench/models/types';++import { beforeEach, describe, expect, it, vi } from 'vitest';++const galleryApi = vi.hoisted(() => ({+ getGalleryImageMetadata: vi.fn(),+}));++vi.mock('@workbench/gallery/api', () => galleryApi);++import { executeImageRecall } from './executeImageRecall';++const model = {+ base: 'sdxl',+ file_size: 1,+ format: 'checkpoint',+ hash: 'hash',+ key: 'sdxl-model',+ name: 'SDXL',+ path: '/models/sdxl.safetensors',+ source: 'local',+ source_type: 'path',+ type: 'main',+} as ModelConfig;++const image: GalleryImage = {+ boardId: 'none',+ height: 768,+ imageCategory: 'general',+ imageName: 'selected.png',+ imageUrl: '/selected.png',+ queuedAt: '2026-06-19T00:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ starred: false,+ thumbnailUrl: '/selected-thumb.png',+ width: 512,+};++describe('executeImageRecall', () => {+ beforeEach(() => {+ galleryApi.getGalleryImageMetadata.mockReset();+ });++ it('recalls remix settings into Generate values', async () => {+ const dispatch = vi.fn();++ galleryApi.getGalleryImageMetadata.mockResolvedValue({ positive_prompt: 'recalled prompt' });++ await expect(+ executeImageRecall({+ dispatch,+ generateValues: { modelKey: model.key },+ image,+ kind: 'remix',+ models: [model],+ })+ ).resolves.toBe(true);++ expect(galleryApi.getGalleryImageMetadata).toHaveBeenCalledWith('selected.png');+ expect(dispatch).toHaveBeenCalledWith({+ type: 'setGenerateSettings',+ values: expect.objectContaining({ positivePrompt: 'recalled prompt' }),+ });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'success', title: 'Recalled remix settings', type: 'recordNotice' })+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.tsnew file mode 100644index 0000000000..545c118e05--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts@@ -0,0 +1,119 @@+import type { GalleryImage } from '@workbench/gallery/api';+import type { GenerateModelConfig, VaeModelConfig } from '@workbench/generation/types';+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 { getDefaultGenerateSettings, isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';+import { isVaeModelConfig, normalizeGenerateWidgetValues } from '@workbench/generation/settings';++import {+ buildImageRecallSettings,+ getImageRecallMessage,+ getImageRecallTitle,+ type ImageRecallKind,+} from './imageRecall';++const imageMetadataRequests = new Map<string, Promise<unknown>>();++const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));++const loadImageMetadata = (imageName: string): Promise<unknown> => {+ const cachedRequest = imageMetadataRequests.get(imageName);++ if (cachedRequest) {+ return cachedRequest;+ }++ const request = getGalleryImageMetadata(imageName).catch((error: unknown) => {+ imageMetadataRequests.delete(imageName);+ throw error;+ });++ imageMetadataRequests.set(imageName, request);++ return request;+};++export const getCurrentGenerateValues = ({+ generateValues,+ supportedModels,+}: {+ generateValues: Record<string, unknown>;+ supportedModels: GenerateModelConfig[];+}) => {+ const normalizedValues = normalizeGenerateWidgetValues(generateValues);++ if (normalizedValues) {+ return normalizedValues;+ }++ const fallbackModelKey = typeof generateValues.modelKey === 'string' ? generateValues.modelKey : null;+ const fallbackModel = supportedModels.find((model) => model.key === fallbackModelKey) ?? supportedModels[0];++ return fallbackModel ? { ...getDefaultGenerateSettings(fallbackModel), model: fallbackModel } : null;+};++export const executeImageRecall = async ({+ dispatch,+ generateValues,+ image,+ kind,+ models,+}: {+ dispatch: Dispatch<WorkbenchAction>;+ generateValues: Record<string, unknown>;+ image: GalleryImage;+ kind: ImageRecallKind;+ models: ModelConfig[];+}): Promise<boolean> => {+ const supportedModels = models.filter(isSupportedGenerateModel);+ const vaeModels = models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig);+ const currentGenerateValues = getCurrentGenerateValues({ generateValues, supportedModels });++ try {+ if (!currentGenerateValues) {+ dispatch({+ kind: 'info',+ message: 'Select a supported Generate model first.',+ title: 'Cannot recall image data',+ type: 'recordNotice',+ });+ return false;+ }++ const metadata = kind === 'dimensions' ? null : await loadImageMetadata(image.imageName);+ const result = buildImageRecallSettings({+ currentValues: currentGenerateValues,+ image,+ kind,+ metadata,+ models,+ supportedModels,+ vaeModels,+ });++ if (!result) {+ dispatch({+ kind: 'info',+ message: 'This image does not include supported Generate metadata.',+ title: 'No recallable image data',+ type: 'recordNotice',+ });+ return false;+ }++ dispatch({ type: 'setGenerateSettings', values: result.values });+ dispatch({+ kind: 'success',+ message: getImageRecallMessage(result.fields),+ title: getImageRecallTitle(kind),+ type: 'recordNotice',+ });+ return true;+ } catch (error: unknown) {+ dispatch({ message: toErrorMessage(error), type: 'recordError' });+ return false;+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.tsindex b49575bd56..9e1417d6c1 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts@@ -14,4 +14,6 @@ export {type ImageRecallKind,type ImageRecallResult,} from './imageRecall';+export { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';+export { getSelectedGalleryImage, getSelectedGalleryImageFromValues } from './selectedImage';export { saveBlobToDisk, useImageActions, type ImageActions } from './useImageActions';diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.test.tsnew file mode 100644index 0000000000..8096ef5a34--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.test.ts@@ -0,0 +1,36 @@+import type { GeneratedImageContract } from '@workbench/types';++import { describe, expect, it } from 'vitest';++import { getSelectedGalleryImageFromValues } from './selectedImage';++const image: GeneratedImageContract = {+ height: 768,+ imageName: 'selected.png',+ imageUrl: '/selected.png',+ queuedAt: '2026-06-19T00:00:00.000Z',+ sourceQueueItemId: 'queue-item',+ thumbnailUrl: '/selected-thumb.png',+ width: 512,+};++describe('getSelectedGalleryImageFromValues', () => {+ it('normalizes the stored selected image for shared image actions', () => {+ expect(getSelectedGalleryImageFromValues({ selectedBoardId: 'board-1', selectedImage: image })).toMatchObject({+ boardId: 'board-1',+ imageCategory: 'general',+ imageName: 'selected.png',+ starred: false,+ });+ });++ it('falls back to recent images by selected name', () => {+ expect(+ getSelectedGalleryImageFromValues({+ recentImages: [image],+ selectedBoardId: 'board-1',+ selectedImageName: image.imageName,+ })+ )?.toMatchObject({ imageName: 'selected.png' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.tsnew file mode 100644index 0000000000..e2c6812e4c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/selectedImage.ts@@ -0,0 +1,36 @@+import type { GalleryImage } from '@workbench/gallery/api';+import type { GeneratedImageContract, Project } from '@workbench/types';++import { getProjectWidgetValues } from '@workbench/widgetState';++const isGeneratedImage = (value: unknown): value is GeneratedImageContract =>+ Boolean(value) && typeof value === 'object' && typeof (value as GeneratedImageContract).imageName === 'string';++const toGalleryImage = (+ image: GeneratedImageContract & Partial<GalleryImage>,+ galleryValues: Record<string, unknown>+): GalleryImage => ({+ ...image,+ boardId:+ image.boardId ?? (typeof galleryValues.selectedBoardId === 'string' ? galleryValues.selectedBoardId : 'none'),+ imageCategory: image.imageCategory ?? 'general',+ starred: image.starred ?? false,+});++export const getSelectedGalleryImageFromValues = (galleryValues: Record<string, unknown>): GalleryImage | null => {+ if (isGeneratedImage(galleryValues.selectedImage)) {+ return toGalleryImage(galleryValues.selectedImage, galleryValues);+ }++ const selectedImageName =+ typeof galleryValues.selectedImageName === 'string' ? galleryValues.selectedImageName : null;+ const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : [];+ const recentImage = recentImages.find(+ (image): image is GeneratedImageContract => isGeneratedImage(image) && image.imageName === selectedImageName+ );++ return recentImage ? toGalleryImage(recentImage, galleryValues) : null;+};++export const getSelectedGalleryImage = (project: Project): GalleryImage | null =>+ getSelectedGalleryImageFromValues(getProjectWidgetValues(project, 'gallery'));diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 26a17eec95..ba4f38a5f1 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -1,5 +1,4 @@-import type { GenerateModelConfig, VaeModelConfig } from '@workbench/generation/types';-import type { ModelConfig } from '@workbench/models/types';+import type { VaeModelConfig } from '@workbench/generation/types';import type { WorkbenchAction } from '@workbench/workbenchState';import {@@ -13,18 +12,16 @@ import {type GalleryBoard,type GalleryImage,} from '@workbench/gallery/api';-import { getDefaultGenerateSettings, isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';-import { isVaeModelConfig, normalizeGenerateWidgetValues } from '@workbench/generation/settings';+import { isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';+import { isVaeModelConfig } from '@workbench/generation/settings';import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { useEffect, useMemo, type Dispatch } from 'react';+import { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';import {- buildImageRecallSettings,EMPTY_IMAGE_RECALL_CAPABILITIES,getImageRecallCapabilities,- getImageRecallMessage,- getImageRecallTitle,type ImageRecallCapabilities,type ImageRecallKind,} from './imageRecall';@@ -92,22 +89,10 @@ export const useImageActions = ({}): ImageActions => {const openWorkbenchWidget = useOpenWorkbenchWidget();const { models } = useModelsSnapshot();- const supportedModels = useMemo<GenerateModelConfig[]>(() => models.filter(isSupportedGenerateModel), [models]);- const vaeModels = useMemo<VaeModelConfig[]>(- () => models.filter((model: ModelConfig) => isVaeModelConfig(model)).map((model) => model as VaeModelConfig),- [models]- );+ const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);+ const vaeModels = useMemo(() => models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig), [models]);const currentGenerateValues = useMemo(() => {- const normalizedValues = normalizeGenerateWidgetValues(generateValues);-- if (normalizedValues) {- return normalizedValues;- }-- const fallbackModelKey = typeof generateValues.modelKey === 'string' ? generateValues.modelKey : null;- const fallbackModel = supportedModels.find((model) => model.key === fallbackModelKey) ?? supportedModels[0];-- return fallbackModel ? { ...getDefaultGenerateSettings(fallbackModel), model: fallbackModel } : null;+ return getCurrentGenerateValues({ generateValues, supportedModels });}, [generateValues, supportedModels]);useEffect(() => {@@ -118,29 +103,9 @@ export const useImageActions = ({const recordError = (error: unknown) => dispatch({ message: toErrorMessage(error), type: 'recordError' });const recordSuccess = (title: string, message?: string) =>dispatch({ kind: 'success', message, title, type: 'recordNotice' });- const recordInfo = (title: string, message?: string) =>- dispatch({ kind: 'info', message, title, type: 'recordNotice' });const refreshGallery = () => dispatch({ type: 'touchGalleryRefresh' });const refreshGalleryImages = () => dispatch({ type: 'touchGalleryImagesRefresh' });const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';- const imageMetadataRequests = new Map<string, Promise<unknown>>();- const loadImageMetadata = (imageName: string): Promise<unknown> => {- const cachedRequest = imageMetadataRequests.get(imageName);-- if (cachedRequest) {- return cachedRequest;- }-- const request = getGalleryImageMetadata(imageName).catch((error: unknown) => {- imageMetadataRequests.delete(imageName);- throw error;- });-- imageMetadataRequests.set(imageName, request);-- return request;- };-return {copyImage: async (image) => {try {@@ -201,7 +166,7 @@ export const useImageActions = ({}try {- const metadata = await loadImageMetadata(image.imageName);+ const metadata = await getGalleryImageMetadata(image.imageName);return getImageRecallCapabilities({currentValues: currentGenerateValues,@@ -242,32 +207,10 @@ export const useImageActions = ({openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });},recallImageData: async (image, kind) => {- try {- if (!currentGenerateValues) {- recordInfo('Cannot recall image data', 'Select a supported Generate model first.');- return;- }+ const didRecall = await executeImageRecall({ dispatch, generateValues, image, kind, models });- const metadata = kind === 'dimensions' ? null : await loadImageMetadata(image.imageName);- const result = buildImageRecallSettings({- currentValues: currentGenerateValues,- image,- kind,- metadata,- models,- supportedModels,- vaeModels,- });-- if (!result) {- recordInfo('No recallable image data', 'This image does not include supported Generate metadata.');- return;- }-- dispatch({ type: 'setGenerateSettings', values: result.values });- recordSuccess(getImageRecallTitle(kind), getImageRecallMessage(result.fields));- } catch (error: unknown) {- recordError(error);+ if (didRecall) {+ openWorkbenchWidget('generate', { preferredRegions: ['left'] });}},selectForCompare: (image) => {@@ -289,6 +232,7 @@ export const useImageActions = ({boards,currentGenerateValues,dispatch,+ generateValues,models,onImagesDeleted,onStarredChange,