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
feat(image-map): sync map clicks with the gallery panel
Lincoln Stein39b8628a9fc6
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex f99b331698..811377124e 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2875,6 +2875,7 @@"selectAllOnPage": "Select all gallery images on page","toggleStarImage": "Toggle gallery image star"},+ "clearClusterSearch": "Clear cluster filter","clearImageSearch": "Clear image similarity search","clearSemanticSearch": "Clear semantic search","createBoard": "Create board",@@ -2979,6 +2980,7 @@"searchOrCreateBoards": "Search or create boards","searchSemantically": "Search semantically","selectedBoardFallback": "selected board",+ "semanticCluster": "Cluster: {{name}}","semanticSimilarTo": "Similar to {{name}}","semanticTextSearch": "Semantic search: {{name}}","semanticWebImage": "web image",diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 4d76802ff4..82b4866bb0 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -34,6 +34,12 @@ export {type GalleryVideoItem,} from './core/items';export { GALLERY_RECENT_IMAGE_LIMIT, getBoundedRecentImages } from './core/recentImages';+export {+ getImageCluster,+ parseGallerySemanticReference,+ registerImageCluster,+ type GallerySemanticReference,+} from './core/semanticImageQuery';export {DEFAULT_GALLERY_SETTINGS,getGallerySettings,diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.tsindex b43eeb9c49..1daed2e6aa 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts@@ -3,8 +3,10 @@ import { describe, expect, it } from 'vitest';import {gallerySemanticReferenceKey,getExternalImageFile,+ getImageCluster,parseGallerySemanticReference,registerExternalImageFile,+ registerImageCluster,semanticReferenceFromDataTransfer,toGallerySemanticQuery,} from './semanticImageQuery';@@ -23,6 +25,20 @@ describe('external image registry', () => {});});+describe('image cluster registry', () => {+ it('holds a single slot: registering a new cluster evicts the previous one', () => {+ const firstId = registerImageCluster(['a.png', 'b.png'], 'first cluster');++ expect(getImageCluster(firstId)).toEqual({ imageNames: ['a.png', 'b.png'], label: 'first cluster' });++ const secondId = registerImageCluster(['c.png'], 'second cluster');++ expect(secondId).not.toBe(firstId);+ expect(getImageCluster(firstId)).toBe(null);+ expect(getImageCluster(secondId)).toEqual({ imageNames: ['c.png'], label: 'second cluster' });+ });+});+describe('semanticReferenceFromDataTransfer', () => {const dataTransfer = (files: File[], uriList = '') => ({files,@@ -88,6 +104,27 @@ describe('parseGallerySemanticReference', () => {expect(parseGallerySemanticReference({ kind: 'nonsense' })).toBe(null);expect(parseGallerySemanticReference('')).toBe(null);});++ it('parses cluster references while registered and drops dangling cluster keys', () => {+ const clusterId = registerImageCluster(['a.png', 'b.png'], 'beaches');++ expect(parseGallerySemanticReference({ clusterId, kind: 'cluster', label: 'beaches' })).toEqual({+ clusterId,+ kind: 'cluster',+ label: 'beaches',+ });+ // A missing label falls back to the registered one rather than dropping+ // the reference.+ expect(parseGallerySemanticReference({ clusterId, kind: 'cluster' })).toEqual({+ clusterId,+ kind: 'cluster',+ label: 'beaches',+ });+ // Registering evicts prior entries, so a stale key reads as no search —+ // exactly how a reload behaves.+ registerImageCluster(['c.png'], 'newer');+ expect(parseGallerySemanticReference({ clusterId, kind: 'cluster', label: 'beaches' })).toBe(null);+ });});describe('semantic reference identity', () => {@@ -102,6 +139,12 @@ describe('semantic reference identity', () => {expect(gallerySemanticReferenceKey({ fileId: 'external-1', kind: 'file', label: 'a' })).toBe(gallerySemanticReferenceKey({ fileId: 'external-1', kind: 'file', label: 'b' }));+ expect(gallerySemanticReferenceKey({ clusterId: 'cluster-1', kind: 'cluster', label: 'a' })).toBe(+ gallerySemanticReferenceKey({ clusterId: 'cluster-1', kind: 'cluster', label: 'b' })+ );+ expect(gallerySemanticReferenceKey({ clusterId: 'external-1', kind: 'cluster', label: 'a' })).not.toBe(+ gallerySemanticReferenceKey({ fileId: 'external-1', kind: 'file', label: 'a' })+ );});it('canonicalizes a file reference to its registry id, dropping the display label', () => {@@ -121,5 +164,9 @@ describe('semantic reference identity', () => {kind: 'text',query: 'a sunset',});+ expect(toGallerySemanticQuery({ clusterId: 'cluster-7', kind: 'cluster', label: 'beaches' })).toEqual({+ clusterId: 'cluster-7',+ kind: 'cluster',+ });});});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.tsindex 80dfcad2bd..b337454611 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts@@ -1,19 +1,25 @@/*** Identity of a semantic gallery search: a text prompt, a gallery image, a- * web image URL, or a dropped file held in the external-image registry.+ * web image URL, a dropped file held in the external-image registry, or an+ * image-map cluster held in the cluster registry.*/export type GallerySemanticQuery =| { kind: 'text'; query: string }| { kind: 'image'; imageName: string }| { kind: 'url'; url: string }- | { kind: 'file'; fileId: string };+ | { kind: 'file'; fileId: string }+ | { kind: 'cluster'; clusterId: string };-/** A persisted semantic search: a text prompt, a gallery image, a web URL, or a dropped file. */+/**+ * A persisted semantic search: a text prompt, a gallery image, a web URL, a+ * dropped file, or an image-map cluster.+ */export type GallerySemanticReference =| { kind: 'text'; query: string }| { kind: 'image'; imageName: string }| { kind: 'url'; url: string }- | { kind: 'file'; fileId: string; label: string };+ | { kind: 'file'; fileId: string; label: string }+ | { kind: 'cluster'; clusterId: string; label: string };/*** Stable identity for equality checks and fetch keys. A file reference is@@ -34,6 +40,8 @@ export const gallerySemanticReferenceKey = (reference: GallerySemanticReferencereturn `url:${reference.url}`;case 'file':return `file:${reference.fileId}`;+ case 'cluster':+ return `cluster:${reference.clusterId}`;}};@@ -48,6 +56,8 @@ export const toGallerySemanticQuery = (reference: GallerySemanticReference): Galreturn { kind: 'url', url: reference.url };case 'file':return { fileId: reference.fileId, kind: 'file' };+ case 'cluster':+ return { clusterId: reference.clusterId, kind: 'cluster' };}};@@ -78,6 +88,35 @@ export const registerExternalImageFile = (blob: Blob, label: string): string =>export const getExternalImageFile = (fileId: string): { blob: Blob; label: string } | null => files.get(fileId) ?? null;+/*+ * In-memory registry for image-map cluster queries, mirroring the file+ * registry above: a cluster's member list (which can run to thousands of+ * names) cannot live in persisted widget values, so the persisted value keeps+ * a registry key, and a key that no longer resolves (e.g. after a reload)+ * reads as a cleared search. Only one cluster query is active at a time, so+ * registering a new cluster evicts the previous one.+ */++let nextClusterId = 0;++const clusters = new Map<string, { imageNames: string[]; label: string }>();++export const registerImageCluster = (imageNames: string[], label: string): string => {+ nextClusterId += 1;+ // Same shape as file ids: the random token keeps a persisted id from a+ // previous JS realm (another tab, a reload) from resolving to this realm's+ // unrelated cluster.+ const clusterId = `cluster-${String(nextClusterId)}-${Math.random().toString(36).slice(2, 10)}`;++ clusters.clear();+ clusters.set(clusterId, { imageNames, label });++ return clusterId;+};++export const getImageCluster = (clusterId: string): { imageNames: string[]; label: string } | null =>+ clusters.get(clusterId) ?? null;+/*** 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@@ -117,6 +156,22 @@ export const parseGallerySemanticReference = (value: unknown): GallerySemanticRelabel: typeof record.label === 'string' && record.label ? record.label : 'dropped image',};}++ if (record.kind === 'cluster' && typeof record.clusterId === 'string' && record.clusterId) {+ // Cluster members live in an in-memory registry; a persisted key that+ // no longer resolves (e.g. after a reload) reads as no search at all.+ const cluster = getImageCluster(record.clusterId);++ if (cluster === null) {+ return null;+ }++ return {+ clusterId: record.clusterId,+ kind: 'cluster',+ label: typeof record.label === 'string' && record.label ? record.label : cluster.label,+ };+ }}return null;diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 0b023ed2f1..a60ef02c90 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -19,7 +19,7 @@ import type {GalleryView,} from '@features/gallery/core/types';-import { getExternalImageFile } from '@features/gallery/core/semanticImageQuery';+import { getExternalImageFile, getImageCluster } from '@features/gallery/core/semanticImageQuery';import { isTimestampInRange } from '@platform/search/dateTokens';import {AccountScopeExpiredError,@@ -801,7 +801,7 @@ const toSemanticResults = (body: SemanticSearchBody): GallerySemanticResult[] =>* registry).*/export const searchGallerySemantic = async (- query: GallerySemanticQuery,+ query: Exclude<GallerySemanticQuery, { kind: 'cluster' }>,{ limit = SEMANTIC_SEARCH_MAX_RESULTS, signal }: { limit?: number; signal?: AbortSignal } = {}): Promise<GallerySemanticResult[]> => {if (query.kind === 'url') {@@ -855,6 +855,19 @@ export const listSemanticGalleryItemNames = async ({query: GallerySemanticQuery;signal?: AbortSignal;}): Promise<GalleryItemNames> => {+ // A cluster query is an explicit member list held client-side (in proximity+ // order from the clicked map point); there is nothing to ask the server.+ if (query.kind === 'cluster') {+ const cluster = getImageCluster(query.clusterId);+ const imageNames = cluster?.imageNames ?? [];++ return {+ items: imageNames.map((name) => ({ kind: 'image', name })),+ starredCount: 0,+ total: imageNames.length,+ };+ }+const results = await searchGallerySemantic(query, { signal });return {diff --git a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.tsindex f8eb382777..8ec0cf681b 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts@@ -1,4 +1,4 @@-import { registerExternalImageFile } from '@features/gallery/core/semanticImageQuery';+import { registerExternalImageFile, registerImageCluster } from '@features/gallery/core/semanticImageQuery';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -132,6 +132,30 @@ describe('listSemanticGalleryItemNames', () => {total: 2,});});++ it('answers cluster queries from the registry without a server round trip', async () => {+ mocks.apiFetchJson.mockReset();+ const clusterId = registerImageCluster(['near.png', 'far.png'], 'beaches');++ await expect(listSemanticGalleryItemNames({ query: { clusterId, kind: 'cluster' } })).resolves.toEqual({+ items: [+ { kind: 'image', name: 'near.png' },+ { kind: 'image', name: 'far.png' },+ ],+ starredCount: 0,+ total: 2,+ });+ // An evicted key (another cluster registered, or a reload) degrades to an+ // empty list rather than an error — the parse layer clears the reference+ // before the UI would ever show that.+ registerImageCluster(['other.png'], 'newer');+ await expect(listSemanticGalleryItemNames({ query: { clusterId, kind: 'cluster' } })).resolves.toEqual({+ items: [],+ starredCount: 0,+ total: 0,+ });+ expect(mocks.apiFetchJson).not.toHaveBeenCalled();+ });});describe('semantic filter canonicalization', () => {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.tsxindex 0e520b7dd9..2fe5748092 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@@ -975,6 +975,41 @@ describe('GalleryImageGrid upload drop zone', () => {});});+describe('GalleryImageGrid selection reveal', () => {+ it('scrolls a changed selection into view once, not again on equivalent re-renders', async () => {+ const gallery = createGallery();++ // The mount's persisted selection counts as a change from nothing.+ await renderGallery(gallery);+ expect(mocks.scrollToIndex).toHaveBeenCalledTimes(1);++ // A refetch that keeps the selection must not yank the user back to it.+ await renderGallery({ ...gallery });+ 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'] });+ expect(mocks.scrollToIndex).toHaveBeenCalledTimes(2);+ });++ it('scrolls when a pending selection materializes with its late-loading page', async () => {+ const items = [createItem('image', 'first.png')];++ // 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: [] }));+ 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'] })+ );+ expect(mocks.scrollToIndex).toHaveBeenCalledTimes(1);+ });+});+describe('GalleryImageGrid virtualization', () => {it('keeps external-store option callbacks stable across equivalent renders', async () => {const gallery = createGallery({ items: [createItem('video', 'clip.mp4')] });diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex b8dd914821..4a080fa61b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -208,6 +208,31 @@ 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);++ if (itemIndex >= 0) {+ scrollToItemIndex(itemIndex);+ }+ });++ useEffect(() => {+ const selectedItemKey = gallery.selectedItemKey;++ if (selectedItemKey && selectedItemKey !== lastScrolledSelectionRef.current) {+ lastScrolledSelectionRef.current = selectedItemKey;+ scrollSelectionIntoView(selectedItemKey);+ }+ }, [gallery.selectedItemKey]);+useLayoutEffect(() => {const viewport = viewportRef.current;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsxindex d961f6c019..ed413ca41a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx@@ -4,7 +4,7 @@ import { Box, Code, HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-uimport { semanticReferenceFromDataTransfer } from '@features/gallery/core/semanticImageQuery';import { describeDateRange, findInvalidDateToken, formatIsoDate, parseDateTokens } from '@platform/search/dateTokens';import { CloseButton, IconButton } from '@platform/ui/Button';-import { CircleHelpIcon, ImageIcon, SparklesIcon } from 'lucide-react';+import { CircleHelpIcon, ImageIcon, MapIcon, SparklesIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -34,6 +34,8 @@ const getSemanticReferenceTitle = (reference: GallerySemanticReference): stringreturn reference.url;case 'file':return reference.label;+ case 'cluster':+ return reference.label;}};@@ -46,6 +48,8 @@ const getSemanticReferenceName = (reference: GallerySemanticReference): string =return reference.imageName;case 'file':return reference.label;+ case 'cluster':+ return reference.label;case 'url': {try {const parsed = new URL(reference.url);@@ -246,6 +250,7 @@ export const GalleryItemSearch = () => {const GallerySemanticChip = ({ onClear, reference }: { onClear: () => void; reference: GallerySemanticReference }) => {const { t } = useTranslation();const isText = reference.kind === 'text';+ const isCluster = reference.kind === 'cluster';const name = getSemanticReferenceName(reference) || t('widgets.gallery.semanticWebImage');return (@@ -261,12 +266,27 @@ const GallerySemanticChip = ({ onClear, reference }: { onClear: () => void; refetitle={getSemanticReferenceTitle(reference)}w="full">- <Icon as={isText ? SparklesIcon : ImageIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Icon+ as={isText ? SparklesIcon : isCluster ? MapIcon : ImageIcon}+ boxSize="3.5"+ color="fg.subtle"+ flexShrink={0}+ /><Text color="fg.muted" flex="1" fontSize="xs" minW="0" truncate>- {isText ? t('widgets.gallery.semanticTextSearch', { name }) : t('widgets.gallery.semanticSimilarTo', { name })}+ {isText+ ? t('widgets.gallery.semanticTextSearch', { name })+ : isCluster+ ? t('widgets.gallery.semanticCluster', { name })+ : t('widgets.gallery.semanticSimilarTo', { name })}</Text><CloseButton- aria-label={isText ? t('widgets.gallery.clearSemanticSearch') : t('widgets.gallery.clearImageSearch')}+ aria-label={+ isText+ ? t('widgets.gallery.clearSemanticSearch')+ : isCluster+ ? t('widgets.gallery.clearClusterSearch')+ : t('widgets.gallery.clearImageSearch')+ }size="2xs"onClick={onClear}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsxindex 8d62fe587e..0f58c87de7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx@@ -37,7 +37,11 @@ export const ImageMapHeaderActions = (_props: WidgetViewProps) => {checked={clickSelectsCluster}icon={GroupIcon}label="Toggle cluster selection mode"- tooltip={clickSelectsCluster ? 'Click selects the whole cluster' : 'Click selects one image'}+ tooltip={+ clickSelectsCluster+ ? 'Click shows the whole cluster in the gallery'+ : 'Click reveals one image in the gallery'+ }onCheckedChange={handleToggleClusterMode}/></>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 3524468eaa..fe96925f04 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -6,9 +6,11 @@ import type { CSSProperties } from 'react';import { Box } from '@chakra-ui/react';import {+ getImageCluster,getPersistedSelectedGalleryItemKeys,getSelectedGalleryImageFromValues,parseGalleryItemKey,+ parseGallerySemanticReference,} from '@features/gallery/contracts';import { attachWheelZoom } from '@workbench/image-map/attachWheelZoom';import { getClusterColor, isClusterColorLight } from '@workbench/image-map/clusterPalette';@@ -314,7 +316,21 @@ const ImageMapPlot = ({.map((ref) => ref.name),shallowEqual);- const selectedNames = useMemo(() => new Set(selectedImageNames), [selectedImageNames]);+ // With a cluster filter active in the gallery, the whole cluster stays+ // highlighted on the map — the gallery is showing exactly these images.+ const clusterQueryImageNames = useWidgetValuesSelector(+ 'gallery',+ (values) => {+ const reference = parseGallerySemanticReference(values.semanticImageQuery);++ return reference?.kind === 'cluster' ? (getImageCluster(reference.clusterId)?.imageNames ?? null) : null;+ },+ shallowEqual+ );+ const selectedNames = useMemo(+ () => new Set([...selectedImageNames, ...(clusterQueryImageNames ?? [])]),+ [clusterQueryImageNames, selectedImageNames]+ );const { selectCluster, selectImage } = useMapSelection();// Bumped after every scene rebuild so the overlay effects (marker,// highlight) re-apply onto the fresh, empty overlay traces.@@ -328,13 +344,15 @@ const ImageMapPlot = ({const pointsRef = useRef(points);const selectedImageNameRef = useRef(selectedImageName);const clusterModeRef = useRef(clickSelectsCluster);+ const clusterLabelsRef = useRef(clusterLabels);// Declared before the effects below so the refs are fresh when they run.useEffect(() => {pointsRef.current = points;selectedImageNameRef.current = selectedImageName;clusterModeRef.current = clickSelectsCluster;- }, [clickSelectsCluster, points, selectedImageName]);+ clusterLabelsRef.current = clusterLabels;+ }, [clickSelectsCluster, clusterLabels, points, selectedImageName]);// The full annotation set for the current data; which of them actually show// is view-dependent (see applyDeclutteredAnnotations), so the source list// lives in a ref the relayout listener can re-filter without re-rendering.@@ -454,7 +472,15 @@ const ImageMapPlot = ({const clusterNames = clusterModeRef.current ? collectClusterSelection(points, imageName) : null;if (clusterNames) {- selectCluster(imageName, clusterNames);+ const clicked = points.find((point) => point.imageName === imageName);+ // The backend's cluster label names the filter chip when one has+ // arrived; the member count is the fallback (labels can be off,+ // still loading, or missing for this cluster).+ const label =+ (clicked ? clusterLabelsRef.current?.[String(clicked.cluster)] : undefined) ??+ `${clusterNames.length} images`;++ selectCluster(imageName, clusterNames, label);} else {// Also the cluster-mode fallback for noise points (cluster -1).selectImage(imageName);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.tsxindex 26029edda7..71ee6d5f92 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@@ -1,18 +1,48 @@import { act, useEffect } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({+ fetchQuery: vi.fn(),+ galleryValues: {} as Record<string, unknown>,+ patchValues: vi.fn(),+ prefetchInfiniteQuery: vi.fn(),+ registerImageCluster: vi.fn(),resolveMany: vi.fn(),selectBoard: vi.fn(),- setItemMultiSelection: vi.fn(),selectItem: vi.fn(),+ setPage: vi.fn(),+ settings: { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: true } as Record<string, unknown>,+ setView: vi.fn(),}));vi.mock('@features/gallery', () => ({galleryImages: { resolveMany: mocks.resolveMany },legacyGeneratedImageToGalleryItem: (image: { image_name: string }) => image,- toGalleryItemKey: (key: { kind: string; name: string }) => key,+}));++vi.mock('@features/gallery/contracts', () => ({+ getGallerySettings: () => mocks.settings,+ registerImageCluster: mocks.registerImageCluster,+}));++vi.mock('@features/gallery/queries', () => ({+ GALLERY_MAX_ROWS: 600,+ GALLERY_PAGE_SIZE: 60,+ galleryItemNamesOptions: (filter: unknown) => ({ filter, queryKey: ['names', filter] }),+ galleryItemsInfiniteOptions: (filter: unknown, window: unknown) => ({+ filter,+ queryKey: ['items', filter, window],+ window,+ }),+}));++vi.mock('@tanstack/react-query', () => ({+ useQueryClient: () => ({ fetchQuery: mocks.fetchQuery, prefetchInfiniteQuery: mocks.prefetchInfiniteQuery }),+}));++vi.mock('@workbench/widgetState', () => ({+ getProjectWidgetValues: () => mocks.galleryValues,}));vi.mock('@workbench/WorkbenchContext', () => ({@@ -20,9 +50,12 @@ vi.mock('@workbench/WorkbenchContext', () => ({gallery: {selectBoard: mocks.selectBoard,selectItem: mocks.selectItem,- setItemMultiSelection: mocks.setItemMultiSelection,+ setPage: mocks.setPage,+ setView: mocks.setView,},+ widgets: { patchValues: mocks.patchValues },}),+ useWorkbenchQueries: () => ({ getSnapshot: () => ({ activeProject: { id: 'project-1' } }) }),}));import { useMapSelection } from './useSelectMapImage';@@ -35,7 +68,7 @@ let root: Root | null = null;/** Published from an effect, not during render, so the probe stays render-pure. */const handle: {click: ((imageName: string) => void) | null;- clickCluster: ((primaryImageName: string, imageNames: string[]) => void) | null;+ clickCluster: ((primaryImageName: string, imageNames: string[], label: string) => void) | null;} = { click: null, clickCluster: null };const Probe = () => {@@ -49,11 +82,13 @@ const Probe = () => {return null;};-/** Runs `fn` inside act and drains the microtask queue so promise callbacks land. */+/** Runs `fn` inside act and drains queued promise callbacks (a macrotask covers the chained awaits). */const flush = async (fn: () => void = () => {}) => {await act(async () => {fn();- await Promise.resolve();+ await new Promise((resolve) => {+ setTimeout(resolve, 0);+ });});};@@ -83,120 +118,270 @@ const deferred = <T,>() => {return { promise, resolve };};+/** A names response placing `imageName` at `index` in its board's ordering. */+const namesWithImageAt = (imageName: string, index: number) => ({+ items: Array.from({ length: index + 1 }, (_, position) => ({+ kind: 'image',+ name: position === index ? imageName : `other-${String(position)}.png`,+ })),+ starredCount: 0,+ total: index + 1,+});++beforeEach(() => {+ mocks.galleryValues = {};+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: true };+ mocks.fetchQuery.mockResolvedValue({ items: [], starredCount: 0, total: 0 });+ mocks.registerImageCluster.mockReturnValue('cluster-key-1');+});+afterEach(async () => {if (root) {await unmount();}+ mocks.fetchQuery.mockReset();+ mocks.patchValues.mockReset();+ mocks.prefetchInfiniteQuery.mockReset();+ mocks.registerImageCluster.mockReset();mocks.resolveMany.mockReset();mocks.selectBoard.mockReset();mocks.selectItem.mockReset();- mocks.setItemMultiSelection.mockReset();+ mocks.setPage.mockReset();+ mocks.setView.mockReset();});describe('useMapSelection', () => {- it('dispatches the selection for a click', async () => {- mocks.resolveMany.mockResolvedValue([{ image_name: 'a.png' }]);- await mount();+ describe('selectImage', () => {+ it('dispatches the selection for a click', async () => {+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.selectItem).toHaveBeenCalledTimes(1);+ expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({+ boardId: 'board-a',+ image_name: 'a.png',+ imageCategory: 'general',+ });+ });++ it("selects the image's board before the image itself", async () => {+ // The map spans every accessible board, but selectGalleryItem stamps the+ // navigation query from whatever list the gallery is currently showing. A+ // cross-board click without this left that query describing a list the+ // image was never in, and Preview's next/prev found no cursor and went+ // dead until the user re-selected from the grid.+ mocks.resolveMany.mockResolvedValue([+ { boardId: 'board-portraits', image_name: 'a.png', imageCategory: 'general' },+ ]);+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.selectBoard).toHaveBeenCalledWith('board-portraits');+ expect(mocks.selectBoard.mock.invocationCallOrder[0]).toBeLessThan(mocks.selectItem.mock.invocationCallOrder[0]);+ });- await flush(() => handle.click?.('a.png'));+ 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));+ await mount();- expect(mocks.selectItem).toHaveBeenCalledTimes(1);- expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({ image_name: 'a.png' });- });+ await flush(() => handle.click?.('deep.png'));- it("selects the image's board before the image itself", async () => {- // The map spans every accessible board, but selectGalleryItem stamps the- // navigation query from whatever list the gallery is currently showing. A- // cross-board click without this left that query describing a list the- // image was never in, and Preview's next/prev found no cursor and went- // dead until the user re-selected from the grid.- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-portraits', image_name: 'a.png' }]);- await mount();+ expect(mocks.setPage).toHaveBeenCalledWith(2);+ expect(mocks.selectItem).toHaveBeenCalledTimes(1);+ // The selection page rides along so the stamped navigation query+ // describes the page the image is actually on.+ expect(mocks.selectItem.mock.calls[0]?.[2]).toBe(2);+ });- await flush(() => handle.click?.('a.png'));+ 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));+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.fetchQuery.mock.calls[0]?.[0].filter).toEqual({+ boardId: 'board-a',+ galleryView: 'images',+ orderDir: 'ASC',+ searchTerm: '',+ starredFirst: false,+ });+ });- expect(mocks.selectBoard).toHaveBeenCalledWith('board-portraits');- expect(mocks.selectBoard.mock.invocationCallOrder[0]).toBeLessThan(mocks.selectItem.mock.invocationCallOrder[0]);- });+ it('prefetches the pages down to the image in infinite mode', async () => {+ 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));+ await mount();- it('does not touch the board for a click that never resolves an image', async () => {- mocks.resolveMany.mockResolvedValue([]);- await mount();+ await flush(() => handle.click?.('deep.png'));- await flush(() => handle.click?.('gone.png'));+ expect(mocks.setPage).not.toHaveBeenCalled();+ expect(mocks.prefetchInfiniteQuery).toHaveBeenCalledTimes(1);+ expect(mocks.prefetchInfiniteQuery.mock.calls[0]?.[0].pages).toBe(3);+ expect(mocks.selectItem.mock.calls[0]?.[2]).toBe(2);+ });- expect(mocks.selectBoard).not.toHaveBeenCalled();- expect(mocks.selectItem).not.toHaveBeenCalled();- });+ it('does not prefetch 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));+ await mount();- it('selects the primary image\u2019s board before the cluster', async () => {- // Same reason as the single-image case: setItemMultiSelection stamps the- // navigation query from the list the gallery is currently showing, so a- // cluster picked from another board would leave that query describing a- // list none of these images are in.- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-landscapes', image_name: 'a.png' }]);- await mount();+ await flush(() => handle.click?.('deep.png'));- await flush(() => handle.clickCluster?.('a.png', ['a.png', 'b.png', 'c.png']));+ expect(mocks.prefetchInfiniteQuery).not.toHaveBeenCalled();+ expect(mocks.selectItem).toHaveBeenCalledTimes(1);+ });- expect(mocks.selectBoard).toHaveBeenCalledWith('board-landscapes');- expect(mocks.selectBoard.mock.invocationCallOrder[0]).toBeLessThan(- mocks.setItemMultiSelection.mock.invocationCallOrder[0]- );- });+ 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.+ mocks.galleryValues = { searchTerm: 'sunset', semanticImageQuery: { kind: 'text', query: 'sunset' } };+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);+ await mount();- it('passes every cluster member as an image-kinded key, anchored on the clicked one', async () => {- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png' }]);- await mount();+ await flush(() => handle.click?.('a.png'));++ expect(mocks.patchValues).toHaveBeenCalledWith('gallery', { searchTerm: '', semanticImageQuery: null });+ });++ it('leaves the filters alone when none are active', async () => {+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.patchValues).not.toHaveBeenCalled();+ });++ it('switches the gallery to the assets tab for a non-general image', async () => {+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'user' }]);+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.setView).toHaveBeenCalledWith('assets');+ });++ it('does not touch the view when it already matches', async () => {+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.setView).not.toHaveBeenCalled();+ });++ 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'));+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.setPage).not.toHaveBeenCalled();+ expect(mocks.selectBoard).toHaveBeenCalledWith('board-a');+ expect(mocks.selectItem).toHaveBeenCalledTimes(1);+ expect(mocks.selectItem.mock.calls[0]?.[2]).toBeUndefined();+ });- await flush(() => handle.clickCluster?.('a.png', ['a.png', 'b.png']));+ it('does not touch the board for a click that never resolves an image', async () => {+ mocks.resolveMany.mockResolvedValue([]);+ await mount();- expect(mocks.setItemMultiSelection).toHaveBeenCalledTimes(1);- const [keys, primary] = mocks.setItemMultiSelection.mock.calls[0] ?? [];- expect(keys).toEqual([- { kind: 'image', name: 'a.png' },- { kind: 'image', name: 'b.png' },- ]);- expect(primary).toEqual({ boardId: 'board-a', image_name: 'a.png' });+ await flush(() => handle.click?.('gone.png'));++ expect(mocks.selectBoard).not.toHaveBeenCalled();+ expect(mocks.selectItem).not.toHaveBeenCalled();+ });});- it('leaves the selection alone when the primary image cannot be resolved', async () => {- mocks.resolveMany.mockResolvedValue([]);- await mount();+ describe('selectCluster', () => {+ it('shows the cluster as a gallery filter with the clicked image selected', async () => {+ mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);+ await mount();++ await flush(() => handle.clickCluster?.('a.png', ['a.png', 'b.png', 'c.png'], 'beaches'));++ expect(mocks.registerImageCluster).toHaveBeenCalledWith(['a.png', 'b.png', 'c.png'], 'beaches');+ expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {+ galleryPage: 0,+ searchTerm: '',+ semanticImageQuery: { clusterId: 'cluster-key-1', kind: 'cluster', label: 'beaches' },+ });+ expect(mocks.selectItem).toHaveBeenCalledTimes(1);+ expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({+ boardId: 'board-a',+ image_name: 'a.png',+ imageCategory: 'general',+ });+ });++ it("selects the primary image's board before the cluster filter", async () => {+ // The selection stamps the navigation query from the list the gallery+ // is currently showing, so the primary image's board must be current+ // before the selection lands.+ mocks.resolveMany.mockResolvedValue([+ { boardId: 'board-landscapes', image_name: 'a.png', imageCategory: 'general' },+ ]);+ await mount();++ await flush(() => handle.clickCluster?.('a.png', ['a.png', 'b.png'], 'label'));++ expect(mocks.selectBoard).toHaveBeenCalledWith('board-landscapes');+ expect(mocks.selectBoard.mock.invocationCallOrder[0]).toBeLessThan(mocks.selectItem.mock.invocationCallOrder[0]);+ });++ it('leaves the gallery alone when the primary image cannot be resolved', async () => {+ mocks.resolveMany.mockResolvedValue([]);+ await mount();- await flush(() => handle.clickCluster?.('gone.png', ['gone.png', 'b.png']));+ await flush(() => handle.clickCluster?.('gone.png', ['gone.png', 'b.png'], 'label'));- expect(mocks.selectBoard).not.toHaveBeenCalled();- expect(mocks.setItemMultiSelection).not.toHaveBeenCalled();+ expect(mocks.registerImageCluster).not.toHaveBeenCalled();+ expect(mocks.patchValues).not.toHaveBeenCalled();+ expect(mocks.selectItem).not.toHaveBeenCalled();+ });});it('shares one sequence guard across both modes, so the newer click wins', async () => {// The two entry points must not race each other: switching cluster mode// mid-flight would otherwise let a stale resolution overwrite a newer// selection.- const slow = deferred<{ image_name: string }[]>();- const fast = deferred<{ image_name: string }[]>();+ const slow = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();+ const fast = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();mocks.resolveMany.mockReturnValueOnce(slow.promise).mockReturnValueOnce(fast.promise);await mount();await flush(() => {- handle.clickCluster?.('slow.png', ['slow.png']);+ handle.clickCluster?.('slow.png', ['slow.png'], 'label');handle.click?.('fast.png');});await flush(() => {- fast.resolve([{ image_name: 'fast.png' }]);- slow.resolve([{ image_name: 'slow.png' }]);+ fast.resolve([{ boardId: 'board-a', image_name: 'fast.png', imageCategory: 'general' }]);+ slow.resolve([{ boardId: 'board-a', image_name: 'slow.png', imageCategory: 'general' }]);});- expect(mocks.setItemMultiSelection).not.toHaveBeenCalled();+ expect(mocks.patchValues).not.toHaveBeenCalled();expect(mocks.selectItem).toHaveBeenCalledTimes(1);- expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({ image_name: 'fast.png' });+ expect(mocks.selectItem.mock.calls[0]?.[0].image_name).toBe('fast.png');});it('ignores a slow click that resolves after a newer one', async () => {- const slow = deferred<{ image_name: string }[]>();- const fast = deferred<{ image_name: string }[]>();+ const slow = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();+ const fast = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();mocks.resolveMany.mockReturnValueOnce(slow.promise).mockReturnValueOnce(fast.promise);await mount();@@ -207,21 +392,41 @@ describe('useMapSelection', () => {});await flush(() => {- fast.resolve([{ image_name: 'fast.png' }]);- slow.resolve([{ image_name: 'slow.png' }]);+ fast.resolve([{ boardId: 'board-a', image_name: 'fast.png', imageCategory: 'general' }]);+ slow.resolve([{ boardId: 'board-a', image_name: 'slow.png', imageCategory: 'general' }]);});// Only the most recent click may win, regardless of resolution order.expect(mocks.selectItem.mock.calls.map((call) => call[0].image_name)).toEqual(['fast.png']);});+ it('ignores a click whose position lookup lands after a newer click', async () => {+ // 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 }>();++ 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));+ await mount();++ await flush(() => handle.click?.('slow.png'));+ await flush(() => handle.click?.('fast.png'));+ await flush(() => slowNames.resolve(namesWithImageAt('slow.png', 0)));++ expect(mocks.selectBoard.mock.calls).toEqual([['board-b']]);+ expect(mocks.selectItem.mock.calls.map((call) => call[0].image_name)).toEqual(['fast.png']);+ });+it('ignores a click left in flight across an unmount/remount', async () => {// The regression this guards: a per-mount counter is reset by the remount,// so the abandoned click compares against a dead counter, passes, and// overwrites the newer mount's selection. Reachable by switching the right// panel away from the map and back while a hydrate is in flight.- const stale = deferred<{ image_name: string }[]>();- const fresh = deferred<{ image_name: string }[]>();+ const stale = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();+ const fresh = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();mocks.resolveMany.mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise);@@ -233,8 +438,8 @@ describe('useMapSelection', () => {await flush(() => handle.click?.('fresh.png'));await flush(() => {- fresh.resolve([{ image_name: 'fresh.png' }]);- stale.resolve([{ image_name: 'stale.png' }]);+ fresh.resolve([{ boardId: 'board-a', image_name: 'fresh.png', imageCategory: 'general' }]);+ stale.resolve([{ boardId: 'board-a', image_name: 'stale.png', imageCategory: 'general' }]);});expect(mocks.selectItem.mock.calls.map((call) => call[0].image_name)).toEqual(['fresh.png']);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.tsindex 1d3f65ecc7..5774fe04af 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts@@ -1,12 +1,23 @@-import { galleryImages, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery';-import { useWorkbenchCommands } from '@workbench/WorkbenchContext';+import type { GalleryView } from '@features/gallery';++import { galleryImages, legacyGeneratedImageToGalleryItem } from '@features/gallery';+import { getGallerySettings, registerImageCluster } from '@features/gallery/contracts';+import {+ GALLERY_MAX_ROWS,+ GALLERY_PAGE_SIZE,+ galleryItemNamesOptions,+ galleryItemsInfiniteOptions,+} from '@features/gallery/queries';+import { useQueryClient } from '@tanstack/react-query';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';export interface MapSelectionActions {- /** Select one image (hydrates the item, then gallery.selectItem). */+ /** Reveal one image: land the gallery on its board, page, and grid cell. */selectImage: (imageName: string) => void;- /** Multi-select a cluster with the clicked image as primary. */- selectCluster: (primaryImageName: string, imageNames: string[]) => void;+ /** Show the whole cluster in the gallery, the clicked image selected. */+ selectCluster: (primaryImageName: string, imageNames: string[], label: string) => void;}/**@@ -19,16 +30,30 @@ export interface MapSelectionActions {let selectionSequence = 0;/**- * Turns map clicks into gallery selections. The map only knows names; the+ * Turns map clicks into gallery navigation. The map only knows names; the* selection contract wants a full gallery item, so names are hydrated through* the bulk by-names resolver — always fresh, since a cached DTO's star/board* state can drift. ONE monotonic sequence spans both selection kinds, so* rapid clicks always resolve to the latest click regardless of which mode* each went through; a slow fetch can never overwrite a newer selection.* Preview follows the gallery selection on its own.+ *+ * A single-image click is a full reveal: the gallery lands on the image's+ * board and view, any search or similarity filter is cleared (the image may+ * not match it), and the image's position in the board's ordering is looked+ * up so the grid can reach it — the page is selected in paginated mode, and+ * in infinite mode the pages down to it are loaded. The grid scrolls to the+ * newly selected item on its own once it is in the loaded window.+ *+ * A cluster click instead behaves like a search: the cluster's members (in+ * proximity order from the clicked point) become the gallery's list via a+ * `cluster` semantic reference, with the clicked image — the list's first+ * entry — as the selection.*/export const useMapSelection = (): MapSelectionActions => {const commands = useWorkbenchCommands();+ const queries = useWorkbenchQueries();+ const queryClient = useQueryClient();const selectImage = useCallback((imageName: string) => {@@ -36,41 +61,99 @@ export const useMapSelection = (): MapSelectionActions => {galleryImages.resolveMany([imageName])- .then((images) => {+ .then(async (images) => {const image = images.at(0);if (!image || sequence !== selectionSequence) {return;}- // Select the image's board first. The map spans every accessible- // board, but `selectGalleryItem` stamps `selectedImageQuery` from- // whatever list the gallery is CURRENTLY showing — it takes the- // selection on faith as "an item from the visible page". Selecting a- // point from another board without this left the stored query- // describing a list the image was never in, so Preview's next/prev- // found no cursor and went dead until the user re-selected from the- // grid. Mirrors the command palette's reveal-in-gallery.- //- // This lands the gallery on page 0 of that board (selectGalleryBoard- // resets the page), so next/prev works whenever the image is on the- // first page. Placing it exactly would need the board's ordering,- // which only the gallery query knows — Preview does it that way, from- // pages it has already loaded. The query is at least coherent now:- // it describes a real list, and any grid selection re-anchors it.+ const getGalleryValues = () => getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');+ const settings = getGallerySettings(getGalleryValues());+ const targetView: GalleryView = image.imageCategory === 'general' ? 'images' : 'assets';+ // The board listing the gallery will show once the reveal below has+ // cleared any search: identical filter shape, so the name list (and+ // the prefetched pages) land in the cache the gallery reads.+ const listingFilter = {+ boardId: image.boardId,+ galleryView: targetView,+ orderDir: settings.imageOrderDir,+ searchTerm: '',+ starredFirst: settings.starredFirst,+ };+ // 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.+ let boardIndex: number | null = null;++ try {+ const names = await queryClient.fetchQuery(galleryItemNamesOptions(listingFilter));+ const index = names.items.findIndex((ref) => ref.kind === 'image' && ref.name === imageName);++ boardIndex = index >= 0 ? index : null;+ } catch {+ boardIndex = null;+ }++ if (sequence !== selectionSequence) {+ return;+ }++ const values = getGalleryValues();+ const currentView: GalleryView = values.galleryView === 'assets' ? 'assets' : 'images';+ const hasSearch = typeof values.searchTerm === 'string' && values.searchTerm !== '';++ // Filters would hide the board listing the index was computed+ // against (the image may not match them), so the reveal clears them.+ if (hasSearch || (values.semanticImageQuery !== null && values.semanticImageQuery !== undefined)) {+ commands.widgets.patchValues('gallery', { searchTerm: '', semanticImageQuery: null });+ }++ if (currentView !== targetView) {+ commands.gallery.setView(targetView);+ }++ // Select the image's board before the image. The map spans every+ // accessible board, but `selectGalleryItem` stamps the navigation+ // query from whatever list the gallery is CURRENTLY showing — a+ // cross-board click without this left Preview's next/prev with no+ // cursor. Mirrors the command palette's reveal-in-gallery.commands.gallery.selectBoard(image.boardId);- commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image));++ const page = boardIndex !== null ? Math.floor(boardIndex / GALLERY_PAGE_SIZE) : null;++ if (page !== null && settings.paginationMode === 'paginated') {+ commands.gallery.setPage(page);+ }++ if (+ boardIndex !== null &&+ page !== null &&+ settings.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,+ });+ }++ commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image), undefined, page ?? undefined);}).catch(() => {// A click on a just-deleted image, or a blip mid-backend-restart,// simply leaves the selection unchanged.});},- [commands]+ [commands, queries, queryClient]);const selectCluster = useCallback(- (primaryImageName: string, imageNames: string[]) => {+ (primaryImageName: string, imageNames: string[], label: string) => {const sequence = ++selectionSequence;galleryImages@@ -82,14 +165,24 @@ export const useMapSelection = (): MapSelectionActions => {return;}- // Same reason as `selectImage` above: the multi-selection command- // stamps `selectedImageQuery` from the board the gallery is showing,- // so without landing on the primary image's board first the query- // describes a list none of these images are in.+ // Same reason as `selectImage` above: the selection stamps the+ // navigation query from the board the gallery is showing, so land+ // on the primary image's board first to keep that query coherent.commands.gallery.selectBoard(image.boardId);- // Map points are always images, so every key is kind-tagged 'image'.- const itemKeys = imageNames.map((name) => toGalleryItemKey({ kind: 'image', name }));- commands.gallery.setItemMultiSelection(itemKeys, legacyGeneratedImageToGalleryItem(image));+ // The member list lives in an in-memory registry (it can run to+ // thousands of names); the persisted value keeps only the key. The+ // page reset and search-term clear mirror setSemanticImageQuery in+ // the gallery's own actions.+ const clusterId = registerImageCluster(imageNames, label);++ commands.widgets.patchValues('gallery', {+ galleryPage: 0,+ searchTerm: '',+ 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.+ commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image));}).catch(() => {// Selection is simply left unchanged on hydrate failure.