Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): generalize gallery grid and dnd
joshistoast4c5aae43c1f9
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-6-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-6-report.mdnew file mode 100644index 0000000000..9b3632f4c7--- /dev/null+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-6-report.md@@ -0,0 +1,261 @@+# Task 6 Report: Mixed-media DnD and virtualized gallery grid++## Status++Complete.++Task 6 replaces the gallery-image drag contract with ordered+`GalleryItemRef[]` payloads, forwards image/video/mixed board drops through a+typed item intent, and converts the existing virtualized grid to canonical+mixed-media items. Static video poster cells, qualified item identity, lazy+mixed range selection, and strict image-only drop refinements are covered by+focused browser and unit tests.++The App compatibility layer does not claim mixed board movement: it receives+the complete ordered ref vector from the board UI, handles an all-image vector+with the current image action, and rejects video/mixed vectors intact pending+Task 7.++## TDD evidence++### RED++The first DnD contract run was made after adding the item payload, qualified-ID,+guard, refinement, and board-resolution assertions:++```sh+pnpm test src/features/gallery/ui/galleryDnd.test.ts+```++```text+Test Files 1 failed (1)+Tests 6 failed | 1 passed (7)+```++The failures were the intended missing-contract failures:+`getGalleryItemDragData`, `getGalleryItemDragId`, the item guard, the all-image+refinement shape, and canonical board filtering did not yet exist.++The first board/consumer run was:++```sh+pnpm test \+ src/features/gallery/ui/GalleryBoardSelect.test.ts \+ src/workbench/widgets/canvas/canvasImageDropLayout.test.ts \+ src/workbench/widgets/preview/previewCompareDnd.test.ts \+ src/workbench/widgetDnd.test.ts+```++```text+Test Files 4 failed (4)+Tests 6 failed | 11 passed (17)+```++The missing item utility exports and board forwarding seam caused the expected+failures. The initial Preview drag browser run also failed at module import+because `PreviewFrame` still used the removed image constructor:++```sh+pnpm test:browser \+ src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx \+ src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx+```++The initial Grid browser run likewise failed at module import while+`GalleryImageGrid` still depended on the removed image constructor:++```sh+pnpm test:browser src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+```++### GREEN++The final focused unit regression run was:++```sh+pnpm test \+ src/features/gallery/ui/galleryDnd.test.ts \+ src/features/gallery/ui/GalleryBoardSelect.test.ts \+ src/features/gallery/ui/galleryStateView.test.ts \+ src/features/gallery/ui/useGalleryData.test.ts \+ src/workbench/widgets/canvas/canvasImageDropLayout.test.ts \+ src/workbench/widgets/preview/previewCompareDnd.test.ts \+ src/workbench/widgetDnd.test.ts+```++```text+Test Files 7 passed (7)+Tests 69 passed (69)+```++The final focused browser regression run was:++```sh+pnpm test:browser \+ src/features/gallery/ui/GalleryImageGrid.browser.test.tsx \+ src/features/gallery/ui/useGalleryActions.browser.test.tsx \+ src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx \+ src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx+```++```text+Test Files 4 passed (4)+Tests 15 passed (15)+```++## Implementation++### Shared DnD contract++- Added `GalleryItemDragData` with `kind: 'gallery-item'` and an ordered+ `GalleryItemRef[]`.+- Draggable IDs are exact `GalleryItemKey` values.+- Added the non-empty item guard and retained+ `isGalleryImageDragData()` as a non-empty all-image refinement whose narrowed+ items expose image names without a media cast.+- Board resolution accepts image, video, and mixed payloads, preserves ref+ order, rejects virtual/date board targets, and excludes already-present refs+ through canonical loaded items keyed by kind and name.+- `GalleryBoardSelect` forwards the complete resolved ref vector to+ `moveItemsToBoard`; it never strips a video subset before forwarding.+- Canvas, Upscale, reference-image, Regional Guidance, and Preview comparison+ consumers use the all-image refinement and therefore reject video/mixed+ payloads.+- Grid, Preview frame, and Preview filmstrip sources now emit the item+ contract. The current native Preview remains image-only until Task 8.++### Canonical virtualized grid++- Removed `GalleryImageStateView` and `getGalleryImageStateView`.+- Kept `GalleryImageGrid.tsx` and exactly two cell arms:+ canonical item and queue placeholder.+- Selection, context targets, hotkey targets, React keys, and draggable IDs use+ qualified item identity, so same-name images and videos remain independent.+- Preserved square cells, constant row estimates, viewport-width seeding,+ scroll-to-index navigation, overscan `4`, the near-end infinite-load trigger,+ and image-only queue placeholders.+- Shift-click lazily fetches ordered item refs on normal boards and reads the+ existing item-name cache for date boards. It captures account epoch, filter+ identity, and the selection anchor before awaiting, ignores stale results,+ and falls back to the materialized range on cache misses or request failure.+- Alt-click sets comparison only for images. Alt-clicking a video performs+ normal item selection, allowing the canonical reducer to clear comparison.+- Right-click outside the current selection forms a target containing only the+ clicked canonical item.++### Video poster cell++- Renders the static thumbnail with an ordinary `<img decoding="async">`.+- Adds no `loading="lazy"` and no grid `<video>`.+- Shows an always-visible decorative Play icon and formatted duration badge in+ the lower badge position.+- Uses tabular numerals and the required opacity-only transition.+- Uses a localized video label containing both the item name and formatted+ duration.+- Renamed the list label to `Gallery items` and updated the accessibility+ journey selector.+- Image thumbnail, dimensions, and star affordances retain their existing+ behavior.++## Verification++All commands ran from `invokeai/frontend/webv2`.++```sh+pnpm lint:tsc+```++```text+tsc --noEmit: passed+```++```sh+pnpm test+```++```text+Test Files 375 passed (375)+Tests 4951 passed (4951)+```++```sh+pnpm test:browser+```++```text+Test Files 61 passed (61)+Tests 254 passed (254)+```++The browser suite emitted its existing React `act(...)`, missing-i18n-instance,+and intentional error-boundary diagnostics; the command exited successfully.++```sh+pnpm test:fixtures+```++```text+Tests 4 passed (4)+```++```sh+pnpm architecture:check+```++```text+Test Files 3 passed (3)+Tests 34 passed (34)+```++```sh+pnpm lint+```++```text+format: all matched files correctly formatted+oxlint: zero warnings/errors+tsc --noEmit: passed+architecture: 3 files passed, 34 tests passed+```++## Intentionally retained Task 7/8 adapters++1. `GalleryImageActions.moveItemsToBoard` is a narrow Task 7 bridge. The board+ UI forwards the full ordered mixed ref vector; the App adapter handles only+ an all-image vector and rejects video/mixed vectors without moving an image+ subset.+2. The canonical Gallery context target is converted to the current+ `ImageContextMenu` target only when every target item is an image. Video and+ mixed targets are rejected pending the Task 7 common item action menu.+3. Grid delete/star hotkeys still call the image-action port only for a fully+ resolved all-image selection. Video, mixed, and unresolved selections are+ rejected pending Task 7.+4. Workbench `patchImages`/`removeImages` and the image-action methods remain+ strict image adapters pending the Task 7 mixed mutation/action port.+5. Legacy Workbench selection commands (`selectImage`, `setCompareImage`,+ `setMultiSelection`, and `toggleImageSelection`) remain for Preview and the+ image command palette. Grid now uses canonical commands; the remaining+ adapters are Task 8 cleanup.+6. Preview still narrows the mixed gallery query to images through+ `flattenPreviewImages` and constructs an image ref for the selected saved+ frame. Native video preview/navigation and the main preview video+ non-draggable boundary remain Task 8 work.+7. Canvas, Upscale, reference-image, Regional Guidance, workflow collision, and+ comparison targets remain intentionally image-only. Their shared refinement+ accepts only non-empty all-image item payloads.++No retained adapter converts or casts a video to an image.++## Self-review++- Confirmed `GeneratedImageContract` is byte-for-byte unchanged from Task 5.+- Confirmed no image-only contract gained optional media fields.+- Confirmed no production file was added or renamed.+- Confirmed no `useEffect` was added.+- Confirmed no Task 6 production change adds `<video>` or lazy image loading.+- Confirmed `migrationExceptions.ts` and performance baselines are untouched.+- Confirmed old DnD constructors/IDs and the Task 5 image grid projection are+ absent; the only old `gallery-image` payload literal is a negative guard+ regression test.+- Confirmed `git diff --check` is clean.+- No unresolved implementation concern.diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 02f6ba161d..81284df9f5 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2070,7 +2070,7 @@"hideDateBoards": "Hide date boards","imageDensity": "Image density","imageSort": "Image Sort",- "imagesAriaLabel": "Gallery images",+ "itemsAriaLabel": "Gallery items","infinite": "Infinite","loadingBackendGallery": "Loading backend gallery...","loadingBoard": "Loading board...",@@ -2084,6 +2084,7 @@"searchImagesPlaceholder": "Search images","searchOrCreateBoards": "Search or create boards","selectImageForPreview": "Select {{name}} for preview",+ "selectVideoForPreview": "Select video {{name}}, duration {{duration}}, for preview","selectedBoardFallback": "selected board","settings": "Gallery settings","settingsGridDensity": "Grid Density",diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 828d4f46ec..a5d75029f5 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -133,7 +133,7 @@ const surfaces = [ready: async (page) => {await waitForWorkbench(page);await selectLayoutPreset(page, 'Gallery');- await page.getByRole('list', { exact: true, name: 'Gallery images' }).waitFor();+ await page.getByRole('list', { exact: true, name: 'Gallery items' }).waitFor();},},{diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsxindex 6bcb59652f..ff56aa30b1 100644--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx@@ -1,12 +1,40 @@-import type { GalleryImageActionsOptions, GalleryImageContextMenuProps } from '@features/gallery/react';+import type {+ GalleryImageActions,+ GalleryImageActionsOptions,+ GalleryItemContextMenuProps,+} from '@features/gallery/react';import type { ReactNode } from 'react';+import { galleryImageItemToGalleryImage, isGalleryImageItem } from '@features/gallery/contracts';import { GalleryImageActionsProvider } from '@features/gallery/react';+import { getGalleryItemDragData, isGalleryImageDragData } from '@features/gallery/utility';import { ImageContextMenu, useImageActions, type ImageActions } from '@workbench/image-actions';+import { useMemo } from 'react';-const GalleryImageContextMenuComponent = ({ actions, ...props }: GalleryImageContextMenuProps) => (- <ImageContextMenu {...props} actions={actions as ImageActions} />-);+const GalleryImageContextMenuComponent = ({ actions, boards, onClose, target }: GalleryItemContextMenuProps) => {+ // TODO(Task 7): The current App action menu is image-only. Keep its input+ // strict until the canonical mixed-media context menu/actions port lands.+ const imageTarget = useMemo(+ () =>+ target && target.items.length > 0 && target.items.every(isGalleryImageItem)+ ? {+ images: target.items.map(galleryImageItemToGalleryImage),+ x: target.x,+ y: target.y,+ }+ : null,+ [target]+ );++ return (+ <ImageContextMenu+ actions={actions as unknown as ImageActions}+ boards={boards}+ target={imageTarget}+ onClose={onClose}+ />+ );+};const GalleryImageActionsAdapterComponent = ({boards,@@ -16,8 +44,29 @@ const GalleryImageActionsAdapterComponent = ({projectId,}: GalleryImageActionsOptions & { children: ReactNode }) => {const actions = useImageActions({ boards, generateValues, onImagesDeleted, projectId });+ const galleryActions = useMemo<GalleryImageActions>(+ () => ({+ ...actions,+ // TODO(Task 7): Replace with the canonical mixed-media organization+ // action. This compatibility bridge deliberately rejects video/mixed+ // refs instead of silently moving only their image subset.+ moveItemsToBoard: async (items, boardId) => {+ const dragData = getGalleryItemDragData(items);++ if (!isGalleryImageDragData(dragData)) {+ return;+ }++ await actions.moveImagesToBoard(+ dragData.items.map((item) => item.name),+ boardId+ );+ },+ }),+ [actions]+ );- return <GalleryImageActionsProvider actions={actions}>{children}</GalleryImageActionsProvider>;+ return <GalleryImageActionsProvider actions={galleryActions}>{children}</GalleryImageActionsProvider>;};export const GalleryImageActionsAdapter = GalleryImageActionsAdapterComponent;diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.tsindex 43961ec28e..6b49447ebf 100644--- a/invokeai/frontend/webv2/src/features/gallery/react.ts+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts@@ -3,6 +3,7 @@ export {GalleryImageActionsProvider,type GalleryImageActions,type GalleryImageActionsOptions,- type GalleryImageContextMenuProps,+ type GalleryItemContextMenuProps,+ type GalleryItemContextMenuTarget,type GalleryUiAdapter,} from './ui/GalleryUiContext';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.test.tsnew file mode 100644index 0000000000..836527cae0--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.test.ts@@ -0,0 +1,56 @@+import type { GalleryItem } from '@features/gallery/contracts';++import { describe, expect, it, vi } from 'vitest';++import { forwardGalleryBoardDrop } from './GalleryBoardSelect';+import { getGalleryBoardDropData, getGalleryItemDragData } from './galleryDnd';++const createItem = (kind: GalleryItem['kind'], name: string, boardId: string): GalleryItem => {+ const base = {+ boardId,+ category: 'general' as const,+ createdAt: '2026-07-30T00:00:00.000Z',+ fullUrl: `/full/${name}`,+ height: 64,+ isIntermediate: false,+ name,+ starred: false,+ thumbnailUrl: `/thumbnail/${name}`,+ width: 64,+ };++ return kind === 'video' ? { ...base, durationSeconds: 8, kind } : { ...base, kind };+};++describe('forwardGalleryBoardDrop', () => {+ it('forwards the full ordered mixed resolution without stripping video refs', () => {+ const moveItemsToBoard = vi.fn();+ const dragData = getGalleryItemDragData([+ { kind: 'video', name: 'shared' },+ { kind: 'image', name: 'image.png' },+ { kind: 'image', name: 'shared' },+ ]);+ const loadedItems = [+ createItem('image', 'shared', 'board-b'),+ createItem('video', 'shared', 'board-a'),+ createItem('image', 'image.png', 'none'),+ ];++ expect(+ forwardGalleryBoardDrop({+ activeData: dragData,+ loadedItems,+ moveItemsToBoard,+ overData: getGalleryBoardDropData('board-b', 'board'),+ })+ ).toBe(true);+ expect(moveItemsToBoard).toHaveBeenCalledOnce();+ expect(moveItemsToBoard).toHaveBeenCalledWith(+ [+ { kind: 'video', name: 'shared' },+ { kind: 'image', name: 'image.png' },+ ],+ 'board-b'+ );+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsxindex 8fa2f7ccae..73b550f5b8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx@@ -1,3 +1,4 @@+import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';import type { GalleryBoard } from '@features/gallery/core/types';import {@@ -46,13 +47,34 @@ import { GalleryBoardMenu, type GalleryBoardMenuTarget } from './GalleryBoardMenimport {getGalleryBoardDropData,getGalleryBoardDropId,- getGalleryImageNamesOutsideBoard,- isGalleryBoardDropData,- isGalleryImageDragData,+ getGalleryItemRefsOutsideBoard,+ isGalleryItemDragData,+ resolveGalleryBoardDrop,} from './galleryDnd';import { getBoardCounts } from './galleryStateView';import { useGalleryWidget } from './GalleryWidgetContext';+export const forwardGalleryBoardDrop = ({+ activeData,+ loadedItems,+ moveItemsToBoard,+ overData,+}: {+ activeData: unknown;+ loadedItems: readonly GalleryItem[];+ moveItemsToBoard: (items: GalleryItemRef[], boardId: string) => void;+ overData: unknown;+}): boolean => {+ const resolution = resolveGalleryBoardDrop(activeData, overData, loadedItems);++ if (!resolution) {+ return false;+ }++ moveItemsToBoard(resolution.items, resolution.boardId);+ return true;+};+export const GalleryBoardSelect = () => {const { t } = useTranslation();const { actions, gallery, imageActions, projectName } = useGalleryWidget();@@ -62,7 +84,7 @@ export const GalleryBoardSelect = () => {const [boardMenuTarget, setBoardMenuTarget] = useState<GalleryBoardMenuTarget | null>(null);const boardMenuActiveRef = useRef(false);const dragOpenedMenuRef = useRef(false);- const isGalleryImageDragActive = isGalleryImageDragData(active?.data.current);+ const isGalleryItemDragActive = isGalleryItemDragData(active?.data.current);const trimmedSearchTerm = boardSearchTerm.trim();const normalizedSearchTerm = trimmedSearchTerm.toLowerCase();const matchesSearch = useCallback(@@ -98,20 +120,19 @@ export const GalleryBoardSelect = () => {const dragData = event.active.data.current;const dropData = event.over?.data.current;- if (isGalleryImageDragData(dragData) && isGalleryBoardDropData(dropData) && dropData.boardKind === 'board') {- const imageNames = getGalleryImageNamesOutsideBoard(dragData, dropData.boardId);-- if (imageNames.length > 0) {- void imageActions.moveImagesToBoard(imageNames, dropData.boardId);- }- }+ forwardGalleryBoardDrop({+ activeData: dragData,+ loadedItems: gallery.items,+ moveItemsToBoard: (items, boardId) => void imageActions.moveItemsToBoard(items, boardId),+ overData: dropData,+ });if (dragOpenedMenuRef.current) {dragOpenedMenuRef.current = false;closeAndReset();}},- [closeAndReset, imageActions]+ [closeAndReset, gallery.items, imageActions]);const handleDragCancel = useCallback(() => {@@ -122,7 +143,7 @@ export const GalleryBoardSelect = () => {}, [closeAndReset]);const handleDragStart = useCallback((event: DragStartEvent) => {- if (!isGalleryImageDragData(event.active.data.current)) {+ if (!isGalleryItemDragData(event.active.data.current)) {return;}@@ -175,13 +196,13 @@ export const GalleryBoardSelect = () => {return;}- if (boardMenuActiveRef.current || isGalleryImageDragActive) {+ if (boardMenuActiveRef.current || isGalleryItemDragActive) {return;}closeAndReset();},- [closeAndReset, isGalleryImageDragActive]+ [closeAndReset, isGalleryItemDragActive]);const handleSearchChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {@@ -448,16 +469,17 @@ const BoardRow = ({}) => {const { t } = useTranslation();const { active } = useDndContext();+ const { gallery } = useGalleryWidget();const dragData = active?.data.current;- const canDropImages =+ const canDropItems =board.kind === 'board' &&- isGalleryImageDragData(dragData) &&- getGalleryImageNamesOutsideBoard(dragData, board.id).length > 0;+ isGalleryItemDragData(dragData) &&+ getGalleryItemRefsOutsideBoard(dragData, board.id, gallery.items).length > 0;const { isOver, setNodeRef } = useDroppable({data: getGalleryBoardDropData(board.id, board.kind),- disabled: !canDropImages,+ disabled: !canDropItems,id: getGalleryBoardDropId(board.id),});@@ -508,8 +530,8 @@ const BoardRow = ({// DropZone tokens without the DropZone component: an outline (not a border) so the drop affordance never shifts menu layout.bg={isOver ? 'accent.muted' : undefined}css={hoverCss}- outline={canDropImages ? '1px dashed' : undefined}- outlineColor={canDropImages ? 'accent.solid' : undefined}+ outline={canDropItems ? '1px dashed' : undefined}+ outlineColor={canDropItems ? 'accent.solid' : undefined}value={board.id}onClick={handleSelect}onContextMenu={onOpenMenu ? handleContextMenu : undefined}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxnew file mode 100644index 0000000000..4034e4cdf1--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -0,0 +1,583 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';++import { ChakraProvider } from '@chakra-ui/react';+import { DndContext, PointerSensor, useDndMonitor, useSensor, useSensors, type DragStartEvent } from '@dnd-kit/core';+import { DEFAULT_GALLERY_SETTINGS } from '@features/gallery/core/settings';+import { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act, type ReactNode } 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 type { GalleryStateView } from './galleryStateView';+import type { GalleryActions, GalleryWidgetContextValue } from './GalleryWidgetContext';++import { GalleryImageGrid } from './GalleryImageGrid';+import { GalleryWidgetContext } from './GalleryWidgetContext';++const mocks = vi.hoisted(() => ({+ fetchNames: vi.fn(),+ measure: vi.fn(),+ scrollToIndex: vi.fn(),+ virtualizerOptions: [] as Array<{+ count: number;+ estimateSize: () => number;+ overscan: number;+ }>,+}));++const getNamesKey = (filter: unknown) => ['test-gallery-item-names', JSON.stringify(filter)] as const;++vi.mock('@features/gallery/data/queries', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ galleryItemNamesOptions: (filter: unknown) => ({+ queryFn: () => mocks.fetchNames(filter),+ queryKey: getNamesKey(filter),+ staleTime: Infinity,+ }),+}));++vi.mock('react-hook-tanstack-virtual', () => ({+ useVirtualizer: (options: { count: number; estimateSize: () => number; overscan: number }) => {+ mocks.virtualizerOptions.push(options);+ const size = options.estimateSize();++ return {+ measure: mocks.measure,+ scrollToIndex: mocks.scrollToIndex,+ totalSize: options.count * size,+ virtualItems: Array.from({ length: options.count }, (_, index) => ({+ end: (index + 1) * size,+ index,+ key: index,+ size,+ start: index * size,+ })),+ };+ },+}));++vi.mock('@features/queue/react', () => ({+ useQueueItemProgress: () => null,+ useQueueItemProgressImage: () => null,+}));++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ initAsync: false,+ lng: 'en',+ resources: {+ en: {+ translation: {+ common: { generating: 'Generating' },+ widgets: {+ gallery: {+ commands: {+ clearSelection: 'Clear selection',+ deleteSelection: 'Delete selection',+ navigationDown: 'Down',+ navigationLeft: 'Left',+ navigationRight: 'Right',+ navigationUp: 'Up',+ selectAllOnPage: 'Select all',+ toggleStarImage: 'Toggle star',+ },+ generationProgress: 'Generation progress',+ generationProgressPercent: 'Generation {{percentage}}%',+ itemsAriaLabel: 'Gallery items',+ loadingBackendGallery: 'Loading gallery',+ noImagesMatch: 'No items',+ selectImageForPreview: 'Select {{name}} for preview',+ selectVideoForPreview: 'Select video {{name}}, duration {{duration}}, for preview',+ selectedBoardFallback: 'selected board',+ starImage: 'Star {{name}}',+ unstarImage: 'Unstar {{name}}',+ windowLimit: 'Limited to {{count}}',+ },+ preview: {+ compare: 'Compare',+ showInProgressDiffusion: 'Show progress',+ viewing: 'Viewing',+ },+ },+ },+ },+ },+});++const createItem = (kind: GalleryItem['kind'], name: string, overrides: Partial<GalleryItem> = {}): GalleryItem => {+ const base = {+ boardId: 'board-a',+ category: 'general' as const,+ createdAt: '2026-07-30T00:00:00.000Z',+ fullUrl: `/full/${kind}/${name}`,+ height: 96,+ isIntermediate: false,+ name,+ starred: false,+ thumbnailUrl: `/thumbnail/${kind}/${name}`,+ width: 128,+ ...overrides,+ };++ return kind === 'video'+ ? ({+ ...base,+ durationSeconds: 'durationSeconds' in base ? (base.durationSeconds ?? 65.2) : 65.2,+ kind,+ } as GalleryItem)+ : ({ ...base, kind } as GalleryItem);+};++const board = {+ archived: false,+ assetCount: 0,+ id: 'board-a',+ imageCount: 3,+ kind: 'board',+ name: 'Board A',+ videoCount: 1,+} as const;++const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateView => {+ const items = overrides.items ?? [+ createItem('image', 'first.png'),+ createItem('video', 'shared'),+ createItem('image', 'last.png'),+ ];++ return {+ boards: [board],+ compareImageKey: null,+ currentItem: { itemKey: 'image:first.png', kind: 'item' },+ galleryView: 'images',+ isLoading: false,+ items,+ pendingPlaceholders: [],+ projectBoardId: null,+ searchTerm: '',+ selectedBoardId: board.id,+ selectedItemKey: 'image:first.png',+ selectedItemKeys: ['image:first.png'],+ settings: { ...DEFAULT_GALLERY_SETTINGS, imageDensityPercent: 0, paginationMode: 'paginated' },+ ...overrides,+ };+};++const actionMocks = {+ loadMore: vi.fn(),+ selectItem: vi.fn(),+ selectItemRange: vi.fn(),+ setCompareItem: vi.fn(),+ toggleItemInSelection: vi.fn(),+};+const imageActionMocks = {+ deleteImages: vi.fn(),+ moveImagesToBoard: vi.fn(),+ moveItemsToBoard: vi.fn(),+ setImagesStarred: vi.fn(),+};+const noop = vi.fn();+const registeredCommands = new Map<string, () => unknown>();+const runtime = {+ commands: {+ register: ({ handler, id }: { handler: () => unknown; id: string }) => {+ registeredCommands.set(id, handler);+ return () => registeredCommands.delete(id);+ },+ },+ hotkeys: { register: () => () => undefined },+};++const createActions = (): GalleryActions =>+ ({+ archiveBoard: vi.fn(),+ createBoard: vi.fn(),+ deleteBoard: vi.fn(),+ downloadBoard: vi.fn(),+ loadMore: actionMocks.loadMore,+ refresh: noop,+ renameBoard: vi.fn(),+ selectBoard: noop,+ selectImage: actionMocks.selectItem,+ selectImageRange: actionMocks.selectItemRange,+ selectItem: actionMocks.selectItem,+ selectItemRange: actionMocks.selectItemRange,+ selectProjectBoard: vi.fn(),+ setCompareItem: actionMocks.setCompareItem,+ setSearchTerm: noop,+ setView: noop,+ toggleImageInSelection: actionMocks.toggleItemInSelection,+ toggleItemInSelection: actionMocks.toggleItemInSelection,+ updateSettings: noop,+ uploadFiles: vi.fn(),+ }) as unknown as GalleryActions;++type CanonicalContextTarget = { items: GalleryItem[]; x: number; y: number } | null;+const ContextMenuProbe = ({ target }: { target: CanonicalContextTarget }) => (+ <output data-testid="context-target">+ {JSON.stringify(target?.items.map(({ kind, name }) => ({ kind, name })) ?? null)}+ </output>+);+const NoopProvider = ({ children }: { children: ReactNode }) => children;++const createAdapter = (): GalleryUiAdapter =>+ ({+ ImageActionsProvider: NoopProvider,+ ImageContextMenu: ContextMenuProbe,+ account: { enableLiveFollow: noop },+ antialiasProgressImages: false,+ gallery: {+ reconcileDeletedBoardOutcome: noop,+ selectBoard: noop,+ selectImage: noop,+ selectItem: noop,+ setCompareImage: noop,+ setCompareItem: noop,+ setItemMultiSelection: noop,+ setMultiSelection: noop,+ setPage: noop,+ setPageInfo: noop,+ setProjectBoard: noop,+ setSearchTerm: noop,+ setView: noop,+ toggleImageSelection: noop,+ toggleItemSelection: noop,+ updateSettings: noop,+ },+ galleryValues: {},+ generateValues: {},+ liveFollowEnabled: false,+ liveProgressTarget: null,+ notifications: { add: noop, reportError: noop },+ projectId: 'project-1',+ projectName: 'Project',+ queueItems: [],+ widgets: { patchGalleryValues: noop },+ }) as unknown as GalleryUiAdapter;++let host: HTMLDivElement | null = null;+let root: Root | null = null;+let queryClient: QueryClient | null = null;+let currentGallery = createGallery();+let onDragStart = vi.fn();+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const DragMonitor = () => {+ useDndMonitor({+ onDragStart: (event: DragStartEvent) => onDragStart({ data: event.active.data.current, id: event.active.id }),+ });++ return null;+};++const Harness = ({ gallery }: { gallery: GalleryStateView }) => {+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));+ const contextValue: GalleryWidgetContextValue = {+ actions: createActions(),+ gallery,+ imageActions: imageActionMocks,+ isWindowTruncated: false,+ projectName: 'Project',+ runtime,+ } as unknown as GalleryWidgetContextValue;++ return (+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient!}>+ <GalleryUiProvider adapter={createAdapter()}>+ <GalleryWidgetContext value={contextValue}>+ <DndContext sensors={sensors}>+ <DragMonitor />+ <GalleryImageGrid layout="wide" />+ </DndContext>+ </GalleryWidgetContext>+ </GalleryUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>+ );+};++const interact = (action: () => void, delay = 0): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, delay);+ });+ });++const renderGallery = async (gallery = currentGallery) => {+ currentGallery = gallery;+ await interact(() => root?.render(<Harness gallery={gallery} />));+};++const getButton = (label: string): HTMLButtonElement => {+ const button = host?.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);++ if (!button) {+ throw new Error(`Expected button "${label}"`);+ }++ return button;+};++const click = (button: HTMLButtonElement, init: MouseEventInit = {}): Promise<void> =>+ interact(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ...init })));++const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {+ target.dispatchEvent(+ new PointerEvent(type, { bubbles: true, button: 0, clientX, clientY, isPrimary: true, pointerId: 1 })+ );+};++beforeEach(() => {+ accountLifecycle.activate('grid-user');+ vi.clearAllMocks();+ registeredCommands.clear();+ currentGallery = createGallery();+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ host = document.createElement('div');+ host.style.cssText = 'height:480px;left:20px;position:fixed;top:20px;width:600px;';+ document.body.append(host);+ root = createRoot(host);+ onDragStart = vi.fn();+});++afterEach(async () => {+ await interact(() => root?.unmount());+ host?.remove();+ queryClient?.clear();+ host = null;+ queryClient = null;+ root = null;+});++describe('GalleryImageGrid mixed item cells', () => {+ it('renders same-name media independently and gives a video a static accessible poster', async () => {+ const gallery = createGallery({+ items: [createItem('image', 'shared'), createItem('video', 'shared')],+ selectedItemKey: 'image:shared',+ selectedItemKeys: ['image:shared'],+ });++ await renderGallery(gallery);++ const list = host?.querySelector('[role="list"]');+ const imageButton = getButton('Select shared for preview');+ const videoButton = getButton('Select video shared, duration 1:06, for preview');+ const videoCell = videoButton.closest<HTMLElement>('[role="listitem"]');+ const videoPoster = videoButton.querySelector<HTMLImageElement>('img');+ const playIcon = videoCell?.querySelector('svg.lucide-play');+ const durationBadge = playIcon?.parentElement;+ const durationBadgeStyle = durationBadge ? getComputedStyle(durationBadge) : null;++ expect(list?.getAttribute('aria-label')).toBe('Gallery items');+ expect(host?.querySelectorAll('[role="listitem"]')).toHaveLength(2);+ expect(imageButton.getAttribute('aria-pressed')).toBe('true');+ expect(videoButton.getAttribute('aria-pressed')).toBe('false');+ expect(videoPoster?.getAttribute('src')).toContain('/thumbnail/video/shared');+ expect(videoPoster?.getAttribute('decoding')).toBe('async');+ expect(videoPoster?.hasAttribute('loading')).toBe(false);+ expect(videoCell?.textContent).toContain('1:06');+ expect(playIcon?.getAttribute('aria-hidden')).toBe('true');+ expect(durationBadgeStyle?.fontVariantNumeric).toContain('tabular-nums');+ expect(durationBadgeStyle?.opacity).toBe('1');+ expect(durationBadgeStyle?.transitionProperty).toBe('opacity');+ expect(imageButton.closest('[role="listitem"]')?.textContent).toContain('128x96');+ expect(host?.querySelector('button[aria-label="Star shared"]')).not.toBeNull();+ expect(host?.querySelector('video')).toBeNull();+ });++ it('uses qualified video drag identity and emits a video-capable item payload', async () => {+ await renderGallery(createGallery({ items: [createItem('video', 'shared')] }));+ const videoButton = getButton('Select video shared, duration 1:06, for preview');++ await interact(() => pointer('pointerdown', videoButton, 80, 80), 20);+ await interact(() => pointer('pointermove', videoButton.ownerDocument, 120, 80), 50);++ expect(onDragStart).toHaveBeenCalledWith({+ data: { items: [{ kind: 'video', name: 'shared' }], kind: 'gallery-item' },+ id: 'video:shared',+ });++ // dnd-kit briefly suppresses the click following a completed drag. Let+ // that document-level guard expire before the next interaction test.+ await interact(() => pointer('pointerup', videoButton.ownerDocument, 120, 80), 300);+ });++ it('keeps Alt comparison image-only and forms a one-video context target outside selection', async () => {+ const image = createItem('image', 'first.png');+ const video = createItem('video', 'clip.mp4', { durationSeconds: 2 });+ await renderGallery(+ createGallery({+ compareImageKey: 'image:compare.png',+ items: [image, video],+ selectedItemKey: 'image:first.png',+ selectedItemKeys: ['image:first.png'],+ })+ );++ await click(getButton('Select first.png for preview'), { altKey: true });+ expect(actionMocks.setCompareItem).toHaveBeenCalledWith(image);+ expect(actionMocks.selectItem).not.toHaveBeenCalled();++ const videoButton = getButton('Select video clip.mp4, duration 0:02, for preview');+ await click(videoButton, { altKey: true });+ expect(actionMocks.selectItem).toHaveBeenCalledWith(video);++ await interact(() =>+ videoButton.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 23, clientY: 41 })+ )+ );+ expect(host?.querySelector('[data-testid="context-target"]')?.textContent).toBe(+ JSON.stringify([{ kind: 'video', name: 'clip.mp4' }])+ );+ });++ it('select-all targets ordered mixed refs while image-only hotkeys reject a mixed selection', async () => {+ const items = [createItem('image', 'shared'), createItem('video', 'shared')];+ await renderGallery(+ createGallery({+ items,+ selectedItemKey: 'video:shared',+ selectedItemKeys: ['image:shared', 'video:shared'],+ })+ );++ registeredCommands.get('gallery.selectAllOnPage')?.();+ registeredCommands.get('gallery.deleteSelection')?.();+ registeredCommands.get('gallery.starImage')?.();++ expect(actionMocks.selectItemRange).toHaveBeenCalledWith(+ [+ { kind: 'image', name: 'shared' },+ { kind: 'video', name: 'shared' },+ ],+ items[0]+ );+ expect(imageActionMocks.deleteImages).not.toHaveBeenCalled();+ expect(imageActionMocks.setImagesStarred).not.toHaveBeenCalled();+ });+});++describe('GalleryImageGrid range selection', () => {+ const orderedRefs: GalleryItemRef[] = [+ { kind: 'image', name: 'first.png' },+ { kind: 'video', name: 'middle.mp4' },+ { kind: 'image', name: 'last.png' },+ ];+ const rangeItems = [+ createItem('image', 'first.png'),+ createItem('video', 'middle.mp4'),+ createItem('image', 'last.png'),+ ];++ it('does not load names on render and lazily selects the backend-ordered mixed range on Shift-click', async () => {+ mocks.fetchNames.mockResolvedValue({ items: orderedRefs, starredCount: 0, total: orderedRefs.length });+ const gallery = createGallery({ items: rangeItems });++ await renderGallery(gallery);+ expect(mocks.fetchNames).not.toHaveBeenCalled();++ await click(getButton('Select last.png for preview'), { shiftKey: true });+ await vi.waitFor(() => expect(actionMocks.selectItemRange).toHaveBeenCalledWith(orderedRefs, rangeItems[2]));+ expect(mocks.fetchNames).toHaveBeenCalledOnce();+ });++ it('reuses the date board name list already in the query cache', async () => {+ const gallery = createGallery({+ boards: [{ ...board, id: 'by_date:2026-07-30', kind: 'date' }],+ items: rangeItems,+ selectedBoardId: 'by_date:2026-07-30',+ });+ const filter = {+ boardId: gallery.selectedBoardId,+ galleryView: gallery.galleryView,+ orderDir: gallery.settings.imageOrderDir,+ searchTerm: '',+ starredFirst: gallery.settings.starredFirst,+ };+ queryClient?.setQueryData(getNamesKey(filter), {+ items: orderedRefs,+ starredCount: 0,+ total: orderedRefs.length,+ });++ await renderGallery(gallery);+ await click(getButton('Select last.png for preview'), { shiftKey: true });++ expect(actionMocks.selectItemRange).toHaveBeenCalledWith(orderedRefs, rangeItems[2]);+ expect(mocks.fetchNames).not.toHaveBeenCalled();+ });++ it('ignores a names response after the filter identity changes', async () => {+ let resolveNames: ((value: { items: GalleryItemRef[]; starredCount: number; total: number }) => void) | null = null;+ mocks.fetchNames.mockReturnValue(+ new Promise((resolve) => {+ resolveNames = resolve;+ })+ );+ const gallery = createGallery({ items: rangeItems });++ await renderGallery(gallery);+ await click(getButton('Select last.png for preview'), { shiftKey: true });+ await renderGallery({ ...gallery, searchTerm: 'different filter' });+ await interact(() => resolveNames?.({ items: orderedRefs, starredCount: 0, total: orderedRefs.length }));++ expect(actionMocks.selectItemRange).not.toHaveBeenCalled();+ });++ it('ignores a names response after the account epoch changes', async () => {+ let resolveNames: ((value: { items: GalleryItemRef[]; starredCount: number; total: number }) => void) | null = null;+ mocks.fetchNames.mockReturnValue(+ new Promise((resolve) => {+ resolveNames = resolve;+ })+ );++ await renderGallery(createGallery({ items: rangeItems }));+ await click(getButton('Select last.png for preview'), { shiftKey: true });+ accountLifecycle.activate('other-grid-user');+ await interact(() => resolveNames?.({ items: orderedRefs, starredCount: 0, total: orderedRefs.length }));++ expect(actionMocks.selectItemRange).not.toHaveBeenCalled();+ });++ it('falls back to the materialized mixed range when the names request fails', async () => {+ mocks.fetchNames.mockRejectedValue(new Error('names unavailable'));++ await renderGallery(createGallery({ items: rangeItems }));+ await click(getButton('Select last.png for preview'), { shiftKey: true });++ await vi.waitFor(() => expect(actionMocks.selectItemRange).toHaveBeenCalledWith(orderedRefs, rangeItems[2]));+ });+});++describe('GalleryImageGrid virtualization', () => {+ it('retains constant row estimates, overscan, and the near-end infinite-load trigger', async () => {+ const items = Array.from({ length: 14 }, (_, index) => createItem('image', `image-${index}.png`));++ await renderGallery(+ createGallery({+ items,+ settings: { ...DEFAULT_GALLERY_SETTINGS, imageDensityPercent: 0, paginationMode: 'infinite' },+ })+ );+ await vi.waitFor(() => expect(actionMocks.loadMore).toHaveBeenCalled());++ const options = mocks.virtualizerOptions.at(-1);+ expect(options?.count).toBe(7);+ expect(options?.overscan).toBe(4);+ expect(options?.estimateSize()).toBe(options?.estimateSize());+ expect(host?.querySelector('[role="listitem"]')).toHaveStyle({ aspectRatio: '1 / 1' });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex 862ac28180..812525f426 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -1,19 +1,29 @@+import type { GalleryImageItem, GalleryItem, GalleryItemRef } from '@features/gallery/core/items';import type { GalleryThumbnailFit } from '@features/gallery/core/settings';-import type { GalleryImage } from '@features/gallery/core/types';import { Badge, Box, Flex, ProgressCircle, ScrollArea, Skeleton, Spinner, Text } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';import { CSS } from '@dnd-kit/utilities';-import { toGalleryItemKey } from '@features/gallery/contracts';+import {+ formatGalleryVideoDuration,+ isGalleryImageItem,+ toGalleryItemKey,+ toGalleryItemRef,+} from '@features/gallery/core/items';+import { isDateBoardId, type GalleryItemNames } from '@features/gallery/data/backend';+import { galleryItemNamesOptions, type GalleryItemsFilter } from '@features/gallery/data/queries';import { useQueueItemProgress, useQueueItemProgressImage } from '@features/queue/react';+import { parseDateTokens } from '@platform/search/dateTokens';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { DropZone, IconButton } from '@platform/ui';import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';-import { StarIcon, UploadIcon } from 'lucide-react';+import { useQueryClient } from '@tanstack/react-query';+import { PlayIcon, StarIcon, UploadIcon } from 'lucide-react';import {+ useCallback,useEffect,useEffectEvent,- useCallback,useLayoutEffect,useMemo,useRef,@@ -24,12 +34,11 @@ import {import { useVirtualizer } from 'react-hook-tanstack-virtual';import { useTranslation } from 'react-i18next';-import type { GalleryImageDragImage } from './galleryDnd';import type { GalleryQueuePlaceholder } from './galleryStateView';-import type { GalleryImageContextMenuTarget } from './GalleryUiContext';+import type { GalleryItemContextMenuTarget } from './GalleryUiContext';-import { getGalleryImageDragData, getGalleryImageDragId } from './galleryDnd';-import { getGalleryImageStateView, getGalleryPlaceholderInsertionIndex } from './galleryStateView';+import { getGalleryItemDragData, getGalleryItemDragId } from './galleryDnd';+import { getGalleryPlaceholderInsertionIndex } from './galleryStateView';import { useGalleryUi } from './GalleryUiContext';import { useGalleryWidget } from './GalleryWidgetContext';@@ -64,16 +73,34 @@ const getGalleryColumnCount = (imageDensityPercent: number, layout: 'stacked' |const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');+const getGalleryItemRange = (+ orderedRefs: readonly GalleryItemRef[],+ anchorItemKey: string,+ targetItemKey: string+): GalleryItemRef[] | null => {+ const anchorIndex = orderedRefs.findIndex((ref) => toGalleryItemKey(ref) === anchorItemKey);+ const targetIndex = orderedRefs.findIndex((ref) => toGalleryItemKey(ref) === targetItemKey);++ if (anchorIndex === -1 || targetIndex === -1) {+ return null;+ }++ const start = Math.min(anchorIndex, targetIndex);+ const end = Math.max(anchorIndex, targetIndex);++ return orderedRefs.slice(start, end + 1);+};+type GridCell =- | { kind: 'image'; image: GalleryImage; imageIndex: number }+ | { kind: 'item'; item: GalleryItem; itemIndex: number }| { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {const { t } = useTranslation();- const { actions, gallery: galleryState, imageActions, isWindowTruncated, runtime } = useGalleryWidget();- const gallery = useMemo(() => getGalleryImageStateView(galleryState), [galleryState]);+ const { actions, gallery, imageActions, isWindowTruncated, runtime } = useGalleryWidget();const { account, antialiasProgressImages, ImageContextMenu, widgets } = useGalleryUi();- const [contextMenuTarget, setContextMenuTarget] = useState<GalleryImageContextMenuTarget | null>(null);+ const queryClient = useQueryClient();+ const [contextMenuTarget, setContextMenuTarget] = useState<GalleryItemContextMenuTarget | null>(null);const [isDropActive, setIsDropActive] = useState(false);const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(layout) ?? 0);const dragDepthRef = useRef(0);@@ -81,24 +108,25 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>const { imageDensityPercent, imageOrderDir, paginationMode, showImageDimensions, starredFirst, thumbnailFit } =gallery.settings;const columnCount = getGalleryColumnCount(imageDensityPercent, layout);- const selectedNames = useMemo(() => new Set(gallery.selectedImageNames), [gallery.selectedImageNames]);+ const selectedItemKeys = useMemo(() => new Set(gallery.selectedItemKeys), [gallery.selectedItemKeys]);const isFollowingLive = gallery.currentItem?.kind === 'placeholder';const isComparisonActive =- gallery.compareImageName !== null &&- gallery.selectedImageName !== null &&- gallery.compareImageName !== gallery.selectedImageName;+ gallery.selectedItemKey?.startsWith('image:') === true &&+ gallery.compareImageKey !== null &&+ gallery.selectedItemKey !== null &&+ gallery.compareImageKey !== gallery.selectedItemKey;const selectedBoardName =gallery.boards.find((board) => board.id === gallery.selectedBoardId)?.name ??t('widgets.gallery.selectedBoardFallback');- const isEmpty = gallery.images.length === 0 && gallery.pendingPlaceholders.length === 0;+ const isEmpty = gallery.items.length === 0 && gallery.pendingPlaceholders.length === 0;- const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(gallery.images, imageOrderDir, starredFirst);+ const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(gallery.items, imageOrderDir, starredFirst);const cells = useMemo<GridCell[]>(() => {- const imageCells: GridCell[] = gallery.images.map((image, imageIndex) => ({- image,- imageIndex,- kind: 'image',+ const itemCells: GridCell[] = gallery.items.map((item, itemIndex) => ({+ item,+ itemIndex,+ kind: 'item',}));const placeholderCells: GridCell[] = gallery.pendingPlaceholders.map((placeholder) => ({kind: 'placeholder',@@ -106,14 +134,14 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>}));return [- ...imageCells.slice(0, placeholderInsertionIndex),+ ...itemCells.slice(0, placeholderInsertionIndex),...placeholderCells,- ...imageCells.slice(placeholderInsertionIndex),+ ...itemCells.slice(placeholderInsertionIndex),];- }, [gallery.images, gallery.pendingPlaceholders, placeholderInsertionIndex]);+ }, [gallery.items, gallery.pendingPlaceholders, placeholderInsertionIndex]);- const getCellIndexForImage = (imageIndex: number): number =>- imageIndex >= placeholderInsertionIndex ? imageIndex + gallery.pendingPlaceholders.length : imageIndex;+ const getCellIndexForItem = (itemIndex: number): number =>+ itemIndex >= placeholderInsertionIndex ? itemIndex + gallery.pendingPlaceholders.length : itemIndex;const rowCount = Math.ceil(cells.length / columnCount);@@ -176,92 +204,166 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>}}, [actions, lastVisibleRowIndex, paginationMode, rowCount]);+ const parsedSearch = useMemo(() => parseDateTokens(gallery.searchTerm), [gallery.searchTerm]);+ const itemNamesFilter = useMemo<GalleryItemsFilter>(+ () => ({+ boardId: gallery.selectedBoardId,+ ...(parsedSearch.range?.from ? { createdFrom: parsedSearch.range.from } : {}),+ ...(parsedSearch.range?.to ? { createdTo: parsedSearch.range.to } : {}),+ galleryView: gallery.galleryView,+ orderDir: imageOrderDir,+ searchTerm: parsedSearch.text,+ starredFirst,+ }),+ [gallery.galleryView, gallery.selectedBoardId, imageOrderDir, parsedSearch.range, parsedSearch.text, starredFirst]+ );+ const itemNamesFilterIdentity = useMemo(() => JSON.stringify(itemNamesFilter), [itemNamesFilter]);+ const rangeInteractionContextRef = useRef({+ filterIdentity: itemNamesFilterIdentity,+ selectedItemKey: gallery.selectedItemKey,+ });+ const syncRangeInteractionContext = useCallback(+ (node: HTMLDivElement | null) => {+ if (node) {+ rangeInteractionContextRef.current = {+ filterIdentity: itemNamesFilterIdentity,+ selectedItemKey: gallery.selectedItemKey,+ };+ }+ },+ [gallery.selectedItemKey, itemNamesFilterIdentity]+ );+const activeContextMenuTarget = useMemo(() => {- const primaryTargetImageName = contextMenuTarget?.images[0]?.imageName;+ const primaryTargetItem = contextMenuTarget?.items[0];- if (!primaryTargetImageName) {+ if (!primaryTargetItem) {return contextMenuTarget;}- return gallery.images.some((image) => image.imageName === primaryTargetImageName) ? contextMenuTarget : null;- }, [contextMenuTarget, gallery.images]);+ const primaryTargetItemKey = toGalleryItemKey(primaryTargetItem);- const handleThumbnailClick = useCallback(- (image: GalleryImage, event: MouseEvent) => {- if (event.shiftKey) {- const targetIndex = gallery.images.findIndex((candidate) => candidate.imageName === image.imageName);- const anchorIndex = gallery.images.findIndex((candidate) => candidate.imageName === gallery.selectedImageName);+ return gallery.items.some((item) => toGalleryItemKey(item) === primaryTargetItemKey) ? contextMenuTarget : null;+ }, [contextMenuTarget, gallery.items]);++ const selectItemRange = useCallback(+ async (item: GalleryItem) => {+ const owner = captureAccountScope();+ const capturedContext = rangeInteractionContextRef.current;+ const anchorItemKey = capturedContext.selectedItemKey;+ const targetItemKey = toGalleryItemKey(item);++ if (!anchorItemKey) {+ actions.selectItem(item);+ return;+ }- if (targetIndex !== -1 && anchorIndex !== -1 && targetIndex !== anchorIndex) {- const start = Math.min(anchorIndex, targetIndex);- const end = Math.max(anchorIndex, targetIndex);+ const isInteractionCurrent = () =>+ isAccountScopeCurrent(owner) &&+ rangeInteractionContextRef.current.filterIdentity === capturedContext.filterIdentity &&+ rangeInteractionContextRef.current.selectedItemKey === capturedContext.selectedItemKey;+ const selectFromRefs = (refs: readonly GalleryItemRef[]): boolean => {+ const range = getGalleryItemRange(refs, anchorItemKey, targetItemKey);- actions.selectImageRange(- gallery.images.slice(start, end + 1).map((candidate) => candidate.imageName),- image- );+ if (!range) {+ return false;+ }++ actions.selectItemRange(range, item);+ return true;+ };+ const materializedRefs = gallery.items.map(toGalleryItemRef);+ const namesOptions = galleryItemNamesOptions(itemNamesFilter);++ try {+ const orderedRefs = isDateBoardId(itemNamesFilter.boardId)+ ? queryClient.getQueryData<GalleryItemNames>(namesOptions.queryKey)?.items+ : (await queryClient.fetchQuery(namesOptions)).items;++ if (!isInteractionCurrent()) {+ return;+ }++ if (orderedRefs && selectFromRefs(orderedRefs)) {+ return;+ }+ } catch {+ if (!isInteractionCurrent()) {return;}}+ if (!selectFromRefs(materializedRefs)) {+ actions.selectItem(item);+ }+ },+ [actions, gallery.items, itemNamesFilter, queryClient]+ );++ const handleThumbnailClick = useCallback(+ (item: GalleryItem, event: MouseEvent) => {+ if (event.shiftKey) {+ void selectItemRange(item);+ return;+ }++ if (event.altKey && isGalleryImageItem(item)) {+ actions.setCompareItem(item);+ return;+ }+if (event.ctrlKey || event.metaKey) {- const itemKey = toGalleryItemKey({ kind: 'image', name: image.imageName });- const remainingItemKeys = galleryState.selectedItemKeys.filter((key) => key !== itemKey);+ const itemKey = toGalleryItemKey(item);+ const remainingItemKeys = gallery.selectedItemKeys.filter((key) => key !== itemKey);const nextPrimaryItem =- galleryState.selectedItemKey === itemKey- ? (galleryState.items.find(- (item) => toGalleryItemKey(item) === remainingItemKeys[remainingItemKeys.length - 1]+ gallery.selectedItemKey === itemKey+ ? (gallery.items.find(+ (candidate) => toGalleryItemKey(candidate) === remainingItemKeys[remainingItemKeys.length - 1]) ?? null): null;- actions.toggleImageInSelection(image, nextPrimaryItem);+ actions.toggleItemInSelection(item, nextPrimaryItem);} else {- actions.selectImage(image);+ actions.selectItem(item);}},- [- actions,- gallery.images,- gallery.selectedImageName,- galleryState.items,- galleryState.selectedItemKey,- galleryState.selectedItemKeys,- ]+ [actions, gallery.items, gallery.selectedItemKey, gallery.selectedItemKeys, selectItemRange]);const handleThumbnailContextMenu = useCallback(- (image: GalleryImage, x: number, y: number) => {- if (selectedNames.has(image.imageName) && selectedNames.size > 1) {- const selectionImages = [- image,- ...gallery.images.filter(- (candidate) => candidate.imageName !== image.imageName && selectedNames.has(candidate.imageName)+ (item: GalleryItem, x: number, y: number) => {+ const itemKey = toGalleryItemKey(item);++ if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {+ const selectionItems = [+ item,+ ...gallery.items.filter(+ (candidate) => toGalleryItemKey(candidate) !== itemKey && selectedItemKeys.has(toGalleryItemKey(candidate))),];- setContextMenuTarget({ images: selectionImages, x, y });+ setContextMenuTarget({ items: selectionItems, x, y });return;}- setContextMenuTarget({ images: [image], x, y });+ setContextMenuTarget({ items: [item], x, y });},- [gallery.images, selectedNames]+ [gallery.items, selectedItemKeys]);- const getDragImages = useCallback(- (image: GalleryImage): GalleryImageDragImage[] => {- if (selectedNames.has(image.imageName) && selectedNames.size > 1) {- return gallery.images- .filter((candidate) => selectedNames.has(candidate.imageName))- .map((candidate) => ({- boardId: candidate.boardId,- imageName: candidate.imageName,- }));+ const getDragItems = useCallback(+ (item: GalleryItem): GalleryItemRef[] => {+ const itemKey = toGalleryItemKey(item);++ if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {+ return gallery.items+ .filter((candidate) => selectedItemKeys.has(toGalleryItemKey(candidate)))+ .map(toGalleryItemRef);}- return [{ boardId: image.boardId, imageName: image.imageName }];+ return [toGalleryItemRef(item)];},- [gallery.images, selectedNames]+ [gallery.items, selectedItemKeys]);const handleDragEnter = useCallback((event: DragEvent) => {@@ -312,41 +414,57 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>}, [account]);const handleToggleStarred = useCallback(- (image: GalleryImage) => void imageActions.setImagesStarred([image.imageName], !image.starred),+ (item: GalleryImageItem) => void imageActions.setImagesStarred([item.name], !item.starred),[imageActions]);const handleCloseContextMenu = useCallback(() => setContextMenuTarget(null), []);+ // TODO(Task 7): Common item actions will consume the canonical selection.+ // Until then, reject video, mixed, or unresolved selections at the existing+ // image-only hotkey boundary.+ const imageOnlyActionSelection = useMemo<GalleryImageItem[] | null>(() => {+ const itemKeys =+ gallery.selectedItemKeys.length > 0+ ? gallery.selectedItemKeys+ : gallery.selectedItemKey+ ? [gallery.selectedItemKey]+ : [];+ const items = itemKeys.flatMap((itemKey) => {+ const item = gallery.items.find((candidate) => toGalleryItemKey(candidate) === itemKey);++ return item ? [item] : [];+ });++ return items.length === itemKeys.length && items.every(isGalleryImageItem) ? items : null;+ }, [gallery.items, gallery.selectedItemKey, gallery.selectedItemKeys]);+const navigate = useEffectEvent((direction: 'down' | 'left' | 'right' | 'up') => {- const imageCount = gallery.images.length;+ const itemCount = gallery.items.length;- if (imageCount === 0) {+ if (itemCount === 0) {return;}- const selectedIndex = gallery.images.findIndex((image) => image.imageName === gallery.selectedImageName);+ const selectedIndex = gallery.items.findIndex((item) => toGalleryItemKey(item) === gallery.selectedItemKey);const fallbackIndex = selectedIndex === -1 ? 0 : selectedIndex;const delta =direction === 'right' ? 1 : direction === 'left' ? -1 : direction === 'down' ? columnCount : -columnCount;- const nextIndex = Math.min(imageCount - 1, Math.max(0, fallbackIndex + delta));- const nextImage = gallery.images[nextIndex];+ const nextIndex = Math.min(itemCount - 1, Math.max(0, fallbackIndex + delta));+ const nextItem = gallery.items[nextIndex];- if (nextImage && (nextIndex !== selectedIndex || selectedIndex === -1)) {- actions.selectImage(nextImage);- virtualizer.scrollToIndex(Math.floor(getCellIndexForImage(nextIndex) / columnCount));+ if (nextItem && (nextIndex !== selectedIndex || selectedIndex === -1)) {+ actions.selectItem(nextItem);+ virtualizer.scrollToIndex(Math.floor(getCellIndexForItem(nextIndex) / columnCount));}});const executeGalleryHotkey = useEffectEvent((commandId: string) => {if (commandId === 'gallery.selectAllOnPage') {- const primaryImage = gallery.images[0];+ const primaryItem = gallery.items[0];- if (primaryImage) {- actions.selectImageRange(- gallery.images.map((image) => image.imageName),- primaryImage- );+ if (primaryItem) {+ actions.selectItemRange(gallery.items.map(toGalleryItemRef), primaryItem);}return;}@@ -360,24 +478,18 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>return;}- if (commandId === 'gallery.deleteSelection' && gallery.selectedImageNames.length > 0) {- void imageActions.deleteImages(gallery.selectedImageNames);+ if (commandId === 'gallery.deleteSelection' && imageOnlyActionSelection?.length) {+ void imageActions.deleteImages(imageOnlyActionSelection.map((item) => item.name));return;}- if (commandId === 'gallery.starImage') {- const imageNames = gallery.selectedImageNames.length- ? gallery.selectedImageNames- : gallery.selectedImageName- ? [gallery.selectedImageName]- : [];- const selectedImages = gallery.images.filter((image) => imageNames.includes(image.imageName));-- if (selectedImages.length > 0) {- const shouldStar = selectedImages.some((image) => !image.starred);+ if (commandId === 'gallery.starImage' && imageOnlyActionSelection?.length) {+ const shouldStar = imageOnlyActionSelection.some((item) => !item.starred);- void imageActions.setImagesStarred(imageNames, shouldStar);- }+ void imageActions.setImagesStarred(+ imageOnlyActionSelection.map((item) => item.name),+ shouldStar+ );}});@@ -417,6 +529,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>return (<Box+ ref={syncRangeInteractionContext}flex="1"maxW="full"minH="0"@@ -437,7 +550,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>) : (<ScrollArea.Root h="full" minH="0" size="xs" variant="hover" w="full"><ScrollArea.Viewport ref={viewportRef} h="full" w="full" outline="none">- <ScrollArea.Content aria-label={t('widgets.gallery.imagesAriaLabel')} role="list">+ <ScrollArea.Content aria-label={t('widgets.gallery.itemsAriaLabel')} role="list"><Box h={`${virtualizer.totalSize}px`} position="relative" w="full">{virtualRows.map((virtualRow) => (<Box@@ -469,20 +582,20 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>/>) : (<GalleryThumbnailCell- key={cell.image.imageName}+ key={toGalleryItemKey(cell.item)}alwaysShowDimensions={showImageDimensions}compareRole={- isComparisonActive && cell.image.imageName === gallery.selectedImageName+ isComparisonActive && toGalleryItemKey(cell.item) === gallery.selectedItemKey? t('widgets.preview.viewing')- : isComparisonActive && cell.image.imageName === gallery.compareImageName+ : isComparisonActive && toGalleryItemKey(cell.item) === gallery.compareImageKey? t('widgets.preview.compare'): null}fit={thumbnailFit}- getDragImages={getDragImages}- image={cell.image}- isPrimary={!isFollowingLive && cell.image.imageName === gallery.selectedImageName}- isSelected={!isFollowingLive && selectedNames.has(cell.image.imageName)}+ getDragItems={getDragItems}+ item={cell.item}+ isPrimary={!isFollowingLive && toGalleryItemKey(cell.item) === gallery.selectedItemKey}+ isSelected={!isFollowingLive && selectedItemKeys.has(toGalleryItemKey(cell.item))}onClick={handleThumbnailClick}onContextMenu={handleThumbnailContextMenu}onToggleStarred={handleToggleStarred}@@ -492,7 +605,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =></Box>))}</Box>- {paginationMode === 'infinite' && gallery.isLoading && gallery.images.length > 0 && (+ {paginationMode === 'infinite' && gallery.isLoading && gallery.items.length > 0 && (<Flex align="center" justify="center" py="2"><Spinner color="fg.subtle" size="xs" /></Flex>@@ -500,7 +613,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>{paginationMode === 'infinite' && !gallery.isLoading && isWindowTruncated && (<Flex align="center" justify="center" py="3"><Text color="fg.subtle" fontSize="xs" textAlign="center">- {t('widgets.gallery.windowLimit', { count: gallery.images.length })}+ {t('widgets.gallery.windowLimit', { count: gallery.items.length })}</Text></Flex>)}@@ -630,9 +743,9 @@ const GalleryPlaceholderCircularProgress = ({ percentage }: { percentage: numberconst GalleryThumbnail = ({alwaysShowDimensions,compareRole,- dragImages,+ dragItems,fit,- image,+ item,isPrimary,isSelected,onClick,@@ -641,21 +754,22 @@ const GalleryThumbnail = ({}: {alwaysShowDimensions: boolean;compareRole: string | null;- dragImages: GalleryImageDragImage[];+ dragItems: GalleryItemRef[];fit: GalleryThumbnailFit;- image: GalleryImage;+ item: GalleryItem;isPrimary: boolean;isSelected: boolean;- onClick: (image: GalleryImage, event: MouseEvent) => void;- onContextMenu: (image: GalleryImage, x: number, y: number) => void;- onToggleStarred: (image: GalleryImage) => void;+ onClick: (item: GalleryItem, event: MouseEvent) => void;+ onContextMenu: (item: GalleryItem, x: number, y: number) => void;+ onToggleStarred: (item: GalleryImageItem) => void;}) => {const { t } = useTranslation();const isCompared = compareRole !== null;+ const duration = item.kind === 'video' ? formatGalleryVideoDuration(item.durationSeconds) : null;const { isDragging, listeners, setNodeRef, transform } = useDraggable({- data: getGalleryImageDragData(dragImages),- id: getGalleryImageDragId(image.imageName),+ data: getGalleryItemDragData(dragItems),+ id: getGalleryItemDragId(toGalleryItemRef(item)),});const containerStyle = useMemo(() => ({ transform: CSS.Transform.toString(transform) }), [transform]);@@ -677,19 +791,22 @@ const GalleryThumbnail = ({const handleContextMenu = useCallback((event: MouseEvent) => {event.preventDefault();- onContextMenu(image, event.clientX, event.clientY);+ onContextMenu(item, event.clientX, event.clientY);},- [image, onContextMenu]+ [item, onContextMenu]);- const handleClick = useCallback((event: MouseEvent) => onClick(image, event), [image, onClick]);+ const handleClick = useCallback((event: MouseEvent) => onClick(item, event), [item, onClick]);const handleToggleStarred = useCallback((event: MouseEvent<HTMLButtonElement>) => {event.stopPropagation();- onToggleStarred(image);++ if (isGalleryImageItem(item)) {+ onToggleStarred(item);+ }},- [image, onToggleStarred]+ [item, onToggleStarred]);return (@@ -716,13 +833,23 @@ const GalleryThumbnail = ({><buttonaria-current={isPrimary ? 'true' : undefined}- aria-label={t('widgets.gallery.selectImageForPreview', { name: image.imageName })}+ aria-label={+ item.kind === 'video'+ ? t('widgets.gallery.selectVideoForPreview', { duration, name: item.name })+ : t('widgets.gallery.selectImageForPreview', { name: item.name })+ }aria-pressed={isSelected}style={THUMBNAIL_BUTTON_STYLE}type="button"onClick={handleClick}>- <img alt={image.imageName} draggable={false} src={image.thumbnailUrl || image.imageUrl} style={imageStyle} />+ <img+ alt={item.name}+ decoding={item.kind === 'video' ? 'async' : undefined}+ draggable={false}+ src={item.thumbnailUrl || item.fullUrl}+ style={imageStyle}+ /></button>{compareRole && (<Badge@@ -737,27 +864,29 @@ const GalleryThumbnail = ({{compareRole}</Badge>)}- <IconButton- aria-label={- image.starred- ? t('widgets.gallery.unstarImage', { name: image.imageName })- : t('widgets.gallery.starImage', { name: image.imageName })- }- className="gallery-thumb-overlay"- colorPalette={image.starred ? 'yellow' : 'gray'}- insetInlineEnd="1"- opacity={image.starred ? 1 : 0}- position="absolute"- size="2xs"- top="1"- transition="opacity var(--wb-motion-duration-medium) ease"- variant="solid"- zIndex="1"- onClick={handleToggleStarred}- >- <StarIcon fill={image.starred ? 'currentColor' : 'none'} />- </IconButton>- {image.width > 0 && image.height > 0 && (+ {item.kind === 'image' ? (+ <IconButton+ aria-label={+ item.starred+ ? t('widgets.gallery.unstarImage', { name: item.name })+ : t('widgets.gallery.starImage', { name: item.name })+ }+ className="gallery-thumb-overlay"+ colorPalette={item.starred ? 'yellow' : 'gray'}+ insetInlineEnd="1"+ opacity={item.starred ? 1 : 0}+ position="absolute"+ size="2xs"+ top="1"+ transition="opacity var(--wb-motion-duration-medium) ease"+ variant="solid"+ zIndex="1"+ onClick={handleToggleStarred}+ >+ <StarIcon fill={item.starred ? 'currentColor' : 'none'} />+ </IconButton>+ ) : null}+ {item.kind === 'image' && item.width > 0 && item.height > 0 && (<Badgebottom="1"className="gallery-thumb-overlay"@@ -770,7 +899,26 @@ const GalleryThumbnail = ({variant="solid"zIndex="1">- {image.width}x{image.height}+ {item.width}x{item.height}+ </Badge>+ )}+ {duration !== null && (+ <Badge+ bottom="1"+ display="flex"+ fontVariantNumeric="tabular-nums"+ gap="1"+ insetInlineStart="1"+ opacity={1}+ pointerEvents="none"+ position="absolute"+ size="xs"+ transition="opacity var(--wb-motion-duration-medium) ease"+ variant="solid"+ zIndex="1"+ >+ <PlayIcon aria-hidden="true" fill="currentColor" />+ {duration}</Badge>)}</Box>@@ -778,13 +926,13 @@ const GalleryThumbnail = ({};const GalleryThumbnailCell = ({- image,- getDragImages,+ item,+ getDragItems,...props-}: Omit<Parameters<typeof GalleryThumbnail>[0], 'dragImages'> & {- getDragImages: (image: GalleryImage) => GalleryImageDragImage[];+}: Omit<Parameters<typeof GalleryThumbnail>[0], 'dragItems'> & {+ getDragItems: (item: GalleryItem) => GalleryItemRef[];}) => {- const dragImages = useMemo(() => getDragImages(image), [getDragImages, image]);+ const dragItems = useMemo(() => getDragItems(item), [getDragItems, item]);- return <GalleryThumbnail {...props} dragImages={dragImages} image={image} />;+ return <GalleryThumbnail {...props} dragItems={dragItems} item={item} />;};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 5f6e749af6..d4232c6260 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -1,4 +1,4 @@-import type { GalleryItem } from '@features/gallery/contracts';+import type { GalleryImageItem, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/contracts';import type { GallerySettings } from '@features/gallery/core/settings';import type { GalleryBoard, GalleryBoardDeletionResult, GalleryImage, GalleryView } from '@features/gallery/core/types';import type { QueueItem } from '@features/queue/contracts';@@ -9,6 +9,11 @@ import type { GalleryLiveTarget } from './galleryStateView';export interface GalleryImageActions {deleteImages(imageNames: string[]): Promise<void>;+ /**+ * TODO(Task 7): Move this narrow board-drop intent to `GalleryItemActions`+ * when common item mutations gain their mixed-media implementation.+ */+ moveItemsToBoard(items: GalleryItemRef[], boardId: string): Promise<void>;moveImagesToBoard(imageNames: string[], boardId: string): Promise<void>;setImagesStarred(imageNames: string[], starred: boolean): Promise<void>;}@@ -20,30 +25,34 @@ export interface GalleryImageActionsOptions {projectId: string;}-export interface GalleryImageContextMenuTarget {- images: GalleryImage[];+export interface GalleryItemContextMenuTarget {+ items: GalleryItem[];x: number;y: number;}-export interface GalleryImageContextMenuProps {+export interface GalleryItemContextMenuProps {actions: GalleryImageActions;boards: GalleryBoard[];- target: GalleryImageContextMenuTarget | null;+ target: GalleryItemContextMenuTarget | null;onClose(): void;}export interface GalleryCommandsPort {reconcileDeletedBoardOutcome(outcome: GalleryBoardDeletionResult): void;selectBoard(boardId: string): void;+ selectItem(item: GalleryItem): void;selectImage(image: GalleryImage): void;+ setCompareItem(image: GalleryImageItem | null): void;setCompareImage(image: GalleryImage | null): void;+ setItemMultiSelection(itemKeys: GalleryItemKey[], primaryItem: GalleryItem): void;setMultiSelection(imageNames: string[], primaryImage: GalleryImage): void;setPage(page: number): void;setPageInfo(totalImages: number): void;setProjectBoard(boardId: string): void;setSearchTerm(searchTerm: string): void;setView(view: GalleryView): void;+ toggleItemSelection(item: GalleryItem, nextPrimaryItem: GalleryItem | null): void;toggleImageSelection(image: GalleryImage, nextPrimaryItem: GalleryItem | null): void;updateSettings(settings: Partial<GallerySettings>): void;}@@ -74,7 +83,7 @@ export interface GalleryWidgetProps {*/export interface GalleryUiAdapter {ImageActionsProvider: ComponentType<GalleryImageActionsOptions & { children: ReactNode }>;- ImageContextMenu: ComponentType<GalleryImageContextMenuProps>;+ ImageContextMenu: ComponentType<GalleryItemContextMenuProps>;account: { enableLiveFollow(): void };antialiasProgressImages: boolean;gallery: GalleryCommandsPort;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex 2b26dbc2c5..5efc81e33b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -1,6 +1,6 @@-import type { GalleryItem } from '@features/gallery/contracts';+import type { GalleryImageItem, GalleryItem, GalleryItemRef } from '@features/gallery/contracts';import type { GallerySettings } from '@features/gallery/core/settings';-import type { GalleryImage, GalleryView } from '@features/gallery/core/types';+import type { GalleryView } from '@features/gallery/core/types';import { createContext, use } from 'react';@@ -22,12 +22,13 @@ export interface GalleryActions {refresh: () => void;renameBoard: (boardId: string, boardName: string) => Promise<void>;selectBoard: (boardId: string) => void;- selectImage: (image: GalleryImage) => void;- selectImageRange: (imageNames: string[], primaryImage: GalleryImage) => void;+ selectItem: (item: GalleryItem) => void;+ selectItemRange: (items: GalleryItemRef[], primaryItem: GalleryItem) => void;selectProjectBoard: () => Promise<void>;+ setCompareItem: (image: GalleryImageItem | null) => void;setSearchTerm: (searchTerm: string) => void;setView: (galleryView: GalleryView) => void;- toggleImageInSelection: (image: GalleryImage, nextPrimaryItem: GalleryItem | null) => void;+ toggleItemInSelection: (item: GalleryItem, nextPrimaryItem: GalleryItem | null) => void;updateSettings: (settings: Partial<GallerySettings>) => void;uploadFiles: (files: File[]) => Promise<void>;}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex 6fd0c592f0..069b6408a4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -1,3 +1,4 @@+import { toGalleryItemKey } from '@features/gallery/core/items';import { getBoundedRecentImages } from '@features/gallery/core/recentImages';import { getGallerySettings } from '@features/gallery/core/settings';import { GALLERY_PAGE_SIZE } from '@features/gallery/data/queries';@@ -10,7 +11,6 @@ import type { GalleryStateView } from './galleryStateView';import { GalleryPanelContent } from './GalleryPanelContent';import {getGalleryPage,- getGalleryImageStateView,getGalleryProjectBoardId,getGallerySearchTerm,getGallerySelectedBoardId,@@ -77,39 +77,37 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgliveFollowEnabled,liveProgressTarget);- const imageGallery = useMemo(() => getGalleryImageStateView(gallery), [gallery]);-const lastPublishedTotalRef = useRef<number | null>(null);- // After a deletion that takes out the previewed image, move the selection to- // the image that now occupies the old index, else the one before it.+ // After a deletion that takes out the previewed item, move the selection to+ // the item that now occupies the old index, else the one before it.const onImagesDeleted = useCallback((imageNames: string[]) => {- const deletedNames = new Set(imageNames);- const images = imageGallery.images;- const anchorName = imageGallery.selectedImageName;+ const deletedItemKeys = new Set(imageNames.map((name) => toGalleryItemKey({ kind: 'image', name })));+ const items = gallery.items;+ const anchorKey = gallery.selectedItemKey;- if (!anchorName || !deletedNames.has(anchorName)) {+ if (!anchorKey || !deletedItemKeys.has(anchorKey)) {return;}- const anchorIndex = images.findIndex((image) => image.imageName === anchorName);+ const anchorIndex = items.findIndex((item) => toGalleryItemKey(item) === anchorKey);if (anchorIndex === -1) {return;}- const remaining = images.filter((image) => !deletedNames.has(image.imageName));- const remainingBeforeAnchor = images+ const remaining = items.filter((item) => !deletedItemKeys.has(toGalleryItemKey(item)));+ const remainingBeforeAnchor = items.slice(0, anchorIndex)- .filter((image) => !deletedNames.has(image.imageName)).length;- const nextImage = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;+ .filter((item) => !deletedItemKeys.has(toGalleryItemKey(item))).length;+ const nextItem = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;- if (nextImage) {- galleryCommands.selectImage(nextImage);+ if (nextItem) {+ galleryCommands.selectItem(nextItem);}},- [galleryCommands, imageGallery.images, imageGallery.selectedImageName]+ [gallery.items, gallery.selectedItemKey, galleryCommands]);const actions = useGalleryActions({diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.tsindex b9bb1f188c..a4214779bd 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts@@ -1,27 +1,130 @@+import type { GalleryItem } from '@features/gallery/contracts';+import { describe, expect, it } from 'vitest';import {getGalleryBoardDropData,- getGalleryImageDragData,- getGalleryImageNamesOutsideBoard,+ getGalleryItemDragData,+ getGalleryItemDragId,isGalleryBoardDropData,isGalleryImageDragData,+ isGalleryItemDragData,+ resolveGalleryBoardDrop,} from './galleryDnd';+const createItem = (kind: GalleryItem['kind'], name: string, boardId: string): GalleryItem => {+ const base = {+ boardId,+ category: 'general' as const,+ createdAt: '2026-07-30T00:00:00.000Z',+ fullUrl: `/full/${name}`,+ height: 64,+ isIntermediate: false,+ name,+ starred: false,+ thumbnailUrl: `/thumbnail/${name}`,+ width: 64,+ };++ return kind === 'video' ? { ...base, durationSeconds: 12.4, kind } : { ...base, kind };+};+describe('galleryDnd', () => {- it('keeps only images outside the target board', () => {- const dragData = getGalleryImageDragData([- { boardId: 'board-a', imageName: 'own.png' },- { boardId: 'board-b', imageName: 'other.png' },- { boardId: 'none', imageName: 'uncategorized.png' },+ it('constructs the shared item payload and uses qualified item keys as draggable ids', () => {+ const refs = [+ { kind: 'image', name: 'shared' },+ { kind: 'video', name: 'shared' },+ ] as const;++ expect(getGalleryItemDragData(refs)).toEqual({+ items: refs,+ kind: 'gallery-item',+ });+ expect(getGalleryItemDragId(refs[0])).toBe('image:shared');+ expect(getGalleryItemDragId(refs[1])).toBe('video:shared');+ });++ it('recognizes only non-empty, well-formed gallery item payloads', () => {+ expect(isGalleryItemDragData(getGalleryItemDragData([{ kind: 'video', name: 'clip.mp4' }]))).toBe(true);+ expect(isGalleryItemDragData({ items: [], kind: 'gallery-item' })).toBe(false);+ expect(isGalleryItemDragData({ items: [{ kind: 'video' }], kind: 'gallery-item' })).toBe(false);+ expect(+ isGalleryItemDragData({ images: [{ boardId: 'none', imageName: 'legacy.png' }], kind: 'gallery-image' })+ ).toBe(false);+ });++ it('refines a non-empty all-image payload and exposes image names without a video cast', () => {+ const getImageNames = (value: unknown): string[] =>+ isGalleryImageDragData(value) ? value.items.map((item) => item.name) : [];+ const imagePayload = getGalleryItemDragData([+ { kind: 'image', name: 'first.png' },+ { kind: 'image', name: 'second.png' },]);- expect(getGalleryImageNamesOutsideBoard(dragData, 'board-a')).toEqual(['other.png', 'uncategorized.png']);+ expect(getImageNames(imagePayload)).toEqual(['first.png', 'second.png']);+ expect(isGalleryImageDragData(getGalleryItemDragData([{ kind: 'video', name: 'clip.mp4' }]))).toBe(false);+ expect(+ isGalleryImageDragData(+ getGalleryItemDragData([+ { kind: 'image', name: 'still.png' },+ { kind: 'video', name: 'clip.mp4' },+ ])+ )+ ).toBe(false);+ expect(isGalleryImageDragData({ items: [], kind: 'gallery-item' })).toBe(false);});- it('recognizes gallery image drag data', () => {- expect(isGalleryImageDragData(getGalleryImageDragData([{ boardId: 'none', imageName: 'image.png' }]))).toBe(true);- expect(isGalleryImageDragData({ images: [{ boardId: 'none' }], kind: 'gallery-image' })).toBe(false);+ it('forwards ordered image, video, and mixed refs to real board drops', () => {+ const imageRef = { kind: 'image', name: 'image.png' } as const;+ const videoRef = { kind: 'video', name: 'video.mp4' } as const;+ const boardDrop = getGalleryBoardDropData('board-b', 'board');++ expect(resolveGalleryBoardDrop(getGalleryItemDragData([imageRef]), boardDrop, [])).toEqual({+ boardId: 'board-b',+ items: [imageRef],+ });+ expect(resolveGalleryBoardDrop(getGalleryItemDragData([videoRef]), boardDrop, [])).toEqual({+ boardId: 'board-b',+ items: [videoRef],+ });+ expect(resolveGalleryBoardDrop(getGalleryItemDragData([videoRef, imageRef]), boardDrop, [])).toEqual({+ boardId: 'board-b',+ items: [videoRef, imageRef],+ });+ });++ it('uses canonical loaded item identity to exclude only refs already on the destination board', () => {+ const dragData = getGalleryItemDragData([+ { kind: 'image', name: 'shared' },+ { kind: 'video', name: 'shared' },+ { kind: 'image', name: 'other.png' },+ ]);+ const loadedItems = [+ createItem('image', 'shared', 'board-a'),+ createItem('video', 'shared', 'board-b'),+ createItem('image', 'other.png', 'none'),+ ];++ expect(resolveGalleryBoardDrop(dragData, getGalleryBoardDropData('board-a', 'board'), loadedItems)).toEqual({+ boardId: 'board-a',+ items: [+ { kind: 'video', name: 'shared' },+ { kind: 'image', name: 'other.png' },+ ],+ });+ });++ it('rejects non-item drags, virtual-board drops, and drops with no item left to move', () => {+ const image = createItem('image', 'image.png', 'board-a');+ const dragData = getGalleryItemDragData([{ kind: 'image', name: image.name }]);++ expect(+ resolveGalleryBoardDrop({ kind: 'widget-instance' }, getGalleryBoardDropData('board-b', 'board'), [image])+ ).toBe(null);+ expect(+ resolveGalleryBoardDrop(dragData, getGalleryBoardDropData('by_date:2026-07-30', 'date'), [image])+ ).toBeNull();+ expect(resolveGalleryBoardDrop(dragData, getGalleryBoardDropData('board-a', 'board'), [image])).toBeNull();});it('recognizes gallery board drop data', () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.tsindex 8cfd20779e..052f7b39e1 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts@@ -1,13 +1,19 @@+import type { GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/core/items';import type { GalleryBoardKind } from '@features/gallery/core/types';-export interface GalleryImageDragImage {- boardId: string;- imageName: string;+import { toGalleryItemKey } from '@features/gallery/core/items';++export interface GalleryItemDragData {+ kind: 'gallery-item';+ items: GalleryItemRef[];+}++export interface GalleryImageDragItem extends GalleryItemRef {+ kind: 'image';}-export interface GalleryImageDragData {- kind: 'gallery-image';- images: GalleryImageDragImage[];+export interface GalleryImageDragData extends GalleryItemDragData {+ items: [GalleryImageDragItem, ...GalleryImageDragItem[]];}export interface GalleryBoardDropData {@@ -16,13 +22,18 @@ export interface GalleryBoardDropData {kind: 'gallery-board';}-export const getGalleryImageDragId = (imageName: string): string => `gallery-image:${imageName}`;+export interface GalleryBoardDropResolution {+ boardId: string;+ items: GalleryItemRef[];+}++export const getGalleryItemDragId = (item: GalleryItemRef): GalleryItemKey => toGalleryItemKey(item);export const getGalleryBoardDropId = (boardId: string): string => `gallery-board:${boardId}`;-export const getGalleryImageDragData = (images: GalleryImageDragImage[]): GalleryImageDragData => ({- images,- kind: 'gallery-image',+export const getGalleryItemDragData = (items: readonly GalleryItemRef[]): GalleryItemDragData => ({+ items: [...items],+ kind: 'gallery-item',});export const getGalleryBoardDropData = (boardId: string, boardKind: GalleryBoardKind): GalleryBoardDropData => ({@@ -31,13 +42,15 @@ export const getGalleryBoardDropData = (boardId: string, boardKind: GalleryBoardkind: 'gallery-board',});-export const isGalleryImageDragData = (value: unknown): value is GalleryImageDragData =>+export const isGalleryItemDragData = (value: unknown): value is GalleryItemDragData =>isRecord(value) &&- value.kind === 'gallery-image' &&- Array.isArray(value.images) &&- value.images.every(- (image) => isRecord(image) && typeof image.imageName === 'string' && typeof image.boardId === 'string'- );+ value.kind === 'gallery-item' &&+ Array.isArray(value.items) &&+ value.items.length > 0 &&+ value.items.every(isGalleryItemRef);++export const isGalleryImageDragData = (value: unknown): value is GalleryImageDragData =>+ isGalleryItemDragData(value) && value.items.every((item): item is GalleryImageDragItem => item.kind === 'image');export const isGalleryBoardDropData = (value: unknown): value is GalleryBoardDropData =>isRecord(value) &&@@ -45,10 +58,37 @@ export const isGalleryBoardDropData = (value: unknown): value is GalleryBoardDrotypeof value.boardId === 'string' &&isGalleryBoardKind(value.boardKind);-export const getGalleryImageNamesOutsideBoard = (dragData: GalleryImageDragData, boardId: string): string[] =>- dragData.images.filter((image) => image.boardId !== boardId).map((image) => image.imageName);+export const getGalleryItemRefsOutsideBoard = (+ dragData: GalleryItemDragData,+ boardId: string,+ loadedItems: readonly GalleryItem[]+): GalleryItemRef[] => {+ const loadedItemsByKey = new Map(loadedItems.map((item) => [toGalleryItemKey(item), item]));++ return dragData.items.filter((ref) => loadedItemsByKey.get(toGalleryItemKey(ref))?.boardId !== boardId);+};++export const resolveGalleryBoardDrop = (+ activeData: unknown,+ overData: unknown,+ loadedItems: readonly GalleryItem[]+): GalleryBoardDropResolution | null => {+ if (!isGalleryItemDragData(activeData) || !isGalleryBoardDropData(overData) || overData.boardKind !== 'board') {+ return null;+ }++ const items = getGalleryItemRefsOutsideBoard(activeData, overData.boardId, loadedItems);++ return items.length > 0 ? { boardId: overData.boardId, items } : null;+};const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;+const isGalleryItemRef = (value: unknown): value is GalleryItemRef =>+ isRecord(value) &&+ (value.kind === 'image' || value.kind === 'video') &&+ typeof value.name === 'string' &&+ value.name.length > 0;+const isGalleryBoardKind = (value: unknown): value is GalleryBoardKind =>value === 'board' || value === 'date' || value === 'uncategorized';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 01fcb3c0c5..edd0604086 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -2,8 +2,6 @@ import type { GalleryBoard, GalleryImage, GalleryOrderDir, GalleryView } from '@import type { QueueItem } from '@features/queue/contracts';import {- galleryImageItemToGalleryImage,- isGalleryImageItem,legacyGeneratedImageToGalleryItem,parseGalleryItemKey,toGalleryItemKey,@@ -435,33 +433,6 @@ export const getGalleryStateView = (};};-export interface GalleryImageStateView extends GalleryStateView {- compareImageName: string | null;- images: GalleryImage[];- selectedImageName: string | null;- selectedImageNames: string[];-}--/**- * TODO(Task 6): Remove when the Gallery grid renders `GalleryItem` directly.- * This is the only image-only Gallery projection and it narrows by kind before- * producing any `GalleryImage` contract.- */-export const getGalleryImageStateView = (gallery: GalleryStateView): GalleryImageStateView => ({- ...gallery,- compareImageName: gallery.compareImageKey ? parseGalleryItemKey(gallery.compareImageKey).name : null,- images: gallery.items.filter(isGalleryImageItem).map(galleryImageItemToGalleryImage),- selectedImageName:- gallery.selectedItemKey && parseGalleryItemKey(gallery.selectedItemKey).kind === 'image'- ? parseGalleryItemKey(gallery.selectedItemKey).name- : null,- selectedImageNames: gallery.selectedItemKeys.flatMap((key) => {- const ref = parseGalleryItemKey(key);-- return ref.kind === 'image' ? [ref.name] : [];- }),-});-export const getBoardCounts = (board: GalleryBoard): { assetCount: number; imageCount: number } => ({assetCount: board.assetCount,imageCount: board.imageCount,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex 130358d90c..d9c1672245 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -32,6 +32,7 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;const actionsRef = createRef<GalleryActions>();const reconcileDeletedBoardOutcome = vi.fn();+const setItemMultiSelection = vi.fn();(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const Probe = ({ ref }: { ref: Ref<GalleryActions> }) => {@@ -70,7 +71,10 @@ const adapter: GalleryUiAdapter = {reconcileDeletedBoardOutcome,selectBoard: noop,selectImage: noop,+ selectItem: noop,setCompareImage: noop,+ setCompareItem: noop,+ setItemMultiSelection,setMultiSelection: noop,setPage: noop,setPageInfo: noop,@@ -78,6 +82,7 @@ const adapter: GalleryUiAdapter = {setSearchTerm: noop,setView: noop,toggleImageSelection: noop,+ toggleItemSelection: noop,updateSettings: noop,},galleryValues: {},@@ -137,3 +142,32 @@ describe('deleteBoard', () => {expect(reconcileDeletedBoardOutcome).toHaveBeenCalledWith(outcome);});});++describe('mixed item selection', () => {+ it('forwards an ordered same-name mixed range as qualified item keys', () => {+ const primaryItem = {+ boardId: 'board-1',+ category: 'general',+ createdAt: '2026-07-30T00:00:00.000Z',+ durationSeconds: 3,+ fullUrl: '/full/shared',+ height: 64,+ isIntermediate: false,+ kind: 'video',+ name: 'shared',+ starred: false,+ thumbnailUrl: '/thumbnail/shared',+ width: 64,+ } as const;++ actionsRef.current?.selectItemRange(+ [+ { kind: 'image', name: 'shared' },+ { kind: 'video', name: 'shared' },+ ],+ primaryItem+ );++ expect(setItemMultiSelection).toHaveBeenCalledWith(['image:shared', 'video:shared'], primaryItem);+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex 1b658933bd..7785774bba 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -1,5 +1,6 @@import type { GalleryBoard } from '@features/gallery/core/types';+import { toGalleryItemKey } from '@features/gallery/core/items';import {createGalleryBoard,deleteGalleryBoard,@@ -156,8 +157,8 @@ export const useGalleryActions = ({}},selectBoard: gallery.selectBoard,- selectImage: gallery.selectImage,- selectImageRange: gallery.setMultiSelection,+ selectItem: gallery.selectItem,+ selectItemRange: (items, primaryItem) => gallery.setItemMultiSelection(items.map(toGalleryItemKey), primaryItem),selectProjectBoard: async () => {const owner = captureAccountScope();@@ -186,9 +187,10 @@ export const useGalleryActions = ({recordError(error);}},+ setCompareItem: gallery.setCompareItem,setSearchTerm: gallery.setSearchTerm,setView: gallery.setView,- toggleImageInSelection: gallery.toggleImageSelection,+ toggleItemInSelection: gallery.toggleItemSelection,updateSettings: gallery.updateSettings,uploadFiles: async (files) => {const owner = captureAccountScope();diff --git a/invokeai/frontend/webv2/src/features/gallery/utility.ts b/invokeai/frontend/webv2/src/features/gallery/utility.tsindex 2447c09202..f7fb292acf 100644--- a/invokeai/frontend/webv2/src/features/gallery/utility.ts+++ b/invokeai/frontend/webv2/src/features/gallery/utility.ts@@ -1,14 +1,18 @@export {getGalleryBoardDropData,getGalleryBoardDropId,- getGalleryImageDragData,- getGalleryImageDragId,- getGalleryImageNamesOutsideBoard,+ getGalleryItemDragData,+ getGalleryItemDragId,+ getGalleryItemRefsOutsideBoard,isGalleryBoardDropData,isGalleryImageDragData,+ isGalleryItemDragData,+ resolveGalleryBoardDrop,type GalleryBoardDropData,+ type GalleryBoardDropResolution,type GalleryImageDragData,- type GalleryImageDragImage,+ type GalleryImageDragItem,+ type GalleryItemDragData,} from './ui/galleryDnd';import { getGalleryImageFullUrl, getGalleryImageThumbnailUrl } from './data/imageUrls';diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsxindex e95e6bafdb..11bc77e4a1 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx@@ -201,7 +201,7 @@ export const GenerateReferenceImagesSection = ({const data = event.active.data.current;if (event.over?.id === 'generate-reference-images' && isGalleryImageDragData(data) && canAdd) {- void addGalleryImages(data.images.map((image) => image.imageName));+ void addGalleryImages(data.items.map((item) => item.name));}},});diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsxindex b5539c8edd..b121581316 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx@@ -367,8 +367,8 @@ const UpscaleImageField = ({onDragEnd: (event) => {const data = event.active.data.current;- if (!isLoading && event.over?.id === DROP_ID && isGalleryImageDragData(data) && data.images.length === 1) {- const imageName = data.images[0]?.imageName;+ if (!isLoading && event.over?.id === DROP_ID && isGalleryImageDragData(data) && data.items.length === 1) {+ const imageName = data.items[0]?.name;if (imageName) {void setGalleryImage(imageName);diff --git a/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts b/invokeai/frontend/webv2/src/workbench/widgetDnd.test.tsindex 9e6861e339..2028cf40dc 100644--- a/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetDnd.test.ts@@ -2,7 +2,7 @@ import type { CollisionDetection, DroppableContainer } from '@dnd-kit/core';import type { Project, WorkbenchState } from '@workbench/projectContracts';import type { WidgetTypeId } from '@workbench/widgetContracts';-import { getGalleryImageDragData } from '@features/gallery/utility';+import { getGalleryItemDragData } from '@features/gallery/utility';import { describe, expect, it } from 'vitest';import {@@ -193,7 +193,7 @@ describe('widget collision detection', () => {it('routes a gallery image drag to an inner canvas target instead of its enclosing widget', () => {const collisions = widgetCollisionDetection(createCollisionArgs({- activeData: getGalleryImageDragData([{ boardId: 'none', imageName: 'image.png' }]),+ activeData: getGalleryItemDragData([{ kind: 'image', name: 'image.png' }]),droppables: [{data: getWidgetInstanceDragData('center', 'canvas', 'canvas'),@@ -283,7 +283,7 @@ describe('widget collision detection', () => {it('excludes widget droppables from the no-pointer closest-center fallback for non-widget drags', () => {const collisions = widgetCollisionDetection(createCollisionArgs({- activeData: getGalleryImageDragData([{ boardId: 'none', imageName: 'image.png' }]),+ activeData: getGalleryItemDragData([{ kind: 'image', name: 'image.png' }]),collisionRect: getRect(0, 0, 20, 20),droppables: [{diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.tsindex 9259b3e0c6..956df596ab 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts@@ -31,7 +31,7 @@ export const resolveCanvasImageDrop = (activeData: unknown, overData: unknown):return {destination: overData.destination,- imageNames: activeData.images.map((image) => image.imageName),+ imageNames: activeData.items.map((item) => item.name),};};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.tsindex ab05fcbf31..127c7ce973 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDropLayout.test.ts@@ -3,7 +3,7 @@ import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngiimport type { Project } from '@workbench/projectContracts';import type { WorkbenchCanvasCommands } from '@workbench/workbenchStore';-import { getGalleryImageDragData } from '@features/gallery/utility';+import { getGalleryItemDragData } from '@features/gallery/utility';import { describe, expect, it } from 'vitest';import {@@ -54,13 +54,13 @@ describe('canvas image drop layout', () => {});describe('resolveCanvasImageDrop', () => {- const galleryDrag = getGalleryImageDragData([- { boardId: 'board-a', imageName: 'third.png' },- { boardId: 'board-b', imageName: 'first.png' },- { boardId: 'board-a', imageName: 'second.png' },+ const galleryDrag = getGalleryItemDragData([+ { kind: 'image', name: 'third.png' },+ { kind: 'image', name: 'first.png' },+ { kind: 'image', name: 'second.png' },]);- it('accepts a gallery-image to canvas-image-target pair and preserves requested order', () => {+ it('accepts an all-image gallery item payload and preserves requested order', () => {expect(resolveCanvasImageDrop(galleryDrag, getCanvasImageDropData('control-resized'))).toEqual({destination: 'control-resized',imageNames: ['third.png', 'first.png', 'second.png'],@@ -70,10 +70,18 @@ describe('resolveCanvasImageDrop', () => {it.each([[null, getCanvasImageDropData('raster')],[{ kind: 'widget-instance' }, getCanvasImageDropData('raster')],+ [getGalleryItemDragData([{ kind: 'video', name: 'clip.mp4' }]), getCanvasImageDropData('raster')],+ [+ getGalleryItemDragData([+ { kind: 'image', name: 'still.png' },+ { kind: 'video', name: 'clip.mp4' },+ ]),+ getCanvasImageDropData('raster'),+ ],[galleryDrag, null],[galleryDrag, { destination: 'raster', kind: 'widget-region' }],[galleryDrag, { destination: 'regional-guidance', kind: 'canvas-image-target' }],- ])('rejects a non gallery-image to canvas-image-target pair', (activeData, overData) => {+ ])('rejects non-image-only gallery payloads and invalid canvas drop pairs', (activeData, overData) => {expect(resolveCanvasImageDrop(activeData, overData)).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex 4648fe4f82..7e55af3257 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -69,7 +69,7 @@ const formatWeight = (value: number): string => value.toFixed(2);const REGIONAL_PROMPT_HEIGHT_PX = 72;-/** DnD droppable id for a specific region's reference-image slot (gallery-image drop target). */+/** DnD droppable id for a specific region's reference-image slot (all-image gallery-item drop target). */const referenceImageDropId = (layerId: string, refId: string): string => `regional-ref-image:${layerId}:${refId}`;/**@@ -295,7 +295,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett[notifications, queryClient, setReferenceImageAsset]);- // A single monitor routes gallery-image drops to the region's ref slot the drop+ // A single monitor routes all-image gallery-item drops to the region's ref slot the drop// landed on (each row registers a droppable keyed by layer + ref id).useDndMonitor({onDragEnd: (event) => {@@ -305,12 +305,12 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettreturn;}const data = event.active.data.current;- if (!isGalleryImageDragData(data) || data.images.length === 0) {+ if (!isGalleryImageDragData(data)) {return;}const refId = overId.slice(prefix.length);- const [first] = data.images;- void galleryImages.resolveMany([first.imageName]).then((images) => {+ const [first] = data.items;+ void galleryImages.resolveMany([first.name]).then((images) => {if (images[0]) {setReferenceImageAsset(refId, images[0]);}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsxindex e2a81a663a..ccb90acf52 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.browser.test.tsx@@ -9,7 +9,7 @@ import {useSensors,type DragEndEvent,} from '@dnd-kit/core';-import { getGalleryImageDragData, getGalleryImageDragId } from '@features/gallery/utility';+import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';import { system } from '@theme/system';import { widgetCollisionDetection } from '@workbench/widgetDnd';import { createInstance } from 'i18next';@@ -45,8 +45,8 @@ const interact = (action: () => void): Promise<void> =>const DraggableThumb = () => {const { listeners, setNodeRef } = useDraggable({- data: getGalleryImageDragData([{ boardId: 'none', imageName: 'dragged.png' }]),- id: getGalleryImageDragId('dragged.png'),+ data: getGalleryItemDragData([{ kind: 'image', name: 'dragged.png' }]),+ id: getGalleryItemDragId({ kind: 'image', name: 'dragged.png' }),});return (@@ -114,7 +114,7 @@ const pointer = (type: string, target: EventTarget, clientX: number, clientY: nu};describe('PreviewCompareDropZone', () => {- it('shows the drop ring during a gallery-image drag and resolves the drop', async () => {+ it('shows the drop ring during an all-image gallery-item drag and resolves the drop', async () => {const { onDrop } = await renderHarness();const thumb = document.querySelector<HTMLElement>('[data-testid="thumb"]')!;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsxindex 3b83594ff5..e7096f9e1e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';import { PREVIEW_COMPARE_DROP_DATA, PREVIEW_COMPARE_DROP_ID } from './previewCompareDnd';/**- * A quiet drop ring over the preview frame, visible only while a gallery-image+ * A quiet drop ring over the preview frame, visible only while an all-image gallery-item* drag is in flight. Dropping arms the dragged image for comparison (resolved* by the widget shell's dnd monitor).*/diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsxindex 3aea67e1ca..cdd4c2ee1d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx@@ -2,7 +2,7 @@ import type { GeneratedImageContract } from '@features/gallery';import { Box, HStack, ScrollArea } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';-import { getGalleryImageDragData } from '@features/gallery/utility';+import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';import { useCallback, useMemo } from 'react';import type { PreviewDensity } from './previewDensity';@@ -11,7 +11,7 @@ import type { PreviewDensity } from './previewDensity';* A docked strip of the current board's thumbnails between frame and footer —* the same `boardImages` the "N of M" counter is derived from, made spatial.* Fixed height (`flexShrink=0`) so the fitted frame's `100cqh` math is never- * stolen from. Thumbs are standard gallery-image drag sources, so they work+ * stolen from. Thumbs are standard all-image gallery-item drag sources, so they work* with every existing drop target (canvas zones, boards, drop-to-compare).*/@@ -83,13 +83,10 @@ const FilmstripThumb = ({size: string;onSelect: (image: GeneratedImageContract) => void;}) => {- const dragData = useMemo(- () => getGalleryImageDragData([{ boardId: image.boardId ?? 'none', imageName: image.imageName }]),- [image.boardId, image.imageName]- );+ const dragData = useMemo(() => getGalleryItemDragData([{ kind: 'image', name: image.imageName }]), [image.imageName]);const { listeners, setNodeRef } = useDraggable({data: dragData,- id: `preview-filmstrip:${image.imageName}`,+ id: getGalleryItemDragId(dragData.items[0]!),});const handleClick = useCallback(() => onSelect(image), [image, onSelect]);// Ref callbacks re-run when `isSelected` changes, keeping the selected thumbdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex c2145ea36d..3bc280c4c0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -1,10 +1,10 @@-import type { GalleryImageDragImage } from '@features/gallery/utility';+import type { GalleryItemRef } from '@features/gallery';/* eslint-disable react/react-compiler */import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';import { Badge, Box, Flex, type SystemStyleObject } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';-import { getGalleryImageDragData } from '@features/gallery/utility';+import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';import { useCallback, useMemo, type CSSProperties, type MouseEvent, type ReactNode, type Ref } from 'react';import { useTranslation } from 'react-i18next';@@ -36,7 +36,7 @@ export const getFittedFrameCss = (width: number, height: number): SystemStyleObjexport const PreviewFrame = ({children,- dragImage,+ dragItem,frameHeight,frameWidth,isLive,@@ -52,7 +52,7 @@ export const PreviewFrame = ({/** Rendered instead of the fitted frame when there is no image source (inset variant only). */children?: ReactNode;/** Saved gallery image represented by this frame. Live progress frames are never draggable. */- dragImage?: GalleryImageDragImage;+ dragItem?: GalleryItemRef;frameHeight: number;frameWidth: number;isLive: boolean;@@ -74,8 +74,8 @@ export const PreviewFrame = ({enabled: variant === 'framed' && !isLive,naturalWidth: frameWidth,});- const dragData = useMemo(() => (dragImage ? getGalleryImageDragData([dragImage]) : undefined), [dragImage]);- const isDragDisabled = !dragImage || isLive || loupe.isZoomed;+ const dragData = useMemo(() => (dragItem ? getGalleryItemDragData([dragItem]) : undefined), [dragItem]);+ const isDragDisabled = !dragItem || isLive || loupe.isZoomed;const {isDragging,listeners,@@ -83,7 +83,7 @@ export const PreviewFrame = ({} = useDraggable({data: dragData,disabled: isDragDisabled,- id: `preview-image:${dragImage?.imageName ?? 'none'}`,+ id: getGalleryItemDragId(dragItem ?? { kind: 'image', name: 'none' }),});const setContentRef = useCallback((element: HTMLDivElement | null) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsxindex b5fd38b362..08d417b4d7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx@@ -87,7 +87,7 @@ const renderHarness = async () => {<DragMonitor onDrop={onDrop} /><div style={{ display: 'flex', height: 220, left: 40, position: 'fixed', top: 40, width: 220 }}><PreviewFrame- dragImage={{ boardId: 'board-1', imageName: 'preview.png' }}+ dragItem={{ kind: 'image', name: 'preview.png' }}frameHeight={128}frameWidth={128}isLive={false}@@ -133,7 +133,7 @@ afterEach(async () => {});describe('PreviewFrame image drag', () => {- it('emits the shared single-gallery-image payload accepted by image drop surfaces', async () => {+ it('emits the shared qualified single-image item payload accepted by image drop surfaces', async () => {const onDrop = await renderHarness();const image = host!.querySelector<HTMLImageElement>('img[alt="preview.png"]')!;@@ -148,8 +148,8 @@ describe('PreviewFrame image drag', () => {expect(result?.overId).toBe('test-image-drop');expect(isGalleryImageDragData(result?.activeData)).toBe(true);expect(result?.activeData).toEqual({- images: [{ boardId: 'board-1', imageName: 'preview.png' }],- kind: 'gallery-image',+ items: [{ kind: 'image', name: 'preview.png' }],+ kind: 'gallery-item',});});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex fb46f36de7..13a017858a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -636,7 +636,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const isFilmstripVisible = getPreviewFilmstripVisible(previewValues);const selectImage = selectPreviewImage;- // Drop-to-compare: any gallery-image drag dropped on the frame's drop zone+ // Drop-to-compare: any all-image gallery-item drag dropped on the frame's drop zone// arms that image for comparison. The drag payload only carries names, so// the full contract is fetched before dispatching.const handleCompareDrop = useCallback(@@ -885,14 +885,11 @@ const SelectedImagePreview = ({});const previewWidth = previewImage?.width ?? image.width;const previewHeight = previewImage?.height ?? image.height;- const dragImage = useMemo(- () => ({ boardId: actionImage?.boardId ?? 'none', imageName: image.imageName }),- [actionImage?.boardId, image.imageName]- );+ const dragItem = useMemo(() => ({ kind: 'image', name: image.imageName }) as const, [image.imageName]);return (<Stack gap="2" h="full" minH="0" w="full"><PreviewFrame- dragImage={dragImage}+ dragItem={dragItem}frameHeight={previewHeight}frameWidth={previewWidth}isLive={false}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.tsindex ddf5959844..5658227a0e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.test.ts@@ -1,27 +1,42 @@-import { getGalleryImageDragData } from '@features/gallery/utility';+import { getGalleryItemDragData } from '@features/gallery/utility';import { describe, expect, it } from 'vitest';import { PREVIEW_COMPARE_DROP_DATA, resolvePreviewCompareDrop } from './previewCompareDnd';describe('resolvePreviewCompareDrop', () => {it('resolves the first dragged gallery image', () => {- const activeData = getGalleryImageDragData([- { boardId: 'none', imageName: 'first.png' },- { boardId: 'none', imageName: 'second.png' },+ const activeData = getGalleryItemDragData([+ { kind: 'image', name: 'first.png' },+ { kind: 'image', name: 'second.png' },]);expect(resolvePreviewCompareDrop(activeData, PREVIEW_COMPARE_DROP_DATA)).toEqual({ imageName: 'first.png' });});it('ignores drops that are not on the compare target', () => {- const activeData = getGalleryImageDragData([{ boardId: 'none', imageName: 'first.png' }]);+ const activeData = getGalleryItemDragData([{ kind: 'image', name: 'first.png' }]);expect(resolvePreviewCompareDrop(activeData, { kind: 'gallery-board' })).toBeNull();expect(resolvePreviewCompareDrop(activeData, null)).toBeNull();});- it('ignores non-image drags and empty drags', () => {+ it('ignores non-image, video, mixed, and empty drags', () => {expect(resolvePreviewCompareDrop({ kind: 'widget-instance' }, PREVIEW_COMPARE_DROP_DATA)).toBeNull();- expect(resolvePreviewCompareDrop(getGalleryImageDragData([]), PREVIEW_COMPARE_DROP_DATA)).toBeNull();+ expect(+ resolvePreviewCompareDrop(+ getGalleryItemDragData([{ kind: 'video', name: 'clip.mp4' }]),+ PREVIEW_COMPARE_DROP_DATA+ )+ ).toBeNull();+ expect(+ resolvePreviewCompareDrop(+ getGalleryItemDragData([+ { kind: 'image', name: 'still.png' },+ { kind: 'video', name: 'clip.mp4' },+ ]),+ PREVIEW_COMPARE_DROP_DATA+ )+ ).toBeNull();+ expect(resolvePreviewCompareDrop({ items: [], kind: 'gallery-item' }, PREVIEW_COMPARE_DROP_DATA)).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.tsindex ea5e634755..2c52674f84 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewCompareDnd.ts@@ -2,7 +2,7 @@ import { isGalleryImageDragData } from '@features/gallery/utility';/*** dnd-kit contract for the preview's drop-to-compare target: dropping any- * gallery-image drag (gallery grid or preview filmstrip thumbs) onto the+ * all-image gallery-item drag (gallery grid or preview filmstrip thumbs) onto the* preview frame arms it as the comparison image.*/@@ -23,7 +23,7 @@ export const resolvePreviewCompareDrop = (activeData: unknown, overData: unknownreturn null;}- const imageName = activeData.images[0]?.imageName;+ const imageName = activeData.items[0]?.name;return imageName ? { imageName } : null;};