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.

fix(gallery): suspend stale recent cutoffs

Josh Corbette00c3d312a63
diff --git a/invokeai/frontend/webv2/src/features/gallery/README.md b/invokeai/frontend/webv2/src/features/gallery/README.md
index 68b2d961d1..0cd4324bd5 100644
--- a/invokeai/frontend/webv2/src/features/gallery/README.md
+++ b/invokeai/frontend/webv2/src/features/gallery/README.md
@@ -2,7 +2,7 @@
Paths are relative to the webv2 `src/` directory.
-Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, Preview, and deep-reveal flows. The Gallery widget's media kind (both, images, or videos) is part of the canonical listing filter, present only when restricted; the picker always lists both kinds. Page key = account lifetime + canonical listing filters + aligned absolute offset; each result keeps its authoritative total and absolute item positions so hydrated gaps never compact. Consumers own separate visible ranges and scroll anchors. Cold numbered page after page zero first requests count-only metadata, then reads only its clamped 60-item page; virtual scrolling discovers count from its first item page. Recent local completions use a temporary overlay, with listing-scoped membership evidence bounded by recent-item limit so an authoritative item does not reappear in overlay when its page is evicted. Sparse viewports render that overlay as rows apart from backend slots, beside the listing's newest end (leading rows in DESC, trailing in ASC), and cannot interleave it, so they overlay only recents created after the listing's newest item. That cut comes from the subscribed page holding the newest end (page zero in DESC, the last page in ASC) and is kept for the listing after that page leaves the view; until that page first loads, nothing is overlaid. Loaded pages elsewhere cannot set it, since newer items may sit in pages not yet read. Paginated mode never overlays recents. An older recent (such as an existing image a workflow echoed) belongs inside the backend listing range, not ahead of it; the listing places it, or the post-run gallery refresh does once its board attach lands. Query layer retains at most ten inactive idle pages per listing while protecting observed pages, and schedules at most four distinct page reads per QueryClient. Deep reveal resolves an item's filtered listing rank, reads its containing page, verifies item at returned absolute position, and retries that rank/page check at most once if offsets shifted. Persisted Preview selection keeps listing identity, media kind included, from when item was selected (a stamp without a media kind lists both); changing active Gallery filters does not rewrite that cursor. While a search is active, the Gallery's `searchScope` setting can widen the listing from the selected board to `ALL_READABLE_BOARDS_ID` (`all`): the caller's own unboarded items plus every non-archived board they may read, as the backend's `board_id=all` defines it. Only the listing's board id changes (`getGalleryListingBoardId`); the selected board, the auto-add board and upload destinations stay put, uploads are refused while it applies, and a selection made in it is stamped `all`, so Preview steps through the search's results. Clearing the search returns the scope to `board`. Preview re-resolves a stale item page after listing mutations; its async navigation is fenced by captured account epoch so a late page cannot stamp selection into a newer account lifetime.
+Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, Preview, and deep-reveal flows. The Gallery widget's media kind (both, images, or videos) is part of the canonical listing filter, present only when restricted; the picker always lists both kinds. Page key = account lifetime + canonical listing filters + aligned absolute offset; each result keeps its authoritative total and absolute item positions so hydrated gaps never compact. Consumers own separate visible ranges and scroll anchors. Cold numbered page after page zero first requests count-only metadata, then reads only its clamped 60-item page; virtual scrolling discovers count from its first item page. Recent local completions use a temporary overlay, with listing-scoped membership evidence bounded by recent-item limit so an authoritative item does not reappear in overlay when its page is evicted. Sparse viewports render that overlay as rows apart from backend slots, beside the listing's newest end (leading rows in DESC, trailing in ASC), and cannot interleave it, so they overlay only recents created after the listing's newest item. That cut comes from the cached page holding the newest end (page zero in DESC, the last page in ASC) and survives that page leaving the view while its cache entry stays valid. A narrow cache subscription does not keep the page observed or trigger extra reads. Invalidation, eviction, or a failed refresh suspends the overlay until the newest-end page loads successfully again; until it first loads, nothing is overlaid. The page lifecycle retains evidence of successful backend reads separately from Query status because optimistic patches and their rollbacks are manual successes; they cannot end an invalidation or failed-refresh suspension. Returning to the suspended newest-end page requests a fresh read even if a manual patch reset Query's freshness clock. Loaded pages elsewhere cannot set it, since newer items may sit in pages not yet read. Paginated mode never overlays recents. An older recent (such as an existing image a workflow echoed) belongs inside the backend listing range, not ahead of it; the listing places it, or the post-run gallery refresh does once its board attach lands. Query layer retains at most ten inactive idle pages per listing while protecting observed pages, and schedules at most four distinct page reads per QueryClient. Deep reveal resolves an item's filtered listing rank, reads its containing page, verifies item at returned absolute position, and retries that rank/page check at most once if offsets shifted. Persisted Preview selection keeps listing identity, media kind included, from when item was selected (a stamp without a media kind lists both); changing active Gallery filters does not rewrite that cursor. While a search is active, the Gallery's `searchScope` setting can widen the listing from the selected board to `ALL_READABLE_BOARDS_ID` (`all`): the caller's own unboarded items plus every non-archived board they may read, as the backend's `board_id=all` defines it. Only the listing's board id changes (`getGalleryListingBoardId`); the selected board, the auto-add board and upload destinations stay put, uploads are refused while it applies, and a selection made in it is stamped `all`, so Preview steps through the search's results. Clearing the search returns the scope to `board`. Preview re-resolves a stale item page after listing mutations; its async navigation is fenced by captured account epoch so a late page cannot stamp selection into a newer account lifetime.
## Realtime refresh and external reveal
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 33db5fa434..19650bc639 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts
@@ -2,7 +2,7 @@ import type { GalleryItem, GalleryItemsPage } from '@features/gallery/core/items
import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';
import { AccountScopeExpiredError, accountLifecycle } from '@platform/state/accountLifecycle';
-import { InfiniteQueryObserver, QueryClient, QueryObserver, type InfiniteData } from '@tanstack/react-query';
+import { hashKey, InfiniteQueryObserver, QueryClient, QueryObserver, type InfiniteData } from '@tanstack/react-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const backend = vi.hoisted(() => ({
@@ -31,6 +31,8 @@ import {
galleryItemsInfiniteOptions,
galleryStarredStripOptions,
getGalleryItemListQueries,
+ getFreshGalleryItemsPage,
+ isGalleryItemsPageAwaitingRefresh,
IMAGE_INDEX_UNAVAILABLE_POLL_MS,
imageIndexAvailabilityOptions,
getGalleryItemsFilterFromKey,
@@ -38,7 +40,7 @@ import {
canonicalizeGalleryItemsFilter,
type GalleryItemsFilter,
} from './queries';
-import { invalidateGalleryItems } from './queryCache';
+import { invalidateGalleryItems, patchGalleryItemCaches } from './queryCache';
const OFFSETS = Array.from({ length: 10 }, (_, index) => index * GALLERY_PAGE_SIZE);
@@ -124,6 +126,72 @@ describe('Gallery item query read model', () => {
expect(backend.listGalleryDateBoards).toHaveBeenCalledOnce();
});
+ it.each(['invalidation', 'failed refresh'] as const)(
+ 'requires a successful page read after %s despite patches, rollback, and cancellation',
+ async (suspension) => {
+ const client = createQueryClient();
+ const options = galleryItemsPageOptions(baseFilter, 0);
+ const queryHash = hashKey(options.queryKey);
+ const page = createPage({ count: 2, offset: 0, total: 2 });
+ backend.listGalleryItems.mockResolvedValue(page);
+ client.setQueryData(options.queryKey, page);
+ expect(getFreshGalleryItemsPage(client, queryHash)).toBeUndefined();
+ expect(isGalleryItemsPageAwaitingRefresh(client, queryHash)).toBe(false);
+ await client.fetchQuery({ ...options, staleTime: 0 });
+ const observer = new QueryObserver(client, options);
+ const unsubscribe = observer.subscribe(() => undefined);
+ const readFreshPage = () => getFreshGalleryItemsPage(client, queryHash);
+ expect(readFreshPage()?.items).toEqual(page.items);
+
+ if (suspension === 'invalidation') {
+ await client.invalidateQueries({ exact: true, queryKey: options.queryKey, refetchType: 'none' });
+ } else {
+ backend.listGalleryItems.mockRejectedValueOnce(new Error('page unavailable'));
+ await expect(client.fetchQuery({ ...options, staleTime: 0 })).rejects.toThrow('page unavailable');
+ }
+ expect(readFreshPage()).toBeUndefined();
+ expect(isGalleryItemsPageAwaitingRefresh(client, queryHash)).toBe(true);
+
+ const applyStar = () =>
+ patchGalleryItemCaches(client, {
+ kind: 'star',
+ result: { failed: [], succeeded: [{ kind: 'image', name: page.items[0]!.name }] },
+ starred: true,
+ });
+ const rollback = applyStar();
+ expect(client.getQueryData<GalleryItemsPage>(options.queryKey)?.items[0]?.starred).toBe(true);
+ expect(readFreshPage()).toBeUndefined();
+ rollback();
+ expect(client.getQueryData<GalleryItemsPage>(options.queryKey)?.items[0]?.starred).toBe(false);
+ expect(readFreshPage()).toBeUndefined();
+
+ let resolvePending: ((page: GalleryItemsPage) => void) | undefined;
+ backend.listGalleryItems.mockImplementationOnce(
+ () =>
+ new Promise<GalleryItemsPage>((resolve) => {
+ resolvePending = resolve;
+ })
+ );
+ const pending = client.fetchQuery({ ...options, staleTime: 0 }).catch(() => undefined);
+ const rollbackPending = applyStar();
+ await client.cancelQueries({ exact: true, queryKey: options.queryKey });
+ await pending;
+ resolvePending?.(page);
+ // Cancelling the read still preserves the optimistic write, but cannot make its old page authoritative.
+ expect(client.getQueryData<GalleryItemsPage>(options.queryKey)?.items[0]?.starred).toBe(true);
+ expect(readFreshPage()).toBeUndefined();
+ rollbackPending();
+ expect(readFreshPage()).toBeUndefined();
+
+ await client.fetchQuery({ ...options, staleTime: 0 });
+ expect(readFreshPage()?.items).toEqual(page.items);
+ expect(isGalleryItemsPageAwaitingRefresh(client, queryHash)).toBe(false);
+ unsubscribe();
+ client.clear();
+ expect(readFreshPage()).toBeUndefined();
+ }
+ );
+
it('keys sparse pages by canonical account, listing, and absolute offset identity', () => {
const page = galleryItemsPageOptions(baseFilter, 60);
const samePage = galleryItemsPageOptions({ ...baseFilter, searchTerm: ' portrait ' }, 119);
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
index cd368a78fa..bc141689e4 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts
@@ -259,6 +259,7 @@ interface PendingPageFetch<T> {
}
interface GalleryPageLifecycle {
+ pageReadFreshness: WeakMap<object, boolean>;
lastUse: WeakMap<Query, number>;
nextUse: number;
queue: PendingPageFetch<unknown>[];
@@ -300,6 +301,7 @@ const ensureLifecycle = (client: QueryClient): GalleryPageLifecycle => {
}
const lifecycle: GalleryPageLifecycle = {
+ pageReadFreshness: new WeakMap(),
lastUse: new WeakMap(),
nextUse: 0,
queue: [],
@@ -360,6 +362,7 @@ const ensureLifecycle = (client: QueryClient): GalleryPageLifecycle => {
seedExistingPages();
lifecycle.unsubscribe = client.getQueryCache().subscribe((event) => {
if (event.type === 'removed') {
+ lifecycle.pageReadFreshness.delete(event.query);
return;
}
@@ -369,6 +372,16 @@ const ensureLifecycle = (client: QueryClient): GalleryPageLifecycle => {
return;
}
+ // Local cache patches and rollbacks are manual successes in Query. They must not certify an invalidated
+ // page as fresh, including when cancellation restores the state captured by one of those manual writes.
+ if (event.type === 'updated') {
+ if (event.query.state.isInvalidated || event.action.type === 'error') {
+ lifecycle.pageReadFreshness.set(event.query, false);
+ } else if (event.action.type === 'success' && !event.action.manual) {
+ lifecycle.pageReadFreshness.set(event.query, true);
+ }
+ }
+
// A failed page waits for its own Retry only while it stays in view. Once nothing observes it, forget the failure
// so returning to the page reads it again, whether its last observer left or it failed with none left to see it.
// (A read its last observer leaves mid-flight is cancelled back to its prior state before `observerRemoved`.)
@@ -399,6 +412,25 @@ const ensureLifecycle = (client: QueryClient): GalleryPageLifecycle => {
return lifecycle;
};
+/** A successful page read remains authoritative through local patches, but only another read ends invalidation. */
+export const getFreshGalleryItemsPage = (client: QueryClient, queryHash: string): GalleryItemsPage | undefined => {
+ const query = client.getQueryCache().get<GalleryItemsPage>(queryHash);
+
+ return query &&
+ query.state.status === 'success' &&
+ !query.state.isInvalidated &&
+ lifecycles.get(client)?.pageReadFreshness.get(query) === true
+ ? query.state.data
+ : undefined;
+};
+
+/** Manual or unobserved cache seeds are unknown, not suspended; only an invalidation or failure requires a reread. */
+export const isGalleryItemsPageAwaitingRefresh = (client: QueryClient, queryHash: string): boolean => {
+ const query = client.getQueryCache().get(queryHash);
+
+ return query !== undefined && lifecycles.get(client)?.pageReadFreshness.get(query) === false;
+};
+
const schedulePageFetch = <T>(
lifecycle: GalleryPageLifecycle,
signal: AbortSignal,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx
index 642976ef4c..732d654ba3 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx
@@ -871,6 +871,112 @@ describe('useGalleryData sparse page subscriptions', () => {
expect(latestData?.items?.some((item) => item.name === 'echoed.png')).toBe(false);
});
+ it.each([
+ ['ASC', false, TOTAL - 1],
+ ['DESC', false, TOTAL - 1],
+ ['ASC', true, TOTAL - 1],
+ ['DESC', true, TOTAL - 1],
+ ['ASC', false, TOTAL],
+ ['ASC', true, TOTAL],
+ ] as const)(
+ 'suspends the %s newest cutoff through invalidation and failed refresh (evicted: %s, initial total: %s)',
+ async (orderDir, evicted, initialTotal) => {
+ let uploaded = false;
+ let allowNewestRefresh = false;
+ const newestOffset = orderDir === 'ASC' ? TOTAL - 60 : 0;
+ const refreshedNewestOffset = orderDir === 'ASC' && initialTotal === TOTAL ? TOTAL : newestOffset;
+ const olderRecent = createRecent('older-recent.png', atSecond(TOTAL + 10));
+ const newerRecent = createRecent('newer-recent.png', atSecond(TOTAL + 30));
+ mocks.listGalleryItems.mockImplementation(({ offset, limit }: { offset: number; limit: number }) => {
+ if (uploaded && offset === refreshedNewestOffset && !allowNewestRefresh) {
+ return Promise.reject(new Error('newest page unavailable'));
+ }
+
+ const total = initialTotal + Number(uploaded);
+ return Promise.resolve({
+ items: Array.from({ length: Math.max(0, Math.min(limit, total - offset)) }, (_, index) => {
+ const itemIndex = orderDir === 'ASC' ? offset + index : total - 1 - offset - index;
+ return uploaded && itemIndex === initialTotal
+ ? { ...createItem(itemIndex), createdAt: atSecond(TOTAL + 20), name: 'upload.png' }
+ : createItem(itemIndex);
+ }),
+ total,
+ });
+ });
+
+ await renderProbe({ orderDir, recentImages: [olderRecent, newerRecent] });
+ await vi.waitFor(() => expect(latestData?.total).toBe(initialTotal));
+ await act(() =>
+ latestData?.setVisibleRange?.({ endIndexExclusive: newestOffset + 60, startIndex: newestOffset })
+ );
+ await vi.waitFor(() => expect(recentNames()).toHaveLength(2));
+
+ await act(() => latestData?.setVisibleRange?.({ endIndexExclusive: 6_060, startIndex: 6_000 }));
+ await vi.waitFor(() => expect(latestData?.sparseListing?.itemSlots.has(6_000)).toBe(true));
+ const newestPage = findPageQuery(newestOffset)!;
+ expect(newestPage.getObserversCount()).toBe(0);
+ expect(recentNames()).toHaveLength(2);
+ const newestReadCount = () => readRequests().filter(({ offset }) => offset === newestOffset).length;
+ const initialNewestReads = newestReadCount();
+
+ if (evicted) {
+ await act(() => queryClient!.removeQueries({ exact: true, queryKey: newestPage.queryKey }));
+ await vi.waitFor(() => expect(recentNames()).toEqual([]));
+ }
+
+ uploaded = true;
+ await act(() => invalidateGallery(queryClient!));
+ await vi.waitFor(() => expect(latestData?.total).toBe(initialTotal + 1));
+ expect(recentNames()).toEqual([]);
+ expect(latestData?.items?.some((item) => item.name === olderRecent.imageName)).toBe(false);
+ expect(newestReadCount()).toBe(initialNewestReads);
+
+ const deletedItem = latestData!.sparseListing!.itemSlots.get(6_000)!;
+ const checkPendingMutation = async () => {
+ const refreshReads = () => readRequests().filter(({ offset }) => offset === refreshedNewestOffset).length;
+ const readsBeforeMutation = refreshReads();
+ let rollback: () => void = () => undefined;
+ await act(() => {
+ // The mutation is still pending: its trailing invalidation has not run yet. Removing a middle item
+ // patches every cached page's total, including the unobserved newest page.
+ rollback = patchGalleryItemCaches(queryClient!, {
+ kind: 'delete',
+ result: { failed: [], succeeded: [{ kind: deletedItem.kind, name: deletedItem.name }] },
+ });
+ });
+ expect(recentNames()).toEqual([]);
+ expect(refreshReads()).toBe(readsBeforeMutation);
+ await act(() => rollback());
+ expect(recentNames()).toEqual([]);
+ expect(refreshReads()).toBe(readsBeforeMutation);
+ };
+ await checkPendingMutation();
+
+ await act(() =>
+ latestData?.setVisibleRange?.({
+ endIndexExclusive: refreshedNewestOffset + 60,
+ startIndex: refreshedNewestOffset,
+ })
+ );
+ await vi.waitFor(() =>
+ expect(latestData?.sparseListing?.pageStates.get(refreshedNewestOffset)?.error?.message).toBe(
+ 'newest page unavailable'
+ )
+ );
+ // Invalidated cached data, patches, and a failed refetch cannot reestablish the cutoff.
+ expect(recentNames()).toEqual([]);
+ await checkPendingMutation();
+ await act(() => invalidateGallery(queryClient!));
+ expect(recentNames()).toEqual([]);
+
+ allowNewestRefresh = true;
+ await act(() => latestData?.sparseListing?.pageStates.get(refreshedNewestOffset)?.retry());
+ await vi.waitFor(() => expect(recentNames()).toEqual(['newer-recent.png']));
+ expect(latestData?.items?.some((item) => item.name === olderRecent.imageName)).toBe(false);
+ expect(latestData?.items?.filter((item) => item.name === 'upload.png')).toHaveLength(1);
+ }
+ );
+
it('uses an indexed distant range while the initial page is still pending', async () => {
let releaseCountDiscovery: (() => void) | undefined;
mocks.listGalleryItems.mockImplementation(({ offset, limit }: { offset: number; limit: number }) => {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
index 23f4287f09..101e26039d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
@@ -20,18 +20,21 @@ import {
galleryItemsPageOptions,
galleryItemsTotalOptions,
getGalleryListingBoardsQuery,
+ getFreshGalleryItemsPage,
+ isGalleryItemsPageAwaitingRefresh,
type GalleryItemsFilter,
} from '@features/gallery/data/queries';
import { parseDateTokens } from '@platform/search/dateTokens';
import {
hashKey,
keepPreviousData,
+ notifyManager,
useInfiniteQuery,
useQueries,
useQuery,
useQueryClient,
} from '@tanstack/react-query';
-import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { planGalleryPageOffsets } from './galleryGridLayout';
import {
@@ -240,30 +243,6 @@ const getNewestCreatedAt = (items: readonly GalleryItem[]): string | undefined =
undefined
);
-/**
- * The newest item of a sparse infinite listing, read from the subscribed page that holds the listing's newest end: the
- * first page in DESC order, the last in ASC. Undefined while that page is not loaded; an empty listing has no item.
- */
-const readSparseListingNewest = ({
- orderDir,
- pageOffsets,
- pages,
-}: {
- orderDir: GalleryItemsFilter['orderDir'];
- pageOffsets: readonly number[];
- pages: readonly ({ items: readonly GalleryItem[]; total: number } | undefined)[];
-}): { createdAt?: string } | undefined => {
- const pageIndex = pageOffsets.findIndex((offset, index) => {
- const page = pages[index];
- const newestIndex = orderDir === 'ASC' ? Math.max(0, (page?.total ?? 0) - 1) : 0;
-
- return page !== undefined && offset === Math.floor(newestIndex / GALLERY_PAGE_SIZE) * GALLERY_PAGE_SIZE;
- });
- const page = pageIndex === -1 ? undefined : pages[pageIndex];
-
- return page && { createdAt: getNewestCreatedAt(page.items) };
-};
-
/** Returns the bounded local recent overlay without assigning it a backend position. */
export const getGalleryRecentItems = ({
backendItems,
@@ -557,11 +536,28 @@ export const useGalleryData = ({
totalCheckOffsets.delete(selectedPageOffset);
}
+ // Paginated and anchored windows cannot place recent rows beside unrelated backend offsets.
+ const shouldOverlayRecentItems = !isPaginated && page === 0;
+ const newestPageOffset =
+ filter.orderDir === 'ASC'
+ ? Math.floor(Math.max(0, (knownTotal ?? 0) - 1) / GALLERY_PAGE_SIZE) * GALLERY_PAGE_SIZE
+ : 0;
const toPageOptions = (offset: number) => {
const options = galleryItemsPageOptions(filter, offset);
// Failed pages wait for their own Retry; broad invalidation must not silently retry visible failures.
- return { ...options, enabled: queryClient.getQueryState(options.queryKey)?.status !== 'error' };
+ return {
+ ...options,
+ enabled: queryClient.getQueryState(options.queryKey)?.status !== 'error',
+ // Manual patches reset Query's freshness clock. Refresh a suspended page on return, without retrying a
+ // mounted failed page merely because a patch changed its status back to success.
+ refetchOnMount:
+ shouldOverlayRecentItems &&
+ offset === newestPageOffset &&
+ isGalleryItemsPageAwaitingRefresh(queryClient, hashKey(options.queryKey))
+ ? ('always' as const)
+ : true,
+ };
};
const pageOptions = sparseViewport ? pageOffsets.map(toPageOptions) : [];
const observedPageOptions = [...pageOptions, ...[...totalCheckOffsets].map(toPageOptions)];
@@ -729,40 +725,39 @@ export const useGalleryData = ({
: new Map<number, GalleryItem>(),
[isPaginated, pageOffsets, pageResults, selectedPageOffset, sparseViewport]
);
- // 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;
- // Sparse recents are cut at the listing's newest item, not the newest loaded one: the loaded pages may hold only
- // older items (ASC opens on its oldest page; a deep DESC scroll drops page zero). The page holding the newest end
- // sets the cut, which outlives that page's subscription; until it first loads, nothing is overlaid.
- const loadedListingNewest =
+ // Read the newest-end page without observing it: scrolling may release or evict it normally. Its cached state
+ // remains the authority for the cutoff, so invalidation/removal suspends the overlay until that page is fresh.
+ const newestPageHash =
sparseViewport && shouldOverlayRecentItems
- ? readSparseListingNewest({
- orderDir: filter.orderDir,
- pageOffsets,
- pages: pageResults.map((result) => result.data),
- })
- : undefined;
- const [listingNewestSnapshot, setListingNewestSnapshot] = useState<{
- createdAt?: string;
- filterIdentity: string;
- } | null>(null);
- if (
- loadedListingNewest &&
- (listingNewestSnapshot?.filterIdentity !== filterIdentity ||
- listingNewestSnapshot.createdAt !== loadedListingNewest.createdAt)
- ) {
- setListingNewestSnapshot({ ...loadedListingNewest, filterIdentity });
- }
- const listingNewest =
- sparseViewport && shouldOverlayRecentItems
- ? (loadedListingNewest ??
- (listingNewestSnapshot?.filterIdentity === filterIdentity ? listingNewestSnapshot : null))
+ ? hashKey(galleryItemsPageOptions(filter, newestPageOffset).queryKey)
: null;
- const listingNewestCreatedAt = listingNewest?.createdAt;
- const hasListingNewest = listingNewest !== null;
+ const queryCache = queryClient.getQueryCache();
+ const subscribeNewestPage = useCallback(
+ (onStoreChange: () => void) => {
+ if (newestPageHash === null) {
+ return () => undefined;
+ }
+ // Read after all cache listeners have applied the page lifecycle's fetch evidence.
+ const notify = notifyManager.batchCalls(onStoreChange);
+ return queryCache.subscribe((event) => {
+ if (event.query.queryHash === newestPageHash) {
+ notify();
+ }
+ });
+ },
+ [newestPageHash, queryCache]
+ );
+ const getNewestPageSnapshot = useCallback(
+ () => (newestPageHash ? getFreshGalleryItemsPage(queryClient, newestPageHash) : undefined),
+ [newestPageHash, queryClient]
+ );
+ const newestPage = useSyncExternalStore(subscribeNewestPage, getNewestPageSnapshot);
+ const hasListingNewest =
+ newestPage !== undefined &&
+ (filter.orderDir !== 'ASC' ||
+ newestPageOffset === Math.floor(Math.max(0, newestPage.total - 1) / GALLERY_PAGE_SIZE) * GALLERY_PAGE_SIZE);
+ const listingNewestCreatedAt = hasListingNewest ? getNewestCreatedAt(newestPage.items) : undefined;
const recentItems = useMemo(
() =>
hasListingNewest
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index f4eafbda83..40768aa509 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -2899,18 +2899,22 @@ describe('queue runtime video board routing', () => {
runtime.dispose();
});
- it('keeps Image Batch and graph inputs out of every partial and final route, scanning them once', async () => {
+ it('scans 10,000 Image Batch inputs once across partial and final image/video routes', async () => {
// Batch values reach the primitive at execution time, so the compiled graph node holds no image.
+ const batchInputs = Array.from({ length: 10_000 }, (_, index) => ({ image_name: `batch-input-${index}.png` }));
const { commands, destinations, queueItem, runtime } = createHarness({
- getResultImages: vi.fn().mockResolvedValue([resultImage('batch-input.png'), resultImage('generated.png')]),
+ getResultImages: vi
+ .fn()
+ .mockResolvedValue([
+ ...batchInputs.map(({ image_name }) => resultImage(image_name)),
+ resultImage('generated.png'),
+ ]),
getResultVideoNames: vi.fn().mockResolvedValue(['source.mp4', 'generated.mp4']),
graphNodes: {
image_primitive: { id: 'image_primitive', type: 'image' },
video_primitive: { id: 'video_primitive', type: 'video', video: { video_name: 'source.mp4' } },
},
- workflowBatchData: [
- [{ fieldName: 'image', items: [{ image_name: 'batch-input.png' }], nodeId: 'image_primitive' }],
- ],
+ workflowBatchData: [[{ fieldName: 'image', items: batchInputs, nodeId: 'image_primitive' }]],
});
const submission = queueItem.snapshot.backendSubmission;
@@ -2927,8 +2931,8 @@ describe('queue runtime video board routing', () => {
expect(commands.routeResults).toHaveBeenCalledWith(routed);
// No pass may move an input onto the destination board.
expect(destinations.addImagesToGalleryBoard).toHaveBeenCalledWith('board-1', ['generated.png']);
- expect(destinations.addImagesToGalleryBoard.mock.calls.flatMap(([, names]) => names)).not.toContain(
- 'batch-input.png'
+ expect(new Set(destinations.addImagesToGalleryBoard.mock.calls.flatMap(([, names]) => names))).toEqual(
+ new Set(['generated.png'])
);
expect(destinations.addVideosToGalleryBoard.mock.calls.flatMap(([, names]) => names)).toEqual(['generated.mp4']);
// Image and video routing of both passes share one scan of the submission.