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(webv2): add Create From Bbox canvas context menu

joshistoasta37b90e18d1e
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 5ef8c25b5a..00ab025391 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1220,8 +1220,18 @@
"undo": "Undo canvas edit"
},
"contextMenu": {
+ "createError": "Couldn't create from BBox",
+ "createFromBbox": "Create From BBox",
+ "createdFromBbox": "Added {{destination}} from BBox",
"empty": "This region has no visible raster content.",
+ "newControlLayer": "New Control Layer",
+ "newGlobalReferenceImage": "New Global Reference Image",
+ "newRasterLayer": "New Raster Layer",
+ "newRegionalReferenceImage": "New Regional Reference Image",
"notReady": "The canvas is still preparing image data.",
+ "referenceImageAdded": "Added reference image",
+ "referenceImageFull": "The selected model can't accept more reference images.",
+ "referenceImageUnsupported": "The selected model doesn't support reference images.",
"saveBboxToGallery": "Save BBox to Gallery",
"saveCanvasToGallery": "Save Canvas to Gallery",
"saveError": "Couldn't save to gallery",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
index c0c9bafb14..42f32d44c7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
@@ -16,6 +16,13 @@ export {
type ImportGalleryImagesResult,
} from './importGalleryImages';
export { getCanvasImportNotice } from './canvasImportNotice';
+export {
+ createFromBbox,
+ type CreateFromBboxDestination,
+ type CreateFromBboxLayerDestination,
+ type CreateFromBboxResult,
+} from './createFromBbox';
+export { getCreateFromBboxNotice, type CreateFromBboxNotice } from './createFromBboxNotice';
export type {
FilterOperationSessionState,
SamInput,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
new file mode 100644
index 0000000000..c8ef5a0b60
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
@@ -0,0 +1,244 @@
+import type { GalleryImage } from '@features/gallery';
+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { CanvasEngine } from '@workbench/canvas-engine/engine';
+import type { RasterCompositeExportResult } from '@workbench/canvas-engine/exportRasterComposite';
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { Project, WorkbenchState } from '@workbench/projectContracts';
+
+import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { uploadCanvasImage } from './backend/canvasImages';
+
+import { createFromBbox, type CreateFromBboxDestination } from './createFromBbox';
+
+const bbox = { height: 512, width: 768, x: 31, y: 47 };
+const uploadedName = 'bbox-upload.png';
+const defaultBlob = new Blob(['pixels'], { type: 'image/png' });
+
+const galleryImage: GalleryImage = {
+ boardId: 'none',
+ height: bbox.height,
+ imageCategory: 'other',
+ imageName: uploadedName,
+ imageUrl: `https://images.example/${uploadedName}`,
+ queuedAt: '2026-01-01T00:00:00.000Z',
+ sourceQueueItemId: 'queue-1',
+ starred: false,
+ thumbnailUrl: `https://images.example/thumb/${uploadedName}`,
+ width: bbox.width,
+};
+
+const withProject = (): { project: Project; state: WorkbenchState } => {
+ const state = createInitialWorkbenchState();
+ const current = state.projects.find((candidate) => candidate.id === state.activeProjectId)!;
+ const document = {
+ ...current.canvas.document,
+ bbox,
+ layers: [createEmptyPaintLayer('Existing', 'previous')],
+ selectedLayerId: 'previous',
+ };
+ const project = { ...current, canvas: { ...current.canvas, document } };
+ return { project, state: { ...state, projects: [project] } };
+};
+
+const createHarness = (
+ options: {
+ canCommitStructural?: boolean;
+ exportResult?: RasterCompositeExportResult;
+ resolved?: GalleryImage[];
+ staleDocument?: boolean;
+ } = {}
+) => {
+ const { project, state } = withProject();
+ const staleState: WorkbenchState = {
+ ...state,
+ projects: state.projects.map((candidate) =>
+ candidate.id === project.id
+ ? { ...candidate, canvas: { ...candidate.canvas, document: { ...candidate.canvas.document } } }
+ : candidate
+ ),
+ };
+ const getState = () => (options.staleDocument ? staleState : state);
+ const order: string[] = [];
+ const exportResult = options.exportResult ?? {
+ blob: defaultBlob,
+ rect: bbox,
+ status: 'ok',
+ };
+ const flushPendingUploads = vi.fn(() => {
+ order.push('flush');
+ return Promise.resolve();
+ });
+ const getDocument = vi.fn(() => {
+ order.push('document');
+ return project.canvas.document as unknown as CanvasDocumentContractV2;
+ });
+ const exportRasterComposite = vi.fn<CanvasEngine['exports']['exportRasterComposite']>(() => {
+ order.push('export');
+ return Promise.resolve(exportResult);
+ });
+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {
+ order.push('upload');
+ return Promise.resolve({ height: bbox.height, imageName: uploadedName, width: bbox.width });
+ });
+ const resolveImages = vi.fn((imageNames: string[]) => {
+ order.push('resolve');
+ expect(imageNames).toEqual([uploadedName]);
+ return Promise.resolve(options.resolved ?? [galleryImage]);
+ });
+ const commitStructural = vi.fn((label: string, forward: CanvasProjectMutation) => {
+ order.push('commit');
+ void label;
+ void forward;
+ return true;
+ });
+ const engine = {
+ document: { getDocument },
+ exports: { exportRasterComposite },
+ layers: {
+ canCommitStructural: vi.fn(() => options.canCommitStructural ?? true),
+ commitStructural,
+ },
+ lifecycle: { flushPendingUploads },
+ projectId: project.id,
+ } as unknown as CanvasEngine;
+ const applyCanvasMutation = vi.fn();
+
+ const run = (destination: CreateFromBboxDestination) =>
+ createFromBbox({
+ applyCanvasMutation,
+ destination,
+ engine,
+ getProject: (projectId) => getState().projects.find((candidate) => candidate.id === projectId) ?? null,
+ isActiveProject: (projectId) => getState().activeProjectId === projectId,
+ project,
+ resolveImages,
+ uploadImage,
+ });
+
+ return {
+ applyCanvasMutation,
+ commitStructural,
+ exportRasterComposite,
+ order,
+ project,
+ resolveImages,
+ run,
+ uploadImage,
+ };
+};
+
+const getCommittedLayers = (harness: ReturnType<typeof createHarness>): readonly CanvasLayerContract[] => {
+ const forward = harness.commitStructural.mock.calls[0]?.[1] as CanvasProjectMutation | undefined;
+ if (forward?.type !== 'applyCanvasLayerStackMutation' || !forward.add) {
+ throw new Error('Expected add stack mutation');
+ }
+ return forward.add.layers;
+};
+
+describe('createFromBbox', () => {
+ it('creates a raster layer at the bbox origin from the uploaded composite', async () => {
+ const harness = createHarness();
+
+ const result = await harness.run('raster');
+
+ expect(harness.order).toEqual(['flush', 'document', 'export', 'upload', 'resolve', 'commit']);
+ expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'rect', rect: bbox });
+ expect(harness.uploadImage).toHaveBeenCalledWith(defaultBlob, {
+ fileName: 'bbox.png',
+ imageCategory: 'other',
+ isIntermediate: false,
+ });
+
+ const layers = getCommittedLayers(harness);
+ expect(layers).toHaveLength(1);
+ expect(layers[0]).toMatchObject({
+ source: { image: { height: bbox.height, imageName: uploadedName, width: bbox.width }, type: 'image' },
+ transform: { x: bbox.x, y: bbox.y },
+ type: 'raster',
+ });
+ expect(result).toEqual({ destination: 'raster', layerIds: [layers[0]!.id], status: 'created' });
+ expect(harness.applyCanvasMutation).not.toHaveBeenCalled();
+ });
+
+ it('creates a control layer sourced from the uploaded composite', async () => {
+ const harness = createHarness();
+
+ const result = await harness.run('control');
+
+ const layers = getCommittedLayers(harness);
+ expect(layers[0]).toMatchObject({
+ source: { image: { imageName: uploadedName }, type: 'image' },
+ transform: { x: bbox.x, y: bbox.y },
+ });
+ expect(result).toMatchObject({ destination: 'control', status: 'created' });
+ });
+
+ it('stores the resolved gallery image on a regional reference layer', async () => {
+ const harness = createHarness();
+
+ const result = await harness.run('regional-reference');
+
+ const layers = getCommittedLayers(harness);
+ const layer = layers[0] as CanvasLayerContract & { referenceImages: { config: { image: unknown } }[] };
+ expect(layer.referenceImages[0]?.config.image).toBe(galleryImage);
+ expect(result).toMatchObject({ destination: 'regional-reference', status: 'created' });
+ });
+
+ it('returns the upload for the global-reference destination without resolving or committing', async () => {
+ const harness = createHarness();
+
+ await expect(harness.run('global-reference')).resolves.toEqual({
+ image: { height: bbox.height, imageName: uploadedName, width: bbox.width },
+ status: 'uploaded',
+ });
+
+ expect(harness.resolveImages).not.toHaveBeenCalled();
+ expect(harness.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it.each(['empty', 'stale', 'not-ready', 'over-budget'] as const)('returns %s without uploading', async (status) => {
+ const harness = createHarness({ exportResult: { status } });
+
+ await expect(harness.run('raster')).resolves.toEqual({ status });
+
+ expect(harness.uploadImage).not.toHaveBeenCalled();
+ });
+
+ it('aborts with stale-document when the canvas changed during export and upload', async () => {
+ const harness = createHarness({ staleDocument: true });
+
+ await expect(harness.run('raster')).resolves.toEqual({ status: 'stale-document' });
+
+ expect(harness.uploadImage).toHaveBeenCalled();
+ expect(harness.commitStructural).not.toHaveBeenCalled();
+ expect(harness.applyCanvasMutation).not.toHaveBeenCalled();
+ });
+
+ it('returns blocked when the engine cannot commit a structural edit', async () => {
+ const harness = createHarness({ canCommitStructural: false });
+
+ await expect(harness.run('raster')).resolves.toEqual({ status: 'blocked' });
+
+ expect(harness.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('propagates upload rejection', async () => {
+ const harness = createHarness();
+ harness.uploadImage.mockRejectedValueOnce(new Error('upload failed'));
+
+ await expect(harness.run('raster')).rejects.toThrow('upload failed');
+
+ expect(harness.resolveImages).not.toHaveBeenCalled();
+ });
+
+ it('throws when the uploaded image cannot be resolved', async () => {
+ const harness = createHarness({ resolved: [] });
+
+ await expect(harness.run('raster')).rejects.toThrow('could not be resolved');
+
+ expect(harness.commitStructural).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
new file mode 100644
index 0000000000..05e7ce8b7a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.ts
@@ -0,0 +1,102 @@
+import type { GalleryImage } from '@features/gallery';
+import type { CanvasLayerCapability } from '@workbench/canvas-engine/api';
+import type { CanvasImageUploadResult } from '@workbench/canvas-engine/document/imageUpload';
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { Project } from '@workbench/projectContracts';
+
+import { galleryImages } from '@features/gallery';
+
+import type { CanvasCompositeExportEngine } from './exportCanvasComposite';
+import type { GalleryCanvasImportDestination } from './importGalleryImages';
+
+import { uploadCanvasImage } from './backend/canvasImages';
+import { exportCanvasComposite } from './exportCanvasComposite';
+import { importGalleryImagesToCanvas } from './importGalleryImages';
+
+export type CreateFromBboxLayerDestination = Extract<
+ GalleryCanvasImportDestination,
+ 'raster' | 'control' | 'regional-reference'
+>;
+
+export type CreateFromBboxDestination = 'global-reference' | CreateFromBboxLayerDestination;
+
+export type CreateFromBboxResult =
+ | { status: 'created'; destination: CreateFromBboxLayerDestination; layerIds: string[] }
+ | { status: 'uploaded'; image: CanvasImageUploadResult }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
+ | { status: 'blocked' | 'stale-document' | 'stale-project' };
+
+type CreateFromBboxEngine = CanvasCompositeExportEngine & {
+ readonly layers: CanvasLayerCapability;
+ readonly projectId: string;
+};
+
+/**
+ * Composites the visible raster layers within the generation bbox, uploads
+ * the PNG as a canvas-owned image, and either hands the upload back for the
+ * global-reference flow or creates the destination layer at the bbox origin
+ * via the shared gallery-import pipeline (which re-checks the document
+ * captured in `project` against the latest state, covering the export/upload
+ * window).
+ */
+export const createFromBbox = async (options: {
+ applyCanvasMutation: (projectId: string, mutation: CanvasProjectMutation) => boolean | void;
+ destination: CreateFromBboxDestination;
+ engine: CreateFromBboxEngine;
+ getProject: (projectId: string) => Project | null;
+ isActiveProject: (projectId: string) => boolean;
+ project: Project;
+ resolveImages?: (imageNames: string[]) => Promise<GalleryImage[]>;
+ uploadImage?: typeof uploadCanvasImage;
+}): Promise<CreateFromBboxResult> => {
+ const {
+ applyCanvasMutation,
+ destination,
+ engine,
+ getProject,
+ isActiveProject,
+ project,
+ resolveImages = galleryImages.resolveMany,
+ uploadImage = uploadCanvasImage,
+ } = options;
+
+ const exported = await exportCanvasComposite(engine, 'bbox');
+ if (exported.status !== 'ok') {
+ return exported;
+ }
+
+ const uploaded = await uploadImage(exported.blob, {
+ fileName: 'bbox.png',
+ imageCategory: 'other',
+ isIntermediate: false,
+ });
+
+ if (destination === 'global-reference') {
+ return { image: uploaded, status: 'uploaded' };
+ }
+
+ const [galleryImage] = await resolveImages([uploaded.imageName]);
+ if (!galleryImage) {
+ throw new Error(`Uploaded bbox composite ${uploaded.imageName} could not be resolved to a gallery image`);
+ }
+
+ const imported = await importGalleryImagesToCanvas({
+ applyCanvasMutation,
+ destination,
+ engine,
+ getProject,
+ images: [galleryImage],
+ isActiveProject,
+ project,
+ });
+
+ if (imported.status === 'imported') {
+ return { destination, layerIds: imported.layerIds, status: 'created' };
+ }
+ if (imported.status === 'empty') {
+ // Unreachable: exactly one image is always passed. Kept for exhaustiveness.
+ return { status: 'blocked' };
+ }
+
+ return imported;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
new file mode 100644
index 0000000000..441be9ff0b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { getCreateFromBboxNotice } from './createFromBboxNotice';
+
+describe('getCreateFromBboxNotice', () => {
+ it.each([
+ ['raster', 'widgets.canvas.import.raster'],
+ ['control', 'widgets.canvas.import.control'],
+ ['regional-reference', 'widgets.canvas.import.regionalReference'],
+ ] as const)('labels a created %s destination with its import label key', (destination, labelKey) => {
+ expect(getCreateFromBboxNotice({ destination, layerIds: ['layer-1'], status: 'created' })).toEqual({
+ kind: 'success',
+ options: { destination: labelKey },
+ titleKey: 'widgets.canvas.contextMenu.createdFromBbox',
+ });
+ });
+
+ it.each([
+ ['empty', 'info', 'widgets.canvas.contextMenu.empty'],
+ ['stale', 'info', 'widgets.canvas.contextMenu.stale'],
+ ['not-ready', 'info', 'widgets.canvas.contextMenu.notReady'],
+ ['over-budget', 'info', 'widgets.canvas.contextMenu.notReady'],
+ ['blocked', 'info', 'widgets.canvas.import.blocked'],
+ ['stale-document', 'error', 'widgets.canvas.import.staleDocument'],
+ ['stale-project', 'error', 'widgets.canvas.import.staleProject'],
+ ] as const)('maps %s to a %s notice', (status, kind, titleKey) => {
+ expect(getCreateFromBboxNotice({ status })).toEqual({ kind, titleKey });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
new file mode 100644
index 0000000000..876a34f5a8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBboxNotice.ts
@@ -0,0 +1,52 @@
+import type { CanvasImportNotice } from './canvasImportNotice';
+import type { CreateFromBboxLayerDestination, CreateFromBboxResult } from './createFromBbox';
+
+import { getCanvasImportNotice } from './canvasImportNotice';
+
+export interface CreateFromBboxNotice {
+ kind: 'error' | 'info' | 'success';
+ titleKey:
+ | CanvasImportNotice['titleKey']
+ | 'widgets.canvas.contextMenu.createdFromBbox'
+ | 'widgets.canvas.contextMenu.empty'
+ | 'widgets.canvas.contextMenu.notReady'
+ | 'widgets.canvas.contextMenu.stale';
+ /** `destination` is itself a translation key naming the created entity. */
+ options?: CanvasImportNotice['options'] | { destination: string };
+}
+
+const DESTINATION_LABEL_KEYS: Record<CreateFromBboxLayerDestination, string> = {
+ control: 'widgets.canvas.import.control',
+ raster: 'widgets.canvas.import.raster',
+ 'regional-reference': 'widgets.canvas.import.regionalReference',
+};
+
+const assertNever = (value: never): never => {
+ throw new Error(`Unhandled create-from-bbox result: ${JSON.stringify(value)}`);
+};
+
+export const getCreateFromBboxNotice = (
+ result: Exclude<CreateFromBboxResult, { status: 'uploaded' }>
+): CreateFromBboxNotice => {
+ switch (result.status) {
+ case 'created':
+ return {
+ kind: 'success',
+ options: { destination: DESTINATION_LABEL_KEYS[result.destination] },
+ titleKey: 'widgets.canvas.contextMenu.createdFromBbox',
+ };
+ case 'empty':
+ return { kind: 'info', titleKey: 'widgets.canvas.contextMenu.empty' };
+ case 'stale':
+ return { kind: 'info', titleKey: 'widgets.canvas.contextMenu.stale' };
+ case 'not-ready':
+ case 'over-budget':
+ return { kind: 'info', titleKey: 'widgets.canvas.contextMenu.notReady' };
+ case 'blocked':
+ case 'stale-document':
+ case 'stale-project':
+ return getCanvasImportNotice({ status: result.status });
+ default:
+ return assertNever(result);
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts
new file mode 100644
index 0000000000..a4364b6cd3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts
@@ -0,0 +1,95 @@
+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
+import type { CanvasEngine } from '@workbench/canvas-engine/engine';
+import type { RasterCompositeExportResult } from '@workbench/canvas-engine/exportRasterComposite';
+import type { Rect } from '@workbench/canvas-engine/types';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { exportCanvasComposite } from './exportCanvasComposite';
+
+const defaultRect: Rect = { height: 456, width: 123, x: -4, y: 8 };
+const defaultBlob = new Blob(['pixels'], { type: 'image/png' });
+
+const createDocument = (bbox: Rect): CanvasDocumentContractV2 => ({ bbox }) as unknown as CanvasDocumentContractV2;
+
+const createHarness = (
+ options: {
+ document?: CanvasDocumentContractV2 | null;
+ exportResult?: RasterCompositeExportResult;
+ onFlush?: () => void;
+ } = {}
+) => {
+ const order: string[] = [];
+ let document = options.document === undefined ? createDocument(defaultRect) : options.document;
+ const exportResult = options.exportResult ?? { blob: defaultBlob, rect: defaultRect, status: 'ok' };
+ const flushPendingUploads = vi.fn(() => {
+ order.push('flush');
+ options.onFlush?.();
+ return Promise.resolve();
+ });
+ const getDocument = vi.fn(() => {
+ order.push('document');
+ return document;
+ });
+ const exportRasterComposite = vi.fn<CanvasEngine['exports']['exportRasterComposite']>(() => {
+ order.push('export');
+ return Promise.resolve(exportResult);
+ });
+ const engine = {
+ document: { getDocument },
+ exports: { exportRasterComposite },
+ lifecycle: { flushPendingUploads },
+ } as unknown as CanvasEngine;
+
+ return {
+ engine,
+ exportRasterComposite,
+ order,
+ setDocument: (next: CanvasDocumentContractV2 | null) => {
+ document = next;
+ },
+ };
+};
+
+describe('exportCanvasComposite', () => {
+ it('flushes pending uploads before reading the document and exporting', async () => {
+ const harness = createHarness();
+
+ await expect(exportCanvasComposite(harness.engine, 'canvas')).resolves.toEqual({
+ blob: defaultBlob,
+ rect: defaultRect,
+ status: 'ok',
+ });
+
+ expect(harness.order).toEqual(['flush', 'document', 'export']);
+ expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'content' });
+ });
+
+ it('exports the post-flush document bbox for the bbox region', async () => {
+ const preFlushRect: Rect = { height: 20, width: 10, x: 0, y: 0 };
+ const postFlushRect: Rect = { height: 40, width: 30, x: 5, y: 6 };
+ let harness: ReturnType<typeof createHarness>;
+ harness = createHarness({
+ document: createDocument(preFlushRect),
+ onFlush: () => harness.setDocument(createDocument(postFlushRect)),
+ });
+
+ await exportCanvasComposite(harness.engine, 'bbox');
+
+ expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'rect', rect: postFlushRect });
+ });
+
+ it('returns not-ready without exporting when there is no post-flush document', async () => {
+ const harness = createHarness({ document: null });
+
+ await expect(exportCanvasComposite(harness.engine, 'bbox')).resolves.toEqual({ status: 'not-ready' });
+
+ expect(harness.exportRasterComposite).not.toHaveBeenCalled();
+ });
+
+ it.each(['empty', 'stale', 'not-ready', 'over-budget'] as const)('passes %s through verbatim', async (status) => {
+ const harness = createHarness({ exportResult: { status } });
+
+ await expect(exportCanvasComposite(harness.engine, 'canvas')).resolves.toEqual({ status });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
new file mode 100644
index 0000000000..927f15b56d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
@@ -0,0 +1,37 @@
+import type {
+ CanvasDocumentCapability,
+ CanvasExportCapability,
+ CanvasLifecycleCapability,
+} from '@workbench/canvas-engine/api';
+import type { Rect } from '@workbench/canvas-engine/types';
+
+export type CanvasCompositeRegion = 'canvas' | 'bbox';
+
+export type ExportCanvasCompositeResult =
+ | { status: 'ok'; blob: Blob; rect: Rect }
+ | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' };
+
+export type CanvasCompositeExportEngine = {
+ readonly document: CanvasDocumentCapability;
+ readonly exports: Pick<CanvasExportCapability, 'exportRasterComposite'>;
+ readonly lifecycle: Pick<CanvasLifecycleCapability, 'flushPendingUploads'>;
+};
+
+/**
+ * Flushes in-flight paint uploads, then composites the visible raster layers
+ * of either the whole canvas content or the post-flush generation bbox.
+ */
+export const exportCanvasComposite = async (
+ engine: CanvasCompositeExportEngine,
+ region: CanvasCompositeRegion
+): Promise<ExportCanvasCompositeResult> => {
+ await engine.lifecycle.flushPendingUploads();
+ const document = engine.document.getDocument();
+ if (!document) {
+ return { status: 'not-ready' };
+ }
+
+ return engine.exports.exportRasterComposite(
+ region === 'canvas' ? { bounds: 'content' } : { bounds: 'rect', rect: document.bbox }
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
index 255831fb25..39c1c281ee 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
@@ -1,8 +1,3 @@
-import type {
- CanvasDocumentCapability,
- CanvasExportCapability,
- CanvasLifecycleCapability,
-} from '@workbench/canvas-engine/api';
import type { Rect } from '@workbench/canvas-engine/types';
import type { Project } from '@workbench/projectContracts';
@@ -11,20 +6,17 @@ import { toModelIdentifier } from '@features/generation/graph';
import { isSupportedGenerateModel, normalizeGenerateWidgetValues } from '@features/generation/settings';
import { getProjectWidgetValues } from '@workbench/widgetState';
+import type { CanvasCompositeExportEngine, CanvasCompositeRegion } from './exportCanvasComposite';
+
import { uploadCanvasImage } from './backend/canvasImages';
+import { exportCanvasComposite } from './exportCanvasComposite';
-export type CanvasGallerySaveRegion = 'canvas' | 'bbox';
+export type CanvasGallerySaveRegion = CanvasCompositeRegion;
export type SaveCanvasToGalleryResult =
| { status: 'saved'; imageName: string }
| { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' };
-type CanvasGallerySaveEngine = {
- readonly document: CanvasDocumentCapability;
- readonly exports: Pick<CanvasExportCapability, 'exportRasterComposite'>;
- readonly lifecycle: Pick<CanvasLifecycleCapability, 'flushPendingUploads'>;
-};
-
const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, unknown> => {
const generateValues = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'));
const dimensions = { height: rect.height, width: rect.width };
@@ -51,7 +43,7 @@ const getCanvasSaveBoardId = (project: Project): string | undefined => {
};
export const saveCanvasToGallery = async (options: {
- engine: CanvasGallerySaveEngine;
+ engine: CanvasCompositeExportEngine;
region: CanvasGallerySaveRegion;
project: Project;
uploadImage?: typeof uploadCanvasImage;
@@ -59,15 +51,7 @@ export const saveCanvasToGallery = async (options: {
const { engine, project, region, uploadImage = uploadCanvasImage } = options;
const boardId = getCanvasSaveBoardId(project);
- await engine.lifecycle.flushPendingUploads();
- const document = engine.document.getDocument();
- if (!document) {
- return { status: 'not-ready' };
- }
-
- const exported = await engine.exports.exportRasterComposite(
- region === 'canvas' ? { bounds: 'content' } : { bounds: 'rect', rect: document.bbox }
- );
+ const exported = await exportCanvasComposite(engine, region);
if (exported.status !== 'ok') {
return exported;
}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts
new file mode 100644
index 0000000000..bb2409d68e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.test.ts
@@ -0,0 +1,100 @@
+import type { MainModelConfig } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+
+import { getDefaultGenerateSettings, getMaxReferenceImages } from '@features/generation/settings';
+import { describe, expect, it } from 'vitest';
+
+import { appendReferenceImage, type AppendReferenceImageResult } from './appendReferenceImage';
+
+const sd1Model: MainModelConfig = {
+ base: 'sd-1',
+ hash: 'model-hash',
+ key: 'sd1-key',
+ name: 'SD1 Model',
+ type: 'main',
+};
+
+const models = [sd1Model] as ModelConfig[];
+
+const image = { height: 512, imageName: 'bbox-upload.png', width: 768 };
+
+const generateValuesFor = (referenceImages: unknown[] = []): Record<string, unknown> => ({
+ ...getDefaultGenerateSettings(sd1Model),
+ model: sd1Model,
+ modelKey: sd1Model.key,
+ referenceImages,
+});
+
+describe('appendReferenceImage', () => {
+ it('appends a reference image built from the flat upload result', () => {
+ const result = appendReferenceImage({ generateValues: generateValuesFor(), image, models });
+
+ if (result.status !== 'appended') {
+ throw new Error(`Expected appended, got ${result.status}`);
+ }
+ expect(result.referenceImages).toHaveLength(1);
+ expect(result.referenceImages[0]).toMatchObject({
+ config: { image: { original: { image: { height: 512, image_name: 'bbox-upload.png', width: 768 } } } },
+ id: expect.any(String) as string,
+ isEnabled: true,
+ });
+ });
+
+ it('preserves existing reference images and appends after them', () => {
+ const first = appendReferenceImage({ generateValues: generateValuesFor(), image, models });
+ if (first.status !== 'appended') {
+ throw new Error('Expected first append to succeed');
+ }
+
+ const second = appendReferenceImage({
+ generateValues: generateValuesFor(first.referenceImages as unknown[]),
+ image: { ...image, imageName: 'second.png' },
+ models,
+ });
+
+ if (second.status !== 'appended') {
+ throw new Error('Expected second append to succeed');
+ }
+ expect(second.referenceImages).toHaveLength(2);
+ expect(second.referenceImages[0]).toEqual(first.referenceImages[0]);
+ });
+
+ it('returns full once the model reference image limit is reached', () => {
+ const limit = getMaxReferenceImages(sd1Model);
+ let referenceImages: unknown[] = [];
+
+ for (let index = 0; index < limit; index += 1) {
+ const result: AppendReferenceImageResult = appendReferenceImage({
+ generateValues: generateValuesFor(referenceImages),
+ image: { ...image, imageName: `image-${index}.png` },
+ models,
+ });
+ if (result.status !== 'appended') {
+ throw new Error(`Expected append ${index} to succeed`);
+ }
+ referenceImages = result.referenceImages as unknown[];
+ }
+
+ expect(appendReferenceImage({ generateValues: generateValuesFor(referenceImages), image, models })).toEqual({
+ status: 'full',
+ });
+ });
+
+ it('returns unsupported when the model cannot take reference images', () => {
+ const unsupportedModel = { base: 'sd-2', hash: 'hash-2', key: 'sd2-key', name: 'SD2', type: 'main' };
+
+ expect(
+ appendReferenceImage({
+ generateValues: { model: unsupportedModel, modelKey: unsupportedModel.key },
+ image,
+ models: [unsupportedModel] as ModelConfig[],
+ })
+ ).toEqual({ status: 'unsupported' });
+ });
+
+ it('falls back to the first supported model when values are incomplete', () => {
+ const result = appendReferenceImage({ generateValues: {}, image, models });
+
+ expect(result.status).toBe('appended');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts
new file mode 100644
index 0000000000..d4211add90
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/appendReferenceImage.ts
@@ -0,0 +1,51 @@
+import type { GeneratedImageContract } from '@features/gallery';
+import type { GenerateWidgetValues } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+
+import {
+ createReferenceImageId,
+ generatedImageToReferenceImage,
+ getDefaultReferenceImageConfig,
+ getMaxReferenceImages,
+ isReferenceImageSupported,
+ isSupportedGenerateModel,
+} from '@features/generation/settings';
+
+import { getCurrentGenerateValues } from './executeImageRecall';
+
+export type AppendReferenceImageResult =
+ | { status: 'appended'; referenceImages: GenerateWidgetValues['referenceImages'] }
+ | { status: 'full' | 'unsupported' };
+
+/**
+ * Builds the generate widget's next `referenceImages` array with `image`
+ * appended as a new reference image for the current model. Pure: the caller
+ * patches the widget values on 'appended'.
+ */
+export const appendReferenceImage = ({
+ generateValues,
+ image,
+ models,
+}: {
+ generateValues: Record<string, unknown>;
+ image: Pick<GeneratedImageContract, 'height' | 'imageName' | 'width'>;
+ models: ModelConfig[];
+}): AppendReferenceImageResult => {
+ const supportedModels = models.filter(isSupportedGenerateModel);
+ const currentValues = getCurrentGenerateValues({ generateValues, supportedModels });
+
+ if (!currentValues || !isReferenceImageSupported(currentValues.model)) {
+ return { status: 'unsupported' };
+ }
+ if (currentValues.referenceImages.length >= getMaxReferenceImages(currentValues.model)) {
+ return { status: 'full' };
+ }
+
+ const referenceImage = {
+ config: getDefaultReferenceImageConfig(currentValues.model, models, generatedImageToReferenceImage(image)),
+ id: createReferenceImageId(),
+ isEnabled: true,
+ };
+
+ return { referenceImages: [...currentValues.referenceImages, referenceImage], status: 'appended' };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index c87e5270fe..593cac75cb 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -7,15 +7,7 @@ import {
type GalleryBoard,
type GalleryImage,
} from '@features/gallery';
-import {
- createReferenceImageId,
- generatedImageToReferenceImage,
- getDefaultReferenceImageConfig,
- getMaxReferenceImages,
- isVaeModelConfig,
- isReferenceImageSupported,
- isSupportedGenerateModel,
-} from '@features/generation/settings';
+import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
@@ -30,6 +22,7 @@ import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchC
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { appendReferenceImage } from './appendReferenceImage';
import { recordCanvasImportError } from './canvasImportError';
import { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';
import {
@@ -309,24 +302,13 @@ export const useImageActions = ({
currentGenerateValues.referenceImages.length < getMaxReferenceImages(currentGenerateValues.model)
),
useAsReferenceImage: (image) => {
- const latestGenerateValues = getLatestGenerateValues();
- const currentValues = getCurrentGenerateValues({ generateValues: latestGenerateValues, supportedModels });
+ const result = appendReferenceImage({ generateValues: getLatestGenerateValues(), image, models });
- if (
- !currentValues ||
- !isReferenceImageSupported(currentValues.model) ||
- currentValues.referenceImages.length >= getMaxReferenceImages(currentValues.model)
- ) {
+ if (result.status !== 'appended') {
return;
}
- const referenceImage = {
- config: getDefaultReferenceImageConfig(currentValues.model, models, generatedImageToReferenceImage(image)),
- id: createReferenceImageId(),
- isEnabled: true,
- };
-
- generation.patchSettings({ referenceImages: [...currentValues.referenceImages, referenceImage] }, projectId);
+ generation.patchSettings({ referenceImages: result.referenceImages }, projectId);
openWorkbenchWidget('generate', { preferredRegions: ['left'] });
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCreateFromBboxSubmenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCreateFromBboxSubmenu.tsx
new file mode 100644
index 0000000000..4bbd098413
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCreateFromBboxSubmenu.tsx
@@ -0,0 +1,83 @@
+import type { CreateFromBboxDestination } from '@workbench/canvas-operations/api';
+
+import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
+import { MenuContent } from '@platform/ui';
+import { ChevronRightIcon, ImagePlusIcon } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const SUBMENU_POSITIONING = { placement: 'right-start' } as const;
+
+const CREATE_FROM_BBOX_ITEMS: readonly { destination: CreateFromBboxDestination; labelKey: string }[] = [
+ { destination: 'global-reference', labelKey: 'widgets.canvas.contextMenu.newGlobalReferenceImage' },
+ { destination: 'regional-reference', labelKey: 'widgets.canvas.contextMenu.newRegionalReferenceImage' },
+ { destination: 'control', labelKey: 'widgets.canvas.contextMenu.newControlLayer' },
+ { destination: 'raster', labelKey: 'widgets.canvas.contextMenu.newRasterLayer' },
+];
+
+const CreateFromBboxMenuItem = ({
+ destination,
+ disabled,
+ labelKey,
+ onCreate,
+}: {
+ destination: CreateFromBboxDestination;
+ disabled: boolean;
+ labelKey: string;
+ onCreate: (destination: CreateFromBboxDestination) => void;
+}) => {
+ const { t } = useTranslation();
+ const onSelect = useCallback(() => onCreate(destination), [destination, onCreate]);
+
+ return (
+ <Menu.Item disabled={disabled} value={destination} onSelect={onSelect}>
+ <HStack gap="2" minW="0" w="full">
+ <Icon as={ImagePlusIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />
+ <Text flex="1" fontSize="xs">
+ {t(labelKey)}
+ </Text>
+ </HStack>
+ </Menu.Item>
+ );
+};
+
+export const CanvasCreateFromBboxSubmenu = ({
+ disabled,
+ onCreate,
+}: {
+ disabled: boolean;
+ onCreate: (destination: CreateFromBboxDestination) => void;
+}) => {
+ const { t } = useTranslation();
+
+ return (
+ <Menu.Root positioning={SUBMENU_POSITIONING}>
+ <Menu.TriggerItem asChild>
+ <button disabled={disabled} type="button">
+ <HStack gap="2" minW="0" w="full">
+ <Icon as={ImagePlusIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />
+ <Text flex="1" fontSize="xs">
+ {t('widgets.canvas.contextMenu.createFromBbox')}
+ </Text>
+ <Icon as={ChevronRightIcon} boxSize="3" color="fg.subtle" flexShrink={0} />
+ </HStack>
+ </button>
+ </Menu.TriggerItem>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="13rem" py="1">
+ {CREATE_FROM_BBOX_ITEMS.map((item) => (
+ <CreateFromBboxMenuItem
+ key={item.destination}
+ destination={item.destination}
+ disabled={disabled}
+ labelKey={item.labelKey}
+ onCreate={onCreate}
+ />
+ ))}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx
index 864b5b6b09..e69990e51e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx
@@ -36,7 +36,11 @@ vi.mock('./useCanvasEngine', () => ({ useCanvasEngine: () => harness.engine }));
vi.mock('./useCanvasGallerySave', () => ({
useCanvasGallerySave: () => ({ isSaving: false, save: () => undefined }),
}));
+vi.mock('./useCreateFromBbox', () => ({
+ useCreateFromBbox: () => ({ createFromBbox: () => undefined, isCreating: false }),
+}));
vi.mock('./CanvasBottomControls', () => ({ CanvasBottomControls: () => null }));
+vi.mock('./CanvasCreateFromBboxSubmenu', () => ({ CanvasCreateFromBboxSubmenu: () => null }));
vi.mock('./CanvasGlobalContextMenu', () => ({ CanvasGlobalContextMenu: () => null }));
vi.mock('./CanvasImageDropOverlay', () => ({ CanvasImageDropOverlay: () => null }));
vi.mock('./CanvasSaveToGallerySubmenu', () => ({ CanvasSaveToGallerySubmenu: () => null }));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 92e55ccc34..45a31ddfa7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -32,6 +32,7 @@ import {
resolveCanvasContextMenuBranch,
type CanvasContextMenuTarget,
} from './canvasContextMenu';
+import { CanvasCreateFromBboxSubmenu } from './CanvasCreateFromBboxSubmenu';
import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';
import { resolveCanvasImageDrop } from './canvasImageDnd';
import { CanvasImageDropOverlay } from './CanvasImageDropOverlay';
@@ -54,6 +55,7 @@ import { INLINE_EDIT_SELECTOR } from './surfaceFocus';
import { ToolStrip } from './ToolStrip';
import { useCanvasEngine } from './useCanvasEngine';
import { useCanvasGallerySave } from './useCanvasGallerySave';
+import { useCreateFromBbox } from './useCreateFromBbox';
/** Command id → document-space nudge delta (shift variants are ×10). */
const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {
@@ -94,6 +96,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
const { document, stagingArea } = canvas;
const operation = useCanvasOperation(engine);
const { isSaving, save: saveToGallery } = useCanvasGallerySave(engine);
+ const { createFromBbox, isCreating } = useCreateFromBbox(engine);
// Right-click on the canvas surface: hit-test the layer under the cursor and
// open either the shared per-layer menu or the global empty-space menu at the
@@ -500,10 +503,24 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
[contextMenuTarget]
);
const contextMenuBranch = resolveCanvasContextMenuBranch(contextMenuTarget, engine !== null);
- const isSaveToGalleryDisabled = !engine || isSaving || isInteractionLocked;
+ // The two composite operations share one busy flag so they can't overlap.
+ const isCompositeMenuDisabled = !engine || isSaving || isCreating || isInteractionLocked;
const saveToGallerySubmenu = useMemo(
- () => <CanvasSaveToGallerySubmenu disabled={isSaveToGalleryDisabled} onSave={saveToGallery} />,
- [isSaveToGalleryDisabled, saveToGallery]
+ () => <CanvasSaveToGallerySubmenu disabled={isCompositeMenuDisabled} onSave={saveToGallery} />,
+ [isCompositeMenuDisabled, saveToGallery]
+ );
+ const createFromBboxSubmenu = useMemo(
+ () => <CanvasCreateFromBboxSubmenu disabled={isCompositeMenuDisabled} onCreate={createFromBbox} />,
+ [createFromBbox, isCompositeMenuDisabled]
+ );
+ const compositeSubmenus = useMemo(
+ () => (
+ <>
+ {saveToGallerySubmenu}
+ {createFromBboxSubmenu}
+ </>
+ ),
+ [createFromBboxSubmenu, saveToGallerySubmenu]
);
const canvasSurface = useMemo(() => (engine ? <CanvasSurface engine={engine} /> : null), [engine]);
@@ -518,7 +535,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
<>
<ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} />
<CanvasLayerContextMenu
- beforeDangerItems={saveToGallerySubmenu}
+ beforeDangerItems={compositeSubmenus}
dispatch={canvasDispatch}
engine={engine}
layers={document.layers}
@@ -530,7 +547,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
) : null}
{contextMenuBranch === 'global' && contextMenuTarget ? (
<CanvasGlobalContextMenu target={contextMenuTarget} onClose={closeContextMenu}>
- {saveToGallerySubmenu}
+ {compositeSubmenus}
</CanvasGlobalContextMenu>
) : null}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts
index ec33895c8b..78f343f4aa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.test.ts
@@ -33,4 +33,15 @@ describe('getCanvasGallerySaveErrorAction', () => {
projectId: 'project-1',
});
});
+
+ it('records under the caller-provided area', () => {
+ expect(
+ getCanvasGallerySaveErrorAction(
+ new Error('backend exploded'),
+ 'project-1',
+ "Couldn't create from BBox",
+ 'canvas-create-from-bbox'
+ )
+ ).toMatchObject({ area: 'canvas-create-from-bbox', message: "Couldn't create from BBox" });
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts
index 089d43c0e2..8eb6452319 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasGallerySaveState.ts
@@ -9,9 +9,10 @@ const toErrorMessage = (error: unknown): string => (error instanceof Error ? err
export const getCanvasGallerySaveErrorAction = (
error: unknown,
projectId: string,
- message: string
+ message: string,
+ area: 'canvas-create-from-bbox' | 'canvas-save-to-gallery' = 'canvas-save-to-gallery'
): Parameters<WorkbenchNotificationCommands['reportError']>[0] => ({
- area: 'canvas-save-to-gallery',
+ area,
context: { error: toErrorMessage(error) },
message,
namespace: 'canvas' as const,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCreateFromBbox.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCreateFromBbox.ts
new file mode 100644
index 0000000000..886b0275e1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCreateFromBbox.ts
@@ -0,0 +1,109 @@
+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
+
+import { ensureModelsLoaded, useModelsSelector } from '@features/models';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import {
+ createFromBbox as runCreateFromBbox,
+ getCreateFromBboxNotice,
+ type CreateFromBboxDestination,
+} from '@workbench/canvas-operations/api';
+import { appendReferenceImage } from '@workbench/image-actions/appendReferenceImage';
+import { useNotify } from '@workbench/useNotify';
+import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { useCallback, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getCanvasGallerySaveErrorAction, withMatchingCanvasProject } from './canvasGallerySaveState';
+
+type CreateFromBboxEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'layers' | 'lifecycle' | 'projectId'>;
+
+export const useCreateFromBbox = (
+ engine: CreateFromBboxEngine | null
+): { isCreating: boolean; createFromBbox: (destination: CreateFromBboxDestination) => Promise<void> } => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const queries = useWorkbenchQueries();
+ const { canvas, generation, notifications } = useWorkbenchCommands();
+ const openWorkbenchWidget = useOpenWorkbenchWidget();
+ const models = useModelsSelector((snapshot) => snapshot.models);
+ const isCreatingRef = useRef(false);
+ const [isCreating, setIsCreating] = useState(false);
+
+ useMountEffect(() => {
+ void ensureModelsLoaded();
+ });
+
+ const createFromBbox = useCallback(
+ async (destination: CreateFromBboxDestination): Promise<void> => {
+ if (isCreatingRef.current) {
+ return;
+ }
+
+ const project = queries.getSnapshot().activeProject;
+
+ await withMatchingCanvasProject(engine, project.id, async (matchedEngine) => {
+ isCreatingRef.current = true;
+ setIsCreating(true);
+
+ try {
+ const result = await runCreateFromBbox({
+ applyCanvasMutation: canvas.apply,
+ destination,
+ engine: matchedEngine,
+ getProject: queries.getProject,
+ isActiveProject: queries.isActiveProject,
+ project,
+ });
+
+ if (result.status === 'uploaded') {
+ const latestProject = queries.getProject(project.id);
+ if (!latestProject) {
+ return;
+ }
+
+ const appended = appendReferenceImage({
+ generateValues: getProjectWidgetValues(latestProject, 'generate'),
+ image: result.image,
+ models,
+ });
+
+ if (appended.status === 'appended') {
+ generation.patchSettings({ referenceImages: appended.referenceImages }, project.id);
+ notify.success(t('widgets.canvas.contextMenu.referenceImageAdded'));
+ openWorkbenchWidget('generate', { preferredRegions: ['left'] });
+ } else if (appended.status === 'full') {
+ notify.info(t('widgets.canvas.contextMenu.referenceImageFull'));
+ } else {
+ notify.info(t('widgets.canvas.contextMenu.referenceImageUnsupported'));
+ }
+ return;
+ }
+
+ const notice = getCreateFromBboxNotice(result);
+ const options =
+ notice.options && 'destination' in notice.options
+ ? { destination: t(notice.options.destination) }
+ : (notice.options ?? {});
+ notify[notice.kind](t(notice.titleKey, options));
+ } catch (error: unknown) {
+ notifications.reportError(
+ getCanvasGallerySaveErrorAction(
+ error,
+ project.id,
+ t('widgets.canvas.contextMenu.createError'),
+ 'canvas-create-from-bbox'
+ )
+ );
+ } finally {
+ isCreatingRef.current = false;
+ setIsCreating(false);
+ }
+ });
+ },
+ [canvas, engine, generation, models, notifications, notify, openWorkbenchWidget, queries, t]
+ );
+
+ return { createFromBbox, isCreating };
+};