Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): show indexing progress in the Image Map panel
Lincoln Stein904a0fee6222
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/api.ts b/invokeai/frontend/webv2/src/workbench/image-map/api.tsindex 4a65014de7..5f2349ecb7 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/api.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/api.ts@@ -1,5 +1,7 @@import { apiFetchJson } from '@platform/transport/http';+import type { ImageIndexCounts } from './indexProgress';+/** Mirrors the backend's ImageMapState literal. */export type ImageMapState = 'disabled' | 'model_missing' | 'empty' | 'computing' | 'ready';@@ -81,6 +83,39 @@ export const fetchImageMapPoints = async (options?: { eps?: number; minSamples?:return mapPoints(body);};+export interface ImageMapStatus {+ /** Embedding-index counts, or null: the backend omits them for non-admins. */+ index: ImageIndexCounts | null;+}++interface BackendImageMapStatusResponse {+ enabled: boolean;+ index?: { total: number; embedded: number; failed?: number } | null;+}++/**+ * Current index/projection status. Only the index counts are read here: the+ * projection half of the response duplicates what /points already carries, and+ * the counts are the one thing no other call returns.+ */+export const fetchImageMapStatus = async (): Promise<ImageMapStatus> => {+ const body = await apiFetchJson<BackendImageMapStatusResponse>('/api/v1/image_map/status');++ if (!body.index) {+ return { index: null };+ }++ const { embedded, total } = body.index;+ const failed = body.index.failed ?? 0;++ return {+ // `pending` is a computed property on the backend model and so is absent+ // from the serialized response; it is derived the same way here (failures+ // are excluded so it can still drain to zero).+ index: { embedded, failed, pending: Math.max(0, total - embedded - failed), total },+ };+};+export const requestImageMapRefresh = async (): Promise<boolean> => {const body = await apiFetchJson<{ enqueued: boolean }>('/api/v1/image_map/refresh', { method: 'POST' });diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.tsindex 6ff095e06c..edda949220 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts@@ -9,9 +9,9 @@ vi.mock('@platform/transport/http', () => ({getApiErrorMessage: (_error: unknown, fallback: string) => fallback,}));-import { fetchImageMapPoints, requestImageMapRefresh } from './api';+import { fetchImageMapPoints, fetchImageMapStatus, requestImageMapRefresh } from './api';import { CLUSTER_PALETTE, getClusterColor, NOISE_COLOR } from './clusterPalette';-import { imageMapStore, refreshImageMapPoints } from './imageMapStore';+import { ensureImageMapLoaded, imageMapStore, recordImageIndexStatus, refreshImageMapPoints } from './imageMapStore';import {ALL_POINTS_TRACE,buildAllPointsTrace,@@ -91,6 +91,7 @@ describe('image map store', () => {data: null,error: null,indexCounts: null,+ indexRate: null,loadState: 'idle',renderError: null,});@@ -289,6 +290,7 @@ describe('snapshot transitions', () => {data: null,error: 'boom',indexCounts: null,+ indexRate: null,loadState: 'error',renderError: null,});@@ -316,6 +318,7 @@ describe('snapshot transitions', () => {data: null,error: null,indexCounts: null,+ indexRate: null,loadState: 'loaded',renderError: 'The map failed to render (WebGL unavailable).',});@@ -323,3 +326,104 @@ describe('snapshot transitions', () => {expect(imageMapStore.getSnapshot().renderError).not.toBeNull();});});++const EMPTY_SNAPSHOT = {+ clusterLabels: null,+ data: null,+ error: null,+ indexCounts: null,+ indexRate: null,+ loadState: 'idle',+ renderError: null,+} as const;++describe('image map status', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ });++ it('derives the pending count the backend computes but does not serialize', async () => {+ mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: { embedded: 30, failed: 2, total: 100 } });++ const status = await fetchImageMapStatus();++ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/status');+ // Failures are excluded, exactly as `ImageIndexStatus.pending` does it, so+ // the queue can still drain to zero with images given up on.+ expect(status.index).toEqual({ embedded: 30, failed: 2, pending: 68, total: 100 });+ });++ it('has no counts for a non-admin, who is not told the aggregate totals', async () => {+ mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: null });++ expect((await fetchImageMapStatus()).index).toBeNull();+ });+});++describe('image index progress', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ imageMapStore.setSnapshot({ ...EMPTY_SNAPSHOT });+ });++ it('measures throughput across successive status reports', () => {+ recordImageIndexStatus({ embedded: 10, failed: 0, pending: 90, total: 100 }, 1_000);++ // One report is a point, not a rate; the UI says "estimating" until there+ // are two to measure between.+ expect(imageMapStore.getSnapshot().indexRate).toBeNull();++ recordImageIndexStatus({ embedded: 20, failed: 0, pending: 80, total: 100 }, 3_000);++ expect(imageMapStore.getSnapshot().indexRate).toBe(5);+ });++ it('forgets the rate once the queue drains so the next run measures its own', () => {+ recordImageIndexStatus({ embedded: 10, failed: 0, pending: 90, total: 100 }, 1_000);+ recordImageIndexStatus({ embedded: 100, failed: 0, pending: 0, total: 100 }, 3_000);++ expect(imageMapStore.getSnapshot().indexRate).toBeNull();++ // A single new image arriving later must not inherit the backfill's rate.+ recordImageIndexStatus({ embedded: 100, failed: 0, pending: 1, total: 101 }, 600_000);++ expect(imageMapStore.getSnapshot().indexRate).toBeNull();+ });++ it('seeds the counts from the status endpoint when the map first loads', async () => {+ // Status events only fire as batches complete, so a panel opened while the+ // worker is parked behind a generation would otherwise show no progress.+ mocks.apiFetchJson.mockImplementation((url: string) =>+ url.startsWith('/api/v1/image_map/status')+ ? Promise.resolve({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } })+ : Promise.resolve(BACKEND_RESPONSE)+ );++ ensureImageMapLoaded();++ await vi.waitFor(() => expect(imageMapStore.getSnapshot().indexCounts).not.toBeNull());+ expect(imageMapStore.getSnapshot().indexCounts).toEqual({ embedded: 40, failed: 0, pending: 60, total: 100 });+ });++ it('does not let a slow seed rewind counts a status event already delivered', async () => {+ let resolveStatus: (value: unknown) => void = () => {};+ mocks.apiFetchJson.mockImplementation((url: string) =>+ url.startsWith('/api/v1/image_map/status')+ ? new Promise((resolve) => {+ resolveStatus = resolve;+ })+ : Promise.resolve(BACKEND_RESPONSE)+ );++ ensureImageMapLoaded();+ recordImageIndexStatus({ embedded: 90, failed: 0, pending: 10, total: 100 }, 1_000);+ resolveStatus({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });++ // A macrotask drains everything the resolved seed queued behind it.+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });++ expect(imageMapStore.getSnapshot().indexCounts?.embedded).toBe(90);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.tsindex 6cf5fd1b59..b445c8c6c3 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts@@ -7,8 +7,10 @@ import { createExternalStore } from '@platform/state/externalStore';import { getApiErrorMessage } from '@platform/transport/http';import type { ImageMapPoints } from './api';+import type { ImageIndexCounts, IndexRateSample } from './indexProgress';-import { fetchImageMapClusterLabels, fetchImageMapPoints } from './api';+import { fetchImageMapClusterLabels, fetchImageMapPoints, fetchImageMapStatus } from './api';+import { appendRateSample, estimateRate } from './indexProgress';/*** Read model for the semantic image map, shared by the widget body and any@@ -16,20 +18,18 @@ import { fetchImageMapClusterLabels, fetchImageMapPoints } from './api';* driven by user action now and by socket events in a later runtime.*/-export interface ImageIndexCounts {- total: number;- embedded: number;- pending: number;- /** Given up on after repeated failures; excluded from `pending`. */- failed: number;-}-export interface ImageMapSnapshot {data: ImageMapPoints | null;loadState: 'idle' | 'loading' | 'loaded' | 'error';error: string | null;/** Embedding-index progress; only ever pushed to admins by the backend. */indexCounts: ImageIndexCounts | null;+ /**+ * Images embedded per second, measured from consecutive status events. Null+ * until two of them have arrived far enough apart to measure, which is what+ * the progress UI shows as "estimating" rather than a made-up time.+ */+ indexRate: number | null;/** Cluster id -> automatic label; null when unavailable (e.g. no text encoder). */clusterLabels: Record<string, string> | null;/**@@ -46,6 +46,7 @@ const EMPTY_IMAGE_MAP_SNAPSHOT: ImageMapSnapshot = {data: null,error: null,indexCounts: null,+ indexRate: null,loadState: 'idle',renderError: null,};@@ -54,6 +55,7 @@ export const imageMapStore = createExternalStore<ImageMapSnapshot>(EMPTY_IMAGE_Mlet inflight: Promise<void> | null = null;let rerunRequested = false;+let rateSamples: IndexRateSample[] = [];// The projection is per-user server state: a login/logout must drop it before// the next account's widgets can observe it.@@ -64,6 +66,7 @@ registerAccountOwnedResource({// Orphan any in-flight labels request so its completion (or failure)// cannot touch the next account's labels.labelsSequence += 1;+ rateSamples = [];imageMapStore.setSnapshot(EMPTY_IMAGE_MAP_SNAPSHOT);},name: 'image-map',@@ -221,8 +224,59 @@ const refreshClusterLabels = (data: ImageMapPoints): void => {});};+/**+ * Fold one status report into the snapshot, keeping the throughput estimate+ * that drives the ETA up to date. Both the socket event and the seeding fetch+ * below land here, so the rate is measured over whatever mix of the two+ * arrives.+ */+export const recordImageIndexStatus = (counts: ImageIndexCounts, at: number = Date.now()): void => {+ if (counts.pending === 0) {+ // The run is over. Dropping the history means the next one measures its+ // own rate from scratch instead of inheriting the tail of this one, which+ // for a backfill followed by a single new image is wildly optimistic.+ rateSamples = [];+ imageMapStore.patchSnapshot({ indexCounts: counts, indexRate: null });++ return;+ }++ rateSamples = appendRateSample(rateSamples, { at, embedded: counts.embedded });+ imageMapStore.patchSnapshot({ indexCounts: counts, indexRate: estimateRate(rateSamples) });+};++/**+ * Seed the counts from the status endpoint. Status events only fire as batches+ * complete, so without this a panel opened while the worker is parked (it+ * waits out every generation) shows no progress at all until the queue moves+ * again. Best-effort: a failure just leaves the socket to fill them in.+ */+const seedImageIndexStatus = (): void => {+ const owner = captureAccountScope();++ void fetchImageMapStatus()+ .then((status) => {+ // Non-admins get no counts at all — the totals aggregate every user's+ // images — so `index` is null for them and there is nothing to seed.+ if (status.index === null || !isAccountScopeCurrent(owner)) {+ return;+ }++ // Never over an event: those are strictly newer, and a slow seed+ // landing after one would rewind the counts the user is watching.+ if (imageMapStore.getSnapshot().indexCounts === null) {+ recordImageIndexStatus(status.index);+ }+ })+ .catch(() => {+ // Progress detail is optional chrome; the map itself reports its own+ // load failures.+ });+};+export const ensureImageMapLoaded = (): void => {if (imageMapStore.getSnapshot().loadState === 'idle') {void refreshImageMapPoints();+ seedImageIndexStatus();}};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.tsnew file mode 100644index 0000000000..ffdaa6e817--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from 'vitest';++import {+ appendRateSample,+ describeIndexProgress,+ estimateRate,+ formatDuration,+ getEtaSeconds,+ getIndexPercent,+ isIndexing,+ RATE_WINDOW_MS,+ type ImageIndexCounts,+ type IndexRateSample,+} from './indexProgress';++const counts = (overrides: Partial<ImageIndexCounts> = {}): ImageIndexCounts => ({+ embedded: 25,+ failed: 0,+ pending: 75,+ total: 100,+ ...overrides,+});++describe('index progress arithmetic', () => {+ it('reports the embedded share of the eligible images', () => {+ expect(getIndexPercent(counts())).toBe(25);+ });++ it('reports zero rather than NaN before the backend knows the total', () => {+ expect(getIndexPercent(counts({ embedded: 0, pending: 0, total: 0 }))).toBe(0);+ });++ it('clamps a total that lags behind the embedded count', () => {+ // The counts are two separate queries on the backend, so a deletion landing+ // between them can leave embedded > total for one event.+ expect(getIndexPercent(counts({ embedded: 120, total: 100 }))).toBe(100);+ });++ it('divides the outstanding work by the measured rate', () => {+ expect(getEtaSeconds(counts({ pending: 60 }), 2)).toBe(30);+ });++ it('has no estimate without a rate, and none once the queue is empty', () => {+ expect(getEtaSeconds(counts(), null)).toBeNull();+ expect(getEtaSeconds(counts(), 0)).toBeNull();+ expect(getEtaSeconds(counts({ pending: 0 }), 2)).toBeNull();+ });++ it('treats only a non-empty queue as indexing', () => {+ expect(isIndexing(null)).toBe(false);+ expect(isIndexing(counts({ pending: 0 }))).toBe(false);+ expect(isIndexing(counts())).toBe(true);+ });+});++describe('formatDuration', () => {+ it('scales the unit to the magnitude', () => {+ expect(formatDuration(45)).toBe('45s');+ expect(formatDuration(270)).toBe('4m 30s');+ expect(formatDuration(3900)).toBe('1h 05m');+ });++ it('never rounds an outstanding queue down to zero', () => {+ expect(formatDuration(0.2)).toBe('1s');+ });++ it('renders nothing for a value that is not a duration', () => {+ expect(formatDuration(Number.POSITIVE_INFINITY)).toBe('');+ expect(formatDuration(-5)).toBe('');+ });+});++describe('rate estimation', () => {+ const samples = (...entries: Array<[number, number]>): IndexRateSample[] =>+ entries.map(([at, embedded]) => ({ at, embedded }));++ it('measures images per second across the retained window', () => {+ expect(estimateRate(samples([0, 0], [1000, 4], [2000, 10]))).toBe(5);+ });++ it('has no estimate from a single sample or a stalled one', () => {+ expect(estimateRate([])).toBeNull();+ expect(estimateRate(samples([1000, 10]))).toBeNull();+ expect(estimateRate(samples([0, 10], [5000, 10]))).toBeNull();+ });++ it('drops samples that have aged out of the window', () => {+ const aged = samples([0, 0], [RATE_WINDOW_MS - 1000, 10]);+ const result = appendRateSample(aged, { at: RATE_WINDOW_MS + 1000, embedded: 20 });++ // The 0ms sample is older than the window; the estimate is the recent+ // 10 images in 2s, not the run-long average of 20 in 61s.+ expect(result).toHaveLength(2);+ expect(estimateRate(result)).toBe(5);+ });++ it('keeps an anchor when events arrive further apart than the window', () => {+ // The worker parks for the length of every generation, so a gap wider than+ // the window is routine. Trimming strictly would leave one sample and no+ // estimate at all for the rest of the run.+ const parked = samples([0, 100]);+ const result = appendRateSample(parked, { at: 5 * RATE_WINDOW_MS, embedded: 400 });++ expect(result).toHaveLength(2);+ expect(estimateRate(result)).toBeCloseTo(1);+ });++ it('restarts the history when the counts stop being comparable', () => {+ // A drop in embedded means the index was reset or images were deleted;+ // measuring across that boundary yields a negative rate.+ const result = appendRateSample(samples([0, 100], [1000, 120]), { at: 2000, embedded: 5 });++ expect(result).toEqual(samples([2000, 5]));+ expect(estimateRate(result)).toBeNull();+ });+});++describe('describeIndexProgress', () => {+ it('spells out the counts, the share and the time remaining', () => {+ const description = describeIndexProgress(counts({ embedded: 1204, pending: 3108, total: 4312 }), 12);++ expect(description.percent).toBeCloseTo(27.92, 2);+ expect(description.counts).toBe(`${(1204).toLocaleString()} of ${(4312).toLocaleString()} images`);+ expect(description.eta).toBe('About 4m 19s remaining');+ expect(description.skipped).toBeNull();+ });++ it('says it is still measuring rather than inventing a time', () => {+ expect(describeIndexProgress(counts(), null).eta).toBe('Estimating time remaining…');+ });++ it('explains images that were given up on', () => {+ expect(describeIndexProgress(counts({ failed: 3 }), null).skipped).toBe('3 skipped after repeated failures');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.ts b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.tsnew file mode 100644index 0000000000..7ab24dcbf2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.ts@@ -0,0 +1,145 @@+/**+ * Progress arithmetic for the embedding index, kept apart from both the store+ * that holds the counts and the components that draw them: throughput and the+ * time estimate derived from it are the only part with real logic in it, and+ * they are worth testing without a socket or a DOM.+ */++/** Embedding-index counts as the backend reports them. */+export interface ImageIndexCounts {+ total: number;+ embedded: number;+ pending: number;+ /** Given up on after repeated failures; excluded from `pending`. */+ failed: number;+}++/** One observation of `embedded` at a point in time, used to estimate throughput. */+export interface IndexRateSample {+ at: number;+ embedded: number;+}++/**+ * Samples older than this are dropped. The rate then reflects recent+ * throughput rather than an average over the whole run, which matters because+ * the worker parks for the length of any generation (see+ * `_wait_for_idle_generation`): a run-long average would keep charging the+ * estimate for a pause that has already ended.+ */+export const RATE_WINDOW_MS = 60_000;++/** Bound on retained samples, so a long backfill cannot grow the array without limit. */+const MAX_SAMPLES = 240;++/**+ * Add an observation, dropping the ones that have aged out of the window.+ *+ * A drop in `embedded` means the counts are no longer comparable to what came+ * before - the model changed, or images were deleted - so the history is+ * discarded rather than producing a negative (and then nonsensical) rate.+ */+export const appendRateSample = (samples: IndexRateSample[], sample: IndexRateSample): IndexRateSample[] => {+ const previous = samples.at(-1);++ if (previous && (sample.embedded < previous.embedded || sample.at < previous.at)) {+ return [sample];+ }++ const appended = [...samples, sample];+ const withinWindow = appended.filter((entry) => sample.at - entry.at <= RATE_WINDOW_MS);++ // Events can arrive further apart than the window (the worker parks while a+ // generation runs). Keeping the last two regardless leaves an anchor to+ // measure against instead of silently dropping to "no estimate".+ const retained = withinWindow.length >= 2 ? withinWindow : appended.slice(-2);++ return retained.length > MAX_SAMPLES ? retained.slice(-MAX_SAMPLES) : retained;+};++/** Images embedded per second over the retained window; null until measurable. */+export const estimateRate = (samples: IndexRateSample[]): number | null => {+ const first = samples.at(0);+ const last = samples.at(-1);++ if (!first || !last) {+ return null;+ }++ const elapsedSeconds = (last.at - first.at) / 1000;+ const embedded = last.embedded - first.embedded;++ if (elapsedSeconds <= 0 || embedded <= 0) {+ return null;+ }++ return embedded / elapsedSeconds;+};++/** Percentage of eligible images that carry an embedding, clamped to 0-100. */+export const getIndexPercent = (counts: ImageIndexCounts): number => {+ if (counts.total <= 0) {+ return 0;+ }++ return Math.min(100, Math.max(0, (counts.embedded / counts.total) * 100));+};++/** Seconds until the queue drains at the measured rate; null when it cannot be estimated. */+export const getEtaSeconds = (counts: ImageIndexCounts, rate: number | null): number | null => {+ if (rate === null || rate <= 0 || counts.pending <= 0) {+ return null;+ }++ return counts.pending / rate;+};++/** Whether there is embedding work in flight worth showing progress for. */+export const isIndexing = (counts: ImageIndexCounts | null): counts is ImageIndexCounts =>+ counts !== null && counts.pending > 0;++/** "45s", "4m 30s", "1h 05m" - the coarser the total, the coarser the unit. */+export const formatDuration = (seconds: number): string => {+ if (!Number.isFinite(seconds) || seconds < 0) {+ return '';+ }++ if (seconds < 60) {+ // Never "0s": a sub-second estimate still means work is outstanding.+ return `${Math.max(1, Math.round(seconds))}s`;+ }++ if (seconds < 3600) {+ return `${Math.floor(seconds / 60)}m ${String(Math.round(seconds % 60)).padStart(2, '0')}s`;+ }++ return `${Math.floor(seconds / 3600)}h ${String(Math.floor((seconds % 3600) / 60)).padStart(2, '0')}m`;+};++const formatCount = (value: number): string => value.toLocaleString();++export interface IndexProgressDescription {+ percent: number;+ /** e.g. "1,204 of 4,312 images" */+ counts: string;+ /** e.g. "About 4m 30s remaining", or the placeholder until a rate exists. */+ eta: string;+ /** Set only once images have been given up on. */+ skipped: string | null;+}++/**+ * The strings the progress UI shows. Assembled here rather than in the+ * components so both the panel and the footer say the same thing, and so the+ * wording is covered by the same tests as the arithmetic behind it.+ */+export const describeIndexProgress = (counts: ImageIndexCounts, rate: number | null): IndexProgressDescription => {+ const etaSeconds = getEtaSeconds(counts, rate);++ return {+ counts: `${formatCount(counts.embedded)} of ${formatCount(counts.total)} images`,+ eta: etaSeconds === null ? 'Estimating time remaining…' : `About ${formatDuration(etaSeconds)} remaining`,+ percent: getIndexPercent(counts),+ skipped: counts.failed > 0 ? `${formatCount(counts.failed)} skipped after repeated failures` : null,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.browser.test.tsxnew file mode 100644index 0000000000..a29201ab50--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.browser.test.tsx@@ -0,0 +1,77 @@+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';++import { ImageIndexProgressPanel } from './ImageIndexProgress';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const settle = (action: () => void): Promise<void> =>+ act(async () => {+ action();+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 40);+ });+ });++const render = async (+ counts: { embedded: number; failed: number; pending: number; total: number },+ rate: number | null+) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await settle(() => {+ root?.render(+ <ChakraProvider value={system}>+ <ImageIndexProgressPanel counts={counts} rate={rate} />+ </ChakraProvider>+ );+ });+};++afterEach(async () => {+ await settle(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('ImageIndexProgressPanel', () => {+ it('exposes the share done to assistive tech, not just as a painted width', async () => {+ await render({ embedded: 25, failed: 0, pending: 75, total: 100 }, 5);++ const bar = host!.querySelector('[role="progressbar"]')!;++ expect(bar.getAttribute('aria-valuenow')).toBe('25');+ expect(bar.getAttribute('aria-valuemax')).toBe('100');+ expect(bar.getAttribute('aria-label')).toBe('Image indexing progress');+ });++ it('shows the counts, the percentage and the time remaining', async () => {+ await render({ embedded: 25, failed: 0, pending: 75, total: 100 }, 5);++ const text = host!.textContent ?? '';++ expect(text).toContain('25 of 100 images');+ expect(text).toContain('25%');+ expect(text).toContain('About 15s remaining');+ });++ it('says it is measuring rather than showing a time it does not have', async () => {+ await render({ embedded: 0, failed: 0, pending: 100, total: 100 }, null);++ expect(host!.textContent).toContain('Estimating time remaining');+ });++ it('accounts for images that were given up on', async () => {+ await render({ embedded: 25, failed: 4, pending: 71, total: 100 }, 5);++ expect(host!.textContent).toContain('4 skipped after repeated failures');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsxnew file mode 100644index 0000000000..8f0d4c1d3b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx@@ -0,0 +1,79 @@+import type { ImageIndexCounts } from '@workbench/image-map/indexProgress';++import { HStack, Progress, Stack, Text } from '@chakra-ui/react';+import { Tooltip } from '@platform/ui';+import { describeIndexProgress } from '@workbench/image-map/indexProgress';++const PROGRESS_LABEL = 'Image indexing progress';++interface ImageIndexProgressProps {+ counts: ImageIndexCounts;+ /** Images per second, or null while it is still being measured. */+ rate: number | null;+}++/**+ * Backfill progress for the embedding index, shown in place of the map while+ * there is nothing to draw yet. The counts are pushed by `image_index_status`+ * (admins only, which in single-user mode is everyone), so a non-admin sees+ * the plain "nothing to map yet" message instead of a bar that never moves.+ */+export const ImageIndexProgressPanel = ({ counts, rate }: ImageIndexProgressProps) => {+ const progress = describeIndexProgress(counts, rate);++ return (+ <Stack align="center" gap="2" maxW="sm" textAlign="center" w="full">+ <Text fontWeight="semibold">Indexing your gallery</Text>+ <Text color="fg.muted" fontSize="sm">+ Your images are being embedded so they can be mapped. The map appears here on its own once enough of them are+ done — you can keep working in the meantime.+ </Text>+ <Stack gap="1" mt="2" w="full">+ <Progress.Root max={100} size="sm" value={progress.percent}>+ {/* The name goes on the track: that is the element carrying+ role="progressbar", and Chakra otherwise names it "25%", which+ tells a screen reader the number but never what it counts. */}+ <Progress.Track aria-label={PROGRESS_LABEL}>+ <Progress.Range />+ </Progress.Track>+ </Progress.Root>+ <HStack color="fg.muted" fontSize="xs" justify="space-between">+ <Text fontVariantNumeric="tabular-nums">{progress.counts}</Text>+ <Text fontVariantNumeric="tabular-nums">{Math.round(progress.percent)}%</Text>+ </HStack>+ <Text color="fg.subtle" fontSize="xs">+ {progress.eta}+ </Text>+ {progress.skipped ? (+ <Text color="fg.subtle" fontSize="xs">+ {progress.skipped}+ </Text>+ ) : null}+ </Stack>+ </Stack>+ );+};++/**+ * The same progress in one line, for the widget footer once the map itself is+ * on screen: the bar is the glanceable part, the time estimate is one hover+ * away rather than competing with the point count for the width.+ */+export const ImageIndexProgressInline = ({ counts, rate }: ImageIndexProgressProps) => {+ const progress = describeIndexProgress(counts, rate);++ return (+ <Tooltip content={`Indexing ${progress.counts} · ${progress.eta}`}>+ <HStack gap="1.5" minW="0">+ <Progress.Root max={100} minW="10" size="xs" value={progress.percent} w="10">+ <Progress.Track aria-label={PROGRESS_LABEL}>+ <Progress.Range />+ </Progress.Track>+ </Progress.Root>+ <Text fontVariantNumeric="tabular-nums" whiteSpace="nowrap">+ indexing {counts.embedded}/{counts.total}+ </Text>+ </HStack>+ </Tooltip>+ );+};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 db5f8752f3..979ec5e8e2 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@@ -44,6 +44,7 @@ describe('attachImageMapDataRuntime', () => {data: null,error: null,indexCounts: null,+ indexRate: null,loadState: 'idle',renderError: null,});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsxindex 52070b95ac..07536d943d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.tsx@@ -3,7 +3,7 @@ import type { ImageIndexStatusEvent, ImageMapProjectionReadyEvent } from '@workbimport { getAuthSession } from '@features/identity';import { useMountEffect } from '@platform/react/useMountEffect';import { socketHub } from '@platform/transport/socketHub';-import { imageMapStore, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';+import { imageMapStore, recordImageIndexStatus, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';/*** Socket-driven refresh for the image map, replacing polling: when the@@ -63,13 +63,13 @@ export const attachImageMapDataRuntime = (): (() => void) => {socketHub.on('image_index_updated', refreshIfLoaded),socketHub.on('image_index_status', (payload: never) => {const event = payload as unknown as ImageIndexStatusEvent;- imageMapStore.patchSnapshot({- indexCounts: {- embedded: event.embedded,- failed: event.failed ?? 0,- pending: event.pending,- total: event.total,- },+ // Through the store rather than a direct patch: it also folds the counts+ // into the throughput estimate the progress UI turns into a time remaining.+ recordImageIndexStatus({+ embedded: event.embedded,+ failed: event.failed ?? 0,+ pending: event.pending,+ total: event.total,});// Quiescence is the moment the point set may have changed: batch// completions, deletions, and the final sweep after failures all enddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsxindex 8aa4fb56de..ad5fefcd64 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx@@ -3,8 +3,11 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';import { HStack, Icon, Text } from '@chakra-ui/react';import { IconButton, Tooltip } from '@platform/ui';import { imageMapStore, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';+import { isIndexing } from '@workbench/image-map/indexProgress';import { RefreshCwIcon } from 'lucide-react';+import { ImageIndexProgressInline } from './ImageIndexProgress';+const handleRefresh = () => {void refreshImageMapPoints();};@@ -15,7 +18,7 @@ const handleRefresh = () => {* a manual refresh.*/export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {- const { data, indexCounts, loadState } = imageMapStore.useSnapshot();+ const { data, indexCounts, indexRate, loadState } = imageMapStore.useSnapshot();// Only the states that actually show a map. `disabled`, `model_missing` and// `empty` all carry data too, and each renders its own explanation — a@@ -25,7 +28,7 @@ export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {return null;}- const indexing = indexCounts && indexCounts.pending > 0;+ const indexing = isIndexing(indexCounts);// Once the queue drains, images given up on are the only reason the index// can settle short of `total` — without saying so the count simply stops// below the total with nothing to explain it.@@ -37,9 +40,10 @@ export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {<Text whiteSpace="nowrap">{data.pointCount} points</Text>{data.stale ? <Text whiteSpace="nowrap">· updating…</Text> : null}{indexing ? (- <Text truncate>- · indexing {indexCounts.embedded}/{indexCounts.total}- </Text>+ <>+ <Text>·</Text>+ <ImageIndexProgressInline counts={indexCounts} rate={indexRate} />+ </>) : null}{skipped ? (<Tooltip content="These images repeatedly failed to embed and were given up on.">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsxindex 2e802591bf..8cb2a6f81b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx@@ -8,9 +8,12 @@ import {refreshImageMapPoints,setClusterLabelsEnabled,} from '@workbench/image-map/imageMapStore';+import { isIndexing } from '@workbench/image-map/indexProgress';import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';import { lazy, Suspense, useEffect } from 'react';+import { ImageIndexProgressPanel } from './ImageIndexProgress';+// Lazy so the plotly bundle (its own vite chunk, ~1.5MB) loads only when the// widget is actually shown.const ImageMapPlot = lazy(() => import('./ImageMapPlot'));@@ -34,7 +37,7 @@ const plotLoadingFallback = (* selects that image in the gallery (and so in Preview).*/export const ImageMapWidgetView = (_props: WidgetViewProps) => {- const { data, error, loadState, renderError } = imageMapStore.useSnapshot();+ const { data, error, indexCounts, indexRate, loadState, renderError } = imageMapStore.useSnapshot();const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);const showClusterLabels = useWidgetValuesSelector('image-map', getImageMapShowClusterLabels);@@ -119,6 +122,18 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {);}+ // Ahead of both `computing` and the empty state: with nothing to draw yet,+ // how far the backfill has got is the only thing that answers "when will+ // there be a map?" - a spinner or "nothing to map yet" leaves a user with a+ // large gallery unable to tell progress from a stall.+ if (isIndexing(indexCounts)) {+ return (+ <Center h="full" p="6">+ <ImageIndexProgressPanel counts={indexCounts} rate={indexRate} />+ </Center>+ );+ }+if (data.state === 'computing') {return (<Center h="full">