Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(gallery): anchored infinite windows so deep reveals can land

Lincoln Stein40e5c29b9255
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
index e799cc748a..f948726f0c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
@@ -237,6 +237,42 @@ describe('Gallery item query read model', () => {
});
});
+ it('anchors an infinite window at its offset, sharing the base key only at offset 0', async () => {
+ // A zero-offset window must keep the historical key so every existing
+ // consumer shares one cache entry; a deep window (a reveal past the base
+ // reach) is its own transient entry starting at its own page.
+ expect(galleryItemsInfiniteOptions(baseFilter, { kind: 'infinite', offset: 0 }).queryKey).toEqual(
+ galleryItemsInfiniteOptions(baseFilter).queryKey
+ );
+ expect(galleryItemsInfiniteOptions(baseFilter, { kind: 'infinite', offset: 6000 }).queryKey).not.toEqual(
+ galleryItemsInfiniteOptions(baseFilter).queryKey
+ );
+
+ const queryClient = createQueryClient();
+ backend.listGalleryItems.mockImplementation(({ offset }: { offset: number }) =>
+ Promise.resolve(createPage({ offset, total: 20_000 }))
+ );
+ const options = galleryItemsInfiniteOptions(baseFilter, { kind: 'infinite', offset: 6000 });
+ const observer = new InfiniteQueryObserver(queryClient, options);
+
+ try {
+ await observer.refetch();
+ expect(observer.getCurrentResult().data?.pageParams).toEqual([6000]);
+
+ // The GALLERY_MAX_ROWS reach applies from the anchor, not from 0.
+ for (let fetches = 0; fetches < 12; fetches += 1) {
+ await observer.fetchNextPage();
+ }
+
+ const pageParams = observer.getCurrentResult().data?.pageParams ?? [];
+
+ expect(pageParams[0]).toBe(6000);
+ expect(pageParams[pageParams.length - 1]).toBe(6000 + GALLERY_MAX_ROWS - GALLERY_PAGE_SIZE);
+ } finally {
+ observer.destroy();
+ }
+ });
+
it('does not create item-list cache entries for repeated invalidation events', async () => {
const queryClient = createQueryClient();
backend.listGalleryItems.mockResolvedValue(createPage({ count: 1, offset: 0, total: 1 }));
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
index 77f3cb04b2..67690a2fda 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
@@ -75,7 +75,14 @@ export interface CanonicalGalleryItemsFilter {
starredFirst: boolean;
}
-export type GalleryItemsWindow = { kind: 'anchor'; offset: number } | { kind: 'infinite' };
+/**
+ * An infinite window can start below the top of the listing: `offset` (a row
+ * offset, normalized to a page multiple, default 0) anchors where the window
+ * begins, and the `GALLERY_MAX_ROWS` reach applies from there. This is what
+ * lets a reveal land the gallery on an image deeper than the base window
+ * could ever load — every board/search/view change resets the anchor to 0.
+ */
+export type GalleryItemsWindow = { kind: 'anchor'; offset: number } | { kind: 'infinite'; offset?: number };
interface GalleryAccountKey {
accountId: string | null;
@@ -90,7 +97,7 @@ type GalleryItemsInfiniteQueryKey = readonly [
CanonicalGalleryItemsFilter,
];
-type GalleryItemsAnchorQueryKey = readonly [...GalleryItemsInfiniteQueryKey, 'anchor', number];
+type GalleryItemsAnchorQueryKey = readonly [...GalleryItemsInfiniteQueryKey, 'anchor' | 'infinite', number];
export type GalleryItemsListQueryKey = GalleryItemsAnchorQueryKey | GalleryItemsInfiniteQueryKey;
@@ -144,8 +151,19 @@ const getAccountKey = (owner: AccountScope): GalleryAccountKey => ({
const normalizePageOffset = (offset: number): number =>
Math.max(0, Math.floor(offset / GALLERY_PAGE_SIZE) * GALLERY_PAGE_SIZE);
-const getWindowKey = (window: GalleryItemsWindow): readonly [] | readonly ['anchor', number] =>
- window.kind === 'infinite' ? [] : ([window.kind, normalizePageOffset(window.offset)] as const);
+const getWindowKey = (
+ window: GalleryItemsWindow
+): readonly [] | readonly ['anchor', number] | readonly ['infinite', number] => {
+ if (window.kind === 'infinite') {
+ const offset = normalizePageOffset(window.offset ?? 0);
+
+ // A zero offset keeps the historical key shape, so every existing
+ // consumer of the base window shares one cache entry with it.
+ return offset === 0 ? [] : (['infinite', offset] as const);
+ }
+
+ return [window.kind, normalizePageOffset(window.offset)] as const;
+};
export const galleryKeys = {
all: ['gallery'] as const,
@@ -302,7 +320,8 @@ const getNextPageParam = (
lastPageParam: number
): number | undefined => {
const nextOffset = lastPageParam + GALLERY_PAGE_SIZE;
- const isInsideWindow = window.kind === 'anchor' || nextOffset < GALLERY_MAX_ROWS;
+ const isInsideWindow =
+ window.kind === 'anchor' || nextOffset < normalizePageOffset(window.offset ?? 0) + GALLERY_MAX_ROWS;
return isInsideWindow && nextOffset < lastPage.total ? nextOffset : undefined;
};
@@ -314,8 +333,11 @@ export const galleryItemsInfiniteOptions = (
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;
+ window.kind === 'infinite'
+ ? ({ kind: 'infinite', offset: normalizePageOffset(window.offset ?? 0) } as const)
+ : ({ ...window, offset: normalizePageOffset(window.offset) } as const);
+ const initialPageParam = normalizedWindow.offset;
+ const isBaseInfiniteWindow = normalizedWindow.kind === 'infinite' && normalizedWindow.offset === 0;
return infiniteQueryOptions<
GalleryItemsPage,
@@ -324,7 +346,9 @@ export const galleryItemsInfiniteOptions = (
GalleryItemsListQueryKey,
number
>({
- ...(normalizedWindow.kind === 'infinite' ? {} : { gcTime: 0 }),
+ // Anchored windows (paginated pages and deep infinite reveals) are
+ // transient views; only the base window's cache is worth keeping around.
+ ...(isBaseInfiniteWindow ? {} : { gcTime: 0 }),
getNextPageParam: (lastPage, allPages, lastPageParam) =>
allPages.length >= GALLERY_MAX_INFINITE_PAGES
? undefined
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
index 9ce935c642..97c628a19c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
@@ -367,7 +367,9 @@ const runGalleryInvalidation = async (
}
const anchorOffset =
- query.queryKey[5] === 'anchor' && typeof query.queryKey[6] === 'number' ? query.queryKey[6] : 0;
+ (query.queryKey[5] === 'anchor' || query.queryKey[5] === 'infinite') && typeof query.queryKey[6] === 'number'
+ ? query.queryKey[6]
+ : 0;
const anchorIndex = Math.max(0, data.pageParams.indexOf(anchorOffset));
client.setQueryData<InfiniteData<GalleryItemsPage, number>>(query.queryKey, {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
index 84a0e62315..fbcb2d8a4c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -414,8 +414,16 @@ export const getGalleryStateView = (
// pending placeholders (which stand in for images-to-come) are hidden while
// a semantic query is active — exactly as they are for a text search.
const semanticImageQuery = getGallerySemanticImageQuery(values);
+ // Placeholders stand in for images that will land at the TOP of the board's
+ // listing. An infinite window anchored mid-board (a deep reveal) shows a
+ // slice nowhere near the top, so they are hidden there too.
+ const isAnchoredInfiniteWindow = settings.paginationMode === 'infinite' && getGalleryPage(values) > 0;
const visibleActivePlaceholder =
- settings.showPendingItems && galleryView === 'images' && searchTerm.trim() === '' && semanticImageQuery === null
+ settings.showPendingItems &&
+ galleryView === 'images' &&
+ searchTerm.trim() === '' &&
+ semanticImageQuery === null &&
+ !isAnchoredInfiniteWindow
? generationSequence.liveSlot?.boardId === selectedBoardId
? generationSequence.liveSlot
: null
@@ -435,7 +443,7 @@ export const getGalleryStateView = (
items,
isLoading,
pendingPlaceholders:
- settings.showPendingItems && semanticImageQuery === null
+ settings.showPendingItems && semanticImageQuery === null && !isAnchoredInfiniteWindow
? getVisibleGalleryQueuePlaceholders(generationSequence.chronologicalSlots, {
galleryView,
imageOrderDir: settings.imageOrderDir,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
index 7ac5d695d8..f06abada1d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
@@ -188,7 +188,13 @@ export const useGalleryData = ({
} = useInfiniteQuery(
galleryItemsInfiniteOptions(
filter,
- isPaginated ? { kind: 'anchor', offset: page * GALLERY_PAGE_SIZE } : { kind: 'infinite' }
+ // In infinite mode `page` anchors where the window starts — 0 in normal
+ // browsing (every board/search/view change resets it). A reveal to an
+ // image deeper than the base window's reach sets it, so the grid can
+ // show that part of the listing at all.
+ isPaginated
+ ? { kind: 'anchor', offset: page * GALLERY_PAGE_SIZE }
+ : { kind: 'infinite', offset: page * GALLERY_PAGE_SIZE }
)
);
const backendItems = useMemo(() => {
@@ -201,7 +207,10 @@ export const useGalleryData = ({
return pageIndex === -1 ? [] : (queryData?.pages[pageIndex]?.items ?? []).slice(0, GALLERY_PAGE_SIZE);
}, [isPaginated, page, queryData]);
- const shouldOverlayRecentItems = !isPaginated;
+ // Recents belong at the top of the listing; overlaying them onto a window
+ // anchored mid-board would sort them into a part of the list they are
+ // nowhere near.
+ const shouldOverlayRecentItems = !isPaginated && page === 0;
const maxRows = isPaginated ? GALLERY_PAGE_SIZE : GALLERY_MAX_ROWS;
const items = useMemo(
() =>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
index 3170333827..84aefff3fc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
@@ -273,10 +273,10 @@ describe('useMapSelection', () => {
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
});
- it('does not fetch past the infinite window cap', async () => {
- // The infinite window cannot reach beyond GALLERY_MAX_ROWS, so loading
- // pages toward an unreachable image would only burn requests. The
- // selection itself still lands (Preview follows it).
+ it('anchors the infinite window at the page of an image past the base reach', async () => {
+ // The base infinite window cannot load beyond GALLERY_MAX_ROWS, so a
+ // deeper image is revealed by anchoring the window at its page instead
+ // of loading toward it; the mounted gallery query fetches on its own.
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite', starredFirst: true };
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 700));
@@ -285,7 +285,9 @@ describe('useMapSelection', () => {
await flush(() => handle.click?.('deep.png'));
expect(mocks.fetchInfiniteQuery).not.toHaveBeenCalled();
+ expect(mocks.setPage).toHaveBeenCalledWith(11);
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
+ expect(mocks.selectItem.mock.calls[0]?.[2]).toBe(11);
});
it('drops the page landing when the ordering settings changed mid-lookup', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
index 3c8b0d88aa..cd95840c8e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
@@ -189,17 +189,20 @@ export const useMapSelection = (): MapSelectionActions => {
commands.gallery.setPage(page);
}
- if (
- boardIndex !== null &&
- page !== null &&
- settingsNow.paginationMode === 'infinite' &&
- boardIndex < GALLERY_MAX_ROWS
- ) {
- // Load every page down to the image so the grid can scroll to it;
- // past the window cap the grid cannot reach it either way. Fire
- // and forget: the selection must not wait on page hydration, and
- // the grid's pending reveal settles whenever the item appears.
- void ensureGalleryPagesLoaded(queryClient, listingFilter, page + 1).catch(() => {});
+ if (boardIndex !== null && page !== null && settingsNow.paginationMode === 'infinite') {
+ if (boardIndex < GALLERY_MAX_ROWS) {
+ // Within the base window's reach: load every page down to the
+ // image so the grid can scroll to it. Fire and forget — the
+ // selection must not wait on page hydration, and the grid's
+ // pending reveal settles whenever the item appears.
+ void ensureGalleryPagesLoaded(queryClient, listingFilter, page + 1).catch(() => {});
+ } else {
+ // Deeper than the base window can ever load: anchor the
+ // infinite window at the image's page instead (the mounted
+ // gallery query fetches it on its own). Any board, search, or
+ // view change resets the anchor back to the top.
+ commands.gallery.setPage(page);
+ }
}
commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image), undefined, page ?? undefined);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts
index aa610f3669..6a5109b1ab 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts
@@ -209,7 +209,16 @@ export const usePreviewNavigation = ({
},
!shouldFollowLive && selectedImageQuery.paginationMode === 'paginated'
? { kind: 'anchor', offset: navigationAnchorPage * GALLERY_PAGE_SIZE }
- : { kind: 'infinite' }
+ : {
+ 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:
+ !shouldFollowLive && navigationAnchorPage * GALLERY_PAGE_SIZE >= GALLERY_MAX_ROWS
+ ? navigationAnchorPage * GALLERY_PAGE_SIZE
+ : 0,
+ }
),
enabled: hasNavigationContext,
});