Skip to content

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.

feat(canvas): add typed gallery image imports

joshistoast81ca358dce36
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
index 4ce46f535c..44bbb4210d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
@@ -70,3 +70,8 @@ export interface CanvasOperationCapability {
}
export type { CommitRasterFilterResult };
+export {
+ importGalleryImagesToCanvas,
+ type GalleryCanvasImportDestination,
+ type ImportGalleryImagesResult,
+} from './importGalleryImages';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
new file mode 100644
index 0000000000..5cf1616544
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -0,0 +1,596 @@
+import type { CanvasEngine } from '@workbench/canvas-engine/engine';
+import type { uploadCanvasImage } from '@workbench/canvas-operations/backend/canvasImages';
+import type { GalleryImage } from '@workbench/gallery/api';
+import type { GenerateWidgetValues } from '@workbench/generation/types';
+import type { CanvasLayerContract, Project, WorkbenchState } from '@workbench/types';
+
+import {
+ createControlLayer,
+ createEmptyPaintLayer,
+ createInpaintMaskFromImage,
+ createRegionalGuidanceFromImage,
+ createRegionalGuidanceLayerWithRefImage,
+ DEFAULT_INPAINT_MASK_FILL,
+ nextRegionalGuidanceFillColor,
+} from '@workbench/widgets/layers/layerOps';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { createInitialWorkbenchState, type WorkbenchAction } from '@workbench/workbenchState';
+import { describe, expect, it, vi } from 'vitest';
+
+import { importGalleryImagesToCanvas, type GalleryCanvasImportDestination } from './importGalleryImages';
+
+const image = (imageName: string, width = 320, height = 160): GalleryImage => ({
+ boardId: 'none',
+ height,
+ imageCategory: 'general',
+ imageName,
+ imageUrl: `https://images.example/${imageName}`,
+ queuedAt: '2026-01-01T00:00:00.000Z',
+ sourceQueueItemId: 'queue-1',
+ starred: false,
+ thumbnailUrl: `https://images.example/thumb/${imageName}`,
+ width,
+});
+
+const withProject = (mutate?: (project: Project) => Project): { project: Project; state: WorkbenchState } => {
+ const state = createInitialWorkbenchState();
+ const current = state.projects.find((candidate) => candidate.id === state.activeProjectId)!;
+ const document = {
+ ...current.canvas.document,
+ bbox: { height: 512, width: 768, x: 31, y: 47 },
+ layers: [createEmptyPaintLayer('Existing', 'previous')],
+ selectedLayerId: 'previous',
+ };
+ const base = { ...current, canvas: { ...current.canvas, document } };
+ const project = mutate ? mutate(base) : base;
+ return { project, state: { ...state, projects: [project] } };
+};
+
+const setModel = (project: Project, base: GenerateWidgetValues['model']['base']): Project => {
+ const generate = project.widgetInstances.generate;
+ if (!generate) {
+ throw new Error('Expected generate widget');
+ }
+ const previous = getProjectWidgetValues(project, 'generate');
+ const model = { base, key: 'test-model', name: 'Test Model', type: 'main' } as GenerateWidgetValues['model'];
+ const values: GenerateWidgetValues = {
+ aspectRatioId: '1:1',
+ aspectRatioIsLocked: false,
+ aspectRatioValue: 1,
+ batchCount: 1,
+ cfgRescaleMultiplier: 0,
+ cfgScale: 7,
+ clipEmbedModel: null,
+ clipGEmbedModel: null,
+ clipLEmbedModel: null,
+ clipSkip: 0,
+ colorCompensation: false,
+ componentSourceModel: null,
+ height: 1024,
+ loras: [],
+ negativePrompt: '',
+ negativePromptEnabled: true,
+ negativePromptHeightPx: 56,
+ positivePrompt: '',
+ positivePromptHeightPx: 96,
+ qwen3EncoderModel: null,
+ qwenVLEncoderModel: null,
+ referenceImages: [],
+ scheduler: 'euler_a',
+ seamlessXAxis: false,
+ seamlessYAxis: false,
+ seed: 1,
+ shouldRandomizeSeed: true,
+ steps: 30,
+ t5EncoderModel: null,
+ vae: null,
+ vaePrecision: 'fp32',
+ width: 1024,
+ ...previous,
+ model,
+ modelKey: model.key,
+ };
+ return {
+ ...project,
+ widgetInstances: {
+ ...project.widgetInstances,
+ generate: {
+ ...generate,
+ state: { ...generate.state, values: values as unknown as Record<string, unknown> },
+ },
+ },
+ };
+};
+
+const engine = (
+ projectId: string,
+ canCommitStructural: CanvasEngine['layers']['canCommitStructural'] = vi.fn(() => true),
+ commitStructural: CanvasEngine['layers']['commitStructural'] = vi.fn(() => true)
+): CanvasEngine => ({ layers: { canCommitStructural, commitStructural }, projectId }) as unknown as CanvasEngine;
+
+const getForwardLayers = (action: WorkbenchAction): readonly CanvasLayerContract[] => {
+ if (action.type !== 'applyCanvasLayerStackMutation' || !action.add) {
+ throw new Error('Expected add stack mutation');
+ }
+ return action.add.layers;
+};
+
+const expectedLayer = (
+ destination: Exclude<GalleryCanvasImportDestination, 'control-resized'>,
+ source: GalleryImage,
+ index: number,
+ bbox: Project['canvas']['document']['bbox'],
+ base: string | null
+): CanvasLayerContract => {
+ const ref = { height: source.height, imageName: source.imageName, width: source.width };
+ switch (destination) {
+ case 'raster':
+ return {
+ blendMode: 'normal',
+ id: expect.any(String) as string,
+ isEnabled: true,
+ isLocked: false,
+ name: `Layer ${index + 1}`,
+ opacity: 1,
+ source: { image: ref, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: bbox.x, y: bbox.y },
+ type: 'raster',
+ };
+ case 'control':
+ return {
+ ...createControlLayer(`Control Layer ${index + 1}`, 'expected', base),
+ id: expect.any(String) as string,
+ source: { image: ref, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: bbox.x, y: bbox.y },
+ };
+ case 'inpaint-mask':
+ return createInpaintMaskFromImage({
+ fill: DEFAULT_INPAINT_MASK_FILL,
+ id: expect.any(String) as string,
+ image: ref,
+ name: `Inpaint Mask ${index + 1}`,
+ rect: bbox,
+ });
+ case 'regional-guidance':
+ return createRegionalGuidanceFromImage({
+ fill: { color: nextRegionalGuidanceFillColor(index), style: 'solid' },
+ id: expect.any(String) as string,
+ image: ref,
+ name: `Regional Guidance ${index + 1}`,
+ rect: bbox,
+ });
+ case 'regional-reference': {
+ const layer = createRegionalGuidanceLayerWithRefImage(`Regional Guidance ${index + 1}`, index, base);
+ const reference = layer.referenceImages[0]!;
+ return {
+ ...layer,
+ id: expect.any(String) as string,
+ referenceImages: [
+ { ...reference, config: { ...reference.config, image: source }, id: expect.any(String) as string },
+ ],
+ };
+ }
+ }
+};
+
+describe('importGalleryImagesToCanvas', () => {
+ it.each<Exclude<GalleryCanvasImportDestination, 'control-resized'>>([
+ 'raster',
+ 'control',
+ 'inpaint-mask',
+ 'regional-guidance',
+ 'regional-reference',
+ ])('builds the %s destination contract in input order and commits one history entry', async (destination) => {
+ const { project, state } = withProject((value) => setModel(value, 'z-image'));
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const canvasEngine = engine(project.id);
+ const images = [image('first.png'), image('second.png', 640, 480)];
+
+ const result = await importGalleryImagesToCanvas({
+ destination,
+ dispatch,
+ engine: canvasEngine,
+ getState: () => state,
+ images,
+ project,
+ });
+
+ expect(result.status).toBe('imported');
+ if (result.status !== 'imported') {
+ return;
+ }
+ expect(result.failedImageNames).toEqual([]);
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(canvasEngine.layers.commitStructural).toHaveBeenCalledOnce();
+ const [, forward, inverse] = vi.mocked(canvasEngine.layers.commitStructural).mock.calls[0]!;
+ const layers = getForwardLayers(forward);
+ expect(layers).toEqual(
+ images.map((source, index) => expectedLayer(destination, source, index, project.canvas.document.bbox, 'z-image'))
+ );
+ expect(result.layerIds).toEqual(layers.map((layer) => layer.id));
+ expect(forward).toMatchObject({
+ add: { index: 0 },
+ enabledUpdates: [],
+ projectId: project.id,
+ selectedLayerId: layers[1]!.id,
+ type: 'applyCanvasLayerStackMutation',
+ });
+ expect(inverse).toEqual({
+ enabledUpdates: [],
+ projectId: project.id,
+ removeIds: layers.map((layer) => layer.id),
+ selectedLayerId: 'previous',
+ type: 'applyCanvasLayerStackMutation',
+ });
+ });
+
+ it('fetches and uploads each resized control once with optimal model dimensions and durable hidden policy', async () => {
+ const { project, state } = withProject((value) => setModel(value, 'flux2'));
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const fetchImage = vi.fn<typeof fetch>(() => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })));
+ const uploadImage = vi.fn<typeof uploadCanvasImage>((_blob, options) =>
+ Promise.resolve({
+ height: options!.resizeTo!.height,
+ imageName: `resized-${options!.fileName}`,
+ width: options!.resizeTo!.width,
+ })
+ );
+
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch,
+ engine: null,
+ fetchImage,
+ getState: () => state,
+ images: [image('wide.png', 1600, 900), image('square.png', 400, 400)],
+ project,
+ uploadImage,
+ });
+
+ expect(result.status).toBe('imported');
+ expect(fetchImage.mock.calls.map(([url]) => url)).toEqual([
+ 'https://images.example/wide.png',
+ 'https://images.example/square.png',
+ ]);
+ expect(uploadImage).toHaveBeenCalledTimes(2);
+ expect(uploadImage.mock.calls.map(([, options]) => options)).toEqual([
+ expect.objectContaining({
+ fileName: 'wide.png',
+ imageCategory: 'other',
+ isIntermediate: false,
+ resizeTo: { height: 768, width: 1360 },
+ }),
+ expect.objectContaining({
+ fileName: 'square.png',
+ imageCategory: 'other',
+ isIntermediate: false,
+ resizeTo: { height: 1024, width: 1024 },
+ }),
+ ]);
+ expect(dispatch).toHaveBeenCalledOnce();
+ const forward = dispatch.mock.calls[0]![0];
+ const layers = getForwardLayers(forward);
+ expect(layers).toEqual([
+ {
+ ...createControlLayer('Control Layer 1', 'expected', 'flux2'),
+ id: expect.any(String),
+ source: { image: { height: 768, imageName: 'resized-wide.png', width: 1360 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 31, y: 47 },
+ },
+ {
+ ...createControlLayer('Control Layer 2', 'expected', 'flux2'),
+ id: expect.any(String),
+ source: { image: { height: 1024, imageName: 'resized-square.png', width: 1024 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 31, y: 47 },
+ },
+ ]);
+ expect(
+ layers.map((layer) => (layer.type === 'control' && layer.source.type === 'image' ? layer.source.image : null))
+ ).toEqual([
+ { height: 768, imageName: 'resized-wide.png', width: 1360 },
+ { height: 1024, imageName: 'resized-square.png', width: 1024 },
+ ]);
+ expect(forward).toMatchObject({
+ projectId: project.id,
+ selectedLayerId: layers[1]!.id,
+ type: 'applyCanvasLayerStackMutation',
+ });
+ });
+
+ it('returns empty without committing', async () => {
+ const { project, state } = withProject();
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const result = await importGalleryImagesToCanvas({
+ destination: 'raster',
+ dispatch,
+ engine: null,
+ getState: () => state,
+ images: [],
+ project,
+ });
+ expect(result).toEqual({ status: 'empty' });
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('blocks a locked matching engine before resized preprocessing', async () => {
+ const { project, state } = withProject();
+ const fetchImage = vi.fn<typeof fetch>();
+ const uploadImage = vi.fn<typeof uploadCanvasImage>();
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch: vi.fn(),
+ engine: engine(
+ project.id,
+ vi.fn(() => false)
+ ),
+ fetchImage,
+ getState: () => state,
+ images: [image('a.png')],
+ project,
+ uploadImage,
+ });
+ expect(result).toEqual({ status: 'blocked' });
+ expect(fetchImage).not.toHaveBeenCalled();
+ expect(uploadImage).not.toHaveBeenCalled();
+ });
+
+ it('returns blocked when the matching engine locks during preprocessing', async () => {
+ const { project, state } = withProject();
+ const fetchImage = vi.fn<typeof fetch>(() => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })));
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() =>
+ Promise.resolve({ height: 512, imageName: 'resized', width: 512 })
+ );
+ const commitStructural = vi.fn<(_label: string, _forward: WorkbenchAction, _inverse: WorkbenchAction) => boolean>(
+ () => false
+ );
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch: vi.fn(),
+ engine: engine(
+ project.id,
+ vi.fn(() => true),
+ commitStructural
+ ),
+ fetchImage,
+ getState: () => state,
+ images: [image('a.png')],
+ project,
+ uploadImage,
+ });
+ expect(result).toEqual({ status: 'blocked' });
+ expect(commitStructural).toHaveBeenCalledOnce();
+ const [, forward, inverse] = commitStructural.mock.calls[0]!;
+ const layers = getForwardLayers(forward);
+ expect(inverse).toEqual({
+ enabledUpdates: [],
+ projectId: project.id,
+ removeIds: layers.map((layer) => layer.id),
+ selectedLayerId: 'previous',
+ type: 'applyCanvasLayerStackMutation',
+ });
+ });
+
+ it('returns stale-project when the target is deleted during preprocessing', async () => {
+ const { project, state } = withProject();
+ let current = state;
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {
+ current = { ...current, projects: [] };
+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });
+ });
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch,
+ engine: null,
+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),
+ getState: () => current,
+ images: [image('a.png')],
+ project,
+ uploadImage,
+ });
+ expect(result).toEqual({ status: 'stale-project' });
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('dispatches to the captured project when the active project changes during preprocessing', async () => {
+ const { project, state } = withProject();
+ const other = { ...project, id: 'other-project' };
+ let current = { ...state, projects: [project, other] };
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const matchingEngine = engine(project.id);
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {
+ current = { ...current, activeProjectId: other.id };
+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });
+ });
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch,
+ engine: matchingEngine,
+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),
+ getState: () => current,
+ images: [image('a.png')],
+ project,
+ uploadImage,
+ });
+ expect(result.status).toBe('imported');
+ expect(matchingEngine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledOnce();
+ expect(dispatch.mock.calls[0]![0]).toMatchObject({ projectId: project.id });
+ });
+
+ it('uses the matching engine final guard when the target project becomes active during preprocessing', async () => {
+ const { project, state } = withProject();
+ const other = { ...project, id: 'other-project' };
+ let current = { ...state, activeProjectId: other.id, projects: [project, other] };
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const commitStructural = vi.fn(() => false);
+ const matchingEngine = engine(
+ project.id,
+ vi.fn(() => true),
+ commitStructural
+ );
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {
+ current = { ...current, activeProjectId: project.id };
+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });
+ });
+
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch,
+ engine: matchingEngine,
+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),
+ getState: () => current,
+ images: [image('a.png')],
+ project,
+ uploadImage,
+ });
+
+ expect(result).toEqual({ status: 'blocked' });
+ expect(commitStructural).toHaveBeenCalledOnce();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('returns stale-document when the captured target document identity changes', async () => {
+ const { project, state } = withProject();
+ let current = state;
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {
+ current = {
+ ...current,
+ projects: current.projects.map((candidate) =>
+ candidate.id === project.id
+ ? { ...candidate, canvas: { ...candidate.canvas, document: { ...candidate.canvas.document } } }
+ : candidate
+ ),
+ };
+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });
+ });
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const result = await importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch,
+ engine: null,
+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),
+ getState: () => current,
+ images: [image('a.png')],
+ project,
+ uploadImage,
+ });
+ expect(result).toEqual({ status: 'stale-document' });
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('single-flights imports per project while allowing other projects', async () => {
+ const first = withProject();
+ const secondProject = { ...first.project, id: 'second-project' };
+ const secondState = { ...first.state, activeProjectId: secondProject.id, projects: [secondProject] };
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const fetchImage = vi.fn<typeof fetch>(async () => {
+ await pending;
+ return new Response(new Blob(['pixels']), { status: 200 });
+ });
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() =>
+ Promise.resolve({ height: 512, imageName: 'resized', width: 512 })
+ );
+ const firstImport = importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch: vi.fn(),
+ engine: null,
+ fetchImage,
+ getState: () => first.state,
+ images: [image('a.png')],
+ project: first.project,
+ uploadImage,
+ });
+ const overlap = await importGalleryImagesToCanvas({
+ destination: 'raster',
+ dispatch: vi.fn(),
+ engine: null,
+ getState: () => first.state,
+ images: [image('b.png')],
+ project: first.project,
+ });
+ const independent = await importGalleryImagesToCanvas({
+ destination: 'raster',
+ dispatch: vi.fn(),
+ engine: null,
+ getState: () => secondState,
+ images: [image('c.png')],
+ project: secondProject,
+ });
+ expect(overlap).toEqual({ status: 'blocked' });
+ expect(independent.status).toBe('imported');
+ release();
+ await firstImport;
+ });
+
+ it('bounds resized work at four, preserves successful order, and reports partial failures once', async () => {
+ const { project, state } = withProject();
+ let active = 0;
+ let maximum = 0;
+ const releases: Array<() => void> = [];
+ const fetchImage = vi.fn<typeof fetch>(async (_input) => {
+ active += 1;
+ maximum = Math.max(maximum, active);
+ await new Promise<void>((resolve) => {
+ releases.push(resolve);
+ });
+ active -= 1;
+ return new Response(new Blob(['pixels']), { status: 200 });
+ });
+ const uploadImage = vi.fn<typeof uploadCanvasImage>((_blob, options) => {
+ if (options!.fileName === '2.png' || options!.fileName === '5.png') {
+ return Promise.reject(new Error('resize failed'));
+ }
+ return Promise.resolve({ height: 512, imageName: `ok-${options!.fileName}`, width: 512 });
+ });
+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();
+ const importing = importGalleryImagesToCanvas({
+ destination: 'control-resized',
+ dispatch,
+ engine: null,
+ fetchImage,
+ getState: () => state,
+ images: Array.from({ length: 7 }, (_, index) => image(`${index}.png`)),
+ project,
+ uploadImage,
+ });
+ await vi.waitFor(() => expect(fetchImage).toHaveBeenCalledTimes(4));
+ expect(maximum).toBe(4);
+ releases.splice(0).forEach((resolve) => resolve());
+ await vi.waitFor(() => expect(fetchImage).toHaveBeenCalledTimes(7));
+ releases.splice(0).forEach((resolve) => resolve());
+ const result = await importing;
+ expect(result.status).toBe('imported');
+ if (result.status !== 'imported') {
+ return;
+ }
+ expect(result.failedImageNames).toEqual(['2.png', '5.png']);
+ expect(dispatch).toHaveBeenCalledOnce();
+ expect(
+ getForwardLayers(dispatch.mock.calls[0]![0]).map((layer) =>
+ layer.type === 'control' && layer.source.type === 'image' ? layer.source.image.imageName : null
+ )
+ ).toEqual(['ok-0.png', 'ok-1.png', 'ok-3.png', 'ok-4.png', 'ok-6.png']);
+ });
+
+ it('throws one AggregateError when every resized image fails and releases the project flight', async () => {
+ const { project, state } = withProject();
+ const options = {
+ destination: 'control-resized' as const,
+ dispatch: vi.fn(),
+ engine: null,
+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),
+ getState: () => state,
+ images: [image('a.png'), image('b.png')],
+ project,
+ uploadImage: vi.fn<typeof uploadCanvasImage>(() => Promise.reject(new Error('failed'))),
+ };
+ await expect(importGalleryImagesToCanvas(options)).rejects.toBeInstanceOf(AggregateError);
+ await expect(importGalleryImagesToCanvas({ ...options, destination: 'raster' })).resolves.toMatchObject({
+ status: 'imported',
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
new file mode 100644
index 0000000000..f3400b42e5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
@@ -0,0 +1,299 @@
+import type { CanvasEngine } from '@workbench/canvas-engine/engine';
+import type { GalleryImage } from '@workbench/gallery/api';
+import type { CanvasImageRef, CanvasLayerContract, Project, WorkbenchState } from '@workbench/types';
+import type { WorkbenchAction } from '@workbench/workbenchState';
+import type { Dispatch } from 'react';
+
+import { getGenerationDimensions } from '@workbench/generation/baseGenerationPolicies';
+import { calculateNewSize, normalizeGenerateWidgetValues } from '@workbench/generation/settings';
+import {
+ createControlLayer,
+ createEmptyPaintLayer,
+ createInpaintMaskFromImage,
+ createLayerId,
+ createRegionalGuidanceFromImage,
+ createRegionalGuidanceLayerWithRefImage,
+ DEFAULT_INPAINT_MASK_FILL,
+ nextControlLayerName,
+ nextInpaintMaskName,
+ nextRegionalGuidanceFillColor,
+ nextRegionalGuidanceName,
+} from '@workbench/widgets/layers/layerOps';
+import { getSelectedModelBase } from '@workbench/widgets/layers/selectedModel';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { nextLayerName } from '@workbench/workbenchState';
+
+import { uploadCanvasImage } from './backend/canvasImages';
+
+export type GalleryCanvasImportDestination =
+ | 'raster'
+ | 'control'
+ | 'inpaint-mask'
+ | 'regional-guidance'
+ | 'regional-reference'
+ | 'control-resized';
+
+export type ImportGalleryImagesResult =
+ | { status: 'imported'; layerIds: string[]; failedImageNames: string[] }
+ | { status: 'blocked' | 'empty' | 'stale-document' | 'stale-project' };
+
+interface BuildLayerContext {
+ bbox: Project['canvas']['document']['bbox'];
+ existingLayers: readonly CanvasLayerContract[];
+ modelBase: string | null;
+}
+
+type LayerImage = CanvasImageRef | GalleryImage;
+
+const activeImports = new Set<string>();
+
+const imageRef = (image: LayerImage): CanvasImageRef => ({
+ height: image.height,
+ imageName: image.imageName,
+ width: image.width,
+});
+
+const isGeneratedImage = (image: LayerImage): image is GalleryImage => 'imageUrl' in image;
+
+const withBboxOrigin = <T extends CanvasLayerContract>(layer: T, bbox: BuildLayerContext['bbox']): T => ({
+ ...layer,
+ transform: { ...layer.transform, x: bbox.x, y: bbox.y },
+});
+
+const buildLayer = (
+ image: LayerImage,
+ destination: GalleryCanvasImportDestination,
+ context: BuildLayerContext
+): CanvasLayerContract => {
+ const id = createLayerId();
+ const names = context.existingLayers.map((layer) => layer.name);
+ const ref = imageRef(image);
+
+ switch (destination) {
+ case 'raster':
+ return withBboxOrigin(
+ { ...createEmptyPaintLayer(nextLayerName(names), id), source: { image: ref, type: 'image' } },
+ context.bbox
+ );
+ case 'control':
+ case 'control-resized':
+ return withBboxOrigin(
+ {
+ ...createControlLayer(nextControlLayerName(names), id, context.modelBase),
+ source: { image: ref, type: 'image' },
+ },
+ context.bbox
+ );
+ case 'inpaint-mask':
+ return createInpaintMaskFromImage({
+ fill: DEFAULT_INPAINT_MASK_FILL,
+ id,
+ image: ref,
+ name: nextInpaintMaskName(names),
+ rect: context.bbox,
+ });
+ case 'regional-guidance': {
+ const regionalGuidanceCount = context.existingLayers.filter((layer) => layer.type === 'regional_guidance').length;
+ return createRegionalGuidanceFromImage({
+ fill: { color: nextRegionalGuidanceFillColor(regionalGuidanceCount), style: 'solid' },
+ id,
+ image: ref,
+ name: nextRegionalGuidanceName(names),
+ rect: context.bbox,
+ });
+ }
+ case 'regional-reference': {
+ const regionalGuidanceCount = context.existingLayers.filter((layer) => layer.type === 'regional_guidance').length;
+ const layer = createRegionalGuidanceLayerWithRefImage(
+ nextRegionalGuidanceName(names),
+ regionalGuidanceCount,
+ context.modelBase,
+ id
+ );
+ const referenceImage = layer.referenceImages[0];
+ if (!referenceImage) {
+ throw new Error('Regional reference factory did not create a reference image');
+ }
+ if (!isGeneratedImage(image)) {
+ throw new Error('Regional reference imports require a gallery image');
+ }
+ return {
+ ...layer,
+ referenceImages: [{ ...referenceImage, config: { ...referenceImage.config, image } }],
+ };
+ }
+ }
+};
+
+const buildLayers = (
+ images: readonly LayerImage[],
+ destination: GalleryCanvasImportDestination,
+ project: Project
+): CanvasLayerContract[] => {
+ const layers: CanvasLayerContract[] = [];
+ const modelBase = getSelectedModelBase(project);
+ for (const image of images) {
+ layers.push(
+ buildLayer(image, destination, {
+ bbox: project.canvas.document.bbox,
+ existingLayers: [...project.canvas.document.layers, ...layers],
+ modelBase,
+ })
+ );
+ }
+ return layers;
+};
+
+const mapWithConcurrency = async <T, R>(
+ items: readonly T[],
+ concurrency: number,
+ mapper: (item: T, index: number) => Promise<R>
+): Promise<R[]> => {
+ const results: R[] = [];
+ let nextIndex = 0;
+ const worker = async (): Promise<void> => {
+ while (nextIndex < items.length) {
+ const index = nextIndex;
+ nextIndex += 1;
+ results[index] = await mapper(items[index]!, index);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
+ return results;
+};
+
+type ResizeResult =
+ | { status: 'fulfilled'; image: LayerImage }
+ | { status: 'rejected'; imageName: string; reason: unknown };
+
+const resizeImages = async (
+ images: readonly GalleryImage[],
+ project: Project,
+ fetchImage: typeof fetch,
+ uploadImage: typeof uploadCanvasImage
+): Promise<{ images: LayerImage[]; failedImageNames: string[] }> => {
+ const generateValues = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'));
+ const dimensions = getGenerationDimensions(generateValues?.model);
+ const results = await mapWithConcurrency(images, 4, async (image): Promise<ResizeResult> => {
+ try {
+ const response = await fetchImage(image.imageUrl);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch ${image.imageName}: ${response.status} ${response.statusText}`);
+ }
+ const blob = await response.blob();
+ const resizeTo = calculateNewSize(image.width / image.height, dimensions.optimal ** 2, dimensions.grid);
+ const uploaded = await uploadImage(blob, {
+ fileName: image.imageName,
+ imageCategory: 'other',
+ isIntermediate: false,
+ resizeTo,
+ });
+ return { image: uploaded, status: 'fulfilled' };
+ } catch (reason) {
+ return { imageName: image.imageName, reason, status: 'rejected' };
+ }
+ });
+ const successful = results.filter(
+ (result): result is Extract<ResizeResult, { status: 'fulfilled' }> => result.status === 'fulfilled'
+ );
+ const failed = results.filter(
+ (result): result is Extract<ResizeResult, { status: 'rejected' }> => result.status === 'rejected'
+ );
+ if (successful.length === 0 && failed.length > 0) {
+ throw new AggregateError(
+ failed.map((result) => result.reason),
+ `Failed to resize ${String(failed.length)} gallery image${failed.length === 1 ? '' : 's'}`
+ );
+ }
+ return {
+ failedImageNames: failed.map((result) => result.imageName),
+ images: successful.map((result) => result.image),
+ };
+};
+
+export const importGalleryImagesToCanvas = async (options: {
+ destination: GalleryCanvasImportDestination;
+ dispatch: Dispatch<WorkbenchAction>;
+ engine: CanvasEngine | null;
+ getState: () => WorkbenchState;
+ images: readonly GalleryImage[];
+ project: Project;
+ fetchImage?: typeof fetch;
+ uploadImage?: typeof uploadCanvasImage;
+}): Promise<ImportGalleryImagesResult> => {
+ const {
+ destination,
+ dispatch,
+ engine,
+ fetchImage = globalThis.fetch,
+ getState,
+ images,
+ project,
+ uploadImage = uploadCanvasImage,
+ } = options;
+ if (images.length === 0) {
+ return { status: 'empty' };
+ }
+ if (activeImports.has(project.id)) {
+ return { status: 'blocked' };
+ }
+ activeImports.add(project.id);
+
+ try {
+ const capturedDocument = project.canvas.document;
+ const initialState = getState();
+ const matchingProjectEngine = engine !== null && engine.projectId === project.id ? engine : null;
+ if (
+ matchingProjectEngine &&
+ initialState.activeProjectId === project.id &&
+ !matchingProjectEngine.layers.canCommitStructural()
+ ) {
+ return { status: 'blocked' };
+ }
+
+ let layerImages: readonly LayerImage[] = images;
+ let failedImageNames: string[] = [];
+ if (destination === 'control-resized') {
+ const resized = await resizeImages(images, project, fetchImage, uploadImage);
+ layerImages = resized.images;
+ failedImageNames = resized.failedImageNames;
+ }
+
+ const layers = buildLayers(layerImages, destination, project);
+ const previousSelectedLayerId = capturedDocument.selectedLayerId;
+ const forward: WorkbenchAction = {
+ add: { index: 0, layers },
+ enabledUpdates: [],
+ projectId: project.id,
+ selectedLayerId: layers.at(-1)?.id ?? previousSelectedLayerId,
+ type: 'applyCanvasLayerStackMutation',
+ };
+ const inverse: WorkbenchAction = {
+ enabledUpdates: [],
+ projectId: project.id,
+ removeIds: layers.map((layer) => layer.id),
+ selectedLayerId: previousSelectedLayerId,
+ type: 'applyCanvasLayerStackMutation',
+ };
+
+ const latestState = getState();
+ const latestProject = latestState.projects.find((candidate) => candidate.id === project.id);
+ if (!latestProject) {
+ return { status: 'stale-project' };
+ }
+ if (latestProject.canvas.document !== capturedDocument) {
+ return { status: 'stale-document' };
+ }
+
+ if (matchingProjectEngine && latestState.activeProjectId === project.id) {
+ if (!matchingProjectEngine.layers.commitStructural('Import gallery images', forward, inverse)) {
+ return { status: 'blocked' };
+ }
+ } else {
+ dispatch(forward);
+ }
+ return { failedImageNames, layerIds: layers.map((layer) => layer.id), status: 'imported' };
+ } finally {
+ activeImports.delete(project.id);
+ }
+};