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(webv2): show image-map tags on gallery hover and in preview details
Lincoln Stein9a3775bc3688
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 5fb0ac385c..fb0051827b 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2598,6 +2598,7 @@"sideBySide": "Side by Side","slider": "Slider","hover": "Hover",+ "imageTags": "Image tags:","hoverComparisonAriaLabel": "Reveal comparison image on hover, focus, or touch","sourceRun": "Source run {{id}}","videoDuration": "Duration {{duration}}",diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex c4b24f9f56..2f2d7107c9 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -1,3 +1,4 @@+import type { GalleryItemRef } from '@features/gallery/contracts';import type { GalleryUiAdapter } from '@features/gallery/react';import type { ReactNode } from 'react';@@ -13,6 +14,14 @@ import { lazy, useMemo } from 'react';const EMPTY_WIDGET_VALUES: Record<string, unknown> = Object.freeze({});+// Loaded on first reveal; the label cache is not part of the editor's initial graph.+const getItemLabel = (item: GalleryItemRef): Promise<string | null> =>+ import('@workbench/image-map/imageLabelCache')+ .then(({ getImageLabels }) => getImageLabels(item))+ .then((labels) => labels?.label ?? null)+ // A chunk that fails to load (stale deploy, dropped network) means no label, not an unhandled rejection.+ .catch(() => null);+const GalleryItemActionsAdapter = lazy(() =>import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryItemActionsAdapter })));@@ -54,6 +63,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })},galleryValues,generateValues,+ getItemLabel,ItemActionsProvider: GalleryItemActionsAdapter,ImageContextMenu: GalleryImageContextMenu,liveFollowEnabled,diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex c61297dd28..18f592ce55 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -9,6 +9,7 @@ export {galleryItemsInfiniteOptions,galleryKeys,galleryStarredStripOptions,+ imageIndexAvailabilityOptions,} from './data/queries';export type {CanonicalGalleryItemsFilter,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 a0cac08449..8a6f1c1039 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@@ -1,5 +1,6 @@/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-object-as-prop */import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';+import type { ImageIndexAvailability } from '@features/gallery/data/backend';import type { GalleryItemsFilter } from '@features/gallery/data/queries';import type { QueueProgressSession } from '@features/queue/contracts';import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';@@ -48,6 +49,8 @@ const mocks = vi.hoisted(() => ({itemProgress: null as { percentage: number; message: string } | null,progressFrame: null as { dataUrl: string; width: number; height: number } | null,fetchNames: vi.fn(),+ getItemLabel: vi.fn<GalleryUiAdapter['getItemLabel']>(),+ indexAvailability: { modelName: null, state: 'disabled' } as ImageIndexAvailability,measure: vi.fn(),scrollToIndex: vi.fn(),setPage: vi.fn(),@@ -63,6 +66,10 @@ const getNamesKey = (filter: unknown) => ['test-gallery-item-names', JSON.stringvi.mock('@features/gallery/data/queries', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),+ imageIndexAvailabilityOptions: () => ({+ queryFn: () => mocks.indexAvailability,+ queryKey: ['test-image-index-availability'],+ }),galleryItemNamesOptions: (filter: unknown) => ({queryFn: () => mocks.fetchNames(filter),queryKey: getNamesKey(filter),@@ -369,6 +376,7 @@ const createAdapter = (},galleryValues: {},generateValues: {},+ getItemLabel: mocks.getItemLabel,liveFollowEnabled,progressSessions,pinnedProgressSessionId,@@ -533,6 +541,8 @@ beforeEach(() => {registeredCommands.clear();currentGallery = createGallery();mocks.itemProgress = null;+ mocks.indexAvailability = { modelName: null, state: 'disabled' };+ mocks.getItemLabel.mockReset();currentProgressSessions = [];currentLiveFollowEnabled = false;currentPinnedSessionId = null;@@ -1020,6 +1030,89 @@ describe('GalleryImageGrid mixed item cells', () => {});});+describe('GalleryImageGrid image-map labels', () => {+ const getTile = (name: string): HTMLElement => {+ const tile = getButton(`Select ${name} for preview`).parentElement;++ if (!tile) {+ throw new Error(`Expected tile for ${name}`);+ }++ return tile;+ };+ const findBadge = (tile: HTMLElement, text: string) =>+ Array.from(tile.querySelectorAll<HTMLElement>('.gallery-thumb-overlay')).find(+ (element) => element.textContent === text+ );+ const opacityOf = (element: HTMLElement | undefined) => (element ? getComputedStyle(element).opacity : null);++ // Seeded so a reveal right after mount does not race the availability fetch.+ const setIndexAvailability = (availability: ImageIndexAvailability) => {+ mocks.indexAvailability = availability;+ queryClient?.setQueryData(['test-image-index-availability'], availability);+ };++ beforeEach(() => setIndexAvailability({ modelName: null, state: 'ready' }));++ it('reveals the hovered item label in step with its dimensions and star', async () => {+ mocks.getItemLabel.mockImplementation((item) => Promise.resolve(item.name === 'a.png' ? 'sunset' : 'forest'));+ await renderGallery(createGallery({ items: [createItem('image', 'a.png'), createItem('image', 'b.png')] }));++ // Nothing is requested for tiles that were only rendered.+ expect(mocks.getItemLabel).not.toHaveBeenCalled();++ const tile = getTile('a.png');+ await userEvent.hover(tile);++ expect(mocks.getItemLabel).toHaveBeenCalledWith({ kind: 'image', name: 'a.png' });+ const dimensions = findBadge(tile, '128x96');+ const star = tile.querySelector<HTMLElement>('button[aria-label="Star a.png"]') ?? undefined;+ await vi.waitFor(() =>+ expect([findBadge(tile, 'sunset'), dimensions, star].map(opacityOf)).toEqual(['1', '1', '1'])+ );++ await userEvent.hover(getTile('b.png'));++ await vi.waitFor(() =>+ expect([findBadge(tile, 'sunset'), dimensions, star].map(opacityOf)).toEqual(['0', '0', '0'])+ );+ await vi.waitFor(() => expect(opacityOf(findBadge(getTile('b.png'), 'forest'))).toBe('1'));+ });++ it('reveals the label for keyboard focus as well as hover', async () => {+ mocks.getItemLabel.mockResolvedValue('sunset');+ await renderGallery(createGallery({ items: [createItem('image', 'a.png')] }));++ await interact(() => getButton('Select a.png for preview').focus());++ await vi.waitFor(() => expect(opacityOf(findBadge(getTile('a.png'), 'sunset'))).toBe('1'));+ });++ it('adds nothing for an unlabeled item', async () => {+ mocks.getItemLabel.mockResolvedValue(null);+ await renderGallery(createGallery({ items: [createItem('image', 'a.png')] }));++ await userEvent.hover(getTile('a.png'));+ await vi.waitFor(() => expect(mocks.getItemLabel).toHaveBeenCalled());+ await interact(noop);++ // Dimensions and star only.+ expect(getTile('a.png').querySelectorAll('.gallery-thumb-overlay')).toHaveLength(2);+ });++ it('never asks for labels while the image index is not ready', async () => {+ setIndexAvailability({ modelName: 'clip', state: 'model_missing' });+ mocks.getItemLabel.mockResolvedValue('sunset');+ await renderGallery(createGallery({ items: [createItem('image', 'a.png')] }));++ await userEvent.hover(getTile('a.png'));+ await interact(noop);++ expect(mocks.getItemLabel).not.toHaveBeenCalled();+ expect(findBadge(getTile('a.png'), 'sunset')).toBeUndefined();+ });+});+describe('GalleryImageGrid range selection', () => {const orderedRefs: GalleryItemRef[] = [{ kind: 'image', name: 'first.png' },diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex a6c98a6f77..2d5b729ae2 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -9,8 +9,9 @@ import {type GalleryRevealRequest,} from '@features/gallery/core/selection';import { isDateBoardId } from '@features/gallery/data/backend';-import { GALLERY_PAGE_SIZE } from '@features/gallery/data/queries';+import { GALLERY_PAGE_SIZE, imageIndexAvailabilityOptions } from '@features/gallery/data/queries';import { Button, DropZone } from '@platform/ui';+import { useQuery } from '@tanstack/react-query';import { ChevronRightIcon, StarIcon, UploadIcon } from 'lucide-react';import {useCallback,@@ -198,7 +199,15 @@ const GalleryStarredSection = ({export const GalleryImageGrid = () => {const { t } = useTranslation();const { actions, gallery, isWindowTruncated, itemActions, region, starredStrip } = useGalleryWidget();- const { gallery: galleryCommands, ImageContextMenu, followedProgressSessionId, progressSessions } = useGalleryUi();+ const {+ gallery: galleryCommands,+ getItemLabel,+ ImageContextMenu,+ followedProgressSessionId,+ progressSessions,+ } = useGalleryUi();+ const { data: indexAvailability } = useQuery(imageIndexAvailabilityOptions());+ const getReadyItemLabel = indexAvailability?.state === 'ready' ? getItemLabel : null;const [isDropActive, setIsDropActive] = useState(false);const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(region) ?? 0);const dragDepthRef = useRef(0);@@ -555,6 +564,7 @@ export const GalleryImageGrid = () => {}fit={thumbnailFit}getDragItems={getDragItems}+ getItemLabel={getReadyItemLabel}isPrimary={!isFollowingLive && itemKey === gallery.selectedItemKey}isSelected={!isFollowingLive && selectedItemKeys.has(itemKey)}item={item}@@ -568,6 +578,7 @@ export const GalleryImageGrid = () => {gallery.compareImageKey,gallery.selectedItemKey,getDragItems,+ getReadyItemLabel,handleThumbnailClick,handleThumbnailContextMenu,handleToggleStarred,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsxindex 35e94cb412..c8f6b46eae 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx@@ -69,6 +69,7 @@ const adapter: GalleryUiAdapter = {},galleryValues: {},generateValues: {},+ getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,progressSessions: [],pinnedProgressSessionId: null,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsxindex 555dc9238a..e9d13b614a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx@@ -133,6 +133,7 @@ const adapter = {pinnedProgressSessionId: null,followedProgressSessionId: null,liveFollowEnabled: false,+ getItemLabel: () => Promise.resolve(null),followProgressSession: vi.fn(),antialiasProgressImages: false,widgets: { openGallery: vi.fn(() => true), patchGalleryValues: vi.fn() },diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsxindex 5f24186f43..1756125c55 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx@@ -1,7 +1,7 @@import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';import type { GalleryThumbnailFit } from '@features/gallery/core/settings';-import { Badge } from '@chakra-ui/react';+import { Badge, chakra } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';import { CSS } from '@dnd-kit/utilities';import { formatGalleryVideoDuration, toGalleryItemRef } from '@features/gallery/core/items';@@ -27,6 +27,14 @@ const PREVIEW_IMAGE_STYLE = {width: '100%',} as const;+/** Leaves room for the star button in the opposite corner. */+const LABEL_MAX_WIDTH = 'calc(100% - 2.25rem)';+/**+ * A label that resolves mid-hover mounts already revealed; fade it in like the overlays it joins. Important+ * because the tile's hover reveal outranks a single-class rule.+ */+const LABEL_CSS = { '@starting-style': { opacity: '0 !important' } } as const;+const THUMBNAIL_BUTTON_STYLE = {background: 'transparent',border: 0,@@ -46,6 +54,7 @@ const GalleryThumbnail = ({dragItems,dragScope,fit,+ getItemLabel,isPrimary,isSelected,item,@@ -59,6 +68,8 @@ const GalleryThumbnail = ({/** Separates this gallery's drags from another instance showing the same item. */dragScope: string;fit: GalleryThumbnailFit;+ /** Null while image-map labels are unavailable. */+ getItemLabel: ((item: GalleryItemRef) => Promise<string | null>) | null;isPrimary: boolean;isSelected: boolean;item: GalleryItem;@@ -147,6 +158,15 @@ const GalleryThumbnail = ({}}, []);+ // Fetched on reveal rather than per rendered tile: labels cost a request each, and the cache makes repeat+ // reveals free while still picking up a rebuilt vocabulary.+ const [label, setLabel] = useState<string | null>(null);+ const handleRevealLabel = useCallback(() => {+ if (getItemLabel) {+ void getItemLabel(toGalleryItemRef(item)).then(setLabel);+ }+ }, [getItemLabel, item]);+const handleToggleStarred = useCallback((event: MouseEvent<HTMLButtonElement>) => {event.stopPropagation();@@ -170,6 +190,8 @@ const GalleryThumbnail = ({// Allow touch panning; the hold sensor yields to scrolling and arms drag only after a sustained hold.touchAction="pan-y"onContextMenu={handleContextMenu}+ onFocus={handleRevealLabel}+ onPointerEnter={handleRevealLabel}><buttonaria-current={isPrimary ? 'true' : undefined}@@ -192,6 +214,29 @@ const GalleryThumbnail = ({style={imageStyle}/></button>+ {/* The compare role owns this corner while comparing. */}+ {label && getItemLabel && !compareRole ? (+ <Badge+ // Hover-dependent and heuristic: keep it out of the tile's accessible text, which the name already covers.+ aria-hidden="true"+ className="gallery-thumb-overlay"+ css={LABEL_CSS}+ insetInlineStart="1"+ maxW={LABEL_MAX_WIDTH}+ opacity={0}+ pointerEvents="none"+ position="absolute"+ size="xs"+ top="1"+ transition="opacity var(--wb-motion-duration-medium) ease"+ variant="solid"+ zIndex="1"+ >+ <chakra.span minW="0" truncate>+ {label}+ </chakra.span>+ </Badge>+ ) : null}{compareRole && (<BadgeinsetInlineStart="1"diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex f12391ebf7..2e75da8be4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -97,6 +97,8 @@ export interface GalleryUiAdapter {gallery: GalleryCommandsPort;galleryValues: Record<string, unknown>;generateValues: Record<string, unknown>;+ /** Resolves an item's best image-map vocabulary label, or null when it has none. */+ getItemLabel(item: GalleryItemRef): Promise<string | null>;notifications: GalleryNotificationsPort;projectId: string;projectName: string;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex 6bae550f5d..1e9ad88883 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -171,6 +171,7 @@ const adapter: GalleryUiAdapter = {},galleryValues: {},generateValues: {},+ getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,progressSessions: [],pinnedProgressSessionId: null,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex 1f47087d18..1b1d55705d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -90,6 +90,7 @@ const adapter: GalleryUiAdapter = {},galleryValues: {},generateValues: {},+ getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,progressSessions: [],pinnedProgressSessionId: null,diff --git a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsxindex 8004bc021a..216ebafdb0 100644--- a/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/videoConditioningClipRole.browser.test.tsx@@ -40,6 +40,7 @@ const galleryAdapter = {gallery: new Proxy({}, { get: () => noop }),galleryValues: {},generateValues: {},+ getItemLabel: () => Promise.resolve(null),liveFollowEnabled: false,notifications: { add: noop, reportError: noop },pinnedProgressSessionId: null,diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.tsindex 98e9fef23f..cf90d4ffb7 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts@@ -115,8 +115,31 @@ describe('image map image-label cache', () => {expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);// The vocabulary is built lazily by the index worker: a 409 can simply- // mean "not ready yet", so the cooldown must expire rather than latch.- vi.setSystemTime(Date.now() + 61_000);+ // mean "not ready yet", so the cooldown must expire rather than latch —+ // and quickly, since a warm build lands within seconds.+ vi.setSystemTime(Date.now() + 5_001);+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });+ await expect(getImageLabels({ kind: 'image', name: 'c.png' })).resolves.toEqual({+ alternates: [],+ label: 'ship',+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it('backs off a server outage for a minute', async () => {+ vi.useFakeTimers();++ try {+ mocks.apiFetchJson.mockRejectedValue(new ApiError('boom', 500));+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();++ vi.setSystemTime(Date.now() + 30_000);+ await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toBeNull();+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);++ vi.setSystemTime(Date.now() + 30_001);mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });await expect(getImageLabels({ kind: 'image', name: 'c.png' })).resolves.toEqual({alternates: [],@@ -153,6 +176,31 @@ describe('image map image-label cache', () => {});});+ it('neither answers nor caches a request that straddles a vocabulary rebuild', async () => {+ let resolveOld: (labels: { alternates: string[]; label: string }) => void = () => {};+ mocks.apiFetchJson.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve;+ })+ );+ const stale = getImageLabels({ kind: 'image', name: 'a.png' });++ clearImageLabels();+ // The rebuild releases the old claim, so a new reveal asks again.+ mocks.apiFetchJson.mockResolvedValueOnce({ alternates: [], label: 'sailboat' });+ const fresh = getImageLabels({ kind: 'image', name: 'a.png' });+ resolveOld({ alternates: [], label: 'ship' });++ await expect(stale).resolves.toBeNull();+ await expect(fresh).resolves.toEqual({ alternates: [], label: 'sailboat' });+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({+ alternates: [],+ label: 'sailboat',+ });+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);+ });+it('clears the cooldown on account switch', async () => {mocks.apiFetchJson.mockRejectedValue(new ApiError('index disabled', 409));await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.tsindex c57303edf9..d2a5ff247a 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts@@ -20,16 +20,21 @@ const labels = new Map<string, ImageMapImageLabels | null>();const inflight = new Map<string, Promise<ImageMapImageLabels | null>>();/**- * Server-wide cooldown prevents one failing request per hovered point while allowing recovery after lazy- * vocabulary build or outage.+ * Server-wide cooldowns prevent one failing request per hovered point or thumbnail while allowing recovery. A 409+ * usually means the index worker is still building the vocabulary, which on a warm disk cache lands in about a+ * second, so it backs off briefly; outages back off longer.*/-const UNAVAILABLE_COOLDOWN_MS = 60_000;+const BUILDING_COOLDOWN_MS = 5_000;+const OUTAGE_COOLDOWN_MS = 60_000;let unavailableUntil = 0;+/** Bumped by every clear so requests issued before it cannot answer or seed the cache after it. */+let generation = 0;// Clear labels and cooldown on login/logout to prevent cross-account results or backend failure state.registerAccountOwnedResource({clear: () => {+ generation += 1;labels.clear();inflight.clear();unavailableUntil = 0;@@ -42,7 +47,9 @@ registerAccountOwnedResource({* pending-build retries resume.*/export const clearImageLabels = (): void => {+ generation += 1;labels.clear();+ inflight.clear();unavailableUntil = 0;};@@ -67,25 +74,29 @@ export const getImageLabels = (item: GalleryItemRef): Promise<ImageMapImageLabel}const owner = captureAccountScope();+ const issuedIn = generation;+ // A resolution that raced an account switch or vocabulary rebuild answers for state that is gone: it must+ // neither seed the cache nor reach the caller.+ const isCurrent = () => issuedIn === generation && isAccountScopeCurrent(owner);const request = fetchImageMapImageLabels(item).then((result): ImageMapImageLabels | null => {- // A resolution that raced an account switch must not seed the next- // account's cache.- if (isAccountScopeCurrent(owner)) {- labels.set(key, result);+ if (!isCurrent()) {+ return null;}+ labels.set(key, result);return result;}).catch((error: unknown): null => {- if (!isAccountScopeCurrent(owner)) {+ if (!isCurrent()) {return null;}- if (error instanceof ApiError && (error.status === 409 || error.status >= 500)) {- // Treat 409/build and 5xx outages as temporary server-wide failures: back off without caching per-item- // results.- unavailableUntil = Date.now() + UNAVAILABLE_COOLDOWN_MS;+ if (error instanceof ApiError && error.status === 409) {+ // Build in progress (or index/vocabulary unavailable): server-wide, not per item.+ unavailableUntil = Date.now() + BUILDING_COOLDOWN_MS;+ } else if (error instanceof ApiError && error.status >= 500) {+ unavailableUntil = Date.now() + OUTAGE_COOLDOWN_MS;} else if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {// Cache definitive item misses: not indexed or not visible to this account.labels.set(key, null);@@ -95,8 +106,8 @@ export const getImageLabels = (item: GalleryItemRef): Promise<ImageMapImageLabelreturn null;}).finally(() => {- // Release only this request's claim; an account switch already cleared- // the in-flight map.+ // Release only this request's claim; a clear already emptied the+ // in-flight map.if (inflight.get(key) === request) {inflight.delete(key);}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsxindex 92883ffdcf..8cfd610602 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx@@ -89,6 +89,7 @@ describe('MapHoverCard', () => {});expect(mocks.getImageLabels).toHaveBeenCalledWith({ kind: 'video', name: 'clip.mp4' });- expect(text).toContain('clip');+ // Named apart from the cluster's tags.+ expect(text).toContain('Image tags: clip, surf');});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsxindex 053a7d6bfd..c042fa20a3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx@@ -163,7 +163,7 @@ export const MapHoverCard = ({</Text></HStack>{clusterTags ? <HoverTagsRow prefix="Cluster tags: " tags={clusterTags} /> : null}- {imageTags ? <HoverTagsRow prefix="Tags: " tags={imageTags} /> : null}+ {imageTags ? <HoverTagsRow prefix="Image tags: " tags={imageTags} /> : null}</Stack>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsxindex 1b6da0ceb5..984f109770 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx@@ -1,8 +1,11 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import type { GalleryImage, GalleryImageItem, GalleryVideoItem } from '@features/gallery';import type * as GalleryModule from '@features/gallery';+import type { ImageIndexAvailability } from '@features/gallery/data/backend';+import type * as GalleryQueriesModule from '@features/gallery/queries';import type * as IdentityModule from '@features/identity';import type { ImageActions } from '@workbench/image-actions';+import type { ImageMapImageLabels } from '@workbench/image-map/api';import { ChakraProvider } from '@chakra-ui/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';@@ -35,6 +38,19 @@ vi.mock('@features/gallery', async (importOriginal) => {},};});+const mocks = vi.hoisted(() => ({+ getImageLabels: vi.fn<() => Promise<ImageMapImageLabels | null>>(),+ indexAvailability: { modelName: null, state: 'disabled' } as ImageIndexAvailability,+}));++vi.mock('@features/gallery/queries', async (importOriginal) => ({+ ...(await importOriginal<typeof GalleryQueriesModule>()),+ imageIndexAvailabilityOptions: () => ({+ queryFn: () => mocks.indexAvailability,+ queryKey: ['test-image-index-availability'],+ }),+}));+vi.mock('@workbench/image-map/imageLabelCache', () => ({ getImageLabels: mocks.getImageLabels }));vi.mock('@features/identity', async (importOriginal) => {const actual = await importOriginal<typeof IdentityModule>();@@ -55,6 +71,7 @@ void i18n.use(initReactI18next).init({details: 'Details',graph: 'Graph',graphJsonLabel: 'Graph JSON',+ imageTags: 'Image tags:',loadingMetadata: 'Loading metadata',metadata: 'Metadata',metadataJsonLabel: 'Metadata JSON',@@ -125,6 +142,7 @@ const POSITION = { boardItemCount: 3, isLoadingBoard: false, selectedIndex: 0 };let host: HTMLDivElement;let root: Root;+let queryClient: QueryClient;const onOpenChange = vi.fn();const settle = (ms = 300) =>@@ -161,7 +179,7 @@ const Widget = ({ item }: { item: GalleryImageItem | GalleryVideoItem }) => {const render = async (item: GalleryImageItem | GalleryVideoItem) => {await act(() =>root.render(- <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <QueryClientProvider client={queryClient}><I18nextProvider i18n={i18n}><ChakraProvider value={system}><Widget item={item} />@@ -190,6 +208,9 @@ const expectBoundedByStage = () => {beforeEach(() => {onOpenChange.mockReset();+ mocks.getImageLabels.mockReset();+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ mocks.indexAvailability = { modelName: null, state: 'disabled' };host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -218,6 +239,71 @@ describe('PreviewDetailsPopover', () => {expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight + 40);});+ it('puts the image tags after the dimensions, truncating them rather than the dimensions', async () => {+ mocks.indexAvailability = { modelName: null, state: 'ready' };+ mocks.getImageLabels.mockResolvedValue({+ alternates: ['a rocky shoreline beneath dramatic evening clouds', 'waves breaking over weathered stones'],+ label: 'sunset over a coastal lighthouse',+ });+ await render(imageItem);++ // Availability, the lazily loaded cache, and the label request resolve in turn; wait rather than time them.+ const tags = await vi.waitFor(() => {+ const element = document.querySelector<HTMLElement>('[data-preview-image-tags]');+ expect(element).not.toBeNull();+ return element;+ });+ const dimensions = page.getByText('512 × 768').element();+ expect(mocks.getImageLabels).toHaveBeenCalledWith({ kind: 'image', name: 'still.png' });+ expect(tags?.textContent).toBe(+ '·Image tags: sunset over a coastal lighthouse, a rocky shoreline beneath dramatic evening clouds, waves breaking over weathered stones'+ );+ // Same header row, to the right of the dimensions, which stay whole while the tags end in an ellipsis.+ expect(tags!.getBoundingClientRect().left).toBeGreaterThan(dimensions.getBoundingClientRect().right);+ expect(Math.abs(tags!.getBoundingClientRect().top - dimensions.getBoundingClientRect().top)).toBeLessThan(2);+ expect(dimensions.scrollWidth).toBeLessThanOrEqual(dimensions.clientWidth);+ expect(tags!.scrollWidth).toBeGreaterThan(tags!.clientWidth);+ expect(getComputedStyle(tags!).textOverflow).toBe('ellipsis');+ expect(tags!.getBoundingClientRect().right).toBeLessThanOrEqual(popover().getBoundingClientRect().right);+ });++ it('withdraws the tags when the image index stops being ready', async () => {+ mocks.indexAvailability = { modelName: null, state: 'ready' };+ mocks.getImageLabels.mockResolvedValue({ alternates: [], label: 'sunset' });+ await render(imageItem);+ await vi.waitFor(() =>+ expect(document.querySelector('[data-preview-image-tags]')?.textContent).toBe('·Image tags: sunset')+ );++ await act(() => {+ queryClient.setQueryData(['test-image-index-availability'], { modelName: 'clip', state: 'model_missing' });+ });++ expect(document.querySelector('[data-preview-image-tags]')).toBeNull();+ expect(document.body.textContent).toContain('512 × 768');+ });++ it('leaves no separator behind for an item without tags', async () => {+ mocks.indexAvailability = { modelName: null, state: 'ready' };+ mocks.getImageLabels.mockResolvedValue(null);+ await render(imageItem);++ await vi.waitFor(() => expect(mocks.getImageLabels).toHaveBeenCalled());+ await settle(50);+ expect(document.querySelector('[data-preview-image-tags]')).toBeNull();+ // The header row ends at the dimensions.+ expect(page.getByText('512 × 768').element().parentElement?.textContent).toMatch(/512 × 768$/);+ });++ it('shows no tags, and asks for none, while the image index is not ready', async () => {+ mocks.getImageLabels.mockResolvedValue({ alternates: [], label: 'sunset' });+ await render(imageItem);++ expect(document.body.textContent).toContain('512 × 768');+ expect(document.querySelector('[data-preview-image-tags]')).toBeNull();+ expect(mocks.getImageLabels).not.toHaveBeenCalled();+ });+it('shows the raw metadata record and the workflow for an image, like the legacy viewer', async () => {await render(imageItem);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsxindex b3c9352c55..c6f35f5096 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx@@ -1,14 +1,16 @@import type { GalleryImage, GalleryItem } from '@features/gallery';import type { ImageActions } from '@workbench/image-actions';-import { HStack, Icon, Popover, Portal, Text } from '@chakra-ui/react';-import { formatGalleryVideoDuration } from '@features/gallery/contracts';+import { chakra, HStack, Icon, Popover, Portal, Text, VisuallyHidden } from '@chakra-ui/react';+import { formatGalleryVideoDuration, toGalleryItemKey, toGalleryItemRef } from '@features/gallery/contracts';+import { imageIndexAvailabilityOptions } from '@features/gallery/queries';import { useAuthSession } from '@features/identity';import { IconButton } from '@platform/ui/Button';import { PopoverContent } from '@platform/ui/Popover';import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { useQuery } from '@tanstack/react-query';import { InfoIcon } from 'lucide-react';-import { useCallback, useMemo, type ComponentProps } from 'react';+import { useCallback, useMemo, type ComponentProps, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import type { PreviewItemPosition } from './previewHeaderStore';@@ -17,6 +19,58 @@ import { PreviewDetails } from './PreviewMetadataPanel';type InteractOutsideHandler = NonNullable<ComponentProps<typeof Popover.Root>['onInteractOutside']>;+const HeaderSeparator = () => (+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs">+ ·+ </Text>+);++/**+ * The item's image-map tags, best first. The label cache is loaded on open, keeping it out of the editor's initial+ * graph, and answers repeat opens without a request; it owns invalidation (vocabulary rebuilds, accounts), so this+ * query keeps nothing once closed.+ */+const PreviewImageTags = ({ accountEpoch, item }: { accountEpoch: number; item: GalleryItem }): ReactNode => {+ const { t } = useTranslation();+ const { data: indexAvailability } = useQuery(imageIndexAvailabilityOptions());+ const isIndexReady = indexAvailability?.state === 'ready';+ const { data: tags } = useQuery({+ enabled: isIndexReady,+ gcTime: 0,+ queryFn: async () => {+ const { getImageLabels } = await import('@workbench/image-map/imageLabelCache');+ const labels = await getImageLabels(toGalleryItemRef(item));++ return labels ? [labels.label, ...labels.alternates].slice(0, 3) : null;+ },+ queryKey: ['preview', 'image-tags', accountEpoch, toGalleryItemKey(item)],+ retry: false,+ staleTime: 0,+ });++ // Tags answered while the index was ready must not outlive it.+ if (!isIndexReady || !tags || tags.length === 0) {+ return null;+ }++ // A zero basis gives the tags only the width the header leaves over, so they truncate before anything else and,+ // with the separator inside them, vanish whole rather than leave a dangling one.+ return (+ <Text color="fg.muted" data-preview-image-tags flex="1 1 0" fontSize="2xs" minW="0" truncate>+ <chakra.span aria-hidden="true" color="fg.subtle" marginInlineEnd="1">+ ·+ </chakra.span>+ <VisuallyHidden>{t('widgets.preview.imageTags')} </VisuallyHidden>+ {tags.map((tag, index) => (+ <chakra.span key={tag} fontWeight={index === 0 ? '600' : undefined}>+ {index > 0 ? ', ' : ''}+ {tag}+ </chakra.span>+ ))}+ </Text>+ );+};+/*** Bound Details to the media stage so long metadata scrolls without covering the filmstrip; images offer parsed* details alongside raw payload tabs.@@ -124,14 +178,13 @@ export const PreviewDetailsPopover = ({<Text color="fg.muted" flexShrink={0} fontSize="2xs" fontVariantNumeric="tabular-nums">{positionLabel}</Text>- <Text color="fg.subtle" flexShrink={0} fontSize="2xs">- ·- </Text>+ <HeaderSeparator /></>)}<Text color="fg.muted" fontSize="2xs" fontVariantNumeric="tabular-nums" truncate>{mediaLabel}</Text>+ <PreviewImageTags accountEpoch={accountEpoch} item={item} /></HStack><PreviewDetails accountEpoch={accountEpoch} actions={actions} image={image} item={item} /></Popover.Body>diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 05e61bed95..de4e41b21d 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -138,6 +138,14 @@ const WIDGET_HOST_MODULES = ['/workbench/widgets/image-map/ImageMapDataRuntime.tsx',] as const;+// Keep the Image Map data modules in one chunk. Its API is also reached through the Gallery's lazily loaded label+// cache, and without this group Rolldown splits the API out, costing every editor boot a request.+const IMAGE_MAP_DATA_MODULES = [+ '/workbench/image-map/api.ts',+ '/workbench/image-map/imageMapStore.ts',+ '/workbench/image-map/indexProgress.ts',+] as const;+// Group Canvas/Layer interaction dependencies to avoid extra text-tool activation requests.const CANVAS_LAYER_SHARED_MODULES = ['/features/workflow/core/layerWorkflow.ts',@@ -282,6 +290,12 @@ export default defineConfig({priority: 30,test: (id) => matchesAnySuffix(id, WIDGET_HOST_MODULES),},+ {+ includeDependenciesRecursively: false,+ name: 'imageMapStore',+ priority: 30,+ test: (id) => matchesAnySuffix(id, IMAGE_MAP_DATA_MODULES),+ },{// ~1 MB, only the lazy Image Map plot needs it.name: 'plotly',