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(gallery): new canvas from image

Josh Corbett7dc63a295d07
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 499ecd732b..c812e60038 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2565,7 +2565,14 @@
"empty": "No gallery images were available to add.",
"failed": "Couldn't add images to canvas",
"inpaintMask": "Inpaint Mask",
- "newLayerFromImage": "New Layer from Image",
+ "newCanvasFromImage_one": "New Canvas from Image",
+ "newCanvasFromImage_other": "New Canvas from Images",
+ "newCanvasSuccess_one": "Created a new canvas from the image",
+ "newCanvasSuccess_other": "Created a new canvas from {{count}} images",
+ "newFromImage_one": "New from Image",
+ "newFromImage_other": "New from Images",
+ "newLayerFromImage_one": "New Layer from Image",
+ "newLayerFromImage_other": "New Layers from Images",
"partial_one": "Added {{successCount}} image; {{failedCount}} could not be prepared.",
"partial_other": "Added {{successCount}} images; {{failedCount}} could not be prepared.",
"raster": "Raster Layer",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
index 42154e23ea..e462802251 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
@@ -16,6 +16,7 @@ export {
type ImportGalleryImagesResult,
} from './importGalleryImages';
export { getCanvasImportNotice } from './canvasImportNotice';
+export { createCanvasFromImages, type CreateCanvasFromImagesResult } from './createCanvasFromImages';
export {
createFromBbox,
type CreateFromBboxDestination,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.test.ts
new file mode 100644
index 0000000000..baaa6e05ac
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.test.ts
@@ -0,0 +1,86 @@
+import type { GalleryImage } from '@features/gallery';
+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { WorkbenchState } from '@workbench/projectContracts';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { createCanvasFromImages } from './createCanvasFromImages';
+
+const image = (imageName: string, width: number, height: number): 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,
+});
+
+/** A tiny store over the real reducer, so project creation and canvas ingestion run for real. */
+const createStore = () => {
+ let state: WorkbenchState = createInitialWorkbenchState();
+ const getProject = (projectId: string) => state.projects.find((project) => project.id === projectId) ?? null;
+ return {
+ applyCanvasMutation: (projectId: string, mutation: CanvasProjectMutation) => {
+ state = workbenchReducer(state, { mutation, projectId, type: 'applyCanvasProjectMutation' });
+ },
+ createProject: () => {
+ state = workbenchReducer(state, { type: 'createProject' });
+ return getProject(state.activeProjectId)!;
+ },
+ getProject,
+ getState: () => state,
+ isActiveProject: (projectId: string) => state.activeProjectId === projectId,
+ };
+};
+
+beforeEach(() => {
+ accountLifecycle.activate('user-a');
+});
+
+describe('createCanvasFromImages', () => {
+ it('creates a new active project sized to the largest image and imports every image as a raster layer', async () => {
+ const store = createStore();
+ const before = store.getState().activeProjectId;
+
+ const result = await createCanvasFromImages({
+ ...store,
+ images: [image('a.png', 640, 400), image('b.png', 300, 900)],
+ });
+
+ expect(result.status).toBe('imported');
+ expect(result.projectId).not.toBe(before);
+ expect(store.getState().activeProjectId).toBe(result.projectId);
+ // The sizing mutations route the fresh project to the canvas, which is what
+ // keeps the generate dimensions following the frame.
+ expect(store.getProject(result.projectId!)!.invocation.sourceId).toBe('canvas');
+ const { document } = store.getProject(result.projectId!)!.canvas;
+ expect({ height: document.height, width: document.width }).toEqual({ height: 900, width: 640 });
+ expect(document.bbox).toEqual({ height: 900, width: 640, x: 0, y: 0 });
+ const rasters = getDocumentLeaves(document).filter((leaf) => leaf.type === 'raster');
+ expect(
+ rasters.map((leaf) => leaf.type === 'raster' && leaf.source.type === 'image' && leaf.source.image.imageName)
+ ).toEqual(['a.png', 'b.png']);
+ expect(rasters.map((leaf) => [leaf.transform.x, leaf.transform.y])).toEqual([
+ [0, 0],
+ [0, 0],
+ ]);
+ expect(document.selectedLayerId).toBe(rasters[1]?.id);
+ });
+
+ it('creates nothing for an empty selection', async () => {
+ const store = createStore();
+ const projects = store.getState().projects.length;
+
+ const result = await createCanvasFromImages({ ...store, images: [] });
+
+ expect(result).toEqual({ projectId: null, status: 'empty' });
+ expect(store.getState().projects).toHaveLength(projects);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.ts
new file mode 100644
index 0000000000..23b9cf0f57
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasFromImages.ts
@@ -0,0 +1,50 @@
+/**
+ * "New Canvas from Image": a fresh project whose canvas is sized to the
+ * images, with each image imported as a raster layer at the origin.
+ *
+ * Runs before any canvas widget mounts for the new project, so the import
+ * always lands through the reducer path of {@link importGalleryImagesToCanvas}.
+ */
+
+import type { GalleryImage } from '@features/gallery';
+import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { Project } from '@workbench/projectContracts';
+
+import { importGalleryImagesToCanvas, type ImportGalleryImagesResult } from './importGalleryImages';
+
+export type CreateCanvasFromImagesResult = ImportGalleryImagesResult & { projectId: string | null };
+
+export const createCanvasFromImages = async (options: {
+ applyCanvasMutation: (projectId: string, mutation: CanvasProjectMutation) => boolean | void;
+ createProject: () => Project;
+ getProject: (projectId: string) => Project | null;
+ isActiveProject: (projectId: string) => boolean;
+ images: readonly GalleryImage[];
+}): Promise<CreateCanvasFromImagesResult> => {
+ const { applyCanvasMutation, createProject, getProject, images, isActiveProject } = options;
+ if (images.length === 0) {
+ return { projectId: null, status: 'empty' };
+ }
+ const created = createProject();
+ // The document and generation frame both cover the largest image; the
+ // bbox/generate-size sync then picks the matching generate dimensions.
+ const width = Math.max(...images.map((image) => image.width));
+ const height = Math.max(...images.map((image) => image.height));
+ applyCanvasMutation(created.id, { height, type: 'resizeCanvasDocument', width });
+ applyCanvasMutation(created.id, { bbox: { height, width, x: 0, y: 0 }, type: 'setCanvasBbox' });
+
+ const project = getProject(created.id);
+ if (!project) {
+ return { projectId: created.id, status: 'stale-project' };
+ }
+ const result = await importGalleryImagesToCanvas({
+ applyCanvasMutation,
+ destination: 'raster',
+ engine: null,
+ getProject,
+ images,
+ isActiveProject,
+ project,
+ });
+ return { ...result, projectId: created.id };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
index 12e5699ef4..e07f2b62d8 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
@@ -40,6 +40,7 @@ const image = (imageName: string): GalleryImage => ({
const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions => ({
canUseAsReferenceImage: false,
copyImage: vi.fn(() => Promise.resolve()),
+ createCanvasFromImages: vi.fn(() => Promise.resolve()),
deleteItems,
deleteImages: vi.fn(() => Promise.resolve()),
deriveImageRecallCapabilities: vi.fn(() => EMPTY_IMAGE_RECALL_CAPABILITIES),
@@ -233,6 +234,31 @@ describe('ImageContextMenu starred state', () => {
});
});
+describe('ImageContextMenu new canvas from image', () => {
+ it.each([1, 3])('opens a new canvas from the %s targeted image(s)', async (count) => {
+ const actions = createActions(vi.fn());
+ const images = Array.from({ length: count }, (_, index) => image(`image-${index}.png`));
+ await renderMenu(actions, images);
+
+ // A nested menu opens from a mouse hover on its trigger item, after zag's open delay.
+ const trigger = getMenuItem('widgets.canvas.import.newFromImage');
+ await interact(() =>
+ trigger.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' }))
+ );
+ await act(
+ () =>
+ new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 300);
+ })
+ );
+ await interact(() => getMenuItem('widgets.canvas.import.newCanvasFromImage').click());
+
+ const calls = vi.mocked(actions.createCanvasFromImages).mock.calls;
+ expect(calls).toHaveLength(1);
+ expect(calls[0]?.[0].map((entry) => entry.imageName)).toEqual(images.map((entry) => entry.imageName));
+ });
+});
+
describe('ImageContextMenu mixed-media action visibility', () => {
it('shows common actions for a single video and hides every image-only action', async () => {
const video = item('video', 'clip.mp4');
@@ -255,7 +281,7 @@ describe('ImageContextMenu mixed-media action visibility', () => {
expect(document.body.textContent).toContain('Recall Metadata');
expect(document.body.textContent).not.toContain('Send to Upscale');
expect(document.body.textContent).not.toContain('Select for Compare');
- expect(document.body.textContent).not.toContain('New from Image');
+ expect(document.body.textContent).not.toContain('widgets.canvas.import.newFromImage');
});
it('shows frame copy and Details only when a Preview host opts a single video into them', async () => {
@@ -333,7 +359,7 @@ describe('ImageContextMenu mixed-media action visibility', () => {
expect(document.body.textContent).not.toContain('Copy to clipboard');
expect(document.body.textContent).not.toContain('Recall Metadata');
expect(document.body.textContent).not.toContain('Select for Compare');
- expect(document.body.textContent).not.toContain('New from Images');
+ expect(document.body.textContent).not.toContain('widgets.canvas.import.newFromImage');
});
it('keeps complete mixed refs for common bulk actions and hides image-only bulk actions when a ref is unresolved', async () => {
@@ -355,7 +381,7 @@ describe('ImageContextMenu mixed-media action visibility', () => {
expect(document.body.textContent).toContain('Download Selection');
expect(document.body.textContent).toContain('Change Board');
expect(document.body.textContent).toContain('Delete Selection');
- expect(document.body.textContent).not.toContain('New from Images');
+ expect(document.body.textContent).not.toContain('widgets.canvas.import.newFromImage');
const openInNewTab = document.querySelector<HTMLButtonElement>('[aria-label="Open in new tab"]');
const openInPreview = document.querySelector<HTMLButtonElement>('[aria-label="Open in preview"]');
expect(openInNewTab).not.toBeNull();
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 8871aa17f4..d1b20c7577 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -956,12 +956,21 @@ const NewFromImageSubMenu = ({
actions: ImageActions;
images: GalleryImage[];
isBulk: boolean;
-}) => (
- <ContextSubMenu icon={FileImageIcon} label={isBulk ? 'New from Images' : 'New from Image'}>
- <ContextMenuItem disabled icon={FileImageIcon} label="New Canvas from Image" value="new-canvas-from-image" />
- <GalleryCanvasImportSubMenu actions={actions} images={images} isBulk={isBulk} />
- </ContextSubMenu>
-);
+}) => {
+ const { t } = useTranslation();
+ const handleNewCanvas = useCallback(() => void actions.createCanvasFromImages(images), [actions, images]);
+ return (
+ <ContextSubMenu icon={FileImageIcon} label={t('widgets.canvas.import.newFromImage', { count: images.length })}>
+ <ContextMenuItem
+ icon={FileImageIcon}
+ label={t('widgets.canvas.import.newCanvasFromImage', { count: images.length })}
+ value="new-canvas-from-image"
+ onClick={handleNewCanvas}
+ />
+ <GalleryCanvasImportSubMenu actions={actions} images={images} isBulk={isBulk} />
+ </ContextSubMenu>
+ );
+};
const GalleryCanvasImportSubMenu = ({
actions,
@@ -976,7 +985,7 @@ const GalleryCanvasImportSubMenu = ({
const items = getGalleryCanvasImportMenuItems(isBulk);
return (
- <ContextSubMenu icon={LayersIcon} label={t('widgets.canvas.import.newLayerFromImage')}>
+ <ContextSubMenu icon={LayersIcon} label={t('widgets.canvas.import.newLayerFromImage', { count: images.length })}>
{items.map((item) => (
<GalleryCanvasImportDestinationMenuItem key={item.destination} actions={actions} images={images} item={item} />
))}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
index 42f4041fc4..0d9811c4ef 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
@@ -1,4 +1,5 @@
import type { GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
+import type { CreateCanvasFromImagesResult } from '@workbench/canvas-operations/api';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -12,6 +13,10 @@ import { useImageActions } from './useImageActions';
const mocks = vi.hoisted(() => ({
addToBoard: vi.fn(),
+ createCanvasFromImages: vi.fn((..._args: unknown[]): Promise<CreateCanvasFromImagesResult> =>
+ Promise.resolve({ projectId: null, status: 'empty' })
+ ),
+ createProject: vi.fn(),
deleteImages: vi.fn(),
downloadArchive: vi.fn(),
downloadBlob: vi.fn(),
@@ -113,11 +118,16 @@ vi.mock('@platform/browser/downloadBlob', () => ({
downloadBlob: (...args: unknown[]) => mocks.downloadBlob(...args),
}));
-vi.mock('@workbench/canvas-operations/api', () => ({
- getCanvasEngine: vi.fn(),
- getCanvasImportNotice: vi.fn(),
- importGalleryImagesToCanvas: vi.fn(),
-}));
+vi.mock('@workbench/canvas-operations/api', async () => {
+ // The notice mapper is pure; the rest of the canvas-operations surface stays doubled.
+ const { getCanvasImportNotice } = await import('@workbench/canvas-operations/canvasImportNotice');
+ return {
+ createCanvasFromImages: (...args: unknown[]) => mocks.createCanvasFromImages(...args),
+ getCanvasEngine: vi.fn(),
+ getCanvasImportNotice,
+ importGalleryImagesToCanvas: vi.fn(),
+ };
+});
vi.mock('@workbench/WorkbenchContext', () => ({
useWorkbenchCommands: () => ({
@@ -131,6 +141,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({
setCompareImage: vi.fn(),
},
generation: { patchSettings: vi.fn() },
+ projects: { create: (...args: unknown[]) => mocks.createProject(...args) },
notifications: {
add: (...args: unknown[]) => mocks.notificationsAdd(...args),
reportError: (...args: unknown[]) => mocks.reportError(...args),
@@ -259,6 +270,53 @@ afterEach(async () => {
root = null;
});
+describe('new canvas from images', () => {
+ const galleryImage = (imageName: string): GalleryImage => ({
+ boardId: 'none',
+ height: 512,
+ imageCategory: 'general',
+ imageName,
+ imageUrl: `/${imageName}`,
+ queuedAt: '2026-06-15T00:00:00Z',
+ sourceQueueItemId: 'queue-item',
+ starred: false,
+ thumbnailUrl: `/thumb-${imageName}`,
+ width: 512,
+ });
+
+ it('reports the new canvas and opens it in the center once the images land', async () => {
+ mocks.createCanvasFromImages.mockResolvedValueOnce({
+ failedImageNames: [],
+ layerIds: ['layer-1', 'layer-2'],
+ projectId: 'project-2',
+ status: 'imported',
+ });
+
+ await act(() => actionsRef.current!.createCanvasFromImages([galleryImage('a.png'), galleryImage('b.png')]));
+
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'success',
+ title: 'widgets.canvas.import.newCanvasSuccess',
+ });
+ expect(mocks.openWorkbenchWidget).toHaveBeenCalledWith('canvas', {
+ preferredRegions: ['center'],
+ requireCenterView: true,
+ });
+ });
+
+ it('surfaces the import notice and leaves the layout alone when the images could not land', async () => {
+ mocks.createCanvasFromImages.mockResolvedValueOnce({ projectId: 'project-2', status: 'stale-project' });
+
+ await act(() => actionsRef.current!.createCanvasFromImages([galleryImage('a.png')]));
+
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'error',
+ title: 'widgets.canvas.import.staleProject',
+ });
+ expect(mocks.openWorkbenchWidget).not.toHaveBeenCalled();
+ });
+});
+
describe('image recall capability cancellation', () => {
it('re-derives capabilities from the current generate model without another metadata request', async () => {
const image: GalleryImage = {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 1dff2f8206..4868d829a1 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -25,7 +25,7 @@ import {
invalidateGallery,
patchGalleryItemCaches,
} from '@features/gallery/queries';
-import { setPendingPromptTemplateDraft } from '@features/generation/react';
+import { flushGenerateDrafts, setPendingPromptTemplateDraft } from '@features/generation/react';
import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { downloadBlob } from '@platform/browser/downloadBlob';
@@ -37,6 +37,7 @@ import {
} from '@platform/state/accountLifecycle';
import { useQueryClient } from '@tanstack/react-query';
import {
+ createCanvasFromImages,
getCanvasImportNotice,
getCanvasEngine,
importGalleryImagesToCanvas,
@@ -86,6 +87,8 @@ export interface ImageActions extends GalleryItemActions {
/** Whether the generate widget's current model can accept another reference image. */
canUseAsReferenceImage: boolean;
copyImage: (image: GalleryImage) => Promise<void>;
+ /** Opens a new project whose canvas holds these images as raster layers. */
+ createCanvasFromImages: (images: readonly GalleryImage[]) => Promise<void>;
deleteImages: (imageNames: string[]) => Promise<void>;
/** Derives recall availability from already-fetched metadata and the current generate/model state. */
deriveImageRecallCapabilities: (
@@ -912,6 +915,43 @@ export const useImageActions = ({
selectForCompare: (image) => {
gallery.setCompareImage(image, projectId);
},
+ createCanvasFromImages: async (images) => {
+ const owner = captureAccountScope();
+ flushGenerateDrafts();
+ try {
+ const result = await createCanvasFromImages({
+ applyCanvasMutation: commands.canvas.apply,
+ createProject: commands.projects.create,
+ getProject: queries.getProject,
+ images,
+ isActiveProject: queries.isActiveProject,
+ });
+
+ assertAccountScopeCurrent(owner);
+ if (result.status === 'imported' && result.failedImageNames.length === 0) {
+ notifications.add({
+ kind: 'success',
+ title: t('widgets.canvas.import.newCanvasSuccess', { count: result.layerIds.length }),
+ });
+ } else {
+ const notice = getCanvasImportNotice(result);
+ notifications.add({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}) });
+ }
+ if (result.status === 'imported' && result.projectId !== null && queries.isActiveProject(result.projectId)) {
+ openWorkbenchWidget('canvas', { preferredRegions: ['center'], requireCenterView: true });
+ }
+ } catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+ recordCanvasImportError({
+ error,
+ localizedMessage: t('widgets.canvas.import.failed'),
+ notifications,
+ projectId,
+ });
+ }
+ },
sendToCanvas: async (images, destination) => {
const owner = captureAccountScope();