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(ui): don't strand the viewer under the progress overlay, for images or videos (#9475)
Lincoln Steine431d249e092
diff --git a/invokeai/frontend/web/package.json b/invokeai/frontend/web/package.jsonindex 6c7ea3f65c..5805082602 100644--- a/invokeai/frontend/web/package.json+++ b/invokeai/frontend/web/package.json@@ -142,6 +142,7 @@"eslint-plugin-storybook": "^10.3.6","eslint-plugin-unused-imports": "^4.4.1","globals": "^16.5.0",+ "happy-dom": "^20.11.6","knip": "^5.77.4","magic-string": "^0.30.21","openapi-types": "^12.1.3",diff --git a/invokeai/frontend/web/pnpm-lock.yaml b/invokeai/frontend/web/pnpm-lock.yamlindex 4901ad0040..6488e7dd0e 100644--- a/invokeai/frontend/web/pnpm-lock.yaml+++ b/invokeai/frontend/web/pnpm-lock.yaml@@ -297,6 +297,9 @@ importers:globals:specifier: ^16.5.0version: 16.5.0+ happy-dom:+ specifier: ^20.11.6+ version: 20.11.6knip:specifier: ^5.77.4version: 5.77.4(@types/[email protected])([email protected])@@ -338,7 +341,7 @@ importers:version: 1.8.1([email protected]([email protected]))([email protected](@types/[email protected])([email protected])([email protected]))vitest:specifier: ^4.1.5- version: 4.1.5(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ version: 4.1.5(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))packages:@@ -1969,6 +1972,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}+'@typescript-eslint/[email protected]':resolution: {integrity: sha512-j/bwmkBvHUtPNxzuWe5z6BEk3q54YRyGlBXkSsmfoih7zNrBvl5A9A98anlp/7JbyZcWIJ8KXo/3Tq/DjFLtuQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -2331,6 +2340,10 @@ packages:engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}hasBin: true+ resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==}+ engines: {node: '>=4.0'}+resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}@@ -2660,6 +2673,10 @@ packages:resolution: {integrity: sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==}engines: {node: '>=10.0.0'}+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==}@@ -3070,6 +3087,10 @@ packages:resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}+ resolution: {integrity: sha512-Hldbg8AdAa5a5oDcZpjqnGitp7JB0hqWmfv/8qr+kft4vzSD8BHsbdRfzYvL/0QcbKcURC/yyoygbeDQarPvYg==}+ engines: {node: '>=20.0.0'}+resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}engines: {node: '>= 0.4'}@@ -4854,6 +4875,10 @@ packages:resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}+ resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}@@ -4919,6 +4944,18 @@ packages:utf-8-validate:optional: true+ resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true+resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}engines: {node: '>=18'}@@ -6497,7 +6534,7 @@ snapshots:'@testing-library/[email protected]':dependencies:- '@babel/code-frame': 7.29.0+ '@babel/code-frame': 7.29.7'@babel/runtime': 7.29.2'@types/aria-query': 5.0.4aria-query: 5.3.0@@ -6635,6 +6672,12 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.19.3+'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@eslint-community/regexpp': 4.12.2@@ -6797,7 +6840,7 @@ snapshots:obug: 2.1.1std-env: 4.1.0tinyrainbow: 3.1.0- vitest: 4.1.5(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ vitest: 4.1.5(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))'@vitest/[email protected]':dependencies:@@ -6859,7 +6902,7 @@ snapshots:sirv: 3.0.2tinyglobby: 0.2.16tinyrainbow: 3.1.0- vitest: 4.1.5(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ vitest: 4.1.5(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))'@vitest/[email protected]':dependencies:@@ -7110,6 +7153,10 @@ snapshots:node-releases: 2.0.38update-browserslist-db: 1.2.3([email protected])+ dependencies:+ '@types/node': 22.19.3+dependencies:base64-js: 1.5.1@@ -7445,6 +7492,8 @@ snapshots:+ [email protected]: {}+dependencies:is-arrayish: 0.2.1@@ -7992,6 +8041,19 @@ snapshots:+ dependencies:+ '@types/node': 22.19.3+ '@types/whatwg-mimetype': 3.0.2+ '@types/ws': 8.18.1+ buffer-image-size: 0.6.4+ entities: 7.0.1+ whatwg-mimetype: 3.0.0+ ws: 8.21.3+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate+@@ -9744,7 +9806,7 @@ snapshots:fsevents: 2.3.3jiti: 2.6.1- [email protected](@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.5'@vitest/mocker': 4.1.5([email protected](@types/[email protected])([email protected])([email protected]))@@ -9770,6 +9832,7 @@ snapshots:'@types/node': 22.19.3'@vitest/coverage-v8': 4.1.5([email protected])'@vitest/ui': 4.1.5([email protected])+ happy-dom: 20.11.6transitivePeerDependencies:- msw@@ -9785,6 +9848,8 @@ snapshots:+ [email protected]: {}+dependencies:tr46: 0.0.3@@ -9858,6 +9923,8 @@ snapshots:+ [email protected]: {}+dependencies:is-wsl: 3.1.1diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.test.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.test.tsnew file mode 100644index 0000000000..54c1ff2bde--- /dev/null+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.test.ts@@ -0,0 +1,73 @@+import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit';+import type { AppStartListening } from 'app/store/store';+import { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';+import {+ boardIdSelected,+ gallerySliceConfig,+ imageSelected,+ selectionChanged,+} from 'features/gallery/store/gallerySlice';+import { beforeEach, describe, expect, it } from 'vitest';++import { addAutoSwitchedSelectionListener } from './autoSwitchedSelection';++// A store with the real gallery reducer and the real listener, so the predicate is exercised+// against actual selection-writing actions rather than a hand-built state pair.+const buildStore = () => {+ const listenerMiddleware = createListenerMiddleware();+ addAutoSwitchedSelectionListener(listenerMiddleware.startListening as unknown as AppStartListening);+ return configureStore({+ reducer: { gallery: gallerySliceConfig.slice.reducer },+ middleware: (getDefaultMiddleware) => getDefaultMiddleware().prepend(listenerMiddleware.middleware),+ });+};++describe('addAutoSwitchedSelectionListener', () => {+ beforeEach(() => {+ // The marker is a module singleton; drop anything a previous test left on it.+ autoSwitchedImages.settle(null);+ });++ it('keeps the marker when the auto-switch selection lands', () => {+ const store = buildStore();+ autoSwitchedImages.record('a.png');+ store.dispatch(imageSelected('a.png'));+ expect(autoSwitchedImages.consume('a.png')).toBe(true);+ });++ it('drops the marker once the user selects something else', () => {+ // The dead click this exists to prevent: the auto-switch to A never rendered because the user+ // clicked B first, so their later click on A must still get its reveal.+ const store = buildStore();+ autoSwitchedImages.record('a.png');+ store.dispatch(imageSelected('a.png'));+ store.dispatch(imageSelected('b.png'));+ store.dispatch(imageSelected('a.png'));+ expect(autoSwitchedImages.consume('a.png')).toBe(false);+ });++ it('settles on every action that writes the selection, not just imageSelected', () => {+ const store = buildStore();++ autoSwitchedImages.record('a.png');+ store.dispatch(imageSelected('a.png'));+ store.dispatch(selectionChanged(['b.png']));+ expect(autoSwitchedImages.consume('a.png')).toBe(false);++ autoSwitchedImages.record('c.png');+ store.dispatch(imageSelected('c.png'));+ store.dispatch(boardIdSelected({ boardId: 'other', select: { selection: ['d.png'], galleryView: 'images' } }));+ expect(autoSwitchedImages.consume('c.png')).toBe(false);+ });++ it('leaves the marker alone when an action does not move the selection', () => {+ const store = buildStore();+ autoSwitchedImages.record('a.png');+ store.dispatch(imageSelected('a.png'));+ // Selecting the same item again, and a board switch that carries no selection, must not+ // discard a marker whose image has not rendered yet.+ store.dispatch(imageSelected('a.png'));+ store.dispatch(boardIdSelected({ boardId: 'other' }));+ expect(autoSwitchedImages.consume('a.png')).toBe(true);+ });+});diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.tsnew file mode 100644index 0000000000..0b14616f0b--- /dev/null+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.ts@@ -0,0 +1,27 @@+import type { AppStartListening } from 'app/store/store';+import { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';+import { selectLastSelectedItem } from 'features/gallery/store/gallerySelectors';++/**+ * Keeps the auto-switch marker scoped to the selection it was recorded for.+ *+ * onInvocationComplete records the item it is about to auto-switch to, so the viewer's reveal+ * effect can tell that handoff apart from a user's gallery click. The marker is only meaningful+ * while that selection stands: once the selection moves on, the recorded auto-switch will never+ * render, and leaving the marker behind would make the user's next click on that item read as an+ * auto-switch and get no reveal.+ *+ * Matched by state rather than by action type on purpose — the selection is written by several+ * reducers (imageSelected, selectionChanged, boardIdSelected, comparedImagesSwapped,+ * showVirtualBoardsChanged, logout), and a new one added later would silently escape an+ * action-type list, leaving exactly the stale marker this exists to prevent.+ */+export const addAutoSwitchedSelectionListener = (startAppListening: AppStartListening) => {+ startAppListening({+ predicate: (_action, currentState, previousState) =>+ selectLastSelectedItem(currentState) !== selectLastSelectedItem(previousState),+ effect: (_action, { getState }) => {+ autoSwitchedImages.settle(selectLastSelectedItem(getState()) ?? null);+ },+ });+};diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.test.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.test.tsnew file mode 100644index 0000000000..32d92de52d--- /dev/null+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.test.ts@@ -0,0 +1,117 @@+import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit';+import type { AppStartListening } from 'app/store/store';+import {+ gallerySliceConfig,+ galleryViewChanged,+ imageSelected,+ selectionChanged,+} from 'features/gallery/store/gallerySlice';+import { api } from 'services/api';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { addBoardIdSelectedListener } from './boardIdSelected';++// The listener waits for the board's item list before auto-selecting, so the store needs the API+// slice present (the query is never fulfilled here — the point is what happens meanwhile).+const buildStore = () => {+ const listenerMiddleware = createListenerMiddleware();+ addBoardIdSelectedListener(listenerMiddleware.startListening as unknown as AppStartListening);+ return configureStore({+ reducer: {+ gallery: gallerySliceConfig.slice.reducer,+ [api.reducerPath]: api.reducer,+ },+ middleware: (getDefaultMiddleware) =>+ getDefaultMiddleware({ serializableCheck: false }).prepend(listenerMiddleware.middleware),+ });+};++describe('addBoardIdSelectedListener', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('does not overwrite a selection made while it was waiting for the board list', async () => {+ // The gallery's auto-switch dispatches galleryViewChanged immediately before imageSelected.+ // Without the cancel, the probe this starts wakes up on that very selection and re-selects+ // from a stale (or empty) list, undoing the auto-switch — and the viewer then reveals the+ // wrong item over the live preview, the flash the auto-switch marker exists to prevent.+ const store = buildStore();++ store.dispatch(galleryViewChanged('images'));+ store.dispatch(imageSelected('new.png'));++ // Past the probe's 5s give-up, which would otherwise clear the selection outright.+ await vi.advanceTimersByTimeAsync(6000);++ expect(store.getState().gallery.selection).toEqual(['new.png']);+ });++ it('still clears the selection when a board switch finds nothing to show', async () => {+ // The auto-select probe itself must keep working: a board change with no items selects+ // nothing rather than leaving the previous board's item highlighted.+ const store = buildStore();+ store.dispatch(imageSelected('from-previous-board.png'));++ store.dispatch(galleryViewChanged('assets'));+ await vi.advanceTimersByTimeAsync(6000);++ expect(store.getState().gallery.selection).toEqual([]);+ });++ it('does not overwrite a selection made through the gallery grid either', () => {+ // Thumbnail clicks and keyboard navigation dispatch selectionChanged, not imageSelected, so+ // matching on the action type alone leaves the ordinary path exposed.+ const store = buildStore();++ store.dispatch(galleryViewChanged('images'));+ store.dispatch(selectionChanged(['picked.png']));++ return vi.advanceTimersByTimeAsync(6000).then(() => {+ expect(store.getState().gallery.selection).toEqual(['picked.png']);+ });+ });++ it('does not overwrite a multi-selection made while the probe was waiting', () => {+ const store = buildStore();++ store.dispatch(galleryViewChanged('images'));+ store.dispatch(selectionChanged(['first.png', 'second.png']));++ return vi.advanceTimersByTimeAsync(6000).then(() => {+ expect(store.getState().gallery.selection).toEqual(['first.png', 'second.png']);+ });+ });++ it('does not overwrite a multi-selection narrowed while the probe was waiting', () => {+ // Removing one of two selected thumbnails leaves the *last* selected item unchanged, so a+ // predicate watching only the active item never fired and the probe survived to replace the+ // whole selection when it woke.+ const store = buildStore();+ store.dispatch(selectionChanged(['first.png', 'second.png']));++ store.dispatch(galleryViewChanged('images'));+ store.dispatch(selectionChanged(['second.png']));++ return vi.advanceTimersByTimeAsync(6000).then(() => {+ expect(store.getState().gallery.selection).toEqual(['second.png']);+ });+ });++ it('does not overwrite a re-selection of the item already active', () => {+ // Same shape: the active item does not change, but the user has just said what they want.+ const store = buildStore();+ store.dispatch(imageSelected('a.png'));++ store.dispatch(galleryViewChanged('images'));+ store.dispatch(imageSelected('a.png'));++ return vi.advanceTimersByTimeAsync(6000).then(() => {+ expect(store.getState().gallery.selection).toEqual(['a.png']);+ });+ });+});diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.tsindex 05dd8e9f20..01072a8116 100644--- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.ts+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/boardIdSelected.ts@@ -1,16 +1,44 @@import { isAnyOf } from '@reduxjs/toolkit';import type { AppStartListening } from 'app/store/store';-import { selectGalleryItemNamesQueryArgs } from 'features/gallery/store/gallerySelectors';+import { selectGalleryItemNamesQueryArgs, selectSelection } from 'features/gallery/store/gallerySelectors';import { boardIdSelected, galleryViewChanged, imageSelected } from 'features/gallery/store/gallerySlice';import { galleryApi } from 'services/api/endpoints/gallery';+/** The actions that ask this listener to pick an item for the user. */+const startsProbe = isAnyOf(boardIdSelected, galleryViewChanged);+export const addBoardIdSelectedListener = (startAppListening: AppStartListening) => {startAppListening({- matcher: isAnyOf(boardIdSelected, galleryViewChanged),+ // Two jobs, so this cannot be a plain action matcher. The probe below is started by a board or+ // view change — but it must also be *cancelled* by any selection that lands while it waits,+ // and a selection arrives through several actions: imageSelected from the gallery's auto-switch+ // and keyboard navigation, selectionChanged from thumbnail clicks, boardIdSelected carrying a+ // selection. Matching the resulting change of the selection covers all of them, including any+ // writer added later — an action list would silently miss it.+ //+ // The whole selection, not just its active item: removing one of several selected thumbnails,+ // or re-picking the one already active, leaves the last item unchanged while still being the+ // user settling what they want. Comparing only that item left the probe running through those,+ // to overwrite their selection when it woke. The state is immutable, so a new array reference+ // is exactly "the selection was written", and cancelling a probe more often than strictly+ // needed costs nothing.+ predicate: (action, currentState, previousState) =>+ startsProbe(action) || selectSelection(currentState) !== selectSelection(previousState),effect: async (action, { getState, dispatch, condition, cancelActiveListeners }) => {// Cancel any in-progress instances of this listener, we don't want to select an item from a previous boardcancelActiveListeners();+ if (!startsProbe(action)) {+ // A selection landed. It settles what should be displayed, so a probe still waiting on a+ // board's items must not overwrite it when it resolves. The gallery's auto-switch dispatches+ // galleryViewChanged immediately before its selection: without this the probe that view+ // change starts wakes on the selection that follows it, re-selects the first name in a+ // possibly stale cached list, and undoes the switch — and the viewer then reveals that+ // wrong image over the live preview, which is the flash the auto-switch marker exists to+ // prevent. Cancelling above is the whole effect; there is nothing to auto-select here.+ return;+ }+if (boardIdSelected.match(action) && action.payload.select) {// This action already has a resource selection - skip the below auto-selection logicreturn;diff --git a/invokeai/frontend/web/src/app/store/store.test.ts b/invokeai/frontend/web/src/app/store/store.test.tsindex 64dcdfe3af..056bc639b4 100644--- a/invokeai/frontend/web/src/app/store/store.test.ts+++ b/invokeai/frontend/web/src/app/store/store.test.ts@@ -4,7 +4,13 @@ import { externalTokenAdopted, logout, sessionExpiredLogout, setCredentials } frimport { isModalOpenChanged, videosToChangeSelected } from 'features/changeBoardModal/store/slice';import { positivePromptChanged } from 'features/controlLayers/store/paramsSlice';import { deleteVideosWithDialog } from 'features/deleteVideoModal/store/state';-import { autoAddBoardIdChanged, boardIdSelected, selectionChanged } from 'features/gallery/store/gallerySlice';+import { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';+import {+ autoAddBoardIdChanged,+ boardIdSelected,+ imageSelected,+ selectionChanged,+} from 'features/gallery/store/gallerySlice';import { appInfoApi } from 'services/api/endpoints/appInfo';import type { S } from 'services/api/types';import { describe, expect, it } from 'vitest';@@ -116,3 +122,22 @@ describe('auth cache isolation', () => {await expect(pending).rejects.toBe('User canceled');});});++describe('gallery listener registration', () => {+ it('settles the auto-switch marker through the real store wiring', () => {+ // The per-listener tests build their own store, so nothing else fails if the registration in+ // store.ts is deleted — and without it the marker never settles, every stale marker suppresses+ // the user's next click on that item, and the exact dead click the marker exists to prevent+ // comes back. This is the one test that dispatches through createStore()'s own listeners.+ const store = createStore();+ autoSwitchedImages.settle(null); // module singleton; start from empty++ autoSwitchedImages.record('auto-switched.png');+ store.dispatch(imageSelected('auto-switched.png'));+ store.dispatch(imageSelected('user-clicked-elsewhere.png'));++ expect(autoSwitchedImages.consume('auto-switched.png'), 'the marker must not survive the selection moving on').toBe(+ false+ );+ });+});diff --git a/invokeai/frontend/web/src/app/store/store.ts b/invokeai/frontend/web/src/app/store/store.tsindex 5955122531..7ea4ffbf45 100644--- a/invokeai/frontend/web/src/app/store/store.ts+++ b/invokeai/frontend/web/src/app/store/store.ts@@ -12,6 +12,7 @@ import { errorHandler } from 'app/store/enhancers/reduxRemember/errors';import { addAdHocPostProcessingRequestedListener } from 'app/store/middleware/listenerMiddleware/listeners/addAdHocPostProcessingRequestedListener';import { addAnyEnqueuedListener } from 'app/store/middleware/listenerMiddleware/listeners/anyEnqueued';import { addAppStartedListener } from 'app/store/middleware/listenerMiddleware/listeners/appStarted';+import { addAutoSwitchedSelectionListener } from 'app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection';import { addBatchEnqueuedListener } from 'app/store/middleware/listenerMiddleware/listeners/batchEnqueued';import { addDeleteBoardAndImagesFulfilledListener } from 'app/store/middleware/listenerMiddleware/listeners/boardAndImagesDeleted';import { addBoardIdSelectedListener } from 'app/store/middleware/listenerMiddleware/listeners/boardIdSelected';@@ -326,6 +327,7 @@ addImageAddedToBoardFulfilledListener(startAppListening);addImageRemovedFromBoardFulfilledListener(startAppListening);addBoardIdSelectedListener(startAppListening);addArchivedOrDeletedBoardListener(startAppListening);+addAutoSwitchedSelectionListener(startAppListening);// Node schemasaddGetOpenAPISchemaListener(startAppListening);diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.test.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.test.tsnew file mode 100644index 0000000000..9f188f87e2--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.test.ts@@ -0,0 +1,39 @@+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++const read = (file: string) => readFileSync(fileURLToPath(new URL(file, import.meta.url)), 'utf8');++// Wiring checks only — this directory has no DOM test environment, so the component cannot be+// mounted. The lifecycle behavior behind onLoadImage is covered by real tests in+// viewerProgressLifecycle.test.ts, and the reveal-suppression registry in autoSwitchedImages.test.ts.+describe('CurrentImagePreview reveal wiring', () => {+ const currentImagePreview = read('./CurrentImagePreview.tsx');++ it('gates the viewer reveal on the thumbnail rather than the full-resolution image', () => {+ // Gating on `/full` holds a stale latent preview on screen for the whole multi-megabyte+ // download on a slow connection.+ expect(currentImagePreview).toContain('useMediaUrl(imageDTO?.thumbnail_url)');+ expect(currentImagePreview).toContain('preloader.src = previewSrc');+ expect(currentImagePreview).not.toMatch(/preloader\.src\s*=\s*imageDTO\.image_url/);+ });++ it('clears the progress overlay when the preload settles, including on error', () => {+ // Chakra reports a failed load as onError, not onLoad, so DndImage's onLoad alone is not+ // enough to guarantee the overlay is ever cleared.+ expect(currentImagePreview).toContain('preloader.onerror = onReady');+ const onReady = currentImagePreview.slice(+ currentImagePreview.indexOf('const onReady ='),+ currentImagePreview.indexOf('if (typeof window ===')+ );+ expect(onReady).toContain('onLoadImage(imageDTO.session_id ?? null)');+ });++ it('routes the reveal through the mounted-tested hook, gated on the settled preload', () => {+ // The wiring is behaviorally covered in useSelectedItemReveal.test.tsx; this pins that the+ // component uses it, and that readiness means "the preload settled" on the image path.+ expect(currentImagePreview).toContain('useSelectedItemReveal({');+ expect(currentImagePreview).toContain('isMediaReady: imageToRender !== null,');+ });+});diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsxindex ba76ca299b..ca0271d6f7 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsx@@ -1,11 +1,13 @@import { Box, Flex } from '@invoke-ai/ui-library';import { useStore } from '@nanostores/react';import { useAppSelector } from 'app/store/storeHooks';+import { useMediaUrl } from 'features/auth/store/mediaCookieRefresh';import { CanvasAlertsInvocationProgress } from 'features/controlLayers/components/CanvasAlerts/CanvasAlertsInvocationProgress';import { DndImage } from 'features/dnd/DndImage';import ImageMetadataViewer from 'features/gallery/components/ImageMetadataViewer/ImageMetadataViewer';import NextPrevItemButtons from 'features/gallery/components/NextPrevItemButtons';import { useNextPrevItemNavigation } from 'features/gallery/components/useNextPrevItemNavigation';+import { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';import { selectLastSelectedItem } from 'features/gallery/store/gallerySelectors';import { useRegisteredHotkeys } from 'features/system/components/HotkeysModal/useHotkeyData';import { navigationApi } from 'features/ui/layouts/navigation-api';@@ -19,11 +21,12 @@ import { AnimatePresence, motion } from 'framer-motion';import { memo, useCallback, useEffect, useRef, useState } from 'react';import type { ImageDTO } from 'services/api/types';-import { useImageViewerContext } from './context';+import { SELECTED_ITEM_MEDIA_GRACE_MS, SELECTED_ITEM_REVEAL_DURATION_MS, useImageViewerContext } from './context';import { NoContentForViewer } from './NoContentForViewer';import { ProgressImage } from './ProgressImage2';import { ProgressImageTiles } from './ProgressImageTiles';import { ProgressIndicator } from './ProgressIndicator2';+import { useSelectedItemReveal } from './useSelectedItemReveal';export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | null }) => {const activeTab = useAppSelector(selectActiveTab);@@ -38,6 +41,7 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nu$activeProgressData,$isProgressImageResolving,$isTemporarilyShowingSelectedImage,+ lastRenderedItemNameRef,} = useImageViewerContext();const progressEvent = useStore($progressEvent);const progressImage = useStore($progressImage);@@ -45,8 +49,22 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nuconst isProgressImageResolving = useStore($isProgressImageResolving);const isTemporarilyShowingSelectedImage = useStore($isTemporarilyShowingSelectedImage);const [imageToRender, setImageToRender] = useState<ImageDTO | null>(null);- const previousRenderedImageNameRef = useRef<string | null>(null);- const selectedImageRevealTimeoutId = useRef(0);+ // One controller per mounted preview component; the previous-item ref inside it is the shared+ // one from the viewer context, so image <-> video clicks read as selection changes on both ends.++ // The reveal gate below deliberately preloads the *thumbnail*, not the full-resolution image. The+ // progress overlay covers this element until onLoadImage fires, so gating on the multi-megabyte+ // `/full` response would hold a stale latent preview on screen for that entire download on a slow+ // connection. The 256px thumbnail is roughly 100x smaller and is typically higher resolution than+ // the preview it replaces; DndImage renders it via Chakra's `fallbackSrc` and swaps the full image+ // in, in place, once that finishes loading.+ //+ // The URL must go through useMediaUrl so it is byte-identical to the one DndImage requests. The+ // media cookie version is a query parameter, so a mismatch is a different key and the bytes are+ // fetched twice (measured: 2 requests mismatched vs 1 matched). Note the reuse here is the+ // document's list of available images, which is keyed by URL and is not the HTTP cache — it still+ // holds in multiuser mode, where images are served `Cache-Control: private, no-store`.+ const previewSrc = useMediaUrl(imageDTO?.thumbnail_url);useEffect(() => {if (!selectedImageName) {@@ -65,9 +83,15 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nureturn;}setImageToRender(imageDTO);+ // Resolve the progress overlay as soon as the thumbnail settles — on success *or* error.+ // Relying on DndImage's onLoad alone leaves the overlay stuck whenever the image fails to+ // load, because Chakra reports that as onError instead. The session id lets the lifecycle+ // attribute the load, so a late-settling thumbnail from an earlier session cannot cut a+ // different session's resolve illusion short.+ onLoadImage(imageDTO.session_id ?? null);};- if (typeof window === 'undefined') {+ if (typeof window === 'undefined' || !previewSrc) {onReady();return;}@@ -76,7 +100,7 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nupreloader.onload = onReady;preloader.onerror = onReady;- preloader.src = imageDTO.image_url;+ preloader.src = previewSrc;if (preloader.complete) {onReady();@@ -87,54 +111,26 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nupreloader.onload = null;preloader.onerror = null;};- }, [imageDTO, imageToRender?.image_name, selectedImageName]);+ }, [imageDTO, imageToRender?.image_name, onLoadImage, previewSrc, selectedImageName]);const hasProgressImage = progressImage !== null;- useEffect(() => {- const renderedImageName = imageToRender?.image_name ?? null;- const previousRenderedImageName = previousRenderedImageNameRef.current;- previousRenderedImageNameRef.current = renderedImageName;-- window.clearTimeout(selectedImageRevealTimeoutId.current);-- if (- !shouldShowProgressInViewer ||- !hasProgressImage ||- isProgressImageResolving ||- !renderedImageName ||- renderedImageName !== selectedImageName- ) {- $isTemporarilyShowingSelectedImage.set(false);- return;- }-- if (previousRenderedImageName === null || previousRenderedImageName === renderedImageName) {- return;- }-- $isTemporarilyShowingSelectedImage.set(true);- selectedImageRevealTimeoutId.current = window.setTimeout(() => {- $isTemporarilyShowingSelectedImage.set(false);- }, SELECTED_IMAGE_REVEAL_DURATION_MS);-- return () => {- window.clearTimeout(selectedImageRevealTimeoutId.current);- };- }, [+ // The reveal sequencing lives in the controller (selectedItemReveal.ts); the effect wiring+ // around it lives in the hook, where it is mounted and tested with real lifecycles. The image+ // path only renders an image once its preload has settled, so whatever is rendered has painted.+ useSelectedItemReveal({+ lastRenderedItemNameRef,$isTemporarilyShowingSelectedImage,+ marker: autoSwitchedImages,+ durationMs: SELECTED_ITEM_REVEAL_DURATION_MS,+ mediaGraceMs: SELECTED_ITEM_MEDIA_GRACE_MS,+ renderedItemName: imageToRender?.image_name ?? null,+ isMediaReady: imageToRender !== null,+ selectedItemName: selectedImageName ?? null,+ shouldShowProgressInViewer,hasProgressImage,- imageToRender?.image_name,isProgressImageResolving,- selectedImageName,- shouldShowProgressInViewer,- ]);-- useEffect(() => {- return () => {- $isTemporarilyShowingSelectedImage.set(false);- };- }, [$isTemporarilyShowingSelectedImage]);+ });// Show and hide the next/prev buttons on mouse moveconst [shouldShowNextPrevButtons, setShouldShowNextPrevButtons] = useState<boolean>(false);@@ -237,7 +233,11 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nu<Flex flexDir="column" gap={2} position="absolute" top={0} insetInlineStart={0} alignItems="flex-start"><CanvasAlertsInvocationProgress /></Flex>- {shouldShowItemDetails && imageToRender && !withProgress && (+ {/* Gated on the reveal state itself, not only on !withProgress (which the reveal turns+ off): the reveal exists to make a mid-render click visibly land, and the full-screen+ metadata panel would drop exactly on top of the just-revealed image for the whole+ window. Mirrors CurrentVideoPreview's gate. */}+ {shouldShowItemDetails && imageToRender && !isTemporarilyShowingSelectedImage && !withProgress && (<Box position="absolute" opacity={0.8} top={0} width="full" height="full" borderRadius="base"><ImageMetadataViewer image={imageToRender} /></Box>@@ -277,5 +277,3 @@ const exit: AnimationProps['exit'] = {opacity: 0,transition: { duration: 0.07 },};--const SELECTED_IMAGE_REVEAL_DURATION_MS = 2000;diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.test.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.test.tsindex 9a22e8cc32..1a79715f61 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.test.ts+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.test.ts@@ -11,3 +11,65 @@ describe('CurrentVideoPreview playback errors', () => {expect(source).toContain('onError={handleVideoError}');});});++describe('CurrentVideoPreview progress overlay', () => {+ const source = readFileSync(fileURLToPath(new URL('./CurrentVideoPreview.tsx', import.meta.url)), 'utf8');++ it('lifts the overlay during the temporary reveal so mid-render thumbnail clicks visibly land', () => {+ // The overlay must consult the shared reveal atom (and never re-cover an actively-playing+ // video) — an unconditional overlay swallows every gallery click for the whole render.+ expect(source).toMatch(+ /withProgress =\s+shouldShowProgressInViewer && hasProgressImage && !isTemporarilyShowingSelectedImage && !isPlaying/+ );+ expect(source).toContain('SELECTED_ITEM_REVEAL_DURATION_MS');+ });++ it('tiles concurrent sessions instead of letting them overwrite each other (multi-GPU)', () => {+ // CurrentImagePreview tiles per-session previews when several renders run at once; the video+ // overlay must do the same or the sessions fight over the single full-size preview slot.+ expect(source).toMatch(/withTiledProgress = withProgress && activeProgressData\.length > 1/);+ expect(source).toContain('<ProgressImageTiles data={activeProgressData} />');+ });++ it('routes the reveal through the mounted-tested hook, fed by the painted-name readiness', () => {+ // The wiring itself — effect order, cleanup, unmount, the component swap — is behaviorally+ // covered in useSelectedItemReveal.test.tsx. What only this file can see is that this+ // component actually uses that hook, with readiness from the real element's onLoadedData+ // rather than from mount.+ expect(source).toContain('useSelectedItemReveal({');+ expect(source).toContain('renderedItemName: videoName,');+ expect(source).toMatch(/const \{ isMediaReady, onPainted \} = usePaintedItemName\(videoName\);/);+ expect(source).toContain('onLoadedData={onPainted}');+ });++ it('does not cover playback or a temporary reveal with the metadata panel', () => {+ // Playing and revealing both turn withProgress off, so gating the full-screen metadata panel+ // on !withProgress alone drops it exactly on top of the native controls / the just-revealed+ // video whenever item details are enabled.+ expect(source).toMatch(+ /shouldShowItemDetails && !isPlaying && !isTemporarilyShowingSelectedImage && !withProgress &&/+ );+ });++ it('restores the overlay when playback ends on its own, not only when the player is closed', () => {+ // isPlaying suppresses the overlay; without onEnded it never falls back, so the live preview+ // stays hidden for the rest of the generation after a short video plays out.+ expect(source).toContain('onEnded={handleClose}');+ });++ it('does not end a pending resolve when play() is rejected', () => {+ // A rejected play() is not a load failure — the element is intact and its metadata has usually+ // already loaded — so it must not clear an overlay belonging to some other session's render.+ const playHandler = source.slice(source.indexOf('const handlePlay'), source.indexOf('const handleClose'));+ expect(playHandler).toContain('reportPlaybackFailure()');+ expect(playHandler).not.toContain('onLoadImage');+ });++ it('ends a pending post-render resolve when the video element errors', () => {+ // onLoadedMetadata normally ends the resolve illusion; an errored element never fires it. The+ // call must carry this video's session id so the lifecycle can tell it apart from a late load+ // belonging to another concurrently-completed session.+ const errorHandler = source.slice(source.indexOf('const handleVideoError'), source.indexOf('const handlePlay'));+ expect(errorHandler).toContain('onLoadImage(videoDTO?.session_id ?? null)');+ });+});diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsxindex 19aacb1944..87c991083e 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx@@ -13,7 +13,12 @@ import { dndInputFix } from 'features/dnd/util';import VideoMetadataViewer from 'features/gallery/components/ImageMetadataViewer/VideoMetadataViewer';import NextPrevItemButtons from 'features/gallery/components/NextPrevItemButtons';import { useNextPrevItemNavigation } from 'features/gallery/components/useNextPrevItemNavigation';-import { selectSelectedBoardId, selectSelection } from 'features/gallery/store/gallerySelectors';+import { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';+import {+ selectLastSelectedItem,+ selectSelectedBoardId,+ selectSelection,+} from 'features/gallery/store/gallerySelectors';import { isVideoName } from 'features/gallery/store/types';import { useRegisteredHotkeys } from 'features/system/components/HotkeysModal/useHotkeyData';import { toast } from 'features/toast/toast';@@ -30,10 +35,12 @@ import { useTranslation } from 'react-i18next';import { PiArrowSquareOutBold, PiCopyBold, PiDownloadSimpleBold, PiTrashSimpleBold, PiXBold } from 'react-icons/pi';import type { VideoDTO } from 'services/api/types';-import { useImageViewerContext } from './context';+import { SELECTED_ITEM_MEDIA_GRACE_MS, SELECTED_ITEM_REVEAL_DURATION_MS, useImageViewerContext } from './context';import { NoContentForViewer } from './NoContentForViewer';import { ProgressImage } from './ProgressImage2';+import { ProgressImageTiles } from './ProgressImageTiles';import { ProgressIndicator } from './ProgressIndicator2';+import { usePaintedItemName, useSelectedItemReveal } from './useSelectedItemReveal';import { VideoPlayButtonOverlay } from './VideoPlayButtonOverlay';type Props = {@@ -57,6 +64,8 @@ type Props = {* appear on top of the previously-loaded video. Without this, a freshly generated render's* progress images had nowhere to display whenever a video was the last-selected gallery* item (and the user only saw the static first-frame still until the new video finished).+ * Also mirrors its temporary reveal: clicking a gallery thumbnail mid-render lifts the+ * overlay briefly so the click visibly lands, then the live preview returns.*/export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {const videoUrl = useMediaUrl(videoDTO?.video_url);@@ -65,23 +74,67 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {const videoName = videoDTO?.video_name ?? null;const videoRef = useRef<HTMLVideoElement | null>(null);const [isPlaying, setIsPlaying] = useState(false);+ const { isMediaReady, onPainted } = usePaintedItemName(videoName);const shouldShowProgressInViewer = useAppSelector(selectShouldShowProgressInViewer);const shouldShowItemDetails = useAppSelector(selectShouldShowItemDetails);const activeTab = useAppSelector(selectActiveTab);const deleteVideoModal = useDeleteVideoModalApi();const { downloadItem } = useDownloadItem();const clipboard = useClipboard();- const { $progressEvent, $progressImage, onLoadImage } = useImageViewerContext();+ const {+ $progressEvent,+ $progressImage,+ $activeProgressData,+ $isProgressImageResolving,+ $isTemporarilyShowingSelectedImage,+ lastRenderedItemNameRef,+ onLoadImage,+ } = useImageViewerContext();const progressEvent = useStore($progressEvent);const progressImage = useStore($progressImage);- const withProgress = shouldShowProgressInViewer && progressImage !== null;+ const activeProgressData = useStore($activeProgressData);+ const isProgressImageResolving = useStore($isProgressImageResolving);+ const isTemporarilyShowingSelectedImage = useStore($isTemporarilyShowingSelectedImage);+ const hasProgressImage = progressImage !== null;+ // `!isPlaying`: a reveal exposes the play button, and an explicit play is a stronger signal than+ // the click that triggered the reveal — never re-cover an actively-playing video with the opaque+ // overlay (its audio would keep running underneath, with the controls unreachable). The overlay+ // returns when playback ends — whether the user closes the player or the video runs out.+ const withProgress =+ shouldShowProgressInViewer && hasProgressImage && !isTemporarilyShowingSelectedImage && !isPlaying;+ // When more than one session is generating concurrently (multi-GPU), tile their previews instead+ // of letting the sessions overwrite each other's full-size preview. Mirrors CurrentImagePreview.+ const withTiledProgress = withProgress && activeProgressData.length > 1;const { goToPreviousImage, goToNextImage, isFetching } = useNextPrevItemNavigation();+ const selectedItemName = useAppSelector(selectLastSelectedItem);+ // One controller per mounted preview component; the previous-item ref inside it is the shared+ // one from the viewer context, so image <-> video clicks read as selection changes on both ends.// Whenever the selected video changes, drop back to the idle still + play overlay.useEffect(() => {setIsPlaying(false);}, [videoName]);+ // Mid-generation gallery clicks: mirror CurrentImagePreview's temporary reveal. Without this,+ // the opaque progress overlay swallows every video-thumbnail click for the whole render — the+ // selection changes underneath, but nothing visibly happens. The sequencing lives in the+ // controller (selectedItemReveal.ts); the effect wiring around it lives in the hook, where it is+ // mounted and tested with real lifecycles. preload="metadata" plus the near-zero seek does not+ // prove a frame exists, so readiness comes from usePaintedItemName fed by onLoadedData.+ useSelectedItemReveal({+ lastRenderedItemNameRef,+ $isTemporarilyShowingSelectedImage,+ marker: autoSwitchedImages,+ durationMs: SELECTED_ITEM_REVEAL_DURATION_MS,+ mediaGraceMs: SELECTED_ITEM_MEDIA_GRACE_MS,+ renderedItemName: videoName,+ isMediaReady,+ selectedItemName: selectedItemName ?? null,+ shouldShowProgressInViewer,+ hasProgressImage,+ isProgressImageResolving,+ });+// Register the viewer's <video> as a drag source so users can drag the currently-displayed// video onto node fields (e.g. a Video Primitive's "Starting Video" input) directly from// the viewer, just like they can from the gallery thumbnail. Mirrors GalleryVideoItem's@@ -117,13 +170,15 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {);}, [videoDTO, store]);- const handleVideoError = useCallback(() => {+ // Drop back to the idle still and tell the user, without touching the progress overlay. Used on+ // its own for a rejected play(), where the media itself is fine.+ const reportPlaybackFailure = useCallback(() => {setIsPlaying(false);// A restored session's <video> request can 401 before the media-cookie self-heal// completes; the URL version bumps and the element reloads once the cookie lands.// Surfacing an error toast for that transient window would be a false alarm.if (isMediaCookieSelfHealPending()) {- return;+ return false;}toast({id: 'VIDEO_PLAYBACK_FAILED',@@ -131,8 +186,23 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {title: t('toast.videoPlaybackFailed'),description: t('toast.videoPlaybackFailedDesc'),});+ return true;}, [t]);+ const handleVideoError = useCallback(() => {+ // The self-heal case reloads the element, which then fires onLoadedMetadata and ends any+ // pending resolve on its own — so only a real element error takes the shortcut below.+ if (!reportPlaybackFailure()) {+ return;+ }+ // A genuinely errored element will never fire onLoadedMetadata, which is what normally ends+ // this session's post-render "resolve" illusion — end it here instead of letting the overlay+ // sit over the viewer for the whole resolve timeout. Attributed to this video's session, so+ // the lifecycle ignores it if some other session's illusion is the one pending, and it is a+ // no-op when none is.+ onLoadImage(videoDTO?.session_id ?? null);+ }, [onLoadImage, reportPlaybackFailure, videoDTO?.session_id]);+const handlePlay = useCallback(() => {setIsPlaying(true);// The ref points at the same element we'll re-render with controls/audio; calling@@ -146,9 +216,12 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {setIsPlaying(false);return;}- handleVideoError();+ // Not a load failure: onLoadedMetadata has usually already fired, and the element is intact.+ // Routing this through the error path would end whichever session's resolve illusion happens+ // to be pending, for a user gesture unrelated to any render.+ reportPlaybackFailure();});- }, [handleVideoError]);+ }, [reportPlaybackFailure]);// Close: stop playback and drop back to the first-frame preview + play overlay. We// explicitly pause() because toggling React's `controls` prop hides the chrome but does@@ -338,6 +411,8 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {playsInlinecontrols={isPlaying}onLoadedMetadata={handleLoadedMetadata}+ onLoadedData={onPainted}+ onEnded={handleClose}onError={handleVideoError}style={{maxWidth: '100%',@@ -348,16 +423,25 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {}}/>{!isPlaying && !withProgress && <VideoPlayButtonOverlay onClick={handlePlay} />}- {shouldShowItemDetails && !withProgress && (+ {/* Gated on the states themselves, not on !withProgress: playing and revealing both turn+ withProgress off, and the full-screen metadata panel would land exactly on top of the+ playback controls / the just-revealed video, swallowing the interaction they exist for. */}+ {shouldShowItemDetails && !isPlaying && !isTemporarilyShowingSelectedImage && !withProgress && (<Box position="absolute" opacity={0.8} top={0} width="full" height="full" borderRadius="base"><VideoMetadataViewer video={videoDTO} /></Box>)}{withProgress && (<Flex w="full" h="full" position="absolute" alignItems="center" justifyContent="center" bg="base.900">- <ProgressImage progressImage={progressImage} />- {progressEvent && (- <ProgressIndicator progressEvent={progressEvent} position="absolute" top={6} right={6} size={8} />+ {withTiledProgress ? (+ <ProgressImageTiles data={activeProgressData} />+ ) : (+ <>+ <ProgressImage progressImage={progressImage} />+ {progressEvent && (+ <ProgressIndicator progressEvent={progressEvent} position="absolute" top={6} right={6} size={8} />+ )}+ </>)}</Flex>)}diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsxindex 19530ffebb..a92558b445 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx@@ -11,8 +11,8 @@ import { selectAutoSwitch } from 'features/gallery/store/gallerySelectors';import type { ProgressImage as ProgressImageType } from 'features/nodes/types/common';import { LRUCache } from 'lru-cache';import { type Atom, atom, computed, map, type MapStore, type WritableAtom } from 'nanostores';-import type { PropsWithChildren } from 'react';-import { createContext, memo, useCallback, useContext, useEffect, useMemo, useState } from 'react';+import type { MutableRefObject, PropsWithChildren } from 'react';+import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';import type { S } from 'services/api/types';import { getEventScope } from 'services/events/eventScope';import { $socket } from 'services/events/stores';@@ -31,6 +31,11 @@ type ImageViewerContextValue = {$activeProgressData: Atom<ViewerProgressDatum[]>;$isProgressImageResolving: Atom<boolean>;$isTemporarilyShowingSelectedImage: WritableAtom<boolean>;+ /** Name of the item most recently rendered by either preview component (image or video). Shared+ * across the two components so a click that switches media type (image -> video or back) still+ * reads as a selection change to the temporary-reveal logic — a per-component ref resets on the+ * swap and would silently swallow the first reveal after every type switch. */+ lastRenderedItemNameRef: MutableRefObject<string | null>;/*** The viewer finished loading the final image/video for the given session (its DTO's* `session_id`, or null when it has none). Ends the completed session's "resolve" illusion.@@ -38,6 +43,14 @@ type ImageViewerContextValue = {onLoadImage: (sessionId: string | null) => void;};+/** How long a mid-generation gallery click shows the clicked item before the live preview returns. */+export const SELECTED_ITEM_REVEAL_DURATION_MS = 2000;++/** How long a reveal waits for the selected item's first frame before showing it anyway. Long+ * enough for a decode on a slow connection, short enough that a click on media that will never+ * load still lands well inside the reveal it was promised. */+export const SELECTED_ITEM_MEDIA_GRACE_MS = 1000;+const ImageViewerContext = createContext<ImageViewerContextValue | null>(null);const log = logger('events');@@ -60,6 +73,7 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {)[0];const $isProgressImageResolving = useState(() => atom(false))[0];const $isTemporarilyShowingSelectedImage = useState(() => atom(false))[0];+ const lastRenderedItemNameRef = useRef<string | null>(null);// We can have race conditions where we receive a progress event for a queue item that has already finished. Easiest// way to handle this is to keep track of finished queue items in a cache and ignore progress events for those.const [finishedQueueItemIds] = useState(() => new LRUCache<number, boolean>({ max: 200 }));@@ -202,6 +216,7 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {$activeProgressData,$isProgressImageResolving,$isTemporarilyShowingSelectedImage,+ lastRenderedItemNameRef,onLoadImage,}),[diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.test.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.test.tsnew file mode 100644index 0000000000..1216869a7e--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.test.ts@@ -0,0 +1,337 @@+import { createAutoSwitchedSelectionMarker } from 'features/gallery/store/autoSwitchedImages';+import { describe, expect, it } from 'vitest';++import { createSelectedItemRevealController } from './selectedItemReveal';++/**+ * Drives the controller through the same call sequences the preview components' effects produce,+ * with a hand-cranked timer so reveal expiry is explicit. The marker is the real implementation —+ * the reveal/auto-switch interplay is exactly what these tests exist to pin.+ */+const createHarness = () => {+ let revealed = false;+ const lastRenderedItemNameRef = { current: null as string | null };+ const marker = createAutoSwitchedSelectionMarker();+ const timers = new Map<number, () => void>();+ let nextTimerId = 1;++ const controller = createSelectedItemRevealController({+ lastRenderedItemNameRef,+ marker,+ setRevealed: (value) => {+ revealed = value;+ },+ durationMs: 2000,+ mediaGraceMs: 1000,+ schedule: (fn) => {+ const id = nextTimerId++;+ timers.set(id, fn);+ return id;+ },+ cancel: (id) => {+ timers.delete(id);+ },+ });++ return {+ controller,+ marker,+ lastRenderedItemNameRef,+ isRevealed: () => revealed,+ // The components' unmount handler lowers the shared flag directly, without going through the+ // controller — StrictMode runs it between the doubled mount effects.+ lowerExternally: () => {+ revealed = false;+ },+ fireTimers: () => {+ for (const [id, fn] of [...timers]) {+ timers.delete(id);+ fn();+ }+ },+ pendingTimerCount: () => timers.size,+ };+};++// An auto-switch as onInvocationComplete + the selection listener produce it: record, then the+// dispatched selection lands and settles the marker.+const autoSwitchTo = (marker: ReturnType<typeof createAutoSwitchedSelectionMarker>, itemName: string) => {+ marker.record(itemName);+ marker.settle(itemName);+};++const inputs = (overrides: Partial<Parameters<ReturnType<typeof createHarness>['controller']['run']>[0]> = {}) => ({+ shouldShowProgressInViewer: true,+ hasProgressImage: true,+ isProgressImageResolving: false,+ renderedItemName: null as string | null,+ selectedItemName: null as string | null,+ // Most sequences are about *which* item is revealed, not about waiting for pixels, so the+ // default is "the item on screen has painted". The media-hold tests override it.+ isMediaReady: true,+ ...overrides,+});++const rendering = (itemName: string) => inputs({ renderedItemName: itemName, selectedItemName: itemName });++describe('createSelectedItemRevealController', () => {+ it('reveals a mid-render selection change, then lowers when the timer fires', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(rendering('b.png'));+ expect(h.isRevealed()).toBe(true);+ h.fireTimers();+ expect(h.isRevealed()).toBe(false);+ });++ it('does not reveal the first render after the viewer opens', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ expect(h.isRevealed()).toBe(false);+ });++ it('does not re-reveal when a later run finds the same item and no reveal in flight', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(rendering('b.png'));+ h.fireTimers();+ // e.g. the resolving flag flapping, or any other dependency change with the item unchanged.+ h.controller.run(rendering('b.png'));+ expect(h.isRevealed()).toBe(false);+ });++ it('does not reveal an auto-switched item', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ autoSwitchTo(h.marker, 'b.png');+ h.controller.run(rendering('b.png'));+ expect(h.isRevealed()).toBe(false);+ });++ it('consumes the marker even when no progress is showing, so a later click on that item reveals', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ autoSwitchTo(h.marker, 'b.png');+ // The auto-switched item renders with the overlay down — the common case.+ h.controller.run(inputs({ renderedItemName: 'b.png', selectedItemName: 'b.png', hasProgressImage: false }));+ expect(h.isRevealed()).toBe(false);+ // A new render starts; the user clicks away and back to the once-auto-switched item.+ h.controller.run(rendering('a.png'));+ h.controller.run(rendering('b.png'));+ expect(h.isRevealed()).toBe(true);+ });++ it('keeps the reveal through a StrictMode double-invoked mount effect', () => {+ // React StrictMode mounts run effect -> cleanup -> effect. The cleanup cancels the reveal+ // timer and the unmount handler lowers the shared flag; the second run then finds the shared+ // ref already holding the new name. Without the re-arm, every cross-media first reveal dies+ // in development.+ const h = createHarness();+ h.controller.run(rendering('previous-image.png'));+ h.controller.run(rendering('clicked-video.mp4'));+ expect(h.isRevealed()).toBe(true);+ h.controller.clearTimer();+ h.lowerExternally();+ h.controller.run(rendering('clicked-video.mp4'));+ expect(h.isRevealed()).toBe(true);+ expect(h.pendingTimerCount()).toBe(1);+ h.fireTimers();+ expect(h.isRevealed()).toBe(false);+ });++ it('reveals a click that landed inside a resolve window once the window ends', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ // The user clicks a video while a finished render's preview is resolving; the next render's+ // progress then resumes before the resolve ends.+ h.controller.run(inputs({ isProgressImageResolving: true, renderedItemName: 'b.mp4', selectedItemName: 'b.mp4' }));+ expect(h.isRevealed()).toBe(false);+ // The ref must not have advanced past the click — that is what kept this click dead before.+ expect(h.lastRenderedItemNameRef.current).toBe('a.png');+ h.controller.run(rendering('b.mp4'));+ expect(h.isRevealed()).toBe(true);+ });++ it('still suppresses an auto-switch whose render landed inside a resolve window', () => {+ // The marker must not be consumed by a run that cannot reveal, or the post-resolve run would+ // read the auto-switch as a user click.+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ autoSwitchTo(h.marker, 'b.mp4');+ h.controller.run(inputs({ isProgressImageResolving: true, renderedItemName: 'b.mp4', selectedItemName: 'b.mp4' }));+ expect(h.isRevealed()).toBe(false);+ h.controller.run(rendering('b.mp4'));+ expect(h.isRevealed()).toBe(false);+ });++ it('reveals the selection made after the selection was cleared — including the same item', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ // Clearing the selection empties the viewer; the ref must not fall back to the "nothing has+ // rendered yet" state or the next click is treated as the viewer's first render and stays+ // hidden under the progress overlay.+ h.controller.run(inputs({ renderedItemName: null, selectedItemName: null }));+ h.controller.run(rendering('b.mp4'));+ expect(h.isRevealed()).toBe(true);++ const h2 = createHarness();+ h2.controller.run(rendering('a.png'));+ h2.controller.run(inputs({ renderedItemName: null, selectedItemName: null }));+ h2.controller.run(rendering('a.png'));+ expect(h2.isRevealed()).toBe(true);+ });++ it('keeps the previous item while a selection exists but its render has not landed', () => {+ // Image preloads and DTO fetches make the rendered item lag the selection; the in-between run+ // must neither reveal nor erase the fact of what was on screen before.+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(inputs({ renderedItemName: null, selectedItemName: 'b.png' }));+ expect(h.isRevealed()).toBe(false);+ expect(h.lastRenderedItemNameRef.current).toBe('a.png');+ h.controller.run(rendering('b.png'));+ expect(h.isRevealed()).toBe(true);+ });++ it('does not reveal while the rendered item lags the selection', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(inputs({ renderedItemName: 'a.png', selectedItemName: 'b.png' }));+ expect(h.isRevealed()).toBe(false);+ });++ it('lowers the reveal when the overlay is not showing at all', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(inputs({ renderedItemName: 'b.png', selectedItemName: 'b.png', hasProgressImage: false }));+ expect(h.isRevealed()).toBe(false);+ const h2 = createHarness();+ h2.controller.run(rendering('a.png'));+ h2.controller.run(+ inputs({ renderedItemName: 'b.png', selectedItemName: 'b.png', shouldShowProgressInViewer: false })+ );+ expect(h2.isRevealed()).toBe(false);+ });++ it('keeps a reveal the user already earned when a generation elsewhere starts resolving', () => {+ // The clicked item is on screen with its two seconds running. Another session finishing is no+ // reason to slam the opaque overlay back over it.+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(rendering('b.png'));+ expect(h.isRevealed()).toBe(true);++ h.controller.run({ ...rendering('b.png'), isProgressImageResolving: true });+ expect(h.isRevealed(), 'the granted reveal survives the resolve window').toBe(true);++ // ...and it still ends on its own rather than sticking there.+ h.fireTimers();+ expect(h.isRevealed()).toBe(false);+ });++ it('lowers during a resolve window when the in-flight reveal is for a different item', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(rendering('b.png'));+ expect(h.isRevealed()).toBe(true);+ h.controller.run({ ...rendering('c.png'), isProgressImageResolving: true });+ expect(h.isRevealed()).toBe(false);+ });++ it('leaves no stale timer behind when a run supersedes a reveal', () => {+ // Two timers alive at once means the older one lowers the newer one's reveal early.+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run(rendering('b.png'));+ h.controller.run(rendering('c.png'));+ expect(h.pendingTimerCount()).toBe(1);++ h.controller.run({ ...rendering('c.png'), isProgressImageResolving: true });+ expect(h.pendingTimerCount(), 'the resolve-window re-arm replaces the timer, not adds one').toBe(1);+ });++ it('reveals the same item re-selected after a clear that happened during a resolve window', () => {+ // The clear has to be recorded even while resolving: leaving the ref on the item that was+ // cleared makes re-selecting it read as "nothing changed" when the window ends, and the+ // re-click stays hidden under the overlay.+ const h = createHarness();+ h.controller.run(rendering('a.png'));++ const resolving = { isProgressImageResolving: true };+ h.controller.run(inputs({ ...resolving, renderedItemName: null, selectedItemName: null }));+ h.controller.run({ ...rendering('a.png'), ...resolving });++ // The resolve window ends with the same item selected again.+ h.controller.run(rendering('a.png'));+ expect(h.isRevealed()).toBe(true);+ });++ it('reveals the first click made from an empty viewer during a generation', () => {+ // The viewer has never shown an item, so there is no previous one to compare against — but the+ // user's click is still a click, and suppressing it leaves their pick behind the overlay for+ // the rest of the render.+ const h = createHarness();+ h.controller.run(inputs({ renderedItemName: null, selectedItemName: null }));++ h.controller.run(rendering('first-pick.mp4'));+ expect(h.isRevealed()).toBe(true);+ });++ it('still does not reveal the render that happens when the viewer opens on a selection', () => {+ // Nothing was clicked; the viewer is just catching up with a selection that already existed.+ const h = createHarness();+ h.controller.run(inputs({ renderedItemName: null, selectedItemName: 'already.png' }));+ h.controller.run(rendering('already.png'));+ expect(h.isRevealed()).toBe(false);+ });++ it('does not spend the reveal on a video that has not decoded a frame yet', () => {+ // preload="metadata" and the near-zero seek do not prove a frame exists. Starting the two+ // seconds at mount let them run out over a black element, then put the overlay back.+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run({ ...rendering('slow.mp4'), isMediaReady: false });+ expect(h.isRevealed()).toBe(false);++ h.controller.run(rendering('slow.mp4'));+ expect(h.isRevealed(), 'the reveal starts when the frame is there').toBe(true);+ });++ it('reveals media that never becomes ready rather than swallowing the click', () => {+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run({ ...rendering('broken.mp4'), isMediaReady: false });+ h.fireTimers();+ expect(h.isRevealed()).toBe(true);+ });++ it('keeps holding a claim across re-runs while the frame is still missing', () => {+ // StrictMode re-runs the mount effect; the wait must not restart from zero each time, nor be+ // dropped as "nothing changed".+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run({ ...rendering('slow.mp4'), isMediaReady: false });+ h.controller.run({ ...rendering('slow.mp4'), isMediaReady: false });+ expect(h.isRevealed()).toBe(false);+ expect(h.pendingTimerCount()).toBe(1);++ h.controller.run(rendering('slow.mp4'));+ expect(h.isRevealed()).toBe(true);+ });++ it('carries an unpainted claim through a resolve window that starts under it', () => {+ // Mid-generation the user clicks a video that has not decoded yet, and the running item then+ // completes, opening its resolve window. The claim must survive the window: dropping it there+ // leaves the next run seeing "same item, nothing pending" and the click is swallowed forever.+ const h = createHarness();+ h.controller.run(rendering('a.png'));+ h.controller.run({ ...rendering('v.mp4'), isMediaReady: false });+ expect(h.isRevealed()).toBe(false);++ h.controller.run({ ...rendering('v.mp4'), isMediaReady: false, isProgressImageResolving: true });+ expect(h.isRevealed(), 'held, not shown — the hand-off owns the viewer').toBe(false);++ h.controller.run(rendering('v.mp4'));+ expect(h.isRevealed(), 'the click is honoured once the window ends and the frame is there').toBe(true);+ });+});diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.tsnew file mode 100644index 0000000000..d385863de2--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.ts@@ -0,0 +1,251 @@+/**+ * The viewer's "reveal selected item" mechanism, extracted from the preview components so its+ * sequencing is testable without rendering.+ *+ * A generation covers the viewer with an opaque progress overlay, which would otherwise swallow+ * every gallery click for the whole render: the selection changes underneath, but nothing visibly+ * happens. The reveal lifts the overlay for `durationMs` when the rendered item changes because+ * the *user* picked a new one, then drops back to the live preview.+ *+ * CurrentImagePreview and CurrentVideoPreview each own one controller and call `run` from the+ * effect that reacts to their rendered item; `lastRenderedItemNameRef` is shared between them via+ * the viewer context so a click that switches media type still reads as a selection change.+ *+ * Sequencing rules the controller encodes (each one has a failure mode without it):+ *+ * - The previous-item ref is NOT advanced, and the auto-switch marker NOT consumed, while a+ * finished render's preview is resolving into its final frame. A click landing inside that+ * window keeps its identity until the window ends, so the next run can still classify it —+ * revealing a user click that resumes progress would otherwise be impossible, and an+ * auto-switch would consume its marker on a run that can never reveal, then read as a user+ * click afterwards.+ * - The marker IS consumed on every other change of the rendered item, even when no progress is+ * showing: it must not outlive the render it was recorded for.+ * - Clearing the selection moves the ref to a sentinel rather than null: null means "nothing has+ * rendered since the viewer opened" and suppresses the reveal (that first render is not a+ * click), but the selection made after a clear IS a click and must reveal — including a+ * re-selection of the very item that was cleared.+ * - A run that finds the rendered item unchanged while this controller's own reveal is the one+ * in flight re-arms it instead of killing it. React StrictMode double-invokes a mount's+ * effects (run → cleanup → run), so without this every cross-media first reveal dies in+ * development: the second run sees the name the first run wrote into the shared ref.+ * - Every other path lowers the reveal. `run` cancels the running reveal's timer before+ * deciding, so an outcome that left the flag raised would have nothing left to lower it.+ */++type SelectedItemRevealInputs = {+ /** Whether the rendered item has a frame on screen: an image decoded, a video's first frame+ * painted. A <video> mounts instantly and stays black until it decodes, so mounting is not the+ * same as being visible. */+ isMediaReady: boolean;+ /** The user's "show progress in viewer" setting. */+ shouldShowProgressInViewer: boolean;+ /** Whether a live progress preview exists to be covering the viewer at all. */+ hasProgressImage: boolean;+ /** Whether a finished generation's preview is mid-handoff to its final frame. */+ isProgressImageResolving: boolean;+ /** The item the component is rendering right now, or null when it has nothing to show. */+ renderedItemName: string | null;+ /** The item the gallery selection points at, or null when the selection is empty. */+ selectedItemName: string | null;+};++type SelectedItemRevealController = {+ /** Decide and apply the reveal state for the current render. Call from the effect body. */+ run: (inputs: SelectedItemRevealInputs) => void;+ /** Cancel the running reveal's timer without changing the revealed state. Call from the+ * effect's cleanup — the next `run` (or the component's unmount handler) owns the state. */+ clearTimer: () => void;+};++// Written into the shared ref when the selection is cleared after something had rendered. Never+// equals a real item name (names are filenames), never equals null (the nothing-rendered-yet+// state), so the next rendered item compares as a change and gets its reveal.+const SELECTION_CLEARED = '';++export const createSelectedItemRevealController = (deps: {+ /** Shared with the other preview component via the viewer context. */+ lastRenderedItemNameRef: { current: string | null };+ /** The auto-switch marker (see features/gallery/store/autoSwitchedImages). */+ marker: { consume: (itemName: string) => boolean };+ /** Writes the shared "temporarily showing selected item" flag. */+ setRevealed: (revealed: boolean) => void;+ durationMs: number;+ /** How long a reveal waits for the item to paint before showing it anyway: media that will never+ * become ready must still make the click land rather than swallowing it. */+ mediaGraceMs: number;+ schedule?: (fn: () => void, ms: number) => number;+ cancel?: (id: number) => void;+}): SelectedItemRevealController => {+ const {+ lastRenderedItemNameRef,+ marker,+ setRevealed,+ durationMs,+ mediaGraceMs,+ schedule = (fn, ms) => window.setTimeout(fn, ms),+ cancel = (id) => window.clearTimeout(id),+ } = deps;++ // The item this controller's currently-armed reveal is showing, null when none is in flight.+ // This is what lets a StrictMode re-run tell "my own reveal, restarted" from "nothing changed".+ let activeRevealItemName: string | null = null;+ // The item owed a reveal that is waiting for its media to paint. Held rather than shown, so the+ // two seconds are spent on a visible frame instead of running out over a black element.+ let awaitingMediaItemName: string | null = null;+ let timerId = 0;++ const lower = () => {+ activeRevealItemName = null;+ awaitingMediaItemName = null;+ setRevealed(false);+ };++ const reveal = (itemName: string) => {+ cancel(timerId);+ awaitingMediaItemName = null;+ activeRevealItemName = itemName;+ setRevealed(true);+ timerId = schedule(lower, durationMs);+ };++ /** Owed a reveal, but the item has not painted yet. Bounded, so media that never loads still+ * makes the click land. */+ const awaitMedia = (itemName: string) => {+ cancel(timerId);+ awaitingMediaItemName = itemName;+ activeRevealItemName = null;+ setRevealed(false);+ timerId = schedule(() => {+ if (awaitingMediaItemName !== null) {+ reveal(awaitingMediaItemName);+ }+ }, mediaGraceMs);+ };++ const run: SelectedItemRevealController['run'] = ({+ shouldShowProgressInViewer,+ hasProgressImage,+ isProgressImageResolving,+ renderedItemName,+ selectedItemName,+ isMediaReady,+ }) => {+ cancel(timerId);++ const previousRenderedItemName = lastRenderedItemNameRef.current;++ // A cleared selection is recorded even while resolving. The deferral below exists to preserve+ // the identity of something that landed but has not been classified yet; a clear has no such+ // identity to keep — it *is* the event — and leaving the ref on the item that was cleared makes+ // re-selecting that same item read as "nothing changed" once the window ends, so the re-click+ // stays hidden under the overlay.+ // Written whether or not anything had rendered before. `null` means "the viewer has not shown+ // the user anything yet", which suppresses the reveal — right for the render that happens when+ // the viewer opens onto an existing selection, wrong for a viewer sitting empty while a+ // generation runs: the user's first click there is a click like any other, and suppressing it+ // left their pick behind the overlay. An empty selection is a state the viewer *has* shown, so+ // it gets the sentinel and the next selection reveals.+ if (renderedItemName === null && selectedItemName === null) {+ lastRenderedItemNameRef.current = SELECTION_CLEARED;+ }++ // Resolve window: leave the ref and the marker otherwise exactly as they are (see the module+ // docblock) so whatever lands during it can still be classified — and revealed — when it ends.+ if (isProgressImageResolving) {+ if (awaitingMediaItemName !== null && awaitingMediaItemName === renderedItemName) {+ // Owed but not yet shown: keep the claim, the hand-off owns the viewer for now.+ timerId = schedule(() => {+ if (awaitingMediaItemName !== null) {+ reveal(awaitingMediaItemName);+ }+ }, mediaGraceMs);+ return;+ }+ if (activeRevealItemName !== null && activeRevealItemName === renderedItemName) {+ // A reveal the user already earned is in flight over this very item. A generation+ // finishing elsewhere is no reason to slam the overlay back over their click, so re-arm+ // (the timer was cancelled above) instead of lowering.+ timerId = schedule(lower, durationMs);+ return;+ }+ lower();+ return;+ }++ // While a selection exists but its render hasn't landed yet (preload or DTO fetch pending), the+ // ref must keep the previous item — nulling it would erase the "previous item" fact and swallow+ // the reveal the successor run would fire. The cleared-selection case is handled above.+ if (renderedItemName !== null) {+ lastRenderedItemNameRef.current = renderedItemName;+ }++ // Consumed before the visibility guards below: in the common case the auto-switched item+ // renders with no progress showing, and the marker must not outlive the render it was+ // recorded for.+ const wasAutoSwitchedTo =+ renderedItemName !== null && renderedItemName !== previousRenderedItemName && marker.consume(renderedItemName);++ if (+ !shouldShowProgressInViewer ||+ !hasProgressImage ||+ renderedItemName === null ||+ // Render lagging the selection: whatever is on screen is not what the user picked, so+ // showing it would not make their click land.+ renderedItemName !== selectedItemName+ ) {+ lower();+ return;+ }++ if (previousRenderedItemName === null || previousRenderedItemName === renderedItemName) {+ if (awaitingMediaItemName === renderedItemName) {+ // Already owed a reveal for this item, waiting on its first frame. If that frame has since+ // arrived, show it; otherwise keep holding rather than restarting the wait.+ if (isMediaReady) {+ reveal(renderedItemName);+ } else {+ timerId = schedule(() => {+ if (awaitingMediaItemName !== null) {+ reveal(awaitingMediaItemName);+ }+ }, mediaGraceMs);+ }+ return;+ }+ if (activeRevealItemName !== renderedItemName) {+ // Not a change of displayed item — nothing happened that needs to be made visible. The+ // first render after the viewer opens is not a click either.+ lower();+ return;+ }+ // This controller's own reveal of this exact item is in flight: a StrictMode re-run of the+ // mount effect (its cleanup already cancelled the timer, and the unmount handler lowered+ // the flag). Fall through and re-arm rather than killing the reveal the user just earned.+ } else if (wasAutoSwitchedTo) {+ // The reveal exists for *user* selections. The auto-switch selection lands after an async+ // DTO fetch, so the next render's first progress event can slot in ahead of it and reset+ // the resolving flag — by the time it reaches this effect, timing cannot tell it from a+ // click, but the marker can. Revealing it would flash the finished item over the new+ // render's live preview.+ lower();+ return;+ }++ if (!isMediaReady) {+ // Spending the two seconds on an element that has not decoded a frame shows the user a black+ // rectangle where their click should be, then puts the overlay back.+ awaitMedia(renderedItemName);+ return;+ }++ reveal(renderedItemName);+ };++ return {+ run,+ clearTimer: () => {+ cancel(timerId);+ },+ };+};diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.test.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.test.tsxnew file mode 100644index 0000000000..952c1b581f--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.test.tsx@@ -0,0 +1,253 @@+// @vitest-environment happy-dom+/**+ * Mounted-DOM coverage for the preview components' reveal wiring. The controller's sequencing has+ * its own unit tests; what only a real mount can verify is the wiring the components rely on —+ * effect ordering, cleanup, StrictMode double-invocation, the image <-> video component swap over+ * the shared ref, and media readiness driven by a real <video> element's event.+ */+import { createAutoSwitchedSelectionMarker } from 'features/gallery/store/autoSwitchedImages';+import { atom } from 'nanostores';+import { act, StrictMode } from 'react';+import type { Root } from 'react-dom/client';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { usePaintedItemName, useSelectedItemReveal } from './useSelectedItemReveal';++declare global {+ var IS_REACT_ACT_ENVIRONMENT: boolean;+}+globalThis.IS_REACT_ACT_ENVIRONMENT = true;++const DURATION_MS = 2000;+const MEDIA_GRACE_MS = 1000;++/** The pieces the viewer context shares between the two preview components. */+const createSharedContext = () => ({+ lastRenderedItemNameRef: { current: null as string | null },+ $isTemporarilyShowingSelectedImage: atom(false),+ marker: createAutoSwitchedSelectionMarker(),+});++type Shared = ReturnType<typeof createSharedContext>;++const RevealProbe = ({+ shared,+ itemName,+ isMediaReady = true,+ hasProgressImage = true,+ isProgressImageResolving = false,+}: {+ shared: Shared;+ itemName: string | null;+ isMediaReady?: boolean;+ hasProgressImage?: boolean;+ isProgressImageResolving?: boolean;+}) => {+ useSelectedItemReveal({+ ...shared,+ durationMs: DURATION_MS,+ mediaGraceMs: MEDIA_GRACE_MS,+ renderedItemName: itemName,+ isMediaReady,+ selectedItemName: itemName,+ shouldShowProgressInViewer: true,+ hasProgressImage,+ isProgressImageResolving,+ });+ return null;+};++/** CurrentVideoPreview's readiness wiring: a real <video> element feeding usePaintedItemName. */+const VideoProbe = ({ shared, videoName }: { shared: Shared; videoName: string | null }) => {+ const { isMediaReady, onPainted } = usePaintedItemName(videoName);+ useSelectedItemReveal({+ ...shared,+ durationMs: DURATION_MS,+ mediaGraceMs: MEDIA_GRACE_MS,+ renderedItemName: videoName,+ isMediaReady,+ selectedItemName: videoName,+ shouldShowProgressInViewer: true,+ hasProgressImage: true,+ isProgressImageResolving: false,+ });+ return <video data-testid="probe-video" key={videoName ?? undefined} onLoadedData={onPainted} />;+};++describe('useSelectedItemReveal (mounted)', () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ vi.useFakeTimers();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ act(() => {+ root.unmount();+ });+ container.remove();+ vi.useRealTimers();+ });++ it('reveals a selection change and lowers when the duration elapses', () => {+ const shared = createSharedContext();+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="a.png" />);+ });+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="b.png" />);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(true);++ act(() => {+ vi.advanceTimersByTime(DURATION_MS);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ });++ it('lowers the flag on unmount and leaves no timer to re-raise it', () => {+ const shared = createSharedContext();+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="a.png" />);+ });+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="b.png" />);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(true);++ act(() => {+ root.unmount();+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get(), 'a reveal must not outlive its component').toBe(false);++ act(() => {+ vi.advanceTimersByTime(DURATION_MS * 2);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ root = createRoot(container); // afterEach unmounts a root; give it a live one+ });++ it('survives StrictMode double-invoked effects', () => {+ const shared = createSharedContext();+ act(() => {+ root.render(+ <StrictMode>+ <RevealProbe shared={shared} itemName="a.png" />+ </StrictMode>+ );+ });+ act(() => {+ root.render(+ <StrictMode>+ <RevealProbe shared={shared} itemName="b.png" />+ </StrictMode>+ );+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get(), 'the reveal survives the doubled effects').toBe(true);+ });++ it('carries the reveal across an image -> video component swap', () => {+ // The two preview components are mutually exclusive; the shared ref is what makes a click that+ // switches media type read as a selection change. Only a real unmount/mount can test that the+ // outgoing component's cleanup does not destroy the incoming one's reveal.+ const shared = createSharedContext();+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="a.png" />);+ });+ act(() => {+ root.render(<VideoProbe shared={shared} videoName="b.mp4" />);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get(), 'held for the unpainted video').toBe(false);++ const video = container.querySelector('video');+ expect(video).not.toBeNull();+ act(() => {+ video?.dispatchEvent(new Event('loadeddata'));+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get(), 'revealed once the frame is there').toBe(true);+ });++ it('does not reveal an auto-switched selection', () => {+ const shared = createSharedContext();+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="a.png" />);+ });+ shared.marker.record('b.png');+ shared.marker.settle('b.png');+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="b.png" />);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ });++ it('reveals an unpainted video after the media grace even if loadeddata never fires', () => {+ const shared = createSharedContext();+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="a.png" />);+ });+ act(() => {+ root.render(<VideoProbe shared={shared} videoName="never-loads.mp4" />);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ act(() => {+ vi.advanceTimersByTime(MEDIA_GRACE_MS);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get(), 'the click still lands').toBe(true);+ });++ it('resets readiness when the video element is swapped for another video', () => {+ // A stale "painted" from the previous element must not lift the overlay onto the new, black+ // one — the readiness is compared by name, so the swap cannot inherit it.+ const shared = createSharedContext();+ act(() => {+ root.render(<VideoProbe shared={shared} videoName="a.mp4" />);+ });+ act(() => {+ container.querySelector('video')?.dispatchEvent(new Event('loadeddata'));+ });+ act(() => {+ root.render(<VideoProbe shared={shared} videoName="b.mp4" />);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get(), 'held: the new element has not painted').toBe(false);+ act(() => {+ container.querySelector('video')?.dispatchEvent(new Event('loadeddata'));+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(true);+ });++ it("does not let the outgoing component's timer cut the incoming reveal short", () => {+ // Image A is mid-reveal when the user clicks video B. A's controller unmounts with ~1.5s left+ // on its timer; if the cleanup does not cancel it, that timer fires into the shared flag and+ // ends B's two seconds early.+ const shared = createSharedContext();+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="a.png" />);+ });+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="b.png" />);+ });+ act(() => {+ vi.advanceTimersByTime(500);+ });+ act(() => {+ root.render(<RevealProbe shared={shared} itemName="c.png" key="other-component" />);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(true);++ // Past where the outgoing component's timer would have fired, short of the new reveal's end.+ act(() => {+ vi.advanceTimersByTime(DURATION_MS - 400);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get(), 'the new reveal runs its full duration').toBe(true);++ act(() => {+ vi.advanceTimersByTime(400);+ });+ expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ });+});diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.tsnew file mode 100644index 0000000000..990ad14d46--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.ts@@ -0,0 +1,106 @@+import type { WritableAtom } from 'nanostores';+import { useCallback, useEffect, useState } from 'react';++import { createSelectedItemRevealController } from './selectedItemReveal';++type UseSelectedItemRevealArgs = {+ /** Shared with the other preview component via the viewer context, so a click that switches+ * media type still reads as a selection change on both ends. */+ lastRenderedItemNameRef: { current: string | null };+ /** The shared overlay-lift flag the progress overlay reads. */+ $isTemporarilyShowingSelectedImage: WritableAtom<boolean>;+ /** The auto-switch marker (see features/gallery/store/autoSwitchedImages). */+ marker: { consume: (itemName: string) => boolean };+ durationMs: number;+ mediaGraceMs: number;+ /** The item the component is rendering right now, or null when it has nothing to show. */+ renderedItemName: string | null;+ /** Whether that item has a frame on screen. See usePaintedItemName. */+ isMediaReady: boolean;+ /** The item the gallery selection points at, or null when the selection is empty. */+ selectedItemName: string | null;+ shouldShowProgressInViewer: boolean;+ hasProgressImage: boolean;+ isProgressImageResolving: boolean;+};++/**+ * The preview components' reveal wiring, extracted so it can be mounted and tested with real+ * effect lifecycles (see useSelectedItemReveal.test.tsx). The sequencing itself lives in the+ * controller — this hook owns what a component must get right around it:+ *+ * - one controller per mounted component, created once;+ * - `run` on every change of the inputs, with the cleanup cancelling only the timer — the next+ * run (or the unmount path) owns the revealed flag;+ * - the flag lowered on unmount, so a reveal cannot outlive the component that raised it.+ */+export const useSelectedItemReveal = ({+ lastRenderedItemNameRef,+ $isTemporarilyShowingSelectedImage,+ marker,+ durationMs,+ mediaGraceMs,+ renderedItemName,+ isMediaReady,+ selectedItemName,+ shouldShowProgressInViewer,+ hasProgressImage,+ isProgressImageResolving,+}: UseSelectedItemRevealArgs): void => {+ const [revealController] = useState(() =>+ createSelectedItemRevealController({+ lastRenderedItemNameRef,+ marker,+ setRevealed: (revealed) => $isTemporarilyShowingSelectedImage.set(revealed),+ durationMs,+ mediaGraceMs,+ })+ );++ useEffect(() => {+ revealController.run({+ shouldShowProgressInViewer,+ hasProgressImage,+ isProgressImageResolving,+ renderedItemName,+ isMediaReady,+ selectedItemName,+ });+ return () => {+ revealController.clearTimer();+ };+ }, [+ hasProgressImage,+ isMediaReady,+ isProgressImageResolving,+ renderedItemName,+ revealController,+ selectedItemName,+ shouldShowProgressInViewer,+ ]);++ useEffect(() => {+ return () => {+ $isTemporarilyShowingSelectedImage.set(false);+ };+ }, [$isTemporarilyShowingSelectedImage]);+};++/**+ * Which item's media has actually painted, as readiness for the item being rendered.+ *+ * Deliberately not a boolean: a boolean would be reset from a different effect than the one that+ * reads it, and a passive effect's setState does not reach the next effect's closure in the same+ * commit — so a video -> video click would read the new name with the previous video's readiness+ * and lift the overlay onto a black element. Comparing names cannot go stale that way.+ */+export const usePaintedItemName = (itemName: string | null) => {+ const [paintedItemName, setPaintedItemName] = useState<string | null>(null);+ const onPainted = useCallback(() => {+ setPaintedItemName(itemName);+ }, [itemName]);+ return {+ isMediaReady: itemName !== null && paintedItemName === itemName,+ onPainted,+ };+};diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/viewerProgressLifecycle.test.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/viewerProgressLifecycle.test.tsindex a3181382a7..2c9b073d8c 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/viewerProgressLifecycle.test.ts+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/viewerProgressLifecycle.test.ts@@ -114,6 +114,19 @@ describe('viewerProgressLifecycle', () => {});+ it('leaves the promoted session up when no further event arrives', () => {+ // The handoff must not be on borrowed time: after A finishes, B may go a long while before+ // its next progress event (a video render's steps are seconds apart), and no timer armed by+ // A's completion may take B's preview down in the meantime.+ const { eventB } = startTwoSessions();+ lifecycle.onTerminal(buildTerminalEvent({ item_id: 1, status: 'completed' }), true);+ lifecycle.onFinalImageLoaded('session-1');+ vi.advanceTimersByTime(RESOLVE_TIMEOUT_MS * 10);+ expect(stores.$progressEvent.get()).toBe(eventB);+ expect(stores.$progressImage.get()).toBe(eventB.image);+ expect(stores.$progressData.get()[2]?.itemId).toBe(2);+ });+it('hands the shared preview to the remaining session even when auto-switch is off', () => {const { eventB } = startTwoSessions();lifecycle.onTerminal(buildTerminalEvent({ item_id: 1, status: 'canceled' }), false);@@ -130,6 +143,34 @@ describe('viewerProgressLifecycle', () => {expect(stores.$progressEvent.get()?.item_id).toBe(1);});+ it('keeps promoting through a chain of terminations while any session is still generating', () => {+ // Three sessions, each promotion making the next owner: the shared preview must never be+ // torn down while something is still generating, no matter how many owners terminate. Each+ // terminal event here arrives with no further progress event behind it, so a promotion that+ // left the new owner unprotected would show up as a blank viewer on the next termination.+ const eventB = buildProgressEvent({ item_id: 2, session_id: 'session-2', image: buildProgressImage(2) });+ const eventC = buildProgressEvent({ item_id: 3, session_id: 'session-3', image: buildProgressImage(3) });+ const eventA = buildProgressEvent({ item_id: 1, session_id: 'session-1', image: buildProgressImage(1) });+ lifecycle.recordProgress(eventC);+ lifecycle.recordProgress(eventB);+ lifecycle.recordProgress(eventA);++ // A owns the preview and completes: B reported most recently of the two left, so B takes it.+ lifecycle.onTerminal(buildTerminalEvent({ item_id: 1, status: 'completed' }), true);+ expect(stores.$progressEvent.get()).toBe(eventB);++ // B is then canceled while C is still generating — C must take the preview, not lose it.+ lifecycle.onTerminal(buildTerminalEvent({ item_id: 2, status: 'canceled' }), true);+ expect(stores.$progressEvent.get()).toBe(eventC);+ expect(stores.$progressImage.get()).toBe(eventC.image);+ expect(stores.$isProgressImageResolving.get()).toBe(false);++ // Only when the last session ends does the preview come down.+ lifecycle.onTerminal(buildTerminalEvent({ item_id: 3, status: 'canceled' }), true);+ expect(stores.$progressEvent.get()).toBeNull();+ expect(stores.$progressImage.get()).toBeNull();+ });+it('leaves the shared preview alone when a non-owner terminates', () => {const { eventA } = startTwoSessions();lifecycle.onTerminal(buildTerminalEvent({ item_id: 2, status: 'canceled' }), true);diff --git a/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.test.ts b/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.test.tsnew file mode 100644index 0000000000..899397eeaa--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import { createAutoSwitchedSelectionMarker } from './autoSwitchedImages';++describe('createAutoSwitchedSelectionMarker', () => {+ it('reports the auto-switched item on its first render, once', () => {+ const marker = createAutoSwitchedSelectionMarker();+ marker.record('a.png');+ marker.settle('a.png');+ expect(marker.consume('a.png')).toBe(true);+ expect(marker.consume('a.png')).toBe(false);+ });++ it('reports nothing for an item that was never auto-switched to', () => {+ const marker = createAutoSwitchedSelectionMarker();+ expect(marker.consume('a.png')).toBe(false);+ });++ it('drops a marker whose selection was superseded before it rendered', () => {+ // The auto-switch to A is dispatched, then the user clicks B before A's preload settles. A can+ // never render as that auto-switch, and the user's later click on A must reveal it.+ const marker = createAutoSwitchedSelectionMarker();+ marker.record('a.png');+ marker.settle('a.png');+ marker.settle('b.png');+ marker.settle('a.png');+ expect(marker.consume('a.png')).toBe(false);+ });++ it('keeps only the last of several auto-switches settled in one batch', () => {+ // Two sessions completing together record two names, but only the last selection stands.+ const marker = createAutoSwitchedSelectionMarker();+ marker.record('a.png');+ marker.settle('a.png');+ marker.record('b.png');+ marker.settle('b.png');+ expect(marker.consume('b.png')).toBe(true);+ expect(marker.consume('a.png')).toBe(false);+ });++ it('survives settles that do not move the selection', () => {+ // Re-selecting the same item (or any other action that leaves the selection alone) must not+ // discard a marker whose item has not rendered yet.+ const marker = createAutoSwitchedSelectionMarker();+ marker.record('a.png');+ marker.settle('a.png');+ marker.settle('a.png');+ expect(marker.consume('a.png')).toBe(true);+ });++ it('drops the marker when the selection is cleared', () => {+ const marker = createAutoSwitchedSelectionMarker();+ marker.record('a.png');+ marker.settle('a.png');+ marker.settle(null);+ expect(marker.consume('a.png')).toBe(false);+ });++ it('does not report a second render of an item after its marker was consumed', () => {+ // The user navigates away and back: that second render is a user selection and must reveal.+ const marker = createAutoSwitchedSelectionMarker();+ marker.record('a.png');+ marker.settle('a.png');+ expect(marker.consume('a.png')).toBe(true);+ marker.settle('b.png');+ marker.settle('a.png');+ expect(marker.consume('a.png')).toBe(false);+ });++ it('does not clear a pending marker when a different item is consumed', () => {+ // The rendered item can lag a just-auto-switched selection: the viewer consumes for whatever+ // is still on screen, and that must not spend the marker the incoming item is owed.+ const marker = createAutoSwitchedSelectionMarker();+ marker.record('a.png');+ marker.settle('a.png');+ expect(marker.consume('b.png')).toBe(false);+ expect(marker.consume('a.png'), 'the marker survives an unrelated consume').toBe(true);+ });+});diff --git a/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.ts b/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.tsnew file mode 100644index 0000000000..d7ab900345--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.ts@@ -0,0 +1,61 @@+/**+ * Marks the gallery selection the auto-switch made, until the viewer renders it.+ *+ * The viewer briefly reveals a newly selected item over the progress overlay so that a+ * mid-generation gallery click is not invisible (see the reveal effect in CurrentImagePreview).+ * Auto-switch selections must not trigger that reveal — but they land asynchronously: the switch is+ * dispatched only after onInvocationComplete's DTO fetch resolves, and the viewer renders it only+ * after the thumbnail preload settles. When the next generation is started quickly, its first+ * invocation_progress event slots into that window and resets $isProgressImageResolving, so by the+ * time the auto-switch selection reaches the viewer it is indistinguishable from a user click and+ * the reveal flashes the previous result over the live preview for 2 seconds.+ *+ * The marker is scoped to the selection it was recorded for, not to the item name: it survives only+ * as long as that selection stands. A name-keyed marker cannot tell "this render is the auto-switch+ * landing" from "the user picked that same item later", so an auto-switch that never rendered —+ * because the user clicked elsewhere first — would swallow their later click on it, the very dead+ * click the reveal exists to prevent. Settling on every selection change closes that: once the+ * selection moves on, the recorded auto-switch can never render, and the marker goes with it.+ *+ * That scoping is also why no expiry or bound is needed. At most one marker exists, and only while+ * its selection is the current one.+ */+type AutoSwitchedSelectionMarker = {+ /** Records that the gallery is auto-switching the selection to this item. Call immediately+ * before dispatching that selection, so the settle it triggers sees the marker. */+ record: (itemName: string) => void;+ /**+ * Points the marker at the selection that now stands, dropping it unless it is still the one+ * recorded. Call on every selection change (see addAutoSwitchedSelectionListener).+ */+ settle: (selectedItemName: string | null) => void;+ /**+ * Returns whether the item now rendering is the one the auto-switch selected, clearing the+ * marker. Call on every change of the rendered item.+ */+ consume: (itemName: string) => boolean;+};++export const createAutoSwitchedSelectionMarker = (): AutoSwitchedSelectionMarker => {+ let pendingItemName: string | null = null;++ return {+ record: (itemName) => {+ pendingItemName = itemName;+ },+ settle: (selectedItemName) => {+ if (pendingItemName !== selectedItemName) {+ pendingItemName = null;+ }+ },+ consume: (itemName) => {+ if (pendingItemName !== itemName) {+ return false;+ }+ pendingItemName = null;+ return true;+ },+ };+};++export const autoSwitchedImages = createAutoSwitchedSelectionMarker();diff --git a/invokeai/frontend/web/src/services/api/endpoints/videos.ts b/invokeai/frontend/web/src/services/api/endpoints/videos.tsindex 49043d763a..3f7327ca49 100644--- a/invokeai/frontend/web/src/services/api/endpoints/videos.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/videos.ts@@ -352,14 +352,13 @@ export const {useDeleteUncategorizedVideosMutation,} = videosApi;+export const { useGetVideoMetadataQuery, useGetVideoWorkflowQuery, useLazyGetVideoWorkflowQuery } = videosApi;+/** @knipignore Reserved for follow-up phases (bulk delete / intermediate toggle / video-only views).* useDeleteVideoMutation is here because the only call site uses videosApi.endpoints.deleteVideo.initiate* via the delete-video modal, but a future bulk/multi-select flow may want the React hook form. */export const {useListVideosQuery,- useGetVideoMetadataQuery,- useGetVideoWorkflowQuery,- useLazyGetVideoWorkflowQuery,useGetVideoNamesQuery,useDeleteVideoMutation,useDeleteVideosMutation,diff --git a/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts b/invokeai/frontend/web/src/services/events/onInvocationComplete.test.tsindex 0a811360ae..a0eb18e986 100644--- a/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts+++ b/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts@@ -111,14 +111,26 @@ vi.mock('services/events/nodeExecutionState', () => ({getUpdatedNodeExecutionStateOnInvocationComplete: vi.fn(() => null),}));+// Mocked so a scheduled refetch that blunders into work it should have skipped is observable:+// deliver() catches its own throw and logs it, which is otherwise invisible from out here.+vi.mock('app/logging/logger', () => {+ const log = { debug: vi.fn(), trace: vi.fn(), warn: vi.fn(), error: vi.fn() };+ return { logger: () => log };+});+vi.mock('services/events/stores', () => ({$lastProgressEvent: { set: vi.fn() },}));// Import AFTER the mocks above are declared (vi.mock is hoisted; explicit ordering here// is for the human reader).+import { logger } from 'app/logging/logger';+import { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';+import { selectAutoSwitch } from 'features/gallery/store/gallerySelectors';+import { imageSelected } from 'features/gallery/store/gallerySlice';import { getImageDTOSafe } from 'services/api/endpoints/images';import { getVideoDTOSafe } from 'services/api/endpoints/videos';+import { $lastProgressEvent } from 'services/events/stores';import {buildOnForeignInvocationComplete,@@ -157,6 +169,10 @@ const buildImageCompleteEvent = (): S['InvocationCompleteEvent'] =>describe('onInvocationComplete polymorphic gallery cache', () => {beforeEach(() => {vi.clearAllMocks();+ // clearAllMocks resets calls, not implementations — restore the factory default so a test that+ // turns auto-switch on cannot leak it into the next one.+ vi.mocked(selectAutoSwitch).mockReturnValue(false);+ autoSwitchedImages.settle(null);});it('invalidates GalleryItemNameList + GalleryItemList when an image output completes', async () => {@@ -288,6 +304,1032 @@ describe('onInvocationComplete polymorphic gallery cache', () => {expect(galleryInvalidation?.payload).toContainEqual({ type: 'BoardVideosTotal', id: 'board-123' });expect(galleryInvalidation?.payload).toContain('VirtualBoards');});++ it('processes each completion event exactly once — a duplicate delivery does no gallery work', async () => {+ // Re-running the gallery handling on a duplicate double-counts the optimistic board totals and+ // re-records the auto-switch marker after it was consumed, which suppresses a later genuine+ // gallery click on that image.+ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ const dispatchCountAfterFirst = dispatch.mock.calls.length;+ expect(getImageDTOSafe).toHaveBeenCalledTimes(1);++ await handler(buildImageCompleteEvent());+ expect(getImageDTOSafe).toHaveBeenCalledTimes(1);+ expect(dispatch.mock.calls.length).toBe(dispatchCountAfterFirst);+ });++ it('rejects a duplicate that arrives while the first delivery is still awaiting its DTO fetch', async () => {+ // The gallery work awaits a DTO fetch, so a duplicate can land mid-flight. The handler must+ // mark the event as processed before the first await, not after.+ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await Promise.all([handler(buildImageCompleteEvent()), handler(buildImageCompleteEvent())]);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(1);+ });++ it('records a duplicated video completion once, so a later reselection of that video reveals', async () => {+ // The duplicate delivery used to re-run addVideosToGallery in full: a second auto-switch+ // marker record and a second selection dispatch. The dedupe must stop the whole re-run.+ autoSwitchedImages.settle(null); // the marker is a module singleton; start from empty+ vi.mocked(selectAutoSwitch).mockReturnValueOnce(true);+ vi.mocked(getVideoDTOSafe).mockResolvedValueOnce({+ video_name: 'fresh-video.mp4',+ video_url: 'mock://fresh-video.mp4',+ thumbnail_url: 'mock://thumb/fresh-video.mp4',+ width: 832,+ height: 480,+ duration_seconds: 3.4,+ frame_count: 81,+ is_intermediate: false,+ is_starred: false,+ board_id: null,+ created_at: '2026-01-01',+ updated_at: '2026-01-01',+ session_id: 'test-session',+ node_id: 'test-node',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const videoEvent = buildImageCompleteEvent();+ videoEvent.invocation.type = 'wan_l2v';+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (videoEvent as any).result = { video: { video_name: 'fresh-video.mp4' } };++ await handler(videoEvent);+ await handler(videoEvent);++ expect(getVideoDTOSafe).toHaveBeenCalledTimes(1);+ expect(imageSelected).toHaveBeenCalledTimes(1);++ // The rest of JPPhoto's sequence, against the real marker singleton: the auto-switched video+ // renders (consume), the user selects another item, then re-selects the video — which must+ // NOT read as an auto-switch, or the click is dead under the progress overlay.+ autoSwitchedImages.settle('fresh-video.mp4');+ expect(autoSwitchedImages.consume('fresh-video.mp4')).toBe(true);+ autoSwitchedImages.settle('some-other-item.png');+ autoSwitchedImages.settle('fresh-video.mp4');+ expect(autoSwitchedImages.consume('fresh-video.mp4')).toBe(false);+ });++ it('lets a re-delivery retry when the first attempt lost its DTO to a transient failure', async () => {+ // getImageDTOSafe swallows fetch errors and returns null, so a transient failure silently+ // drops the image from the gallery. Keeping the dedupe key in that case would make the loss+ // permanent — the redelivery that could fix it is turned away as a duplicate.+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatched: unknown[] = [];+ const dispatch = vi.fn((action: unknown) => {+ dispatched.push(action);+ return { unwrap: () => Promise.resolve(undefined) };+ });+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ expect(+ dispatched.some((action) => {+ const payload = (action as { payload?: unknown }).payload;+ return Array.isArray(payload) && payload.includes('GalleryItemNameList');+ }),+ 'a failed lookup produces no gallery work'+ ).toBe(false);++ await handler(buildImageCompleteEvent());+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ expect(+ dispatched.some((action) => {+ const payload = (action as { payload?: unknown }).payload;+ return Array.isArray(payload) && payload.includes('GalleryItemNameList');+ }),+ 'the retry must do the gallery work the first delivery lost'+ ).toBe(true);+ });++ it('retries only the output whose lookup failed, leaving the ones that landed alone', async () => {+ // One of two image lookups fails. The successful one's board totals and optimistic insert have+ // already gone out, so a re-delivery must not touch it — but the lost one is only recoverable+ // here, since nothing re-emits the event on its own.+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const twoImages = buildImageCompleteEvent();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (twoImages as any).result = {+ image_1: { image_name: 'first.png' },+ image_2: { image_name: 'second.png' },+ };++ await handler(twoImages);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);++ await handler(twoImages);+ // Exactly one more lookup, and it is the one that failed.+ expect(getImageDTOSafe).toHaveBeenCalledTimes(3);+ expect(vi.mocked(getImageDTOSafe).mock.calls.at(-1)?.[0]).toBe('first.png');++ // Once everything has landed, the event is closed again.+ await handler(twoImages);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(3);+ });++ it('retries a failed lookup inside an image collection', async () => {+ // Collections are where partial failure is actually plausible: the user sees most of a batch+ // and silently misses one image, its auto-switch, and its board count.+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const collection = buildImageCompleteEvent();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (collection as any).result = {+ collection: [{ image_name: 'batch-1.png' }, { image_name: 'batch-2.png' }, { image_name: 'batch-3.png' }],+ };++ await handler(collection);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(3);++ await handler(collection);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(4);+ expect(vi.mocked(getImageDTOSafe).mock.calls.at(-1)?.[0]).toBe('batch-1.png');+ });++ it('lets a duplicate that overlapped a lost delivery become the retry', async () => {+ // The duplicate arrives while the first delivery is still fetching, so it cannot be told yet+ // that the fetch will fail. Rejecting it outright strands the output: there is no third event.+ let resolveFirstLookup: (value: null) => void = () => {};+ vi.mocked(getImageDTOSafe).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirstLookup = resolve;+ })+ );++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const event = buildImageCompleteEvent();+ const first = handler(event);+ const duplicate = handler(event);++ // The first delivery's only lookup fails, losing the image.+ resolveFirstLookup(null);+ await Promise.all([first, duplicate]);++ // The duplicate picked the work back up rather than being discarded.+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ expect(vi.mocked(getImageDTOSafe).mock.calls.at(-1)?.[0]).toBe('fresh-image.png');+ });++ it('marks the selection it auto-switches to, so the viewer does not reveal it as a user click', async () => {+ // Without the marker the finished image flashes over the next generation's live preview for+ // two seconds — the regression this PR exists to fix. The marker is the only signal that can+ // tell the handoff from a click, since it lands after the next generation's first progress+ // event has already reset the timing-based guard.+ vi.mocked(selectAutoSwitch).mockReturnValue(true);+ autoSwitchedImages.settle(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());++ expect(autoSwitchedImages.consume('fresh-image.png')).toBe(true);+ });++ it('does not mark anything when auto-switch is off — nothing is selected to be revealed', async () => {+ vi.mocked(selectAutoSwitch).mockReturnValue(false);+ autoSwitchedImages.settle(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());++ expect(autoSwitchedImages.consume('fresh-image.png')).toBe(false);+ });++ it('retries only the image half of a mixed result, not the video that landed', async () => {+ // The video lookup succeeded, so its board invalidation and auto-switch already went out; a+ // re-delivery re-running them would invalidate twice and move the selection a second time.+ vi.mocked(selectAutoSwitch).mockReturnValue(true);+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);+ vi.mocked(getVideoDTOSafe).mockResolvedValueOnce({+ video_name: 'fresh-video.mp4',+ video_url: 'mock://fresh-video.mp4',+ thumbnail_url: 'mock://thumb/fresh-video.mp4',+ is_intermediate: false,+ is_starred: false,+ board_id: 'board-123',+ created_at: '2026-01-01',+ updated_at: '2026-01-01',+ session_id: 'test-session',+ node_id: 'test-node',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const mixed = buildImageCompleteEvent();+ mixed.invocation.type = 'wan_l2v';+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (mixed as any).result = {+ image: { image_name: 'lost-image.png' },+ video: { video_name: 'fresh-video.mp4' },+ };++ await handler(mixed);+ expect(getVideoDTOSafe).toHaveBeenCalledTimes(1);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(1);++ // The re-delivery refetches the lost image and leaves the video alone.+ await handler(mixed);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ expect(getVideoDTOSafe).toHaveBeenCalledTimes(1);+ });++ it('redoes only the gallery work on a retry, not the global side effects', async () => {+ // The canvas processing flag and $lastProgressEvent are global: by the time a re-delivery+ // arrives the user may have started another run, and clearing them again would stop that run's+ // spinner and blank its progress.+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatched: unknown[] = [];+ const dispatch = vi.fn((action: unknown) => {+ dispatched.push(action);+ return { unwrap: () => Promise.resolve(undefined) };+ });+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const canvasEvent = buildImageCompleteEvent();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (canvasEvent as any).origin = 'canvas_workflow_integration';++ await handler(canvasEvent);+ const canvasClears = () => dispatched.filter((a) => (a as { type?: string }).type === 'mock/canvasComplete').length;+ expect(canvasClears()).toBe(1);+ expect($lastProgressEvent.set).toHaveBeenCalledTimes(1);++ // The retry must redo the lost gallery fetch...+ await handler(canvasEvent);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ // ...and nothing else.+ expect(canvasClears()).toBe(1);+ expect($lastProgressEvent.set).toHaveBeenCalledTimes(1);+ });++ it('retries the lost output alongside an intermediate one, without redoing the intermediate', async () => {+ // An intermediate image never reaches the gallery, so there is nothing to redo for it — but the+ // lookup that failed beside it must still be recoverable.+ vi.mocked(getImageDTOSafe)+ .mockResolvedValueOnce(null)+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ .mockResolvedValueOnce({ image_name: 'intermediate.png', is_intermediate: true, board_id: null } as any);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const twoImages = buildImageCompleteEvent();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (twoImages as any).result = {+ image_1: { image_name: 'lost.png' },+ image_2: { image_name: 'intermediate.png' },+ };++ await handler(twoImages);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);++ // Only the lost output is refetched — the intermediate one never had gallery work to redo.+ await handler(twoImages);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(3);+ expect(vi.mocked(getImageDTOSafe).mock.calls.at(-1)?.[0]).toBe('lost.png');+ });++ it('serializes several duplicates waiting on one lost delivery into a single retry', async () => {+ // All three duplicates are parked on the same in-flight delivery. When it fails they all wake+ // up; only one may pick the work back up, or the retried output lands two or three times over.+ let resolveFirstLookup: (value: null) => void = () => {};+ vi.mocked(getImageDTOSafe).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirstLookup = resolve;+ })+ );++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const event = buildImageCompleteEvent();+ const deliveries = [handler(event), handler(event), handler(event), handler(event)];++ resolveFirstLookup(null);+ await Promise.all(deliveries);++ // One failed lookup plus exactly one retry.+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ });++ it('counts an image named twice in one result once', async () => {+ // An image collection concatenates its inputs without deduping, so the same name can appear+ // twice. It is one image: fetching and counting each occurrence inflates the board total.+ vi.mocked(selectAutoSwitch).mockReturnValue(true);++ const dispatched: unknown[] = [];+ const dispatch = vi.fn((action: unknown) => {+ dispatched.push(action);+ return { unwrap: () => Promise.resolve(undefined) };+ });+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const duplicated = buildImageCompleteEvent();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (duplicated as any).result = {+ collection: [{ image_name: 'dup.png' }, { image_name: 'dup.png' }],+ };++ await handler(duplicated);++ expect(getImageDTOSafe, 'one lookup for the repeated name').toHaveBeenCalledTimes(1);+ const boardTotalUpdates = dispatched.filter(+ (action) => (action as { type?: string }).type === 'mock/boardsApi/upsertQueryEntries'+ );+ expect(boardTotalUpdates).toHaveLength(1);+ });++ it('keeps a non-intermediate sibling of an intermediate output', async () => {+ // This used to bail out of the whole pass on the first intermediate, abandoning siblings that+ // belong in the gallery — and with per-output retry such a sibling is in nobody's missing set,+ // so no re-delivery could recover it.+ // mockResolvedValueOnce, not mockImplementation: clearAllMocks resets calls but not+ // implementations, so a persistent one would leak into every test after this.+ const dto = (imageName: string, isIntermediate: boolean) =>+ ({+ image_name: imageName,+ image_url: `mock://${imageName}`,+ thumbnail_url: `mock://thumb/${imageName}`,+ is_intermediate: isIntermediate,+ is_starred: false,+ image_category: 'general',+ board_id: null,+ created_at: '2026-01-01',+ updated_at: '2026-01-01',+ session_id: 'test-session',+ node_id: 'test-node',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ }) as any;+ vi.mocked(getImageDTOSafe)+ .mockResolvedValueOnce(dto('intermediate.png', true))+ .mockResolvedValueOnce(dto('keeper.png', false));++ const dispatched: unknown[] = [];+ const dispatch = vi.fn((action: unknown) => {+ dispatched.push(action);+ return { unwrap: () => Promise.resolve(undefined) };+ });+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const mixed = buildImageCompleteEvent();+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (mixed as any).result = {+ collection: [{ image_name: 'intermediate.png' }, { image_name: 'keeper.png' }],+ };++ await handler(mixed);++ const galleryInvalidation = dispatched.find((action) => {+ const payload = (action as { payload?: unknown }).payload;+ return Array.isArray(payload) && payload.includes('GalleryItemNameList');+ });+ expect(galleryInvalidation, 'the non-intermediate sibling must reach the gallery').toBeDefined();+ });++ it('does not move the selection again when a retry lands the lost output', async () => {+ // The re-delivery can arrive long after the user has selected something else.+ vi.mocked(selectAutoSwitch).mockReturnValue(true);+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ expect(imageSelected).not.toHaveBeenCalled();++ await handler(buildImageCompleteEvent());+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ expect(imageSelected, 'a retry lands the image without re-running the handoff').not.toHaveBeenCalled();+ });++ it('logs rather than rejecting when the gallery work throws', async () => {+ // Both call sites discard this handler's promise, so a rejection would surface only as an+ // unhandled rejection.+ const dispatch = vi.fn(() => {+ throw new Error('dispatch exploded');+ });+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await expect(handler(buildImageCompleteEvent())).resolves.toBeUndefined();+ });++ it('refetches a lost output on its own, without waiting for a duplicate delivery', async () => {+ // Nothing re-emits a completion event, so before this the recovery path only ran if the server+ // happened to send the event twice — which usually meant the output stayed missing.+ vi.useFakeTimers();+ try {+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ expect(getImageDTOSafe).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(1000);+ expect(getImageDTOSafe, 'the first backoff step refetches the missing name').toHaveBeenCalledTimes(2);++ // It succeeded this time, so nothing further is scheduled.+ await vi.advanceTimersByTimeAsync(60_000);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('gives up after a bounded number of refetches', async () => {+ // A permanently missing output must not retry forever.+ vi.useFakeTimers();+ try {+ vi.mocked(getImageDTOSafe).mockResolvedValue(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ await vi.advanceTimersByTimeAsync(120_000);++ // The delivery plus the three backoff steps, and no more.+ expect(getImageDTOSafe).toHaveBeenCalledTimes(4);+ } finally {+ vi.mocked(getImageDTOSafe).mockReset();+ vi.useRealTimers();+ }+ });++ it('drops a scheduled refetch when a duplicate delivery recovers the output first', async () => {+ vi.useFakeTimers();+ try {+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ // A re-delivery lands before the first backoff step and does the work.+ await handler(buildImageCompleteEvent());+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);++ await vi.advanceTimersByTimeAsync(60_000);+ expect(getImageDTOSafe, 'the scheduled retry finds nothing left to do').toHaveBeenCalledTimes(2);+ // ...and it works that out before starting a pass, rather than failing inside one.+ expect(logger('events').error).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not run a second chain of refetches when a duplicate delivery lands', async () => {+ // Each pass supersedes the refetch already queued for that event; two chains would run to+ // exhaustion side by side and double the bound the backoff is there to impose.+ vi.useFakeTimers();+ try {+ vi.mocked(getImageDTOSafe).mockResolvedValue(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ await vi.advanceTimersByTimeAsync(500);+ // A duplicate arrives mid-backoff and takes the work over.+ await handler(buildImageCompleteEvent());+ await vi.advanceTimersByTimeAsync(120_000);++ // Two deliveries plus one chain of three attempts — not two chains.+ expect(getImageDTOSafe).toHaveBeenCalledTimes(5);+ } finally {+ vi.mocked(getImageDTOSafe).mockReset();+ vi.useRealTimers();+ }+ });++ it('refreshes board state from the server on a retry instead of counting the output again', async () => {+ // A retry lands seconds later, by which time a gallery refetch or another delivery may already+ // have inserted the output. The name-list insert dedupes; the board totals are blind+ // increments, so re-running them would double-count.+ vi.mocked(getImageDTOSafe).mockResolvedValueOnce(null);++ const dispatched: unknown[] = [];+ const dispatch = vi.fn((action: unknown) => {+ dispatched.push(action);+ return { unwrap: () => Promise.resolve(undefined) };+ });+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ const beforeRetry = dispatched.length;++ await handler(buildImageCompleteEvent());++ const retryDispatches = dispatched.slice(beforeRetry);+ expect(+ retryDispatches.some((action) => (action as { type?: string }).type === 'mock/boardsApi/upsertQueryEntries'),+ 'no optimistic total bump on a retry'+ ).toBe(false);+ expect(+ retryDispatches.some((action) => {+ const payload = (action as { payload?: unknown }).payload;+ return Array.isArray(payload) && payload.some((tag) => (tag as { type?: string })?.type === 'BoardImagesTotal');+ }),+ 'the board totals are refreshed from the server instead'+ ).toBe(true);+ });++ it('drops pending refetches when its session is torn down', async () => {+ // The timers close over an event from *this* session but dispatch into whatever store is+ // current when they fire, so a logout or account switch inside the retry window would fetch+ // the old session's output into the new session's caches.+ vi.useFakeTimers();+ try {+ vi.mocked(getImageDTOSafe).mockResolvedValue(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ expect(getImageDTOSafe).toHaveBeenCalledTimes(1);++ handler.dispose();+ await vi.advanceTimersByTimeAsync(120_000);++ expect(getImageDTOSafe, 'nothing from the old session fires afterwards').toHaveBeenCalledTimes(1);+ } finally {+ vi.mocked(getImageDTOSafe).mockReset();+ vi.useRealTimers();+ }+ });++ it('does not let a lookup that was already in flight schedule work after disposal', async () => {+ // Clearing the queued timers is not enough: the DTO request that was mid-flight when the+ // session ended comes back afterwards, and would schedule its refetch against whatever store+ // has replaced it.+ vi.useFakeTimers();+ try {+ let failFirstLookup: (value: null) => void = () => {};+ vi.mocked(getImageDTOSafe).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ failFirstLookup = resolve;+ })+ );++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const delivery = handler(buildImageCompleteEvent());+ expect(getImageDTOSafe).toHaveBeenCalledTimes(1);++ // The socket goes away while that lookup is still outstanding, and only then does it fail.+ handler.dispose();+ failFirstLookup(null);+ await delivery;+ // Checked before advancing: a timer armed here would fire and be gone by the time the clock+ // moved, so asserting afterwards would pass either way.+ expect(vi.getTimerCount(), 'nothing is armed for a session that has ended').toBe(0);++ await vi.advanceTimersByTimeAsync(120_000);+ expect(getImageDTOSafe, 'and nothing is refetched for it').toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('does not dispatch an output whose lookup resolved after disposal', async () => {+ // The DTO belongs to the session that has just ended; inserting it now puts one user's output+ // in the next user's gallery.+ vi.useFakeTimers();+ try {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let resolveLookup: (value: any) => void = () => {};+ vi.mocked(getImageDTOSafe).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveLookup = resolve;+ })+ );++ const dispatched: unknown[] = [];+ const dispatch = vi.fn((action: unknown) => {+ dispatched.push(action);+ return { unwrap: () => Promise.resolve(undefined) };+ });+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const delivery = handler(buildImageCompleteEvent());+ handler.dispose();+ resolveLookup({+ image_name: 'from-old-session.png',+ board_id: null,+ is_intermediate: false,+ image_category: 'general',+ session_id: 'old-session',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any);+ await delivery;++ expect(+ dispatched.some((action) => {+ const payload = (action as { payload?: unknown }).payload;+ return Array.isArray(payload) && payload.includes('GalleryItemNameList');+ }),+ 'no gallery work for the session that ended'+ ).toBe(false);+ // $lastProgressEvent is module-global: clearing it now would blank whatever the session that+ // replaced this one has put there.+ expect($lastProgressEvent.set).not.toHaveBeenCalledWith(null);+ } finally {+ vi.useRealTimers();+ }+ });++ it('resumes the backoff for a duplicate rather than restarting it', async () => {+ // A stream of duplicates during an outage would otherwise start a fresh 1s chain each time,+ // so the "bounded" refetch would never actually be bounded.+ vi.useFakeTimers();+ try {+ vi.mocked(getImageDTOSafe).mockResolvedValue(null);++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const event = buildImageCompleteEvent();+ await handler(event);+ // Duplicates keep arriving *after* each scheduled attempt has fired — the shape that used to+ // restart the chain rather than continue it.+ for (let i = 0; i < 5; i++) {+ await vi.advanceTimersByTimeAsync(15_000);+ await handler(event);+ }+ await vi.advanceTimersByTimeAsync(120_000);++ // Six deliveries, and one shared chain of three attempts across all of them.+ expect(getImageDTOSafe).toHaveBeenCalledTimes(9);+ } finally {+ vi.mocked(getImageDTOSafe).mockReset();+ vi.useRealTimers();+ }+ });++ it('ignores an event delivered after disposal', async () => {+ // The socket is being torn down, but an event already queued for dispatch can still arrive.+ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ handler.dispose();+ await handler(buildImageCompleteEvent());++ expect(getImageDTOSafe).not.toHaveBeenCalled();+ });++ it('does not act on a video completion whose lookup resolved after disposal', async () => {+ // Every other disposal test uses an image event; the video path has its own dispatches — the+ // board invalidation, the auto-switch marker, the selection — behind its own guard.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let resolveLookup: (value: any) => void = () => {};+ vi.mocked(getVideoDTOSafe).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveLookup = resolve;+ })+ );+ vi.mocked(selectAutoSwitch).mockReturnValue(true);++ const dispatched: unknown[] = [];+ const dispatch = vi.fn((action: unknown) => {+ dispatched.push(action);+ return { unwrap: () => Promise.resolve(undefined) };+ });+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const videoEvent = buildImageCompleteEvent();+ videoEvent.invocation.type = 'wan_l2v';+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (videoEvent as any).result = { video: { video_name: 'from-old-session.mp4' } };++ const delivery = handler(videoEvent);+ // Disposal must land while the lookup is in flight — disposing before the handler's first+ // await resumes would be stopped by the fetch-loop guard instead, leaving the post-fetch+ // guard unexercised.+ while (vi.mocked(getVideoDTOSafe).mock.calls.length === 0) {+ await Promise.resolve();+ }+ handler.dispose();+ resolveLookup({+ video_name: 'from-old-session.mp4',+ board_id: 'board-123',+ is_intermediate: false,+ session_id: 'old-session',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ } as any);+ await delivery;++ expect(imageSelected, 'the dead session must not move the new selection').not.toHaveBeenCalled();+ expect(+ dispatched.some((action) => {+ const payload = (action as { payload?: unknown }).payload;+ return Array.isArray(payload) && payload.includes('GalleryItemNameList');+ }),+ 'and must not invalidate its gallery'+ ).toBe(false);+ });++ it('stops fetching the rest of a result once its session has ended', async () => {+ // Disposal mid-collection: the remaining lookups would run under the replacement session's+ // credentials and write into its cache. One event, image collection + video: dispose during+ // the first image fetch, and neither the second image nor the video may be requested.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let resolveFirst: (value: any) => void = () => {};+ vi.mocked(getImageDTOSafe).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirst = resolve;+ })+ );++ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));+ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ const mixed = buildImageCompleteEvent();+ mixed.invocation.type = 'wan_l2v';+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (mixed as any).result = {+ collection: [{ image_name: 'first.png' }, { image_name: 'second.png' }],+ video: { video_name: 'tail.mp4' },+ };++ const delivery = handler(mixed);+ handler.dispose();+ resolveFirst(null);+ await delivery;++ expect(getImageDTOSafe, 'no further image lookups after disposal').toHaveBeenCalledTimes(1);+ expect(getVideoDTOSafe, 'and no video lookup at all').not.toHaveBeenCalled();+ });++ it('still processes distinct invocations of the same queue item', async () => {+ const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));+ const getState = vi.fn(() => ({}));++ const handler = buildOnInvocationComplete(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ getState as any,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ dispatch as any,+ new Map()+ );++ await handler(buildImageCompleteEvent());+ const secondNode = buildImageCompleteEvent();+ secondNode.invocation.id = 'prepared-node-2';+ await handler(secondNode);+ expect(getImageDTOSafe).toHaveBeenCalledTimes(2);+ });});describe('buildOnForeignInvocationComplete', () => {diff --git a/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx b/invokeai/frontend/web/src/services/events/onInvocationComplete.tsxindex 5318043749..f79cea1cf5 100644--- a/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx+++ b/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx@@ -1,6 +1,7 @@import { logger } from 'app/logging/logger';import type { AppDispatch, AppGetState } from 'app/store/store';import { canvasWorkflowIntegrationProcessingCompleted } from 'features/controlLayers/store/canvasWorkflowIntegrationSlice';+import { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';import {selectAutoSwitch,selectGalleryView,@@ -11,6 +12,7 @@ import {import { boardIdSelected, galleryViewChanged, imageSelected } from 'features/gallery/store/gallerySlice';import { $nodeExecutionStates, upsertExecutionState } from 'features/nodes/hooks/useNodeExecutionState';import { isImageField, isImageFieldCollection, isVideoField } from 'features/nodes/types/common';+import { LRUCache } from 'lru-cache';import type { ApiTagDescription } from 'services/api';import { api, LIST_ALL_TAG, LIST_TAG } from 'services/api';import { boardsApi } from 'services/api/endpoints/boards';@@ -31,6 +33,44 @@ import type { JsonObject } from 'type-fest';const log = logger('events');+/**+ * What a completion event still has outstanding.+ *+ * `done` rejects any re-delivery. `retryable` names the outputs whose DTO lookup failed — the ones+ * that never reached the gallery — so a re-delivery can fetch exactly those again. Tracking the+ * missing outputs rather than the event as a whole is what makes a partial failure recoverable: an+ * event-wide flag would either re-run the outputs that did land (double-counting their board totals+ * and optimistic inserts) or abandon the one that did not.+ */+type ProcessedInvocationState =+ | { status: 'done' }+ | {+ status: 'retryable';+ missingNames: ReadonlySet<string>;+ /** How many refetches this event has already had. Carried on the state rather than passed+ * down the call chain so a duplicate delivery resumes the backoff instead of restarting it —+ * a stream of duplicates during an outage would otherwise start a fresh 1s chain each time. */+ attempts: number;+ };++/**+ * When to retry outputs a delivery lost to a failed DTO lookup, and how many times.+ *+ * Recovery used to depend on the server happening to re-deliver the completion event: nothing+ * re-emits one on its own, so an output lost to a transient failure usually stayed lost until the+ * gallery was refetched for some unrelated reason. These are spaced to ride out a brief network+ * blip without hammering a server that is actually down, and bounded because an output that is+ * still missing after ~13 seconds is not coming back from a retry — the image is gone, or the+ * problem is bigger than this handler.+ */+const RETRY_BACKOFF_MS = [1000, 3000, 9000];++/** The completion handler, plus the teardown hook its scheduled refetches require. */+type InvocationCompleteHandler = ((data: S['InvocationCompleteEvent']) => Promise<void>) & {+ /** Ends this handler's session: nothing it has in flight or queued may touch the next one. */+ dispose: () => void;+};+// These nodes are passthrough nodes. They do not add images/videos to the gallery — their// outputs reference an existing asset — so we must skip the gallery handling for them.// Without 'video' here, a Video Primitive completing mid-run would invalidate the gallery@@ -53,27 +93,74 @@ export const buildOnInvocationComplete = (dispatch: AppDispatch,completedInvocationKeysByItemId: Map<number, Set<string>>) => {- const addImagesToGallery = async (data: S['InvocationCompleteEvent']) => {+ // A duplicate delivery of a completion event must not repeat the work below: re-running the+ // gallery handling double-counts the optimistic board totals and re-dispatches the auto-switch+ // selection. The shared completedInvocationKeysByItemId map cannot detect this — the+ // workflow coordinator pre-marks first-delivery events for non-active workflow items before this+ // handler runs — so the handler tracks what it has processed itself. The invocation id half of+ // the key is the prepared node's per-execution UUID, so keys cannot collide across distinct+ // executions even where item ids restart (in-memory DB); the LRU bounds memory.+ const processedInvocations = new LRUCache<string, ProcessedInvocationState>({ max: 1000 });+ // Deliveries currently fetching, so a duplicate can wait for one instead of being discarded.+ // Entries live only for the duration of a pass; the LRU above is what bounds long-term memory.+ const inFlightDeliveries = new Map<string, Promise<void>>();+ // The pending refetch for each event, so a new pass supersedes it rather than running beside it.+ const scheduledRetries = new Map<string, ReturnType<typeof setTimeout>>();+ // Set when this handler's socket/session goes away. Every await below is a point where the store+ // underneath can have become a different user's, so the flag is checked after each one: clearing+ // the queued timers alone still let a DTO fetch that was already in flight come back and dispatch+ // into — or schedule more work against — the session that replaced this one.+ let isDisposed = false;++ // `retryNames`, when set, restricts this pass to the outputs a previous delivery lost to a failed+ // lookup — everything else already landed and must not be dispatched twice.+ const addImagesToGallery = async (+ data: S['InvocationCompleteEvent'],+ onLookupFailure: (imageName: string) => void,+ retryNames: ReadonlySet<string> | null+ ) => {+ // A retry exists to land an output the gallery lost, not to re-run the handoff around it. By+ // the time a re-delivery arrives the user has had time to select something else, and pulling+ // the selection back would be a worse failure than the one being repaired.+ const isRetry = retryNames !== null;if (nodeTypeDenylist.includes(data.invocation.type)) {log.trace(`Skipping denylisted node type (${data.invocation.type})`);return;}- const imageDTOs = await getResultImageDTOs(data);+ const fetchedImageDTOs = await getResultImageDTOs(data, onLookupFailure, retryNames);+ if (isDisposed) {+ // The session that asked for these is gone; dispatching now would insert its outputs into+ // whichever one replaced it.+ return;+ }+ // Intermediates never reach the gallery. Dropping them here rather than bailing out of the+ // whole pass on the first one (which is what this used to do) matters now that a delivery's+ // outputs are tracked individually: a sibling abandoned that way is in nobody's missing set,+ // so no re-delivery could ever recover it. Mirrors addVideosToGallery.+ const imageDTOs = fetchedImageDTOs.filter((imageDTO) => !imageDTO.is_intermediate);if (imageDTOs.length === 0) {return;}+ if (isRetry) {+ // A retry lands seconds after the fact, and the optimistic bookkeeping below assumes this+ // delivery is the first thing to know about the output. By now a gallery refetch, or another+ // delivery, may already have inserted it: the name-list insert dedupes, but the board totals+ // are blind increments and would count it twice. Ask the server instead — a retry is rare+ // enough that one authoritative refresh is cheaper than making every optimistic update+ // idempotent against the cache.+ const retriedBoards = [...new Set(imageDTOs.map((imageDTO) => imageDTO.board_id ?? 'none'))];+ dispatch(galleryApi.util.invalidateTags(getTagsToInvalidateForBoardAffectingMutation(retriedBoards)));+ return;+ }+// For efficiency's sake, we want to minimize the number of dispatches and invalidations we do.// We'll keep track of each change we need to make and do them all at once.const boardTotalAdditions: Record<string, number> = {};const getImageNamesArg = selectGetImageNamesQueryArgs(getState());for (const imageDTO of imageDTOs) {- if (imageDTO.is_intermediate) {- return;- }-const board_id = imageDTO.board_id ?? 'none';// update the total images for the boardboardTotalAdditions[board_id] = (boardTotalAdditions[board_id] || 0) + 1;@@ -182,7 +269,7 @@ export const buildOnInvocationComplete = (const autoSwitch = selectAutoSwitch(getState());- if (!autoSwitch) {+ if (!autoSwitch || isRetry) {return;}@@ -196,6 +283,12 @@ export const buildOnInvocationComplete = (const { image_name } = lastImageDTO;const board_id = lastImageDTO.board_id ?? 'none';+ // Both branches below auto-switch the selection to this image. Record that so the viewer's+ // reveal effect can tell the handoff apart from a user's gallery click — this dispatch happens+ // after an async DTO fetch, so it can land after the next generation's first progress event has+ // already reset $isProgressImageResolving, and timing alone cannot distinguish the two.+ autoSwitchedImages.record(image_name);+// With optimistic updates, we can immediately switch to the new imageconst selectedBoardId = selectSelectedBoardId(getState());@@ -222,35 +315,78 @@ export const buildOnInvocationComplete = (}};- const getResultImageDTOs = async (data: S['InvocationCompleteEvent']): Promise<ImageDTO[]> => {+ // getImageDTOSafe swallows fetch errors and returns null, which downstream is indistinguishable+ // from "this node produced no image". onLookupFailure separates the two, naming the output that+ // was lost so a re-delivery can fetch just that one again.+ const getResultImageDTOs = async (+ data: S['InvocationCompleteEvent'],+ onLookupFailure: (imageName: string) => void,+ retryNames: ReadonlySet<string> | null+ ): Promise<ImageDTO[]> => {const { result } = data;const imageDTOs: ImageDTO[] = [];+ const fetched = new Set<string>();+ const fetch = async (imageName: string) => {+ if (isDisposed) {+ // The session that wanted these is gone; issuing more requests would fetch under the+ // replacement session's credentials and write into its RTK cache.+ return;+ }+ if (retryNames !== null && !retryNames.has(imageName)) {+ return;+ }+ // A result can name the same image twice (an image collection concatenates its inputs+ // without deduping). It is still one image: fetching it once keeps its board total counted+ // once, and keeps the retry set — which is keyed by name — from re-admitting an occurrence+ // that already landed.+ if (fetched.has(imageName)) {+ return;+ }+ fetched.add(imageName);+ const imageDTO = await getImageDTOSafe(imageName);+ if (imageDTO) {+ imageDTOs.push(imageDTO);+ } else {+ onLookupFailure(imageName);+ }+ };for (const [_name, value] of objectEntries(result)) {if (isImageField(value)) {- const imageDTO = await getImageDTOSafe(value.image_name);- if (imageDTO) {- imageDTOs.push(imageDTO);- }+ await fetch(value.image_name);} else if (isImageFieldCollection(value)) {for (const imageField of value) {- const imageDTO = await getImageDTOSafe(imageField.image_name);- if (imageDTO) {- imageDTOs.push(imageDTO);- }+ await fetch(imageField.image_name);}}}return imageDTOs;};- const getResultVideoDTOs = async (data: S['InvocationCompleteEvent']): Promise<VideoDTO[]> => {+ const getResultVideoDTOs = async (+ data: S['InvocationCompleteEvent'],+ onLookupFailure: (videoName: string) => void,+ retryNames: ReadonlySet<string> | null+ ): Promise<VideoDTO[]> => {const { result } = data;const videoDTOs: VideoDTO[] = [];+ const fetched = new Set<string>();for (const [_name, value] of objectEntries(result)) {+ if (isDisposed) {+ break;+ }if (isVideoField(value)) {+ if (retryNames !== null && !retryNames.has(value.video_name)) {+ continue;+ }+ if (fetched.has(value.video_name)) {+ continue;+ }+ fetched.add(value.video_name);const videoDTO = await getVideoDTOSafe(value.video_name);if (videoDTO) {videoDTOs.push(videoDTO);+ } else {+ onLookupFailure(value.video_name);}}}@@ -266,12 +402,21 @@ export const buildOnInvocationComplete = (// (DndImage onLoad) to clear them. When auto-switching to a video, the viewer swaps// CurrentImagePreview for CurrentVideoPreview, which unmounts the stale progress overlay// so the stuck "Saving video" spinner goes away on its own.- const addVideosToGallery = async (data: S['InvocationCompleteEvent']) => {+ const addVideosToGallery = async (+ data: S['InvocationCompleteEvent'],+ onLookupFailure: (videoName: string) => void,+ retryNames: ReadonlySet<string> | null+ ) => {+ // See addImagesToGallery: a retry does not redo the auto-switch.+ const isRetry = retryNames !== null;if (nodeTypeDenylist.includes(data.invocation.type)) {return;}- const videoDTOs = await getResultVideoDTOs(data);+ const videoDTOs = await getResultVideoDTOs(data, onLookupFailure, retryNames);+ if (isDisposed) {+ return;+ }if (videoDTOs.length === 0) {return;}@@ -296,7 +441,7 @@ export const buildOnInvocationComplete = (dispatch(galleryApi.util.invalidateTags(getTagsToInvalidateForBoardAffectingMutation(affectedBoards)));const autoSwitch = selectAutoSwitch(getState());- if (!autoSwitch) {+ if (!autoSwitch || isRetry) {return;}@@ -308,6 +453,13 @@ export const buildOnInvocationComplete = (const { video_name } = lastVideoDTO;const board_id = lastVideoDTO.board_id ?? 'none';+ // Both branches below auto-switch the selection to this video. Record that so the viewer's+ // reveal effect can tell the handoff apart from a user's gallery click — this dispatch happens+ // after an async DTO fetch, so it can land after the next render's first progress event has+ // already reset $isProgressImageResolving, and timing alone cannot distinguish the two. The+ // marker is keyed by gallery item name, which is polymorphic across images and videos.+ autoSwitchedImages.record(video_name);+// Selection is a polymorphic string[]; useGalleryItemDTO discriminates by filename extension.const selectedBoardId = selectSelectedBoardId(getState());if (board_id !== selectedBoardId) {@@ -350,36 +502,218 @@ export const buildOnInvocationComplete = (}};- return async (data: S['InvocationCompleteEvent']) => {- log.debug({ data } as JsonObject, `Invocation complete (${data.invocation.type}, ${data.invocation_source_id})`);+ /**+ * One pass over a completion event. `retryNames` is null for a first delivery and otherwise names+ * the outputs an earlier delivery lost, restricting this pass to those.+ *+ * Returns the outputs whose lookup failed this time. Bookkeeping is done here, before the+ * returned promise settles, so a duplicate waiting on it always observes the final state.+ */+ const deliver = async (+ data: S['InvocationCompleteEvent'],+ invocationKey: string,+ retryNames: ReadonlySet<string> | null,+ attemptsSoFar: number+ ): Promise<void> => {+ const isRetry = retryNames !== null;+ const missingNames = new Set<string>();+ const onLookupFailure = (itemName: string) => {+ missingNames.add(itemName);+ };++ // A retry redoes the lost gallery work and nothing else: the rest of this handler is not+ // idempotent against a *later* generation, because the canvas processing flag and+ // $lastProgressEvent are global. Re-running them would end the spinner and blank the progress+ // of whatever is running by then.+ if (!isRetry) {+ const nodeExecutionState = $nodeExecutionStates.get()[data.invocation_source_id];+ const updatedNodeExecutionState = getUpdatedNodeExecutionStateOnInvocationComplete(+ nodeExecutionState,+ data,+ completedInvocationKeysByItemId+ );++ if (nodeExecutionState && !updatedNodeExecutionState) {+ log.trace(+ { data } as JsonObject,+ `Ignoring duplicate invocation complete (${data.invocation.type}, ${data.invocation_source_id})`+ );+ }++ if (updatedNodeExecutionState) {+ upsertExecutionState(updatedNodeExecutionState.nodeId, updatedNodeExecutionState);+ }- const nodeExecutionState = $nodeExecutionStates.get()[data.invocation_source_id];- const updatedNodeExecutionState = getUpdatedNodeExecutionStateOnInvocationComplete(- nodeExecutionState,- data,- completedInvocationKeysByItemId+ // Clear canvas workflow integration processing state if needed+ clearCanvasWorkflowIntegrationProcessing(data);+ }++ try {+ // Add images to gallery (canvas workflow integration results go to staging area automatically)+ await addImagesToGallery(data, onLookupFailure, retryNames);+ await addVideosToGallery(data, onLookupFailure, retryNames);++ if (!isRetry && !isDisposed) {+ // $lastProgressEvent is module-global, shared across handler sessions: a delivery that was+ // in flight when this session ended must not blank whatever the next session has put there.+ $lastProgressEvent.set(null);+ }+ } catch (error) {+ // Both call sites discard this handler's promise, so a throw here would surface as an+ // unhandled rejection and nothing else. Log it and let the bookkeeping below run: the+ // outputs whose lookups failed are still worth recording as retryable.+ log.error({ data, error } as JsonObject, `Error handling invocation complete: ${String(error)}`);+ } finally {+ if (missingNames.size > 0) {+ processedInvocations.set(invocationKey, { status: 'retryable', missingNames, attempts: attemptsSoFar });+ }+ }+ };++ /**+ * Run one pass and record what it left outstanding, scheduling the next attempt if anything is+ * still missing. `nextAttempt` indexes RETRY_BACKOFF_MS for the retry this pass would schedule;+ * a socket delivery starts at 0, so its first retry waits RETRY_BACKOFF_MS[0].+ */+ const runTrackedDelivery = async (+ data: S['InvocationCompleteEvent'],+ invocationKey: string,+ retryNames: ReadonlySet<string> | null,+ nextAttempt: number+ ): Promise<void> => {+ if (isDisposed) {+ return;+ }++ // This pass supersedes any refetch already queued for the event: leaving that timer armed would+ // run a second chain of attempts alongside this one, doubling the bound RETRY_BACKOFF_MS is+ // supposed to impose.+ const queued = scheduledRetries.get(invocationKey);+ if (queued !== undefined) {+ clearTimeout(queued);+ scheduledRetries.delete(invocationKey);+ }++ // Mark before the awaits below so a duplicate cannot start a second pass over the same outputs+ // while this one is in flight; the handshake in the handler is what lets it retry afterwards.+ processedInvocations.set(invocationKey, { status: 'done' });++ const delivery = deliver(data, invocationKey, retryNames, nextAttempt);+ // Waiters only need to know when the pass finished, not whether it threw.+ const settled = delivery.then(+ () => undefined,+ () => undefined);+ inFlightDeliveries.set(invocationKey, settled);+ try {+ await delivery;+ } finally {+ if (inFlightDeliveries.get(invocationKey) === settled) {+ inFlightDeliveries.delete(invocationKey);+ }+ }++ const outcome = processedInvocations.get(invocationKey);+ if (outcome?.status === 'retryable') {+ // nextAttempt is where this pass would resume the backoff; the state carries where the event+ // actually got to, so a duplicate that superseded a queued retry continues the chain rather+ // than restarting it at one second.+ scheduleRetry(data, invocationKey, Math.max(nextAttempt, outcome.attempts), outcome.missingNames);+ }+ };++ const scheduleRetry = (+ data: S['InvocationCompleteEvent'],+ invocationKey: string,+ attempt: number,+ missingNames: ReadonlySet<string>+ ) => {+ if (isDisposed) {+ return;+ }+ const delayMs = RETRY_BACKOFF_MS[attempt];+ if (delayMs === undefined) {+ log.warn(+ { data } as JsonObject,+ `Gave up refetching outputs for ${data.invocation.type} (${data.invocation_source_id}) after ${attempt} attempts`+ );+ // Left 'retryable' on purpose: a re-delivered completion can still recover it for free.+ return;+ }+ // Bare setTimeout, not the window member: this module is unit tested outside a DOM.+ // The names are captured here rather than read back from processedInvocations when the timer+ // fires: that cache is a bounded LRU, and a burst of completions can evict this entry in the+ // meantime. Reading it back would turn eviction into "silently give up on the output", which+ // is the failure the refetch exists to prevent.+ const missingAtSchedule = missingNames;+ const timeout = setTimeout(() => {+ scheduledRetries.delete(invocationKey);+ const state = processedInvocations.get(invocationKey);+ if (state !== undefined && state.status !== 'retryable') {+ // A duplicate delivery got there first, or the outputs landed some other way.+ return;+ }+ void runTrackedDelivery(data, invocationKey, state?.missingNames ?? missingAtSchedule, attempt + 1);+ }, delayMs);+ scheduledRetries.set(invocationKey, timeout);+ };++ const onInvocationComplete: InvocationCompleteHandler = async (data: S['InvocationCompleteEvent']) => {+ log.debug({ data } as JsonObject, `Invocation complete (${data.invocation.type}, ${data.invocation_source_id})`);- if (nodeExecutionState && !updatedNodeExecutionState) {+ const invocationKey = `${data.item_id}:${data.invocation.id}`;+ const logDuplicate = () => {log.trace({ data } as JsonObject,`Ignoring duplicate invocation complete (${data.invocation.type}, ${data.invocation_source_id})`);- }+ };- if (updatedNodeExecutionState) {- upsertExecutionState(updatedNodeExecutionState.nodeId, updatedNodeExecutionState);+ // A duplicate that lands while the first delivery is still fetching waits for it rather than+ // being discarded: if that delivery lost outputs to failed lookups, this duplicate is the only+ // thing that can recover them — nothing re-emits the event on its own. This check must come+ // before the 'done' one, which the in-flight delivery has already written by now.+ //+ // Several duplicates can be waiting here at once. They resume one at a time, and the first to+ // find work marks the event 'done' again before it suspends, so the rest fall through to the+ // duplicate branch rather than starting parallel retries.+ const inFlight = inFlightDeliveries.get(invocationKey);+ if (inFlight) {+ await inFlight;+ if (processedInvocations.get(invocationKey)?.status !== 'retryable') {+ logDuplicate();+ return;+ }+ } else if (processedInvocations.get(invocationKey)?.status === 'done') {+ logDuplicate();+ return;}- // Clear canvas workflow integration processing state if needed- clearCanvasWorkflowIntegrationProcessing(data);-- // Add images to gallery (canvas workflow integration results go to staging area automatically)- await addImagesToGallery(data);- await addVideosToGallery(data);+ const state = processedInvocations.get(invocationKey);+ const retryNames = state?.status === 'retryable' ? state.missingNames : null;+ // A duplicate resumes this event's backoff where it had got to. Starting it over at one second+ // would make the bound meaningless: a stream of duplicates during an outage — exactly when+ // duplicates are likely — would restart the chain indefinitely.+ const resumeAttempt = state?.status === 'retryable' ? state.attempts : 0;+ await runTrackedDelivery(data, invocationKey, retryNames, resumeAttempt);+ };- $lastProgressEvent.set(null);+ /**+ * Drops every pending refetch. Must be called when the socket or the authenticated session goes+ * away: the timers hold a closure over an event from *that* session but dispatch into whatever+ * store is current when they fire, so a logout or account switch inside the retry window would+ * have them fetch the old session's output and insert it into the new one's gallery and board+ * caches.+ */+ onInvocationComplete.dispose = () => {+ isDisposed = true;+ for (const timeout of scheduledRetries.values()) {+ clearTimeout(timeout);+ }+ scheduledRetries.clear();};++ return onInvocationComplete;};/**diff --git a/invokeai/frontend/web/src/services/events/setEventListeners.test.ts b/invokeai/frontend/web/src/services/events/setEventListeners.test.tsindex 10f8aa4438..d8a231a7a0 100644--- a/invokeai/frontend/web/src/services/events/setEventListeners.test.ts+++ b/invokeai/frontend/web/src/services/events/setEventListeners.test.ts@@ -23,7 +23,7 @@ vi.mock('features/toast/toast', () => ({// Expose the built handlers and the completed-invocation tracking map that setEventListeners// hands to both the coordinator and the gallery handler, so tests can assert routing: own events// reach the own handler via the coordinator, foreign events reach only the foreign handler.-const mockOnInvocationComplete = vi.fn();+const mockOnInvocationComplete = Object.assign(vi.fn(), { dispose: vi.fn() });const mockOnForeignInvocationComplete = vi.fn();let capturedCompletedInvocationKeys: Map<number, Set<string>> | null = null;vi.mock('./onInvocationComplete', () => ({@@ -588,6 +588,26 @@ describe('setEventListeners cross-user isolation', () => {* queue_item_status_changed, so queue_items_canceled is the only signal that pending items left* the queue. Regression: an admin's cancel-all-except-current left other users' badges stale.*/+describe('setEventListeners teardown', () => {+ it('hands back a disposer that ends the completion handler session', () => {+ // The completion handler can hold refetches for outputs of *this* socket's session, and they+ // dispatch into whatever store is current when they fire — the next user's, after a logout or+ // account switch. Nothing else in this suite exercises the returned value.+ const socket = createMockSocket();+ const store = { dispatch: vi.fn(), getState: vi.fn(() => ({})) };++ const dispose = setEventListeners({+ socket: socket as never,+ store: store as never,+ setIsConnected: vi.fn(),+ });++ expect(mockOnInvocationComplete.dispose).not.toHaveBeenCalled();+ dispose();+ expect(mockOnInvocationComplete.dispose).toHaveBeenCalledTimes(1);+ });+});+describe('setEventListeners queue_items_canceled', () => {const setup = () => {const socket = createMockSocket();diff --git a/invokeai/frontend/web/src/services/events/setEventListeners.tsx b/invokeai/frontend/web/src/services/events/setEventListeners.tsxindex a45c202b24..5c4c8f9932 100644--- a/invokeai/frontend/web/src/services/events/setEventListeners.tsx+++ b/invokeai/frontend/web/src/services/events/setEventListeners.tsx@@ -73,8 +73,12 @@ const selectModelInstalls = modelsApi.endpoints.listModelInstalls.select();/*** Sets up event listeners for the socketio client. Some components will set up their own listeners. These are the ones* that have app-wide implications.+ *+ * Returns a disposer. It must be called when this socket goes away — a reconnect with new auth, a+ * logout, an account switch — because the completion handler can hold pending refetches for outputs+ * of *this* session, and they dispatch into whatever store is current when they fire.*/-export const setEventListeners = ({ socket, store, setIsConnected }: SetEventListenersArg) => {+export const setEventListeners = ({ socket, store, setIsConnected }: SetEventListenersArg): (() => void) => {const { dispatch, getState } = store;const completedInvocationKeysByItemId = new Map<number, Set<string>>();@@ -1041,4 +1045,11 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLislog.warn({ data } as JsonObject, 'LLM task error');clearLLMTaskState(data.task_id);});++ return () => {+ // Ends this socket's session for the completion handler: its queued refetches are dropped, and+ // anything it already has in flight is barred from dispatching into whatever session replaces+ // this one.+ onInvocationComplete.dispose();+ };};diff --git a/invokeai/frontend/web/src/services/events/useSocketIO.ts b/invokeai/frontend/web/src/services/events/useSocketIO.tsindex a6b62297fe..62dc9c1e24 100644--- a/invokeai/frontend/web/src/services/events/useSocketIO.ts+++ b/invokeai/frontend/web/src/services/events/useSocketIO.ts@@ -76,7 +76,7 @@ export const useSocketIO = () => {const socket: AppSocket = io(socketUrl, socketOptions);$socket.set(socket);- setEventListeners({ socket, store, setIsConnected: $isConnected.set });+ const disposeEventListeners = setEventListeners({ socket, store, setIsConnected: $isConnected.set });socket.connect();@@ -101,6 +101,8 @@ export const useSocketIO = () => {console.log('Socket teardown', socket);}unsubscribeQueueStatusListener();+ // Before the socket goes: anything this session scheduled must not land in the next one.+ disposeEventListeners();socket.disconnect();$socket.set(null);};