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(image-map): make single-image reveal actually reach the grid

Lincoln Stein9ec35e3e886f
diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
index 82b4866bb0..e191030014 100644
--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
@@ -40,6 +40,7 @@ export {
registerImageCluster,
type GallerySemanticReference,
} from './core/semanticImageQuery';
+export { requestGalleryItemReveal } from './core/revealRequest';
export {
DEFAULT_GALLERY_SETTINGS,
getGallerySettings,
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/revealRequest.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/revealRequest.test.ts
new file mode 100644
index 0000000000..85a0ed6290
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/core/revealRequest.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { getGalleryRevealRequest, requestGalleryItemReveal, subscribeGalleryRevealRequests } from './revealRequest';
+
+describe('gallery reveal requests', () => {
+ it('notifies subscribers with a fresh token per request, even for the same item', () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeGalleryRevealRequests(listener);
+
+ requestGalleryItemReveal('image:a.png');
+ const first = getGalleryRevealRequest();
+
+ requestGalleryItemReveal('image:a.png');
+ const second = getGalleryRevealRequest();
+
+ expect(listener).toHaveBeenCalledTimes(2);
+ expect(first?.itemKey).toBe('image:a.png');
+ expect(second?.itemKey).toBe('image:a.png');
+ // The token is what lets a repeated gesture on an unchanged selection
+ // still read as a new reveal.
+ expect(second?.token).not.toBe(first?.token);
+
+ unsubscribe();
+ requestGalleryItemReveal('image:b.png');
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/revealRequest.ts b/invokeai/frontend/webv2/src/features/gallery/core/revealRequest.ts
new file mode 100644
index 0000000000..31dd93ec72
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/core/revealRequest.ts
@@ -0,0 +1,43 @@
+import type { GalleryItemKey } from './items';
+
+/**
+ * An explicit "scroll this item into view" signal from surfaces outside the
+ * grid (the image map's reveal). Deliberately NOT derived from the selection:
+ * the selection also changes when a finished generation auto-selects its
+ * image, and scrolling on that yanked the grid out from under a browsing
+ * user. A reveal is a deliberate gesture, so it gets its own channel — and a
+ * token, so repeating the same gesture (re-clicking the same map point after
+ * scrolling away) reveals again even though the selection is unchanged.
+ *
+ * Module-scoped rather than persisted widget state: a reveal is an ephemeral
+ * intent for the currently mounted grid, and persisting it would replay a
+ * stale scroll on the next session.
+ */
+
+export interface GalleryRevealRequest {
+ itemKey: GalleryItemKey;
+ token: number;
+}
+
+let currentRequest: GalleryRevealRequest | null = null;
+let nextToken = 0;
+
+const listeners = new Set<() => void>();
+
+export const requestGalleryItemReveal = (itemKey: GalleryItemKey): void => {
+ nextToken += 1;
+ currentRequest = { itemKey, token: nextToken };
+ for (const listener of listeners) {
+ listener();
+ }
+};
+
+export const getGalleryRevealRequest = (): GalleryRevealRequest | null => currentRequest;
+
+export const subscribeGalleryRevealRequests = (listener: () => void): (() => void) => {
+ listeners.add(listener);
+
+ return () => {
+ listeners.delete(listener);
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts
index 1daed2e6aa..15cc789ec3 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts
@@ -5,6 +5,7 @@ import {
getExternalImageFile,
getImageCluster,
parseGallerySemanticReference,
+ pruneImageClusterMembers,
registerExternalImageFile,
registerImageCluster,
semanticReferenceFromDataTransfer,
@@ -37,6 +38,33 @@ describe('image cluster registry', () => {
expect(getImageCluster(firstId)).toBe(null);
expect(getImageCluster(secondId)).toEqual({ imageNames: ['c.png'], label: 'second cluster' });
});
+
+ it('prunes deleted members with a rollback, preserving order', () => {
+ const clusterId = registerImageCluster(['a.png', 'b.png', 'c.png'], 'beaches');
+ const rollback = pruneImageClusterMembers(['b.png', 'unrelated.png']);
+
+ expect(getImageCluster(clusterId)?.imageNames).toEqual(['a.png', 'c.png']);
+
+ rollback();
+ expect(getImageCluster(clusterId)?.imageNames).toEqual(['a.png', 'b.png', 'c.png']);
+ });
+
+ it('makes pruning a no-op when nothing matches, and rollback a no-op once superseded', () => {
+ const clusterId = registerImageCluster(['a.png'], 'beaches');
+
+ // Nothing to prune: the entry is untouched.
+ pruneImageClusterMembers(['other.png']);
+ expect(getImageCluster(clusterId)?.imageNames).toEqual(['a.png']);
+
+ // A rollback captured before a newer registration must not resurrect the
+ // old list into the newer cluster's slot.
+ const rollback = pruneImageClusterMembers(['a.png']);
+ const newerId = registerImageCluster(['x.png'], 'newer');
+
+ rollback();
+ expect(getImageCluster(clusterId)).toBe(null);
+ expect(getImageCluster(newerId)?.imageNames).toEqual(['x.png']);
+ });
});
describe('semanticReferenceFromDataTransfer', () => {
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts
index b337454611..958c8ccb1a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts
@@ -117,6 +117,40 @@ export const registerImageCluster = (imageNames: string[], label: string): strin
export const getImageCluster = (clusterId: string): { imageNames: string[]; label: string } | null =>
clusters.get(clusterId) ?? null;
+/**
+ * Drops deleted images from the registered cluster, in step with the gallery's
+ * optimistic cache patch: the member list is client-owned, so without this the
+ * cluster view's total (and its trailing page) would keep counting images that
+ * no longer exist. Returns a rollback that restores the previous member list —
+ * unless a different registration has since replaced the entry, in which case
+ * the rollback is a no-op (the newer cluster owns the slot).
+ */
+export const pruneImageClusterMembers = (imageNames: readonly string[]): (() => void) => {
+ const entry = [...clusters.entries()].at(0);
+
+ if (!entry || imageNames.length === 0) {
+ return () => undefined;
+ }
+
+ const [clusterId, cluster] = entry;
+ const removed = new Set(imageNames);
+ const prunedNames = cluster.imageNames.filter((name) => !removed.has(name));
+
+ if (prunedNames.length === cluster.imageNames.length) {
+ return () => undefined;
+ }
+
+ clusters.set(clusterId, { imageNames: prunedNames, label: cluster.label });
+
+ return () => {
+ const current = clusters.get(clusterId);
+
+ if (current && current.imageNames === prunedNames) {
+ clusters.set(clusterId, { imageNames: cluster.imageNames, label: current.label });
+ }
+ };
+};
+
/**
* Parses a persisted widget value into a semantic reference. Tolerates the
* legacy bare-image-name shape, and reads a file key that no longer resolves
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
index 6b7f2809f0..9ce935c642 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
@@ -10,6 +10,7 @@ import type { AccountScope } from '@platform/state/accountLifecycle';
import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query';
import { toGalleryItemKey } from '@features/gallery/core/items';
+import { pruneImageClusterMembers } from '@features/gallery/core/semanticImageQuery';
import { captureAccountScope } from '@platform/state/accountLifecycle';
import { rollBackUnclaimedEntries } from '@platform/state/compareAndSwapRollback';
import { hashKey } from '@tanstack/react-query';
@@ -168,6 +169,13 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCa
return () => undefined;
}
+ // The cluster filter's member list is client-owned, so a server refetch can
+ // never reconcile it: prune it in the same optimistic step (and restore it
+ // with the same rollback) as the list caches it feeds.
+ const rollbackClusterMembers =
+ patch.kind === 'delete'
+ ? pruneImageClusterMembers(patch.result.succeeded.filter((ref) => ref.kind === 'image').map((ref) => ref.name))
+ : null;
const rollbackEntries: ItemCacheRollbackEntry[] = [];
for (const query of getGalleryItemListQueries(client)) {
@@ -191,12 +199,14 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCa
}
}
- return () =>
+ return () => {
+ rollbackClusterMembers?.();
rollBackUnclaimedEntries(
rollbackEntries,
(entry) => client.getQueryData<InfiniteData<GalleryItemsPage, number>>(entry.queryKey),
(entry) => client.setQueryData(entry.queryKey, entry.before)
);
+ };
};
/**
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index 2fe5748092..40c9ff2111 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -14,6 +14,7 @@ import {
type DragStartEvent,
} from '@dnd-kit/core';
import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';
+import { requestGalleryItemReveal } from '@features/gallery/core/revealRequest';
import { DEFAULT_GALLERY_SETTINGS } from '@features/gallery/core/settings';
import { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';
import { isGalleryImageDragData } from '@features/gallery/utility';
@@ -975,39 +976,69 @@ describe('GalleryImageGrid upload drop zone', () => {
});
});
-describe('GalleryImageGrid selection reveal', () => {
- it('scrolls a changed selection into view once, not again on equivalent re-renders', async () => {
+describe('GalleryImageGrid reveal requests', () => {
+ it('never scrolls on selection changes alone', async () => {
+ // The selection also changes when a finished generation auto-selects its
+ // image; scrolling on that would yank the grid out from under a browsing
+ // user. Only the explicit reveal channel may scroll.
const gallery = createGallery();
- // The mount's persisted selection counts as a change from nothing.
await renderGallery(gallery);
- expect(mocks.scrollToIndex).toHaveBeenCalledTimes(1);
+ await renderGallery({ ...gallery, selectedItemKey: 'image:last.png', selectedItemKeys: ['image:last.png'] });
- // A refetch that keeps the selection must not yank the user back to it.
- await renderGallery({ ...gallery });
+ expect(mocks.scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('scrolls to a revealed item, and again when the same item is re-revealed', async () => {
+ const gallery = createGallery();
+
+ await renderGallery(gallery);
+ await interact(() => requestGalleryItemReveal('image:first.png'));
expect(mocks.scrollToIndex).toHaveBeenCalledTimes(1);
- // An external selection (image-map reveal, palette) scrolls to its row.
- await renderGallery({ ...gallery, selectedItemKey: 'image:last.png', selectedItemKeys: ['image:last.png'] });
+ // Re-clicking the same map point after scrolling away must reveal again
+ // even though the selection is unchanged.
+ await interact(() => requestGalleryItemReveal('image:first.png'));
expect(mocks.scrollToIndex).toHaveBeenCalledTimes(2);
});
- it('scrolls when a pending selection materializes with its late-loading page', async () => {
+ it('keeps a reveal pending until its item materializes with a late-loading page', async () => {
const items = [createItem('image', 'first.png')];
+ const gallery = createGallery({ items, selectedItemKey: null, selectedItemKeys: [] });
- // The selection's page has not loaded yet, so the visible selection key
- // is still null — nothing to scroll to.
- await renderGallery(createGallery({ items, selectedItemKey: null, selectedItemKeys: [] }));
+ await renderGallery(gallery);
+ await interact(() => requestGalleryItemReveal('image:deep.png'));
expect(mocks.scrollToIndex).not.toHaveBeenCalled();
- // The page lands and the selected item appears: scroll exactly then.
- const loadedItems = [...items, createItem('image', 'deep.png')];
-
- await renderGallery(
- createGallery({ items: loadedItems, selectedItemKey: 'image:deep.png', selectedItemKeys: ['image:deep.png'] })
- );
+ // The page lands and the revealed item appears: scroll exactly then.
+ await renderGallery({
+ ...gallery,
+ items: [...items, createItem('image', 'deep.png')],
+ selectedItemKey: 'image:deep.png',
+ selectedItemKeys: ['image:deep.png'],
+ });
expect(mocks.scrollToIndex).toHaveBeenCalledTimes(1);
});
+
+ it('retires a pending reveal once a different selection lands', async () => {
+ const items = [createItem('image', 'first.png')];
+ const gallery = createGallery({ items, selectedItemKey: null, selectedItemKeys: [] });
+
+ await renderGallery(gallery);
+ await interact(() => requestGalleryItemReveal('image:deep.png'));
+
+ // The user picks something else before the reveal's page arrives.
+ await renderGallery({ ...gallery, selectedItemKey: 'image:first.png', selectedItemKeys: ['image:first.png'] });
+
+ // The revealed item arriving later must not scroll away from that choice.
+ await renderGallery({
+ ...gallery,
+ items: [...items, createItem('image', 'deep.png')],
+ selectedItemKey: 'image:first.png',
+ selectedItemKeys: ['image:first.png'],
+ });
+ expect(mocks.scrollToIndex).not.toHaveBeenCalled();
+ });
});
describe('GalleryImageGrid virtualization', () => {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index 4a080fa61b..bf111781ae 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -1,6 +1,11 @@
import { Box, chakra, Flex, HStack, Icon, ScrollArea, Spinner, Stack, Text } from '@chakra-ui/react';
import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
import { toGalleryItemKey, type GalleryItem } from '@features/gallery/core/items';
+import {
+ getGalleryRevealRequest,
+ subscribeGalleryRevealRequests,
+ type GalleryRevealRequest,
+} from '@features/gallery/core/revealRequest';
import { isDateBoardId } from '@features/gallery/data/backend';
import { DropZone } from '@platform/ui';
import { ChevronRightIcon, StarIcon, UploadIcon } from 'lucide-react';
@@ -12,6 +17,7 @@ import {
useMemo,
useRef,
useState,
+ useSyncExternalStore,
type DragEvent,
type KeyboardEvent,
} from 'react';
@@ -208,30 +214,49 @@ export const GalleryImageGrid = () => {
useGalleryGridHotkeys({ actionSelectionRefs, columnCount, scrollToItemIndex });
- // Selections made outside the grid (the image map's reveal, the command
- // palette) must land in view. The trigger is the *visible* selection key, so
- // a selection whose page is still loading scrolls exactly when the item
- // materializes; a selection already on screen is a no-op (`scrollToIndex`
- // only moves when the row is out of view). Keyed on the selection rather
- // than the row model: refetches that keep the selection must not yank the
- // user back to it after they scroll away.
- const lastScrolledSelectionRef = useRef<string | null>(null);
- const scrollSelectionIntoView = useEffectEvent((selectedItemKey: string) => {
- const itemIndex = gallery.items.findIndex((item) => toGalleryItemKey(item) === selectedItemKey);
+ // Reveals from outside the grid (the image map's click-to-reveal) must land
+ // in view. This listens to the explicit reveal channel, NOT the selection:
+ // the selection also changes when a finished generation auto-selects its
+ // image, and scrolling on that would yank the grid out from under a
+ // browsing user — while re-clicking the already-selected map point changes
+ // no selection at all yet must still reveal. A reveal whose page is still
+ // loading stays pending until the item materializes (each row-model change
+ // retries), and is dropped as soon as some other selection supersedes it.
+ const revealRequest = useSyncExternalStore(subscribeGalleryRevealRequests, getGalleryRevealRequest);
+ const pendingRevealRef = useRef<GalleryRevealRequest | null>(null);
+ const consumedRevealTokenRef = useRef(revealRequest?.token ?? 0);
+ const settlePendingReveal = useEffectEvent(() => {
+ const pending = pendingRevealRef.current;
+
+ if (!pending) {
+ return;
+ }
+
+ // A different selection landing after the reveal (the user clicked
+ // something else) retires it — a late page load must not scroll away
+ // from what they chose.
+ if (gallery.selectedItemKey !== null && gallery.selectedItemKey !== pending.itemKey) {
+ pendingRevealRef.current = null;
+
+ return;
+ }
+
+ const itemIndex = gallery.items.findIndex((item) => toGalleryItemKey(item) === pending.itemKey);
if (itemIndex >= 0) {
+ pendingRevealRef.current = null;
scrollToItemIndex(itemIndex);
}
});
useEffect(() => {
- const selectedItemKey = gallery.selectedItemKey;
-
- if (selectedItemKey && selectedItemKey !== lastScrolledSelectionRef.current) {
- lastScrolledSelectionRef.current = selectedItemKey;
- scrollSelectionIntoView(selectedItemKey);
+ if (revealRequest && revealRequest.token !== consumedRevealTokenRef.current) {
+ consumedRevealTokenRef.current = revealRequest.token;
+ pendingRevealRef.current = revealRequest;
}
- }, [gallery.selectedItemKey]);
+
+ settlePendingReveal();
+ }, [revealRequest, rows]);
useLayoutEffect(() => {
const viewport = viewportRef.current;
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 71ee6d5f92..3170333827 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
@@ -3,11 +3,15 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
- fetchQuery: vi.fn(),
+ /** Simulated page count of the cached infinite window; null = no cache. */
+ cachedPageCount: null as number | null,
+ fetchBoards: vi.fn(),
+ fetchInfiniteQuery: vi.fn(),
+ fetchNames: vi.fn(),
galleryValues: {} as Record<string, unknown>,
patchValues: vi.fn(),
- prefetchInfiniteQuery: vi.fn(),
registerImageCluster: vi.fn(),
+ requestReveal: vi.fn(),
resolveMany: vi.fn(),
selectBoard: vi.fn(),
selectItem: vi.fn(),
@@ -19,26 +23,36 @@ const mocks = vi.hoisted(() => ({
vi.mock('@features/gallery', () => ({
galleryImages: { resolveMany: mocks.resolveMany },
legacyGeneratedImageToGalleryItem: (image: { image_name: string }) => image,
+ toGalleryItemKey: (ref: { kind: string; name: string }) => `${ref.kind}:${ref.name}`,
}));
vi.mock('@features/gallery/contracts', () => ({
getGallerySettings: () => mocks.settings,
registerImageCluster: mocks.registerImageCluster,
+ requestGalleryItemReveal: mocks.requestReveal,
}));
vi.mock('@features/gallery/queries', () => ({
GALLERY_MAX_ROWS: 600,
GALLERY_PAGE_SIZE: 60,
- galleryItemNamesOptions: (filter: unknown) => ({ filter, queryKey: ['names', filter] }),
+ galleryBoardsOptions: (query: unknown) => ({ kind: 'boards', query, queryKey: ['boards', query] }),
+ galleryItemNamesOptions: (filter: unknown) => ({ filter, kind: 'names', queryKey: ['names', filter] }),
galleryItemsInfiniteOptions: (filter: unknown, window: unknown) => ({
filter,
+ kind: 'items',
queryKey: ['items', filter, window],
window,
}),
}));
vi.mock('@tanstack/react-query', () => ({
- useQueryClient: () => ({ fetchQuery: mocks.fetchQuery, prefetchInfiniteQuery: mocks.prefetchInfiniteQuery }),
+ useQueryClient: () => ({
+ fetchInfiniteQuery: (options: { pages: number }) => mocks.fetchInfiniteQuery(options),
+ fetchQuery: (options: { kind: string }) =>
+ options.kind === 'boards' ? mocks.fetchBoards(options) : mocks.fetchNames(options),
+ getQueryData: () =>
+ mocks.cachedPageCount === null ? undefined : { pages: Array.from({ length: mocks.cachedPageCount }) },
+ }),
}));
vi.mock('@workbench/widgetState', () => ({
@@ -129,9 +143,18 @@ const namesWithImageAt = (imageName: string, index: number) => ({
});
beforeEach(() => {
+ mocks.cachedPageCount = null;
mocks.galleryValues = {};
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: true };
- mocks.fetchQuery.mockResolvedValue({ items: [], starredCount: 0, total: 0 });
+ // Empty boards read as "still loading" — the reveal gives the board the
+ // benefit of the doubt, matching the gallery's own fallback rules.
+ mocks.fetchBoards.mockResolvedValue([]);
+ mocks.fetchInfiniteQuery.mockImplementation((options: { pages: number }) => {
+ mocks.cachedPageCount = options.pages;
+
+ return Promise.resolve();
+ });
+ mocks.fetchNames.mockResolvedValue({ items: [], starredCount: 0, total: 0 });
mocks.registerImageCluster.mockReturnValue('cluster-key-1');
});
@@ -139,10 +162,12 @@ afterEach(async () => {
if (root) {
await unmount();
}
- mocks.fetchQuery.mockReset();
+ mocks.fetchBoards.mockReset();
+ mocks.fetchInfiniteQuery.mockReset();
+ mocks.fetchNames.mockReset();
mocks.patchValues.mockReset();
- mocks.prefetchInfiniteQuery.mockReset();
mocks.registerImageCluster.mockReset();
+ mocks.requestReveal.mockReset();
mocks.resolveMany.mockReset();
mocks.selectBoard.mockReset();
mocks.selectItem.mockReset();
@@ -152,7 +177,7 @@ afterEach(async () => {
describe('useMapSelection', () => {
describe('selectImage', () => {
- it('dispatches the selection for a click', async () => {
+ it('dispatches the selection and a reveal for a click', async () => {
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
await mount();
@@ -164,6 +189,9 @@ describe('useMapSelection', () => {
image_name: 'a.png',
imageCategory: 'general',
});
+ // The reveal channel is what scrolls the grid; the selection alone must
+ // not (auto-selected generation results would yank the scroll).
+ expect(mocks.requestReveal).toHaveBeenCalledWith('image:a.png');
});
it("selects the image's board before the image itself", async () => {
@@ -186,7 +214,7 @@ describe('useMapSelection', () => {
it('lands the gallery on the page holding the image in paginated mode', async () => {
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: true };
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
- mocks.fetchQuery.mockResolvedValue(namesWithImageAt('deep.png', 130));
+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
await mount();
await flush(() => handle.click?.('deep.png'));
@@ -201,12 +229,12 @@ describe('useMapSelection', () => {
it("resolves the image's position against the listing the reveal lands on", async () => {
mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated', starredFirst: false };
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
- mocks.fetchQuery.mockResolvedValue(namesWithImageAt('a.png', 0));
+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('a.png', 0));
await mount();
await flush(() => handle.click?.('a.png'));
- expect(mocks.fetchQuery.mock.calls[0]?.[0].filter).toEqual({
+ expect(mocks.fetchNames.mock.calls[0]?.[0].filter).toEqual({
boardId: 'board-a',
galleryView: 'images',
orderDir: 'ASC',
@@ -215,35 +243,102 @@ describe('useMapSelection', () => {
});
});
- it('prefetches the pages down to the image in infinite mode', async () => {
+ it('force-fetches the pages down to the image in infinite mode', async () => {
+ // A plain prefetch is not enough: the mounted gallery keeps the query
+ // fresh, and a fresh cache short-circuits the fetch WITHOUT honoring
+ // the `pages` option — the window would never grow.
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite', starredFirst: true };
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
- mocks.fetchQuery.mockResolvedValue(namesWithImageAt('deep.png', 130));
+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
await mount();
await flush(() => handle.click?.('deep.png'));
expect(mocks.setPage).not.toHaveBeenCalled();
- expect(mocks.prefetchInfiniteQuery).toHaveBeenCalledTimes(1);
- expect(mocks.prefetchInfiniteQuery.mock.calls[0]?.[0].pages).toBe(3);
+ expect(mocks.fetchInfiniteQuery).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchInfiniteQuery.mock.calls[0]?.[0]).toMatchObject({ pages: 3, staleTime: 0 });
expect(mocks.selectItem.mock.calls[0]?.[2]).toBe(2);
});
- it('does not prefetch past the infinite window cap', async () => {
+ it('skips the fetch when the window already covers the image', async () => {
+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite', starredFirst: true };
+ mocks.cachedPageCount = 5;
+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
+ await mount();
+
+ await flush(() => handle.click?.('deep.png'));
+
+ expect(mocks.fetchInfiniteQuery).not.toHaveBeenCalled();
+ 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).
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite', starredFirst: true };
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
- mocks.fetchQuery.mockResolvedValue(namesWithImageAt('deep.png', 700));
+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 700));
+ await mount();
+
+ await flush(() => handle.click?.('deep.png'));
+
+ expect(mocks.fetchInfiniteQuery).not.toHaveBeenCalled();
+ expect(mocks.selectItem).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops the page landing when the ordering settings changed mid-lookup', async () => {
+ // The computed index describes the ordering the name list was fetched
+ // under; landing on that page under a different ordering would show an
+ // unrelated screen of images.
+ const names = deferred<ReturnType<typeof namesWithImageAt>>();
+
+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: true };
+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.fetchNames.mockReturnValue(names.promise);
await mount();
await flush(() => handle.click?.('deep.png'));
+ mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated', starredFirst: true };
+ await flush(() => names.resolve(namesWithImageAt('deep.png', 130)));
- expect(mocks.prefetchInfiniteQuery).not.toHaveBeenCalled();
+ expect(mocks.setPage).not.toHaveBeenCalled();
+ expect(mocks.selectItem).toHaveBeenCalledTimes(1);
+ expect(mocks.selectItem.mock.calls[0]?.[2]).toBeUndefined();
+ });
+
+ it('drops the page landing when the board is not listable in the gallery', async () => {
+ // The gallery falls back to Uncategorized for a board its boards query
+ // does not list (archived with "show archived" off); landing on the
+ // hidden board's page number there would jump to an unrelated page.
+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: true };
+ mocks.fetchBoards.mockResolvedValue([{ id: 'board-other' }]);
+ mocks.resolveMany.mockResolvedValue([
+ { boardId: 'board-archived', image_name: 'deep.png', imageCategory: 'general' },
+ ]);
+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
+ await mount();
+
+ await flush(() => handle.click?.('deep.png'));
+
+ expect(mocks.setPage).not.toHaveBeenCalled();
+ expect(mocks.selectBoard).toHaveBeenCalledWith('board-archived');
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
});
+ it('keeps the page landing when the boards lookup fails', async () => {
+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: true };
+ mocks.fetchBoards.mockRejectedValue(new Error('boards endpoint down'));
+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
+ await mount();
+
+ await flush(() => handle.click?.('deep.png'));
+
+ expect(mocks.setPage).toHaveBeenCalledWith(2);
+ });
+
it('clears an active search and similarity filter before revealing', async () => {
// The image was located in the plain board listing; an active filter
// would show some other list entirely.
@@ -285,7 +380,7 @@ describe('useMapSelection', () => {
it('still selects when the position lookup fails', async () => {
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
- mocks.fetchQuery.mockRejectedValue(new Error('names endpoint down'));
+ mocks.fetchNames.mockRejectedValue(new Error('names endpoint down'));
await mount();
await flush(() => handle.click?.('a.png'));
@@ -294,6 +389,7 @@ describe('useMapSelection', () => {
expect(mocks.selectBoard).toHaveBeenCalledWith('board-a');
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
expect(mocks.selectItem.mock.calls[0]?.[2]).toBeUndefined();
+ expect(mocks.requestReveal).toHaveBeenCalledWith('image:a.png');
});
it('does not touch the board for a click that never resolves an image', async () => {
@@ -304,11 +400,12 @@ describe('useMapSelection', () => {
expect(mocks.selectBoard).not.toHaveBeenCalled();
expect(mocks.selectItem).not.toHaveBeenCalled();
+ expect(mocks.requestReveal).not.toHaveBeenCalled();
});
});
describe('selectCluster', () => {
- it('shows the cluster as a gallery filter with the clicked image selected', async () => {
+ it('shows the cluster as a gallery filter with the clicked image selected and revealed', async () => {
mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
await mount();
@@ -326,6 +423,10 @@ describe('useMapSelection', () => {
image_name: 'a.png',
imageCategory: 'general',
});
+ // Re-clicking the same cluster point after scrolling away must return
+ // the grid to the top; the reveal channel carries that even when the
+ // selection is unchanged.
+ expect(mocks.requestReveal).toHaveBeenCalledWith('image:a.png');
});
it("selects the primary image's board before the cluster filter", async () => {
@@ -352,6 +453,7 @@ describe('useMapSelection', () => {
expect(mocks.registerImageCluster).not.toHaveBeenCalled();
expect(mocks.patchValues).not.toHaveBeenCalled();
expect(mocks.selectItem).not.toHaveBeenCalled();
+ expect(mocks.requestReveal).not.toHaveBeenCalled();
});
});
@@ -404,12 +506,12 @@ describe('useMapSelection', () => {
// The guard must hold across BOTH async hops: the hydrate and the
// name-list fetch. A click whose names arrive late must not move the
// gallery after a newer click has already landed it elsewhere.
- const slowNames = deferred<{ items: { kind: string; name: string }[]; starredCount: number; total: number }>();
+ const slowNames = deferred<ReturnType<typeof namesWithImageAt>>();
mocks.resolveMany
.mockResolvedValueOnce([{ boardId: 'board-a', image_name: 'slow.png', imageCategory: 'general' }])
.mockResolvedValueOnce([{ boardId: 'board-b', image_name: 'fast.png', imageCategory: 'general' }]);
- mocks.fetchQuery.mockReturnValueOnce(slowNames.promise).mockResolvedValueOnce(namesWithImageAt('fast.png', 0));
+ mocks.fetchNames.mockReturnValueOnce(slowNames.promise).mockResolvedValueOnce(namesWithImageAt('fast.png', 0));
await mount();
await flush(() => handle.click?.('slow.png'));
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 5774fe04af..3c8b0d88aa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
@@ -1,10 +1,13 @@
import type { GalleryView } from '@features/gallery';
+import type { GalleryItemsFilter } from '@features/gallery/queries';
+import type { QueryClient } from '@tanstack/react-query';
-import { galleryImages, legacyGeneratedImageToGalleryItem } from '@features/gallery';
-import { getGallerySettings, registerImageCluster } from '@features/gallery/contracts';
+import { galleryImages, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery';
+import { getGallerySettings, registerImageCluster, requestGalleryItemReveal } from '@features/gallery/contracts';
import {
GALLERY_MAX_ROWS,
GALLERY_PAGE_SIZE,
+ galleryBoardsOptions,
galleryItemNamesOptions,
galleryItemsInfiniteOptions,
} from '@features/gallery/queries';
@@ -29,6 +32,32 @@ export interface MapSelectionActions {
*/
let selectionSequence = 0;
+/**
+ * Extends the infinite window until it covers `pagesNeeded` pages. This must
+ * NOT be a plain prefetch: the mounted gallery keeps the query fresh, and
+ * `fetchQuery` returns fresh cache without honoring the `pages` option — the
+ * reveal has to force the fetch (staleTime 0) or the window never grows. Two
+ * passes because a concurrent fetch already in flight (a second rapid click)
+ * absorbs the call without extending; the retry runs after it settles.
+ */
+const ensureGalleryPagesLoaded = async (
+ queryClient: QueryClient,
+ listingFilter: GalleryItemsFilter,
+ pagesNeeded: number
+): Promise<void> => {
+ const options = galleryItemsInfiniteOptions(listingFilter, { kind: 'infinite' });
+
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const data = queryClient.getQueryData<{ pages: unknown[] }>(options.queryKey);
+
+ if ((data?.pages.length ?? 0) >= pagesNeeded) {
+ return;
+ }
+
+ await queryClient.fetchInfiniteQuery({ ...options, pages: pagesNeeded, staleTime: 0 });
+ }
+};
+
/**
* Turns map clicks into gallery navigation. The map only knows names; the
* selection contract wants a full gallery item, so names are hydrated through
@@ -83,14 +112,36 @@ export const useMapSelection = (): MapSelectionActions => {
};
// The image's position within its board's ordering, which is what
// lets the gallery land on the right page rather than page 0. A
- // failure here only costs the scroll, not the selection.
+ // failure here only costs the scroll, not the selection. The boards
+ // list rides along because the gallery falls back to Uncategorized
+ // when the target board is not listable (archived with "show
+ // archived" off) — landing on the hidden board's page number there
+ // would jump to an unrelated page of the wrong board.
let boardIndex: number | null = null;
try {
+ const boardsPromise = queryClient
+ .fetchQuery(
+ galleryBoardsOptions({
+ includeArchived: settings.showArchivedBoards,
+ includeDateBoards: settings.showDateBoards,
+ orderBy: settings.boardOrderBy,
+ orderDir: settings.boardOrderDir,
+ })
+ )
+ // Unknown beats blocked: without the boards list the reveal
+ // proceeds as if the board were listable.
+ .catch(() => null);
const names = await queryClient.fetchQuery(galleryItemNamesOptions(listingFilter));
+ const boards = await boardsPromise;
const index = names.items.findIndex((ref) => ref.kind === 'image' && ref.name === imageName);
+ const isBoardListable =
+ image.boardId === 'none' ||
+ boards === null ||
+ boards.length === 0 ||
+ boards.some((board) => board.id === image.boardId);
- boardIndex = index >= 0 ? index : null;
+ boardIndex = index >= 0 && isBoardListable ? index : null;
} catch {
boardIndex = null;
}
@@ -100,6 +151,18 @@ export const useMapSelection = (): MapSelectionActions => {
}
const values = getGalleryValues();
+ const settingsNow = getGallerySettings(values);
+
+ // The listing's ordering may have changed while the name list was
+ // in flight (sort direction, starred-first); the computed index
+ // describes the old ordering, so the page landing is dropped.
+ if (
+ settingsNow.imageOrderDir !== settings.imageOrderDir ||
+ settingsNow.starredFirst !== settings.starredFirst
+ ) {
+ boardIndex = null;
+ }
+
const currentView: GalleryView = values.galleryView === 'assets' ? 'assets' : 'images';
const hasSearch = typeof values.searchTerm === 'string' && values.searchTerm !== '';
@@ -122,27 +185,25 @@ export const useMapSelection = (): MapSelectionActions => {
const page = boardIndex !== null ? Math.floor(boardIndex / GALLERY_PAGE_SIZE) : null;
- if (page !== null && settings.paginationMode === 'paginated') {
+ if (page !== null && settingsNow.paginationMode === 'paginated') {
commands.gallery.setPage(page);
}
if (
boardIndex !== null &&
page !== null &&
- settings.paginationMode === 'infinite' &&
+ 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 scrolls whenever the item appears.
- void queryClient.prefetchInfiniteQuery({
- ...galleryItemsInfiniteOptions(listingFilter, { kind: 'infinite' }),
- pages: page + 1,
- });
+ // the grid's pending reveal settles whenever the item appears.
+ void ensureGalleryPagesLoaded(queryClient, listingFilter, page + 1).catch(() => {});
}
commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image), undefined, page ?? undefined);
+ requestGalleryItemReveal(toGalleryItemKey({ kind: 'image', name: imageName }));
})
.catch(() => {
// A click on a just-deleted image, or a blip mid-backend-restart,
@@ -181,8 +242,11 @@ export const useMapSelection = (): MapSelectionActions => {
semanticImageQuery: { clusterId, kind: 'cluster', label },
});
// The clicked image is the proximity ordering's first entry, so it
- // is selected at the top of the cluster view; Preview follows.
+ // is selected at the top of the cluster view; Preview follows. The
+ // reveal brings the grid back to it even when this exact selection
+ // is already current (re-clicking the cluster after scrolling away).
commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image));
+ requestGalleryItemReveal(toGalleryItemKey({ kind: 'image', name: primaryImageName }));
})
.catch(() => {
// Selection is simply left unchanged on hydrate failure.