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
fix(preview): stamp a host's selections with the host's own page
Lincoln Stein11963423bbf1
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex deb754ede8..320be3cdd4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -19,6 +19,15 @@ export interface GalleryItemActions {export interface GalleryItemActionContext {filterIdentity: string;+ /**+ * The page a selection of `item` should be stamped with, when the host+ * navigates from a window of its own. A selection made without one is+ * stamped with the gallery grid's page, which names the grid's window; a+ * host walking a different window — Preview anchored deep in a board the+ * grid shows from the top — would have its selection filed outside the+ * window it came from, with nowhere for the arrow keys to go.+ */+ getItemSelectionPage?(item: GalleryItem): number;items: GalleryItem[];loadOrderedRefs(signal: AbortSignal): Promise<GalleryItemRef[]>;selectedItemKey: GalleryItemKey | null;diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsxindex 30979852f7..a13626b57b 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx@@ -165,6 +165,7 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;const actionsRef = createRef<ImageActions>();interface ItemActionContext {+ getItemSelectionPage?: (item: GalleryItem) => number;filterIdentity: string;items: GalleryItem[];loadOrderedRefs(): Promise<GalleryItemRef[]>;@@ -1013,6 +1014,72 @@ describe('primary successor after confirmed deletion', () => {expect(mocks.gallerySelectItem).not.toHaveBeenCalled();});+ it('stamps the successor with the page the host navigates from, when the host provides one', async () => {+ // The successor comes from the host's own list. Preview anchored deep in a+ // board the grid shows from the top would otherwise have it stamped with+ // the grid's page, outside the window it came from.+ const before = galleryItem('video', 'before.mp4');+ const primary = galleryItem('image', 'primary.png');+ const after = galleryItem('image', 'after.png');+ const refs = [before, primary, after].map(({ kind, name }) => ({ kind, name }));+ currentItemActionContext = {+ filterIdentity: 'filter-a',+ getItemSelectionPage: () => 30,+ items: [before, primary, after],+ loadOrderedRefs: () => Promise.resolve(refs),+ selectedItemKey: 'image:primary.png',+ };+ mocks.itemDelete.mockResolvedValue({+ affectedBoardIds: ['board-1'],+ failed: [],+ succeeded: [{ kind: 'image', name: 'primary.png' }],+ });++ await act(async () => {+ await getItemActions().deleteItems([{ kind: 'image', name: 'primary.png' }]);+ });++ expect(mocks.gallerySelectItem).toHaveBeenCalledWith(before, 'project-1', 30, true);+ });++ it('carries the host page into a retained multi-selection after a partial failure', async () => {+ const successor = galleryItem('image', 'successor.png');+ const primary = galleryItem('image', 'primary.png');+ const failedImage = galleryItem('image', 'failed.png');+ const requested = [+ { kind: 'image' as const, name: failedImage.name },+ { kind: 'image' as const, name: primary.name },+ ];+ currentItemActionContext = {+ filterIdentity: 'filter-a',+ getItemSelectionPage: () => 30,+ items: [successor, primary, failedImage],+ loadOrderedRefs: () =>+ Promise.resolve([+ { kind: 'image' as const, name: successor.name },+ { kind: 'image' as const, name: primary.name },+ { kind: 'image' as const, name: failedImage.name },+ ]),+ selectedItemKey: 'image:primary.png',+ };+ mocks.itemDelete.mockResolvedValue({+ affectedBoardIds: ['board-1'],+ failed: [requested[0]],+ succeeded: [requested[1]],+ });++ await act(async () => {+ await getItemActions().deleteItems(requested);+ });++ expect(mocks.gallerySetItemMultiSelection).toHaveBeenCalledWith(+ ['image:failed.png', 'image:successor.png'],+ successor,+ 'project-1',+ 30+ );+ });+it('atomically retains failed qualified selections while promoting a surviving successor', async () => {const successor = galleryItem('image', 'successor.png');const primary = galleryItem('image', 'shared');diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex ae6ef2d7e2..23aa127332 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -420,11 +420,23 @@ export const useImageActions = ({const retainedFailedKeys = items.filter((item) => failedKeys.has(toGalleryItemKey(item))).map(toGalleryItemKey);+ // The successor was chosen from the host's own list, so it is+ // stamped the way the host would stamp it — in the window it+ // came from, not the grid's.+ const selectionPage = deletionContext?.getItemSelectionPage?.(successor);if (retainedFailedKeys.length > 0) {- gallery.setItemMultiSelection([...retainedFailedKeys, toGalleryItemKey(successor)], successor, projectId);- } else {+ const itemKeys = [...retainedFailedKeys, toGalleryItemKey(successor)];++ if (selectionPage === undefined) {+ gallery.setItemMultiSelection(itemKeys, successor, projectId);+ } else {+ gallery.setItemMultiSelection(itemKeys, successor, projectId, selectionPage);+ }+ } else if (selectionPage === undefined) {gallery.selectItem(successor, projectId);+ } else {+ gallery.selectItem(successor, projectId, selectionPage, true);}}onImagesDeleted?.(result.succeeded.filter((item) => item.kind === 'image').map((item) => item.name));@@ -766,7 +778,13 @@ export const useImageActions = ({window.open(item.fullUrl, '_blank', 'noopener');},openItemInPreview: (item) => {- gallery.selectItem(item, projectId);+ const selectionPage = getItemActionContext?.()?.getItemSelectionPage?.(item);++ if (selectionPage === undefined) {+ gallery.selectItem(item, projectId);+ } else {+ gallery.selectItem(item, projectId, selectionPage, true);+ }openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });},setItemsStarred,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 e63da09ad5..c4526342a1 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@@ -111,6 +111,7 @@ const mocks = vi.hoisted(() => {galleryItemPages: [] as GalleryItemsPage[],imageActionOptions: null as null | {getItemActionContext?: () => {+ getItemSelectionPage?: (item: GalleryImageItem | GalleryVideoItem) => number;items: Array<GalleryImageItem | GalleryVideoItem>;loadOrderedRefs: (signal: AbortSignal) => Promise<Array<{ kind: 'image' | 'video'; name: string }>>;selectedItemKey: string | null;@@ -746,6 +747,79 @@ describe('preview keyboard navigation boundary', () => {);});+ it('hands image actions a page that keeps a deletion successor in the deep window', async () => {+ // A successor is chosen from Preview's own list. Selected without a page+ // it is stamped with the GRID's page — 0 once a result has landed on the+ // board or the project was reloaded — and lands outside the window it+ // came from: forward arrow dead, back arrow a 1800-row teleport.+ const deepNewer = createImageItem('deep-newer', '2026-07-20T00:00:02.000Z');+ const deepOlder = createImageItem('deep-older', '2026-07-20T00:00:01.000Z');++ setGalleryValues({+ galleryPage: 0,+ recentImages: [legacyImage('fresh-generation', '2026-07-23T00:00:00.000Z', 'queue-item-done')],+ selectedImage: legacyImage('deep-newer', '2026-07-20T00:00:02.000Z'),+ selectedImageName: 'deep-newer',+ selectedImageQuery: deepQuery,+ });+ mocks.galleryItemPages = deepBoardPages([deepNewer, deepOlder]);++ await render();++ const context = mocks.imageActionOptions?.getItemActionContext?.();++ expect(context?.getItemSelectionPage?.(deepOlder)).toBe(30);+ // A recent is not in the window; it lives at the top of the listing.+ expect(context?.getItemSelectionPage?.(createImageItem('fresh-generation', '2026-07-23T00:00:00.000Z'))).toBe(0);+ });++ it('swaps the compare image in and back out without losing the deep window', async () => {+ // Swapping a top-of-board image in moves the window to the top, and the+ // deep image goes into the compare slot. Swapping back must return to the+ // window that image was navigated in, not guess at one.+ setGalleryValues({+ compareImage: legacyImage('compare-top', '2026-07-24T00:00:00.000Z'),+ galleryPage: 0,+ recentImages: [],+ selectedImage: legacyImage('deep-newer', '2026-07-20T00:00:02.000Z'),+ selectedImageName: 'deep-newer',+ selectedImageQuery: deepQuery,+ });+ mocks.galleryItemPages = deepBoardPages([createImageItem('deep-newer', '2026-07-20T00:00:02.000Z')]);+ mocks.galleryItemPages[0] = { items: [createImageItem('compare-top', '2026-07-24T00:00:00.000Z')], total: 2 };++ await render();++ const swap = () =>+ act(async () => {+ registeredCommands.get('viewer.swapImages')?.();+ await Promise.resolve();+ });++ await swap();++ expect(mocks.commands.gallery.selectItem).toHaveBeenLastCalledWith(+ expect.objectContaining({ kind: 'image', name: 'compare-top' }),+ undefined,+ 0,+ true+ );++ // Commit the swap as the reducer would: the top image is selected at page+ // 0, and the deep image is now in the compare slot.+ await commitLastSelection();+ setGalleryValues({ compareImage: legacyImage('deep-newer', '2026-07-20T00:00:02.000Z') });+ await rerender();+ await swap();++ expect(mocks.commands.gallery.selectItem).toHaveBeenLastCalledWith(+ expect.objectContaining({ kind: 'image', name: 'deep-newer' }),+ undefined,+ 30,+ true+ );+ });+it('fetches the next infinite page before stepping past the loaded backend boundary', async () => {const newest: GalleryImage = {...mocks.recentImages[0],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 74df494db8..30cb102045 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -266,6 +266,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {);const {boardItems,+ getSelectionPage,handleNavigationKeyDown,isLoadingBoard,navigate,@@ -294,6 +295,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const getItemActionContext = useCallback(() => ({filterIdentity: navigationQueryKey,+ getItemSelectionPage: getSelectionPage,items: boardItems,loadOrderedRefs: (signal: AbortSignal) => {signal.throwIfAborted();@@ -301,7 +303,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {},selectedItemKey,}),- [boardItems, navigationQueryKey, selectedItemKey]+ [boardItems, getSelectionPage, navigationQueryKey, selectedItemKey]);const projectId = useActiveProjectId();const { dialog: deletionConfirmationDialog, requestDeletionConfirmation } = useDeletionConfirmation();@@ -325,12 +327,27 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {[contextMenuItem]);const exitCompare = useCallback(() => gallery.setCompareItem(null), [gallery]);+ // The page the item now in the compare slot was selected at, when Preview+ // put it there by swapping. The window may not hold that item any more —+ // swapping a top-of-board image in moves the window to the top — so a swap+ // back could only guess at its page. This is not a guess: it is the window+ // the item was navigated in, and restoring it puts the arrows back where+ // they were before the first swap.+ const swappedOutRef = useRef<{ key: GalleryItemKey; page: number } | null>(null);const swapCompareImages = useCallback(() => {if (selectedItem?.kind === 'image' && compareImage) {- selectPreviewItem(legacyGeneratedImageToGalleryItem(compareImage));+ const compareItem = legacyGeneratedImageToGalleryItem(compareImage);+ const swappedOut = swappedOutRef.current;++ swappedOutRef.current = { key: toGalleryItemKey(selectedItem), page: selectedImageQuery.page };+ if (swappedOut && swappedOut.key === toGalleryItemKey(compareItem)) {+ selectGalleryItemAtPage(compareItem, swappedOut.page);+ } else {+ selectPreviewItem(compareItem);+ }gallery.setCompareItem(selectedItem);}- }, [compareImage, gallery, selectPreviewItem, selectedItem]);+ }, [compareImage, gallery, selectGalleryItemAtPage, selectPreviewItem, selectedImageQuery.page, selectedItem]);const isItemCurrent = useCallback((itemKey: GalleryItemKey) => {const currentValues = getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');@@ -491,8 +508,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {}if (commandId === 'viewer.swapImages' && selectedItem?.kind === 'image' && compareImage) {- selectPreviewItem(legacyGeneratedImageToGalleryItem(compareImage));- gallery.setCompareItem(selectedItem);+ swapCompareImages();return;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 7252eb90ea..9abb760cde 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -128,6 +128,8 @@ export interface PreviewNavigationState {/** Identity of the backing query — the action context's filter identity. */navigationQueryKey: string;navigationSequence: PreviewNavigationItem<GalleryItem>[];+ /** The page a selection of `item` is stamped with — see the action context's `getItemSelectionPage`. */+ getSelectionPage: (item: GalleryItem) => number;selectPreviewItem: (item: GalleryItem) => void;}@@ -295,8 +297,8 @@ export const usePreviewNavigation = ({enabled: hasNavigationContext,});- const stampSelection = useCallback(- (item: GalleryItem, data: typeof boardItemsData) => {+ const getSelectionPageIn = useCallback(+ (item: GalleryItem, data: typeof boardItemsData): number => {const itemKey = toGalleryItemKey(item);const pageIndex = data?.pages.findIndex((page) =>page.items.some((candidate) => toGalleryItemKey(candidate) === itemKey)@@ -323,26 +325,25 @@ export const usePreviewNavigation = ({// at all (a recent the listing has not caught up with, the compare// slot's image) is stamped at the top: that is where a recent lives,// and the base window's reach is the best guess for anything else.- const selectionPage =- navigationSemanticQuery !== null- ? 0- : selectedImageQuery.paginationMode === 'paginated'- ? typeof pageParam === 'number'- ? Math.floor(pageParam / GALLERY_PAGE_SIZE)- : selectedImageQuery.page- : typeof pageParam === 'number'- ? deepAnchorOffset / GALLERY_PAGE_SIZE- : 0;-- selectGalleryItem(item, selectionPage);+ return navigationSemanticQuery !== null+ ? 0+ : selectedImageQuery.paginationMode === 'paginated'+ ? typeof pageParam === 'number'+ ? Math.floor(pageParam / GALLERY_PAGE_SIZE)+ : selectedImageQuery.page+ : typeof pageParam === 'number'+ ? deepAnchorOffset / GALLERY_PAGE_SIZE+ : 0;},- [- deepAnchorOffset,- navigationSemanticQuery,- selectGalleryItem,- selectedImageQuery.page,- selectedImageQuery.paginationMode,- ]+ [deepAnchorOffset, navigationSemanticQuery, selectedImageQuery.page, selectedImageQuery.paginationMode]+ );+ const stampSelection = useCallback(+ (item: GalleryItem, data: typeof boardItemsData) => selectGalleryItem(item, getSelectionPageIn(item, data)),+ [getSelectionPageIn, selectGalleryItem]+ );+ const getSelectionPage = useCallback(+ (item: GalleryItem) => getSelectionPageIn(item, boardItemsData),+ [boardItemsData, getSelectionPageIn]);const selectPreviewItem = useCallback((item: GalleryItem) => stampSelection(item, boardItemsData),@@ -606,6 +607,7 @@ export const usePreviewNavigation = ({navigationCursor,navigationQueryKey,navigationSequence,+ getSelectionPage,selectPreviewItem,};};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex b1b856b317..db8a2c83a4 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -3507,6 +3507,33 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');});+ it('stamps an explicit page into the navigation query already on a multi-selection', () => {+ // A host navigating its own window passes the page that keeps the primary+ // item in that window — the same contract as selectGalleryItem with+ // preserveNavigationQuery — rather than the grid's page.+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { page: 0, type: 'setGalleryPage' });+ state = workbenchReducer(state, {+ item: createGalleryImageItem('deep.png'),+ preserveNavigationQuery: false,+ selectionPage: 30,+ type: 'selectGalleryItem',+ });+ state = workbenchReducer(state, {+ itemKeys: ['image:failed.png', 'image:successor.png'],+ primaryItem: createGalleryImageItem('successor.png'),+ selectionPage: 30,+ type: 'setGalleryMultiSelection',+ });++ const values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values.selectedImagePage).toBe(30);+ expect((values.selectedImageQuery as { page: number }).page).toBe(30);+ expect(values.galleryPage).toBe(0);+ });+it('pauses live-follow for saved Gallery multi-selection and comparison intents', () => {const primaryImage = createGalleryImageItem('primary.png');const compareImage = createGalleryImageItem('compare.png');diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex c71841d158..f818a65bb5 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -333,7 +333,14 @@ type WorkbenchReducerAction =nextPrimaryItem: GalleryItem | null;projectId?: string;}- | { type: 'setGalleryMultiSelection'; itemKeys: GalleryItemKey[]; primaryItem: GalleryItem; projectId?: string }+ | {+ type: 'setGalleryMultiSelection';+ itemKeys: GalleryItemKey[];+ primaryItem: GalleryItem;+ projectId?: string;+ /** Stamps this page, in the navigation query already on the selection, instead of the grid's. */+ selectionPage?: number;+ }| { type: 'setGalleryCompareImage'; image: GalleryImageItem | null; projectId?: string }| { type: 'selectGalleryBoard'; boardId: string; projectId?: string }| { type: 'setGalleryView'; galleryView: 'images' | 'assets'; projectId?: string }@@ -4434,10 +4441,16 @@ export const __workbenchReducerInternal = (state,(values) => {const settings = getGallerySettings(values);- const selectedImagePage =- typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)+ const hasSelectionPage = typeof action.selectionPage === 'number' && Number.isFinite(action.selectionPage);+ const selectedImagePage = hasSelectionPage+ ? Math.max(0, Math.floor(action.selectionPage as number))+ : typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)? Math.max(0, Math.floor(values.galleryPage)): 0;+ const existingNavigationQuery =+ values.selectedImageQuery && typeof values.selectedImageQuery === 'object'+ ? (values.selectedImageQuery as Record<string, unknown>)+ : null;return {...values,@@ -4446,14 +4459,20 @@ export const __workbenchReducerInternal = (selectedImageName: toGalleryItemKey(action.primaryItem),selectedImageNames: action.itemKeys,selectedImagePage,- selectedImageQuery: {- boardId: typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none',- galleryView: values.galleryView === 'assets' ? 'assets' : 'images',- imageOrderDir: settings.imageOrderDir,- page: selectedImagePage,- paginationMode: settings.paginationMode,- searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',- },+ // An explicit page comes from a host navigating its own window, and+ // names a page of the query already on the selection — the same+ // contract as `selectGalleryItem` with `preserveNavigationQuery`.+ selectedImageQuery:+ hasSelectionPage && existingNavigationQuery+ ? { ...existingNavigationQuery, page: selectedImagePage }+ : {+ boardId: typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none',+ galleryView: values.galleryView === 'assets' ? 'assets' : 'images',+ imageOrderDir: settings.imageOrderDir,+ page: selectedImagePage,+ paginationMode: settings.paginationMode,+ searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',+ },};},action.projectIddiff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex fcbc42c9fb..503f328bf6 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -178,8 +178,9 @@ const createCommands = ((itemKeys: ActionPayload<'setGalleryMultiSelection'>['itemKeys'],primaryItem: ActionPayload<'setGalleryMultiSelection'>['primaryItem'],- projectId?: string- ) => ({ itemKeys, primaryItem, projectId })+ projectId?: string,+ selectionPage?: number+ ) => ({ itemKeys, primaryItem, projectId, selectionPage })),toggleItemSelection: command('toggleGalleryItemInSelection',