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): canonicalize mixed gallery selection
joshistoast8ac2a4fff0b3
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-5-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-5-report.mdnew file mode 100644index 0000000000..f47a18766d--- /dev/null+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-5-report.md@@ -0,0 +1,278 @@+# Task 5 Report: Canonical mixed-media selection and cross-project pruning++## Status++Complete.++Task 5 now persists canonical mixed-media selection state without renaming the+existing persisted properties:++- `selectedImage` writes a canonical `GalleryItem`.+- `selectedImageName` and `selectedImageNames` write qualified+ `GalleryItemKey` values.+- `compareImage` writes only a canonical `GalleryImageItem`.+- `recentImages` remains an image-only `GeneratedImageContract[]`.++The state projection, reducer actions, shared query/cache path, image-only+consumer boundaries, and cross-project reconciliation logic all use the+qualified mixed-media contract.++## TDD evidence++### RED++The first focused run was made after adding the selection, projection,+consumer, and reducer assertions, before implementing the mixed state:++```sh+pnpm test \+ src/features/gallery/core/selection.test.ts \+ src/features/gallery/ui/galleryStateView.test.ts \+ src/workbench/workbenchState.test.ts \+ src/app/gallerySelectionConsumers.test.ts+```++Result:++```text+Test Files 4 failed (4)+Tests 17 failed | 173 passed (190)+```++The failures were the intended missing-contract failures: no canonical item+reader, old image-named projection fields, missing mixed reducer action types,+unqualified selection writes, comparison surviving video selection, and direct+Generation/Workflow consumers not exposing the image-only reader boundary.++After the reducer action candidates could execute, the narrowed reducer RED run+showed the three intended behavioral failures:++```sh+pnpm test src/workbench/workbenchState.test.ts \+ -t "writes canonical mixed|prunes qualified|reconciles authoritative"+```++```text+Tests 3 failed | 155 skipped (158)+```++### GREEN++The final focused regression run after implementation and self-review was:++```sh+pnpm test \+ src/workbench/workbenchState.test.ts \+ src/features/gallery/core/selection.test.ts \+ src/features/gallery/ui/galleryStateView.test.ts \+ src/features/gallery/data/queryCache.test.ts \+ src/app/gallerySelectionConsumers.test.ts+```++```text+Test Files 5 passed (5)+Tests 195 passed (195)+```++An earlier broader focused run also covered mixed query/data overlays and the+image-only compatibility views:++```text+Test Files 9 passed (9)+Tests 211 passed (211)+```++## Implementation++### Selection readers++- Added `getSelectedGalleryItemFromValues`.+- Canonical image and video items round-trip unchanged.+- Legacy generated-image objects and bare/qualified image names adapt to+ canonical image items.+- `getSelectedGalleryImageFromValues` delegates to the item reader, narrows by+ `kind`, and returns `null` for a selected video.+- Generation UI and Workflow field input selectors now use that image-only+ reader directly.++### State projection and data++- Renamed the canonical projection fields to `items`, `selectedItemKey`,+ `selectedItemKeys`, and `compareImageKey`.+- `GalleryCurrentItem` now identifies an item by qualified key.+- Persisted bare names are canonicalized as image keys; image/video items with+ the same name remain distinct.+- Mixed selection order is preserved.+- Gallery data and Preview now consume `galleryItemsInfiniteOptions` and+ `GalleryItemsPage`.+- The current image-only Grid and Preview paths use explicit narrowing adapters+ that filter with `isGalleryImageItem` before constructing `GalleryImage`+ contracts.++### Reducer and commands++- Renamed internal actions to:+ - `selectGalleryItem`+ - `toggleGalleryItemInSelection`+ - `setGalleryMultiSelection`+ - `patchGalleryItems`+ - `removeGalleryItems`+- Added canonical item commands alongside narrow typed image adapters for the+ Task 6/8 callers.+- Selecting or making a video primary clears comparison.+- Queue result routing keeps recents image-only while writing a canonical+ selected image and qualified selection keys.+- Patch operations migrate legacy selected/compare objects to canonical items+ while retaining the legacy recent-image shape.++### Pruning and board outcomes++- Qualified-key patch/removal runs across every open project.+- A video key never removes a same-name recent image or upscale image input.+- Image keys prune image-only recents and upscale inputs across all projects.+- The canonical board reconciliation action accepts authoritative+ deleted/failed image/video arrays.+- Confirmed deletes are removed.+- Every other locally known item on the deleted board—including explicitly+ failed items—is moved to `none`.+- Selected/project board references and pending/running queue destinations are+ repaired across projects.++### Legacy query/cache cleanup++Removed all Task 4 compatibility debt assigned to Task 5:++- `gallery/legacy-images/list` and `galleryKeys.legacy*`+- `galleryImagesInfiniteOptions`+- `flattenGalleryImagesData`+- legacy image query discovery/key guards and type aliases+- `patchGalleryImageCaches` and `GalleryImageCachePatch`+- `invalidateGalleryImages`+- `mergeGalleryImageWindow`+- the corresponding `features/gallery/queries.ts` facade exports++Image actions now translate their image-only inputs into qualified+`GalleryItemMutationResult` values and patch the shared mixed item cache.++## Verification++From `invokeai/frontend/webv2`:++```sh+pnpm test+```++```text+Test Files 374 passed (374)+Tests 4938 passed (4938)+```++```sh+pnpm test:browser+```++```text+Test Files 58 passed (58)+Tests 240 passed (240)+```++The browser suite emitted its existing React `act(...)`, missing-i18n-instance,+and intentional error-boundary console output; the command exited successfully.++```sh+pnpm test:fixtures+```++```text+Tests 4 passed (4)+```++```sh+pnpm format:check+pnpm lint:oxc+pnpm lint:tsc+pnpm architecture:check+```++```text+format: all matched files correctly formatted+oxlint: zero warnings/errors+tsc --noEmit: passed+architecture: 3 files passed, 34 tests passed+```++From the repository root:++```sh+uv run pytest -q tests/app/services/gallery/test_gallery_default.py+```++```text+17 passed, 4 environment/deprecation warnings+```++## Compatibility obligations++The remaining adapters are deliberately narrow and type-safe:++1. `getGalleryImageStateView` is marked `TODO(Task 6)` and filters canonical+ items before serving the current image-only Grid.+2. Image selection command adapters are marked `TODO(Task 6/8)` and convert+ `GeneratedImageContract & Partial<GalleryImage>` to `GalleryImageItem`+ before dispatch.+3. Preview's mixed-query image projection is marked `TODO(Task 8)` and filters+ before converting.+4. The boolean board-deletion adapter is marked `TODO(Task 7)`; the canonical+ outcome command and reducer already require the four authoritative arrays.+5. `CurrentImageFlowNode` remains intentionally image-only by reading only+ `recentImages`.++No adapter accepts a video as an image or relies on an unsafe mixed-to-image+cast.++## Self-review and concerns++- Confirmed every new reducer action is strongly typed in the internal action+ union; the RED-only candidate-action test cast was removed after GREEN.+- Confirmed all new selection writes are canonical and all selected-name writes+ are qualified.+- Confirmed comparison cannot be set to a video through the reducer or public+ commands and is cleared when a video becomes primary.+- Confirmed same-name image/video pruning is kind-qualified across projects.+- Confirmed board reconciliation treats only deleted arrays as confirmed+ deletion and moves every local non-deleted survivor.+- Confirmed all marked Task 5/7 legacy query/cache symbols are absent from+ production and tests.+- Confirmed no `useEffect` was added.+- No unresolved implementation concern.++## Files++### Production++- `invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx`+- `invokeai/frontend/webv2/src/features/gallery/contracts.ts`+- `invokeai/frontend/webv2/src/features/gallery/core/selection.ts`+- `invokeai/frontend/webv2/src/features/gallery/data/queries.ts`+- `invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts`+- `invokeai/frontend/webv2/src/features/gallery/queries.ts`+- `invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx`+- `invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx`+- `invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts`+- `invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts`+- `invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx`+- `invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts`+- `invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx`+- `invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx`+- `invokeai/frontend/webv2/src/workbench/workbenchState.ts`+- `invokeai/frontend/webv2/src/workbench/workbenchStore.ts`++### Tests++- `invokeai/frontend/webv2/src/app/gallerySelectionConsumers.test.ts`+- `invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts`+- `invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts`+- `invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts`+- `invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts`+- `invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx`+- `invokeai/frontend/webv2/src/workbench/workbenchState.test.ts`diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsxindex 872e60d380..454867f3c1 100644--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx@@ -17,6 +17,8 @@ import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { lazy, useMemo } from 'react';+export const getGenerationSelectedGalleryImage = getSelectedGalleryImageFromValues;+const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));const GenerateCanvasCompositingSection = lazy(() =>import('@workbench/widgets/canvas/GenerateCanvasCompositingSection').then((module) => ({@@ -37,7 +39,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNode}));const promptHistoryItems = useActiveProjectSelector((activeProject) => activeProject.promptHistory);const selectedGalleryImage = useActiveProjectSelector((activeProject) =>- getSelectedGalleryImageFromValues(getProjectWidgetValues(activeProject, 'gallery'))+ getGenerationSelectedGalleryImage(getProjectWidgetValues(activeProject, 'gallery')));const modelsCatalog = useModelsSelector((snapshot) => snapshot.models);const modelsError = useModelsSelector((snapshot) => snapshot.error);diff --git a/invokeai/frontend/webv2/src/app/gallerySelectionConsumers.test.ts b/invokeai/frontend/webv2/src/app/gallerySelectionConsumers.test.tsnew file mode 100644index 0000000000..17120a744c--- /dev/null+++ b/invokeai/frontend/webv2/src/app/gallerySelectionConsumers.test.ts@@ -0,0 +1,30 @@+import type { GalleryVideoItem } from '@features/gallery/contracts';++import { getGenerationSelectedGalleryImage } from '@app/GenerationUiAdapter';+import { getWorkflowSelectedGalleryImage } from '@features/workflow/ui/fields/WorkflowFieldInput';+import { describe, expect, it } from 'vitest';++const selectedVideo: GalleryVideoItem = {+ boardId: 'board-1',+ category: 'general',+ createdAt: '2026-07-30T00:00:00.000Z',+ durationSeconds: 3,+ fullUrl: '/videos/selected',+ height: 720,+ isIntermediate: false,+ kind: 'video',+ name: 'selected',+ starred: false,+ thumbnailUrl: '/videos/selected/thumbnail',+ width: 1280,+};++describe('direct image-only Gallery consumers', () => {+ it('keeps a selected video out of GenerationUiAdapter', () => {+ expect(getGenerationSelectedGalleryImage({ selectedImage: selectedVideo })).toBeNull();+ });++ it('keeps a selected video out of WorkflowFieldInput', () => {+ expect(getWorkflowSelectedGalleryImage({ selectedImage: selectedVideo })).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 6c1d4a5d7e..8b6a4563f9 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -52,4 +52,4 @@ export {type GalleryQueuePlaceholder,type GallerySelectedImageQuery,} from './ui/galleryStateView';-export { getSelectedGalleryImageFromValues } from './core/selection';+export { getSelectedGalleryImageFromValues, getSelectedGalleryItemFromValues } from './core/selection';diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.test.tsnew file mode 100644index 0000000000..31beef0c45--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from 'vitest';++import type { GalleryImageItem, GalleryItem, GalleryVideoItem } from './items';+import type { GeneratedImageContract } from './types';++import * as selection from './selection';++const legacyImage: GeneratedImageContract = {+ height: 768,+ imageName: 'legacy.png',+ imageUrl: '/images/legacy.png',+ queuedAt: '2026-07-30T00:00:00.000Z',+ sourceQueueItemId: 'queue-item',+ thumbnailUrl: '/thumbnails/legacy.png',+ width: 512,+};++const imageItem: GalleryImageItem = {+ boardId: 'board-1',+ category: 'general',+ createdAt: '2026-07-30T01:00:00.000Z',+ fullUrl: '/images/shared',+ height: 768,+ isIntermediate: false,+ kind: 'image',+ name: 'shared',+ sourceQueueItemId: 'backend-gallery',+ starred: true,+ thumbnailUrl: '/thumbnails/shared',+ width: 512,+};++const videoItem: GalleryVideoItem = {+ boardId: 'board-1',+ category: 'general',+ createdAt: '2026-07-30T02:00:00.000Z',+ durationSeconds: 4,+ fullUrl: '/videos/shared',+ height: 768,+ isIntermediate: false,+ kind: 'video',+ name: 'shared',+ starred: false,+ thumbnailUrl: '/video-thumbnails/shared',+ width: 512,+};++type SelectionModule = typeof selection & {+ getSelectedGalleryItemFromValues?: (values: Record<string, unknown>) => GalleryItem | null;+};++const getSelectedGalleryItemFromValues = (values: Record<string, unknown>): GalleryItem | null | undefined =>+ (selection as SelectionModule).getSelectedGalleryItemFromValues?.(values);++describe('persisted Gallery selection readers', () => {+ it('returns a canonical selected image item unchanged', () => {+ expect(getSelectedGalleryItemFromValues({ selectedImage: imageItem })).toBe(imageItem);+ });++ it('returns a canonical selected video while the image-only reader rejects it', () => {+ const values = { selectedImage: videoItem, selectedImageName: 'video:shared' };++ expect(getSelectedGalleryItemFromValues(values)).toBe(videoItem);+ expect(selection.getSelectedGalleryImageFromValues(values)).toBeNull();+ });++ it('adapts a legacy generated-image object into a canonical image item', () => {+ expect(+ getSelectedGalleryItemFromValues({+ selectedBoardId: 'board-1',+ selectedImage: legacyImage,+ })+ ).toEqual({+ boardId: 'board-1',+ category: 'general',+ createdAt: legacyImage.queuedAt,+ fullUrl: legacyImage.imageUrl,+ height: legacyImage.height,+ isIntermediate: false,+ kind: 'image',+ name: legacyImage.imageName,+ sourceQueueItemId: legacyImage.sourceQueueItemId,+ starred: false,+ thumbnailUrl: legacyImage.thumbnailUrl,+ width: legacyImage.width,+ });+ });++ it.each(['legacy.png', 'image:legacy.png'])(+ 'adapts the legacy recent-image fallback selected by %s',+ (selectedImageName) => {+ const values = {+ recentImages: [legacyImage],+ selectedBoardId: 'board-1',+ selectedImageName,+ };++ expect(getSelectedGalleryItemFromValues(values)).toMatchObject({+ boardId: 'board-1',+ kind: 'image',+ name: legacyImage.imageName,+ });+ expect(selection.getSelectedGalleryImageFromValues(values)).toMatchObject({+ boardId: 'board-1',+ imageName: legacyImage.imageName,+ });+ }+ );++ it('converts a canonical image item for legacy image-only consumers', () => {+ expect(selection.getSelectedGalleryImageFromValues({ selectedImage: imageItem })).toEqual({+ boardId: imageItem.boardId,+ height: imageItem.height,+ imageCategory: imageItem.category,+ imageName: imageItem.name,+ imageUrl: imageItem.fullUrl,+ queuedAt: imageItem.createdAt,+ sourceQueueItemId: imageItem.sourceQueueItemId,+ starred: imageItem.starred,+ thumbnailUrl: imageItem.thumbnailUrl,+ width: imageItem.width,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.tsindex 13249cb9fc..c7f4e1f461 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.ts@@ -1,30 +1,76 @@import type { GalleryImage, GeneratedImageContract } from './types';+import {+ galleryImageItemToGalleryImage,+ isGalleryImageItem,+ legacyGeneratedImageToGalleryItem,+ parseGalleryItemKey,+ type GalleryItem,+} from './items';++const isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object';+const isGeneratedImage = (value: unknown): value is GeneratedImageContract =>- Boolean(value) && typeof value === 'object' && typeof (value as GeneratedImageContract).imageName === 'string';+ isRecord(value) && typeof value.imageName === 'string';++const isGalleryItem = (value: unknown): value is GalleryItem => {+ if (+ !isRecord(value) ||+ (value.kind !== 'image' && value.kind !== 'video') ||+ typeof value.name !== 'string' ||+ typeof value.boardId !== 'string' ||+ typeof value.category !== 'string' ||+ typeof value.createdAt !== 'string' ||+ typeof value.fullUrl !== 'string' ||+ typeof value.height !== 'number' ||+ typeof value.isIntermediate !== 'boolean' ||+ typeof value.starred !== 'boolean' ||+ typeof value.thumbnailUrl !== 'string' ||+ typeof value.width !== 'number'+ ) {+ return false;+ }-const toGalleryImage = (+ return value.kind === 'image' || typeof value.durationSeconds === 'number';+};++const legacyImageToGalleryItem = (image: GeneratedImageContract & Partial<GalleryImage>,galleryValues: Record<string, unknown>-): GalleryImage => ({- ...image,- boardId:- image.boardId ?? (typeof galleryValues.selectedBoardId === 'string' ? galleryValues.selectedBoardId : 'none'),- imageCategory: image.imageCategory ?? 'general',- starred: image.starred ?? false,-});+): GalleryItem =>+ legacyGeneratedImageToGalleryItem({+ ...image,+ boardId:+ image.boardId ?? (typeof galleryValues.selectedBoardId === 'string' ? galleryValues.selectedBoardId : 'none'),+ });++export const getSelectedGalleryItemFromValues = (galleryValues: Record<string, unknown>): GalleryItem | null => {+ if (isGalleryItem(galleryValues.selectedImage)) {+ return galleryValues.selectedImage;+ }-export const getSelectedGalleryImageFromValues = (galleryValues: Record<string, unknown>): GalleryImage | null => {if (isGeneratedImage(galleryValues.selectedImage)) {- return toGalleryImage(galleryValues.selectedImage, galleryValues);+ return legacyImageToGalleryItem(galleryValues.selectedImage, galleryValues);}const selectedImageName =typeof galleryValues.selectedImageName === 'string' ? galleryValues.selectedImageName : null;+ const selectedRef = selectedImageName ? parseGalleryItemKey(selectedImageName) : null;++ if (!selectedRef || selectedRef.kind !== 'image') {+ return null;+ }+const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : [];const recentImage = recentImages.find(- (image): image is GeneratedImageContract => isGeneratedImage(image) && image.imageName === selectedImageName+ (image): image is GeneratedImageContract => isGeneratedImage(image) && image.imageName === selectedRef.name);- return recentImage ? toGalleryImage(recentImage, galleryValues) : null;+ return recentImage ? legacyImageToGalleryItem(recentImage, galleryValues) : null;+};++export const getSelectedGalleryImageFromValues = (galleryValues: Record<string, unknown>): GalleryImage | null => {+ const item = getSelectedGalleryItemFromValues(galleryValues);++ return item && isGalleryImageItem(item) ? galleryImageItemToGalleryImage(item) : null;};diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsindex 0082300932..46f577b3ce 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -1,11 +1,5 @@import type { GalleryItem, GalleryItemsPage } from '@features/gallery/core/items';-import type {- GalleryBoardOrderBy,- GalleryImage,- GalleryImagesPage,- GalleryOrderDir,- GalleryView,-} from '@features/gallery/core/types';+import type { GalleryBoardOrderBy, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';import type { AccountScope } from '@platform/state/accountLifecycle';import { toGalleryItemKey } from '@features/gallery/core/items';@@ -28,7 +22,6 @@ import {listGalleryDateBoards,listGalleryItemNames,listGalleryItems,- listPaletteImages,} from './backend';export const GALLERY_PAGE_SIZE = 60;@@ -90,18 +83,6 @@ type GalleryItemsAnchorQueryKey = readonly [...GalleryItemsInfiniteQueryKey, 'anexport type GalleryItemsListQueryKey = GalleryItemsAnchorQueryKey | GalleryItemsInfiniteQueryKey;-type LegacyGalleryImagesInfiniteQueryKey = readonly [- 'gallery',- 'legacy-images',- 'list',- GalleryAccountKey,- CanonicalGalleryItemsFilter,-];--type LegacyGalleryImagesAnchorQueryKey = readonly [...LegacyGalleryImagesInfiniteQueryKey, 'anchor', number];--type LegacyGalleryImagesListQueryKey = LegacyGalleryImagesAnchorQueryKey | LegacyGalleryImagesInfiniteQueryKey;-const canonicalizeBoardsQuery = (query: GalleryBoardsQuery): CanonicalGalleryBoardsQuery => ({includeArchived: query.includeArchived ?? false,includeDateBoards: query.includeDateBoards ?? false,@@ -149,25 +130,6 @@ export const galleryKeys = {itemNamesForAccount: (owner: AccountScope) => [...galleryKeys.itemNamesRoot(), getAccountKey(owner)] as const,itemNames: (owner: AccountScope, filter: CanonicalGalleryItemsFilter) =>[...galleryKeys.itemNamesForAccount(owner), filter] as const,-- /**- * TODO(Task 5/7): Remove the legacy image query domain after Gallery state,- * projection, and preview consumers use GalleryItem throughout.- */- legacyImagesRoot: () => [...galleryKeys.all, 'legacy-images'] as const,- legacyImageListsRoot: () => [...galleryKeys.legacyImagesRoot(), 'list'] as const,- legacyImageListsForAccount: (owner: AccountScope) =>- [...galleryKeys.legacyImageListsRoot(), getAccountKey(owner)] as const,- legacyImages: (- owner: AccountScope,- filter: CanonicalGalleryItemsFilter,- window: GalleryItemsWindow = { kind: 'infinite' }- ): LegacyGalleryImagesListQueryKey =>- [- ...galleryKeys.legacyImageListsForAccount(owner),- filter,- ...getWindowKey(window),- ] as LegacyGalleryImagesListQueryKey,};const galleryItemNamesOptionsForOwner = (owner: AccountScope, filter: CanonicalGalleryItemsFilter) =>@@ -419,111 +381,3 @@ export const getGalleryItemsFilterFromKey = (queryKey: QueryKey): CanonicalGalleexport const getGalleryItemListQueries = (client: QueryClient, owner: AccountScope = captureAccountScope()) =>client.getQueryCache().findAll({ queryKey: galleryKeys.itemListsForAccount(owner) });--/**- * TODO(Task 5/7): Remove this image-page compatibility query after Gallery- * state/projection and Preview consume `galleryItemsInfiniteOptions`.- * It is isolated under `gallery/legacy-images` and never changes the mixed- * query's GalleryItemsPage result.- */-export const galleryImagesInfiniteOptions = (- inputFilter: GalleryItemsFilter,- window: GalleryItemsWindow = { kind: 'infinite' }-) => {- const owner = captureAccountScope();- const filter = canonicalizeGalleryItemsFilter(inputFilter);- const normalizedWindow =- window.kind === 'infinite' ? window : ({ ...window, offset: normalizePageOffset(window.offset) } as const);- const initialPageParam = normalizedWindow.kind === 'infinite' ? 0 : normalizedWindow.offset;-- return infiniteQueryOptions<- GalleryImagesPage,- Error,- InfiniteData<GalleryImagesPage, number>,- LegacyGalleryImagesListQueryKey,- number- >({- ...(normalizedWindow.kind === 'infinite' ? {} : { gcTime: 0 }),- getNextPageParam: (lastPage, allPages, lastPageParam) =>- allPages.length >= GALLERY_MAX_INFINITE_PAGES- ? undefined- : getNextPageParam(normalizedWindow, lastPage, lastPageParam),- getPreviousPageParam: (_firstPage, allPages, firstPageParam) =>- allPages.length < GALLERY_MAX_INFINITE_PAGES && firstPageParam >= GALLERY_PAGE_SIZE- ? firstPageParam - GALLERY_PAGE_SIZE- : undefined,- initialPageParam,- maxPages: GALLERY_MAX_INFINITE_PAGES,- queryFn: async ({ pageParam, signal }) => {- const requestSignal = AbortSignal.any([signal, owner.signal]);- const result = await listPaletteImages({- ...filter,- limit: GALLERY_PAGE_SIZE,- offset: pageParam,- signal: requestSignal,- });-- assertAccountScopeCurrent(owner);- requestSignal.throwIfAborted();-- return result.images.length <= GALLERY_PAGE_SIZE- ? result- : { ...result, images: result.images.slice(0, GALLERY_PAGE_SIZE) };- },- queryKey: galleryKeys.legacyImages(owner, filter, normalizedWindow),- staleTime: 60_000,- });-};--/** TODO(Task 5/7): Remove with `galleryImagesInfiniteOptions`. */-export const flattenGalleryImagesData = (data: InfiniteData<GalleryImagesPage, number> | undefined): GalleryImage[] => {- if (!data) {- return [];- }-- const imageNames = new Set<string>();- const images: GalleryImage[] = [];-- for (const page of data.pages) {- for (const image of page.images) {- if (imageNames.has(image.imageName)) {- continue;- }-- imageNames.add(image.imageName);- images.push(image);-- if (images.length === GALLERY_MAX_ROWS) {- return images;- }- }- }-- return images;-};--/** TODO(Task 5/7): Remove legacy image cache discovery. */-export const getGalleryImageListQueries = (client: QueryClient, owner: AccountScope = captureAccountScope()) =>- client.getQueryCache().findAll({ queryKey: galleryKeys.legacyImageListsForAccount(owner) });--/** TODO(Task 5/7): Remove legacy image key guard. */-export const getGalleryImagesFilterFromKey = (queryKey: QueryKey): CanonicalGalleryItemsFilter | null => {- if (- queryKey[0] !== 'gallery' ||- queryKey[1] !== 'legacy-images' ||- queryKey[2] !== 'list' ||- !queryKey[4] ||- typeof queryKey[4] !== 'object'- ) {- return null;- }-- return queryKey[4] as CanonicalGalleryItemsFilter;-};--/** TODO(Task 5/7): Remove legacy type aliases with the image-only consumers. */-export type GalleryImagesFilter = GalleryItemsFilter;-export type CanonicalGalleryImagesFilter = CanonicalGalleryItemsFilter;-export type GalleryImagesWindow = GalleryItemsWindow;-export type GalleryImagesListQueryKey = LegacyGalleryImagesListQueryKey;-export const canonicalizeGalleryImagesFilter = canonicalizeGalleryItemsFilter;diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.tsindex 6504ccde65..0e8d6de507 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts@@ -1,4 +1,4 @@-import type { GalleryImage, GalleryImagesPage } from '@features/gallery/core/types';+import type { GalleryItem, GalleryItemMutationResult, GalleryItemsPage } from '@features/gallery/core/items';import type { AccountScope } from '@platform/state/accountLifecycle';import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';@@ -6,10 +6,10 @@ import { QueryClient, type InfiniteData } from '@tanstack/react-query';import { beforeEach, describe, expect, it } from 'vitest';import { ALL_READABLE_BOARDS_ID } from './backend';-import { canonicalizeGalleryImagesFilter, galleryKeys } from './queries';-import { invalidateGallery, invalidateGalleryImages, patchGalleryImageCaches } from './queryCache';+import { canonicalizeGalleryItemsFilter, galleryKeys } from './queries';+import { invalidateGallery, invalidateGalleryItems, patchGalleryItemCaches } from './queryCache';-type GalleryImagesData = InfiniteData<GalleryImagesPage, number>;+type GalleryItemsData = InfiniteData<GalleryItemsPage, number>;const createClient = (): QueryClient =>new QueryClient({@@ -21,67 +21,95 @@ const createClient = (): QueryClient =>},});-const createImage = (imageName: string, boardId = 'board-1', starred = false): GalleryImage => ({- boardId,- height: 768,- imageCategory: 'general',- imageName,- imageUrl: `/api/v1/images/i/${imageName}/full`,- queuedAt: '2026-07-26T00:00:00.000Z',- sourceQueueItemId: 'backend-gallery',- starred,- thumbnailUrl: `/api/v1/images/i/${imageName}/thumbnail`,- width: 512,-});+const createItem = (+ name: string,+ boardId = 'board-1',+ starred = false,+ kind: 'image' | 'video' = 'image'+): GalleryItem =>+ kind === 'image'+ ? {+ boardId,+ category: 'general',+ createdAt: '2026-07-26T00:00:00.000Z',+ fullUrl: `/api/v1/images/i/${name}/full`,+ height: 768,+ isIntermediate: false,+ kind,+ name,+ sourceQueueItemId: 'backend-gallery',+ starred,+ thumbnailUrl: `/api/v1/images/i/${name}/thumbnail`,+ width: 512,+ }+ : {+ boardId,+ category: 'general',+ createdAt: '2026-07-26T00:00:00.000Z',+ durationSeconds: 1,+ fullUrl: `/api/v1/videos/i/${name}/full`,+ height: 768,+ isIntermediate: false,+ kind,+ name,+ starred,+ thumbnailUrl: `/api/v1/videos/i/${name}/thumbnail`,+ width: 512,+ };-const createData = (pages: GalleryImage[][]): GalleryImagesData => {- const total = pages.reduce((count, images) => count + images.length, 0);+const createData = (pages: GalleryItem[][]): GalleryItemsData => {+ const total = pages.reduce((count, items) => count + items.length, 0);return {pageParams: pages.map((_, index) => index * 60),- pages: pages.map((images) => ({ images, total })),+ pages: pages.map((items) => ({ items, total })),};};-const getImagesKey = (boardId: string, owner: AccountScope = captureAccountScope()) =>- galleryKeys.legacyImages(+const getItemsKey = (boardId: string, owner: AccountScope = captureAccountScope()) =>+ galleryKeys.items(owner,- canonicalizeGalleryImagesFilter({+ canonicalizeGalleryItemsFilter({boardId,galleryView: 'images',searchTerm: '',}));-const getData = (client: QueryClient, queryKey: ReturnType<typeof getImagesKey>): GalleryImagesData => {- const data = client.getQueryData<GalleryImagesData>(queryKey);+const getData = (client: QueryClient, queryKey: ReturnType<typeof getItemsKey>): GalleryItemsData => {+ const data = client.getQueryData<GalleryItemsData>(queryKey);expect(data).toBeDefined();- return data as GalleryImagesData;+ return data as GalleryItemsData;};-describe('Gallery image cache patches', () => {+const getResult = (+ succeeded: GalleryItemMutationResult['succeeded'],+ failed: GalleryItemMutationResult['failed'] = []+): GalleryItemMutationResult => ({ failed, succeeded });++describe('Gallery item cache patches', () => {beforeEach(() => {accountLifecycle.activate('gallery-query-cache-test');});- it('patches a star in place and rolls back without rebuilding untouched pages or page params', () => {+ it('patches a qualified star in place and rolls back without rebuilding untouched pages or page params', () => {const client = createClient();- const target = createImage('target.png');- const samePageUntouched = createImage('same-page-untouched.png');- const untouchedPageImage = createImage('untouched-page.png');- const key = getImagesKey('board-1');+ const target = createItem('target.png');+ const samePageUntouched = createItem('same-page-untouched.png');+ const untouchedPageItem = createItem('untouched-page.mp4', 'board-1', false, 'video');+ const key = getItemsKey('board-1');- client.setQueryData(key, createData([[target, samePageUntouched], [untouchedPageImage]]));+ client.setQueryData(key, createData([[target, samePageUntouched], [untouchedPageItem]]));const before = getData(client, key);const firstPageBefore = before.pages[0];const untouchedPageBefore = before.pages[1];const pageParamsBefore = before.pageParams;- const rollback = patchGalleryImageCaches(client, {- imageNames: [target.imageName],+ const rollback = patchGalleryItemCaches(client, {kind: 'star',+ result: getResult([{ kind: 'image', name: target.name }]),starred: true,});const after = getData(client, key);@@ -90,8 +118,8 @@ describe('Gallery image cache patches', () => {expect(after.pageParams).toBe(pageParamsBefore);expect(after.pages[0]).not.toBe(firstPageBefore);expect(after.pages[1]).toBe(untouchedPageBefore);- expect(after.pages[0]?.images[0]).toEqual({ ...target, starred: true });- expect(after.pages[0]?.images[1]).toBe(samePageUntouched);+ expect(after.pages[0]?.items[0]).toEqual({ ...target, starred: true });+ expect(after.pages[0]?.items[1]).toBe(samePageUntouched);rollback();@@ -100,16 +128,16 @@ describe('Gallery image cache patches', () => {expect(rolledBack).toEqual(before);expect(rolledBack.pageParams).toBe(pageParamsBefore);expect(rolledBack.pages[1]).toBe(untouchedPageBefore);- expect(rolledBack.pages[0]?.images[1]).toBe(samePageUntouched);+ expect(rolledBack.pages[0]?.items[1]).toBe(samePageUntouched);});- it('deletes matching images across pages and keeps each page total consistent', () => {+ it('deletes matching qualified items across pages and keeps each page total consistent', () => {const client = createClient();- const firstTarget = createImage('first-target.png');- const firstUntouched = createImage('first-untouched.png');- const secondTarget = createImage('second-target.png');- const secondUntouched = createImage('second-untouched.png');- const key = getImagesKey('board-1');+ const firstTarget = createItem('shared-name', 'board-1', false, 'image');+ const firstUntouched = createItem('shared-name', 'board-1', false, 'video');+ const secondTarget = createItem('second-target.mp4', 'board-1', false, 'video');+ const secondUntouched = createItem('second-untouched.png');+ const key = getItemsKey('board-1');client.setQueryData(key,@@ -120,59 +148,59 @@ describe('Gallery image cache patches', () => {);const before = getData(client, key);- patchGalleryImageCaches(client, {- imageNames: [firstTarget.imageName, secondTarget.imageName],+ patchGalleryItemCaches(client, {kind: 'delete',+ result: getResult([+ { kind: 'image', name: firstTarget.name },+ { kind: 'video', name: secondTarget.name },+ ]),});const after = getData(client, key);expect(after.pageParams).toBe(before.pageParams);- expect(after.pages.map((page) => page.images)).toEqual([[firstUntouched], [secondUntouched]]);+ expect(after.pages.map((page) => page.items)).toEqual([[firstUntouched], [secondUntouched]]);expect(after.pages.map((page) => page.total)).toEqual([2, 2]);});- it('removes moved images from source boards while all-images and date views retain the updated image', () => {+ it('removes moved items from source boards while all-items and date views retain updated items', () => {const client = createClient();- const target = createImage('moved.png', 'board-1');- const untouched = createImage('untouched.png', 'board-1');- const sourceKey = getImagesKey('board-1');- const allKey = getImagesKey(ALL_READABLE_BOARDS_ID);- const dateKey = getImagesKey('by_date:2026-07-26');+ const target = createItem('moved.mp4', 'board-1', false, 'video');+ const untouched = createItem('untouched.png');+ const sourceKey = getItemsKey('board-1');+ const allKey = getItemsKey(ALL_READABLE_BOARDS_ID);+ const dateKey = getItemsKey('by_date:2026-07-26');+ const result = getResult([{ kind: 'video', name: target.name }]);client.setQueryData(sourceKey, createData([[target], [untouched]]));client.setQueryData(allKey, createData([[target], [untouched]]));client.setQueryData(dateKey, createData([[target], [untouched]]));- patchGalleryImageCaches(client, {- boardId: 'board-2',- imageNames: [target.imageName],- kind: 'move',- });+ patchGalleryItemCaches(client, { boardId: 'board-2', kind: 'move', result });const source = getData(client, sourceKey);const all = getData(client, allKey);const date = getData(client, dateKey);- expect(source.pages.flatMap((page) => page.images)).toEqual([untouched]);+ expect(source.pages.flatMap((page) => page.items)).toEqual([untouched]);expect(source.pages.map((page) => page.total)).toEqual([1, 1]);for (const retained of [all, date]) {- expect(retained.pages.flatMap((page) => page.images)).toEqual([{ ...target, boardId: 'board-2' }, untouched]);+ expect(retained.pages.flatMap((page) => page.items)).toEqual([{ ...target, boardId: 'board-2' }, untouched]);expect(retained.pages.map((page) => page.total)).toEqual([2, 2]);}});it('does not let rollback clobber a later concurrent cache update', () => {const client = createClient();- const target = createImage('target.png');- const key = getImagesKey('board-1');+ const target = createItem('target.png');+ const key = getItemsKey('board-1');client.setQueryData(key, createData([[target]]));- const rollback = patchGalleryImageCaches(client, {- imageNames: [target.imageName],+ const rollback = patchGalleryItemCaches(client, {kind: 'star',+ result: getResult([{ kind: 'image', name: target.name }]),starred: true,});- const concurrent = client.setQueryData<GalleryImagesData>(key, (current) => {+ const concurrent = client.setQueryData<GalleryItemsData>(key, (current) => {if (!current) {return current;}@@ -181,8 +209,8 @@ describe('Gallery image cache patches', () => {...current,pages: current.pages.map((page) => ({...page,- images: page.images.map((image) =>- image.imageName === target.imageName ? { ...image, boardId: 'board-concurrent' } : image+ items: page.items.map((item) =>+ item.kind === target.kind && item.name === target.name ? { ...item, boardId: 'board-concurrent' } : item),})),};@@ -191,9 +219,10 @@ describe('Gallery image cache patches', () => {rollback();expect(getData(client, key)).toBe(concurrent);- expect(getData(client, key).pages[0]?.images[0]).toMatchObject({+ expect(getData(client, key).pages[0]?.items[0]).toMatchObject({boardId: 'board-concurrent',- imageName: target.imageName,+ kind: 'image',+ name: target.name,starred: true,});});@@ -207,8 +236,8 @@ describe('Gallery cache invalidation', () => {it('invalidates only current-account Gallery domains and never grows query cardinality', async () => {const client = createClient();const oldOwner = captureAccountScope();- const oldImagesKey = getImagesKey('board-1', oldOwner);- const oldFilter = canonicalizeGalleryImagesFilter({+ const oldItemsKey = getItemsKey('board-1', oldOwner);+ const oldFilter = canonicalizeGalleryItemsFilter({boardId: 'by_date:2026-07-25',galleryView: 'images',searchTerm: '',@@ -221,14 +250,14 @@ describe('Gallery cache invalidation', () => {orderDir: 'DESC',});- client.setQueryData(oldImagesKey, createData([[createImage('old.png')]]));- client.setQueryData(oldDateNamesKey, { imageNames: ['old.png'], total: 1 });+ client.setQueryData(oldItemsKey, createData([[createItem('old.png')]]));+ client.setQueryData(oldDateNamesKey, { items: [{ kind: 'image', name: 'old.png' }], total: 1 });client.setQueryData(oldBoardsKey, []);accountLifecycle.activate('gallery-query-cache-current-account');const currentOwner = captureAccountScope();- const currentImagesKey = getImagesKey('board-1', currentOwner);- const currentFilter = canonicalizeGalleryImagesFilter({+ const currentItemsKey = getItemsKey('board-1', currentOwner);+ const currentFilter = canonicalizeGalleryItemsFilter({boardId: 'by_date:2026-07-26',galleryView: 'images',searchTerm: '',@@ -241,20 +270,20 @@ describe('Gallery cache invalidation', () => {orderDir: 'DESC',});- client.setQueryData(currentImagesKey, createData([[createImage('current.png')]]));- client.setQueryData(currentDateNamesKey, { imageNames: ['current.png'], total: 1 });+ client.setQueryData(currentItemsKey, createData([[createItem('current.png')]]));+ client.setQueryData(currentDateNamesKey, { items: [{ kind: 'image', name: 'current.png' }], total: 1 });client.setQueryData(currentBoardsKey, []);const initialCardinality = client.getQueryCache().getAll().length;for (let index = 0; index < 100; index += 1) {- await invalidateGalleryImages(client);+ await invalidateGalleryItems(client);}expect(client.getQueryCache().getAll()).toHaveLength(initialCardinality);- expect(client.getQueryState(currentImagesKey)?.isInvalidated).toBe(true);+ expect(client.getQueryState(currentItemsKey)?.isInvalidated).toBe(true);expect(client.getQueryState(currentDateNamesKey)?.isInvalidated).toBe(true);expect(client.getQueryState(currentBoardsKey)?.isInvalidated).toBe(false);- expect(client.getQueryState(oldImagesKey)?.isInvalidated).toBe(false);+ expect(client.getQueryState(oldItemsKey)?.isInvalidated).toBe(false);expect(client.getQueryState(oldDateNamesKey)?.isInvalidated).toBe(false);await invalidateGallery(client);diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 077c8c15ab..17a144e0d0 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -4,7 +4,6 @@ import type {GalleryItemMutationResult,GalleryItemsPage,} from '@features/gallery/core/items';-import type { GalleryImage, GalleryImagesPage } from '@features/gallery/core/types';import type { AccountScope } from '@platform/state/accountLifecycle';import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query';@@ -17,10 +16,7 @@ import {galleryKeys,getGalleryItemListQueries,getGalleryItemsFilterFromKey,- getGalleryImageListQueries,- getGalleryImagesFilterFromKey,type CanonicalGalleryItemsFilter,- type CanonicalGalleryImagesFilter,} from './queries';export type GalleryItemCachePatch =@@ -199,191 +195,10 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCa};};-/** TODO(Task 5/7): Remove after image actions use confirmed mixed mutation results. */-export type GalleryImageCachePatch =- | { imageNames: readonly string[]; kind: 'delete' }- | { boardId: string; imageNames: readonly string[]; kind: 'move' }- | { imageNames: readonly string[]; kind: 'star'; starred: boolean };--interface CacheRollbackEntry {- after: InfiniteData<GalleryImagesPage, number>;- before: InfiniteData<GalleryImagesPage, number>;- queryKey: QueryKey;-}--const isGalleryImagesData = (value: unknown): value is InfiniteData<GalleryImagesPage, number> => {- if (!value || typeof value !== 'object' || !('pages' in value) || !('pageParams' in value)) {- return false;- }-- const data = value as { pages?: unknown; pageParams?: unknown };-- return Array.isArray(data.pages) && Array.isArray(data.pageParams);-};--const mapPageImages = (- page: GalleryImagesPage,- mapImage: (image: GalleryImage) => GalleryImage | null,- totalDelta = 0-): GalleryImagesPage => {- let changed = false;- const images: GalleryImage[] = [];-- for (const image of page.images) {- const nextImage = mapImage(image);-- if (nextImage !== image) {- changed = true;- }- if (nextImage) {- images.push(nextImage);- }- }-- if (!changed && totalDelta === 0) {- return page;- }-- return {- ...page,- images: changed ? images : page.images,- total: Math.max(0, page.total - totalDelta),- };-};--const patchPage = (- page: GalleryImagesPage,- filter: CanonicalGalleryImagesFilter,- patch: GalleryImageCachePatch,- imageNames: ReadonlySet<string>,- removedImageCount: number-): GalleryImagesPage => {- if (patch.kind === 'star') {- return mapPageImages(page, (image) => {- if (!imageNames.has(image.imageName) || image.starred === patch.starred) {- return image;- }-- return { ...image, starred: patch.starred };- });- }-- if (patch.kind === 'delete') {- return mapPageImages(page, (image) => (imageNames.has(image.imageName) ? null : image), removedImageCount);- }-- const keepsMovedImages =- filter.boardId === ALL_READABLE_BOARDS_ID || filter.boardId === patch.boardId || isDateBoardId(filter.boardId);-- return mapPageImages(- page,- (image) => {- if (!imageNames.has(image.imageName)) {- return image;- }-- if (!keepsMovedImages) {- return null;- }-- return image.boardId === patch.boardId ? image : { ...image, boardId: patch.boardId };- },- keepsMovedImages ? 0 : removedImageCount- );-};--const patchInfiniteData = (- data: InfiniteData<GalleryImagesPage, number>,- filter: CanonicalGalleryImagesFilter,- patch: GalleryImageCachePatch-): InfiniteData<GalleryImagesPage, number> => {- const imageNames = new Set(patch.imageNames);- const removesImages =- patch.kind === 'delete' ||- (patch.kind === 'move' &&- filter.boardId !== ALL_READABLE_BOARDS_ID &&- filter.boardId !== patch.boardId &&- !isDateBoardId(filter.boardId));- const removedImageNames = new Set<string>();-- if (removesImages) {- for (const page of data.pages) {- for (const image of page.images) {- if (imageNames.has(image.imageName)) {- removedImageNames.add(image.imageName);- }- }- }- }-- let changed = false;- const pages = data.pages.map((page) => {- const nextPage = patchPage(page, filter, patch, imageNames, removedImageNames.size);- changed ||= nextPage !== page;-- return nextPage;- });-- return changed ? { ...data, pages } : data;-};--/**- * Applies a small mutation to every currently cached page for this account.- * The returned rollback is concurrency-safe: it only restores an entry while- * the optimistic value is still the current cache value.- *- * TODO(Task 5/7): Remove after image actions use confirmed mixed mutation- * results with `patchGalleryItemCaches`.- */-export const patchGalleryImageCaches = (client: QueryClient, patch: GalleryImageCachePatch): (() => void) => {- if (patch.imageNames.length === 0) {- return () => undefined;- }-- const rollbackEntries: CacheRollbackEntry[] = [];-- for (const query of getGalleryImageListQueries(client)) {- const before = query.state.data;- const filter = getGalleryImagesFilterFromKey(query.queryKey);-- if (!filter || !isGalleryImagesData(before)) {- continue;- }-- // A starred-first query cannot be patched coherently in place: changing- // the flag may move an image across pages. Leave that cache untouched and- // let the post-mutation invalidation rebuild its server-defined order.- if (patch.kind === 'star' && filter.starredFirst) {- continue;- }-- const after = patchInfiniteData(before, filter, patch);-- if (after === before) {- continue;- }-- const applied = client.setQueryData<InfiniteData<GalleryImagesPage, number>>(query.queryKey, after);-- if (applied) {- rollbackEntries.push({ after: applied, before, queryKey: query.queryKey });- }- }-- return () => {- for (const { after, before, queryKey } of rollbackEntries) {- if (client.getQueryData(queryKey) === after) {- client.setQueryData(queryKey, before);- }- }- };-};-const runGalleryInvalidation = async (client: QueryClient,owner: AccountScope,- includeBoards: boolean,- includeLegacyImages: boolean+ includeBoards: boolean): Promise<void> => {// Date-board pages and lazy range selection share these names. Mark them// stale before active pages refetch so they cannot hydrate stale refs.@@ -393,9 +208,6 @@ const runGalleryInvalidation = async (refetchType: 'none',});await client.cancelQueries({ queryKey: galleryKeys.itemListsForAccount(owner) });- if (includeLegacyImages) {- await client.cancelQueries({ queryKey: galleryKeys.legacyImageListsForAccount(owner) });- }// Refetching an infinite query replays every retained page. Collapse each// logical window to its pinned page first; users can explicitly load the@@ -417,31 +229,8 @@ const runGalleryInvalidation = async (});}- if (includeLegacyImages) {- for (const query of getGalleryImageListQueries(client, owner)) {- const data = query.state.data;-- if (!isGalleryImagesData(data) || data.pages.length <= 1) {- continue;- }-- const anchorOffset =- query.queryKey[5] === 'anchor' && typeof query.queryKey[6] === 'number' ? query.queryKey[6] : 0;- const anchorIndex = Math.max(0, data.pageParams.indexOf(anchorOffset));-- client.setQueryData<InfiniteData<GalleryImagesPage, number>>(query.queryKey, {- pageParams: [data.pageParams[anchorIndex] ?? anchorOffset],- pages: [data.pages[anchorIndex] ?? data.pages[0]],- });- }- }-await client.invalidateQueries({ queryKey: galleryKeys.itemListsForAccount(owner) });- if (includeLegacyImages) {- await client.invalidateQueries({ queryKey: galleryKeys.legacyImageListsForAccount(owner) });- }-if (includeBoards) {await client.invalidateQueries({ queryKey: galleryKeys.boardsForAccount(owner) });}@@ -449,7 +238,6 @@ const runGalleryInvalidation = async (interface GalleryInvalidationState {includeBoards: boolean;- includeLegacyImages: boolean;promise: Promise<void> | null;requested: boolean;}@@ -464,14 +252,12 @@ const galleryInvalidations = new WeakMap<QueryClient, Map<string, GalleryInvalidconst scheduleGalleryInvalidation = (client: QueryClient,owner: AccountScope,- includeBoards: boolean,- includeLegacyImages: boolean+ includeBoards: boolean): Promise<void> => {const ownerKey = hashKey(galleryKeys.itemListsForAccount(owner));const clientStates = galleryInvalidations.get(client) ?? new Map<string, GalleryInvalidationState>();const state = clientStates.get(ownerKey) ?? {includeBoards: false,- includeLegacyImages: false,promise: null,requested: false,};@@ -479,7 +265,6 @@ const scheduleGalleryInvalidation = (galleryInvalidations.set(client, clientStates);clientStates.set(ownerKey, state);state.includeBoards ||= includeBoards;- state.includeLegacyImages ||= includeLegacyImages;state.requested = true;if (!state.promise) {@@ -491,11 +276,9 @@ const scheduleGalleryInvalidation = (while (state.requested) {state.requested = false;const shouldInvalidateBoards = state.includeBoards;- const shouldInvalidateLegacyImages = state.includeLegacyImages;state.includeBoards = false;- state.includeLegacyImages = false;- await runGalleryInvalidation(client, owner, shouldInvalidateBoards, shouldInvalidateLegacyImages);+ await runGalleryInvalidation(client, owner, shouldInvalidateBoards);}} finally {state.promise = null;@@ -510,16 +293,7 @@ const scheduleGalleryInvalidation = (export const invalidateGalleryItems = (client: QueryClient,owner: AccountScope = captureAccountScope()-): Promise<void> => scheduleGalleryInvalidation(client, owner, false, false);--/**- * TODO(Task 5/7): Remove when legacy image consumers leave their isolated- * query domain.- */-export const invalidateGalleryImages = (- client: QueryClient,- owner: AccountScope = captureAccountScope()-): Promise<void> => scheduleGalleryInvalidation(client, owner, false, true);+): Promise<void> => scheduleGalleryInvalidation(client, owner, false);export const invalidateGallery = (client: QueryClient, owner: AccountScope = captureAccountScope()): Promise<void> =>- scheduleGalleryInvalidation(client, owner, true, true);+ scheduleGalleryInvalidation(client, owner, true);diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex f1d83b3d8c..f1333d276e 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -16,28 +16,5 @@ export type {GalleryItemsListQueryKey,GalleryItemsWindow,} from './data/queries';--/**- * TODO(Task 5/7): Remove these legacy image-query facade exports after Gallery- * state/projection and Preview consume the mixed item query API.- */-export {- canonicalizeGalleryImagesFilter,- flattenGalleryImagesData,- galleryImagesInfiniteOptions,-} from './data/queries';-export type {- CanonicalGalleryImagesFilter,- GalleryImagesFilter,- GalleryImagesListQueryKey,- GalleryImagesWindow,-} from './data/queries';export { invalidateGallery, invalidateGalleryItems, patchGalleryItemCaches } from './data/queryCache';export type { GalleryItemCachePatch } from './data/queryCache';--/**- * TODO(Task 5/7): Remove these legacy image-cache facade exports after image- * actions and remaining image-only consumers use confirmed mixed item results.- */-export { invalidateGalleryImages, patchGalleryImageCaches } from './data/queryCache';-export type { GalleryImageCachePatch } from './data/queryCache';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex bc5b24c550..cba1187d98 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -28,7 +28,7 @@ import type { GalleryQueuePlaceholder } from './galleryStateView';import type { GalleryImageContextMenuTarget } from './GalleryUiContext';import { getGalleryImageDragData, getGalleryImageDragId } from './galleryDnd';-import { getGalleryPlaceholderInsertionIndex } from './galleryStateView';+import { getGalleryImageStateView, getGalleryPlaceholderInsertionIndex } from './galleryStateView';import { useGalleryUi } from './GalleryUiContext';import { useGalleryWidget } from './GalleryWidgetContext';@@ -69,7 +69,8 @@ type GridCell =export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {const { t } = useTranslation();- const { actions, gallery, imageActions, isWindowTruncated, runtime } = useGalleryWidget();+ const { actions, gallery: galleryState, imageActions, isWindowTruncated, runtime } = useGalleryWidget();+ const gallery = useMemo(() => getGalleryImageStateView(galleryState), [galleryState]);const { account, antialiasProgressImages, ImageContextMenu, widgets } = useGalleryUi();const [contextMenuTarget, setContextMenuTarget] = useState<GalleryImageContextMenuTarget | null>(null);const [isDropActive, setIsDropActive] = useState(false);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex 8b4a2b6dea..6fd0c592f0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -10,6 +10,7 @@ import type { GalleryStateView } from './galleryStateView';import { GalleryPanelContent } from './GalleryPanelContent';import {getGalleryPage,+ getGalleryImageStateView,getGalleryProjectBoardId,getGallerySearchTerm,getGallerySelectedBoardId,@@ -70,12 +71,13 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgconst gallery = getGalleryStateView(galleryValues,data.boards,- data.images,- data.isLoadingImages,+ data.items,+ data.isLoadingItems,queueItems,liveFollowEnabled,liveProgressTarget);+ const imageGallery = useMemo(() => getGalleryImageStateView(gallery), [gallery]);const lastPublishedTotalRef = useRef<number | null>(null);@@ -84,8 +86,8 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgconst onImagesDeleted = useCallback((imageNames: string[]) => {const deletedNames = new Set(imageNames);- const images = gallery.images;- const anchorName = gallery.selectedImageName;+ const images = imageGallery.images;+ const anchorName = imageGallery.selectedImageName;if (!anchorName || !deletedNames.has(anchorName)) {return;@@ -107,7 +109,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidggalleryCommands.selectImage(nextImage);}},- [gallery.images, gallery.selectedImageName, galleryCommands]+ [galleryCommands, imageGallery.images, imageGallery.selectedImageName]);const actions = useGalleryActions({@@ -161,7 +163,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg}, [galleryCommands, page, settings.paginationMode, total]);if (region === 'bottom' && presentation !== 'expanded') {- return <StatusWidgetChip icon={ImageIcon}>Gallery: {total ?? gallery.images.length}</StatusWidgetChip>;+ return <StatusWidgetChip icon={ImageIcon}>Gallery: {total ?? gallery.items.length}</StatusWidgetChip>;}return (diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex 3413d24fdb..bfc74d8055 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -1,3 +1,4 @@+import type { GalleryImageItem, GalleryItem, GalleryVideoItem } from '@features/gallery/core/items';import type { GalleryBoard, GeneratedImageContract } from '@features/gallery/core/types';import type { QueueHistoryItemStatus, QueueItem } from '@features/queue/contracts';@@ -36,6 +37,29 @@ const createImage = (imageName: string): GeneratedImageContract => ({width: 512,});+const createImageItem = (name: string): GalleryImageItem => ({+ boardId: 'none',+ category: 'general',+ createdAt: '2026-06-09T00:00:00.000Z',+ fullUrl: `/api/v1/images/i/${name}/full`,+ height: 768,+ isIntermediate: false,+ kind: 'image',+ name,+ sourceQueueItemId: 'queue-item-1',+ starred: false,+ thumbnailUrl: `/api/v1/images/i/${name}/thumbnail`,+ width: 512,+});++const createVideoItem = (name: string): GalleryVideoItem => ({+ ...createImageItem(name),+ durationSeconds: 3,+ fullUrl: `/api/v1/videos/i/${name}/full`,+ kind: 'video',+ thumbnailUrl: `/api/v1/videos/i/${name}/thumbnail`,+});+const createQueueItem = ({backendItemIds,batchCount = 1,@@ -96,7 +120,7 @@ describe('gallery state view', () => {const values = { recentImages: [createImage('local-fallback.png')], selectedBoardId: 'none' };const gallery = getGalleryStateView(values, boards, null, true);- expect(gallery.images).toEqual([]);+ expect((gallery as typeof gallery & { items?: GalleryItem[] }).items).toEqual([]);expect(gallery.isLoading).toBe(true);});@@ -122,26 +146,64 @@ describe('gallery state view', () => {});});- it('derives the multi-selection from persisted values with a single-selection fallback', () => {+ it('qualifies legacy names and preserves ordered mixed-media selection keys', () => {+ const gallery = getGalleryStateView(+ { selectedImageNames: ['a.png', 'video:shared', 'image:shared', 7] },+ boards,+ [],+ false+ ) as ReturnType<typeof getGalleryStateView> & { selectedItemKeys?: string[] };++ expect(gallery.selectedItemKeys).toEqual(['image:a.png', 'video:shared', 'image:shared']);expect(- getGalleryStateView({ selectedImageNames: ['a.png', 'b.png', 7] }, boards, [], false).selectedImageNames- ).toEqual(['a.png', 'b.png']);- expect(getGalleryStateView({ selectedImageName: 'a.png' }, boards, [], false).selectedImageNames).toEqual([- 'a.png',- ]);+ (+ getGalleryStateView({ selectedImageName: 'a.png' }, boards, [], false) as ReturnType<+ typeof getGalleryStateView+ > & { selectedItemKeys?: string[] }+ ).selectedItemKeys+ ).toEqual(['image:a.png']);});- it('restores the selection set from a visible primary image after tab switches clear it', () => {- const image = createImage('selected.png');+ it('restores the selection set from a visible primary item after tab switches clear it', () => {+ const image = createImageItem('selected.png');const gallery = getGalleryStateView(- { selectedImageName: image.imageName, selectedImageNames: [] },+ { selectedImageName: 'image:selected.png', selectedImageNames: [] },boards,- [{ ...image, boardId: 'none', imageCategory: 'general', starred: false }],+ [image],false- );+ ) as ReturnType<typeof getGalleryStateView> & {+ selectedItemKey?: string | null;+ selectedItemKeys?: string[];+ };- expect(gallery.selectedImageName).toBe(image.imageName);- expect(gallery.selectedImageNames).toEqual([image.imageName]);+ expect(gallery.selectedItemKey).toBe('image:selected.png');+ expect(gallery.selectedItemKeys).toEqual(['image:selected.png']);+ });++ it('projects same-name images and videos independently by qualified key', () => {+ const image = createImageItem('shared');+ const video = createVideoItem('shared');+ const gallery = getGalleryStateView(+ {+ compareImage: image,+ selectedImage: video,+ selectedImageName: 'video:shared',+ selectedImageNames: ['image:shared', 'video:shared'],+ },+ boards,+ [image, video],+ false+ ) as ReturnType<typeof getGalleryStateView> & {+ compareImageKey?: string | null;+ items?: GalleryItem[];+ selectedItemKey?: string | null;+ selectedItemKeys?: string[];+ };++ expect(gallery.items?.map((item) => `${item.kind}:${item.name}`)).toEqual(['image:shared', 'video:shared']);+ expect(gallery.selectedItemKey).toBe('video:shared');+ expect(gallery.selectedItemKeys).toEqual(['image:shared', 'video:shared']);+ expect(gallery.compareImageKey).toBe('image:shared');});it('creates placeholders for in-flight gallery queue items on the viewed board', () => {@@ -297,7 +359,7 @@ describe('gallery state view', () => {activePlaceholder: placeholder,isComparisonActive: false,liveFollowEnabled: true,- selectedImageName: 'saved.png',+ selectedItemKey: 'image:saved.png',})).toEqual({ kind: 'placeholder', placeholder });expect(@@ -305,21 +367,16 @@ describe('gallery state view', () => {activePlaceholder: placeholder,isComparisonActive: false,liveFollowEnabled: false,- selectedImageName: 'saved.png',+ selectedItemKey: 'image:saved.png',})- ).toEqual({ imageName: 'saved.png', kind: 'image' });+ ).toEqual({ itemKey: 'image:saved.png', kind: 'item' });});it('keeps the visible image selected when the active placeholder belongs to another board', () => {- const image = {- ...createImage('selected.png'),- boardId: 'board-1',- imageCategory: 'general',- starred: false,- } as const;+ const image = { ...createImageItem('selected.png'), boardId: 'board-1' } as const;const activeItem = createQueueItem({ boardId: 'board-2', localId: 'active-other-board', status: 'running' });const gallery = getGalleryStateView(- { selectedBoardId: 'board-1', selectedImageName: image.imageName },+ { selectedBoardId: 'board-1', selectedImageName: 'image:selected.png' },boards,[image],false,@@ -328,7 +385,7 @@ describe('gallery state view', () => {{ itemIndex: 1, queueItemId: activeItem.id });- expect(gallery.currentItem).toEqual({ imageName: image.imageName, kind: 'image' });+ expect(gallery.currentItem).toEqual({ itemKey: 'image:selected.png', kind: 'item' });});it('skips cancelled backend item slots when creating placeholders', () => {@@ -379,12 +436,7 @@ describe('gallery state view', () => {it('hides only pending placeholders when the persisted setting is disabled', () => {const queueItems = [createQueueItem({ boardId: 'none', status: 'pending' })];- const image = {- ...createImage('completed.png'),- boardId: 'none',- imageCategory: 'general',- starred: false,- } as const;+ const image = createImageItem('completed.png');const gallery = getGalleryStateView({ selectedBoardId: 'none', showPendingItems: false },boards,@@ -394,7 +446,7 @@ describe('gallery state view', () => {);expect(gallery.pendingPlaceholders).toEqual([]);- expect(gallery.images).toEqual([image]);+ expect((gallery as typeof gallery & { items?: GalleryItem[] }).items).toEqual([image]);expect(gallery.settings.showPendingItems).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 43bf2593db..01fcb3c0c5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -1,14 +1,17 @@-import type {- GalleryBoard,- GalleryImage,- GalleryOrderDir,- GalleryView,- GeneratedImageContract,-} from '@features/gallery/core/types';+import type { GalleryBoard, GalleryImage, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';import type { QueueItem } from '@features/queue/contracts';-import { normalizeGalleryImage } from '@features/gallery/core/image';+import {+ galleryImageItemToGalleryImage,+ isGalleryImageItem,+ legacyGeneratedImageToGalleryItem,+ parseGalleryItemKey,+ toGalleryItemKey,+ type GalleryItem,+ type GalleryItemKey,+} from '@features/gallery/core/items';import { getBoundedRecentImages } from '@features/gallery/core/recentImages';+import { getSelectedGalleryImageFromValues, getSelectedGalleryItemFromValues } from '@features/gallery/core/selection';import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';@@ -53,23 +56,23 @@ export interface GalleryGenerationSequence {}export type GalleryCurrentItem =- | { kind: 'image'; imageName: string }+ | { kind: 'item'; itemKey: GalleryItemKey }| { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder }| null;export interface GalleryStateView {boards: GalleryBoard[];- compareImageName: string | null;+ compareImageKey: GalleryItemKey | null;currentItem: GalleryCurrentItem;galleryView: GalleryView;- images: GalleryImage[];+ items: GalleryItem[];isLoading: boolean;pendingPlaceholders: GalleryQueuePlaceholder[];projectBoardId: string | null;searchTerm: string;selectedBoardId: string;- selectedImageName: string | null;- selectedImageNames: string[];+ selectedItemKey: GalleryItemKey | null;+ selectedItemKeys: GalleryItemKey[];settings: GallerySettings;}@@ -196,18 +199,18 @@ export const getGalleryCurrentItem = ({activePlaceholder,isComparisonActive,liveFollowEnabled,- selectedImageName,+ selectedItemKey,}: {activePlaceholder: GalleryQueuePlaceholder | null;isComparisonActive: boolean;liveFollowEnabled: boolean;- selectedImageName: string | null;+ selectedItemKey: GalleryItemKey | null;}): GalleryCurrentItem => {if (liveFollowEnabled && !isComparisonActive && activePlaceholder) {return { kind: 'placeholder', placeholder: activePlaceholder };}- return selectedImageName ? { imageName: selectedImageName, kind: 'image' } : null;+ return selectedItemKey ? { itemKey: selectedItemKey, kind: 'item' } : null;};export const getGalleryView = (values: Record<string, unknown>): GalleryView =>@@ -226,12 +229,22 @@ export const getGallerySelectedBoardId = (values: Record<string, unknown>, backereturn 'none';};-export const getGallerySelectedImageNames = (values: Record<string, unknown>): string[] => {+const canonicalizePersistedItemKey = (key: string): GalleryItemKey => toGalleryItemKey(parseGalleryItemKey(key));++export const getGallerySelectedItemKeys = (values: Record<string, unknown>): GalleryItemKey[] => {if (Array.isArray(values.selectedImageNames)) {- return (values.selectedImageNames as unknown[]).filter((name): name is string => typeof name === 'string');+ return (values.selectedImageNames as unknown[])+ .filter((name): name is string => typeof name === 'string')+ .map(canonicalizePersistedItemKey);+ }++ if (typeof values.selectedImageName === 'string') {+ return [canonicalizePersistedItemKey(values.selectedImageName)];}- return typeof values.selectedImageName === 'string' ? [values.selectedImageName] : [];+ const selectedItem = getSelectedGalleryItemFromValues(values);++ return selectedItem ? [toGalleryItemKey(selectedItem)] : [];};export const getGalleryPage = (values: Record<string, unknown>): number =>@@ -297,19 +310,12 @@ export const getGalleryTotalImages = (values: Record<string, unknown>): number |export const getGalleryProjectBoardId = (values: Record<string, unknown>): string | null =>typeof values.projectBoardId === 'string' ? values.projectBoardId : null;-export const getGalleryCompareImage = (values: Record<string, unknown>): GeneratedImageContract | null => {- const compareImage = values.compareImage;-- if (- compareImage &&- typeof compareImage === 'object' &&- typeof (compareImage as GeneratedImageContract).imageName === 'string'- ) {- return compareImage as GeneratedImageContract;- }-- return null;-};+export const getGalleryCompareImage = (values: Record<string, unknown>): GalleryImage | null =>+ getSelectedGalleryImageFromValues({+ selectedBoardId: values.selectedBoardId,+ selectedImage: values.compareImage,+ selectedImageName: null,+ });export const getGalleryQueuePlaceholders = (queueItems: QueueItem[],@@ -349,28 +355,45 @@ const getVisibleGalleryQueuePlaceholders = (export const getGalleryStateView = (values: Record<string, unknown>,backendBoards: GalleryBoard[],- backendImages: GalleryImage[] | null,+ backendItems: GalleryItem[] | null,isLoading: boolean,queueItems: QueueItem[] = [],liveFollowEnabled = false,liveTarget: GalleryLiveTarget | null = null): GalleryStateView => {- const localImages = getBoundedRecentImages(values.recentImages).map((image) => normalizeGalleryImage(image));- const images = backendImages ?? (isLoading ? [] : localImages);- const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;- const visibleSelectedImageName = images.some((image) => image.imageName === selectedImageName)- ? selectedImageName- : null;- const selectedImageNames = getGallerySelectedImageNames(values);+ const localItems = getBoundedRecentImages(values.recentImages).map(legacyGeneratedImageToGalleryItem);+ const items = backendItems ?? (isLoading ? [] : localItems);+ const selectedItem = getSelectedGalleryItemFromValues(values);+ const persistedSelectedItemKey =+ typeof values.selectedImageName === 'string'+ ? canonicalizePersistedItemKey(values.selectedImageName)+ : selectedItem+ ? toGalleryItemKey(selectedItem)+ : null;+ const visibleSelectedItemKey =+ persistedSelectedItemKey && items.some((item) => toGalleryItemKey(item) === persistedSelectedItemKey)+ ? persistedSelectedItemKey+ : null;+ const selectedItemKeys = getGallerySelectedItemKeys(values);const galleryView = getGalleryView(values);const settings = getGallerySettings(values);const searchTerm = getGallerySearchTerm(values);- const boards = backendBoards.length ? backendBoards : [{ ...UNCATEGORIZED_BOARD, imageCount: images.length }];+ const boards = backendBoards.length+ ? backendBoards+ : [+ {+ ...UNCATEGORIZED_BOARD,+ imageCount: items.filter((item) => item.kind === 'image' && item.category === 'general').length,+ videoCount: items.filter((item) => item.kind === 'video').length,+ },+ ];const selectedBoardId = getGallerySelectedBoardId(values, backendBoards);const compareImage = getGalleryCompareImage(values);- const compareImageName = compareImage?.imageName ?? null;+ const compareImageKey = compareImage ? toGalleryItemKey({ kind: 'image', name: compareImage.imageName }) : null;const isComparisonActive =- visibleSelectedImageName !== null && compareImageName !== null && compareImageName !== visibleSelectedImageName;+ visibleSelectedItemKey?.startsWith('image:') === true &&+ compareImageKey !== null &&+ compareImageKey !== visibleSelectedItemKey;const generationSequence = getGalleryGenerationSequence(queueItems, liveTarget);const visibleActivePlaceholder =settings.showPendingItems && galleryView === 'images' && searchTerm.trim() === ''@@ -382,15 +405,15 @@ export const getGalleryStateView = (activePlaceholder: visibleActivePlaceholder,isComparisonActive,liveFollowEnabled,- selectedImageName: visibleSelectedImageName,+ selectedItemKey: visibleSelectedItemKey,});return {boards,- compareImageName,+ compareImageKey,currentItem,galleryView,- images,+ items,isLoading,pendingPlaceholders: settings.showPendingItems? getVisibleGalleryQueuePlaceholders(generationSequence.chronologicalSlots, {@@ -403,15 +426,42 @@ export const getGalleryStateView = (projectBoardId: getGalleryProjectBoardId(values),searchTerm,selectedBoardId,- selectedImageName: visibleSelectedImageName,- selectedImageNames:- visibleSelectedImageName && !selectedImageNames.includes(visibleSelectedImageName)- ? [visibleSelectedImageName, ...selectedImageNames]- : selectedImageNames,+ selectedItemKey: visibleSelectedItemKey,+ selectedItemKeys:+ visibleSelectedItemKey && !selectedItemKeys.includes(visibleSelectedItemKey)+ ? [visibleSelectedItemKey, ...selectedItemKeys]+ : selectedItemKeys,settings,};};+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/useGalleryData.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.tsindex b0817fd996..3fb1244403 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts@@ -4,7 +4,7 @@ import type { GalleryImage, GeneratedImageContract } from '@features/gallery/corimport { getBoundedRecentImages } from '@features/gallery/core/recentImages';import { describe, expect, it } from 'vitest';-import { isGalleryWindowTruncated, mergeGalleryImageWindow, mergeGalleryItemWindow } from './useGalleryData';+import { isGalleryWindowTruncated, mergeGalleryItemWindow } from './useGalleryData';const createImage = (index: number, overrides: Partial<GalleryImage> = {}): GalleryImage => ({boardId: 'none',@@ -30,66 +30,6 @@ const filter = {starredFirst: false,};-describe('mergeGalleryImageWindow', () => {- it('deduplicates the recent overlay and keeps newest-first ordering', () => {- const backend = [createImage(1), createImage(2)];- const recent = [asGenerated(createImage(3)), asGenerated(createImage(2))];-- expect(- mergeGalleryImageWindow({ backendImages: backend, filter, maxRows: 600, recentImages: recent }).map(- (image) => image.imageName- )- ).toEqual(['image-0003.png', 'image-0002.png', 'image-0001.png']);- });-- it('bounds both the optimistic overlay and the rendered infinite window', () => {- const backend = Array.from({ length: 600 }, (_, index) => createImage(index));- const rawRecent = Array.from({ length: 1_000 }, (_, index) => asGenerated(createImage(1_000 + index)));- const recent = getBoundedRecentImages(rawRecent);- const images = mergeGalleryImageWindow({ backendImages: backend, filter, maxRows: 600, recentImages: recent });-- expect(recent).toHaveLength(60);- expect(images).toHaveLength(600);- expect(images.slice(0, 60).map((image) => image.imageName)).toEqual(- recent.map((image) => image.imageName).reverse()- );- });-- it('does not overlay recent images into incompatible board, asset, search, or date filters', () => {- const recent = [asGenerated(createImage(2))];- const filters = [- { ...filter, boardId: 'board-2' },- { ...filter, galleryView: 'assets' as const },- { ...filter, searchTerm: 'portrait' },- { ...filter, createdFrom: '2026-01-01' },- { ...filter, boardId: 'by_date:2026-01-01' },- ];-- for (const candidate of filters) {- expect(- mergeGalleryImageWindow({- backendImages: [createImage(1)],- filter: candidate,- maxRows: 600,- recentImages: recent,- })- ).toHaveLength(1);- }- });-- it('preserves starred-first ordering and the paginated row cap', () => {- const images = mergeGalleryImageWindow({- backendImages: Array.from({ length: 60 }, (_, index) => createImage(index)),- filter: { ...filter, starredFirst: true },- maxRows: 60,- recentImages: [asGenerated(createImage(100, { starred: true }))],- });-- expect(images).toHaveLength(60);- expect(images[0]).toMatchObject({ imageName: 'image-0100.png', starred: true });- });-});-describe('mergeGalleryItemWindow', () => {it('deduplicates by qualified key and mirrors server starred/time/kind/name ordering', () => {const image = {@@ -138,6 +78,31 @@ describe('mergeGalleryItemWindow', () => {).toEqual(['image:shared', 'video:shared']);});+ it('bounds the optimistic image overlay and the mixed rendered window', () => {+ const createItem = (index: number): GalleryItem => ({+ boardId: 'none',+ category: 'general',+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),+ fullUrl: `/images/${index}`,+ height: 512,+ isIntermediate: false,+ kind: 'image',+ name: `image-${index}.png`,+ starred: false,+ thumbnailUrl: `/thumbnails/${index}`,+ width: 512,+ });+ const backendItems = Array.from({ length: 600 }, (_, index) => createItem(index));+ const recentImages = getBoundedRecentImages(+ Array.from({ length: 1_000 }, (_, index) => asGenerated(createImage(1_000 + index)))+ );+ const items = mergeGalleryItemWindow({ backendItems, filter, maxRows: 600, recentImages });++ expect(recentImages).toHaveLength(60);+ expect(items).toHaveLength(600);+ expect(items.slice(0, 60).map((item) => item.name)).toEqual(recentImages.map((image) => image.imageName).reverse());+ });+it('uses SQLite binary ordering for mixed-case and punctuation name ties in both directions', () => {const createTiedItem = (name: string): GalleryItem => ({boardId: 'none',diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsindex eb016104da..cb5e73a987 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -1,18 +1,17 @@import type { GalleryItem } from '@features/gallery/core/items';import type { GallerySettings } from '@features/gallery/core/settings';-import type { GalleryBoard, GalleryImage, GalleryView, GeneratedImageContract } from '@features/gallery/core/types';+import type { GalleryBoard, GalleryView, GeneratedImageContract } from '@features/gallery/core/types';-import { normalizeGalleryImage } from '@features/gallery/core/image';import { legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery/core/items';import { GALLERY_RECENT_IMAGE_LIMIT } from '@features/gallery/core/recentImages';import { ALL_READABLE_BOARDS_ID, isDateBoardId } from '@features/gallery/data/backend';import {- flattenGalleryImagesData,+ flattenGalleryItemsData,GALLERY_MAX_ROWS,GALLERY_PAGE_SIZE,galleryBoardsOptions,- galleryImagesInfiniteOptions,- type GalleryImagesFilter,+ galleryItemsInfiniteOptions,+ type GalleryItemsFilter,} from '@features/gallery/data/queries';import { parseDateTokens } from '@platform/search/dateTokens';import { useInfiniteQuery, useQuery } from '@tanstack/react-query';@@ -21,8 +20,7 @@ import { useCallback, useMemo } from 'react';export interface GalleryData {boards: GalleryBoard[];hasMore: boolean;- images: GalleryImage[] | null;- isLoadingImages: boolean;+ isLoadingItems: boolean;/*** True when the infinite window is full *and* the board holds more images* than it can reach. `hasMore` is false in that case exactly as it is at the@@ -31,6 +29,7 @@ export interface GalleryData {* user an explanation.*/isWindowTruncated: boolean;+ items: GalleryItem[] | null;loadMore: () => void;total: number | null;}@@ -48,38 +47,7 @@ const useGalleryBoards = ({ settings }: { settings: GallerySettings }) => {return { boards: query.data ?? [] };};-const isRecentImageVisible = (image: GalleryImage, filter: GalleryImagesFilter): boolean => {- if (- filter.searchTerm !== '' ||- filter.createdFrom !== undefined ||- filter.createdTo !== undefined ||- isDateBoardId(filter.boardId)- ) {- return false;- }-- const hasMatchingBoard = filter.boardId === ALL_READABLE_BOARDS_ID || filter.boardId === image.boardId;- const hasMatchingCategory =- filter.galleryView === 'images' ? image.imageCategory === 'general' : image.imageCategory !== 'general';-- return hasMatchingBoard && hasMatchingCategory;-};--const compareGalleryImages = (- a: GalleryImage,- b: GalleryImage,- { orderDir = 'DESC', starredFirst = false }: GalleryImagesFilter-): number => {- if (starredFirst && a.starred !== b.starred) {- return a.starred ? -1 : 1;- }-- const chronologicalOrder = a.queuedAt.localeCompare(b.queuedAt);-- return orderDir === 'ASC' ? chronologicalOrder : -chronologicalOrder;-};--const isRecentItemVisible = (item: GalleryItem, filter: GalleryImagesFilter): boolean => {+const isRecentItemVisible = (item: GalleryItem, filter: GalleryItemsFilter): boolean => {if (filter.searchTerm !== '' ||filter.createdFrom !== undefined ||@@ -103,7 +71,7 @@ const compareSqliteBinaryText = (a: string, b: string): number => (a === b ? 0 :const compareGalleryItems = (a: GalleryItem,b: GalleryItem,- { orderDir = 'DESC', starredFirst = false }: GalleryImagesFilter+ { orderDir = 'DESC', starredFirst = false }: GalleryItemsFilter): number => {if (starredFirst && a.starred !== b.starred) {return a.starred ? -1 : 1;@@ -132,7 +100,7 @@ export const mergeGalleryItemWindow = ({recentImages,}: {backendItems: readonly GalleryItem[];- filter: GalleryImagesFilter;+ filter: GalleryItemsFilter;maxRows: number;recentImages: readonly GeneratedImageContract[];}): GalleryItem[] => {@@ -158,33 +126,6 @@ export const mergeGalleryItemWindow = ({.slice(0, maxRows);};-/** TODO(Task 5): Remove after the Gallery projection consumes GalleryItem. */-export const mergeGalleryImageWindow = ({- backendImages,- filter,- maxRows,- recentImages,-}: {- backendImages: readonly GalleryImage[];- filter: GalleryImagesFilter;- maxRows: number;- recentImages: readonly GeneratedImageContract[];-}): GalleryImage[] => {- const backendImageNames = new Set(backendImages.map((image) => image.imageName));- const missingRecentImages = recentImages- .slice(0, GALLERY_RECENT_IMAGE_LIMIT)- .map((image) => normalizeGalleryImage(image))- .filter((image) => !backendImageNames.has(image.imageName) && isRecentImageVisible(image, filter));-- if (missingRecentImages.length === 0) {- return backendImages.length <= maxRows ? (backendImages as GalleryImage[]) : backendImages.slice(0, maxRows);- }-- return [...missingRecentImages, ...backendImages]- .sort((a, b) => compareGalleryImages(a, b, filter))- .slice(0, maxRows);-};-/*** Distinguishes "this board has no more images" from "this board has more* images than the infinite window can reach".@@ -228,7 +169,7 @@ export const useGalleryData = ({boards.length === 0 || boards.some((board) => board.id === selectedBoardId) ? selectedBoardId : 'none';const isPaginated = settings.paginationMode === 'paginated';const dateParse = useMemo(() => parseDateTokens(searchTerm), [searchTerm]);- const filter = useMemo<GalleryImagesFilter>(+ const filter = useMemo<GalleryItemsFilter>(() => ({boardId,createdFrom: dateParse.range?.from,@@ -255,41 +196,41 @@ export const useGalleryData = ({isFetching,isFetchingNextPage,} = useInfiniteQuery(- galleryImagesInfiniteOptions(+ galleryItemsInfiniteOptions(filter,isPaginated ? { kind: 'anchor', offset: page * GALLERY_PAGE_SIZE } : { kind: 'infinite' }));- const backendImages = useMemo(() => {+ const backendItems = useMemo(() => {if (!isPaginated) {- return flattenGalleryImagesData(queryData);+ return flattenGalleryItemsData(queryData);}const pageOffset = page * GALLERY_PAGE_SIZE;const pageIndex = queryData?.pageParams.indexOf(pageOffset) ?? -1;- return pageIndex === -1 ? [] : (queryData?.pages[pageIndex]?.images ?? []).slice(0, GALLERY_PAGE_SIZE);+ return pageIndex === -1 ? [] : (queryData?.pages[pageIndex]?.items ?? []).slice(0, GALLERY_PAGE_SIZE);}, [isPaginated, page, queryData]);- const shouldOverlayRecentImages = !isPaginated;+ const shouldOverlayRecentItems = !isPaginated;const maxRows = isPaginated ? GALLERY_PAGE_SIZE : GALLERY_MAX_ROWS;- const images = useMemo(+ const items = useMemo(() =>- queryData || (shouldOverlayRecentImages && recentImages.length > 0)- ? mergeGalleryImageWindow({- backendImages,+ queryData || (shouldOverlayRecentItems && recentImages.length > 0)+ ? mergeGalleryItemWindow({+ backendItems,filter,maxRows,- recentImages: shouldOverlayRecentImages ? recentImages : [],+ recentImages: shouldOverlayRecentItems ? recentImages : [],}): null,- [backendImages, filter, maxRows, queryData, recentImages, shouldOverlayRecentImages]+ [backendItems, filter, maxRows, queryData, recentImages, shouldOverlayRecentItems]);const total = queryData?.pages[0]?.total ?? null;const hasMore = !isPaginated && Boolean(hasNextPage);const isWindowTruncated = isGalleryWindowTruncated({hasNextPage: Boolean(hasNextPage),isPaginated,- loadedRowCount: backendImages.length,+ loadedRowCount: backendItems.length,maxRows,total,});@@ -301,5 +242,5 @@ export const useGalleryData = ({void fetchNextPage();}, [fetchNextPage, hasMore, isFetchingNextPage]);- return { boards, hasMore, images, isLoadingImages: isFetching, isWindowTruncated, loadMore, total };+ return { boards, hasMore, isLoadingItems: isFetching, isWindowTruncated, items, loadMore, total };};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex fb8e32424c..bd1e88c37e 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -2,7 +2,8 @@ import type { ModelConfig, ModelTaxonomyType } from '@features/models/react';import type { FieldInputTemplate } from '@features/workflow/contracts';import { createListCollection, HStack, Input, Switch, Text } from '@chakra-ui/react';-import { galleryDestinations, type GalleryBoard, type GeneratedImageContract } from '@features/gallery';+import { galleryDestinations, type GalleryBoard } from '@features/gallery';+import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';import { SCHEDULER_OPTIONS } from '@features/generation/settings';import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';import {@@ -21,6 +22,8 @@ const MODEL_SELECT_FALLBACK = (</Button>);+export const getWorkflowSelectedGalleryImage = getSelectedGalleryImageFromValues;+/*** Direct-input controls for workflow fields, shared between the node editor* and the Linear UI panel. Renders by template field type; connection-only@@ -365,8 +368,8 @@ const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInp};const ImageInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {- const gallerySelection = useWorkflowProjectSelector(- (project) => project.galleryValues.selectedImage as GeneratedImageContract | null | undefined+ const gallerySelection = useWorkflowProjectSelector((project) =>+ getWorkflowSelectedGalleryImage(project.galleryValues));const imageName =typeof (value as { image_name?: unknown } | null)?.image_name === 'string'diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 8577b6285c..2e18119926 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -4,10 +4,12 @@ import {galleryImages,galleryOrganization,galleryTransfers,+ toGalleryItemKey,type GalleryBoard,type GalleryImage,+ type GalleryItemMutationResult,} from '@features/gallery';-import { invalidateGallery, invalidateGalleryImages, patchGalleryImageCaches } from '@features/gallery/queries';+import { invalidateGallery, invalidateGalleryItems, patchGalleryItemCaches } from '@features/gallery/queries';import { setPendingPromptTemplateDraft } from '@features/generation/react';import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';@@ -68,6 +70,14 @@ export interface ImageActions {const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));+const getImageMutationResult = (+ succeededImageNames: readonly string[],+ failedImageNames: readonly string[] = []+): GalleryItemMutationResult => ({+ failed: failedImageNames.map((name) => ({ kind: 'image', name })),+ succeeded: succeededImageNames.map((name) => ({ kind: 'image', name })),+});+const toPngBlob = async (blob: Blob): Promise<Blob> => {if (blob.type === 'image/png') {return blob;@@ -168,8 +178,10 @@ export const useImageActions = ({// Evict only what the backend actually deleted. A name it refused is still on the// server, so dropping it from the cache would hide a live image until a full refresh.if (deletedImageNames.length > 0) {- patchGalleryImageCaches(queryClient, { imageNames: deletedImageNames, kind: 'delete' });- gallery.removeImages(deletedImageNames);+ const result = getImageMutationResult(deletedImageNames, failedImageNames);++ patchGalleryItemCaches(queryClient, { kind: 'delete', result });+ gallery.removeItems(result.succeeded.map(toGalleryItemKey));onImagesDeleted?.(deletedImageNames);}@@ -305,8 +317,10 @@ export const useImageActions = ({}assertAccountScopeCurrent(owner);- patchGalleryImageCaches(queryClient, { boardId, imageNames, kind: 'move' });- gallery.patchImages(imageNames, { boardId });+ const result = getImageMutationResult(imageNames);++ patchGalleryItemCaches(queryClient, { boardId, kind: 'move', result });+ gallery.patchItems(result.succeeded.map(toGalleryItemKey), { boardId });recordSuccess(imageNames.length === 1? `Moved image to ${getBoardName(boardId)}`@@ -389,14 +403,15 @@ export const useImageActions = ({},setImagesStarred: async (imageNames, starred) => {const owner = captureAccountScope();- const rollback = patchGalleryImageCaches(queryClient, { imageNames, kind: 'star', starred });+ const result = getImageMutationResult(imageNames);+ const rollback = patchGalleryItemCaches(queryClient, { kind: 'star', result, starred });try {await galleryOrganization.setStarred(imageNames, starred, owner.signal);assertAccountScopeCurrent(owner);- gallery.patchImages(imageNames, { starred });- void invalidateGalleryImages(queryClient);+ gallery.patchItems(result.succeeded.map(toGalleryItemKey), { starred });+ void invalidateGalleryItems(queryClient);} catch (error: unknown) {rollback();@@ -404,7 +419,7 @@ export const useImageActions = ({return;}- void invalidateGalleryImages(queryClient);+ void invalidateGalleryItems(queryClient);recordError(error);}},diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsxindex 6511b0ed7f..ef34c45c84 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx@@ -5,7 +5,7 @@ import type { FormEvent } from 'react';import { chakra, createListCollection, Dialog, Portal, Stack, Text } from '@chakra-ui/react';import { galleryDurability, galleryImages } from '@features/gallery';-import { invalidateGalleryImages } from '@features/gallery/queries';+import { invalidateGalleryItems } from '@features/gallery/queries';import { runUtilityGraph } from '@features/queue/utility';import {buildLayerWorkflowGraph,@@ -373,7 +373,7 @@ export const RunLayerWorkflowDialog = ({saveToGallery: galleryDurability.save,touchGallery: () => {if (isAccountScopeCurrent(owner)) {- void invalidateGalleryImages(queryClient, owner);+ void invalidateGalleryItems(queryClient, owner);}},uploadIntermediate: (blob, signal) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsxindex bbddeb035e..aeca0c0549 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx@@ -1,5 +1,5 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */-import type { GalleryImage, GalleryImagesPage } from '@features/gallery';+import type { GalleryImage, GalleryItemsPage } from '@features/gallery';import type { QueueItem } from '@features/queue/contracts';import type { WidgetViewProps } from '@workbench/widgetContracts';@@ -75,8 +75,8 @@ const mocks = vi.hoisted(() => {preview: { state: { values: {} }, typeId: 'preview' },},},- galleryImagePageOffsets: [] as number[],- galleryImagePages: [] as GalleryImagesPage[],+ galleryItemPageOffsets: [] as number[],+ galleryItemPages: [] as GalleryItemsPage[],recentImages,useActiveProgressTarget: vi.fn(() => null as unknown),useProgressImage: vi.fn(() => null as unknown),@@ -99,36 +99,36 @@ vi.mock('@features/queue/react', async (importOriginal) => ({vi.mock('@features/gallery/queries', () => ({GALLERY_MAX_ROWS: 600,GALLERY_PAGE_SIZE: 60,- flattenGalleryImagesData: (data: InfiniteData<GalleryImagesPage, number> | undefined): GalleryImage[] =>- data?.pages.flatMap((page) => page.images) ?? [],+ flattenGalleryItemsData: (data: InfiniteData<GalleryItemsPage, number> | undefined) =>+ data?.pages.flatMap((page) => page.items) ?? [],galleryBoardsOptions: () => ({ queryFn: () => [], queryKey: ['test-boards'], staleTime: Infinity }),- galleryImagesInfiniteOptions: (+ galleryItemsInfiniteOptions: (query: { boardId: string; orderDir?: 'ASC' | 'DESC' },window: { kind: 'anchor' | 'infinite' | 'page'; offset?: number } = { kind: 'infinite' }) => {- const pages = mocks.galleryImagePages.map((page) => {- const images = page.images.filter((image) => image.boardId === query.boardId);+ const pages = mocks.galleryItemPages.map((page) => {+ const items = page.items.filter((item) => item.boardId === query.boardId);return {...page,- images: query.orderDir === 'ASC' ? images.reverse() : images,+ items: query.orderDir === 'ASC' ? items.reverse() : items,};});const initialOffset = window.kind === 'infinite' ? 0 : (window.offset ?? 0);- const initialPage = pages[initialOffset / 60] ?? { images: [], total: 0 };+ const initialPage = pages[initialOffset / 60] ?? { items: [], total: 0 };return {- getNextPageParam: (_lastPage: GalleryImagesPage, _allPages: GalleryImagesPage[], lastPageParam: number) =>+ getNextPageParam: (_lastPage: GalleryItemsPage, _allPages: GalleryItemsPage[], lastPageParam: number) =>pages[lastPageParam / 60 + 1] ? lastPageParam + 60 : undefined,- getPreviousPageParam: (_firstPage: GalleryImagesPage, _allPages: GalleryImagesPage[], firstPageParam: number) =>+ getPreviousPageParam: (_firstPage: GalleryItemsPage, _allPages: GalleryItemsPage[], firstPageParam: number) =>firstPageParam >= 60 ? firstPageParam - 60 : undefined,initialData: { pageParams: [initialOffset], pages: [initialPage] },initialPageParam: initialOffset,queryFn: ({ pageParam }: { pageParam: number }) => {- mocks.galleryImagePageOffsets.push(pageParam);- return Promise.resolve(pages[pageParam / 60] ?? { images: [], total: 0 });+ mocks.galleryItemPageOffsets.push(pageParam);+ return Promise.resolve(pages[pageParam / 60] ?? { items: [], total: 0 });},- queryKey: ['test-images', query.boardId, query.orderDir, window.kind, initialOffset],+ queryKey: ['test-items', query.boardId, query.orderDir, window.kind, initialOffset],staleTime: Infinity,};},@@ -236,14 +236,22 @@ beforeEach(() => {boardId: 'none',};mocks.project.widgetInstances.gallery.state.values.selectedImageName = 'newest';- mocks.galleryImagePageOffsets.length = 0;- mocks.galleryImagePages = [+ mocks.galleryItemPageOffsets.length = 0;+ mocks.galleryItemPages = [{- images: mocks.recentImages.map((image) => ({- ...image,+ items: mocks.recentImages.map((image) => ({boardId: 'none',- imageCategory: 'general',+ category: 'general' as const,+ createdAt: image.queuedAt,+ fullUrl: image.imageUrl,+ height: image.height,+ isIntermediate: false,+ kind: 'image' as const,+ name: image.imageName,+ sourceQueueItemId: image.sourceQueueItemId,starred: false,+ thumbnailUrl: image.thumbnailUrl,+ width: image.width,})),total: mocks.recentImages.length,},@@ -298,9 +306,45 @@ describe('preview keyboard navigation boundary', () => {starred: false,};mocks.project.widgetInstances.gallery.state.values.recentImages = [mocks.recentImages[0]];- mocks.galleryImagePages = [- { images: [newest], total: 2 },- { images: [oldest], total: 2 },+ mocks.galleryItemPages = [+ {+ items: [+ {+ boardId: newest.boardId,+ category: newest.imageCategory,+ createdAt: newest.queuedAt,+ fullUrl: newest.imageUrl,+ height: newest.height,+ isIntermediate: false,+ kind: 'image',+ name: newest.imageName,+ sourceQueueItemId: newest.sourceQueueItemId,+ starred: newest.starred,+ thumbnailUrl: newest.thumbnailUrl,+ width: newest.width,+ },+ ],+ total: 2,+ },+ {+ items: [+ {+ boardId: oldest.boardId,+ category: oldest.imageCategory,+ createdAt: oldest.queuedAt,+ fullUrl: oldest.imageUrl,+ height: oldest.height,+ isIntermediate: false,+ kind: 'image',+ name: oldest.imageName,+ sourceQueueItemId: oldest.sourceQueueItemId,+ starred: oldest.starred,+ thumbnailUrl: oldest.thumbnailUrl,+ width: oldest.width,+ },+ ],+ total: 2,+ },];await render();@@ -314,7 +358,7 @@ describe('preview keyboard navigation boundary', () => {true);});- expect(mocks.galleryImagePageOffsets).toEqual([60]);+ expect(mocks.galleryItemPageOffsets).toEqual([60]);expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);});@@ -347,9 +391,41 @@ describe('preview keyboard navigation boundary', () => {galleryValues.recentImages = [];galleryValues.selectedImage = selected;galleryValues.selectedImageName = selected.imageName;- mocks.galleryImagePages = [- { images: [pageZero], total: 3 },- { images: [selected, neighbor], total: 3 },+ mocks.galleryItemPages = [+ {+ items: [pageZero].map((image) => ({+ boardId: image.boardId,+ category: image.imageCategory,+ createdAt: image.queuedAt,+ fullUrl: image.imageUrl,+ height: image.height,+ isIntermediate: false,+ kind: 'image' as const,+ name: image.imageName,+ sourceQueueItemId: image.sourceQueueItemId,+ starred: image.starred,+ thumbnailUrl: image.thumbnailUrl,+ width: image.width,+ })),+ total: 3,+ },+ {+ items: [selected, neighbor].map((image) => ({+ boardId: image.boardId,+ category: image.imageCategory,+ createdAt: image.queuedAt,+ fullUrl: image.imageUrl,+ height: image.height,+ isIntermediate: false,+ kind: 'image' as const,+ name: image.imageName,+ sourceQueueItemId: image.sourceQueueItemId,+ starred: image.starred,+ thumbnailUrl: image.thumbnailUrl,+ width: image.width,+ })),+ total: 3,+ },];await render();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 346cdc1c97..fb46f36de7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -16,16 +16,22 @@ import {getGalleryLiveSlots,getGallerySelectedImageQuery,getGallerySettings,+ getSelectedGalleryImageFromValues,+ getSelectedGalleryItemFromValues,getBoundedRecentImages,+ galleryImageItemToGalleryImage,+ isGalleryImageItem,normalizeGalleryImage,+ parseGalleryItemKey,+ type GalleryItemsPage,type GalleryQueuePlaceholder,} from '@features/gallery/contracts';import {- flattenGalleryImagesData,+ flattenGalleryItemsData,GALLERY_MAX_ROWS,GALLERY_PAGE_SIZE,galleryBoardsOptions,- galleryImagesInfiniteOptions,+ galleryItemsInfiniteOptions,} from '@features/gallery/queries';import { createGenerateFormValuesSelector } from '@features/generation/react';import { useDeviceLabel } from '@features/queue/devices';@@ -43,7 +49,7 @@ import {progressImageToStreamingSource,} from '@platform/ui/streaming-image/streamingImageSource';import { useStreamingImageSource } from '@platform/ui/streaming-image/useStreamingImageSource';-import { useInfiniteQuery, useQuery } from '@tanstack/react-query';+import { useInfiniteQuery, useQuery, type InfiniteData } from '@tanstack/react-query';import {ImageContextMenu,useImageActions,@@ -105,24 +111,32 @@ const getGalleryImages = (values: Record<string, unknown>, queueItems: QueueItem};const getSelectedImage = (values: Record<string, unknown>, localImages: PreviewImage[]): PreviewImage | null => {- const selectedImage = values.selectedImage;- const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;+ const selectedItem = getSelectedGalleryItemFromValues(values);- if (- selectedImage &&- typeof selectedImage === 'object' &&- typeof (selectedImage as GeneratedImageContract).imageName === 'string'- ) {- const image = selectedImage as PreviewImage;+ if (selectedItem?.kind === 'video') {+ return null;+ }++ const selectedImage = getSelectedGalleryImageFromValues(values);- return typeof image.boardId === 'string'- ? image- : (localImages.find((candidate) => candidate.imageName === image.imageName) ?? image);+ if (selectedImage) {+ return localImages.find((candidate) => candidate.imageName === selectedImage.imageName) ?? selectedImage;}- return localImages.find((image) => image.imageName === selectedImageName) ?? localImages[0] ?? null;+ if (typeof values.selectedImageName === 'string' && parseGalleryItemKey(values.selectedImageName).kind === 'video') {+ return null;+ }++ return localImages[0] ?? null;};+/**+ * TODO(Task 8): Remove when Preview navigates `GalleryItem` directly.+ * The compatibility projection narrows before creating image contracts.+ */+const flattenPreviewImages = (data: InfiniteData<GalleryItemsPage, number> | undefined): GalleryImage[] =>+ flattenGalleryItemsData(data).filter(isGalleryImageItem).map(galleryImageItemToGalleryImage);+const getOrderedPreviewImages = (images: PreviewImage[],imageOrderDir: 'ASC' | 'DESC',@@ -330,7 +344,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {isFetchingNextPage: isFetchingNextBoardImagesPage,isFetchingPreviousPage: isFetchingPreviousBoardImagesPage,} = useInfiniteQuery({- ...galleryImagesInfiniteOptions(+ ...galleryItemsInfiniteOptions({boardId: navigationBoardId,createdFrom: shouldFollowLive ? undefined : selectedImageSearch.range?.from,@@ -349,7 +363,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const selectPreviewImage = useCallback((image: GeneratedImageContract) => {const pageIndex = boardImagesData?.pages.findIndex((page) =>- page.images.some((candidate) => candidate.imageName === image.imageName)+ page.items.some((candidate) => isGalleryImageItem(candidate) && candidate.name === image.imageName));const pageParam = pageIndex === undefined || pageIndex < 0 ? undefined : boardImagesData?.pageParams[pageIndex];const selectionPage =@@ -398,7 +412,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {return [selectedImage, ...localBoardImages];}, [localBoardImages, selectedImage, shouldFollowLive]);- const backendBoardImages = useMemo(() => flattenGalleryImagesData(boardImagesData), [boardImagesData]);+ const backendBoardImages = useMemo(() => flattenPreviewImages(boardImagesData), [boardImagesData]);const boardImages = useMemo(() =>!hasNavigationContext@@ -481,7 +495,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {return;}- const nextBackendBoardImages = flattenGalleryImagesData(result.data);+ const nextBackendBoardImages = flattenPreviewImages(result.data);const nextBoardImages = mergePreviewBoardImages(nextBackendBoardImages,previewLocalBoardImages,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 79e6c124f5..ec4e657251 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1,4 +1,4 @@-import type { GeneratedImageContract } from '@features/gallery';+import type { GalleryImageItem, GalleryVideoItem, GeneratedImageContract } from '@features/gallery';import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';import type {CanvasControlLayerContract,@@ -10,7 +10,7 @@ import type {import type { GraphContract } from '@workbench/graphContracts';import type { Project, WorkbenchState } from '@workbench/projectContracts';-import { GALLERY_RECENT_IMAGE_LIMIT } from '@features/gallery/contracts';+import { GALLERY_RECENT_IMAGE_LIMIT, legacyGeneratedImageToGalleryItem } from '@features/gallery/contracts';import { MAX_PROMPT_HISTORY } from '@features/generation/settings';import { describe, expect, it, vi } from 'vitest';@@ -202,6 +202,40 @@ const createImage = (imageName: string, sourceQueueItemId: string): GeneratedImawidth: 512,});+const createGalleryImageItem = (name: string, boardId = 'none'): GalleryImageItem => ({+ boardId,+ category: 'general',+ createdAt: '2026-07-30T00:00:00.000Z',+ fullUrl: `/api/v1/images/i/${name}/full`,+ height: 768,+ isIntermediate: false,+ kind: 'image',+ name,+ sourceQueueItemId: 'backend-gallery',+ starred: false,+ thumbnailUrl: `/api/v1/images/i/${name}/thumbnail`,+ width: 512,+});++const createGalleryVideoItem = (name: string, boardId = 'none'): GalleryVideoItem => ({+ ...createGalleryImageItem(name, boardId),+ durationSeconds: 3,+ fullUrl: `/api/v1/videos/i/${name}/full`,+ kind: 'video',+ thumbnailUrl: `/api/v1/videos/i/${name}/thumbnail`,+});++const galleryItemToRecentImage = (item: GalleryImageItem): GeneratedImageContract & { boardId: string } => ({+ boardId: item.boardId,+ height: item.height,+ imageName: item.name,+ imageUrl: item.fullUrl,+ queuedAt: item.createdAt,+ sourceQueueItemId: item.sourceQueueItemId ?? 'backend-gallery',+ thumbnailUrl: item.thumbnailUrl,+ width: item.width,+});+const createStagingCandidate = (imageName: string,sourceQueueItemId: string,@@ -1924,14 +1958,14 @@ describe('workbenchReducer Phase 5 generation flow', () => {const expectedImage = {...createImage('gallery-image.png', queueItem.id),boardId: 'none',- imageCategory: 'general',+ imageCategory: 'general' as const,starred: false,};expect(updatedProject.canvas.stagingArea.pendingImages).toEqual([]);expect(galleryValues.recentImages).toEqual([expectedImage]);- expect(galleryValues.selectedImage).toEqual(expectedImage);- expect(galleryValues.selectedImageName).toBe('gallery-image.png');+ expect(galleryValues.selectedImage).toEqual(legacyGeneratedImageToGalleryItem(expectedImage));+ expect(galleryValues.selectedImageName).toBe('image:gallery-image.png');});it('preserves the destination board on freshly routed Gallery results', () => {@@ -1953,7 +1987,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImage).toMatchObject({boardId: 'board-1',- imageName: image.imageName,+ kind: 'image',+ name: image.imageName,});});@@ -2016,8 +2051,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(recentImageNames).toEqual(Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) => `gallery-image-${999 - index}.png`));- expect(galleryValues.selectedImageName).toBe('gallery-image-999.png');- expect(galleryValues.selectedImageNames).toEqual(['gallery-image-999.png']);+ expect(galleryValues.selectedImageName).toBe('image:gallery-image-999.png');+ expect(galleryValues.selectedImageNames).toEqual(['image:gallery-image-999.png']);});it('omits transient recent images from immutable queue snapshots', () => {@@ -2148,7 +2183,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {});}- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('gallery-image-3.png');+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:gallery-image-3.png'+ );state = workbenchReducer(state, {images,@@ -2157,7 +2194,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {type: 'routeQueueItemResults',});- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('gallery-image-3.png');+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:gallery-image-3.png'+ );});it('does not reorder existing results when an older batch final aggregate arrives late', () => {@@ -2222,7 +2261,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {type: 'routeQueueItemResults',});- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('gallery-image-3.png');+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:gallery-image-3.png'+ );});it('pauses live-follow when the user selects a saved Gallery image', () => {@@ -2230,10 +2271,13 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(true);- state = workbenchReducer(state, { image: createImage('selected.png', 'gallery'), type: 'selectGalleryImage' });+ state = workbenchReducer(state, {+ item: createGalleryImageItem('selected.png'),+ type: 'selectGalleryItem',+ });expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('selected.png');+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');});it('preserves a manually selected image when later Gallery results arrive', () => {@@ -2243,8 +2287,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {const project = getActiveProject(state);const queueItem = project.queue.items[0];- const selectedImage = createImage('selected.png', 'backend-gallery');- state = workbenchReducer(state, { image: selectedImage, type: 'selectGalleryImage' });+ const selectedImage = createGalleryImageItem('selected.png');+ state = workbenchReducer(state, { item: selectedImage, type: 'selectGalleryItem' });state = workbenchReducer(state, {images: [createImage('completed.png', queueItem.id)],projectId: project.id,@@ -2252,17 +2296,17 @@ describe('workbenchReducer Phase 5 generation flow', () => {type: 'routeQueueItemResults',});- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(selectedImage.imageName);+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');});it('pauses live-follow for saved Gallery multi-selection and comparison intents', () => {- const primaryImage = createImage('primary.png', 'gallery');- const compareImage = createImage('compare.png', 'gallery');+ const primaryImage = createGalleryImageItem('primary.png');+ const compareImage = createGalleryImageItem('compare.png');let state = createInitialWorkbenchState();state = workbenchReducer(state, {- imageNames: [primaryImage.imageName, compareImage.imageName],- primaryImage,+ itemKeys: ['image:primary.png', 'image:compare.png'],+ primaryItem: primaryImage,type: 'setGalleryMultiSelection',});@@ -2292,11 +2336,13 @@ describe('workbenchReducer Phase 5 generation flow', () => {it('stores full selected gallery image data for Preview widget', () => {let state = createInitialWorkbenchState();- const image = createImage('backend-selected.png', 'backend-gallery');+ const image = createGalleryImageItem('backend-selected.png');- state = workbenchReducer(state, { image, type: 'selectGalleryImage' });+ state = workbenchReducer(state, { item: image, type: 'selectGalleryItem' });- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('backend-selected.png');+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:backend-selected.png'+ );expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImage).toEqual(image);});});@@ -2370,6 +2416,191 @@ describe('workbench backend connection recovery', () => {expect(state.backendConnection.lastConnectedAt).toBeDefined();});+ it('writes canonical mixed selections with ordered qualified keys and clears comparison for video', () => {+ const image = createGalleryImageItem('shared');+ const video = createGalleryVideoItem('shared');+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { image, type: 'setGalleryCompareImage' });+ state = workbenchReducer(state, { item: video, type: 'selectGalleryItem' });++ let values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values.selectedImage).toBe(video);+ expect(values.selectedImageName).toBe('video:shared');+ expect(values.selectedImageNames).toEqual(['video:shared']);+ expect(values.compareImage).toBeNull();++ state = workbenchReducer(state, { item: image, type: 'toggleGalleryItemInSelection' });+ values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values.selectedImage).toBe(image);+ expect(values.selectedImageName).toBe('image:shared');+ expect(values.selectedImageNames).toEqual(['video:shared', 'image:shared']);++ state = workbenchReducer(state, {+ itemKeys: ['image:shared', 'video:shared'],+ primaryItem: video,+ type: 'setGalleryMultiSelection',+ });+ values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values.selectedImage).toBe(video);+ expect(values.selectedImageName).toBe('video:shared');+ expect(values.selectedImageNames).toEqual(['image:shared', 'video:shared']);+ expect(values.compareImage).toBeNull();+ });++ it('prunes qualified items across projects without treating a same-name video as an image input', () => {+ const image = createGalleryImageItem('shared');+ const video = createGalleryVideoItem('shared');+ const recentImage = galleryItemToRecentImage(image);+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;++ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ state = workbenchReducer(state, {+ projectId: firstProjectId,+ type: 'patchWidgetValues',+ values: {+ compareImage: image,+ recentImages: [recentImage],+ selectedImage: image,+ selectedImageName: 'image:shared',+ selectedImageNames: ['image:shared'],+ },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, {+ projectId: secondProjectId,+ type: 'patchWidgetValues',+ values: {+ recentImages: [recentImage],+ selectedImage: video,+ selectedImageName: 'video:shared',+ selectedImageNames: ['video:shared'],+ },+ widgetId: 'gallery',+ });+ for (const projectId of [firstProjectId, secondProjectId]) {+ state = workbenchReducer(state, {+ projectId,+ type: 'patchWidgetValues',+ values: { inputImage: { height: image.height, image_name: image.name, width: image.width } },+ widgetId: 'upscale',+ });+ }++ state = workbenchReducer(state, {+ itemKeys: ['video:shared'],+ type: 'removeGalleryItems',+ });++ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'gallery')).toMatchObject({+ compareImage: image,+ recentImages: [recentImage],+ selectedImage: image,+ selectedImageName: 'image:shared',+ selectedImageNames: ['image:shared'],+ });+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'gallery')).toMatchObject({+ recentImages: [recentImage],+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });+ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'upscale').inputImage).not.toBeNull();+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'upscale').inputImage).not.toBeNull();++ state = workbenchReducer(state, {+ itemKeys: ['image:shared'],+ type: 'removeGalleryItems',+ });++ for (const projectId of [firstProjectId, secondProjectId]) {+ expect(getProjectWidgetValues(getProject(state, projectId), 'gallery').recentImages).toEqual([]);+ expect(getProjectWidgetValues(getProject(state, projectId), 'upscale').inputImage).toBeNull();+ }+ });++ it('reconciles authoritative board outcomes by deleting confirmed media and moving every survivor', () => {+ const boardId = 'deleted-board';+ const deletedImage = createGalleryImageItem('deleted-image', boardId);+ const failedImage = createGalleryImageItem('failed-image', boardId);+ const deletedVideo = createGalleryVideoItem('deleted-video', boardId);+ const failedVideo = createGalleryVideoItem('failed-video', boardId);+ let state = createInitialWorkbenchState();++ while (state.projects.length < 4) {+ state = workbenchReducer(state, { type: 'createProject' });+ }++ const fixtures = [+ {+ item: deletedImage,+ recentImages: [galleryItemToRecentImage(deletedImage)],+ },+ {+ item: failedImage,+ recentImages: [galleryItemToRecentImage(failedImage)],+ },+ { item: deletedVideo, recentImages: [] },+ { item: failedVideo, recentImages: [] },+ ] as const;++ for (const [index, project] of state.projects.entries()) {+ const fixture = fixtures[index]!;+ state = workbenchReducer(state, {+ projectId: project.id,+ type: 'patchWidgetValues',+ values: {+ projectBoardId: index === 0 ? boardId : null,+ recentImages: fixture.recentImages,+ selectedBoardId: boardId,+ selectedImage: fixture.item,+ selectedImageName: `${fixture.item.kind}:${fixture.item.name}`,+ selectedImageNames: [`${fixture.item.kind}:${fixture.item.name}`],+ },+ widgetId: 'gallery',+ });+ }++ state = workbenchReducer(state, {+ boardId,+ deletedImageNames: [deletedImage.name],+ deletedVideoNames: [deletedVideo.name],+ failedImageNames: [failedImage.name],+ failedVideoNames: [failedVideo.name],+ type: 'reconcileDeletedGalleryBoard',+ });++ const [deletedImageProject, failedImageProject, deletedVideoProject, failedVideoProject] = state.projects.map(+ (project) => getProjectWidgetValues(project, 'gallery')+ );++ expect(deletedImageProject).toMatchObject({+ projectBoardId: null,+ recentImages: [],+ selectedBoardId: 'none',+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });+ expect(failedImageProject?.selectedImage).toMatchObject({ boardId: 'none', kind: 'image', name: failedImage.name });+ expect(failedImageProject?.recentImages).toEqual([{ ...galleryItemToRecentImage(failedImage), boardId: 'none' }]);+ expect(deletedVideoProject).toMatchObject({+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });+ expect(failedVideoProject?.selectedImage).toMatchObject({ boardId: 'none', kind: 'video', name: failedVideo.name });++ for (const values of [failedImageProject, deletedVideoProject, failedVideoProject]) {+ expect(values?.selectedBoardId).toBe('none');+ }+ });+it('reconciles moved and starred metadata across every project recent-image overlay', () => {let state = createInitialWorkbenchState();const image = createImage('patched.png', 'backend-gallery');@@ -2385,16 +2616,17 @@ describe('workbench backend connection recovery', () => {}state = workbenchReducer(state, {changes: { boardId: 'board-2', starred: true },- imageNames: [image.imageName],- type: 'patchGalleryImages',+ itemKeys: [`image:${image.imageName}`],+ type: 'patchGalleryItems',});for (const project of state.projects) {const values = getProjectWidgetValues(project, 'gallery');+ const patchedImage = { ...image, boardId: 'board-2', starred: true };- expect(values.recentImages).toEqual([{ ...image, boardId: 'board-2', starred: true }]);- expect(values.selectedImage).toEqual({ ...image, boardId: 'board-2', starred: true });- expect(values.compareImage).toEqual({ ...image, boardId: 'board-2', starred: true });+ expect(values.recentImages).toEqual([patchedImage]);+ expect(values.selectedImage).toEqual(legacyGeneratedImageToGalleryItem(patchedImage));+ expect(values.compareImage).toEqual(legacyGeneratedImageToGalleryItem(patchedImage));}});@@ -2427,8 +2659,8 @@ describe('workbench backend connection recovery', () => {}state = workbenchReducer(state, {- imageNames: [image.imageName],- type: 'removeGalleryImages',+ itemKeys: [`image:${image.imageName}`],+ type: 'removeGalleryItems',});expect(getProjectWidgetValues(getProject(state, firstProjectId), 'gallery').recentImages).toEqual([]);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex ddb22a52e4..2b3d9fe4a0 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -43,8 +43,15 @@ import type {import {getBoundedRecentImages,getGallerySettings,+ getSelectedGalleryItemFromValues,+ legacyGeneratedImageToGalleryItem,normalizeGalleryImage,+ parseGalleryItemKey,+ toGalleryItemKey,type GalleryImage,+ type GalleryImageItem,+ type GalleryItem,+ type GalleryItemKey,type GallerySettings,type GeneratedImageContract,} from '@features/gallery/contracts';@@ -247,15 +254,15 @@ type WorkbenchReducerAction =| { type: 'routeQueueItemResults'; projectId: string; queueItemId: string; images: GeneratedImageContract[] }| { type: 'appendCanvasStagingCandidate'; projectId: string; candidate: CanvasStagingCandidateContract }| {- type: 'selectGalleryImage';- image: GeneratedImageContract;+ type: 'selectGalleryItem';+ item: GalleryItem;preserveNavigationQuery?: boolean;projectId?: string;selectionPage?: number;}- | { type: 'toggleGalleryImageInSelection'; image: GeneratedImageContract; projectId?: string }- | { type: 'setGalleryMultiSelection'; imageNames: string[]; primaryImage: GeneratedImageContract; projectId?: string }- | { type: 'setGalleryCompareImage'; image: GeneratedImageContract | null; projectId?: string }+ | { type: 'toggleGalleryItemInSelection'; item: GalleryItem; projectId?: string }+ | { type: 'setGalleryMultiSelection'; itemKeys: GalleryItemKey[]; primaryItem: GalleryItem; projectId?: string }+ | { type: 'setGalleryCompareImage'; image: GalleryImageItem | null; projectId?: string }| { type: 'selectGalleryBoard'; boardId: string; projectId?: string }| { type: 'setGalleryView'; galleryView: 'images' | 'assets'; projectId?: string }| { type: 'setGallerySearchTerm'; searchTerm: string; projectId?: string }@@ -263,12 +270,24 @@ type WorkbenchReducerAction =| { type: 'setGalleryPage'; page: number; projectId?: string }| { type: 'setGalleryPageInfo'; totalImages: number; projectId?: string }| {- type: 'patchGalleryImages';- changes: Partial<Pick<GalleryImage, 'boardId' | 'starred'>>;- imageNames: string[];+ type: 'patchGalleryItems';+ changes: Partial<Pick<GalleryItem, 'boardId' | 'starred'>>;+ itemKeys: GalleryItemKey[];}- | { type: 'removeGalleryImages'; imageNames: string[] }- | { type: 'reconcileDeletedGalleryBoard'; boardId: string; includeImages: boolean }+ | { type: 'removeGalleryItems'; itemKeys: GalleryItemKey[] }+ | {+ type: 'reconcileDeletedGalleryBoard';+ boardId: string;+ deletedImageNames: string[];+ deletedVideoNames: string[];+ failedImageNames: string[];+ failedVideoNames: string[];+ }+ /**+ * TODO(Task 7): Remove after board deletion returns and forwards the+ * authoritative per-kind outcome arrays.+ */+ | { type: 'reconcileDeletedGalleryBoardLegacy'; boardId: string; includeImages: boolean }| { type: 'setGalleryProjectBoardId'; boardId: string; projectId?: string }| {type: 'applyCanvasProjectMutation';@@ -690,14 +709,31 @@ const clampCanvasStagingSelection = (project: Project): Project => {const getGalleryImages = (values: Record<string, unknown>): GeneratedImageContract[] =>getBoundedRecentImages(values.recentImages);-const getGallerySelectedImageNames = (values: Record<string, unknown>): string[] => {+const canonicalizeGalleryItemKey = (key: string): GalleryItemKey => toGalleryItemKey(parseGalleryItemKey(key));++const getGallerySelectedItemKeys = (values: Record<string, unknown>): GalleryItemKey[] => {if (Array.isArray(values.selectedImageNames)) {- return (values.selectedImageNames as unknown[]).filter((name): name is string => typeof name === 'string');+ return (values.selectedImageNames as unknown[])+ .filter((name): name is string => typeof name === 'string')+ .map(canonicalizeGalleryItemKey);+ }++ if (typeof values.selectedImageName === 'string') {+ return [canonicalizeGalleryItemKey(values.selectedImageName)];}- return typeof values.selectedImageName === 'string' ? [values.selectedImageName] : [];+ const selectedItem = getSelectedGalleryItemFromValues(values);++ return selectedItem ? [toGalleryItemKey(selectedItem)] : [];};+const getGalleryItemFromPersistedValue = (values: Record<string, unknown>, value: unknown): GalleryItem | null =>+ getSelectedGalleryItemFromValues({+ selectedBoardId: values.selectedBoardId,+ selectedImage: value,+ selectedImageName: null,+ });+/*** Deep-clones an already-v2 canvas state and normalizes staging candidate placements. Not a* migration boundary: callers with genuinely unknown/legacy input must run@@ -1761,32 +1797,127 @@ const updateAllProjectGalleryValues = (return didChange ? { ...state, projects } : state;};-const removeGalleryImagesFromAllProjects = (+const patchGalleryItemsAcrossProjects = (+ state: WorkbenchState,+ itemKeys: ReadonlySet<GalleryItemKey>,+ changes: Partial<Pick<GalleryItem, 'boardId' | 'starred'>>+): WorkbenchState => {+ if (itemKeys.size === 0) {+ return state;+ }++ return updateAllProjectGalleryValues(state, (values) => {+ let didChange = false;+ const patchPersistedItem = (value: unknown, imageOnly = false): unknown => {+ const item = getGalleryItemFromPersistedValue(values, value);++ if (!item || (imageOnly && item.kind !== 'image') || !itemKeys.has(toGalleryItemKey(item))) {+ return value;+ }++ didChange = true;+ return { ...item, ...changes };+ };+ const recentImages = getGalleryImages(values).map((image) => {+ if (!itemKeys.has(toGalleryItemKey({ kind: 'image', name: image.imageName }))) {+ return image;+ }++ didChange = true;+ return { ...image, ...changes };+ });+ const selectedImage = patchPersistedItem(values.selectedImage);+ const compareImage = patchPersistedItem(values.compareImage, true);+ const selectedImageMoved = changes.boardId !== undefined && selectedImage !== values.selectedImage;+ const selectedImageQuery =+ selectedImageMoved && values.selectedImageQuery && typeof values.selectedImageQuery === 'object'+ ? {+ ...(values.selectedImageQuery as Record<string, unknown>),+ boardId: changes.boardId,+ page: 0,+ paginationMode: 'infinite',+ searchTerm: '',+ }+ : values.selectedImageQuery;++ return didChange+ ? {+ ...values,+ compareImage,+ recentImages,+ selectedImage,+ ...(selectedImageMoved ? { selectedImagePage: 0, selectedImageQuery } : {}),+ }+ : values;+ });+};++const getLocallyKnownGalleryItemsOnBoard = (+ state: WorkbenchState,+ boardId: string+): Map<GalleryItemKey, GalleryItem> => {+ const items = new Map<GalleryItemKey, GalleryItem>();++ for (const project of state.projects) {+ const values = getWidgetValues(project, 'gallery');+ const candidates: GalleryItem[] = [+ ...getGalleryImages(values).map((image) => legacyGeneratedImageToGalleryItem(image)),+ ...[values.selectedImage, values.compareImage].flatMap((value) => {+ const item = getGalleryItemFromPersistedValue(values, value);++ return item ? [item] : [];+ }),+ ];++ for (const item of candidates) {+ if (item.boardId === boardId) {+ items.set(toGalleryItemKey(item), item);+ }+ }+ }++ return items;+};++const removeGalleryItemsFromAllProjects = (state: WorkbenchState,- removedImageNames: ReadonlySet<string>+ removedItemKeys: ReadonlySet<GalleryItemKey>): WorkbenchState => {- if (removedImageNames.size === 0) {+ if (removedItemKeys.size === 0) {return state;}+ const removedImageNames = new Set(+ [...removedItemKeys].flatMap((key) => {+ const ref = parseGalleryItemKey(key);++ return ref.kind === 'image' ? [ref.name] : [];+ })+ );let didChange = false;const projects = state.projects.map((project) => {- const withoutGalleryImages = updateProjectWidgetValues(project, 'gallery', (values) => {- const selectedImage = values.selectedImage as GeneratedImageContract | null | undefined;- const compareImage = values.compareImage as GeneratedImageContract | null | undefined;+ const withoutGalleryItems = updateProjectWidgetValues(project, 'gallery', (values) => {+ const selectedImage = values.selectedImage;+ const compareImage = values.compareImage;const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;const recentImages = getGalleryImages(values);- const selectedImageNames = getGallerySelectedImageNames(values);- const nextRecentImages = recentImages.filter((image) => !removedImageNames.has(image.imageName));- const nextSelectedImageNames = selectedImageNames.filter((name) => !removedImageNames.has(name));- const nextSelectedImage = selectedImage && removedImageNames.has(selectedImage.imageName) ? null : selectedImage;- const nextCompareImage = compareImage && removedImageNames.has(compareImage.imageName) ? null : compareImage;- const nextSelectedImageName =- selectedImageName && removedImageNames.has(selectedImageName) ? null : selectedImageName;+ const selectedItemKeys = getGallerySelectedItemKeys(values);+ const selectedItem = getGalleryItemFromPersistedValue(values, selectedImage);+ const compareItem = getGalleryItemFromPersistedValue(values, compareImage);+ const selectedImageKey = selectedItem ? toGalleryItemKey(selectedItem) : null;+ const compareImageKey = compareItem ? toGalleryItemKey(compareItem) : null;+ const selectedNameKey = selectedImageName ? canonicalizeGalleryItemKey(selectedImageName) : null;+ const nextRecentImages = recentImages.filter(+ (image) => !removedItemKeys.has(toGalleryItemKey({ kind: 'image', name: image.imageName }))+ );+ const nextSelectedItemKeys = selectedItemKeys.filter((key) => !removedItemKeys.has(key));+ const nextSelectedImage = selectedImageKey && removedItemKeys.has(selectedImageKey) ? null : selectedImage;+ const nextCompareImage = compareImageKey && removedItemKeys.has(compareImageKey) ? null : compareImage;+ const nextSelectedImageName = selectedNameKey && removedItemKeys.has(selectedNameKey) ? null : selectedImageName;if (nextRecentImages.length === recentImages.length &&- nextSelectedImageNames.length === selectedImageNames.length &&+ nextSelectedItemKeys.length === selectedItemKeys.length &&nextSelectedImage === selectedImage &&nextCompareImage === compareImage &&nextSelectedImageName === selectedImageName@@ -1800,10 +1931,10 @@ const removeGalleryImagesFromAllProjects = (recentImages: nextRecentImages,selectedImage: nextSelectedImage,selectedImageName: nextSelectedImageName,- selectedImageNames: nextSelectedImageNames,+ selectedImageNames: nextSelectedItemKeys,};});- const withoutUpscaleInput = updateProjectWidgetValues(withoutGalleryImages, 'upscale', (rawValues) => {+ const withoutUpscaleInput = updateProjectWidgetValues(withoutGalleryItems, 'upscale', (rawValues) => {const values = normalizeUpscaleWidgetValues(rawValues);if (!values?.inputImage || !removedImageNames.has(values.inputImage.image_name)) {@@ -1820,6 +1951,55 @@ const removeGalleryImagesFromAllProjects = (return didChange ? { ...state, projects } : state;};+const reconcileDeletedGalleryBoard = (+ state: WorkbenchState,+ boardId: string,+ deletedItemKeys: ReadonlySet<GalleryItemKey>+): WorkbenchState => {+ const survivingItemKeys = new Set(+ [...getLocallyKnownGalleryItemsOnBoard(state, boardId).keys()].filter((key) => !deletedItemKeys.has(key))+ );+ const withoutDeletedItems = removeGalleryItemsFromAllProjects(state, deletedItemKeys);+ const withSurvivorsMoved = patchGalleryItemsAcrossProjects(withoutDeletedItems, survivingItemKeys, {+ boardId: 'none',+ });+ const withBoardReferencesCleared = updateAllProjectGalleryValues(withSurvivorsMoved, (values) => {+ const selectedBoardWasDeleted = values.selectedBoardId === boardId;+ const projectBoardWasDeleted = values.projectBoardId === boardId;++ if (!selectedBoardWasDeleted && !projectBoardWasDeleted) {+ return values;+ }++ return {+ ...values,+ ...(selectedBoardWasDeleted ? { galleryPage: 0, selectedBoardId: 'none' } : {}),+ ...(projectBoardWasDeleted ? { projectBoardId: null } : {}),+ };+ });+ let didChangeQueue = false;+ const projects = withBoardReferencesCleared.projects.map((project) => {+ let didChangeItems = false;+ const items = project.queue.items.map((item) => {+ if ((item.status !== 'pending' && item.status !== 'running') || item.snapshot.galleryBoardId !== boardId) {+ return item;+ }++ didChangeItems = true;+ return { ...item, snapshot: { ...item.snapshot, galleryBoardId: 'none' } };+ });++ if (!didChangeItems) {+ return project;+ }++ didChangeQueue = true;+ return { ...project, queue: { ...project.queue, items } };+ });++ return didChangeQueue ? { ...withBoardReferencesCleared, projects } : withBoardReferencesCleared;+};+const updateGalleryValuesAndPauseLiveFollow = (state: WorkbenchState,getValues: (values: Record<string, unknown>) => Record<string, unknown>,@@ -1915,14 +2095,16 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageCconst shouldSelectIncomingImage =project.settings.showProgressImagesInViewer || typeof galleryValues.selectedImageName !== 'string';const nextSelectedImage = shouldSelectIncomingImage ? newImages[0] : undefined;+ const nextSelectedItem = nextSelectedImage ? legacyGeneratedImageToGalleryItem(nextSelectedImage) : undefined;+ const nextSelectedItemKey = nextSelectedItem ? toGalleryItemKey(nextSelectedItem) : undefined;const gallerySettings = getGallerySettings(galleryValues);return updateProjectWidgetValues(project, 'gallery', () => ({...galleryValues,recentImages: getBoundedRecentImages([...newImages, ...previousImages]),- selectedImage: nextSelectedImage ?? galleryValues.selectedImage,- selectedImageName: nextSelectedImage?.imageName ?? galleryValues.selectedImageName,- selectedImageNames: nextSelectedImage ? [nextSelectedImage.imageName] : getGallerySelectedImageNames(galleryValues),+ selectedImage: nextSelectedItem ?? galleryValues.selectedImage,+ selectedImageName: nextSelectedItemKey ?? galleryValues.selectedImageName,+ selectedImageNames: nextSelectedItemKey ? [nextSelectedItemKey] : getGallerySelectedItemKeys(galleryValues),...(nextSelectedImage? {selectedImagePage: 0,@@ -2878,7 +3060,7 @@ export const __workbenchReducerInternal = (appendCanvasStagingCandidate(project, action.candidate));}- case 'selectGalleryImage': {+ case 'selectGalleryItem': {return updateGalleryValuesAndPauseLiveFollow(state,(values) => {@@ -2905,12 +3087,14 @@ export const __workbenchReducerInternal = (searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',starredFirst: settings.starredFirst,};+ const itemKey = toGalleryItemKey(action.item);return {...values,- selectedImage: action.image,- selectedImageName: action.image.imageName,- selectedImageNames: [action.image.imageName],+ ...(action.item.kind === 'video' ? { compareImage: null } : {}),+ selectedImage: action.item,+ selectedImageName: itemKey,+ selectedImageNames: [itemKey],selectedImagePage,selectedImageQuery,};@@ -2918,14 +3102,14 @@ export const __workbenchReducerInternal = (action.projectId);}- case 'toggleGalleryImageInSelection': {+ case 'toggleGalleryItemInSelection': {return updateGalleryValuesAndPauseLiveFollow(state,(values) => {- const imageName = action.image.imageName;- const selectedImageNames = getGallerySelectedImageNames(values);+ const itemKey = toGalleryItemKey(action.item);+ const selectedItemKeys = getGallerySelectedItemKeys(values);- if (!selectedImageNames.includes(imageName)) {+ if (!selectedItemKeys.includes(itemKey)) {const settings = getGallerySettings(values);const selectedImagePage =typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)@@ -2934,9 +3118,10 @@ export const __workbenchReducerInternal = (return {...values,- selectedImage: action.image,- selectedImageName: imageName,- selectedImageNames: [...selectedImageNames, imageName],+ ...(action.item.kind === 'video' ? { compareImage: null } : {}),+ selectedImage: action.item,+ selectedImageName: itemKey,+ selectedImageNames: [...selectedItemKeys, itemKey],selectedImagePage,selectedImageQuery: {boardId: typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none',@@ -2950,16 +3135,23 @@ export const __workbenchReducerInternal = (};}- const remainingImageNames = selectedImageNames.filter((name) => name !== imageName);- const wasPrimary = values.selectedImageName === imageName;+ const remainingItemKeys = selectedItemKeys.filter((key) => key !== itemKey);+ const selectedItem = getSelectedGalleryItemFromValues(values);+ const selectedItemKey =+ typeof values.selectedImageName === 'string'+ ? canonicalizeGalleryItemKey(values.selectedImageName)+ : selectedItem+ ? toGalleryItemKey(selectedItem)+ : null;+ const wasPrimary = selectedItemKey === itemKey;return {...values,selectedImage: wasPrimary ? null : values.selectedImage,selectedImageName: wasPrimary- ? (remainingImageNames[remainingImageNames.length - 1] ?? null)+ ? (remainingItemKeys[remainingItemKeys.length - 1] ?? null): values.selectedImageName,- selectedImageNames: remainingImageNames,+ selectedImageNames: remainingItemKeys,};},action.projectId@@ -2977,9 +3169,10 @@ export const __workbenchReducerInternal = (return {...values,- selectedImage: action.primaryImage,- selectedImageName: action.primaryImage.imageName,- selectedImageNames: action.imageNames,+ ...(action.primaryItem.kind === 'video' ? { compareImage: null } : {}),+ selectedImage: action.primaryItem,+ selectedImageName: toGalleryItemKey(action.primaryItem),+ selectedImageNames: action.itemKeys,selectedImagePage,selectedImageQuery: {boardId: typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none',@@ -3075,160 +3268,28 @@ export const __workbenchReducerInternal = (action.projectId);}- case 'patchGalleryImages': {- const imageNames = new Set(action.imageNames);-- return updateAllProjectGalleryValues(state, (values) => {- let didChange = false;- const patchImage = (value: unknown): unknown => {- if (- !value ||- typeof value !== 'object' ||- typeof (value as Partial<GeneratedImageContract>).imageName !== 'string' ||- !imageNames.has((value as GeneratedImageContract).imageName)- ) {- return value;- }-- didChange = true;- return { ...value, ...action.changes };- };- const recentImages = getGalleryImages(values).map(patchImage) as GeneratedImageContract[];- const selectedImage = patchImage(values.selectedImage);- const compareImage = patchImage(values.compareImage);- const selectedImageMoved = action.changes.boardId !== undefined && selectedImage !== values.selectedImage;- const selectedImageQuery =- selectedImageMoved && values.selectedImageQuery && typeof values.selectedImageQuery === 'object'- ? {- ...(values.selectedImageQuery as Record<string, unknown>),- boardId: action.changes.boardId,- page: 0,- paginationMode: 'infinite',- searchTerm: '',- }- : values.selectedImageQuery;-- return didChange- ? {- ...values,- compareImage,- recentImages,- selectedImage,- ...(selectedImageMoved ? { selectedImagePage: 0, selectedImageQuery } : {}),- }- : values;- });+ case 'patchGalleryItems': {+ return patchGalleryItemsAcrossProjects(state, new Set(action.itemKeys), action.changes);}- case 'removeGalleryImages': {- return removeGalleryImagesFromAllProjects(state, new Set(action.imageNames));+ case 'removeGalleryItems': {+ return removeGalleryItemsFromAllProjects(state, new Set(action.itemKeys));}case 'reconcileDeletedGalleryBoard': {- const imageNames = new Set<string>();-- for (const project of state.projects) {- const values = getWidgetValues(project, 'gallery');- const candidates = [- ...getGalleryImages(values),- values.selectedImage as GeneratedImageContract | null | undefined,- values.compareImage as GeneratedImageContract | null | undefined,- ];-- for (const candidate of candidates) {- if (- candidate &&- typeof candidate === 'object' &&- (candidate as Partial<GalleryImage>).boardId === action.boardId- ) {- imageNames.add(candidate.imageName);- }- }- }-- const reconciledState = action.includeImages- ? removeGalleryImagesFromAllProjects(state, imageNames)- : updateAllProjectGalleryValues(state, (values) => {- let didChange = false;- const patchBoard = (value: unknown): unknown => {- if (!value || typeof value !== 'object' || (value as Partial<GalleryImage>).boardId !== action.boardId) {- return value;- }+ const deletedItemKeys = new Set<GalleryItemKey>([+ ...action.deletedImageNames.map((name) => toGalleryItemKey({ kind: 'image', name })),+ ...action.deletedVideoNames.map((name) => toGalleryItemKey({ kind: 'video', name })),+ ]);- didChange = true;- return { ...value, boardId: 'none' };- };- const recentImages = getGalleryImages(values).map(patchBoard) as GeneratedImageContract[];- const selectedImage = patchBoard(values.selectedImage);- const compareImage = patchBoard(values.compareImage);- const selectedImageMoved = selectedImage !== values.selectedImage;-- return didChange- ? {- ...values,- compareImage,- recentImages,- selectedImage,- ...(selectedImageMoved- ? {- selectedImagePage: 0,- selectedImageQuery: {- ...(values.selectedImageQuery && typeof values.selectedImageQuery === 'object'- ? (values.selectedImageQuery as Record<string, unknown>)- : {}),- boardId: 'none',- page: 0,- paginationMode: 'infinite',- searchTerm: '',- },- }- : {}),- }- : values;- });-- const boardReferencesState = updateAllProjectGalleryValues(reconciledState, (values) => {- const selectedBoardWasDeleted = values.selectedBoardId === action.boardId;- const projectBoardWasDeleted = values.projectBoardId === action.boardId;-- if (!selectedBoardWasDeleted && !projectBoardWasDeleted) {- return values;- }-- return {- ...values,- ...(selectedBoardWasDeleted- ? {- galleryPage: 0,- selectedBoardId: 'none',- ...(action.includeImages ? { selectedImageNames: [] } : {}),- }- : {}),- ...(projectBoardWasDeleted ? { projectBoardId: null } : {}),- };- });- let didChangeQueue = false;- const projects = boardReferencesState.projects.map((project) => {- let didChangeItems = false;- const items = project.queue.items.map((item) => {- if (- (item.status !== 'pending' && item.status !== 'running') ||- item.snapshot.galleryBoardId !== action.boardId- ) {- return item;- }-- didChangeItems = true;- return { ...item, snapshot: { ...item.snapshot, galleryBoardId: 'none' } };- });-- if (!didChangeItems) {- return project;- }-- didChangeQueue = true;- return { ...project, queue: { ...project.queue, items } };- });+ // Failed and otherwise unconfirmed local items survive. The reconciler+ // moves every locally known key not confirmed deleted to Uncategorized.+ return reconcileDeletedGalleryBoard(state, action.boardId, deletedItemKeys);+ }+ case 'reconcileDeletedGalleryBoardLegacy': {+ const deletedItemKeys = action.includeImages+ ? new Set(getLocallyKnownGalleryItemsOnBoard(state, action.boardId).keys())+ : new Set<GalleryItemKey>();- return didChangeQueue ? { ...boardReferencesState, projects } : boardReferencesState;+ return reconcileDeletedGalleryBoard(state, action.boardId, deletedItemKeys);}case 'setGalleryProjectBoardId': {return updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }), action.projectId);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 1a56bad57d..5b3f21cfc6 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -1,6 +1,12 @@import type { ProjectGraphAction } from '@features/workflow/utility';import type { Project, WorkbenchState } from '@workbench/projectContracts';+import {+ legacyGeneratedImageToGalleryItem,+ toGalleryItemKey,+ type GalleryImage,+ type GeneratedImageContract,+} from '@features/gallery/contracts';import { createExternalStore } from '@platform/state/externalStore';import type { CanvasEditIntent } from './autoRoutePolicy';@@ -79,45 +85,122 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchStappendStagingCandidate: command('appendCanvasStagingCandidate'),},gallery: {- patchImages: command(- 'patchGalleryImages',- (imageNames: string[], changes: ActionPayload<'patchGalleryImages'>['changes']) => ({+ patchItems: command(+ 'patchGalleryItems',+ (+ itemKeys: ActionPayload<'patchGalleryItems'>['itemKeys'],+ changes: ActionPayload<'patchGalleryItems'>['changes']+ ) => ({changes,- imageNames,+ itemKeys,})),- removeImages: command('removeGalleryImages', (imageNames: string[]) => ({ imageNames })),- reconcileDeletedBoard: command('reconcileDeletedGalleryBoard', (boardId: string, includeImages: boolean) => ({- boardId,- includeImages,+ removeItems: command('removeGalleryItems', (itemKeys: ActionPayload<'removeGalleryItems'>['itemKeys']) => ({+ itemKeys,})),- selectBoard: command('selectGalleryBoard', (boardId: string, projectId?: string) => ({ boardId, projectId })),- selectImage: command(- 'selectGalleryImage',+ reconcileDeletedBoardOutcome: command(+ 'reconcileDeletedGalleryBoard',+ (boardId: string, outcome: Omit<ActionPayload<'reconcileDeletedGalleryBoard'>, 'boardId'>) => ({+ boardId,+ ...outcome,+ })+ ),+ /**+ * TODO(Task 7): Remove these image/boolean adapters when image actions+ * and board deletion dispatch confirmed mixed-media outcomes directly.+ */+ patchImages: (imageNames: string[], changes: ActionPayload<'patchGalleryItems'>['changes']): void =>+ dispatch({+ changes,+ itemKeys: imageNames.map((name) => toGalleryItemKey({ kind: 'image', name })),+ type: 'patchGalleryItems',+ }),+ removeImages: (imageNames: string[]): void =>+ dispatch({+ itemKeys: imageNames.map((name) => toGalleryItemKey({ kind: 'image', name })),+ type: 'removeGalleryItems',+ }),+ reconcileDeletedBoard: command(+ 'reconcileDeletedGalleryBoardLegacy',+ (boardId: string, includeImages: boolean) => ({+ boardId,+ includeImages,+ })+ ),+ selectItem: command(+ 'selectGalleryItem',(- image: ActionPayload<'selectGalleryImage'>['image'],+ item: ActionPayload<'selectGalleryItem'>['item'],projectId?: string,selectionPage?: number,preserveNavigationQuery?: boolean) => ({- image,+ item,preserveNavigationQuery,projectId,selectionPage,})),- setCompareImage: command(+ setCompareItem: command('setGalleryCompareImage',(image: ActionPayload<'setGalleryCompareImage'>['image'], projectId?: string) => ({ image, projectId })),- setMultiSelection: command(+ setItemMultiSelection: command('setGalleryMultiSelection',(- imageNames: string[],- primaryImage: ActionPayload<'setGalleryMultiSelection'>['primaryImage'],+ itemKeys: ActionPayload<'setGalleryMultiSelection'>['itemKeys'],+ primaryItem: ActionPayload<'setGalleryMultiSelection'>['primaryItem'],projectId?: string- ) => ({ imageNames, primaryImage, projectId })+ ) => ({ itemKeys, primaryItem, projectId })),+ toggleItemSelection: command(+ 'toggleGalleryItemInSelection',+ (item: ActionPayload<'toggleGalleryItemInSelection'>['item'], projectId?: string) => ({+ item,+ projectId,+ })+ ),+ /**+ * TODO(Task 6/8): Remove after Gallery Grid, Preview, and the image+ * command palette dispatch canonical items.+ */+ selectImage: (+ image: GeneratedImageContract & Partial<GalleryImage>,+ projectId?: string,+ selectionPage?: number,+ preserveNavigationQuery?: boolean+ ): void =>+ dispatch({+ item: legacyGeneratedImageToGalleryItem(image),+ preserveNavigationQuery,+ projectId,+ selectionPage,+ type: 'selectGalleryItem',+ }),+ setCompareImage: (image: (GeneratedImageContract & Partial<GalleryImage>) | null, projectId?: string): void =>+ dispatch({+ image: image ? legacyGeneratedImageToGalleryItem(image) : null,+ projectId,+ type: 'setGalleryCompareImage',+ }),+ setMultiSelection: (+ imageNames: string[],+ primaryImage: GeneratedImageContract & Partial<GalleryImage>,+ projectId?: string+ ): void =>+ dispatch({+ itemKeys: imageNames.map((name) => toGalleryItemKey({ kind: 'image', name })),+ primaryItem: legacyGeneratedImageToGalleryItem(primaryImage),+ projectId,+ type: 'setGalleryMultiSelection',+ }),+ toggleImageSelection: (image: GeneratedImageContract & Partial<GalleryImage>, projectId?: string): void =>+ dispatch({+ item: legacyGeneratedImageToGalleryItem(image),+ projectId,+ type: 'toggleGalleryItemInSelection',+ }),+ selectBoard: command('selectGalleryBoard', (boardId: string, projectId?: string) => ({ boardId, projectId })),setPage: command('setGalleryPage', (page: number, projectId?: string) => ({ page, projectId })),setPageInfo: command('setGalleryPageInfo', (totalImages: number, projectId?: string) => ({projectId,@@ -138,13 +221,6 @@ const createCommands = (dispatch: WorkbenchDispatch, getState: () => WorkbenchStprojectId,})),- toggleImageSelection: command(- 'toggleGalleryImageInSelection',- (image: ActionPayload<'toggleGalleryImageInSelection'>['image'], projectId?: string) => ({- image,- projectId,- })- ),updateSettings: command('updateGallerySettings',(settings: ActionPayload<'updateGallerySettings'>['settings'], projectId?: string) => ({