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): offer destinations for pasted media

Josh Corbett30c2c5d3af16
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 9a43c28e1f..b7e70b79ff 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -930,6 +930,7 @@
"source:src/workbench/shell/CenterArea.tsx",
"source:src/workbench/shell/DocumentTitleProgress.tsx",
"source:src/workbench/shell/Panels.tsx",
+ "source:src/workbench/shell/PasteMediaRuntime.tsx",
"source:src/workbench/shell/ProjectConflictBanner.tsx",
"source:src/workbench/shell/QueueRecoveryBanner.tsx",
"source:src/workbench/shell/StatusBar.tsx",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 5e6aec7153..20a21c4505 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1626,6 +1626,7 @@
"source:src/workbench/shell/CenterArea.tsx",
"source:src/workbench/shell/DocumentTitleProgress.tsx",
"source:src/workbench/shell/Panels.tsx",
+ "source:src/workbench/shell/PasteMediaRuntime.tsx",
"source:src/workbench/shell/ProjectConflictBanner.tsx",
"source:src/workbench/shell/QueueRecoveryBanner.tsx",
"source:src/workbench/shell/StatusBar.tsx",
@@ -2679,6 +2680,7 @@
"source:src/workbench/shell/CenterArea.tsx",
"source:src/workbench/shell/DocumentTitleProgress.tsx",
"source:src/workbench/shell/Panels.tsx",
+ "source:src/workbench/shell/PasteMediaRuntime.tsx",
"source:src/workbench/shell/ProjectConflictBanner.tsx",
"source:src/workbench/shell/QueueRecoveryBanner.tsx",
"source:src/workbench/shell/StatusBar.tsx",
@@ -3930,6 +3932,7 @@
"source:src/workbench/shell/CenterArea.tsx",
"source:src/workbench/shell/DocumentTitleProgress.tsx",
"source:src/workbench/shell/Panels.tsx",
+ "source:src/workbench/shell/PasteMediaRuntime.tsx",
"source:src/workbench/shell/ProjectConflictBanner.tsx",
"source:src/workbench/shell/QueueRecoveryBanner.tsx",
"source:src/workbench/shell/StatusBar.tsx",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 1556ad4029..8d5dc1a9fa 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1862,7 +1862,20 @@
"deleteLayoutPresetBody": "Delete \"{{name}}\"? This only removes the saved preset.",
"deleteLayoutPresetQuestion": "Delete layout preset?",
"layoutPresetName": "Preset name",
- "renameLayoutPreset": "Rename layout preset"
+ "renameLayoutPreset": "Rename layout preset",
+ "pasteMedia": {
+ "title_one": "Pasted file",
+ "title_other": "Pasted files",
+ "description_one": "Choose where the pasted file should go.",
+ "description_other": "Choose where the {{count}} pasted files should go.",
+ "gallery": "Upload to Gallery",
+ "canvasHeading": "Add to Canvas as",
+ "reference": "Use as Reference Image",
+ "videosGalleryOnly": "Videos are uploaded to the gallery only.",
+ "imagePreview": "Pasted image {{index}}",
+ "videoPreview": "Pasted video {{index}}",
+ "morePreviews": "+{{count}} more"
+ }
},
"widgets": {
"actionsLabel": "{{label}} actions",
diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
index 08bcbd6706..a875e9d21d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
@@ -14,6 +14,7 @@ export { getGalleryBoardLabel, type GalleryBoardTranslate } from './core/boardLa
export { normalizeGalleryImage } from './core/image';
export {
assertNeverGalleryItem,
+ classifyGalleryUpload,
compareGalleryItems,
formatGalleryVideoDuration,
galleryImageItemToGalleryImage,
@@ -56,9 +57,11 @@ export {
getGalleryCompareImage,
getGalleryDestinationBoardId,
getGalleryPage,
+ getGallerySelectedBoardId,
getGallerySelectedImagePage,
getGallerySelectedImageQuery,
getGallerySemanticImageQuery,
+ getGalleryView,
type GallerySelectedImageQuery,
} from './ui/galleryStateView';
export {
diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.ts
index c7681a9e5a..e6fe172b28 100644
--- a/invokeai/frontend/webv2/src/features/gallery/react.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts
@@ -8,3 +8,4 @@ export {
type GalleryItemContextMenuTarget,
type GalleryUiAdapter,
} from './ui/GalleryUiContext';
+export { useGalleryUploadAction } from './ui/useGalleryUploadAction';
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx
new file mode 100644
index 0000000000..d211692218
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaDialog.tsx
@@ -0,0 +1,313 @@
+import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKind } from '@features/gallery/contracts';
+import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';
+
+import { Box, Dialog, Flex, Image, Portal, SimpleGrid, Stack, Text } from '@chakra-ui/react';
+import {
+ classifyGalleryUpload,
+ galleryImageItemToGalleryImage,
+ getGalleryBoardLabel,
+ getGalleryDestinationBoardId,
+ getGallerySelectedBoardId,
+ getGallerySettings,
+ getGalleryView,
+ isGalleryImageItem,
+} from '@features/gallery/contracts';
+import { galleryBoardsOptions } from '@features/gallery/queries';
+import { useGalleryUploadAction } from '@features/gallery/react';
+import { createGenerateFormValuesSelector } from '@features/generation/react';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { Button, CloseButton } from '@platform/ui';
+import { useQuery } from '@tanstack/react-query';
+import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';
+import {
+ getGalleryCanvasImportMenuItems,
+ useDeletionConfirmation,
+ useImageActions,
+ type ImageActions,
+} from '@workbench/image-actions';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { useActiveProjectId, useActiveProjectSelector, useWidgetValuesSelector } from '@workbench/WorkbenchContext';
+import { FilmIcon, ImagePlusIcon, ImagesIcon } from 'lucide-react';
+import { useCallback, useId, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { PasteMediaRequest } from './PasteMediaRuntime';
+
+type PasteMediaChoice =
+ | { kind: 'gallery' }
+ | { kind: 'canvas'; destination: GalleryCanvasImportDestination }
+ | { kind: 'reference' };
+
+const selectGenerateValues = createGenerateFormValuesSelector();
+const CANVAS_ITEMS = getGalleryCanvasImportMenuItems(true);
+const PREVIEW_LIMIT = 6;
+const EMPTY_BOARDS: GalleryBoard[] = [];
+
+/** Upload and follow-on actions report their own failures. */
+const routePastedFiles = async (
+ files: File[],
+ choice: PasteMediaChoice,
+ {
+ addReferenceImage,
+ sendToCanvas,
+ uploadFiles,
+ }: {
+ addReferenceImage: ImageActions['useAsReferenceImage'];
+ sendToCanvas: ImageActions['sendToCanvas'];
+ uploadFiles: (files: File[]) => Promise<GalleryItem[]>;
+ }
+): Promise<void> => {
+ const items = await uploadFiles(files);
+ if (choice.kind === 'gallery') {
+ return;
+ }
+ const images: GalleryImage[] = items.filter(isGalleryImageItem).map(galleryImageItemToGalleryImage);
+ if (images.length === 0) {
+ return;
+ }
+ if (choice.kind === 'canvas') {
+ await sendToCanvas(images, choice.destination);
+ return;
+ }
+ for (const image of images) {
+ addReferenceImage(image);
+ }
+};
+
+const CanvasDestinationButton = ({
+ destination,
+ label,
+ onChoose,
+}: {
+ destination: GalleryCanvasImportDestination;
+ label: string;
+ onChoose: (destination: GalleryCanvasImportDestination) => void;
+}) => {
+ const handleClick = useCallback(() => onChoose(destination), [destination, onChoose]);
+
+ return (
+ <Button justifyContent="flex-start" size="sm" variant="outline" onClick={handleClick}>
+ {label}
+ </Button>
+ );
+};
+
+/**
+ * Destination picker for a media paste. Every choice uploads the files to the
+ * gallery's current board first (the asset stays findable), then hands the
+ * uploaded images on to the existing canvas-import or reference-image actions.
+ */
+export const PasteMediaDialog = ({ request }: { request: PasteMediaRequest }) => {
+ const { t } = useTranslation();
+ useMountEffect(() => registerHotkeyModalLayer('paste-media'));
+ const projectId = useActiveProjectId();
+ const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));
+ const generateValues = useWidgetValuesSelector('generate', selectGenerateValues);
+ // The gallery's own boards query (same key, shared cache): the board the
+ // person is looking at may be archived or a date bucket, which the default
+ // listing omits.
+ const gallerySettings = getGallerySettings(galleryValues);
+ const boards =
+ useQuery(
+ galleryBoardsOptions({
+ includeArchived: gallerySettings.showArchivedBoards,
+ includeDateBoards: gallerySettings.showDateBoards,
+ orderBy: gallerySettings.boardOrderBy,
+ orderDir: gallerySettings.boardOrderDir,
+ })
+ ).data ?? EMPTY_BOARDS;
+ // Uploads land where generation results do: the picked board, else the
+ // project board — never a date bucket, which cannot hold items.
+ const destinationBoardId = getGalleryDestinationBoardId(galleryValues) ?? 'none';
+ const selectedBoardId = getGallerySelectedBoardId(galleryValues, boards);
+ const galleryView = getGalleryView(galleryValues);
+ const getCurrentGalleryLocation = useCallback(
+ () => ({ galleryView, selectedBoardId }),
+ [galleryView, selectedBoardId]
+ );
+ const uploadFiles = useGalleryUploadAction({
+ boards,
+ getCurrentGalleryLocation,
+ selectedBoardId: destinationBoardId,
+ });
+ const { dialog: deletionDialog, requestDeletionConfirmation } = useDeletionConfirmation();
+ const actions = useImageActions({ boards, generateValues, projectId, requestDeletionConfirmation });
+ const addReferenceImage = actions.useAsReferenceImage;
+
+ const [previews, setPreviews] = useState<{ kind: GalleryItemKind; url: string }[]>([]);
+ // Object URLs are created and revoked together per mount, so StrictMode's
+ // simulated remount cannot revoke URLs a live <img> still points at.
+ useMountEffect(() => {
+ const next = request.files.slice(0, PREVIEW_LIMIT).map((file) => ({
+ kind: classifyGalleryUpload(file)?.kind ?? 'image',
+ url: URL.createObjectURL(file),
+ }));
+ setPreviews(next);
+ return () => next.forEach((preview) => URL.revokeObjectURL(preview.url));
+ });
+ const hasImages = request.files.some((file) => classifyGalleryUpload(file)?.kind === 'image');
+ const hasVideos = request.files.some((file) => classifyGalleryUpload(file)?.kind === 'video');
+ const destinationBoard = boards.find((candidate) => candidate.id === destinationBoardId);
+ const boardName =
+ destinationBoardId === 'none'
+ ? t('widgets.gallery.uncategorized')
+ : destinationBoard
+ ? getGalleryBoardLabel(destinationBoard, t)
+ : null;
+
+ const canvasHeadingId = useId();
+ const galleryButtonRef = useRef<HTMLButtonElement | null>(null);
+ const getInitialFocusEl = useCallback(() => galleryButtonRef.current, []);
+ const returnFocus = useCallback(
+ () => (request.returnFocus?.isConnected ? request.returnFocus : null),
+ [request.returnFocus]
+ );
+ const close = request.settle;
+ const handleOpenChange = useCallback(
+ ({ open }: { open: boolean }) => {
+ if (!open) {
+ close();
+ }
+ },
+ [close]
+ );
+ const choose = useCallback(
+ (choice: PasteMediaChoice) => {
+ close();
+ void routePastedFiles(request.files, choice, {
+ addReferenceImage,
+ sendToCanvas: actions.sendToCanvas,
+ uploadFiles,
+ });
+ },
+ [actions.sendToCanvas, addReferenceImage, close, request.files, uploadFiles]
+ );
+ const chooseGallery = useCallback(() => choose({ kind: 'gallery' }), [choose]);
+ const chooseReference = useCallback(() => choose({ kind: 'reference' }), [choose]);
+ const chooseCanvas = useCallback(
+ (destination: GalleryCanvasImportDestination) => choose({ destination, kind: 'canvas' }),
+ [choose]
+ );
+
+ return (
+ <>
+ <Dialog.Root
+ open
+ finalFocusEl={returnFocus}
+ initialFocusEl={getInitialFocusEl}
+ placement="center"
+ size="sm"
+ onOpenChange={handleOpenChange}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content>
+ <Dialog.Header>
+ <Dialog.Title>{t('shell.pasteMedia.title', { count: request.files.length })}</Dialog.Title>
+ </Dialog.Header>
+ <Dialog.Body>
+ <Stack gap="3">
+ <Flex gap="2" wrap="wrap">
+ {previews.map((preview, index) => (
+ <Box
+ key={preview.url}
+ bg="bg.inset"
+ borderRadius="control"
+ borderWidth="1px"
+ boxSize="64px"
+ overflow="hidden"
+ >
+ {preview.kind === 'video' ? (
+ <Flex align="center" color="fg.muted" h="full" justify="center">
+ <FilmIcon aria-label={t('shell.pasteMedia.videoPreview', { index: index + 1 })} size={20} />
+ </Flex>
+ ) : (
+ <Image
+ alt={t('shell.pasteMedia.imagePreview', { index: index + 1 })}
+ h="full"
+ objectFit="cover"
+ src={preview.url}
+ w="full"
+ />
+ )}
+ </Box>
+ ))}
+ {request.files.length > PREVIEW_LIMIT ? (
+ <Flex align="center" color="fg.muted" fontSize="sm" h="64px" px="2">
+ {t('shell.pasteMedia.morePreviews', { count: request.files.length - PREVIEW_LIMIT })}
+ </Flex>
+ ) : null}
+ </Flex>
+ <Text color="fg.muted" fontSize="sm">
+ {t('shell.pasteMedia.description', { count: request.files.length })}
+ </Text>
+ <Stack gap="2">
+ <Button
+ ref={galleryButtonRef}
+ justifyContent="flex-start"
+ size="sm"
+ variant="outline"
+ onClick={chooseGallery}
+ >
+ <ImagesIcon />
+ {t('shell.pasteMedia.gallery')}
+ {boardName ? (
+ <Text as="span" color="fg.muted" fontWeight="normal" truncate>
+ {boardName}
+ </Text>
+ ) : null}
+ </Button>
+ {hasImages ? (
+ <>
+ <Text id={canvasHeadingId} color="fg.muted" fontSize="xs" mt="1">
+ {t('shell.pasteMedia.canvasHeading')}
+ </Text>
+ <SimpleGrid aria-labelledby={canvasHeadingId} columns={2} gap="2" role="group">
+ {CANVAS_ITEMS.map((item) => (
+ <CanvasDestinationButton
+ key={item.destination}
+ destination={item.destination}
+ label={t(item.label)}
+ onChoose={chooseCanvas}
+ />
+ ))}
+ </SimpleGrid>
+ {actions.canUseAsReferenceImage ? (
+ <Button
+ justifyContent="flex-start"
+ mt="1"
+ size="sm"
+ variant="outline"
+ onClick={chooseReference}
+ >
+ <ImagePlusIcon />
+ {t('shell.pasteMedia.reference')}
+ </Button>
+ ) : null}
+ </>
+ ) : null}
+ {hasImages && hasVideos ? (
+ <Text color="fg.muted" fontSize="xs">
+ {t('shell.pasteMedia.videosGalleryOnly')}
+ </Text>
+ ) : null}
+ </Stack>
+ </Stack>
+ </Dialog.Body>
+ <Dialog.Footer>
+ <Button color="fg" size="sm" variant="ghost" onClick={close}>
+ {t('common.cancel')}
+ </Button>
+ </Dialog.Footer>
+ <Dialog.CloseTrigger asChild>
+ <CloseButton aria-label={t('common.close')} />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ {deletionDialog}
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.browser.test.tsx
new file mode 100644
index 0000000000..34c005c247
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.browser.test.tsx
@@ -0,0 +1,280 @@
+import type { GalleryImageItem } from '@features/gallery/contracts';
+import type { Project } from '@workbench/projectContracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { applyThemeToRoot } from '@theme/applyTheme';
+import { system } from '@theme/system';
+import { DEFAULT_THEME_ID } from '@theme/themes';
+import { isHotkeyModalLayerActive, registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';
+import { getProjectWidgetInstance } from '@workbench/widgetState';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { PasteMediaRuntime } from './PasteMediaRuntime';
+
+const mocks = vi.hoisted(() => ({
+ canUseAsReferenceImage: true,
+ project: null as unknown as Project,
+ sendToCanvas: vi.fn(),
+ uploadFiles: vi.fn(),
+ uploadOptions: null as null | { selectedBoardId: string },
+ useAsReferenceImage: vi.fn(),
+}));
+
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectId: () => mocks.project.id,
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(mocks.project),
+ useWidgetValuesSelector: () => ({}),
+}));
+vi.mock('@features/gallery/react', () => ({
+ useGalleryUploadAction: (options: { selectedBoardId: string }) => {
+ mocks.uploadOptions = options;
+ return mocks.uploadFiles;
+ },
+}));
+vi.mock('@features/gallery/queries', () => ({
+ galleryBoardsOptions: () => ({
+ queryFn: () =>
+ Promise.resolve([
+ {
+ archived: false,
+ assetCount: 0,
+ assetVideoCount: 0,
+ id: 'board-1',
+ imageCount: 0,
+ kind: 'board',
+ name: 'Moodboard',
+ },
+ ]),
+ queryKey: ['boards'],
+ }),
+}));
+vi.mock('@features/generation/react', () => ({ createGenerateFormValuesSelector: () => () => ({}) }));
+vi.mock('@workbench/image-actions', () => ({
+ getGalleryCanvasImportMenuItems: () => [
+ { destination: 'raster', label: 'widgets.canvas.import.raster', value: 'raster' },
+ { destination: 'control', label: 'widgets.canvas.import.control', value: 'control' },
+ ],
+ useDeletionConfirmation: () => ({ dialog: null, requestDeletionConfirmation: vi.fn() }),
+ useImageActions: () => ({
+ canUseAsReferenceImage: mocks.canUseAsReferenceImage,
+ sendToCanvas: mocks.sendToCanvas,
+ useAsReferenceImage: mocks.useAsReferenceImage,
+ }),
+}));
+
+const i18n = createInstance();
+await i18n.use(initReactI18next).init({
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+ interpolation: { escapeValue: false },
+});
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const uploadedImage: GalleryImageItem = {
+ boardId: 'board-1',
+ category: 'user',
+ createdAt: '2026-09-21T00:00:00.000Z',
+ fullUrl: '/full/pasted.png',
+ height: 2,
+ isIntermediate: false,
+ kind: 'image',
+ name: 'pasted.png',
+ starred: false,
+ thumbnailUrl: '/thumb/pasted.png',
+ width: 2,
+};
+
+// A 2x2 PNG: real bytes so the preview <img> renders instead of logging a decode error.
+const PNG_BYTES = Uint8Array.from(
+ atob('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEklEQVR4nGP4z8DwHwyBNAMDAC+tBv1+4dL7AAAAAElFTkSuQmCC'),
+ (char) => char.charCodeAt(0)
+);
+const imageFile = () => new File([PNG_BYTES], 'shot.png', { type: 'image/png' });
+
+const pasteDialog = () => page.getByRole('dialog', { name: /^Pasted file/ });
+
+const paste = (target: EventTarget, files: File[], text?: string): ClipboardEvent => {
+ const clipboardData = new DataTransfer();
+ files.forEach((file) => clipboardData.items.add(file));
+ if (text !== undefined) {
+ clipboardData.setData('text/plain', text);
+ }
+ const event = new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData });
+ act(() => target.dispatchEvent(event));
+ return event;
+};
+
+describe('PasteMediaRuntime', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ let queryClient: QueryClient;
+
+ beforeEach(async () => {
+ mocks.canUseAsReferenceImage = true;
+ mocks.project = createInitialWorkbenchState().projects[0]!;
+ getProjectWidgetInstance(mocks.project, 'gallery')!.state.values.selectedBoardId = 'board-1';
+ applyThemeToRoot(DEFAULT_THEME_ID);
+ mocks.sendToCanvas.mockReset().mockResolvedValue(undefined);
+ mocks.uploadFiles.mockReset().mockResolvedValue([uploadedImage]);
+ mocks.useAsReferenceImage.mockReset();
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <QueryClientProvider client={queryClient}>
+ <button type="button">Origin</button>
+ <textarea aria-label="Prompt" />
+ <div role="dialog" aria-label="Rename">
+ <input aria-label="Name" />
+ </div>
+ <PasteMediaRuntime />
+ </QueryClientProvider>
+ </I18nextProvider>
+ </ChakraProvider>
+ )
+ );
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ });
+
+ it('offers destinations for a pasted image and routes the upload to the chosen one', async () => {
+ const origin = page.getByRole('button', { name: 'Origin' });
+ origin.element().focus();
+ const file = imageFile();
+
+ const event = paste(document.body, [file]);
+
+ expect(event.defaultPrevented).toBe(true);
+ const dialog = page.getByRole('dialog', { name: i18n.t('shell.pasteMedia.title', { count: 1 }) });
+ await expect.element(dialog).toBeVisible();
+ await expect.element(page.getByRole('button', { name: /Upload to Gallery/ })).toHaveFocus();
+ await expect.element(page.getByText('Moodboard')).toBeVisible();
+ await expect
+ .element(page.getByRole('img', { name: i18n.t('shell.pasteMedia.imagePreview', { index: 1 }) }))
+ .toBeVisible();
+ expect(isHotkeyModalLayerActive()).toBe(true);
+
+ await page.getByRole('button', { name: i18n.t('widgets.canvas.import.control') }).click();
+
+ await expect.element(dialog).not.toBeInTheDocument();
+ expect(mocks.uploadFiles).toHaveBeenCalledExactlyOnceWith([file]);
+ await vi.waitFor(() => expect(mocks.sendToCanvas).toHaveBeenCalledOnce());
+ expect(mocks.sendToCanvas.mock.calls[0]?.[0]).toMatchObject([{ imageName: 'pasted.png', width: 2, height: 2 }]);
+ expect(mocks.sendToCanvas.mock.calls[0]?.[1]).toBe('control');
+ expect(mocks.useAsReferenceImage).not.toHaveBeenCalled();
+ await expect.element(origin).toHaveFocus();
+ expect(isHotkeyModalLayerActive()).toBe(false);
+ });
+
+ it('uploads to the gallery without a follow-on action, and uses images as reference images', async () => {
+ paste(document.body, [imageFile()]);
+ await page.getByRole('button', { name: /Upload to Gallery/ }).click();
+ expect(mocks.uploadFiles).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(pasteDialog().elements()).toHaveLength(0));
+ expect(mocks.sendToCanvas).not.toHaveBeenCalled();
+
+ paste(document.body, [imageFile()]);
+ await page.getByRole('button', { name: i18n.t('shell.pasteMedia.reference') }).click();
+ await vi.waitFor(() => expect(mocks.useAsReferenceImage).toHaveBeenCalledOnce());
+ expect(mocks.useAsReferenceImage.mock.calls[0]?.[0]).toMatchObject({ imageName: 'pasted.png' });
+ });
+
+ it('keeps canvas and reference destinations for images only', async () => {
+ paste(document.body, [new File(['x'], 'clip.mp4', { type: 'video/mp4' })]);
+
+ await expect.element(pasteDialog()).toBeVisible();
+ expect(page.getByRole('button', { name: i18n.t('widgets.canvas.import.raster') }).elements()).toHaveLength(0);
+ expect(page.getByRole('button', { name: i18n.t('shell.pasteMedia.reference') }).elements()).toHaveLength(0);
+ expect(page.getByText(i18n.t('shell.pasteMedia.videosGalleryOnly')).elements()).toHaveLength(0);
+ await expect.element(page.getByRole('button', { name: /Upload to Gallery/ })).toBeVisible();
+ });
+
+ it('uploads to the project board while the gallery shows a date bucket', async () => {
+ const values = getProjectWidgetInstance(mocks.project, 'gallery')!.state.values;
+ values.selectedBoardId = 'by_date:2026-09-21';
+ values.projectBoardId = 'board-1';
+ paste(document.body, [imageFile()]);
+
+ await expect.element(page.getByRole('button', { name: /Upload to Gallery/ })).toHaveAccessibleName(/Moodboard/);
+ expect(mocks.uploadOptions?.selectedBoardId).toBe('board-1');
+ });
+
+ it('hides the reference option while the current model cannot take another reference image', async () => {
+ mocks.canUseAsReferenceImage = false;
+ paste(document.body, [imageFile()]);
+
+ await expect.element(pasteDialog()).toBeVisible();
+ await expect.element(page.getByRole('group', { name: i18n.t('shell.pasteMedia.canvasHeading') })).toBeVisible();
+ expect(page.getByRole('button', { name: i18n.t('shell.pasteMedia.reference') }).elements()).toHaveLength(0);
+ });
+
+ it('sends only the uploaded images of a mixed paste on to the canvas', async () => {
+ const video = new File(['x'], 'clip.mp4', { type: 'video/mp4' });
+ const uploadedVideo = {
+ boardId: 'board-1',
+ category: 'user' as const,
+ createdAt: '2026-09-21T00:00:00.000Z',
+ duration: 1,
+ fullUrl: '/full/clip.mp4',
+ height: 2,
+ isIntermediate: false,
+ kind: 'video' as const,
+ name: 'clip.mp4',
+ starred: false,
+ thumbnailUrl: '/thumb/clip.png',
+ width: 2,
+ };
+ mocks.uploadFiles.mockResolvedValue([uploadedVideo, uploadedImage]);
+ paste(document.body, [imageFile(), video]);
+
+ await expect
+ .element(page.getByRole('dialog', { name: i18n.t('shell.pasteMedia.title', { count: 2 }) }))
+ .toBeVisible();
+ await expect.element(page.getByText(i18n.t('shell.pasteMedia.videosGalleryOnly'))).toBeVisible();
+ await page.getByRole('button', { name: i18n.t('widgets.canvas.import.raster') }).click();
+
+ await vi.waitFor(() => expect(mocks.sendToCanvas).toHaveBeenCalledOnce());
+ expect(mocks.sendToCanvas.mock.calls[0]?.[0]).toHaveLength(1);
+ expect(mocks.sendToCanvas.mock.calls[0]?.[0]).toMatchObject([{ imageName: 'pasted.png' }]);
+ });
+
+ it('leaves text pastes into fields, non-media pastes, and pastes under a modal or inside a dialog alone', async () => {
+ const textarea = page.getByRole('textbox', { name: 'Prompt' }).element();
+ textarea.focus();
+ expect(paste(textarea, [imageFile()], 'caption').defaultPrevented).toBe(false);
+ expect(paste(document.body, [], 'just text').defaultPrevented).toBe(false);
+ expect(paste(document.body, [new File(['{}'], 'data.json', { type: 'application/json' })]).defaultPrevented).toBe(
+ false
+ );
+ const release = registerHotkeyModalLayer('test-modal');
+ expect(paste(document.body, [imageFile()]).defaultPrevented).toBe(false);
+ release();
+ // Dialogs that register no modal layer still own pastes from inside them.
+ const nameInput = page.getByRole('textbox', { name: 'Name' }).element();
+ nameInput.focus();
+ expect(paste(nameInput, [imageFile()]).defaultPrevented).toBe(false);
+ expect(pasteDialog().elements()).toHaveLength(0);
+
+ // A media-only paste into a field is still media.
+ expect(paste(textarea, [imageFile()]).defaultPrevented).toBe(true);
+ await expect.element(pasteDialog()).toBeVisible();
+ await page.getByRole('button', { name: i18n.t('common.cancel') }).click();
+ await expect.element(pasteDialog()).not.toBeInTheDocument();
+ expect(mocks.uploadFiles).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx
new file mode 100644
index 0000000000..2bfce1ad77
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/shell/PasteMediaRuntime.tsx
@@ -0,0 +1,65 @@
+import { classifyGalleryUpload } from '@features/gallery/contracts';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { isEditableHotkeyTarget } from '@workbench/hotkeys/keys';
+import { isHotkeyModalLayerActive } from '@workbench/hotkeys/modalLayer';
+import { lazy, Suspense, useCallback, useState } from 'react';
+
+export interface PasteMediaRequest {
+ ticket: number;
+ files: File[];
+ returnFocus: HTMLElement | null;
+ settle: () => void;
+}
+
+// Not every dialog registers a hotkey modal layer (ConfirmDialog, RenameDialog,
+// feature-owned dialogs); a paste from inside any open dialog stays with it.
+const isInsideDialog = (target: EventTarget | null): boolean =>
+ target instanceof Element && target.closest('[role="dialog"], [role="alertdialog"]') !== null;
+
+const PasteMediaDialog = lazy(() =>
+ import('./PasteMediaDialog').then((module) => ({ default: module.PasteMediaDialog }))
+);
+
+/**
+ * Turns a media paste anywhere in the workbench into a destination choice.
+ * The canvas keeps its own `mod+v` (a layer from the clipboard pixels): its
+ * hotkey cancels the keydown, so no paste event reaches here while the canvas
+ * owns focus. Text pasted into a field and pastes inside open dialogs are never
+ * intercepted.
+ */
+export const PasteMediaRuntime = () => {
+ const [request, setRequest] = useState<PasteMediaRequest | null>(null);
+ const settle = useCallback(() => setRequest(null), []);
+
+ useMountEffect(() => {
+ let ticket = 0;
+ const handlePaste = (event: ClipboardEvent) => {
+ const clipboard = event.clipboardData;
+ if (!clipboard || isHotkeyModalLayerActive() || isInsideDialog(event.target)) {
+ return;
+ }
+ if (isEditableHotkeyTarget(event.target) && clipboard.types.includes('text/plain')) {
+ return;
+ }
+ const files = Array.from(clipboard.files).filter((file) => classifyGalleryUpload(file) !== null);
+ if (files.length === 0) {
+ return;
+ }
+ event.preventDefault();
+ setRequest({
+ ticket: ++ticket,
+ files,
+ returnFocus: document.activeElement instanceof HTMLElement ? document.activeElement : null,
+ settle,
+ });
+ };
+ document.addEventListener('paste', handlePaste);
+ return () => document.removeEventListener('paste', handlePaste);
+ });
+
+ return request ? (
+ <Suspense fallback={null}>
+ <PasteMediaDialog key={request.ticket} request={request} />
+ </Suspense>
+ ) : null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
index ddf589bdcd..513dfb1c86 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
@@ -53,6 +53,7 @@ import {
} from './holdToDragSensor';
import { WorkbenchNotificationToaster } from './notifications';
import { LeftPanel, RightPanel } from './Panels';
+import { PasteMediaRuntime } from './PasteMediaRuntime';
import { ProjectConflictBanner } from './ProjectConflictBanner';
import { QueueRecoveryBanner } from './QueueRecoveryBanner';
import { StatusBar } from './StatusBar';
@@ -348,6 +349,7 @@ export const WorkbenchShell = () => {
</Flex>
<FloatingWidgetLayer />
<GalleryDragCursor />
+ <PasteMediaRuntime />
{/* The overlay renders whenever anything is being dragged, even with no
preview to show — and it is a fixed, full-size div over the dragged
element. Without this it swallows every pointer event aimed at what