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(ui): rich cluster-info hover cards on the image map
Lincoln Stein62b14bda36fd
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex d6834d07bf..204ebc07b1 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -779,6 +779,95 @@ async def get_image_map_cluster_labels()+class ImageMapImageLabelsResponse(BaseModel):+ """The best vocabulary labels for one image."""++ label: str = Field(description="Best-matching vocabulary phrase")+ alternates: list[str] = Field(description="Runner-up phrases")+ score: float = Field(description="Cosine similarity of the best phrase to the image's embedding")+++@image_map_router.get(+ "/image_labels", operation_id="get_image_map_image_labels", response_model=ImageMapImageLabelsResponse+)+async def get_image_map_image_labels(+ current_user: CurrentUserOrDefault,+ image_name: str = Query(description="The image to label"),+ top_k: int = Query(default=3, ge=1, le=10, description="Number of candidate labels"),+) -> ImageMapImageLabelsResponse:+ """Labels one image with the vocabulary phrases most similar to its stored embedding.++ Serves map hover cards, so it only covers images the index has embedded;+ an unindexed image (assets, intermediates, not-yet-indexed) is a 404+ rather than an on-demand embed — a hover must never queue encoder work.+ Requires the embedding model's text encoder, like /cluster_labels.+ """+ services = ApiDependencies.invoker.services+ model_id = services.image_index.model_id+ if model_id is None:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="The image index is not enabled")++ assert_image_read_access(image_name, current_user)++ try:+ vocabulary, vocab_embeddings = await asyncio.to_thread(services.image_index.get_vocab_embeddings)+ except TextSearchUnavailableError as e:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))+ if not vocabulary:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="The labeling vocabulary is empty")++ # A BLOB read and a SQLite transaction; off the event loop like the+ # clustering endpoints, since this one fires per hovered point.+ #+ # A stored row whose blob length disagrees with its `dim` column raises out+ # of `blob_to_embedding`, and a row whose dim disagrees with the vocabulary+ # matrix raises out of the matmul below. Both are this one image's data+ # being unusable, so both answer 404 like the degenerate-vector case — an+ # unhandled 500 here would refire on every hover of that point, which is+ # once per pointer sweep rather than once per user action.+ try:+ found, matrix = await asyncio.to_thread(services.image_index_records.get_embeddings, [image_name], model_id)+ if not found:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND, detail="This image has no stored embedding to label"+ )++ # float64 for the norm, and a degenerate row is refused rather than+ # passed through — exactly as `_normalize_query_vector` does for search+ # queries. Dividing by a zero or non-finite norm makes every score NaN,+ # and `argpartition` then returns arbitrary rows: the card would present+ # three unrelated vocabulary phrases as this image's tags, with a+ # `score` that serializes as JSON null against a schema that declares it+ # a float. The writer rejects such rows now, but ones predating that+ # guard are still out there — the same assumption this file already+ # makes about cached coords.+ vector = matrix[0]+ norm = float(np.linalg.norm(vector.astype(np.float64)))+ if not np.isfinite(norm) or norm == 0.0:+ raise ValueError("degenerate stored embedding")++ scores = vocab_embeddings @ (vector / norm).astype(vocab_embeddings.dtype)+ except HTTPException:+ raise+ except ValueError:+ services.logger.warning(f"Image map: cannot label '{image_name}' from its stored embedding", exc_info=True)+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND, detail="This image's stored embedding cannot be labeled"+ )++ # Bounded by the score vector too, not just the phrase list: a cached vocab+ # matrix shorter than its phrase list would otherwise put `kth` out of+ # bounds and 500.+ count = min(top_k, len(vocabulary), int(scores.shape[0]))+ top = np.argpartition(-scores, count - 1)[:count]+ top = top[np.argsort(-scores[top])]+ return ImageMapImageLabelsResponse(+ label=vocabulary[int(top[0])],+ alternates=[vocabulary[int(index)] for index in top[1:]],+ score=float(scores[int(top[0])]),+ )++@image_map_router.post("/refresh",operation_id="refresh_image_map",diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 7b12ab4173..25736e5f7b 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -6576,6 +6576,68 @@}}},+ "/api/v1/image_map/image_labels": {+ "get": {+ "tags": ["image_map"],+ "summary": "Get Image Map Image Labels",+ "description": "Labels one image with the vocabulary phrases most similar to its stored embedding.\n\nServes map hover cards, so it only covers images the index has embedded;\nan unindexed image (assets, intermediates, not-yet-indexed) is a 404\nrather than an on-demand embed \u2014 a hover must never queue encoder work.\nRequires the embedding model's text encoder, like /cluster_labels.",+ "operationId": "get_image_map_image_labels",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "image_name",+ "in": "query",+ "required": true,+ "schema": {+ "type": "string",+ "description": "The image to label",+ "title": "Image Name"+ },+ "description": "The image to label"+ },+ {+ "name": "top_k",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 10,+ "minimum": 1,+ "description": "Number of candidate labels",+ "default": 3,+ "title": "Top K"+ },+ "description": "Number of candidate labels"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ImageMapImageLabelsResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v1/image_map/refresh": {"post": {"tags": ["image_map"],@@ -42270,6 +42332,32 @@"title": "ImageMapClusterLabelsResponse","description": "Automatic labels for the current user's visible clusters, keyed by cluster id."},+ "ImageMapImageLabelsResponse": {+ "properties": {+ "label": {+ "type": "string",+ "title": "Label",+ "description": "Best-matching vocabulary phrase"+ },+ "alternates": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Alternates",+ "description": "Runner-up phrases"+ },+ "score": {+ "type": "number",+ "title": "Score",+ "description": "Cosine similarity of the best phrase to the image's embedding"+ }+ },+ "type": "object",+ "required": ["label", "alternates", "score"],+ "title": "ImageMapImageLabelsResponse",+ "description": "The best vocabulary labels for one image."+ },"ImageMapPoint": {"properties": {"x": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 95fdb99e30..72ad52c729 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1548,6 +1548,31 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/image_map/image_labels": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Get Image Map Image Labels+ * @description Labels one image with the vocabulary phrases most similar to its stored embedding.+ *+ * Serves map hover cards, so it only covers images the index has embedded;+ * an unindexed image (assets, intermediates, not-yet-indexed) is a 404+ * rather than an on-demand embed — a hover must never queue encoder work.+ * Requires the embedding model's text encoder, like /cluster_labels.+ */+ get: operations["get_image_map_image_labels"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v1/image_map/refresh": {parameters: {query?: never;@@ -17551,6 +17576,27 @@ export type components = {*/updated_at?: string | null;};+ /**+ * ImageMapImageLabelsResponse+ * @description The best vocabulary labels for one image.+ */+ ImageMapImageLabelsResponse: {+ /**+ * Label+ * @description Best-matching vocabulary phrase+ */+ label: string;+ /**+ * Alternates+ * @description Runner-up phrases+ */+ alternates: string[];+ /**+ * Score+ * @description Cosine similarity of the best phrase to the image's embedding+ */+ score: number;+ };/*** ImageMapPoint* @description One image's position on the 2D semantic map.@@ -47657,6 +47703,40 @@ export interface operations {};};};+ get_image_map_image_labels: {+ parameters: {+ query: {+ /** @description The image to label */+ image_name: string;+ /** @description Number of candidate labels */+ top_k?: number;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ImageMapImageLabelsResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };refresh_image_map: {parameters: {query?: never;diff --git a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.tsindex 262546852c..9bc48bae24 100644--- a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts+++ b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts@@ -18,7 +18,7 @@ describe('account-owned workbench UI stores', () => {requestLayerProperties('user-a-layer', 'filter');// Partial stand-in: the snapshot only needs to be observably non-empty.imageMapStore.patchSnapshot({- clusterLabels: { '0': 'cats' },+ clusterLabels: { '0': { alternates: [], label: 'cats' } },data: { pointCount: 1, state: 'ready' } as unknown as ImageMapPoints,indexCounts: { embedded: 1, failed: 0, pending: 0, total: 1 },loadState: 'loaded',diff --git a/invokeai/frontend/webv2/src/workbench/image-map/api.ts b/invokeai/frontend/webv2/src/workbench/image-map/api.tsindex 5f2349ecb7..80b4fc5894 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/api.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/api.ts@@ -122,8 +122,15 @@ export const requestImageMapRefresh = async (): Promise<boolean> => {return body.enqueued;};+export interface ImageMapClusterLabelInfo {+ /** Best-matching vocabulary phrase. */+ label: string;+ /** Runner-up phrases, best first. */+ alternates: string[];+}+export interface ImageMapClusterLabels {- labels: Record<string, string>;+ labels: Record<string, ImageMapClusterLabelInfo>;/** Fingerprint of the visible image set the labels were clustered over. */visibleHash: string | null;/** The projection these labels were computed against. */@@ -146,14 +153,35 @@ export const fetchImageMapClusterLabels = async (options?: {const queryString = query.toString();const body = await apiFetchJson<{- labels: Record<string, { label: string }>;+ labels: Record<string, { label: string; alternates?: string[] }>;visible_hash?: string | null;updated_at?: string | null;}>(`/api/v1/image_map/cluster_labels${queryString ? `?${queryString}` : ''}`);return {- labels: Object.fromEntries(Object.entries(body.labels).map(([clusterId, info]) => [clusterId, info.label])),+ labels: Object.fromEntries(+ Object.entries(body.labels).map(([clusterId, info]) => [+ clusterId,+ { alternates: info.alternates ?? [], label: info.label },+ ])+ ),updatedAt: body.updated_at ?? null,visibleHash: body.visible_hash ?? null,};};++export interface ImageMapImageLabels {+ /** Best-matching vocabulary phrase. */+ label: string;+ /** Runner-up phrases, best first. */+ alternates: string[];+}++export const fetchImageMapImageLabels = async (imageName: string): Promise<ImageMapImageLabels> => {+ const query = new URLSearchParams({ image_name: imageName });+ const body = await apiFetchJson<{ label: string; alternates?: string[] }>(+ `/api/v1/image_map/image_labels?${query.toString()}`+ );++ return { alternates: body.alternates ?? [], label: body.label };+};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.tsindex b30182b745..89c9b41200 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts@@ -31,3 +31,17 @@ export const getClusterColor = (cluster: number): string => {return CLUSTER_PALETTE[cluster % CLUSTER_PALETTE.length];};++/**+ * Whether text on this background needs to be dark to stay readable.+ * Perceived-brightness formula and threshold from PhotoMapAI, so hover cards+ * flip dark/light at the same point its popups do.+ */+export const isClusterColorLight = (hexColor: string): boolean => {+ const hex = hexColor.replace('#', '');+ const r = parseInt(hex.slice(0, 2), 16);+ const g = parseInt(hex.slice(2, 4), 16);+ const b = parseInt(hex.slice(4, 6), 16);++ return (r * 299 + g * 587 + b * 114) / 1000 > 180;+};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.tsnew file mode 100644index 0000000000..e42a4db86d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts@@ -0,0 +1,150 @@+import type * as httpModule from '@platform/transport/http';++import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ apiFetchJson: vi.fn(),+}));++vi.mock('@platform/transport/http', async (importOriginal) => ({+ ...(await importOriginal<typeof httpModule>()),+ apiFetchJson: mocks.apiFetchJson,+}));++import { accountLifecycle } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';++import { clearImageLabels, getImageLabels } from './imageLabelCache';++describe('image map image-label cache', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ // Each activation owns a fresh cache: the previous test's entries (and+ // any 409 latch) are account state and go with the account.+ accountLifecycle.invalidate();+ accountLifecycle.activate('user-a');+ });++ it('caches resolved labels per image name', async () => {+ mocks.apiFetchJson.mockResolvedValue({ alternates: ['boat', 'harbor'], label: 'ship' });++ await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: ['boat', 'harbor'], label: 'ship' });+ await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: ['boat', 'harbor'], label: 'ship' });+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it('caches a definitive per-image failure but retries transient ones', async () => {+ // 404: the image is simply not indexed; asking again cannot change that.+ mocks.apiFetchJson.mockRejectedValue(new ApiError('not indexed', 404));+ await expect(getImageLabels('a.png')).resolves.toBeNull();+ await expect(getImageLabels('a.png')).resolves.toBeNull();+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);++ // A network failure is retried on the next hover.+ mocks.apiFetchJson.mockRejectedValue(new Error('offline'));+ await expect(getImageLabels('b.png')).resolves.toBeNull();+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });+ await expect(getImageLabels('b.png')).resolves.toEqual({ alternates: [], label: 'ship' });+ });++ it('backs a server error off instead of caching it as "this image has no labels"', async () => {+ vi.useFakeTimers();++ try {+ // A backend or proxy restart mid-sweep must not permanently blank the+ // tags of every image the pointer crossed during the outage...+ mocks.apiFetchJson.mockRejectedValue(new ApiError('bad gateway', 502));+ await expect(getImageLabels('a.png')).resolves.toBeNull();+ await expect(getImageLabels('b.png')).resolves.toBeNull();+ // ...but a deterministic 500 must not refire on every hover either.+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);++ vi.setSystemTime(Date.now() + 61_000);+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });+ await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'ship' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('backs off a 409 for a cooldown, then tries again', async () => {+ vi.useFakeTimers();++ try {+ mocks.apiFetchJson.mockRejectedValue(new ApiError('still being prepared', 409));++ await expect(getImageLabels('a.png')).resolves.toBeNull();+ // Server-wide, so sweeping the map must not fire one request per point.+ await expect(getImageLabels('b.png')).resolves.toBeNull();+ 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);+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });+ await expect(getImageLabels('c.png')).resolves.toEqual({ alternates: [], label: 'ship' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps serving labels it already has while a 409 cooldown is active', async () => {+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });+ await getImageLabels('a.png');++ mocks.apiFetchJson.mockRejectedValue(new ApiError('still being prepared', 409));+ await expect(getImageLabels('b.png')).resolves.toBeNull();++ // The cooldown suppresses new requests, never cached results.+ await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'ship' });+ });++ it('drops cached labels when a vocabulary rebuild lands', async () => {+ // The phrases these are scored against are admin-editable, so a rebuild+ // makes every cached answer stale — including a cooldown that was only+ // ever waiting for that rebuild.+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });+ await getImageLabels('a.png');+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);++ clearImageLabels();++ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'sailboat' });+ await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'sailboat' });+ });++ it('clears the cooldown on account switch', async () => {+ mocks.apiFetchJson.mockRejectedValue(new ApiError('index disabled', 409));+ await expect(getImageLabels('a.png')).resolves.toBeNull();++ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });+ await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'ship' });+ });++ it('clears settled entries and stale in-flight results on account invalidation', async () => {+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'user-a-label' });+ await getImageLabels('a.png');++ // A request still in flight when the account switches must not seed the+ // next account's cache.+ let resolveLate: (labels: { alternates: string[]; label: string }) => void = () => {};+ mocks.apiFetchJson.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveLate = resolve;+ })+ );+ const late = getImageLabels('b.png');++ accountLifecycle.invalidate();+ resolveLate({ alternates: [], label: 'stale-b-label' });+ await late;++ accountLifecycle.activate('user-b');+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'user-b-label' });+ await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'user-b-label' });+ await expect(getImageLabels('b.png')).resolves.toEqual({ alternates: [], label: 'user-b-label' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.tsnew file mode 100644index 0000000000..622855bd1d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts@@ -0,0 +1,121 @@+import {+ captureAccountScope,+ isAccountScopeCurrent,+ registerAccountOwnedResource,+} from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';++import type { ImageMapImageLabels } from './api';++import { fetchImageMapImageLabels } from './api';++/**+ * Image-name → vocabulary-labels cache for map hover cards. Labels derive from+ * the image's stored embedding, which never changes, and the labeling+ * vocabulary, which does: an admin can edit the supplementary term list. So+ * results (including "no labels for this image") are cached until a+ * vocabulary rebuild lands, at which point `clearImageLabels` drops them.+ */+const labels = new Map<string, ImageMapImageLabels | null>();+const inflight = new Map<string, Promise<ImageMapImageLabels | null>>();++/**+ * How long a server-wide failure suppresses further requests. Such a failure+ * is not about this image, so hovering across the map would otherwise fire one+ * doomed request per point — but it is not necessarily permanent either: the+ * vocabulary is built lazily by the index worker, and every call until that+ * build lands answers "still being prepared". A cooldown backs off without+ * giving up.+ */+const UNAVAILABLE_COOLDOWN_MS = 60_000;++let unavailableUntil = 0;++// Labels are account-owned gallery data: drop them on login/logout so one+// account's hovers can never serve another account's labels. The cooldown is+// account state too — a different login may have a different backend.+registerAccountOwnedResource({+ clear: () => {+ labels.clear();+ inflight.clear();+ unavailableUntil = 0;+ },+ name: 'image-map-image-labels',+});++/**+ * Drop every cached label. Called when a supplementary-vocabulary rebuild+ * lands: the same phrases the cluster labels are re-fetched for also decide+ * these, and a card pairing freshly-fetched cluster tags with tags scored+ * against the previous vocabulary would be quietly inconsistent. Also clears+ * the cooldown, since a completed rebuild is exactly what a 409 was waiting+ * for.+ */+export const clearImageLabels = (): void => {+ labels.clear();+ unavailableUntil = 0;+};++export const getImageLabels = (imageName: string): Promise<ImageMapImageLabels | null> => {+ // Checked before the cooldown: labels already fetched for this image stay+ // available even while a server-wide 409 is being backed off.+ const cached = labels.get(imageName);++ if (cached !== undefined) {+ return Promise.resolve(cached);+ }++ const pending = inflight.get(imageName);++ if (pending) {+ return pending;+ }++ if (Date.now() < unavailableUntil) {+ return Promise.resolve(null);+ }++ const owner = captureAccountScope();+ const request = fetchImageMapImageLabels(imageName)+ .then((result): ImageMapImageLabels | null => {+ // A resolution that raced an account switch must not seed the next+ // account's cache.+ if (isAccountScopeCurrent(owner)) {+ labels.set(imageName, result);+ }++ return result;+ })+ .catch((error: unknown): null => {+ if (!isAccountScopeCurrent(owner)) {+ return null;+ }++ if (error instanceof ApiError && (error.status === 409 || error.status >= 500)) {+ // Server-wide and possibly temporary: a 409 means the vocabulary may+ // still be building, a 5xx that the backend is unwell. Back off rather+ // than cache anything per image — but back off, because this is driven+ // by pointer movement, and a deterministic failure would otherwise+ // refire several times a second for the rest of the session.+ unavailableUntil = Date.now() + UNAVAILABLE_COOLDOWN_MS;+ } else if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {+ // The only definitive per-image answers: not indexed, or not visible+ // to this account. Nothing about this session can change either.+ labels.set(imageName, null);+ }++ // Everything else (5xx, 429, a dropped connection) is transient and is+ // deliberately not cached: the next hover of this image retries.+ return null;+ })+ .finally(() => {+ // Release only this request's claim; an account switch already cleared+ // the in-flight map.+ if (inflight.get(imageName) === request) {+ inflight.delete(imageName);+ }+ });+ inflight.set(imageName, request);++ return request;+};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.tsindex 595c23084a..e8a10f228f 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts@@ -94,6 +94,7 @@ describe('image map store', () => {mocks.apiFetchJson.mockReset();imageMapStore.setSnapshot({clusterLabels: null,+ clusterLabelsHash: null,data: null,error: null,indexCounts: null,@@ -118,7 +119,7 @@ describe('image map store', () => {mocks.apiFetchJson.mockImplementation((url: string) => {if (url.startsWith('/api/v1/image_map/cluster_labels')) {return Promise.resolve({- labels: { '0': { label: 'cats' } },+ labels: { '0': { alternates: ['kittens', 'pets'], label: 'cats' } },updated_at: BACKEND_RESPONSE.updated_at,visible_hash: BACKEND_RESPONSE.visible_hash,});@@ -133,8 +134,46 @@ describe('image map store', () => {// with; the adaptive default could resolve differently on a drifted set.await vi.waitFor(() => {expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/cluster_labels?eps=0.42');- expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': 'cats' });+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({+ '0': { alternates: ['kittens', 'pets'], label: 'cats' },+ });+ });+ // Stamped with the set they were clustered over, so a consumer can tell+ // they still describe the drawn points.+ expect(imageMapStore.getSnapshot().clusterLabelsHash).toBe(BACKEND_RESPONSE.visible_hash);+ });++ it('marks labels stale as soon as a refresh renumbers the clusters', async () => {+ // L1: points and matching labels land together.+ mocks.apiFetchJson.mockImplementation((url: string) => {+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {+ return Promise.resolve({+ labels: { '0': { alternates: [], label: 'cats' } },+ updated_at: BACKEND_RESPONSE.updated_at,+ visible_hash: BACKEND_RESPONSE.visible_hash,+ });+ }++ return Promise.resolve(BACKEND_RESPONSE);+ });+ await refreshImageMapPoints();+ await vi.waitFor(() => {+ expect(imageMapStore.getSnapshot().clusterLabelsHash).toBe(BACKEND_RESPONSE.visible_hash);});++ // L2: a refresh over a drifted set, whose labels have not come back yet.+ // DBSCAN may have renumbered every cluster, so the labels still in the+ // store describe a clustering that is no longer drawn — the hash must say+ // so for the whole window rather than only once new labels arrive.+ const drifted = { ...BACKEND_RESPONSE, visible_hash: 'hash-2' };+ mocks.apiFetchJson.mockImplementation((url: string) =>+ url.startsWith('/api/v1/image_map/cluster_labels') ? new Promise(() => {}) : Promise.resolve(drifted)+ );+ await refreshImageMapPoints();++ const snapshot = imageMapStore.getSnapshot();+ expect(snapshot.clusterLabels).not.toBeNull();+ expect(snapshot.clusterLabelsHash).not.toBe(snapshot.data?.visibleHash);});it('discards label responses clustered over a drifted visible set', async () => {@@ -194,7 +233,7 @@ describe('image map store', () => {});await refreshImageMapPoints();await vi.waitFor(() => {- expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': 'cats' });+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': { alternates: [], label: 'cats' } });});// L1's late failure is stale: it must not wipe the labels L2 set.@@ -202,7 +241,7 @@ describe('image map store', () => {await new Promise((resolve) => {setTimeout(resolve, 0);});- expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': 'cats' });+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': { alternates: [], label: 'cats' } });});it('records errors and keeps prior data', async () => {@@ -320,6 +359,7 @@ describe('snapshot transitions', () => {// starts at null; seed a real error first so the clearing is what is tested.imageMapStore.setSnapshot({clusterLabels: null,+ clusterLabelsHash: null,data: null,error: 'boom',indexCounts: null,@@ -348,6 +388,7 @@ describe('snapshot transitions', () => {// mounting the plot, and nothing else ever resets renderError.imageMapStore.setSnapshot({clusterLabels: null,+ clusterLabelsHash: null,data: null,error: null,indexCounts: null,@@ -368,6 +409,7 @@ const drainMacrotask = (): Promise<void> =>const EMPTY_SNAPSHOT = {clusterLabels: null,+ clusterLabelsHash: null,data: null,error: null,indexCounts: null,diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.tsindex 39633e64a0..5e806516f3 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts@@ -6,7 +6,7 @@ import {import { createExternalStore } from '@platform/state/externalStore';import { getApiErrorMessage } from '@platform/transport/http';-import type { ImageMapPoints } from './api';+import type { ImageMapClusterLabelInfo, ImageMapPoints } from './api';import type { ImageIndexCounts } from './indexProgress';import { fetchImageMapClusterLabels, fetchImageMapPoints, fetchImageMapStatus } from './api';@@ -32,8 +32,21 @@ export interface ImageMapSnapshot {* whenever there are no counts.*/indexUpdatedAt: number | null;- /** Cluster id -> automatic label; null when unavailable (e.g. no text encoder). */- clusterLabels: Record<string, string> | null;+ /** Cluster id -> automatic label info; null when unavailable (e.g. no text encoder). */+ clusterLabels: Record<string, ImageMapClusterLabelInfo> | null;+ /**+ * The visible-set fingerprint `clusterLabels` were computed over, so a+ * consumer can tell whether they still describe the drawn clustering.+ *+ * Labels lag their points by a request: a refresh replaces `data` while the+ * previous clustering's labels are still in the store, and DBSCAN can+ * renumber every cluster between the two. Annotations have always accepted+ * that lag (clearing them on each refresh would blink every label off and+ * back on), but a consumer making a stronger promise — the hover card names+ * one specific cluster — compares this against `data.visibleHash` and shows+ * nothing rather than another cluster's tags.+ */+ clusterLabelsHash: string | null;/*** The plot canvas itself failed (WebGL unavailable). Distinct from `error`,* which means a fetch failed: with `error` the cached points are still worth@@ -45,6 +58,7 @@ export interface ImageMapSnapshot {const EMPTY_IMAGE_MAP_SNAPSHOT: ImageMapSnapshot = {clusterLabels: null,+ clusterLabelsHash: null,data: null,error: null,indexCounts: null,@@ -133,14 +147,30 @@ export const refreshImageMapPoints = (): Promise<void> => {let labelsSequence = 0;-const areLabelMapsEqual = (left: Record<string, string> | null, right: Record<string, string>): boolean => {+const areLabelMapsEqual = (+ left: Record<string, ImageMapClusterLabelInfo> | null,+ right: Record<string, ImageMapClusterLabelInfo>+): boolean => {if (left === null) {return false;}const keys = Object.keys(right);- return keys.length === Object.keys(left).length && keys.every((key) => left[key] === right[key]);+ return (+ keys.length === Object.keys(left).length &&+ keys.every((key) => {+ const before = left[key];+ const after = right[key];++ return (+ before !== undefined &&+ before.label === after.label &&+ before.alternates.length === after.alternates.length &&+ before.alternates.every((alternate, index) => alternate === after.alternates[index])+ );+ })+ );};/**@@ -168,7 +198,7 @@ export const setClusterLabelsEnabled = (enabled: boolean): void => {if (!enabled) {// Bump the sequence so a request already in flight cannot land after this.labelsSequence += 1;- imageMapStore.patchSnapshot({ clusterLabels: null });+ imageMapStore.patchSnapshot({ clusterLabels: null, clusterLabelsHash: null });return;}@@ -190,7 +220,7 @@ const refreshClusterLabels = (data: ImageMapPoints): void => {// sequence so an in-flight labels response cannot repopulate the labels// this clears.labelsSequence += 1;- imageMapStore.patchSnapshot({ clusterLabels: null });+ imageMapStore.patchSnapshot({ clusterLabels: null, clusterLabelsHash: null });return;}@@ -214,7 +244,7 @@ const refreshClusterLabels = (data: ImageMapPoints): void => {}if (!areLabelMapsEqual(current.clusterLabels, response.labels)) {- imageMapStore.patchSnapshot({ clusterLabels: response.labels });+ imageMapStore.patchSnapshot({ clusterLabels: response.labels, clusterLabelsHash: response.visibleHash });}}).catch(() => {@@ -222,7 +252,7 @@ const refreshClusterLabels = (data: ImageMapPoints): void => {// labels. A slow stale request failing after a newer one already set// fresh labels must not wipe them.if (sequence === labelsSequence) {- imageMapStore.patchSnapshot({ clusterLabels: null });+ imageMapStore.patchSnapshot({ clusterLabels: null, clusterLabelsHash: null });}});};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.tsindex 686113e16c..b29656770a 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts@@ -16,6 +16,7 @@ import {import { apiFetchJson } from '@platform/transport/http';import { queryOptions } from '@tanstack/react-query';+import { clearImageLabels } from './imageLabelCache';import { refetchClusterLabels } from './imageMapStore';/** Mirrors the backend's VocabBuildState literal. */@@ -142,6 +143,10 @@ const watchRebuild = (): void => {}if (body.state === 'ready') {+ // The hover card's per-image tags are scored against this same+ // vocabulary, so they go stale on exactly this event — and unlike+ // the cluster labels, nothing else in the map's flow refetches them.+ clearImageLabels();refetchClusterLabels();}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.tsindex 696f514ce9..f69ea9abb9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts@@ -41,6 +41,7 @@ describe('attachImageMapDataRuntime', () => {mocks.getAuthSession.mockReset().mockReturnValue({ user: null });imageMapStore.setSnapshot({clusterLabels: null,+ clusterLabelsHash: null,data: null,error: null,indexCounts: null,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 7890929bf3..3524468eaa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -1,7 +1,8 @@-import type { ImageMapPoint } from '@workbench/image-map/api';+import type { ImageMapClusterLabelInfo, ImageMapImageLabels, ImageMapPoint } from '@workbench/image-map/api';import type { ClusterAnnotation } from '@workbench/image-map/imageMapTraces';import type { AxisRanges } from '@workbench/image-map/imageMapViewport';import type { PlotlyHTMLElement } from 'plotly.js';+import type { CSSProperties } from 'react';import { Box } from '@chakra-ui/react';import {@@ -10,7 +11,9 @@ import {parseGalleryItemKey,} from '@features/gallery/contracts';import { attachWheelZoom } from '@workbench/image-map/attachWheelZoom';+import { getClusterColor, isClusterColorLight } from '@workbench/image-map/clusterPalette';import { collectClusterSelection } from '@workbench/image-map/clusterSelection';+import { getImageLabels } from '@workbench/image-map/imageLabelCache';import { imageMapStore } from '@workbench/image-map/imageMapStore';import {buildAllPointsTrace,@@ -31,7 +34,7 @@ import {import { getThumbnailUrl } from '@workbench/image-map/thumbnailCache';import { shallowEqual, useWidgetValuesSelector } from '@workbench/WorkbenchContext';import Plotly from 'plotly.js-gl2d-dist-min';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useMapSelection } from './useSelectMapImage';@@ -50,9 +53,11 @@ const swallow = (promise: Promise<unknown>): void => {promise.catch(() => {});};-/** Matches the preview's `maxW`/`maxH` (Chakra 40 = 10rem); used to keep it on-screen. */+/** Bounds the hover card's thumbnail. */const HOVER_PREVIEW_MAX_PX = 160;const HOVER_PREVIEW_OFFSET_PX = 14;+/** Keep the hover card at least this clear of the viewport edges. */+const HOVER_PREVIEW_EDGE_PAD_PX = 10;interface HoverPreview {imageName: string;@@ -61,6 +66,162 @@ interface HoverPreview {clientY: number;}+/**+ * Cluster identity for the hovered image, resolved from the CURRENT points.+ * Deliberately not captured at hover time: a hover survives a live refresh+ * (see `hoverPreview` below), and a refresh re-runs DBSCAN, which can renumber+ * every cluster. A frozen id would then be paired with the new clustering's+ * labels and color — a card describing a cluster the image is not in.+ */+interface HoverCluster {+ /** DBSCAN cluster of the hovered point; -1 means unclustered noise. */+ cluster: number;+ /** Points currently on the map in that cluster. */+ clusterSize: number;+}++const FIRST_TAG_STYLE: CSSProperties = { fontStyle: 'italic', fontWeight: 'bold' };+const REST_TAG_STYLE: CSSProperties = { fontStyle: 'italic' };+const HOVER_IMG_STYLE: CSSProperties = {+ borderRadius: '6px',+ display: 'block',+ margin: '0 auto',+ maxHeight: `${HOVER_PREVIEW_MAX_PX}px`,+ maxWidth: `${HOVER_PREVIEW_MAX_PX}px`,+};++/** "a, b, c" with the first tag emphasized, all on the cluster color. */+const HoverTagsRow = ({ prefix, tags, style }: { prefix: string; tags: string[]; style: CSSProperties }) => (+ <Box fontSize="xs" px="2" py="0.5" style={style} textAlign="center">+ {prefix}+ {tags.map((tag, index) => (+ <span key={tag} style={index === 0 ? FIRST_TAG_STYLE : REST_TAG_STYLE}>+ {index > 0 ? ', ' : ''}+ {tag}+ </span>+ ))}+ </Box>+);++/**+ * The hover card: thumbnail, filename, cluster identity/size, and the top+ * cluster and image tags — PhotoMapAI's popup. The card is tinted with the+ * hovered cluster's color, and the text flips dark/light to stay readable on+ * it. Its size depends on async content (the thumbnail and the lazily+ * fetched image tags), so it renders invisibly, is measured, and is then+ * placed beside the cursor — flipped to the other side when it would leave+ * the viewport. Parents key this by image name so a new hover starts clean.+ */+const MapHoverCard = ({+ preview,+ hoverCluster,+ clusterLabel,+}: {+ preview: HoverPreview;+ hoverCluster: HoverCluster;+ clusterLabel: ImageMapClusterLabelInfo | null;+}) => {+ const cardRef = useRef<HTMLDivElement | null>(null);+ const [imageLabels, setImageLabels] = useState<ImageMapImageLabels | null>(null);+ const [imageLoaded, setImageLoaded] = useState(false);+ const [position, setPosition] = useState<{ left: number; top: number } | null>(null);++ // Image tags are computed on demand (network round-trip on first hover of+ // an image; session-cached after). The card renders without the row until+ // they arrive.+ useEffect(() => {+ let cancelled = false;++ void getImageLabels(preview.imageName).then((labels) => {+ if (!cancelled) {+ setImageLabels(labels);+ }+ });++ return () => {+ cancelled = true;+ };+ }, [preview.imageName]);++ // Re-measure whenever content that changes the card's size lands.+ useLayoutEffect(() => {+ const card = cardRef.current;++ if (!card) {+ return;+ }++ const rect = card.getBoundingClientRect();+ let left = preview.clientX + HOVER_PREVIEW_OFFSET_PX;+ let top = preview.clientY + HOVER_PREVIEW_OFFSET_PX;++ if (left + rect.width > window.innerWidth - HOVER_PREVIEW_EDGE_PAD_PX) {+ left = Math.max(0, preview.clientX - rect.width - HOVER_PREVIEW_OFFSET_PX);+ }++ if (top + rect.height > window.innerHeight - HOVER_PREVIEW_EDGE_PAD_PX) {+ top = Math.max(0, preview.clientY - rect.height - HOVER_PREVIEW_OFFSET_PX);+ }++ setPosition({ left, top });+ }, [preview.clientX, preview.clientY, imageLabels, imageLoaded, clusterLabel, hoverCluster]);++ // The palette color drives every style on the card; memoized so JSX gets+ // stable objects (and text stays readable via the dark/light flip).+ const styles = useMemo(() => {+ const clusterColor = getClusterColor(hoverCluster.cluster);+ const lightBackground = isClusterColorLight(clusterColor);+ const color = lightBackground ? '#222222' : '#FFFFFF';+ const textShadow = lightBackground ? '0 1px 2px #FFFFFF' : '0 1px 2px #000000';++ return {+ band: { background: 'rgba(0, 0, 0, 0.25)', color, textShadow } satisfies CSSProperties,+ card: { background: clusterColor, border: `2px solid ${clusterColor}` } satisfies CSSProperties,+ filename: { color, textShadow, wordBreak: 'break-all' } satisfies CSSProperties,+ tags: { color, textShadow } satisfies CSSProperties,+ };+ }, [hoverCluster.cluster]);++ const clusterTags = clusterLabel ? [clusterLabel.label, ...clusterLabel.alternates].slice(0, 3) : null;+ const imageTags = imageLabels ? [imageLabels.label, ...imageLabels.alternates].slice(0, 3) : null;++ return (+ <Box+ left={`${position?.left ?? 0}px`}+ maxW="60"+ p="2"+ pb="1"+ pointerEvents="none"+ position="fixed"+ ref={cardRef}+ rounded="lg"+ shadow="lg"+ style={styles.card}+ top={`${position?.top ?? 0}px`}+ visibility={position ? 'visible' : 'hidden'}+ zIndex="tooltip"+ >+ <img+ alt={preview.imageName}+ onError={() => setImageLoaded(true)}+ onLoad={() => setImageLoaded(true)}+ src={preview.url}+ style={HOVER_IMG_STYLE}+ />+ <Box fontSize="xs" mt="1" style={styles.filename} textAlign="center">+ {preview.imageName}+ </Box>+ <Box fontSize="xs" fontWeight="bold" mt="1" py="0.5" rounded="sm" style={styles.band} textAlign="center">+ {hoverCluster.cluster < 0+ ? 'Unclustered'+ : `Cluster ${hoverCluster.cluster} (size=${hoverCluster.clusterSize})`}+ </Box>+ {clusterTags ? <HoverTagsRow prefix="Cluster tags: " style={styles.tags} tags={clusterTags} /> : null}+ {imageTags ? <HoverTagsRow prefix="Image tags: " style={styles.tags} tags={imageTags} /> : null}+ </Box>+ );+};+interface PlotElement extends PlotlyHTMLElement {_fullLayout?: {xaxis?: { range?: [number, number] };@@ -130,6 +291,14 @@ const ImageMapPlot = ({const containerRef = useRef<HTMLDivElement | null>(null);const points = imageMapStore.useSelector((snapshot) => snapshot.data?.points ?? null);const clusterLabels = imageMapStore.useSelector((snapshot) => snapshot.clusterLabels);+ // Whether those labels were computed over the clustering now drawn. The+ // annotations accept a stale set for the ~1s until fresh ones land (see the+ // relayout effect below), but the hover card names one specific cluster by+ // id, and a refresh can renumber every id — so it shows no tags rather than+ // another cluster's.+ const clusterLabelsMatchPoints = imageMapStore.useSelector(+ (snapshot) => snapshot.clusterLabelsHash !== null && snapshot.clusterLabelsHash === snapshot.data?.visibleHash+ );const selectedImageName = useWidgetValuesSelector('gallery',(values) => getSelectedGalleryImageFromValues(values)?.imageName ?? null@@ -449,6 +618,16 @@ const ImageMapPlot = ({// re-materializing every coordinate array — and, more visibly, from resetting// the highlight and current-image traces to empty, which made the gold marker// and the multi-select highlight blink off and back on with every refresh.+ // The annotation builder wants the display strings only; the full label+ // info (alternates included) feeds the hover card below.+ const annotationLabels = useMemo(+ () =>+ clusterLabels === null+ ? null+ : Object.fromEntries(Object.entries(clusterLabels).map(([clusterId, info]) => [clusterId, info.label])),+ [clusterLabels]+ );+useEffect(() => {const container = containerRef.current as PlotElement | null;@@ -456,9 +635,9 @@ const ImageMapPlot = ({return;}- fullAnnotationsRef.current = buildClusterAnnotations(points, showClusterLabels ? clusterLabels : null);+ fullAnnotationsRef.current = buildClusterAnnotations(points, showClusterLabels ? annotationLabels : null);applyDeclutteredAnnotations(container);- }, [applyDeclutteredAnnotations, clusterLabels, plotRevision, points, showClusterLabels]);+ }, [annotationLabels, applyDeclutteredAnnotations, plotRevision, points, showClusterLabels]);// Custom zoom handlers + container size tracking, attached once for the// plot's lifetime; plotly does not observe its container.@@ -534,52 +713,42 @@ const ImageMapPlot = ({// clearing on it would silently cancel live hovers — they would not come// back either, since `Plotly.react` resets hover state and no new// `plotly_hover` fires until the pointer moves.+ // Requires a live point set, not just one that does not contradict the+ // hover: `points` goes null when the account is invalidated, and the card+ // must go with it rather than keep the previous account's thumbnail on+ // screen — with a cluster identity that resolves to the noise sentinel.const hoverPreview =- pendingHoverPreview && points && !points.some((point) => point.imageName === pendingHoverPreview.imageName)- ? null- : pendingHoverPreview;-- // The widget is usually docked in a side rail, so a point near the right or- // bottom edge would otherwise put a fixed-position preview off-screen, where- // nothing can scroll it into view. Flip to the other side of the cursor when- // it does not fit.- const previewPosition = hoverPreview- ? {- left:- hoverPreview.clientX + HOVER_PREVIEW_OFFSET_PX + HOVER_PREVIEW_MAX_PX > window.innerWidth- ? Math.max(0, hoverPreview.clientX - HOVER_PREVIEW_OFFSET_PX - HOVER_PREVIEW_MAX_PX)- : hoverPreview.clientX + HOVER_PREVIEW_OFFSET_PX,- top:- hoverPreview.clientY + HOVER_PREVIEW_OFFSET_PX + HOVER_PREVIEW_MAX_PX > window.innerHeight- ? Math.max(0, hoverPreview.clientY - HOVER_PREVIEW_OFFSET_PX - HOVER_PREVIEW_MAX_PX)- : hoverPreview.clientY + HOVER_PREVIEW_OFFSET_PX,- }- : { left: 0, top: 0 };+ pendingHoverPreview && points?.some((point) => point.imageName === pendingHoverPreview.imageName)+ ? pendingHoverPreview+ : null;++ // Resolved from the live points, so the id, the size and the tint describe+ // the clustering currently drawn even after a refresh has renumbered it+ // under a stationary pointer. `hoverPreview` non-null already implies the+ // image is in `points`, so there is no missing-point fallback to take.+ const hoverCluster = useMemo((): HoverCluster => {+ if (!hoverPreview || !points) {+ return { cluster: -1, clusterSize: 0 };+ }++ const cluster = points.find((point) => point.imageName === hoverPreview.imageName)?.cluster ?? -1;++ return {+ cluster,+ clusterSize: points.reduce((count, point) => (point.cluster === cluster ? count + 1 : count), 0),+ };+ }, [hoverPreview, points]);return (<Box h="full" minH="0" position="relative" w="full"><Box ref={containerRef} h="full" w="full" />{hoverPreview ? (- <Box- borderColor="border.emphasized"- borderWidth="1px"- left={`${previewPosition.left}px`}- maxH="40"- maxW="40"- overflow="hidden"- pointerEvents="none"- position="fixed"- rounded="md"- shadow="lg"- top={`${previewPosition.top}px`}- zIndex="tooltip"- >- <img- alt={hoverPreview.imageName}- src={hoverPreview.url}- style={{ display: 'block', maxHeight: `${HOVER_PREVIEW_MAX_PX}px`, maxWidth: `${HOVER_PREVIEW_MAX_PX}px` }}- />- </Box>+ <MapHoverCard+ clusterLabel={(clusterLabelsMatchPoints ? clusterLabels?.[String(hoverCluster.cluster)] : null) ?? null}+ hoverCluster={hoverCluster}+ key={hoverPreview.imageName}+ preview={hoverPreview}+ />) : null}</Box>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsxindex a81cd6f2ec..3754ab3e16 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx@@ -49,6 +49,7 @@ const dataFor = (state: Extract<ImageMapState, 'disabled' | 'model_missing'>) =>const renderState = async (state: Extract<ImageMapState, 'disabled' | 'model_missing'>) => {imageMapStore.setSnapshot({clusterLabels: null,+ clusterLabelsHash: null,data: dataFor(state),error: null,indexCounts: null,@@ -106,6 +107,7 @@ describe('Image Map indexing activity', () => {) => {imageMapStore.setSnapshot({clusterLabels: null,+ clusterLabelsHash: null,data: {clusterEps: null,modelName: null,diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 00c135c7c0..e760eff26c 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -1207,3 +1207,147 @@ def test_vocab_writes_are_admin_only(multiuser, mock_invoker: Invoker, client: Tread = client.get("/api/v1/image_map/vocab", headers=user_headers)assert read.status_code == 200assert read.json()["terms"] == ["zebra"]+++# --- Per-image labels ---+++def test_image_labels_rank_the_vocabulary_for_one_image(mock_invoker: Invoker, client: TestClient) -> None:+ # Mostly axis 1, leaning to axis 0, with the rest strictly ordered below+ # them: "beta" wins and "alpha" is the first alternate. Every component is+ # distinct so the ranking never depends on how argpartition/argsort — both+ # unstable — happen to break a tie.+ vector = np.array([0.6, 0.8, 0.3, 0.1], dtype=np.float32)+ _save_unembedded_image(mock_invoker, "leaning.png")+ _records(mock_invoker).upsert_embedding("leaning.png", MODEL_ID, vector / np.linalg.norm(vector))++ body = client.get("/api/v1/image_map/image_labels", params={"image_name": "leaning.png"}).json()++ assert body["label"] == "beta"+ assert body["alternates"] == ["alpha", "gamma"]+ assert body["score"] == pytest.approx(0.8 / float(np.linalg.norm(vector)))++ # top_k bounds the total label count (best + alternates).+ body = client.get("/api/v1/image_map/image_labels", params={"image_name": "leaning.png", "top_k": 1}).json()+ assert body["alternates"] == []+++def test_image_labels_unindexed_image_is_404(mock_invoker: Invoker, client: TestClient) -> None:+ _save_unembedded_image(mock_invoker, "no-embedding.png")++ response = client.get("/api/v1/image_map/image_labels", params={"image_name": "no-embedding.png"})++ assert response.status_code == 404+++def test_image_labels_disabled_index_conflicts(image_index_service: FakeImageIndexService, client: TestClient) -> None:+ image_index_service._model_id = None++ assert client.get("/api/v1/image_map/image_labels", params={"image_name": "a.png"}).status_code == 409+++def test_image_labels_unavailable_text_encoder_conflicts(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ _seed_embedded_image(mock_invoker, "a.png")+ image_index_service.text_unavailable = True++ assert client.get("/api/v1/image_map/image_labels", params={"image_name": "a.png"}).status_code == 409+++def test_multiuser_image_labels_enforce_read_access(multiuser, mock_invoker: Invoker, client: TestClient) -> None:+ _create_user(mock_invoker, "[email protected]", is_admin=True)+ user1_id = _create_user(mock_invoker, "[email protected]")+ _create_user(mock_invoker, "[email protected]")+ user2_headers = _login(client, "[email protected]")++ # user1's private image: user2 must not learn its labels (or that it has any).+ _seed_embedded_image(mock_invoker, "private1.png", user_id=user1_id)+ response = client.get(+ "/api/v1/image_map/image_labels", params={"image_name": "private1.png"}, headers=user2_headers+ )++ assert response.status_code == 403+++def _seed_degenerate_embedding(mock_invoker: Invoker, image_name: str, vector: np.ndarray) -> None:+ """Write an embedding blob straight to the table, bypassing the writer's guards.++ `embedding_to_blob` refuses non-finite and all-zero vectors, but rows+ predating that guard are still in existing databases, and the read path+ validates only the blob's length.+ """+ _save_unembedded_image(mock_invoker, image_name)+ records = _records(mock_invoker)+ blob = np.ascontiguousarray(vector, dtype=np.float32).tobytes()+ with records._db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES (?, ?, ?, ?);",+ (image_name, MODEL_ID, vector.shape[0], blob),+ )+++ "vector",+ [+ pytest.param(np.full(DIM, np.nan, dtype=np.float32), id="non-finite"),+ pytest.param(np.zeros(DIM, dtype=np.float32), id="all-zero"),+ ],+)+def test_image_labels_refuse_a_degenerate_stored_embedding(+ mock_invoker: Invoker, client: TestClient, vector: np.ndarray+) -> None:+ """A degenerate row must not yield confident nonsense.++ Normalizing by a zero or non-finite norm makes every score NaN, and+ argpartition then returns arbitrary rows — three unrelated vocabulary+ phrases presented as this image's tags, with a `score` that serializes as+ JSON null against a schema declaring it a float.+ """+ _seed_degenerate_embedding(mock_invoker, "degenerate.png", vector)++ response = client.get("/api/v1/image_map/image_labels", params={"image_name": "degenerate.png"})++ assert response.status_code == 404+ assert "label" not in response.json(), "a refusal must not carry an arbitrary vocabulary phrase"+ # The row IS present: this must be the degenerate-vector refusal, not the+ # not-indexed 404, or the test would pass without exercising the guard.+ assert response.json()["detail"] == "This image's stored embedding cannot be labeled"+++def test_image_labels_corrupt_blob_is_404_not_500(mock_invoker: Invoker, client: TestClient) -> None:+ """A row whose blob length disagrees with its `dim` column.++ `blob_to_embedding` raises on it. Unhandled that is a 500, and because+ this endpoint is driven by pointer movement it would refire several times+ a second for as long as the point is hovered.+ """+ _save_unembedded_image(mock_invoker, "corrupt.png")+ records = _records(mock_invoker)+ with records._db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES (?, ?, ?, ?);",+ ("corrupt.png", MODEL_ID, DIM, np.zeros(DIM - 1, dtype=np.float32).tobytes()),+ )++ response = client.get("/api/v1/image_map/image_labels", params={"image_name": "corrupt.png"})++ assert response.status_code == 404+++def test_image_labels_dim_mismatch_with_the_vocabulary_is_404_not_500(+ mock_invoker: Invoker, client: TestClient+) -> None:+ """A stored embedding from a different-width model than the vocab matrix."""+ _save_unembedded_image(mock_invoker, "wide.png")+ records = _records(mock_invoker)+ wide = np.ones(DIM + 3, dtype=np.float32)+ with records._db.transaction() as cursor:+ cursor.execute(+ "INSERT INTO image_embeddings (image_name, model_id, dim, embedding) VALUES (?, ?, ?, ?);",+ ("wide.png", MODEL_ID, wide.shape[0], wide.tobytes()),+ )++ response = client.get("/api/v1/image_map/image_labels", params={"image_name": "wide.png"})++ assert response.status_code == 404