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 the window's anchor, not the row the cursor is on
Lincoln Stein7aef735aebb1
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 1f4baaffa6..e63da09ad5 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@@ -107,6 +107,7 @@ const mocks = vi.hoisted(() => {},},galleryItemPageOffsets: [] as number[],+ galleryItemWindowOffsets: [] as number[],galleryItemPages: [] as GalleryItemsPage[],imageActionOptions: null as null | {getItemActionContext?: () => {@@ -154,14 +155,19 @@ vi.mock('@features/gallery/queries', () => ({items: query.orderDir === 'ASC' ? items.reverse() : items,};});- const initialOffset = window.kind === 'infinite' ? 0 : (window.offset ?? 0);+ const initialOffset = window.offset ?? 0;const initialPage = pages[initialOffset / 60] ?? { items: [], total: 0 };+ mocks.galleryItemWindowOffsets.push(initialOffset);+return {getNextPageParam: (_lastPage: GalleryItemsPage, _allPages: GalleryItemsPage[], lastPageParam: number) =>pages[lastPageParam / 60 + 1] ? lastPageParam + 60 : undefined,getPreviousPageParam: (_firstPage: GalleryItemsPage, _allPages: GalleryItemsPage[], firstPageParam: number) =>- firstPageParam >= 60 ? firstPageParam - 60 : undefined,+ // An anchored infinite window cannot grow upward past its anchor.+ firstPageParam >= 60 && (window.kind !== 'infinite' || firstPageParam - 60 >= initialOffset)+ ? firstPageParam - 60+ : undefined,initialData: { pageParams: [initialOffset], pages: [initialPage] },initialPageParam: initialOffset,queryFn: ({ pageParam }: { pageParam: number }) => {@@ -267,19 +273,15 @@ const instance = { id: 'preview-instance', typeId: 'preview' } as unknown as Widlet host: HTMLDivElement | null = null;let root: Root | null = null;+let queryClient: QueryClient | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const render = async () => {- host = document.createElement('div');- host.style.cssText = 'height:320px;width:480px;';- document.body.append(host);- root = createRoot(host);-+const renderTree = async (client: QueryClient) => {await act(async () => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <QueryClientProvider client={new QueryClient()}>+ <QueryClientProvider client={client}><DndContext><PreviewWidgetView instance={instance} manifest={manifest} region="center" runtime={runtime} /></DndContext>@@ -291,6 +293,104 @@ const render = async () => {});};+const render = async () => {+ host = document.createElement('div');+ host.style.cssText = 'height:320px;width:480px;';+ document.body.append(host);+ root = createRoot(host);++ const client = new QueryClient();++ queryClient = client;+ await renderTree(client);+};++// Re-renders the mounted tree against the SAME query client, so cached pages+// survive exactly as they do in production and a window change has to earn+// its data. Widget values are read by identity, so callers hand the view a+// fresh values object rather than mutating in place.+const rerender = async () => {+ if (!queryClient) {+ throw new Error('Expected render() to have created a query client.');+ }++ await renderTree(queryClient);+};++const setGalleryValues = (patch: Record<string, unknown>) => {+ const state = mocks.project.widgetInstances.gallery.state as { values: Record<string, unknown> };++ state.values = { ...state.values, ...patch };+};++// Applies Preview's most recent selection to the gallery values the way the+// real reducer would — item, key, and the stamped page — and re-renders. The+// selection command is a mock, so without this a second arrow press would+// still start from the item the first one left.+const commitLastSelection = async () => {+ const lastCall = mocks.commands.gallery.selectItem.mock.lastCall as+ | [GalleryImageItem, unknown, number | undefined, boolean | undefined]+ | undefined;++ if (!lastCall) {+ throw new Error('Expected a selection to commit.');+ }++ const [item, , selectionPage] = lastCall;+ const state = mocks.project.widgetInstances.gallery.state as { values: Record<string, unknown> };+ const selectedImageQuery = (state.values.selectedImageQuery ?? {}) as Record<string, unknown>;++ setGalleryValues({+ selectedImage: {+ boardId: item.boardId,+ height: item.height,+ imageName: item.name,+ imageUrl: item.fullUrl,+ queuedAt: item.createdAt,+ sourceQueueItemId: item.sourceQueueItemId,+ thumbnailUrl: item.thumbnailUrl,+ width: item.width,+ },+ selectedImageName: item.name,+ selectedImageQuery: { ...selectedImageQuery, page: selectionPage ?? selectedImageQuery.page },+ });+ await rerender();+};++const deepQuery = {+ boardId: 'none',+ galleryView: 'images',+ imageOrderDir: 'DESC',+ page: 30,+ paginationMode: 'infinite',+ searchTerm: '',+};++const legacyImage = (name: string, queuedAt: string, sourceQueueItemId = `queue-${name}`) => ({+ boardId: 'none',+ height: 64,+ imageName: name,+ imageUrl: `/images/${name}/full`,+ queuedAt,+ sourceQueueItemId,+ thumbnailUrl: `/images/${name}/thumbnail`,+ width: 64,+});++// A board whose page 30 holds `deep` (newest first) and whose page 31 holds+// `next`; every other page is empty. Enough to anchor a window at row 1800+// and to have a boundary to cross.+const deepBoardPages = (deep: GalleryImageItem[], next: GalleryImageItem[] = []) =>+ Array.from({ length: 32 }, (_unused, index) => {+ if (index === 30) {+ return { items: deep, total: deep.length + next.length };+ }++ return index === 31+ ? { items: next, total: deep.length + next.length }+ : { items: [], total: deep.length + next.length };+ });+const getBoundary = (): HTMLElement => {const boundary = host?.querySelector<HTMLElement>('[tabindex="0"]');@@ -329,6 +429,7 @@ beforeEach(() => {};mocks.project.widgetInstances.gallery.state.values.selectedImageName = 'newest';mocks.galleryItemPageOffsets.length = 0;+ mocks.galleryItemWindowOffsets.length = 0;mocks.imageActionOptions = null;mocks.galleryItemPages = [{@@ -436,6 +537,215 @@ describe('preview keyboard navigation boundary', () => {);});+ it('keeps settled recents out of an infinite window anchored at a deep reveal', async () => {+ // A deep reveal anchors Preview's window ~1800 rows down the board. Recents+ // belong at the TOP of the listing: date-sorting them into a slice from+ // the middle puts images in Preview that the grid is not showing, and+ // stepping onto one files it under a board page it is nowhere near.+ 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();+ // Descending: Right steps deeper into the anchored slice...+ await pressArrow('ArrowRight');+ // ...and Left, off the top of it, must not find the recent above it.+ await pressArrow('ArrowLeft');++ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledTimes(1);+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'image', name: 'deep-older' }),+ undefined,+ 30,+ true+ );+ });++ it('keeps recents out of a deep window whose stamp outlives a switch to paginated mode', async () => {+ // The live setting says paginated while the stamp still describes the deep+ // infinite window Preview is querying. The window is what the list is made+ // of, so it is what the exclusion follows.+ 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,+ paginationMode: 'paginated',+ 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();+ await pressArrow('ArrowRight');+ await pressArrow('ArrowLeft');++ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledTimes(1);+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'image', name: 'deep-older' }),+ undefined,+ 30,+ true+ );+ });++ it('stamps the top of the listing on an in-flight image a deep window does not hold', async () => {+ // In-flight work still merges into a deep window, and the window has no+ // page for it. The page the preview opened on is 30 board pages from+ // where the image will land, so it must not be what gets stamped.+ mocks.project.queue.items = [queueItem];+ setGalleryValues({+ galleryPage: 0,+ recentImages: [legacyImage('in-flight', '2026-07-23T00:00:00.000Z', 'queue-item-live')],+ 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')]);++ await render();+ await pressArrow('ArrowLeft');++ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'image', name: 'in-flight' }),+ undefined,+ 0,+ true+ );+ });++ it('stamps the top of the listing when the compare image is swapped in', async () => {+ // The compare slot holds an arbitrary image the window may not contain.+ // Reusing the deep page filed a top-of-board image under row 1800, and+ // Preview then queried a slice its own selection was not in.+ 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')]);++ await render();++ const swap = registeredCommands.get('viewer.swapImages');++ expect(swap).toBeDefined();+ await act(async () => {+ swap?.();+ await Promise.resolve();+ });++ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'image', name: 'compare-top' }),+ undefined,+ 0,+ true+ );+ });++ it('holds a deep window still while the cursor walks across a page boundary and back', async () => {+ // An anchored infinite window is one-way: it cannot grow upward past its+ // anchor. So the anchor must stay where the selection was made, and every+ // step — including one that lands on a page the boundary fetch has just+ // added — stamps THAT anchor, not the row it landed on. Stamping the row+ // re-keys the window at each boundary, discards the old entry, and makes+ // everything the user just walked through unreachable.+ const deepA = createImageItem('deep-a', '2026-07-20T00:00:04.000Z');+ const deepB = createImageItem('deep-b', '2026-07-20T00:00:03.000Z');+ const deepC = createImageItem('deep-c', '2026-07-20T00:00:02.000Z');+ const deepD = createImageItem('deep-d', '2026-07-20T00:00:01.000Z');++ setGalleryValues({+ galleryPage: 0,+ recentImages: [],+ selectedImage: legacyImage('deep-b', '2026-07-20T00:00:03.000Z'),+ selectedImageName: 'deep-b',+ selectedImageQuery: deepQuery,+ });+ mocks.galleryItemPages = deepBoardPages([deepA, deepB], [deepC, deepD]);++ await render();+ // Across the boundary: the fetch adds page 31, and the item selected out+ // of it is still stamped with the window's anchor.+ await pressArrow('ArrowRight');+ await commitLastSelection();+ // One more step inside the new page.+ await pressArrow('ArrowRight');+ await commitLastSelection();+ // And back, twice: the second press crosses the boundary in the direction+ // the window cannot grow, and must find page 30 still loaded.+ await pressArrow('ArrowLeft');+ await commitLastSelection();+ await pressArrow('ArrowLeft');++ const selected = mocks.commands.gallery.selectItem.mock.calls.map(([item, , page]) => [+ (item as { name: string }).name,+ page,+ ]);++ expect(selected).toEqual([+ ['deep-c', 30],+ ['deep-d', 30],+ ['deep-c', 30],+ ['deep-b', 30],+ ]);+ expect(mocks.galleryItemWindowOffsets).not.toContain(1860);+ expect(mocks.galleryItemWindowOffsets).not.toContain(0);+ });++ it('moves to the top of the listing when a selection is made there from outside Preview', async () => {+ // Board, view, order, mode and search are unchanged, so the query identity+ // is the same. A grid click on the newest image stamps the grid's page, 0,+ // and Preview must follow it — held sticky, the anchor kept querying rows+ // 1800+ for a selection at row 0.+ const topNewer = createImageItem('top-newer', '2026-07-22T00:00:02.000Z');+ const topOlder = createImageItem('top-older', '2026-07-22T00:00:01.000Z');++ setGalleryValues({+ 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: [topNewer, topOlder], total: 3 };++ await render();++ expect(mocks.galleryItemWindowOffsets).toContain(1800);++ mocks.galleryItemWindowOffsets.length = 0;+ setGalleryValues({+ selectedImage: legacyImage('top-newer', '2026-07-22T00:00:02.000Z'),+ selectedImageName: 'top-newer',+ selectedImageQuery: { ...deepQuery, page: 0 },+ });+ await rerender();+ await pressArrow('ArrowRight');++ expect(mocks.galleryItemWindowOffsets).not.toContain(1800);+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'image', name: 'top-older' }),+ undefined,+ 0,+ 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/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 083ac4249b..7252eb90ea 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -217,7 +217,38 @@ export const usePreviewNavigation = ({setNavigationAnchor({ page: selectedImageQuery.page, queryKey: navigationQueryKey });}- const navigationAnchorPage = hasStaleNavigationAnchor ? selectedImageQuery.page : navigationAnchor.page;+ // Stickiness is a PAGINATED concern: stepping across pages stamps each+ // item's own page, and the window must not move out from under the cursor+ // when it does. An infinite anchor is read live. Preview's own steps never+ // rewrite it — they stamp the window's anchor, see selectPreviewItem — so+ // the only thing that changes it is a selection made elsewhere: a grid+ // click, a reveal, a result arriving under live-follow. Each of those names+ // the window that holds the new selection, and Preview has to move to it.+ // Held sticky, the anchor outlived every one of them: a click on the newest+ // image at the top of the board left Preview walking rows 1800+ for a+ // selection at row 0.+ const navigationAnchorPage =+ selectedImageQuery.paginationMode === 'paginated'+ ? hasStaleNavigationAnchor+ ? selectedImageQuery.page+ : navigationAnchor.page+ : selectedImageQuery.page;+ const isPaginatedWindow = !shouldFollowLive && selectedImageQuery.paginationMode === 'paginated';+ // A selection deeper than the base window's reach (a deep reveal from the+ // image map) anchors navigation at its own page — walking from offset 0+ // could never arrive at the cursor. Such a window is a slice from the+ // middle of the board, and it is one-way by design: it cannot grow upward+ // past its anchor, because the grid shares the cache entry and rows spliced+ // in above its viewport would shift the content under the user. So the+ // anchor must stay where the selection was made, and the exclusions below+ // that hinge on "is this window mid-board?" are all derived from it.+ const deepAnchorOffset =+ !shouldFollowLive &&+ !isPaginatedWindow &&+ navigationSemanticQuery === null &&+ navigationAnchorPage * GALLERY_PAGE_SIZE >= GALLERY_MAX_ROWS+ ? navigationAnchorPage * GALLERY_PAGE_SIZE+ : 0;// A ranked list mirrors the GRID's paging instead of the stamped context.// The stamped page indexes the board listing, and a board page applied to a@@ -235,16 +266,7 @@ export const usePreviewNavigation = ({({ kind: 'infinite', offset: galleryPage * GALLERY_PAGE_SIZE } as const): selectedImageQuery.paginationMode === 'paginated'? ({ kind: 'anchor', offset: navigationAnchorPage * GALLERY_PAGE_SIZE } as const)- : ({- kind: 'infinite',- // A selection deeper than the base window's reach (a deep reveal- // from the image map) anchors navigation at its own page —- // walking from offset 0 could never arrive at the cursor.- offset:- navigationAnchorPage * GALLERY_PAGE_SIZE >= GALLERY_MAX_ROWS- ? navigationAnchorPage * GALLERY_PAGE_SIZE- : 0,- } as const);+ : ({ kind: 'infinite', offset: deepAnchorOffset } as const);const {data: boardItemsData,@@ -273,13 +295,13 @@ export const usePreviewNavigation = ({enabled: hasNavigationContext,});- const selectPreviewItem = useCallback(- (item: GalleryItem) => {+ const stampSelection = useCallback(+ (item: GalleryItem, data: typeof boardItemsData) => {const itemKey = toGalleryItemKey(item);- const pageIndex = boardItemsData?.pages.findIndex((page) =>+ const pageIndex = data?.pages.findIndex((page) =>page.items.some((candidate) => toGalleryItemKey(candidate) === itemKey));- const pageParam = pageIndex === undefined || pageIndex < 0 ? undefined : boardItemsData?.pageParams[pageIndex];+ const pageParam = pageIndex === undefined || pageIndex < 0 ? undefined : data?.pageParams[pageIndex];// `page` is stamped as a BOARD page and read as one everywhere else, so// a ranked window's page params — offsets into the ranking — must not be// written into it. Neither may the grid's own page: in paginated mode@@ -290,16 +312,41 @@ export const usePreviewNavigation = ({// holds in both modes is the top of the listing: setting a search and// clearing it both reset the grid to page 0, so that is the board// context a ranked session hands back.+ //+ // In an INFINITE window the page is the anchor of the window that holds+ // the item, which is what a grid click stamps too (the grid's own page,+ // whatever row was clicked). Stamping the item's row instead rolls the+ // window forward with the cursor: the anchor is read live, so each step+ // past a page boundary re-keys the query at the new row, the old entry+ // is discarded, and — a deep window being one-way — everything the user+ // just walked through is unreachable. An item the window does not hold+ // 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- : typeof pageParam === 'number'- ? Math.floor(pageParam / GALLERY_PAGE_SIZE)- : selectedImageQuery.page;+ : 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);},- [boardItemsData, navigationSemanticQuery, selectGalleryItem, selectedImageQuery.page]+ [+ deepAnchorOffset,+ navigationSemanticQuery,+ selectGalleryItem,+ selectedImageQuery.page,+ selectedImageQuery.paginationMode,+ ]+ );+ const selectPreviewItem = useCallback(+ (item: GalleryItem) => stampSelection(item, boardItemsData),+ [boardItemsData, stampSelection]);const optimisticQueueItemIds = useMemo(@@ -314,15 +361,16 @@ export const usePreviewNavigation = ({// row"; dropping a completed batch during that window made arrow keys skip// the images just generated. So local items stay unconditionally, except// where the backend window is a *subset* of the board and dedupe cannot- // help: an active search (backend-filtered, local items are not) and- // paginated mode (the window anchors mid-board, so settled recents would- // splice in permanently). There, only in-flight work and the selection- // merge.+ // help: an active search (backend-filtered, local items are not), and any+ // window anchored mid-board — paginated, or the infinite window a deep+ // reveal anchors — where settled recents would splice in permanently.+ // Recents belong at the TOP of the listing, so a window nowhere near the+ // top is not theirs to join; the grid draws the same line for its own+ // window. There, only in-flight work and the selection merge.const hasActiveSearch =!shouldFollowLive && (selectedImageSearch.text.trim() !== '' || selectedImageSearch.range !== undefined);- const isPaginatedWindow = !shouldFollowLive && selectedImageQuery.paginationMode === 'paginated';- if (!hasActiveSearch && !isPaginatedWindow) {+ if (!hasActiveSearch && !isPaginatedWindow && deepAnchorOffset === 0) {return localItems;}@@ -337,10 +385,11 @@ export const usePreviewNavigation = ({item.sourceQueueItemId === refreshingSelectedSourceId);}, [+ deepAnchorOffset,isFetchingBoardItems,+ isPaginatedWindow,localItems,optimisticQueueItemIds,- selectedImageQuery.paginationMode,selectedImageSearch,selectedItem,shouldFollowLive,@@ -474,7 +523,10 @@ export const usePreviewNavigation = ({const nextTarget = getPreviewNavigationTarget(nextNavigationSequence, nextNavigationCursor, offset);if (nextTarget?.kind === 'item') {- selectPreviewItem(nextTarget.item);+ // Against the data just fetched: the item is not in the pages this+ // render closed over, and a lookup there would read it as an item+ // the window does not hold.+ stampSelection(nextTarget.item, result.data);} else if (nextTarget?.kind === 'placeholder') {enableLiveFollow();}@@ -502,6 +554,7 @@ export const usePreviewNavigation = ({selectedItemKey,selectPreviewItem,shouldFollowLive,+ stampSelection,]);