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): add Image Map widget with plotly scatter and click-to-select
Lincoln Stein2401290a1c80
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex 63c6c1c520..03c991df77 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -57,6 +57,7 @@"i18next-http-backend": "^4.0.1","lucide-react": "^1.28.0","perfect-freehand": "^1.2.3",+ "plotly.js-gl2d-dist-min": "^3.7.0","react": "^19.2.8","react-dom": "^19.2.8","react-hook-tanstack-virtual": "^0.0.4",@@ -71,6 +72,7 @@"devDependencies": {"@rolldown/plugin-babel": "^0.2.3","@types/node": "^26.1.2",+ "@types/plotly.js": "^3.0.10","@types/react": "^19.2.18","@types/react-dom": "^19.2.4","@types/use-sync-external-store": "^1.5.0",diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yamlindex d9e25ed78f..2bce4f14f1 100644--- a/invokeai/frontend/webv2/pnpm-lock.yaml+++ b/invokeai/frontend/webv2/pnpm-lock.yaml@@ -67,6 +67,9 @@ importers:perfect-freehand:specifier: ^1.2.3version: 1.2.3+ plotly.js-gl2d-dist-min:+ specifier: ^3.7.0+ version: 3.7.0react:specifier: ^19.2.8version: 19.2.8@@ -104,6 +107,9 @@ importers:'@types/node':specifier: ^26.1.2version: 26.1.2+ '@types/plotly.js':+ specifier: ^3.0.10+ version: 3.0.13'@types/react':specifier: ^19.2.18version: 19.2.18@@ -920,6 +926,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-mWI1NZRDHDoiFiPEvUjR0P12fv21kmT8XSLrEjfNwIDahELaXXkSz38n6o+5SYsq0YEGxkK3ANqqM0cRl8uZdg==}+'@types/[email protected]':resolution: {integrity: sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==}peerDependencies:@@ -1765,6 +1774,9 @@ packages:engines: {node: '>=20'}hasBin: true+ resolution: {integrity: sha512-3vR+89HBYkuLNIx/DmIQbIG6JW+4Ok6MMuWVNYO4OsghZR2n0fB+XL241buc0YsvNWKtLV1YtRrPUiZmOdvBsw==}+resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==}engines: {node: '>=14.19.0'}@@ -2742,6 +2754,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected](@types/[email protected])':dependencies:'@types/react': 19.2.18@@ -3853,6 +3867,8 @@ snapshots:optionalDependencies:fsevents: 2.3.2+ [email protected]: {}+diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 2204c65c98..887a06dc4a 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1382,6 +1382,7 @@"diagnostics": "Diagnostics","gallery": "Gallery","generate": "Generate",+ "imageMap": "Image Map","layers": "Layers","notifications": "Notifications","preview": "Preview",diff --git a/invokeai/frontend/webv2/scripts/widget-sources.mjs b/invokeai/frontend/webv2/scripts/widget-sources.mjsindex fabb89878e..43537696c7 100644--- a/invokeai/frontend/webv2/scripts/widget-sources.mjs+++ b/invokeai/frontend/webv2/scripts/widget-sources.mjs@@ -11,6 +11,7 @@ export const WIDGET_SOURCES = new Map([['src/workbench/widgets/autosave-status/implementation.ts', 'autosave-status'],['src/workbench/widgets/canvas/implementation.ts', 'canvas'],['src/workbench/widgets/diagnostics/implementation.ts', 'diagnostics'],+ ['src/workbench/widgets/image-map/implementation.ts', 'image-map'],['src/workbench/widgets/layers/implementation.ts', 'layers'],['src/workbench/widgets/notifications/implementation.ts', 'notifications'],['src/workbench/widgets/preview/implementation.ts', 'preview'],diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.jsonindex 5e799b4807..2a4ccbc7ae 100644--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json@@ -35,6 +35,10 @@"targetOwner": "workbench","targetPath": "workbench/image-actions"},+ "image-map": {+ "targetOwner": "workbench",+ "targetPath": "workbench/image-map"+ },"launchpad": {"targetOwner": "workbench","targetPath": "workbench/launchpad"diff --git a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.tsindex 0679a3baea..8938b02c0a 100644--- a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts+++ b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts@@ -1,7 +1,10 @@import { accountLifecycle } from '@platform/state/accountLifecycle';import { describe, expect, it } from 'vitest';+import type { ImageMapPoints } from './image-map/api';+import { isHotkeyModalLayerActive, registerHotkeyModalLayer } from './hotkeys/modalLayer';+import { imageMapStore } from './image-map/imageMapStore';import { commandPaletteStore } from './palette/paletteStore';import { settingsDialogStore } from './settings/settingsDialogStore';import { getLayerPropertiesRequest, requestLayerProperties } from './widgets/layers/layerPropertiesRequestStore';@@ -13,6 +16,11 @@ describe('account-owned workbench UI stores', () => {settingsDialogStore.setSnapshot({ isOpen: true, sectionId: 'developer' });const unregisterModal = registerHotkeyModalLayer('settings');requestLayerProperties('user-a-layer', 'filter');+ // Partial stand-in: the snapshot only needs to be observably non-empty.+ imageMapStore.patchSnapshot({+ data: { pointCount: 1, state: 'ready' } as unknown as ImageMapPoints,+ loadState: 'loaded',+ });accountLifecycle.invalidate();@@ -20,6 +28,10 @@ describe('account-owned workbench UI stores', () => {expect(settingsDialogStore.getSnapshot()).toEqual({ isOpen: false, sectionId: 'appearance' });expect(isHotkeyModalLayerActive()).toBe(false);expect(getLayerPropertiesRequest()).toBeNull();+ const imageMapSnapshot = imageMapStore.getSnapshot();+ expect(imageMapSnapshot.data).toBeNull();+ expect(imageMapSnapshot.loadState).toBe('idle');+ expect(imageMapSnapshot.error).toBeNull();unregisterModal();});});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/api.ts b/invokeai/frontend/webv2/src/workbench/image-map/api.tsnew file mode 100644index 0000000000..4792531e2c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/api.ts@@ -0,0 +1,80 @@+import { apiFetchJson } from '@platform/transport/http';++/** Mirrors the backend's ImageMapState literal. */+export type ImageMapState = 'disabled' | 'model_missing' | 'empty' | 'computing' | 'ready';++export interface ImageMapPoint {+ x: number;+ y: number;+ imageName: string;+ /** DBSCAN cluster label; -1 means unclustered noise. */+ cluster: number;+}++export interface ImageMapPoints {+ points: ImageMapPoint[];+ state: ImageMapState;+ /** The accessible image set changed since this projection was computed; a refresh is pending. */+ stale: boolean;+ pointCount: number;+ /** The configured embedding model's name; only set when state is 'model_missing'. */+ modelName: string | null;+ updatedAt: string | null;+}++interface BackendImageMapPoint {+ x: number;+ y: number;+ image_name: string;+ cluster: number;+}++interface BackendImageMapPointsResponse {+ points: BackendImageMapPoint[];+ state: ImageMapState;+ stale: boolean;+ point_count: number;+ model_name?: string | null;+ updated_at: string | null;+}++const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({+ modelName: body.model_name ?? null,+ pointCount: body.point_count,+ points: body.points.map((point) => ({+ cluster: point.cluster,+ imageName: point.image_name,+ x: point.x,+ y: point.y,+ })),+ stale: body.stale,+ state: body.state,+ updatedAt: body.updated_at ?? null,+});++export const fetchImageMapPoints = async (options?: { eps?: number; minSamples?: number }): Promise<ImageMapPoints> => {+ const query = new URLSearchParams();++ if (options?.eps !== undefined) {+ query.set('eps', String(options.eps));+ }++ if (options?.minSamples !== undefined) {+ query.set('min_samples', String(options.minSamples));+ }++ // Not URLSearchParams.size: it is newer than the build's browser baseline+ // (undefined on Safari 16, which would silently drop the params).+ const queryString = query.toString();+ const body = await apiFetchJson<BackendImageMapPointsResponse>(+ `/api/v1/image_map/points${queryString ? `?${queryString}` : ''}`+ );++ return mapPoints(body);+};++export const requestImageMapRefresh = async (): Promise<boolean> => {+ const body = await apiFetchJson<{ enqueued: boolean }>('/api/v1/image_map/refresh', { method: 'POST' });++ return body.enqueued;+};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.tsnew file mode 100644index 0000000000..b30182b745--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterPalette.ts@@ -0,0 +1,33 @@+/**+ * Categorical colors for map clusters, cycled by cluster id. Modeled on+ * PhotoMapAI's cluster palette: saturated, well-separated hues that read on+ * both light and dark plot backgrounds.+ */+export const CLUSTER_PALETTE = [+ '#4E79A7',+ '#F28E2B',+ '#E15759',+ '#76B7B2',+ '#59A14F',+ '#EDC948',+ '#B07AA1',+ '#FF9DA7',+ '#9C755F',+ '#BAB0AC',+ '#86BCB6',+ '#D37295',+ '#FABFD2',+ '#B6992D',+ '#499894',+] as const;++/** Color for DBSCAN noise (cluster -1): a neutral gray, drawn dimmed. */+export const NOISE_COLOR = '#8A8A8A';++export const getClusterColor = (cluster: number): string => {+ if (cluster < 0) {+ return NOISE_COLOR;+ }++ return CLUSTER_PALETTE[cluster % CLUSTER_PALETTE.length];+};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.tsnew file mode 100644index 0000000000..3f03ae50ba--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts@@ -0,0 +1,164 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ apiFetchJson: vi.fn(),+}));++vi.mock('@platform/transport/http', () => ({+ apiFetchJson: mocks.apiFetchJson,+ getApiErrorMessage: (_error: unknown, fallback: string) => fallback,+}));++import { fetchImageMapPoints, requestImageMapRefresh } from './api';+import { CLUSTER_PALETTE, getClusterColor, NOISE_COLOR } from './clusterPalette';+import { imageMapStore, refreshImageMapPoints } from './imageMapStore';+import {+ ALL_POINTS_TRACE,+ buildAllPointsTrace,+ buildCurrentImageTrace,+ buildMapLayout,+ CURRENT_IMAGE_TRACE,+} from './imageMapTraces';++const BACKEND_RESPONSE = {+ point_count: 2,+ points: [+ { cluster: 0, image_name: 'a.png', x: 1.5, y: -2 },+ { cluster: -1, image_name: 'b.png', x: 0, y: 3 },+ ],+ stale: false,+ state: 'ready',+ updated_at: '2026-08-02 12:00:00',+};++describe('image map api', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ });++ it('maps snake_case points to camelCase', async () => {+ mocks.apiFetchJson.mockResolvedValue(BACKEND_RESPONSE);++ const result = await fetchImageMapPoints();++ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/points');+ expect(result.state).toBe('ready');+ expect(result.pointCount).toBe(2);+ expect(result.points[0]).toEqual({ cluster: 0, imageName: 'a.png', x: 1.5, y: -2 });+ });++ it('maps the model_missing state with the configured model name', async () => {+ mocks.apiFetchJson.mockResolvedValue({+ model_name: 'clip-vit-large-patch14',+ point_count: 0,+ points: [],+ stale: false,+ state: 'model_missing',+ updated_at: null,+ });++ const result = await fetchImageMapPoints();++ expect(result.state).toBe('model_missing');+ expect(result.modelName).toBe('clip-vit-large-patch14');+ });++ it('passes eps and min_samples as query params', async () => {+ mocks.apiFetchJson.mockResolvedValue({ ...BACKEND_RESPONSE, points: [] });++ await fetchImageMapPoints({ eps: 0.4, minSamples: 5 });++ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/points?eps=0.4&min_samples=5');+ });++ it('posts refresh requests', async () => {+ mocks.apiFetchJson.mockResolvedValue({ enqueued: true });++ await expect(requestImageMapRefresh()).resolves.toBe(true);+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/refresh', { method: 'POST' });+ });+});++describe('image map store', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ imageMapStore.setSnapshot({ data: null, error: null, loadState: 'idle' });+ });++ it('loads points into the snapshot', async () => {+ mocks.apiFetchJson.mockResolvedValue(BACKEND_RESPONSE);++ await refreshImageMapPoints();++ const snapshot = imageMapStore.getSnapshot();+ expect(snapshot.loadState).toBe('loaded');+ expect(snapshot.data?.points).toHaveLength(2);+ expect(snapshot.error).toBeNull();+ });++ it('records errors and keeps prior data', async () => {+ mocks.apiFetchJson.mockResolvedValue(BACKEND_RESPONSE);+ await refreshImageMapPoints();++ mocks.apiFetchJson.mockRejectedValue(new Error('boom'));+ await refreshImageMapPoints();++ const snapshot = imageMapStore.getSnapshot();+ expect(snapshot.loadState).toBe('error');+ expect(snapshot.error).toBe('Failed to load the image map');+ expect(snapshot.data?.points).toHaveLength(2);+ });+});++describe('cluster palette', () => {+ it('cycles the palette by cluster id and dims noise', () => {+ expect(getClusterColor(0)).toBe(CLUSTER_PALETTE[0]);+ expect(getClusterColor(CLUSTER_PALETTE.length)).toBe(CLUSTER_PALETTE[0]);+ expect(getClusterColor(3)).toBe(CLUSTER_PALETTE[3]);+ expect(getClusterColor(-1)).toBe(NOISE_COLOR);+ });+});++describe('trace builders', () => {+ const points = [+ { cluster: 0, imageName: 'a.png', x: 1, y: 2 },+ { cluster: -1, imageName: 'b.png', x: 3, y: 4 },+ ];++ it('builds the all-points scattergl trace with image names as customdata', () => {+ const trace = buildAllPointsTrace(points);++ expect(trace.type).toBe('scattergl');+ expect(trace.name).toBe(ALL_POINTS_TRACE);+ expect(trace.x).toEqual([1, 3]);+ expect(trace.y).toEqual([2, 4]);+ expect(trace.customdata).toEqual(['a.png', 'b.png']);+ expect((trace.marker.color as string[])[0]).toBe(getClusterColor(0));+ // Noise points are dimmed relative to clustered points.+ const opacities = trace.marker.opacity as number[];+ expect(opacities[1]).toBeLessThan(opacities[0]);+ });++ it('builds an empty gold current-image trace that stays last in z-order', () => {+ const trace = buildCurrentImageTrace();++ expect(trace.name).toBe(CURRENT_IMAGE_TRACE);+ expect(trace.x).toEqual([]);+ expect(trace.marker.color).toBe('#FFD700');+ expect(trace.marker.symbol).toBe('circle-dot');+ expect(trace.marker.size).toBe(18);+ });++ it('builds an isotropic pannable layout', () => {+ const layout = buildMapLayout();++ expect(layout.dragmode).toBe('pan');+ expect(layout.xaxis?.scaleanchor).toBe('y');+ expect(layout.plot_bgcolor).toBe('rgba(0,0,0,0)');+ // Orientation grid: lines on, labels off (no units), on both axes.+ expect(layout.xaxis?.showgrid).toBe(true);+ expect(layout.yaxis?.showgrid).toBe(true);+ expect(layout.xaxis?.showticklabels).toBe(false);+ expect(layout.yaxis?.showticklabels).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.tsnew file mode 100644index 0000000000..d1f492d1a1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts@@ -0,0 +1,91 @@+import {+ captureAccountScope,+ isAccountScopeCurrent,+ registerAccountOwnedResource,+} from '@platform/state/accountLifecycle';+import { createExternalStore } from '@platform/state/externalStore';+import { getApiErrorMessage } from '@platform/transport/http';++import type { ImageMapPoints } from './api';++import { fetchImageMapPoints } from './api';++/**+ * Read model for the semantic image map, shared by the widget body and any+ * future header/footer chrome. One store, one in-flight fetch; refreshes are+ * driven by user action now and by socket events in a later runtime.+ */++export interface ImageMapSnapshot {+ data: ImageMapPoints | null;+ loadState: 'idle' | 'loading' | 'loaded' | 'error';+ error: string | null;+}++const EMPTY_IMAGE_MAP_SNAPSHOT: ImageMapSnapshot = {+ data: null,+ error: null,+ loadState: 'idle',+};++export const imageMapStore = createExternalStore<ImageMapSnapshot>(EMPTY_IMAGE_MAP_SNAPSHOT);++let inflight: Promise<void> | null = null;++// The projection is per-user server state: a login/logout must drop it before+// the next account's widgets can observe it.+registerAccountOwnedResource({+ clear: () => {+ inflight = null;+ imageMapStore.setSnapshot(EMPTY_IMAGE_MAP_SNAPSHOT);+ },+ name: 'image-map',+});++export const refreshImageMapPoints = (): Promise<void> => {+ if (inflight) {+ return inflight;+ }++ const owner = captureAccountScope();++ if (imageMapStore.getSnapshot().loadState === 'idle') {+ imageMapStore.patchSnapshot({ loadState: 'loading' });+ }++ const refresh = fetchImageMapPoints()+ .then((data) => {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ imageMapStore.patchSnapshot({ data, error: null, loadState: 'loaded' });+ })+ .catch((error: unknown) => {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ imageMapStore.patchSnapshot({+ error: getApiErrorMessage(error, 'Failed to load the image map'),+ loadState: 'error',+ });+ })+ .finally(() => {+ // Release only this refresh's claim: an account switch already reset+ // `inflight` and may have let a fresh refresh start.+ if (inflight === refresh) {+ inflight = null;+ }+ });++ inflight = refresh;++ return refresh;+};++export const ensureImageMapLoaded = (): void => {+ if (imageMapStore.getSnapshot().loadState === 'idle') {+ void refreshImageMapPoints();+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.tsnew file mode 100644index 0000000000..1b12ee65cf--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts@@ -0,0 +1,110 @@+import type { Layout } from 'plotly.js';++import type { ImageMapPoint } from './api';++import { getClusterColor } from './clusterPalette';++/**+ * Pure trace/layout builders for the map, kept apart from the plotly host so+ * the math is testable without WebGL. Trace identity follows PhotoMapAI:+ * named traces in a fixed z-order, with "Current Image" always last so the+ * gold marker renders on top.+ */++export const ALL_POINTS_TRACE = 'All Points';+export const CURRENT_IMAGE_TRACE = 'Current Image';++/** Opacity for DBSCAN noise points (cluster -1); clustered points are solid. */+const NOISE_OPACITY = 0.25;+const POINT_OPACITY = 0.85;++export interface ScatterTrace {+ x: number[];+ y: number[];+ customdata: string[];+ mode: 'markers';+ type: 'scattergl';+ name: string;+ hoverinfo: 'none' | 'text';+ text?: string[];+ marker: {+ color: string | string[];+ opacity: number | number[];+ size: number;+ symbol?: string;+ line?: { color: string; width: number };+ };+}++export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({+ customdata: points.map((point) => point.imageName),+ hoverinfo: 'none',+ marker: {+ color: points.map((point) => getClusterColor(point.cluster)),+ opacity: points.map((point) => (point.cluster < 0 ? NOISE_OPACITY : POINT_OPACITY)),+ size: 5,+ },+ mode: 'markers',+ name: ALL_POINTS_TRACE,+ type: 'scattergl',+ x: points.map((point) => point.x),+ y: points.map((point) => point.y),+});++/**+ * The gold target marking the current gallery image. Built empty here; a later+ * PR restyles it live as the selection changes.+ */+export const buildCurrentImageTrace = (): ScatterTrace => ({+ customdata: [],+ hoverinfo: 'none',+ marker: {+ color: '#FFD700',+ line: { color: '#000000', width: 2 },+ opacity: 1,+ size: 18,+ symbol: 'circle-dot',+ },+ mode: 'markers',+ name: CURRENT_IMAGE_TRACE,+ type: 'scattergl',+ x: [],+ y: [],+});++// Theme-independent grid: visible but recessive on both light and dark+// map backgrounds; the axis origin is slightly stronger for orientation.+const GRID_LINE_COLOR = 'rgba(128, 128, 128, 0.16)';+const GRID_ZERO_COLOR = 'rgba(128, 128, 128, 0.32)';++export const buildMapLayout = (): Partial<Layout> => ({+ dragmode: 'pan',+ margin: { b: 0, l: 0, r: 0, t: 0 },+ paper_bgcolor: 'rgba(0,0,0,0)',+ plot_bgcolor: 'rgba(0,0,0,0)',+ showlegend: false,+ // Preserves the user's pan/zoom across Plotly.react data updates.+ uirevision: 'image-map',+ xaxis: {+ // Unlabeled gridlines give the eye a frame of reference when the map is+ // sparse. Mid-gray at low alpha reads on every theme background, like+ // the rest of the map's fixed styling.+ gridcolor: GRID_LINE_COLOR,+ gridwidth: 1,+ scaleanchor: 'y',+ showgrid: true,+ showticklabels: false,+ zeroline: true,+ zerolinecolor: GRID_ZERO_COLOR,+ zerolinewidth: 1,+ },+ yaxis: {+ gridcolor: GRID_LINE_COLOR,+ gridwidth: 1,+ showgrid: true,+ showticklabels: false,+ zeroline: true,+ zerolinecolor: GRID_ZERO_COLOR,+ zerolinewidth: 1,+ },+});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/plotly.d.ts b/invokeai/frontend/webv2/src/workbench/image-map/plotly.d.tsnew file mode 100644index 0000000000..b4c441fd62--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/plotly.d.ts@@ -0,0 +1,10 @@+/**+ * The partial-bundle plotly distributions ship no type declarations; re-export+ * the full plotly.js types (dev dependency @types/plotly.js) for the gl2d+ * bundle, which contains only the scatter/scattergl trace modules.+ */+declare module 'plotly.js-gl2d-dist-min' {+ import * as Plotly from 'plotly.js';++ export = Plotly;+}diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex 0351092efe..9a39ea173d 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -30,6 +30,7 @@ const defaultInstanceTypes: Record<WidgetInstanceId, WidgetTypeId> = {'gallery:bottom': 'gallery','gallery:center': 'gallery',generate: 'generate',+ 'image-map': 'image-map',upscale: 'upscale',layers: 'layers',notifications: 'notifications',@@ -170,7 +171,7 @@ export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [}),right: createRegion({activeInstanceId: 'gallery',- instanceIds: ['gallery', 'preview', 'queue', 'layers', 'diagnostics', 'project'],+ instanceIds: ['gallery', 'image-map', 'preview', 'queue', 'layers', 'diagnostics', 'project'],sizePx: 450,}),},@@ -203,7 +204,7 @@ export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [}),right: createRegion({activeInstanceId: 'layers',- instanceIds: ['layers', 'gallery', 'queue', 'preview', 'diagnostics', 'project'],+ instanceIds: ['layers', 'gallery', 'image-map', 'queue', 'preview', 'diagnostics', 'project'],sizePx: 450,}),},@@ -236,7 +237,7 @@ export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [}),right: createRegion({activeInstanceId: 'queue',- instanceIds: ['queue', 'gallery', 'layers', 'preview', 'diagnostics', 'project'],+ instanceIds: ['queue', 'gallery', 'image-map', 'layers', 'preview', 'diagnostics', 'project'],sizePx: 450,}),},diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.tsindex 88312bb8f7..7de6d45d69 100644--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts@@ -13,6 +13,7 @@ export type FirstPartyWidgetTypeId =| 'gallery'| 'generate'| 'history-controls'+ | 'image-map'| 'layers'| 'notifications'| 'preview'diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.tsindex fa2a05f964..043debc854 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts@@ -26,7 +26,7 @@ describe('widget registry', () => {it('registers first-party widget manifests without icon validation failures', () => {const widgets = registerFirstPartyWidgets();- expect(widgets).toHaveLength(14);+ expect(widgets).toHaveLength(15);expect(widgets.flatMap((widget) => widget.failure ?? [])).toEqual([]);expect(widgets.every((widget) => widget.status === 'enabled')).toBe(true);});diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.tsindex d8ee0f5d43..7537d337b9 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts@@ -15,6 +15,7 @@ import { canvasWidgetManifest } from './widgets/canvas/manifest';import { diagnosticsWidgetManifest } from './widgets/diagnostics/manifest';import { galleryWidgetManifest } from './widgets/gallery/manifest';import { generateWidgetManifest } from './widgets/generate/manifest';+import { imageMapWidgetManifest } from './widgets/image-map/manifest';import { layersWidgetManifest } from './widgets/layers/manifest';import { notificationsWidgetManifest } from './widgets/notifications/manifest';import { previewWidgetManifest } from './widgets/preview/manifest';@@ -32,6 +33,7 @@ export const firstPartyWidgetManifests: WidgetManifest[] = [canvasWidgetManifest,diagnosticsWidgetManifest,galleryWidgetManifest,+ imageMapWidgetManifest,previewWidgetManifest,projectWidgetManifest,layersWidgetManifest,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxnew file mode 100644index 0000000000..f17b3e5ce5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -0,0 +1,88 @@+import type { PlotlyHTMLElement } from 'plotly.js';++import { Box } from '@chakra-ui/react';+import { imageMapStore } from '@workbench/image-map/imageMapStore';+import { buildAllPointsTrace, buildCurrentImageTrace, buildMapLayout } from '@workbench/image-map/imageMapTraces';+import Plotly from 'plotly.js-gl2d-dist-min';+import { useEffect, useRef } from 'react';++import { useSelectMapImage } from './useSelectMapImage';++/**+ * Imperative plotly host. All plotly calls happen in effects against a ref+ * div — plotly manages its own DOM and must never render through JSX. This+ * module is lazy-loaded so the plotly bundle stays out of the app's critical+ * path.+ */+const ImageMapPlot = () => {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const points = imageMapStore.useSelector((snapshot) => snapshot.data?.points ?? null);+ const selectImage = useSelectMapImage();++ useEffect(() => {+ const container = containerRef.current;++ if (!container || points === null) {+ return;+ }++ const traces = [buildAllPointsTrace(points), buildCurrentImageTrace()];+ let disposed = false;++ void Plotly.react(container, traces as Plotly.Data[], buildMapLayout(), {+ displayModeBar: false,+ // Wheel/pinch zoom is replaced with custom handlers in a later PR;+ // plotly's own scrollZoom has long-standing Safari issues.+ scrollZoom: false,+ })+ .then((plot: PlotlyHTMLElement) => {+ if (disposed) {+ return;+ }++ plot.removeAllListeners?.('plotly_click');+ plot.on('plotly_click', (event) => {+ const imageName = event.points?.[0]?.customdata;++ if (typeof imageName === 'string') {+ selectImage(imageName);+ }+ });+ })+ .catch(() => {+ // WebGL context creation can fail (blocked GPU, context exhaustion);+ // an unhandled rejection would bypass the widget failure boundary, so+ // surface it through the store's error state instead.+ imageMapStore.patchSnapshot({ error: 'The map failed to render (WebGL unavailable).', loadState: 'error' });+ });++ return () => {+ disposed = true;+ };+ }, [points, selectImage]);++ // Track the widget frame's size; plotly does not observe its container.+ useEffect(() => {+ const container = containerRef.current;++ if (!container) {+ return;+ }++ const observer = new ResizeObserver(() => {+ if (container.offsetWidth > 0 && container.offsetHeight > 0) {+ void Plotly.Plots.resize(container);+ }+ });+ observer.observe(container);++ return () => {+ observer.disconnect();+ Plotly.purge(container);+ };+ }, []);++ return <Box ref={containerRef} h="full" minH="0" w="full" />;+};++export default ImageMapPlot;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsxnew file mode 100644index 0000000000..82128d9641--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx@@ -0,0 +1,120 @@+import type { WidgetViewProps } from '@workbench/widgetContracts';++import { Button, Center, Spinner, Stack, Text } from '@chakra-ui/react';+import { ensureImageMapLoaded, imageMapStore, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';+import { lazy, useEffect } from 'react';++// Lazy so the plotly bundle (its own vite chunk) loads only when the widget+// is actually shown; WidgetRenderer supplies the Suspense fallback.+const ImageMapPlot = lazy(() => import('./ImageMapPlot'));++const handleRefresh = () => {+ void refreshImageMapPoints();+};++/**+ * Semantic map of the gallery: every image embedded by the backend's image+ * index, projected to 2D with UMAP and colored by cluster. Clicking a point+ * selects that image in the gallery (and so in Preview).+ */+export const ImageMapWidgetView = (_props: WidgetViewProps) => {+ const { data, error, loadState } = imageMapStore.useSnapshot();++ useEffect(() => {+ ensureImageMapLoaded();+ }, []);++ // A working map beats a full-screen error: when a refresh fails but prior+ // points exist, keep showing them (the next successful refresh recovers).+ if (data && data.points.length > 0) {+ return <ImageMapPlot />;+ }++ if (loadState === 'idle' || loadState === 'loading') {+ return (+ <Center h="full">+ <Spinner size="lg" />+ </Center>+ );+ }++ if (loadState === 'error') {+ return (+ <CenteredMessage+ actionLabel="Retry"+ detail={error ?? 'Failed to load the image map.'}+ onAction={handleRefresh}+ title="Image map unavailable"+ />+ );+ }++ if (data?.state === 'model_missing') {+ const model = data.modelName ?? 'the model named by `image_index_model`';++ return (+ <CenteredMessage+ detail={`Image indexing is enabled, but the embedding model '${model}' is not installed. Install the CLIP Vision model with this name, then restart the server.`}+ title="Embedding model not installed"+ />+ );+ }++ if (!data || data.state === 'disabled') {+ return (+ <CenteredMessage+ detail="Enable `image_index_enabled` in the server configuration and restart the server to build a semantic index of your gallery."+ title="Image indexing is off"+ />+ );+ }++ if (data.state === 'computing') {+ return (+ <Center h="full">+ <Stack align="center" gap="3">+ <Spinner size="lg" />+ <Text color="fg.muted" fontSize="sm">+ Computing your image map…+ </Text>+ <Button onClick={handleRefresh} size="xs" variant="outline">+ Check again+ </Button>+ </Stack>+ </Center>+ );+ }++ return (+ <CenteredMessage+ detail="Generate or import images and they will appear here, clustered by visual similarity."+ title="Nothing to map yet"+ />+ );+};++const CenteredMessage = ({+ actionLabel,+ detail,+ onAction,+ title,+}: {+ title: string;+ detail: string;+ actionLabel?: string;+ onAction?: () => void;+}) => (+ <Center h="full" p="6">+ <Stack align="center" gap="2" maxW="sm" textAlign="center">+ <Text fontWeight="semibold">{title}</Text>+ <Text color="fg.muted" fontSize="sm">+ {detail}+ </Text>+ {actionLabel && onAction ? (+ <Button mt="2" onClick={onAction} size="xs" variant="outline">+ {actionLabel}+ </Button>+ ) : null}+ </Stack>+ </Center>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/implementation.tsnew file mode 100644index 0000000000..d6fe12186e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/implementation.ts@@ -0,0 +1,7 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { ImageMapWidgetView } from './ImageMapWidgetView';++export const widgetImplementation = {+ view: ImageMapWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.tsnew file mode 100644index 0000000000..d47c340db0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts@@ -0,0 +1,14 @@+import type { WidgetManifest } from '@workbench/widgetContracts';++import { MapIcon } from 'lucide-react';++export const imageMapWidgetManifest: WidgetManifest = {+ allowMultiple: false,+ allowedRegions: ['left', 'right', 'center'],+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },+ icon: MapIcon,+ id: 'image-map',+ label: (t) => t('widgets.labels.imageMap'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),+ version: 1,+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.tsnew file mode 100644index 0000000000..93613782c5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts@@ -0,0 +1,40 @@+import { galleryImages, legacyGeneratedImageToGalleryItem } from '@features/gallery';+import { useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useCallback, useRef } from 'react';++/**+ * Turns a map point's image name into the current gallery selection. The map+ * only knows names; the selection contract wants a full gallery item, so names+ * are hydrated through the bulk by-names resolver — always fresh, since a+ * cached DTO's star/board state can drift. A monotonic sequence guards rapid+ * clicks: only the most recent click may dispatch, so a slow fetch can never+ * overwrite a newer selection. Preview follows the gallery selection on its+ * own.+ */+export const useSelectMapImage = (): ((imageName: string) => void) => {+ const commands = useWorkbenchCommands();+ const sequenceRef = useRef(0);++ return useCallback(+ (imageName: string) => {+ const sequence = ++sequenceRef.current;++ galleryImages+ .resolveMany([imageName])+ .then((images) => {+ const image = images.at(0);++ if (!image || sequence !== sequenceRef.current) {+ return;+ }++ commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image));+ })+ .catch(() => {+ // A click on a just-deleted image, or a blip mid-backend-restart,+ // simply leaves the selection unchanged.+ });+ },+ [commands]+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 86cce4055e..4fe252e1e4 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -391,6 +391,7 @@ describe('workbench widget region defaults', () => {expect(getActiveProject(hydratedLegacyDefault).widgetRegions.right.instanceIds).toEqual(['gallery',+ 'image-map','preview','queue','layers',@@ -850,7 +851,7 @@ describe('workbench layout presets', () => {});expect(project.widgetRegions.right).toMatchObject({activeInstanceId: 'gallery',- instanceIds: ['gallery', 'preview', 'queue', 'layers', 'diagnostics', 'project'],+ instanceIds: ['gallery', 'image-map', 'preview', 'queue', 'layers', 'diagnostics', 'project'],isCollapsed: false,sizePx: 450,});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 0c7f3f6e4e..d7a98734bc 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -1097,6 +1097,7 @@ const createWidgetStates = (): WidgetStateMap => ({diagnostics: { id: 'diagnostics', label: 'Diagnostics', values: {}, version: 1 },gallery: { id: 'gallery', label: 'Gallery', values: {}, version: 1 },generate: { graphId: 'generate-graph', id: 'generate', label: 'Generate', values: {}, version: 1 },+ 'image-map': { id: 'image-map', label: 'Image Map', values: {}, version: 1 },layers: { id: 'layers', label: 'Layers', values: {}, version: 1 },notifications: { id: 'notifications', label: 'Notifications', values: {}, version: 1 },preview: { id: 'preview', label: 'Preview', values: {}, version: 1 },@@ -1139,6 +1140,7 @@ const defaultWidgetInstanceTypes: Record<WidgetInstanceId, WidgetTypeId> = {'gallery:bottom': 'gallery','gallery:center': 'gallery',generate: 'generate',+ 'image-map': 'image-map',upscale: 'upscale',layers: 'layers',notifications: 'notifications',diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 0ef51316ba..7066300df5 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -158,6 +158,13 @@ export default defineConfig({priority: 30,test: (id) => matchesAnySuffix(id, WORKBENCH_TOPBAR_MODULES),},+ {+ // Plotly is large (~1MB min) and only used by the lazy-loaded+ // Image Map plot; keep it out of the eager vendor chunk.+ name: 'plotly',+ priority: 30,+ test: (id) => id.includes('plotly') && id.includes('node_modules'),+ },{name: getLegacyChunkName,},