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
fix(webv2): report image-index progress without inventing a time remaining
Lincoln Stein6c8e71cc3875
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 283e63be5e..e78c31abdc 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1,6 +1,6 @@{- "browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome",- "capturedAt": "2026-08-18",+ "browserExecutable": "/home/lstein/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome",+ "capturedAt": "2026-08-19","routes": [{"activatedResourceBaseline": {@@ -25,13 +25,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 112,+ "domContentLoadedMedianMs": 129.2999997138977,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 112.39999999850988,- "longestTaskMaxMs": 70,+ "loadMedianMs": 129.40000009536743,+ "longestTaskMaxMs": 75,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -58,7 +58,7 @@"scriptRequestCount": 32,"totalRawBytes": 1789725},- "routeReadyMedianMs": 248.19999999925494,+ "routeReadyMedianMs": 284.8999996185303,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"},@@ -85,13 +85,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 115.5,+ "domContentLoadedMedianMs": 125.2000002861023,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 115.59999999776483,- "longestTaskMaxMs": 70,+ "loadMedianMs": 125.30000019073486,+ "longestTaskMaxMs": 72,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -118,7 +118,7 @@"scriptRequestCount": 32,"totalRawBytes": 1789725},- "routeReadyMedianMs": 268.5999999977648,+ "routeReadyMedianMs": 296.80000019073486,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"},@@ -145,15 +145,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 114.59999999776483,+ "domContentLoadedMedianMs": 127.90000009536743,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 114.80000000074506,- "longestTaskMaxMs": 98,+ "loadMedianMs": 128,+ "longestTaskMaxMs": 106,"owner": "workbench",- "projectSwitchMedianMs": 37.30000000074506,+ "projectSwitchMedianMs": 38,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -163,9 +163,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 114,- "scriptRawBytes": 3045777,+ "scriptRawBytes": 3047217,"scriptRequestCount": 109,- "totalRawBytes": 3364402+ "totalRawBytes": 3365842},"resourceLimits": {"cssRawBytes": 2181,@@ -174,11 +174,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 114,- "scriptRawBytes": 3076235,+ "scriptRawBytes": 3077690,"scriptRequestCount": 109,- "totalRawBytes": 3398047+ "totalRawBytes": 3399501},- "routeReadyMedianMs": 653.3000000007451,+ "routeReadyMedianMs": 707.3000001907349,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -205,15 +205,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 112.09999999776483,+ "domContentLoadedMedianMs": 127.90000009536743,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 112.29999999701977,- "longestTaskMaxMs": 181,+ "loadMedianMs": 128.09999990463257,+ "longestTaskMaxMs": 191,"owner": "workbench",- "projectSwitchMedianMs": 55.79999999701977,+ "projectSwitchMedianMs": 51.59999990463257,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -223,9 +223,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 114,- "scriptRawBytes": 3045777,+ "scriptRawBytes": 3047217,"scriptRequestCount": 109,- "totalRawBytes": 3364402+ "totalRawBytes": 3365842},"resourceLimits": {"cssRawBytes": 2181,@@ -234,11 +234,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 114,- "scriptRawBytes": 3076235,+ "scriptRawBytes": 3077690,"scriptRequestCount": 109,- "totalRawBytes": 3398047+ "totalRawBytes": 3399501},- "routeReadyMedianMs": 449.5,+ "routeReadyMedianMs": 512.7999997138977,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -265,13 +265,13 @@"scriptRequestCount": 6,"totalRawBytes": 287313},- "domContentLoadedMedianMs": 114.5,+ "domContentLoadedMedianMs": 127.90000009536743,"id": "editor-canvas",- "layoutAckMedianMs": 2.400000002235174,- "layoutReturnSwitchMedianMs": 38,- "layoutSwitchMedianMs": 67.10000000149012,- "loadMedianMs": 114.60000000149012,- "longestTaskMaxMs": 91,+ "layoutAckMedianMs": 3.0999999046325684,+ "layoutReturnSwitchMedianMs": 36.90000009536743,+ "layoutSwitchMedianMs": 63.5,+ "loadMedianMs": 128,+ "longestTaskMaxMs": 110,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -283,9 +283,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 120,- "scriptRawBytes": 3330245,+ "scriptRawBytes": 3331685,"scriptRequestCount": 115,- "totalRawBytes": 3648870+ "totalRawBytes": 3650310},"resourceLimits": {"cssRawBytes": 2181,@@ -294,11 +294,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 120,- "scriptRawBytes": 3363548,+ "scriptRawBytes": 3365002,"scriptRequestCount": 115,- "totalRawBytes": 3685359+ "totalRawBytes": 3686814},- "routeReadyMedianMs": 996,+ "routeReadyMedianMs": 1081.0999999046326,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"},@@ -325,13 +325,13 @@"scriptRequestCount": 6,"totalRawBytes": 287313},- "domContentLoadedMedianMs": 108.5,+ "domContentLoadedMedianMs": 126.80000019073486,"id": "editor-canvas",- "layoutAckMedianMs": 2.399999998509884,- "layoutReturnSwitchMedianMs": 35.69999999925494,- "layoutSwitchMedianMs": 183.89999999850988,- "loadMedianMs": 108.60000000149012,- "longestTaskMaxMs": 404,+ "layoutAckMedianMs": 3,+ "layoutReturnSwitchMedianMs": 35.700000286102295,+ "layoutSwitchMedianMs": 195.09999990463257,+ "loadMedianMs": 126.90000009536743,+ "longestTaskMaxMs": 385,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -343,9 +343,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 120,- "scriptRawBytes": 3330245,+ "scriptRawBytes": 3331685,"scriptRequestCount": 115,- "totalRawBytes": 3648870+ "totalRawBytes": 3650310},"resourceLimits": {"cssRawBytes": 2181,@@ -354,11 +354,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 120,- "scriptRawBytes": 3363548,+ "scriptRawBytes": 3365002,"scriptRequestCount": 115,- "totalRawBytes": 3685359+ "totalRawBytes": 3686814},- "routeReadyMedianMs": 1222.5,+ "routeReadyMedianMs": 1357.0999999046326,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"},@@ -385,13 +385,13 @@"scriptRequestCount": 7,"totalRawBytes": 361318},- "domContentLoadedMedianMs": 110,+ "domContentLoadedMedianMs": 125,"id": "editor-workflow",- "layoutAckMedianMs": 2,- "layoutReturnSwitchMedianMs": 31.299999997019768,- "layoutSwitchMedianMs": 85.30000000074506,- "loadMedianMs": 110.10000000149012,- "longestTaskMaxMs": 93,+ "layoutAckMedianMs": 2.6000003814697266,+ "layoutReturnSwitchMedianMs": 32.60000038146973,+ "layoutSwitchMedianMs": 80.30000019073486,+ "loadMedianMs": 125.09999990463257,+ "longestTaskMaxMs": 113,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -403,9 +403,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 122,- "scriptRawBytes": 3388104,+ "scriptRawBytes": 3389544,"scriptRequestCount": 116,- "totalRawBytes": 3722142+ "totalRawBytes": 3723582},"resourceLimits": {"cssRawBytes": 17748,@@ -414,11 +414,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 122,- "scriptRawBytes": 3421986,+ "scriptRawBytes": 3423440,"scriptRequestCount": 116,- "totalRawBytes": 3759364+ "totalRawBytes": 3760818},- "routeReadyMedianMs": 1008.5,+ "routeReadyMedianMs": 1070.5,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "empty"},@@ -445,13 +445,13 @@"scriptRequestCount": 7,"totalRawBytes": 361318},- "domContentLoadedMedianMs": 114.80000000074506,+ "domContentLoadedMedianMs": 134.5,"id": "editor-workflow",- "layoutAckMedianMs": 2.599999997764826,- "layoutReturnSwitchMedianMs": 40.5,- "layoutSwitchMedianMs": 127.89999999850988,- "loadMedianMs": 115,- "longestTaskMaxMs": 353,+ "layoutAckMedianMs": 3.4000000953674316,+ "layoutReturnSwitchMedianMs": 40.799999713897705,+ "layoutSwitchMedianMs": 141.39999961853027,+ "loadMedianMs": 134.7999997138977,+ "longestTaskMaxMs": 440,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -463,9 +463,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 122,- "scriptRawBytes": 3388104,+ "scriptRawBytes": 3389544,"scriptRequestCount": 116,- "totalRawBytes": 3722142+ "totalRawBytes": 3723582},"resourceLimits": {"cssRawBytes": 17748,@@ -474,11 +474,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 122,- "scriptRawBytes": 3421986,+ "scriptRawBytes": 3423440,"scriptRequestCount": 116,- "totalRawBytes": 3759364+ "totalRawBytes": 3760818},- "routeReadyMedianMs": 1181.199999999255,+ "routeReadyMedianMs": 1288.2999997138977,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "representative"},@@ -505,13 +505,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 112.5,+ "domContentLoadedMedianMs": 153.5,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 23,- "loadMedianMs": 112.60000000149012,- "longestTaskMaxMs": 87,+ "layoutSwitchMedianMs": 29.40000009536743,+ "loadMedianMs": 153.60000038146973,+ "longestTaskMaxMs": 106,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -523,9 +523,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 114,- "scriptRawBytes": 3045777,+ "scriptRawBytes": 3047217,"scriptRequestCount": 109,- "totalRawBytes": 3364402+ "totalRawBytes": 3365842},"resourceLimits": {"cssRawBytes": 2181,@@ -534,11 +534,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 114,- "scriptRawBytes": 3076235,+ "scriptRawBytes": 3077690,"scriptRequestCount": 109,- "totalRawBytes": 3398047+ "totalRawBytes": 3399501},- "routeReadyMedianMs": 1216.8999999985099,+ "routeReadyMedianMs": 1383.9000000953674,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -565,13 +565,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 108.69999999925494,+ "domContentLoadedMedianMs": 158.7999997138977,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 85,- "loadMedianMs": 108.69999999925494,- "longestTaskMaxMs": 162,+ "layoutSwitchMedianMs": 99.5,+ "loadMedianMs": 159,+ "longestTaskMaxMs": 197,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -583,9 +583,9 @@"largestAssetRawBytes": 746305,"otherRawBytes": 136426,"requestCount": 114,- "scriptRawBytes": 3045777,+ "scriptRawBytes": 3047217,"scriptRequestCount": 109,- "totalRawBytes": 3364402+ "totalRawBytes": 3365842},"resourceLimits": {"cssRawBytes": 2181,@@ -594,11 +594,11 @@"largestAssetRawBytes": 753769,"otherRawBytes": 137791,"requestCount": 114,- "scriptRawBytes": 3076235,+ "scriptRawBytes": 3077690,"scriptRequestCount": 109,- "totalRawBytes": 3398047+ "totalRawBytes": 3399501},- "routeReadyMedianMs": 1438,+ "routeReadyMedianMs": 1581.1999998092651,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"}@@ -1611,6 +1611,7 @@"source:src/workbench/image-actions/useImageActions.ts","source:src/workbench/image-map/api.ts","source:src/workbench/image-map/imageMapStore.ts",+ "source:src/workbench/image-map/indexProgress.ts","source:src/workbench/invocation.ts","source:src/workbench/invocationSubmit.ts","source:src/workbench/launchpad/HelpMenu.tsx",@@ -2509,6 +2510,7 @@"source:src/workbench/image-actions/useImageActions.ts","source:src/workbench/image-map/api.ts","source:src/workbench/image-map/imageMapStore.ts",+ "source:src/workbench/image-map/indexProgress.ts","source:src/workbench/invocation.ts","source:src/workbench/invocationSubmit.ts","source:src/workbench/launchpad/HelpMenu.tsx",@@ -3563,6 +3565,7 @@"source:src/workbench/image-actions/useImageActions.ts","source:src/workbench/image-map/api.ts","source:src/workbench/image-map/imageMapStore.ts",+ "source:src/workbench/image-map/indexProgress.ts","source:src/workbench/invocation.ts","source:src/workbench/invocationSubmit.ts","source:src/workbench/launchpad/HelpMenu.tsx",diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.tsindex edda949220..7695a9b66c 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts@@ -11,7 +11,13 @@ vi.mock('@platform/transport/http', () => ({import { fetchImageMapPoints, fetchImageMapStatus, requestImageMapRefresh } from './api';import { CLUSTER_PALETTE, getClusterColor, NOISE_COLOR } from './clusterPalette';-import { ensureImageMapLoaded, imageMapStore, recordImageIndexStatus, refreshImageMapPoints } from './imageMapStore';+import {+ ensureImageMapLoaded,+ imageMapStore,+ recordImageIndexStatus,+ refreshImageIndexStatus,+ refreshImageMapPoints,+} from './imageMapStore';import {ALL_POINTS_TRACE,buildAllPointsTrace,@@ -91,7 +97,7 @@ describe('image map store', () => {data: null,error: null,indexCounts: null,- indexRate: null,+ indexUpdatedAt: null,loadState: 'idle',renderError: null,});@@ -290,7 +296,7 @@ describe('snapshot transitions', () => {data: null,error: 'boom',indexCounts: null,- indexRate: null,+ indexUpdatedAt: null,loadState: 'error',renderError: null,});@@ -318,7 +324,7 @@ describe('snapshot transitions', () => {data: null,error: null,indexCounts: null,- indexRate: null,+ indexUpdatedAt: null,loadState: 'loaded',renderError: 'The map failed to render (WebGL unavailable).',});@@ -327,12 +333,18 @@ describe('snapshot transitions', () => {});});+/** Lets everything a just-resolved request queued behind it run. */+const drainMacrotask = (): Promise<void> =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+const EMPTY_SNAPSHOT = {clusterLabels: null,data: null,error: null,indexCounts: null,- indexRate: null,+ indexUpdatedAt: null,loadState: 'idle',renderError: null,} as const;@@ -366,28 +378,27 @@ describe('image index progress', () => {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();+ it('stamps when the index last moved so the UI can say how long it has stood still', () => {+ recordImageIndexStatus({ embedded: 10, failed: 0, pending: 90, total: 100 }, 4_000);- recordImageIndexStatus({ embedded: 20, failed: 0, pending: 80, total: 100 }, 3_000);-- expect(imageMapStore.getSnapshot().indexRate).toBe(5);+ expect(imageMapStore.getSnapshot().indexUpdatedAt).toBe(4_000);});- it('forgets the rate once the queue drains so the next run measures its own', () => {+ it('does not treat a growing gallery as the index making progress', () => {+ // `total` moves as the generation the indexer is waiting out saves its+ // images. Counting that would reset the clock on every generation.recordImageIndexStatus({ embedded: 10, failed: 0, pending: 90, total: 100 }, 1_000);- recordImageIndexStatus({ embedded: 100, failed: 0, pending: 0, total: 100 }, 3_000);+ recordImageIndexStatus({ embedded: 10, failed: 0, pending: 95, total: 105 }, 60_000);- expect(imageMapStore.getSnapshot().indexRate).toBeNull();+ expect(imageMapStore.getSnapshot().indexUpdatedAt).toBe(1_000);+ expect(imageMapStore.getSnapshot().indexCounts?.total).toBe(105);+ });- // A single new image arriving later must not inherit the backfill's rate.- recordImageIndexStatus({ embedded: 100, failed: 0, pending: 1, total: 101 }, 600_000);+ it('restarts the clock as soon as the index does move', () => {+ recordImageIndexStatus({ embedded: 10, failed: 0, pending: 90, total: 100 }, 1_000);+ recordImageIndexStatus({ embedded: 18, failed: 0, pending: 82, total: 100 }, 60_000);- expect(imageMapStore.getSnapshot().indexRate).toBeNull();+ expect(imageMapStore.getSnapshot().indexUpdatedAt).toBe(60_000);});it('seeds the counts from the status endpoint when the map first loads', async () => {@@ -420,10 +431,79 @@ describe('image index progress', () => {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);- });+ await drainMacrotask();expect(imageMapStore.getSnapshot().indexCounts?.embedded).toBe(90);});++ it('re-reads the counts on every mount, not just the first load of the map', async () => {+ // The widget is routinely reopened long after the first load — mid-+ // backfill, with the worker parked and no event due — which is exactly+ // when the panel has nothing else to show.+ mocks.apiFetchJson.mockImplementation((url: string) =>+ url.startsWith('/api/v1/image_map/status')+ ? Promise.resolve({ enabled: true, index: { embedded: 70, failed: 0, total: 100 } })+ : Promise.resolve(BACKEND_RESPONSE)+ );++ imageMapStore.setSnapshot({ ...EMPTY_SNAPSHOT, loadState: 'loaded' });+ ensureImageMapLoaded();++ await vi.waitFor(() => expect(imageMapStore.getSnapshot().indexCounts).not.toBeNull());+ expect(imageMapStore.getSnapshot().indexCounts).toEqual({ embedded: 70, failed: 0, pending: 30, total: 100 });+ });++ it('lets a later status fetch correct counts an event left stale', async () => {+ // The run's final `pending: 0` report is lost while the socket is down, so+ // without this the progress UI claims a finished backfill is still running+ // until the page is reloaded.+ recordImageIndexStatus({ embedded: 40, failed: 0, pending: 60, total: 100 }, 1_000);+ mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: { embedded: 100, failed: 0, total: 100 } });++ refreshImageIndexStatus();++ await vi.waitFor(() => expect(imageMapStore.getSnapshot().indexCounts?.pending).toBe(0));+ });++ it('ages the counts from when they last moved, not from when they were re-read', async () => {+ // Otherwise pressing "Check again" — the one thing a user watching a+ // frozen bar will do — pushes the note out by another interval, forever.+ recordImageIndexStatus({ embedded: 40, failed: 0, pending: 60, total: 100 }, 1_000);+ mocks.apiFetchJson.mockResolvedValue({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });++ refreshImageIndexStatus();++ await vi.waitFor(() => expect(mocks.apiFetchJson).toHaveBeenCalled());+ await drainMacrotask();++ expect(imageMapStore.getSnapshot().indexUpdatedAt).toBe(1_000);+ });++ it('runs one status request at a time so an older response cannot land last', async () => {+ // Concurrent requests resolve in no fixed order, and every mount, retry+ // and reconnect asks for one.+ const resolvers: Array<(value: unknown) => void> = [];+ mocks.apiFetchJson.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolvers.push(resolve);+ })+ );++ refreshImageIndexStatus();+ refreshImageIndexStatus();+ refreshImageIndexStatus();++ expect(resolvers).toHaveLength(1);++ // ...and the claim is released once it settles, so the next caller is not+ // locked out for the rest of the session.+ resolvers[0]?.({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });+ await vi.waitFor(() => expect(imageMapStore.getSnapshot().indexCounts).not.toBeNull());++ refreshImageIndexStatus();+ expect(resolvers).toHaveLength(2);+ resolvers[1]?.({ enabled: true, index: { embedded: 40, failed: 0, total: 100 } });+ await drainMacrotask();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.tsindex b445c8c6c3..738b43fdfd 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts@@ -7,10 +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 type { ImageIndexCounts } from './indexProgress';import { fetchImageMapClusterLabels, fetchImageMapPoints, fetchImageMapStatus } from './api';-import { appendRateSample, estimateRate } from './indexProgress';+import { hasProgressed } from './indexProgress';/*** Read model for the semantic image map, shared by the widget body and any@@ -25,11 +25,13 @@ export interface ImageMapSnapshot {/** 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.+ * When the index last actually moved, so the UI can say how long it has+ * stood still. Not when the counts were last written: `total` shifts+ * whenever anyone saves or deletes an image, and a generation running while+ * the indexer waits for it must not read as the index progressing. Null+ * whenever there are no counts.*/- indexRate: number | null;+ indexUpdatedAt: number | null;/** Cluster id -> automatic label; null when unavailable (e.g. no text encoder). */clusterLabels: Record<string, string> | null;/**@@ -46,7 +48,7 @@ const EMPTY_IMAGE_MAP_SNAPSHOT: ImageMapSnapshot = {data: null,error: null,indexCounts: null,- indexRate: null,+ indexUpdatedAt: null,loadState: 'idle',renderError: null,};@@ -55,7 +57,10 @@ export const imageMapStore = createExternalStore<ImageMapSnapshot>(EMPTY_IMAGE_Mlet inflight: Promise<void> | null = null;let rerunRequested = false;-let rateSamples: IndexRateSample[] = [];+let statusInflight: Promise<void> | null = null;+// Bumped by every socket-delivered status report, so a status fetch that+// started earlier can tell whether one landed while it was in flight.+let indexEventSequence = 0;// The projection is per-user server state: a login/logout must drop it before// the next account's widgets can observe it.@@ -66,7 +71,8 @@ registerAccountOwnedResource({// Orphan any in-flight labels request so its completion (or failure)// cannot touch the next account's labels.labelsSequence += 1;- rateSamples = [];+ statusInflight = null;+ indexEventSequence += 1;imageMapStore.setSnapshot(EMPTY_IMAGE_MAP_SNAPSHOT);},name: 'image-map',@@ -225,58 +231,90 @@ 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.+ * Fold one status report into the snapshot.+ *+ * `measure` marks a socket-delivered report. Only those bump the sequence a+ * status fetch checks itself against, so a fetch cannot rewind counts an event+ * delivered while it was in flight.*/-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;+export const recordImageIndexStatus = (+ counts: ImageIndexCounts,+ at: number = Date.now(),+ { measure = true }: { measure?: boolean } = {}+): void => {+ if (measure) {+ indexEventSequence += 1;}- rateSamples = appendRateSample(rateSamples, { at, embedded: counts.embedded });- imageMapStore.patchSnapshot({ indexCounts: counts, indexRate: estimateRate(rateSamples) });+ const { indexCounts: previous, indexUpdatedAt: previousAt } = imageMapStore.getSnapshot();+ // Only real progress restarts the clock. A re-read that returns the same+ // work done — which is every re-read while the indexer waits out a+ // generation, since `total` moves as that generation saves images — would+ // otherwise hide exactly the stall the note exists to report.+ const updatedAt = hasProgressed(previous, counts) ? at : (previousAt ?? at);++ imageMapStore.patchSnapshot({ indexCounts: counts, indexUpdatedAt: updatedAt });};/**- * 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.+ * Pull 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 — and a client that was disconnected when+ * the run's final `pending === 0` event went out would otherwise show a+ * finished backfill as still running until the page is reloaded. Called on the+ * first load, on every socket reconnect, and from the panel's own retry.+ *+ * Best-effort: a failure just leaves the socket to fill the counts in.*/-const seedImageIndexStatus = (): void => {+export const refreshImageIndexStatus = (): void => {+ // One at a time, like the point set above. Every widget mount, every retry+ // click and every reconnect calls this, and concurrent requests resolve in+ // no particular order: without the dedup the *oldest* response can land last+ // and rewind the counts to what the server said before the newer one asked.+ if (statusInflight) {+ return;+ }+const owner = captureAccountScope();+ // Events that land while this is in flight are strictly newer than what it+ // will return, and must not be rewound by it.+ const sequence = indexEventSequence;- void fetchImageMapStatus()+ const request: Promise<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)) {+ // images — so `index` is null for them and there is nothing to record.+ if (status.index === null || !isAccountScopeCurrent(owner) || sequence !== indexEventSequence) {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);- }+ recordImageIndexStatus(status.index, Date.now(), { measure: false });}).catch(() => {// Progress detail is optional chrome; the map itself reports its own// load failures.+ })+ .finally(() => {+ // Release only this request's claim: an account switch already cleared+ // it and may have let a fresh one start.+ if (statusInflight === request) {+ statusInflight = null;+ }});++ statusInflight = request;};export const ensureImageMapLoaded = (): void => {if (imageMapStore.getSnapshot().loadState === 'idle') {void refreshImageMapPoints();- seedImageIndexStatus();}++ // Unguarded, unlike the point set: the counts are one cheap request, and the+ // widget may well be reopened long after the first load — mid-backfill, with+ // the worker parked and no event due — which is exactly the case the panel+ // exists for. The store's own guards stop it rewinding anything newer.+ refreshImageIndexStatus();};diff --git a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.tsindex ffdaa6e817..3356adc3ca 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.test.ts@@ -1,16 +1,14 @@import { describe, expect, it } from 'vitest';import {- appendRateSample,describeIndexProgress,- estimateRate,formatDuration,- getEtaSeconds,+ getDisplayPercent,getIndexPercent,+ hasProgressed,isIndexing,- RATE_WINDOW_MS,+ STALE_AFTER_MS,type ImageIndexCounts,- type IndexRateSample,} from './indexProgress';const counts = (overrides: Partial<ImageIndexCounts> = {}): ImageIndexCounts => ({@@ -22,7 +20,7 @@ const counts = (overrides: Partial<ImageIndexCounts> = {}): ImageIndexCounts =>});describe('index progress arithmetic', () => {- it('reports the embedded share of the eligible images', () => {+ it('reports the share of the gallery the index has finished with', () => {expect(getIndexPercent(counts())).toBe(25);});@@ -30,20 +28,28 @@ describe('index progress arithmetic', () => {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('counts images given up on as finished so the bar reaches full', () => {+ // They never drain. Leaving them out parks the bar short of full for a run+ // that has in fact finished.+ expect(getIndexPercent(counts({ embedded: 94, failed: 5, pending: 1, total: 100 }))).toBe(99);+ expect(getIndexPercent(counts({ embedded: 95, failed: 5, pending: 0, total: 100 }))).toBe(100);});- it('divides the outstanding work by the measured rate', () => {- expect(getEtaSeconds(counts({ pending: 60 }), 2)).toBe(30);+ it('agrees with the counts line it is shown beside', () => {+ // "300 of 1,000 images" next to "90%" is not something a user can+ // reconcile; both are read off `pending`, so they cannot diverge.+ const description = describeIndexProgress(counts({ embedded: 300, failed: 600, pending: 100, total: 1000 }));++ expect(description.counts).toBe('900 of 1,000 images');+ expect(description.percent).toBe(90);+ expect(description.skipped).toBe('600 skipped after repeated failures');});- 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('holds the announced value below full while anything is outstanding', () => {+ // 99.7% rounds to 100, which tells a screen reader the run is done with+ // 300 images still queued.+ expect(getDisplayPercent(counts({ embedded: 99_700, failed: 0, pending: 300, total: 100_000 }))).toBe(99);+ expect(getDisplayPercent(counts({ embedded: 100_000, failed: 0, pending: 0, total: 100_000 }))).toBe(100);});it('treats only a non-empty queue as indexing', () => {@@ -53,6 +59,22 @@ describe('index progress arithmetic', () => {});});+describe('hasProgressed', () => {+ it('is progress when the index has done more work', () => {+ expect(hasProgressed(counts({ embedded: 25 }), counts({ embedded: 26, pending: 74 }))).toBe(true);+ expect(hasProgressed(counts({ failed: 0 }), counts({ failed: 1, pending: 74 }))).toBe(true);+ expect(hasProgressed(null, counts())).toBe(true);+ });++ it('is not progress when only the gallery moved', () => {+ // `total` shifts whenever anyone saves or deletes an image — including the+ // very generation the indexer is waiting out. Counting that as progress+ // would reset the "no progress" clock every time someone generates.+ expect(hasProgressed(counts({ pending: 75, total: 100 }), counts({ pending: 76, total: 101 }))).toBe(false);+ expect(hasProgressed(counts(), counts())).toBe(false);+ });+});+describe('formatDuration', () => {it('scales the unit to the magnitude', () => {expect(formatDuration(45)).toBe('45s');@@ -60,76 +82,58 @@ describe('formatDuration', () => {expect(formatDuration(3900)).toBe('1h 05m');});- it('never rounds an outstanding queue down to zero', () => {+ it('never rounds an elapsed interval 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('carries a rounded-up remainder instead of rendering a 60th second', () => {+ // Rounding the parts independently gives "60s", "1m 60s" and "59m 60s".+ expect(formatDuration(59.6)).toBe('1m 00s');+ expect(formatDuration(119.6)).toBe('2m 00s');+ expect(formatDuration(3599.6)).toBe('1h 00m');});- 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('renders the unit boundaries themselves', () => {+ expect(formatDuration(59)).toBe('59s');+ expect(formatDuration(60)).toBe('1m 00s');+ expect(formatDuration(3599)).toBe('59m 59s');+ expect(formatDuration(3600)).toBe('1h 00m');});- 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('renders nothing for a value that is not a duration', () => {+ expect(formatDuration(Number.NaN)).toBe('');+ expect(formatDuration(Number.POSITIVE_INFINITY)).toBe('');+ expect(formatDuration(-5)).toBe('');});+});- 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 });+describe('describeIndexProgress', () => {+ it('spells out the counts and the share', () => {+ const description = describeIndexProgress(counts({ embedded: 1204, pending: 3108, total: 4312 }));- expect(result).toHaveLength(2);- expect(estimateRate(result)).toBeCloseTo(1);+ expect(description.counts).toBe(`${(1204).toLocaleString()} of ${(4312).toLocaleString()} images`);+ expect(description.compact).toBe(`${(1204).toLocaleString()}/${(4312).toLocaleString()}`);+ expect(description.percent).toBe(28);});- 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();+ it('says nothing about staleness while reports are still arriving', () => {+ expect(describeIndexProgress(counts(), STALE_AFTER_MS - 1).stale).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);+ it('states how long the index has stood still, and claims nothing more', () => {+ const stale = describeIndexProgress(counts(), STALE_AFTER_MS);- 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();+ // Not "paused while the queue is busy": the indexer waiting out a+ // generation and the indexer having died look identical from here, and+ // the first is routine, so neither may be asserted.+ expect(stale.stale).toBe('No progress reported for 2m 00s');});- it('says it is still measuring rather than inventing a time', () => {- expect(describeIndexProgress(counts(), null).eta).toBe('Estimating time remaining…');+ it('keeps the note honest over long waits', () => {+ expect(describeIndexProgress(counts(), 3_600_000).stale).toBe('No progress reported for 1h 00m');});it('explains images that were given up on', () => {- expect(describeIndexProgress(counts({ failed: 3 }), null).skipped).toBe('3 skipped after repeated failures');+ expect(describeIndexProgress(counts({ failed: 3 })).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.tsindex 7ab24dcbf2..af0002ea87 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/indexProgress.ts@@ -1,8 +1,17 @@/*** 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.+ * that holds the counts and the components that draw them, so the wording and+ * the numbers behind it can be tested without a socket or a DOM.+ *+ * Deliberately no time estimate. The indexer stands down for the whole of+ * every generation (`_wait_for_idle_generation`) and reports nothing while it+ * waits, so the gaps between reports are mostly other people's work, not the+ * index's. Measuring across them makes the estimate pessimistic by ~200x;+ * excluding them makes it optimistic by ~10x, because the pauses still to come+ * are left out; and no threshold separates the two, since embedding a batch on+ * a slow CPU takes exactly as long as a fast generation. What the panel can+ * say honestly is how far the run has got and when it last moved, which is all+ * that was needed to tell progress from a stall.*//** Embedding-index counts as the backend reports them. */@@ -14,116 +23,93 @@ export interface ImageIndexCounts {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.+ * How long the counts may stand still before the panel says so.+ *+ * Above any single batch — the worker emits one report per batch of+ * `image_index_batch_size`, seconds apart on a GPU and up to a minute on a+ * slow CPU — so ordinary embedding never trips it, and short enough that a run+ * that has actually stopped does not keep looking busy.*/-export const RATE_WINDOW_MS = 60_000;+export const STALE_AFTER_MS = 2 * 60_000;-/** Bound on retained samples, so a long backfill cannot grow the array without limit. */-const MAX_SAMPLES = 240;+/** Images the index is finished with, whether they embedded or were given up on. */+const getProcessed = (counts: ImageIndexCounts): number => Math.max(0, counts.total - counts.pending);/**- * Add an observation, dropping the ones that have aged out of the window.+ * Share of the gallery the index is finished with, 0-100.*- * 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.+ * Counted off `pending` so the bar is full exactly when the queue drains.+ * Images given up on are finished with too: leaving them out parks the bar+ * short of full forever, and taking them out of the denominator instead+ * shrinks the total under the user as they retire one by one.*/-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));+ return Math.min(100, Math.max(0, (getProcessed(counts) / 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;- }+/**+ * What to paint, print and announce — one value for all three, so the bar+ * cannot sit visually full beside a number that says otherwise. Held below+ * full while anything is outstanding: 99.7% rounded up tells a screen reader+ * the run is done with 300 images still queued.+ */+export const getDisplayPercent = (counts: ImageIndexCounts): number => {+ const percent = Math.round(getIndexPercent(counts));- return counts.pending / rate;+ return counts.pending > 0 ? Math.min(99, percent) : percent;};/** 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;+/**+ * Whether one report represents progress over another, rather than the same+ * work re-reported. `total` moves whenever anyone saves or deletes an image,+ * so it cannot be part of this: a generation running while the indexer waits+ * for it would otherwise look like the index moving.+ */+export const hasProgressed = (previous: ImageIndexCounts | null, next: ImageIndexCounts): boolean =>+ previous === null || previous.embedded !== next.embedded || previous.failed !== next.failed;+/** "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`;+ // Rounded to whole seconds up front, so the unit split below can never carry+ // - rounding each part on its own renders 119.6s as "1m 60s".+ // Never "0s": a sub-second age still means some time has passed.+ const total = Math.max(1, Math.round(seconds));++ if (total < 60) {+ return `${total}s`;}- if (seconds < 3600) {- return `${Math.floor(seconds / 60)}m ${String(Math.round(seconds % 60)).padStart(2, '0')}s`;+ if (total < 3600) {+ return `${Math.floor(total / 60)}m ${String(total % 60).padStart(2, '0')}s`;}- return `${Math.floor(seconds / 3600)}h ${String(Math.floor((seconds % 3600) / 60)).padStart(2, '0')}m`;+ return `${Math.floor(total / 3600)}h ${String(Math.floor((total % 3600) / 60)).padStart(2, '0')}m`;};const formatCount = (value: number): string => value.toLocaleString();export interface IndexProgressDescription {+ /** Rounded, and held below 100 while anything is outstanding. Paint this too. */percent: number;- /** e.g. "1,204 of 4,312 images" */+ /** e.g. "1,204 of 4,312 images" — done, out of the whole gallery. */counts: string;- /** e.g. "About 4m 30s remaining", or the placeholder until a rate exists. */- eta: string;+ /** The same pair with no words, for the footer's single line: "1,204/4,312". */+ compact: string;+ /** Set once the counts have stood still long enough to be worth saying. */+ stale: string | null;/** Set only once images have been given up on. */skipped: string | null;}@@ -131,15 +117,17 @@ export interface IndexProgressDescription {/*** 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.+ * wording is covered by the same tests as the numbers behind it.+ *+ * `sinceMs` is how long the counts have been standing. The note it produces+ * states the fact and stops there: nothing the client can see distinguishes an+ * indexer waiting out a generation from one that has died, so it must not+ * claim to know which.*/-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,- };-};+export const describeIndexProgress = (counts: ImageIndexCounts, sinceMs = 0): IndexProgressDescription => ({+ compact: `${formatCount(getProcessed(counts))}/${formatCount(counts.total)}`,+ counts: `${formatCount(getProcessed(counts))} of ${formatCount(counts.total)} images`,+ percent: getDisplayPercent(counts),+ skipped: counts.failed > 0 ? `${formatCount(counts.failed)} skipped after repeated failures` : null,+ stale: sinceMs >= STALE_AFTER_MS ? `No progress reported for ${formatDuration(sinceMs / 1000)}` : 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.tsxindex a29201ab50..214a9989b6 100644--- 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.tsx@@ -1,10 +1,11 @@import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';+import { STALE_AFTER_MS } from '@workbench/image-map/indexProgress';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { ImageIndexProgressPanel } from './ImageIndexProgress';+import { ImageIndexProgressInline, ImageIndexProgressPanel } from './ImageIndexProgress';let host: HTMLDivElement | null = null;let root: Root | null = null;@@ -18,23 +19,37 @@ const settle = (action: () => void): Promise<void> =>});});-const render = async (- counts: { embedded: number; failed: number; pending: number; total: number },- rate: number | null-) => {+type Counts = { embedded: number; failed: number; pending: number; total: number };++// Hoisted: an object or function literal in a JSX attribute is what+// react-perf/jsx-no-new-*-as-prop forbids, tests included.+const noop = () => {};+const QUARTER: Counts = { embedded: 25, failed: 0, pending: 75, total: 100 };+const PART_WAY: Counts = { embedded: 1204, failed: 0, pending: 3108, total: 4312 };+const SIX_DIGITS: Counts = { embedded: 123456, failed: 0, pending: 60544, total: 184000 };+const NARROW_HOST = { display: 'flex', width: '120px' } as const;+const NARROW_HOST_280 = { display: 'flex', width: '280px' } as const;+const LONG_ERROR =+ 'sqlite3.OperationalError: no such column: image_index_embeddings.model_key_normalized_v2_with_a_long_suffix';++const mount = async (element: React.ReactElement, width?: string) => {host = document.createElement('div');++ if (width) {+ host.style.width = width;+ }+document.body.append(host);root = createRoot(host);await settle(() => {- root?.render(- <ChakraProvider value={system}>- <ImageIndexProgressPanel counts={counts} rate={rate} />- </ChakraProvider>- );+ root?.render(<ChakraProvider value={system}>{element}</ChakraProvider>);});};+const render = (counts: Counts, updatedAt: number | null = null) =>+ mount(<ImageIndexProgressPanel counts={counts} updatedAt={updatedAt} onRetry={noop} />);+afterEach(async () => {await settle(() => root?.unmount());host?.remove();@@ -44,7 +59,7 @@ afterEach(async () => {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);+ await render({ embedded: 25, failed: 0, pending: 75, total: 100 });const bar = host!.querySelector('[role="progressbar"]')!;@@ -53,25 +68,159 @@ describe('ImageIndexProgressPanel', () => {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);+ it('rounds the announced value instead of reading out sixteen digits', async () => {+ await render(PART_WAY);++ expect(host!.querySelector('[role="progressbar"]')!.getAttribute('aria-valuenow')).toBe('28');+ });++ it('shows the counts and the percentage', async () => {+ await render({ embedded: 25, failed: 0, pending: 75, total: 100 });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);+ it('says nothing about staleness while reports are still arriving', async () => {+ await render({ embedded: 25, failed: 0, pending: 75, total: 100 }, Date.now());++ expect(host!.textContent).not.toContain('No progress reported');+ });++ it('notices the silence itself, without waiting for an event', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });++ try {+ await render({ embedded: 25, failed: 0, pending: 75, total: 100 }, Date.now());+ expect(host!.textContent).not.toContain('No progress reported');++ await act(async () => {+ await vi.advanceTimersByTimeAsync(STALE_AFTER_MS + 10_000);+ });++ expect(host!.textContent).toContain('No progress reported for');+ } finally {+ vi.useRealTimers();+ }+ });++ it('states the fact without claiming to know the cause', async () => {+ await render({ embedded: 25, failed: 0, pending: 75, total: 100 }, Date.now() - 10 * 60_000);- expect(host!.textContent).toContain('Estimating time remaining');+ const text = host!.textContent ?? '';++ // An indexer waiting out a generation and one that has died look+ // identical from here, and the first is routine.+ expect(text).toContain('No progress reported for 10m 00s');+ expect(text).not.toContain('queue');+ expect(text).not.toContain('Paused');});it('accounts for images that were given up on', async () => {- await render({ embedded: 25, failed: 4, pending: 71, total: 100 }, 5);+ await render({ embedded: 25, failed: 4, pending: 71, total: 100 });expect(host!.textContent).toContain('4 skipped after repeated failures');});++ it('states a failed refresh instead of letting the branch it precedes swallow it', async () => {+ const onRetry = vi.fn();++ await mount(+ <ImageIndexProgressPanel+ counts={QUARTER}+ error="Failed to load the image map"+ updatedAt={null}+ onRetry={onRetry}+ />+ );++ const text = host!.textContent ?? '';++ // Both, not one or the other: the backfill is still worth watching.+ expect(text).toContain('Failed to load the image map');+ expect(text).toContain('25 of 100 images');++ const retry = [...host!.querySelectorAll('button')].find((element) => element.textContent === 'Retry')!;++ await settle(() => retry.click());+ expect(onRetry).toHaveBeenCalledTimes(1);+ });++ it('keeps a server error message inside the panel at the minimum widget width', async () => {+ await mount(+ <div style={NARROW_HOST_280}>+ <ImageIndexProgressPanel counts={QUARTER} error={LONG_ERROR} updatedAt={null} onRetry={noop} />+ </div>,+ '280px'+ );++ // A URL or a dotted identifier has no break opportunity, and the widget+ // body is clipped: without `overflowWrap` it runs off both edges.+ expect(host!.scrollWidth).toBeLessThanOrEqual(host!.clientWidth);+ });++ it('offers a way out when the counts themselves are what is stuck', async () => {+ const onRetry = vi.fn();++ await mount(<ImageIndexProgressPanel counts={QUARTER} updatedAt={null} onRetry={onRetry} />);++ const button = [...host!.querySelectorAll('button')].find((element) => element.textContent === 'Check again')!;++ await settle(() => button.click());+ expect(onRetry).toHaveBeenCalledTimes(1);+ });+});++describe('ImageIndexProgressInline', () => {+ it('stays inside a footer narrower than its content', async () => {+ // The widget resizes down to 280px and the counts can be six digits each.+ // `<Text truncate>` is what kept the line this replaced from pushing past+ // the panel edge and under the refresh button.+ await mount(+ <div style={NARROW_HOST}>+ <ImageIndexProgressInline counts={SIX_DIGITS} updatedAt={Date.now()} />+ </div>,+ '120px'+ );++ expect(host!.scrollWidth).toBeLessThanOrEqual(host!.clientWidth);+ });++ it('labels its bar and keeps the counts compact', async () => {+ await mount(<ImageIndexProgressInline counts={PART_WAY} updatedAt={Date.now()} />);++ expect(host!.textContent).toContain(`indexing ${(1204).toLocaleString()}/${(4312).toLocaleString()}`);+ expect(host!.querySelector('[role="progressbar"]')!.getAttribute('aria-valuenow')).toBe('28');+ });++ it('carries the counts in the accessible name, which truncation cannot take away', async () => {+ // At the minimum widget width the visible label is down to a couple of+ // characters and the tooltip that carries the rest is hover-only.+ await mount(+ <div style={NARROW_HOST}>+ <ImageIndexProgressInline counts={SIX_DIGITS} updatedAt={Date.now()} />+ </div>,+ '120px'+ );++ const name = host!.querySelector('[role="progressbar"]')!.getAttribute('aria-label') ?? '';++ expect(name).toContain('Image indexing progress');+ expect(name).toContain(`${(123456).toLocaleString()} of ${(184000).toLocaleString()} images`);+ });++ it('keeps the bar at full size when the label has to shrink', async () => {+ await mount(+ <div style={NARROW_HOST}>+ <ImageIndexProgressInline counts={SIX_DIGITS} updatedAt={Date.now()} />+ </div>,+ '120px'+ );++ // The bar is the glanceable half; letting the flex squash it would leave+ // the row saying nothing at all.+ expect(host!.querySelector('[role="progressbar"]')!.getBoundingClientRect().width).toBeGreaterThanOrEqual(38);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsxindex 8f0d4c1d3b..0b5d71fae8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx@@ -1,15 +1,43 @@import type { ImageIndexCounts } from '@workbench/image-map/indexProgress';-import { HStack, Progress, Stack, Text } from '@chakra-ui/react';+import { Button, HStack, Progress, Stack, Text } from '@chakra-ui/react';import { Tooltip } from '@platform/ui';import { describeIndexProgress } from '@workbench/image-map/indexProgress';+import { useEffect, useState } from 'react';const PROGRESS_LABEL = 'Image indexing progress';+/**+ * How often the age of the counts is re-read. The only thing it drives is a+ * minutes-scale "no progress" note, so this is deliberately coarse: the same+ * interval serves the panel and the footer, and neither announces a number+ * that moves every second.+ */+const TICK_MS = 5_000;++/** How long the counts have been standing, re-read on a timer. */+const useCountsAge = (updatedAt: number | null): number => {+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ if (updatedAt === null) {+ return;+ }++ const timer = setInterval(() => setNow(Date.now()), TICK_MS);++ return () => clearInterval(timer);+ }, [updatedAt]);++ // Clamped rather than reset on a new report: until the next tick `now` still+ // predates it, and a negative age would read as the future.+ return updatedAt === null ? 0 : Math.max(0, now - updatedAt);+};+interface ImageIndexProgressProps {counts: ImageIndexCounts;- /** Images per second, or null while it is still being measured. */- rate: number | null;+ /** When the index last moved, or null if it never has been reported. */+ updatedAt: number | null;}/**@@ -17,61 +45,99 @@ interface ImageIndexProgressProps {* 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.+ *+ * The wording stays away from "your images": the backend's counts aggregate+ * every user's gallery, so for an admin on a multi-user server this is the+ * server's backlog and not necessarily any of their own.*/-export const ImageIndexProgressPanel = ({ counts, rate }: ImageIndexProgressProps) => {- const progress = describeIndexProgress(counts, rate);+export const ImageIndexProgressPanel = ({+ counts,+ error,+ onRetry,+ updatedAt,+}: ImageIndexProgressProps & { error?: string | null; onRetry: () => void }) => {+ const progress = describeIndexProgress(counts, useCountsAge(updatedAt));return (<Stack align="center" gap="2" maxW="sm" textAlign="center" w="full">- <Text fontWeight="semibold">Indexing your gallery</Text>+ <Text fontWeight="semibold">Indexing images</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.+ 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 carryingrole="progressbar", and Chakra otherwise names it "25%", whichtells a screen reader the number but never what it counts. */}- <Progress.Track aria-label={PROGRESS_LABEL}>+ <Progress.Track aria-label={PROGRESS_LABEL} aria-valuenow={progress.percent}><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>+ <Text fontVariantNumeric="tabular-nums">{progress.percent}%</Text></HStack>- <Text color="fg.subtle" fontSize="xs">- {progress.eta}- </Text>+ {/* States the fact and stops there. Nothing here can tell an indexer+ waiting out a generation from one that has died, and the first is+ routine, so neither may be claimed. */}+ {progress.stale ? (+ <Text color="fg.subtle" fontSize="xs">+ {progress.stale}+ </Text>+ ) : null}{progress.skipped ? (<Text color="fg.subtle" fontSize="xs">{progress.skipped}</Text>) : null}</Stack>+ {error ? (+ // `overflowWrap: anywhere` because the message is whatever the server+ // said: a URL or a dotted identifier has no break opportunity, and a+ // centered flex item sizes to min-content, so it would otherwise run+ // off both edges of a widget clipped at 280px with no ellipsis.+ <Text color="fg.error" fontSize="xs" maxW="full" minW="0" mt="2" overflowWrap="anywhere" role="alert">+ {error}+ </Text>+ ) : null}+ {/* The widget's only control in this state — the footer renders nothing+ until the map itself is ready. It matters most when the counts are+ wrong: a client that was offline for the run's final report sits on a+ bar that will never move again, and this re-reads them. */}+ <Button mt={error ? '0' : '2'} onClick={onRetry} size="xs" variant="outline">+ {error ? 'Retry' : 'Check again'}+ </Button></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.+ * on screen: the bar is the glanceable part, the rest 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);+export const ImageIndexProgressInline = ({ counts, updatedAt }: ImageIndexProgressProps) => {+ const progress = describeIndexProgress(counts, useCountsAge(updatedAt));+ const label = progress.stale ? `Indexing ${progress.counts} · ${progress.stale}` : `Indexing ${progress.counts}`;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}>+ <Tooltip content={label}>+ {/* `minW="0"` and a truncating label, both of which the plain `<Text+ truncate>` this replaced got for free: the footer resizes down to+ 280px and the counts can be six digits each, and without them the row+ grows past the panel edge and slides under the refresh button. */}+ <HStack gap="1.5" minW="0" overflow="hidden" title={label}>+ <Progress.Root flexShrink="0" max={100} size="xs" value={progress.percent} w="10">+ {/* The counts go in the name too: at the widget's minimum width the+ label beside it truncates to a couple of characters, and the+ tooltip carrying the full text is hover-only. */}+ <Progress.Track aria-label={`${PROGRESS_LABEL}: ${label}`} aria-valuenow={progress.percent}><Progress.Range /></Progress.Track></Progress.Root>- <Text fontVariantNumeric="tabular-nums" whiteSpace="nowrap">- indexing {counts.embedded}/{counts.total}+ <Text fontVariantNumeric="tabular-nums" truncate>+ indexing {progress.compact}</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 979ec5e8e2..696f514ce9 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,7 +44,7 @@ describe('attachImageMapDataRuntime', () => {data: null,error: null,indexCounts: null,- indexRate: null,+ indexUpdatedAt: 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 07536d943d..c8e1d842c2 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,12 @@ import type { ImageIndexStatusEvent, ImageMapProjectionReadyEvent } from '@workbimport { getAuthSession } from '@features/identity';import { useMountEffect } from '@platform/react/useMountEffect';import { socketHub } from '@platform/transport/socketHub';-import { imageMapStore, recordImageIndexStatus, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';+import {+ imageMapStore,+ recordImageIndexStatus,+ refreshImageIndexStatus,+ refreshImageMapPoints,+} from '@workbench/image-map/imageMapStore';/*** Socket-driven refresh for the image map, replacing polling: when the@@ -27,6 +32,15 @@ const isForAnotherUser = (userId: unknown): boolean => {};export const attachImageMapDataRuntime = (): (() => void) => {+ // The widget host is mounted whenever the image-map widget is *available*,+ // not when it is open, so anything unconditional here bills a user who never+ // looks at the map.+ const hasLoadedOnce = () => {+ const { loadState } = imageMapStore.getSnapshot();++ return loadState === 'loaded' || loadState === 'error';+ };+const refreshIfLoaded = () => {const { loadState, renderError } = imageMapStore.getSnapshot();@@ -102,6 +116,16 @@ export const attachImageMapDataRuntime = (): (() => void) => {if (isReconnect) {refreshIfLoaded();++ // Status events are not replayed, so a run that finished during the+ // outage never announces it: the counts would sit at their last+ // pre-outage value and the progress UI would claim a backfill is still+ // running until the page is reloaded. Re-reading them closes that gap —+ // behind the same guard, so a session that never opened the map still+ // pays nothing for a flapping connection.+ if (hasLoadedOnce()) {+ refreshImageIndexStatus();+ }}});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsxindex ad5fefcd64..ebbc0c76a0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx@@ -2,7 +2,7 @@ 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 { imageMapStore, refreshImageIndexStatus, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';import { isIndexing } from '@workbench/image-map/indexProgress';import { RefreshCwIcon } from 'lucide-react';@@ -10,6 +10,10 @@ import { ImageIndexProgressInline } from './ImageIndexProgress';const handleRefresh = () => {void refreshImageMapPoints();+ // The counts too: this footer is the surface that shows them once the map+ // exists, and counts left stale by a status event missed while offline are+ // exactly what its refresh should be able to correct.+ refreshImageIndexStatus();};/**@@ -18,7 +22,7 @@ const handleRefresh = () => {* a manual refresh.*/export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {- const { data, indexCounts, indexRate, loadState } = imageMapStore.useSnapshot();+ const { data, indexCounts, indexUpdatedAt, 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@@ -42,7 +46,7 @@ export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {{indexing ? (<><Text>·</Text>- <ImageIndexProgressInline counts={indexCounts} rate={indexRate} />+ <ImageIndexProgressInline counts={indexCounts} updatedAt={indexUpdatedAt} /></>) : null}{skipped ? (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsxindex 8cb2a6f81b..4044f90952 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx@@ -5,6 +5,7 @@ import { getImageMapClickSelectsCluster, getImageMapShowClusterLabels } from '@wimport {ensureImageMapLoaded,imageMapStore,+ refreshImageIndexStatus,refreshImageMapPoints,setClusterLabelsEnabled,} from '@workbench/image-map/imageMapStore';@@ -20,6 +21,9 @@ const ImageMapPlot = lazy(() => import('./ImageMapPlot'));const handleRefresh = () => {void refreshImageMapPoints();+ // The counts too: when the retry is the progress panel's, stale counts are+ // the likeliest reason the user pressed it.+ refreshImageIndexStatus();};// Module scope: an inline element would be a new value on every render, which@@ -37,7 +41,7 @@ const plotLoadingFallback = (* selects that image in the gallery (and so in Preview).*/export const ImageMapWidgetView = (_props: WidgetViewProps) => {- const { data, error, indexCounts, indexRate, loadState, renderError } = imageMapStore.useSnapshot();+ const { data, error, indexCounts, indexUpdatedAt, loadState, renderError } = imageMapStore.useSnapshot();const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);const showClusterLabels = useWidgetValuesSelector('image-map', getImageMapShowClusterLabels);@@ -123,13 +127,24 @@ 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.+ // how far the backfill has got is the one 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. `computing` is routine+ // here (the backend asks for a projection as soon as anything is embedded),+ // so deferring to it would hide the progress for most of a backfill.+ //+ // A failed refresh is carried into the panel rather than shadowed by it:+ // preempting the `error` branch below would otherwise drop both the message+ // and the only retry the widget has before the map is ready.if (isIndexing(indexCounts)) {return (<Center h="full" p="6">- <ImageIndexProgressPanel counts={indexCounts} rate={indexRate} />+ <ImageIndexProgressPanel+ counts={indexCounts}+ error={loadState === 'error' ? (error ?? 'Failed to load the image map.') : null}+ updatedAt={indexUpdatedAt}+ onRetry={handleRefresh}+ /></Center>);}