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
refactor(ui): item-owned reveal state machine with explicit selection identity (#9520)
Lincoln Stein97844ed66a3b
diff --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.tsdeleted file mode 100644index 54c1ff2bde..0000000000--- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.test.ts+++ /dev/null@@ -1,73 +0,0 @@-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.tsdeleted file mode 100644index 0b14616f0b..0000000000--- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/autoSwitchedSelection.ts+++ /dev/null@@ -1,27 +0,0 @@-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.tsindex 32d92de52d..1ffade0f41 100644--- 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.ts@@ -1,28 +1,38 @@import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit';-import type { AppStartListening } from 'app/store/store';+import type { AppStartListening, RootState } from 'app/store/store';+import { $gallerySelection, resetGallerySelectionSource } from 'features/gallery/store/gallerySelectionSource';+import { selectGalleryItemNamesQueryArgs } from 'features/gallery/store/gallerySelectors';import {+ boardIdSelected,gallerySliceConfig,galleryViewChanged,imageSelected,selectionChanged,} from 'features/gallery/store/gallerySlice';import { api } from 'services/api';+import { galleryApi } from 'services/api/endpoints/gallery';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { addBoardIdSelectedListener } from './boardIdSelected';+import { addGallerySelectionSourceListener } from './gallerySelectionSource';// 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 = () => {+// slice present (in most tests here the query is never fulfilled — the point is what happens+// meanwhile). `withSelectionSource` also registers the listener that publishes selections to the+// viewer, for the tests that care whether the probe's own write reads as a user pick.+const buildStore = ({ withSelectionSource = false }: { withSelectionSource?: boolean } = {}) => {const listenerMiddleware = createListenerMiddleware();addBoardIdSelectedListener(listenerMiddleware.startListening as unknown as AppStartListening);+ if (withSelectionSource) {+ addGallerySelectionSourceListener(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),+ getDefaultMiddleware({ serializableCheck: false }).prepend(listenerMiddleware.middleware).concat(api.middleware),});};@@ -64,8 +74,8 @@ describe('addBoardIdSelectedListener', () => {});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.+ // Ctrl/shift-clicks and the delete flow's selection pruning dispatch selectionChanged, not+ // imageSelected, so matching on the action type alone leaves those paths exposed.const store = buildStore();store.dispatch(galleryViewChanged('images'));@@ -114,4 +124,49 @@ describe('addBoardIdSelectedListener', () => {expect(store.getState().gallery.selection).toEqual(['a.png']);});});++ it("auto-selects the board's first item without that reading as a user pick", async () => {+ // The probe picks *for* the user, so its write must not publish as a pick when it lands on the+ // item already displayed: NoBoardBoard re-dispatches boardIdSelected even when its board is+ // already selected, and the viewer answers a pick by lifting a running generation's progress+ // overlay off the item for two seconds — a stale flash for a click on the current board.+ resetGallerySelectionSource();+ const store = buildStore({ withSelectionSource: true });++ store.dispatch(boardIdSelected({ boardId: 'none' }));+ // Fulfil the item-name query the probe is waiting on, under the same cache key it computes.+ // The store here carries only the two slices this listener needs, so the selector — typed+ // against the whole RootState — has to be told that is enough.+ const queryArgs = selectGalleryItemNamesQueryArgs(store.getState() as unknown as RootState);+ // The upsert has to be flushed through the fake timers before it is awaited, or its fulfilled+ // action lands after the probe's 5s give-up.+ const upsert = store.dispatch(+ galleryApi.util.upsertQueryData('listGalleryItemNames', queryArgs, {+ item_names: ['already-showing.png'],+ starred_count: 0,+ total_count: 1,+ })+ );+ await vi.advanceTimersByTimeAsync(0);+ await upsert;+ await vi.advanceTimersByTimeAsync(6000);++ // The probe really does select for the user — this is also the only coverage of that path.+ expect(store.getState().gallery.selection).toEqual(['already-showing.png']);+ const generationAfterFirstProbe = $gallerySelection.get().generation;+ expect(generationAfterFirstProbe, 'moving the viewer to a new item is worth publishing').toBeGreaterThan(0);++ // Re-select the same board. The probe runs again and lands on the item already displayed.+ store.dispatch(boardIdSelected({ boardId: 'none' }));+ // The listener's `condition` only re-evaluates its predicate when an action is dispatched, so a+ // test that merely advances time would watch this second probe time out and clear the selection+ // — the give-up path, not the path under test. Any action wakes it; this one touches nothing.+ store.dispatch({ type: 'test/tick' });+ await vi.advanceTimersByTimeAsync(6000);++ expect(store.getState().gallery.selection).toEqual(['already-showing.png']);+ expect($gallerySelection.get().generation, 'nothing moved, so there is nothing to reveal').toBe(+ generationAfterFirstProbe+ );+ });});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 01072a8116..10a66b1772 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,7 +1,7 @@import { isAnyOf } from '@reduxjs/toolkit';import type { AppStartListening } from 'app/store/store';import { selectGalleryItemNamesQueryArgs, selectSelection } from 'features/gallery/store/gallerySelectors';-import { boardIdSelected, galleryViewChanged, imageSelected } from 'features/gallery/store/gallerySlice';+import { boardIdSelected, galleryViewChanged, selectionChanged } 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. */@@ -11,10 +11,11 @@ export const addBoardIdSelectedListener = (startAppListening: AppStartListening)startAppListening({// 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.+ // and a selection arrives through several actions: imageSelected from the gallery's auto-switch,+ // plain thumbnail clicks and keyboard navigation, selectionChanged from ctrl/shift-clicks, the+ // delete flow's pruning and this listener's own probe, 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@@ -53,15 +54,30 @@ export const addBoardIdSelectedListener = (startAppListening: AppStartListening)// must use getState() to ensure we do not have stale stateconst isSuccess = await condition(() => selectQuery(getState()).isSuccess, 5000);+ // The probe picks an item *for* the user, so it writes the selection with the mutation+ // action rather than `imageSelected`. The state is identical either way, but `imageSelected`+ // means "the user asked to see this", and while a generation is running the viewer answers+ // that by lifting the progress overlay off the item for a couple of seconds — so a write+ // that changes nothing must not announce itself as a pick. NoBoardBoard and the view tabs+ // dispatch even when nothing changed (unlike GalleryBoard and VirtualBoardItem), which+ // re-runs this probe; when it lands back on the item already displayed, the mutation action+ // is what keeps it silent. A write that genuinely moves the displayed item still reveals,+ // through the change-of-active-item clause. See gallerySelectionSource.+ //+ // This does NOT stop that re-run from *replacing* a selection further down the list with+ // `item_names[0]` — a real bug, but an older and wider one than this file, tracked in its own+ // issue along with the give-up branch below clearing a good selection whenever `condition`+ // gets no wake-up within 5s.if (!isSuccess) {- dispatch(imageSelected(null));+ dispatch(selectionChanged([]));return;}// the board was just changed - we can select the first gallery item (image or video)const itemNames = selectQuery(getState()).data?.item_names;+ const firstItemName = itemNames?.[0];- dispatch(imageSelected(itemNames?.[0] ?? null));+ dispatch(selectionChanged(firstItemName ? [firstItemName] : []));},});};diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource.test.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource.test.tsnew file mode 100644index 0000000000..96b57f8a80--- /dev/null+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource.test.ts@@ -0,0 +1,97 @@+import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit';+import type { AppStartListening } from 'app/store/store';+import {+ $gallerySelection,+ markNextSelectionAutoSwitched,+ resetGallerySelectionSource,+} from 'features/gallery/store/gallerySelectionSource';+import {+ boardIdSelected,+ gallerySliceConfig,+ imageSelected,+ selectionChanged,+} from 'features/gallery/store/gallerySlice';+import { beforeEach, describe, expect, it } from 'vitest';++import { addGallerySelectionSourceListener } from './gallerySelectionSource';++const buildStore = () => {+ const listenerMiddleware = createListenerMiddleware();+ addGallerySelectionSourceListener(listenerMiddleware.startListening as unknown as AppStartListening);+ return configureStore({+ reducer: { gallery: gallerySliceConfig.slice.reducer },+ middleware: (getDefaultMiddleware) => getDefaultMiddleware().prepend(listenerMiddleware.middleware),+ });+};++describe('addGallerySelectionSourceListener', () => {+ beforeEach(() => {+ resetGallerySelectionSource();+ });++ it('publishes a click made through the gallery grid', () => {+ const store = buildStore();+ store.dispatch(imageSelected('clicked.png'));+ expect($gallerySelection.get()).toMatchObject({ name: 'clicked.png', isAutoSwitch: false });+ });++ it('does not publish a multi-select mutation that leaves the active item in place', () => {+ // Active item b, selection [a, b]: ctrl-clicking `a` off the selection dispatches+ // selectionChanged([b]). Nothing the viewer shows changes — publishing it would flash the+ // progress overlay off for bookkeeping aimed at a different item.+ const store = buildStore();+ store.dispatch(selectionChanged(['a.png', 'b.png']));+ const beforeDeselect = $gallerySelection.get().generation;++ store.dispatch(selectionChanged(['b.png']));++ expect($gallerySelection.get().generation).toBe(beforeDeselect);+ });++ it('publishes a multi-select mutation that moves the active item', () => {+ // Ctrl-clicking an unselected item appends it and makes it active. selectionChanged is not in+ // the pick list, so this relies on the change-of-active-item clause.+ const store = buildStore();+ store.dispatch(imageSelected('a.png'));+ store.dispatch(selectionChanged(['a.png', 'b.png']));+ expect($gallerySelection.get()).toMatchObject({ name: 'b.png', isAutoSwitch: false });+ });++ it('publishes a re-selection of the item already active as a new selection', () => {+ // Nothing in the state changes, so a state-transition-only predicate would miss it — and the+ // viewer would have no way to make a repeat click on the displayed item visible.+ const store = buildStore();+ store.dispatch(imageSelected('a.png'));+ const first = $gallerySelection.get().generation;+ store.dispatch(imageSelected('a.png'));+ expect($gallerySelection.get().generation).toBeGreaterThan(first);+ });++ it('attributes an auto-switch that carries its own board change', () => {+ const store = buildStore();+ markNextSelectionAutoSwitched();+ store.dispatch(boardIdSelected({ boardId: 'other', select: { selection: ['auto.png'], galleryView: 'images' } }));+ expect($gallerySelection.get()).toMatchObject({ name: 'auto.png', isAutoSwitch: true });+ });++ it('publishes a selection cleared by an action it does not name', () => {+ // logout is not in the action list; the active-item clause is what covers it.+ const store = buildStore();+ store.dispatch(imageSelected('a.png'));+ store.dispatch({ type: 'auth/logout' });+ expect($gallerySelection.get().name).toBeNull();+ });++ it('does not treat a bare board click as the user picking the item that stays selected', () => {+ // Clicking a board in the boards list dispatches boardIdSelected with no selection payload and+ // leaves the selection alone. Counting it would make the viewer reveal an item the user never+ // clicked, over the live progress preview.+ const store = buildStore();+ store.dispatch(imageSelected('a.png'));+ const beforeBoardClick = $gallerySelection.get().generation;++ store.dispatch(boardIdSelected({ boardId: 'some-other-board' }));++ expect($gallerySelection.get().generation).toBe(beforeBoardClick);+ });+});diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource.tsnew file mode 100644index 0000000000..1203181bd6--- /dev/null+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource.ts@@ -0,0 +1,59 @@+import type { UnknownAction } from '@reduxjs/toolkit';+import { isAnyOf } from '@reduxjs/toolkit';+import type { AppStartListening } from 'app/store/store';+import { recordGallerySelection } from 'features/gallery/store/gallerySelectionSource';+import { selectLastSelectedItem } from 'features/gallery/store/gallerySelectors';+import { boardIdSelected, comparedImagesSwapped, imageSelected } from 'features/gallery/store/gallerySlice';++/**+ * The actions through which a user (or the auto-switch) picks something.+ *+ * `boardIdSelected` only counts when it carries a selection: clicking a board in the boards list+ * dispatches it bare, leaves the selection alone, and must not read as the user picking the item+ * that happens to still be selected — the viewer would reveal an item they never clicked.+ *+ * `selectionChanged` is deliberately absent: it is the multi-selection *mutation* action+ * (ctrl/shift-clicks, bulk operations, the delete flow pruning deleted names out of the+ * selection), and a mutation that leaves the active item in place — ctrl-clicking a non-active+ * item off the selection, say — is bookkeeping, not the user asking to see the item that stays+ * active; counting it would flash the progress overlay off for a gesture aimed at a different+ * item. A mutation that *moves* the active item is caught by the change-of-active-item clause+ * below, and a plain click dispatches `imageSelected`, so the deliberate re-pick of the+ * already-active item still lands here.+ *+ * The corollary binds the writers, not just this file: code that rewrites the selection without+ * the user having asked for anything must use `selectionChanged`, even where `imageSelected`+ * would leave identical state — when the write leaves the active item where it is, the action is+ * the only thing left to distinguish "the user picked this" from "this happens to still be+ * selected". Choosing the action is necessary but not sufficient, though: the clause below still+ * publishes if the write *moves* the active item, so such a writer must also leave the active item+ * alone rather than collapsing the selection onto a stale snapshot of it. See the delete modals'+ * survivor branch, which does both, and its fallback, which fires only when everything selected has+ * been deleted and cannot honour the second half — so it does reveal. The board auto-select probe+ * in listeners/boardIdSelected.ts honours the first half only: it is silent when it lands back on+ * the item already displayed, but a re-run for a navigation that changed nothing still replaces a+ * selection further down the list, which is tracked separately.+ */+const isSelectionDispatch = (action: UnknownAction): boolean =>+ isAnyOf(imageSelected, comparedImagesSwapped)(action) ||+ (boardIdSelected.match(action) && action.payload.select !== undefined);++/**+ * Publishes every gallery selection to $gallerySelection, so the viewer can tell a user's click+ * from the gallery auto-switching to a finished item, and one selection from the next.+ *+ * The predicate has two clauses because neither alone is sufficient. Matching the selection+ * *actions* catches re-selecting the item already active — a real event that changes no state, and+ * the one the reveal needs in order to make a repeat click visible. Matching a *change of active+ * item* catches every other writer, including ones added later that an action list would miss+ * (`showVirtualBoardsChanged` and `logout` both clear the selection today).+ */+export const addGallerySelectionSourceListener = (startAppListening: AppStartListening) => {+ startAppListening({+ predicate: (action, currentState, previousState) =>+ isSelectionDispatch(action) || selectLastSelectedItem(currentState) !== selectLastSelectedItem(previousState),+ effect: (_action, { getState }) => {+ recordGallerySelection(selectLastSelectedItem(getState()) ?? null);+ },+ });+};diff --git a/invokeai/frontend/web/src/app/store/store.test.ts b/invokeai/frontend/web/src/app/store/store.test.tsindex 056bc639b4..e98155b8ae 100644--- a/invokeai/frontend/web/src/app/store/store.test.ts+++ b/invokeai/frontend/web/src/app/store/store.test.ts@@ -4,7 +4,11 @@ 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 { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';+import {+ $gallerySelection,+ markNextSelectionAutoSwitched,+ resetGallerySelectionSource,+} from 'features/gallery/store/gallerySelectionSource';import {autoAddBoardIdChanged,boardIdSelected,@@ -124,20 +128,19 @@ describe('auth cache isolation', () => {});describe('gallery listener registration', () => {- it('settles the auto-switch marker through the real store wiring', () => {+ it('publishes selections 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.+ // store.ts is deleted — and without it no selection is ever published: the auto-switch mark is+ // never spent, and the viewer's reveal machine never hears about any selection at all. This is+ // the one test that dispatches through createStore()'s own listeners.const store = createStore();- autoSwitchedImages.settle(null); // module singleton; start from empty+ resetGallerySelectionSource(); // module singleton; start from empty- autoSwitchedImages.record('auto-switched.png');+ markNextSelectionAutoSwitched();store.dispatch(imageSelected('auto-switched.png'));- store.dispatch(imageSelected('user-clicked-elsewhere.png'));+ expect($gallerySelection.get()).toMatchObject({ name: 'auto-switched.png', isAutoSwitch: true });- expect(autoSwitchedImages.consume('auto-switched.png'), 'the marker must not survive the selection moving on').toBe(- false- );+ store.dispatch(imageSelected('user-clicked.png'));+ expect($gallerySelection.get()).toMatchObject({ name: 'user-clicked.png', isAutoSwitch: false });});});diff --git a/invokeai/frontend/web/src/app/store/store.ts b/invokeai/frontend/web/src/app/store/store.tsindex 7ea4ffbf45..ea57993bf4 100644--- a/invokeai/frontend/web/src/app/store/store.ts+++ b/invokeai/frontend/web/src/app/store/store.ts@@ -12,11 +12,11 @@ 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';import { addBulkDownloadListeners } from 'app/store/middleware/listenerMiddleware/listeners/bulkDownload';+import { addGallerySelectionSourceListener } from 'app/store/middleware/listenerMiddleware/listeners/gallerySelectionSource';import { addGetOpenAPISchemaListener } from 'app/store/middleware/listenerMiddleware/listeners/getOpenAPISchema';import { addImageAddedToBoardFulfilledListener } from 'app/store/middleware/listenerMiddleware/listeners/imageAddedToBoard';import { addImageRemovedFromBoardFulfilledListener } from 'app/store/middleware/listenerMiddleware/listeners/imageRemovedFromBoard';@@ -327,7 +327,7 @@ addImageAddedToBoardFulfilledListener(startAppListening);addImageRemovedFromBoardFulfilledListener(startAppListening);addBoardIdSelectedListener(startAppListening);addArchivedOrDeletedBoardListener(startAppListening);-addAutoSwitchedSelectionListener(startAppListening);+addGallerySelectionSourceListener(startAppListening);// Node schemasaddGetOpenAPISchemaListener(startAppListening);diff --git a/invokeai/frontend/web/src/features/deleteImageModal/store/state.test.ts b/invokeai/frontend/web/src/features/deleteImageModal/store/state.test.tsindex 385482447c..298ef013a5 100644--- a/invokeai/frontend/web/src/features/deleteImageModal/store/state.test.ts+++ b/invokeai/frontend/web/src/features/deleteImageModal/store/state.test.ts@@ -32,6 +32,7 @@ vi.mock('features/gallery/store/gallerySelectors', () => ({vi.mock('features/gallery/store/gallerySlice', () => ({imageSelected: vi.fn((payload: string | null) => ({ type: 'gallery/imageSelected', payload })),+ selectionChanged: vi.fn((payload: string[]) => ({ type: 'gallery/selectionChanged', payload })),}));vi.mock('features/system/store/systemSlice', () => ({@@ -58,34 +59,63 @@ vi.mock('features/gallery/store/selectCachedGalleryItemNames', async (importOrigimport type { AppStore } from 'app/store/store';import { selectLastSelectedItem } from 'features/gallery/store/gallerySelectors';+import { imageSelected } from 'features/gallery/store/gallerySlice';import { selectCachedGalleryItemNames } from 'features/gallery/store/selectCachedGalleryItemNames';import { handleDeletions } from './state';-const buildStore = (selection: string[], failingNames: Set<string>) => {+/**+ * `selectionDuringDelete` re-points the store's selection when the delete request is issued,+ * standing in for the user selecting something else while it is in flight. The rest of+ * handleDeletions then runs against that newer selection, as it does in the app.+ *+ * It writes `currentSelection` directly rather than dispatching, so the simulated gesture does not+ * land in `dispatched` and cannot be mistaken for the production write under test. The seam is+ * only equivalent to a real mid-flight click because neither modal reads state between issuing the+ * request and the post-await block; anything added in between would need a real dispatch here.+ */+const buildStore = (selection: string[], failingNames: Set<string>, selectionDuringDelete?: string[]) => {const dispatched: unknown[] = [];+ let currentSelection = selection;const dispatch = vi.fn((action: unknown) => {dispatched.push(action);const typed = action as { type?: string; image_names?: string[] };if (typed?.type === 'imagesApi/deleteImages') {return {- unwrap: () =>- Promise.resolve({+ unwrap: () => {+ if (selectionDuringDelete) {+ currentSelection = selectionDuringDelete;+ }+ return Promise.resolve({deleted_images: (typed.image_names ?? []).filter((name) => !failingNames.has(name)),affected_boards: [],- }),+ });+ },};}return action;});- const getState = vi.fn(() => ({ gallery: { selection }, nodes: { present: { nodes: [] } } }));+ const getState = vi.fn(() => ({ gallery: { selection: currentSelection }, nodes: { present: { nodes: [] } } }));return { store: { dispatch, getState } as unknown as AppStore, dispatched };};-const getSelectionChange = (dispatched: unknown[]) =>- dispatched.find(- (action): action is { type: string; payload: string | null } =>- !!action && typeof action === 'object' && (action as { type?: string }).type === 'gallery/imageSelected'+/**+ * Every write to the selection, in order and raw — so an expectation pins the whole payload *and*+ * that there was exactly one write. Returning just the first match let a stray second dispatch+ * (which is what the user would actually end up looking at) pass unnoticed.+ *+ * The two branches use different actions deliberately: advancing to a neighbour *picks* an item+ * (`imageSelected`), while keeping the displayed item and dropping the deleted ones from the+ * multi-selection is a *mutation* (`selectionChanged`), which the viewer does not treat as the+ * user asking to see anything.+ */+const getSelectionWrites = (dispatched: unknown[]) =>+ dispatched.filter(+ (candidate): candidate is { type: string; payload: string | string[] | null } =>+ !!candidate &&+ typeof candidate === 'object' &&+ ((candidate as { type?: string }).type === 'gallery/imageSelected' ||+ (candidate as { type?: string }).type === 'gallery/selectionChanged'));describe('handleDeletions selection behavior', () => {@@ -103,17 +133,22 @@ describe('handleDeletions selection behavior', () => {// Before the fix this dispatched imageSelected(null) and dropped the viewer to its// empty state even though the displayed video still exists.- expect(getSelectionChange(dispatched)?.payload).toBe('c.mp4');+ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['c.mp4'] }]);});- it('keeps viewing the displayed image on hover-delete of another selected image', async () => {+ it('keeps viewing the displayed image on hover-delete of another selected image, without re-picking it', async () => {// Multi-selection [a, b] with b displayed; the hover delete button deletes only a.vi.mocked(selectLastSelectedItem).mockReturnValue('b.png');const { store, dispatched } = buildStore(['a.png', 'b.png'], new Set());await handleDeletions(['a.png'], store);- expect(getSelectionChange(dispatched)?.payload).toBe('b.png');+ // The action matters, not just the resulting state (PR #9520 review). `imageSelected('b.png')`+ // would leave the very same selection, but it is the action that means "the user picked this",+ // and the viewer answers a pick by lifting an in-progress generation's overlay off the item for+ // two seconds. Deleting `a` must not flash `b` over a running render.+ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['b.png'] }]);+ expect(imageSelected).not.toHaveBeenCalled();});it('does not move the selection when the displayed image fails to delete', async () => {@@ -122,7 +157,7 @@ describe('handleDeletions selection behavior', () => {await handleDeletions(['a.png'], store);- expect(getSelectionChange(dispatched), 'a failed delete must not advance the selection').toBeUndefined();+ expect(getSelectionWrites(dispatched), 'a failed delete must not advance the selection').toEqual([]);});it('keeps a surviving (failed-delete) neighbour as the replacement candidate', async () => {@@ -133,7 +168,7 @@ describe('handleDeletions selection behavior', () => {await handleDeletions(['a.png', 'b.png'], store);// If b.png were treated as deleted, the selection would skip to c.mp4.- expect(getSelectionChange(dispatched)?.payload).toBe('b.png');+ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/imageSelected', payload: 'b.png' }]);});it('advances to the nearest surviving neighbour when everything requested is deleted', async () => {@@ -142,6 +177,44 @@ describe('handleDeletions selection behavior', () => {await handleDeletions(['b.png'], store);- expect(getSelectionChange(dispatched)?.payload).toBe('a.png');+ // The displayed item is gone, so the viewer really does move to a different image: that is a+ // pick, and revealing it over a running generation is the point.+ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/imageSelected', payload: 'a.png' }]);+ });++ it('keeps surviving siblings of a larger multi-selection', async () => {+ // No race here: [a, b, c] with c displayed, delete a. Collapsing onto the displayed item used+ // to deselect b as collateral, which the branch's own comment never claimed to do.+ vi.mocked(selectLastSelectedItem).mockReturnValue('c.mp4');+ const { store, dispatched } = buildStore(['a.png', 'b.png', 'c.mp4'], new Set());++ await handleDeletions(['a.png'], store);++ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['b.png', 'c.mp4'] }]);+ });++ it('leaves a selection made while the delete was in flight alone', async () => {+ // The branch decides on a snapshot taken before the request, so by the time it runs the user+ // may have selected something else. Collapsing onto the snapshot would discard that pick *and*+ // move the active item back — which the viewer publishes as a change of active item and+ // reveals, the very flash the mutation action avoids.+ vi.mocked(selectLastSelectedItem).mockReturnValue('b.png');+ const { store, dispatched } = buildStore(['a.png', 'b.png'], new Set(), ['a.png', 'b.png', 'c.mp4']);++ await handleDeletions(['a.png'], store);++ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['b.png', 'c.mp4'] }]);+ expect(imageSelected).not.toHaveBeenCalled();+ });++ it('falls back to the surviving displayed item when the newer selection is all deleted', async () => {+ // Same race, but everything the user selected meanwhile went away: there is nothing to keep,+ // so the viewer stays on the item that survived rather than emptying out.+ vi.mocked(selectLastSelectedItem).mockReturnValue('b.png');+ const { store, dispatched } = buildStore(['a.png', 'b.png'], new Set(), ['a.png']);++ await handleDeletions(['a.png'], store);++ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['b.png'] }]);});});diff --git a/invokeai/frontend/web/src/features/deleteImageModal/store/state.ts b/invokeai/frontend/web/src/features/deleteImageModal/store/state.tsindex 8169a54baf..fab65eb715 100644--- a/invokeai/frontend/web/src/features/deleteImageModal/store/state.ts+++ b/invokeai/frontend/web/src/features/deleteImageModal/store/state.ts@@ -12,7 +12,7 @@ import { selectCanvasSlice } from 'features/controlLayers/store/selectors';import type { CanvasState, RefImagesState } from 'features/controlLayers/store/types';import type { ImageUsage } from 'features/deleteImageModal/store/types';import { selectLastSelectedItem } from 'features/gallery/store/gallerySelectors';-import { imageSelected } from 'features/gallery/store/gallerySlice';+import { imageSelected, selectionChanged } from 'features/gallery/store/gallerySlice';import {pickSelectionAfterDelete,selectCachedGalleryItemNames,@@ -107,7 +107,26 @@ export const handleDeletions = async (image_names: string[], store: AppStore) =>// video displayed while images were deleted, or a hover-delete of another item)// or its own delete failed. Keep viewing it and just prune the deleted items// from the multi-selection.- dispatch(imageSelected(lastSelected));+ //+ // This is a mutation, not a pick. `imageSelected` would leave the same state in the+ // ordinary case, but it is the action that means "the user asked to see this" — and+ // while a generation is running the viewer answers that by lifting the progress+ // overlay off the item for a couple of seconds. Deleting some *other* item is not a+ // request to look at the one already on screen. See gallerySelectionSource.+ //+ // Filtered from the *live* selection rather than collapsed onto the pre-await+ // snapshot: the user can select something else while the delete is in flight, and+ // collapsing would both discard that and move the active item — which publishes as+ // a change of active item and reveals anyway, the very flash this avoids.+ //+ // The fallback (everything they had selected meanwhile was deleted) does not get+ // that guarantee: `lastSelected` is not in the live selection at all there, so it+ // moves the active item and does reveal — and `deletedNames` only proves it outlived+ // *this* request, so a second delete overlapping this one can leave it pointing at+ // an item that is already gone. Both are pre-existing and want the advance branch's+ // neighbour search, which cannot run off these pre-await snapshots.+ const survivors = getState().gallery.selection.filter((name) => !deletedNames.has(name));+ dispatch(selectionChanged(survivors.length > 0 ? survivors : [lastSelected]));} else {// Advance to a still-living neighbour (prev > next) so the Viewer keeps a real// selection. May pick a video — the polymorphic list intentionally allows that.diff --git a/invokeai/frontend/web/src/features/deleteVideoModal/store/state.test.ts b/invokeai/frontend/web/src/features/deleteVideoModal/store/state.test.tsindex 82fdfeb3ff..f1fb3b4f0e 100644--- a/invokeai/frontend/web/src/features/deleteVideoModal/store/state.test.ts+++ b/invokeai/frontend/web/src/features/deleteVideoModal/store/state.test.ts@@ -36,6 +36,7 @@ vi.mock('features/gallery/store/gallerySelectors', () => ({vi.mock('features/gallery/store/gallerySlice', () => ({imageSelected: vi.fn((payload: string | null) => ({ type: 'gallery/imageSelected', payload })),+ selectionChanged: vi.fn((payload: string[]) => ({ type: 'gallery/selectionChanged', payload })),}));vi.mock('features/nodes/store/nodesSlice', () => ({@@ -75,33 +76,67 @@ const buildVideoFieldNode = (nodeId: string, videoName: string) => ({},});-const buildStore = (selection: string[], failingNames: Set<string>, nodes: unknown[] = [], rejectAll = false) => {+/**+ * `selectionDuringDelete` re-points the store's selection when the delete request is issued,+ * standing in for the user selecting something else while it is in flight. The rest of+ * handleDeletions then runs against that newer selection, as it does in the app.+ *+ * It writes `currentSelection` directly rather than dispatching, so the simulated gesture does not+ * land in `dispatched` and cannot be mistaken for the production write under test. The seam is+ * only equivalent to a real mid-flight click because neither modal reads state between issuing the+ * request and the post-await block; anything added in between would need a real dispatch here.+ */+const buildStore = (+ selection: string[],+ failingNames: Set<string>,+ nodes: unknown[] = [],+ rejectAll = false,+ selectionDuringDelete?: string[]+) => {const dispatched: unknown[] = [];+ let currentSelection = selection;const dispatch = vi.fn((action: unknown) => {dispatched.push(action);const typed = action as { type?: string; video_names?: string[] };if (typed?.type === 'videosApi/deleteVideos') {return {- unwrap: () =>- rejectAll+ unwrap: () => {+ if (selectionDuringDelete) {+ currentSelection = selectionDuringDelete;+ }+ return rejectAll? Promise.reject(new Error('delete failed')): Promise.resolve({deleted_videos: (typed.video_names ?? []).filter((name) => !failingNames.has(name)),failed_videos: (typed.video_names ?? []).filter((name) => failingNames.has(name)),affected_boards: ['none'],- }),+ });+ },};}return action;});- const getState = vi.fn(() => ({ gallery: { selection }, nodes: { present: { nodes } } }));+ const getState = vi.fn(() => ({ gallery: { selection: currentSelection }, nodes: { present: { nodes } } }));return { store: { dispatch, getState } as unknown as AppStore, dispatched };};-const getSelectionChange = (dispatched: unknown[]) =>- dispatched.find(- (action): action is { type: string; payload: string | null } =>- !!action && typeof action === 'object' && (action as { type?: string }).type === 'gallery/imageSelected'+/**+ * Every write to the selection, in order and raw — so an expectation pins the whole payload *and*+ * that there was exactly one write. Returning just the first match let a stray second dispatch+ * (which is what the user would actually end up looking at) pass unnoticed.+ *+ * The two branches use different actions deliberately: advancing to a neighbour *picks* an item+ * (`imageSelected`), while keeping the displayed item and dropping the deleted ones from the+ * multi-selection is a *mutation* (`selectionChanged`), which the viewer does not treat as the+ * user asking to see anything.+ */+const getSelectionWrites = (dispatched: unknown[]) =>+ dispatched.filter(+ (candidate): candidate is { type: string; payload: string | string[] | null } =>+ !!candidate &&+ typeof candidate === 'object' &&+ ((candidate as { type?: string }).type === 'gallery/imageSelected' ||+ (candidate as { type?: string }).type === 'gallery/selectionChanged'));const getVideoFieldChanges = (dispatched: unknown[]) =>@@ -143,7 +178,7 @@ describe('handleDeletions selection behavior on partial failure', () => {await handleDeletions(['a.mp4'], store);- expect(getSelectionChange(dispatched), 'a failed delete must not advance the selection').toBeUndefined();+ expect(getSelectionWrites(dispatched), 'a failed delete must not advance the selection').toEqual([]);});it('does not move the selection when the whole batch request fails', async () => {@@ -152,7 +187,7 @@ describe('handleDeletions selection behavior on partial failure', () => {await handleDeletions(['a.mp4'], store);- expect(getSelectionChange(dispatched)).toBeUndefined();+ expect(getSelectionWrites(dispatched)).toEqual([]);});it('keeps a surviving (failed-delete) neighbour as the replacement candidate', async () => {@@ -163,11 +198,11 @@ describe('handleDeletions selection behavior on partial failure', () => {await handleDeletions(['a.mp4', 'b.mp4'], store);// Before the fix, b.mp4 was excluded as "deleted" and the selection skipped to c.png.- expect(getSelectionChange(dispatched)?.payload).toBe('b.mp4');+ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/imageSelected', payload: 'b.mp4' }]);expect(toast).toHaveBeenCalledWith(expect.objectContaining({ status: 'warning' }));});- it('keeps viewing the displayed video when its delete fails but another selected video was deleted', async () => {+ it('keeps viewing the displayed video when another selected video was deleted, without re-picking it', async () => {vi.mocked(selectLastSelectedItem).mockReturnValue('a.mp4');const { store, dispatched } = buildStore(['a.mp4', 'b.mp4'], new Set(['a.mp4']));@@ -175,7 +210,13 @@ describe('handleDeletions selection behavior on partial failure', () => {// The multi-selection contained a deleted item (b), so the selection is pruned — but it// must land on the still-existing displayed video, not jump to a neighbour.- expect(getSelectionChange(dispatched)?.payload).toBe('a.mp4');+ //+ // And it must prune rather than re-pick (PR #9520 review): `imageSelected('a.mp4')` leaves the+ // very same selection, but it is the action that means "the user picked this", which makes the+ // viewer lift an in-progress generation's overlay off the video for two seconds. Deleting some+ // other video is not a request to look at this one.+ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['a.mp4'] }]);+ expect(imageSelected).not.toHaveBeenCalled();});it('advances to the nearest surviving neighbour when everything requested is deleted', async () => {@@ -184,9 +225,41 @@ describe('handleDeletions selection behavior on partial failure', () => {await handleDeletions(['b.mp4'], store);- expect(getSelectionChange(dispatched)?.payload).toBe('a.mp4');+ // The displayed item is gone, so the viewer really does move to a different video: that is a+ // pick, and revealing it over a running generation is the point.+ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/imageSelected', payload: 'a.mp4' }]);expect(imageSelected).toHaveBeenCalledWith('a.mp4');});++ it('leaves a selection made while the delete was in flight alone', async () => {+ // The branch decides on a snapshot taken before the request, so by the time it runs the user+ // may have selected something else. Collapsing onto the snapshot would discard that pick *and*+ // move the active item back — which the viewer publishes as a change of active item and+ // reveals, the very flash the mutation action avoids.+ vi.mocked(selectLastSelectedItem).mockReturnValue('a.mp4');+ const { store, dispatched } = buildStore(['a.mp4', 'b.mp4'], new Set(['a.mp4']), [], false, [+ 'a.mp4',+ 'b.mp4',+ 'c.png',+ ]);++ await handleDeletions(['a.mp4', 'b.mp4'], store);++ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['a.mp4', 'c.png'] }]);+ expect(imageSelected).not.toHaveBeenCalled();+ });++ it('falls back to the surviving displayed video when the newer selection is all deleted', async () => {+ // Same race, but everything the user selected meanwhile went away. Without the fallback this+ // dispatches selectionChanged([]) and drops the viewer to its empty-state placeholder while a+ // surviving video is still on screen — the original #9163 bug this file exists to guard.+ vi.mocked(selectLastSelectedItem).mockReturnValue('a.mp4');+ const { store, dispatched } = buildStore(['a.mp4'], new Set(['a.mp4']), [], false, ['b.mp4']);++ await handleDeletions(['a.mp4', 'b.mp4'], store);++ expect(getSelectionWrites(dispatched)).toEqual([{ type: 'gallery/selectionChanged', payload: ['a.mp4'] }]);+ });});describe('handleDeletions node VideoField cleanup', () => {diff --git a/invokeai/frontend/web/src/features/deleteVideoModal/store/state.ts b/invokeai/frontend/web/src/features/deleteVideoModal/store/state.tsindex 9821267088..96227b9690 100644--- a/invokeai/frontend/web/src/features/deleteVideoModal/store/state.ts+++ b/invokeai/frontend/web/src/features/deleteVideoModal/store/state.ts@@ -3,7 +3,7 @@ import type { AppDispatch, AppStore, RootState } from 'app/store/store';import { useAppStore } from 'app/store/storeHooks';import { intersection } from 'es-toolkit/compat';import { selectLastSelectedItem } from 'features/gallery/store/gallerySelectors';-import { imageSelected } from 'features/gallery/store/gallerySlice';+import { imageSelected, selectionChanged } from 'features/gallery/store/gallerySlice';import {pickSelectionAfterDelete,selectCachedGalleryItemNames,@@ -127,7 +127,26 @@ export const handleDeletions = async (video_names: string[], store: AppStore) =>if (lastSelected && !deletedNames.has(lastSelected)) {// The displayed item survived (its delete failed) — keep viewing it and just prune// the deleted items from the multi-selection.- dispatch(imageSelected(lastSelected));+ //+ // This is a mutation, not a pick. `imageSelected` would leave the same state in the+ // ordinary case, but it is the action that means "the user asked to see this" — and+ // while a generation is running the viewer answers that by lifting the progress+ // overlay off the item for a couple of seconds. Deleting some *other* item is not a+ // request to look at the one already on screen. See gallerySelectionSource.+ //+ // Filtered from the *live* selection rather than collapsed onto the pre-await+ // snapshot: the user can select something else while the delete is in flight, and+ // collapsing would both discard that and move the active item — which publishes as a+ // change of active item and reveals anyway, the very flash this avoids.+ //+ // The fallback (everything they had selected meanwhile was deleted) does not get that+ // guarantee: `lastSelected` is not in the live selection at all there, so it moves the+ // active item and does reveal — and `deletedNames` only proves it outlived *this*+ // request, so a second delete overlapping this one can leave it pointing at an item+ // that is already gone. Both are pre-existing and want the advance branch's neighbour+ // search, which cannot run off these pre-await snapshots.+ const survivors = stateAfter.gallery.selection.filter((name) => !deletedNames.has(name));+ dispatch(selectionChanged(survivors.length > 0 ? survivors : [lastSelected]));} else {const replacement =lastSelectedIndex >= 0 ? pickSelectionAfterDelete(galleryItemNames, lastSelectedIndex, deletedNames) : null;diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsxindex baf88e1bb2..5ef80e914e 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryImage.tsx@@ -17,7 +17,12 @@ import { dndInputFix } from 'features/dnd/util';import { useImageContextMenu } from 'features/gallery/components/ContextMenu/ImageContextMenu';import { GalleryItemHoverIcons } from 'features/gallery/components/ImageGrid/GalleryItemHoverIcons';import { selectSelectedBoardId, selectSelection } from 'features/gallery/store/gallerySelectors';-import { imageToCompareChanged, selectGallerySlice, selectionChanged } from 'features/gallery/store/gallerySlice';+import {+ imageSelected,+ imageToCompareChanged,+ selectGallerySlice,+ selectionChanged,+} from 'features/gallery/store/gallerySlice';import { selectCachedGalleryItemNames } from 'features/gallery/store/selectCachedGalleryItemNames';import { isVideoName } from 'features/gallery/store/types';import { navigationApi } from 'features/ui/layouts/navigation-api';@@ -46,7 +51,7 @@ const buildOnClick =if (itemNames.length === 0) {// Without an ordered list we can still honor a plain single-click.if (!shiftKey && !ctrlKey && !metaKey && !altKey) {- dispatch(selectionChanged([imageName]));+ dispatch(imageSelected(imageName));}return;}@@ -80,7 +85,12 @@ const buildOnClick =dispatch(selectionChanged(uniq(selection.concat(imageName))));}} else {- dispatch(selectionChanged([imageName]));+ // A plain click is the user picking one item, where the modifier branches above mutate the+ // multi-selection. The distinction is load-bearing: the gallery selection source reads+ // `imageSelected` as a pick (so a repeat click on the active item reveals it over the+ // progress overlay) but deliberately does not read `selectionChanged`, whose mutations only+ // count when they move the active item.+ dispatch(imageSelected(imageName));}};diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryVideoItem.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryVideoItem.tsxindex b6af3ff149..3bdf4b2db6 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryVideoItem.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageGrid/GalleryVideoItem.tsx@@ -14,7 +14,7 @@ import {selectSelectedBoardId,selectSelection,} from 'features/gallery/store/gallerySelectors';-import { selectGallerySlice, selectionChanged } from 'features/gallery/store/gallerySlice';+import { imageSelected, selectGallerySlice, selectionChanged } from 'features/gallery/store/gallerySlice';import { selectCachedGalleryItemNames } from 'features/gallery/store/selectCachedGalleryItemNames';import { isVideoName } from 'features/gallery/store/types';import { navigationApi } from 'features/ui/layouts/navigation-api';@@ -52,7 +52,7 @@ const buildOnClick =if (itemNames.length === 0) {// Without an ordered list, only basic single-click selection is possible.if (!shiftKey && !ctrlKey && !metaKey && !altKey) {- dispatch(selectionChanged([videoName]));+ dispatch(imageSelected(videoName));}return;}@@ -61,7 +61,7 @@ const buildOnClick =if (altKey) {// Alt-click is image-only (comparison view). Quietly treat as a normal click for videos.- dispatch(selectionChanged([videoName]));+ dispatch(imageSelected(videoName));} else if (shiftKey) {const lastSelectedItem = selection.at(-1);const lastClickedIndex = itemNames.findIndex((name) => name === lastSelectedItem);@@ -82,7 +82,9 @@ const buildOnClick =dispatch(selectionChanged(uniq(selection.concat(videoName))));}} else {- dispatch(selectionChanged([videoName]));+ // A plain click is a pick of one item, not a mutation of the multi-selection — see the same+ // branch in GalleryImage for why the gallery selection source depends on the distinction.+ dispatch(imageSelected(videoName));}};diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsxindex ca0271d6f7..c37831be93 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentImagePreview.tsx@@ -7,7 +7,6 @@ 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';@@ -21,7 +20,7 @@ import { AnimatePresence, motion } from 'framer-motion';import { memo, useCallback, useEffect, useRef, useState } from 'react';import type { ImageDTO } from 'services/api/types';-import { SELECTED_ITEM_MEDIA_GRACE_MS, SELECTED_ITEM_REVEAL_DURATION_MS, useImageViewerContext } from './context';+import { useImageViewerContext } from './context';import { NoContentForViewer } from './NoContentForViewer';import { ProgressImage } from './ProgressImage2';import { ProgressImageTiles } from './ProgressImageTiles';@@ -41,7 +40,7 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nu$activeProgressData,$isProgressImageResolving,$isTemporarilyShowingSelectedImage,- lastRenderedItemNameRef,+ revealMachine,} = useImageViewerContext();const progressEvent = useStore($progressEvent);const progressImage = useStore($progressImage);@@ -119,14 +118,9 @@ export const CurrentImagePreview = memo(({ imageDTO }: { imageDTO: ImageDTO | nu// 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,+ revealMachine,renderedItemName: imageToRender?.image_name ?? null,isMediaReady: imageToRender !== null,- selectedItemName: selectedImageName ?? null,shouldShowProgressInViewer,hasProgressImage,isProgressImageResolving,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 1a79715f61..d48e950ee9 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@@ -21,7 +21,9 @@ describe('CurrentVideoPreview progress overlay', () => {expect(source).toMatch(/withProgress =\s+shouldShowProgressInViewer && hasProgressImage && !isTemporarilyShowingSelectedImage && !isPlaying/);- expect(source).toContain('SELECTED_ITEM_REVEAL_DURATION_MS');+ // The reveal's timing constants live with the machine in the viewer context now; what this+ // component owns is consulting the shared atom in its overlay gate, asserted above.+ expect(source).toContain('revealMachine,');});it('tiles concurrent sessions instead of letting them overwrite each other (multi-GPU)', () => {diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsxindex 87c991083e..92dc9c897d 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/CurrentVideoPreview.tsx@@ -13,12 +13,7 @@ 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 { autoSwitchedImages } from 'features/gallery/store/autoSwitchedImages';-import {- selectLastSelectedItem,- selectSelectedBoardId,- selectSelection,-} from 'features/gallery/store/gallerySelectors';+import { 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';@@ -35,7 +30,7 @@ import { useTranslation } from 'react-i18next';import { PiArrowSquareOutBold, PiCopyBold, PiDownloadSimpleBold, PiTrashSimpleBold, PiXBold } from 'react-icons/pi';import type { VideoDTO } from 'services/api/types';-import { SELECTED_ITEM_MEDIA_GRACE_MS, SELECTED_ITEM_REVEAL_DURATION_MS, useImageViewerContext } from './context';+import { useImageViewerContext } from './context';import { NoContentForViewer } from './NoContentForViewer';import { ProgressImage } from './ProgressImage2';import { ProgressImageTiles } from './ProgressImageTiles';@@ -87,7 +82,7 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {$activeProgressData,$isProgressImageResolving,$isTemporarilyShowingSelectedImage,- lastRenderedItemNameRef,+ revealMachine,onLoadImage,} = useImageViewerContext();const progressEvent = useStore($progressEvent);@@ -106,7 +101,6 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {// 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.@@ -122,14 +116,9 @@ export const CurrentVideoPreview = memo(({ videoDTO }: Props) => {// 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,+ revealMachine,renderedItemName: videoName,- isMediaReady,- selectedItemName: selectedItemName ?? null,+ isMediaReady: isMediaReady,shouldShowProgressInViewer,hasProgressImage,isProgressImageResolving,diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsxindex a92558b445..f7fc8ca625 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/context.tsx@@ -7,18 +7,22 @@ import type {ViewerProgressDatum,} from 'features/gallery/components/ImageViewer/viewerProgressLifecycle';import { createViewerProgressLifecycle } from 'features/gallery/components/ImageViewer/viewerProgressLifecycle';+import { $gallerySelection } from 'features/gallery/store/gallerySelectionSource';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 { MutableRefObject, PropsWithChildren } from 'react';-import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';+import type { PropsWithChildren } from 'react';+import { createContext, memo, useCallback, useContext, useEffect, useMemo, useState } from 'react';import type { S } from 'services/api/types';import { getEventScope } from 'services/events/eventScope';import { $socket } from 'services/events/stores';import { assert } from 'tsafe';import type { JsonObject } from 'type-fest';+import type { SelectedItemRevealMachine } from './selectedItemReveal';+import { createSelectedItemRevealMachine } from './selectedItemReveal';+export type { ViewerProgressDatum } from 'features/gallery/components/ImageViewer/viewerProgressLifecycle';type ImageViewerContextValue = {@@ -31,11 +35,9 @@ 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's reveal state machine. Both preview components drive this one instance, so a+ * click that switches media type is just another selection. */+ revealMachine: SelectedItemRevealMachine;/*** 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.@@ -44,12 +46,12 @@ type ImageViewerContextValue = {};/** How long a mid-generation gallery click shows the clicked item before the live preview returns. */-export const SELECTED_ITEM_REVEAL_DURATION_MS = 2000;+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;+/** How long a reveal waits for the selected item's media to paint before showing it anyway. Long+ * enough for a decode or a first video frame on a slow connection, short enough that a click on+ * media that will never load still lands well inside the reveal it was promised. */+const SELECTED_ITEM_MEDIA_GRACE_MS = 1000;const ImageViewerContext = createContext<ImageViewerContextValue | null>(null);@@ -73,7 +75,13 @@ 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);+ const [revealMachine] = useState(() =>+ createSelectedItemRevealMachine({+ setRevealed: (revealed) => $isTemporarilyShowingSelectedImage.set(revealed),+ durationMs: SELECTED_ITEM_REVEAL_DURATION_MS,+ mediaGraceMs: SELECTED_ITEM_MEDIA_GRACE_MS,+ })+ );// 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 }));@@ -93,6 +101,14 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {}))[0];+ // Selections that land while no preview component is mounted (comparison mode) have to be+ // settled somewhere, or returning to the viewer replays them as a reveal nobody asked for.+ useEffect(() => $gallerySelection.listen((selection) => revealMachine.noteSelection(selection)), [revealMachine]);++ // The machine outlives the components that drive it, so its timers are this provider's to clean+ // up: without this an armed grace timer fires on a dead machine and raises an orphaned flag.+ useEffect(() => () => revealMachine.reset(), [revealMachine]);+useEffect(() => {if (!socket) {return;@@ -216,7 +232,7 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {$activeProgressData,$isProgressImageResolving,$isTemporarilyShowingSelectedImage,- lastRenderedItemNameRef,+ revealMachine,onLoadImage,}),[@@ -228,6 +244,7 @@ export const ImageViewerContextProvider = memo((props: PropsWithChildren) => {$progressEvent,$progressImage,onLoadImage,+ revealMachine,]);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.tsindex 1216869a7e..8642fa127a 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.test.ts+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.test.ts@@ -1,31 +1,28 @@-import { createAutoSwitchedSelectionMarker } from 'features/gallery/store/autoSwitchedImages';+import type { GallerySelectionDescriptor } from 'features/gallery/store/gallerySelectionSource';import { describe, expect, it } from 'vitest';-import { createSelectedItemRevealController } from './selectedItemReveal';+import { createSelectedItemRevealMachine } 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 DURATION_MS = 2000;+const MEDIA_GRACE_MS = 1000;++/** Drives the machine the way the preview components' effects do, with hand-cranked timers. */const createHarness = () => {let revealed = false;- const lastRenderedItemNameRef = { current: null as string | null };- const marker = createAutoSwitchedSelectionMarker();- const timers = new Map<number, () => void>();+ let generation = 0;+ let selection: GallerySelectionDescriptor = { name: null, generation: 0, isAutoSwitch: false };+ const timers = new Map<number, { fn: () => void; ms: number }>();let nextTimerId = 1;- const controller = createSelectedItemRevealController({- lastRenderedItemNameRef,- marker,+ const machine = createSelectedItemRevealMachine({setRevealed: (value) => {revealed = value;},- durationMs: 2000,- mediaGraceMs: 1000,- schedule: (fn) => {+ durationMs: DURATION_MS,+ mediaGraceMs: MEDIA_GRACE_MS,+ schedule: (fn, ms) => {const id = nextTimerId++;- timers.set(id, fn);+ timers.set(id, { fn, ms });return id;},cancel: (id) => {@@ -33,305 +30,273 @@ const createHarness = () => {},});+ const base = {+ renderedItemName: null as string | null,+ isMediaReady: false,+ shouldShowProgressInViewer: true,+ hasProgressImage: true,+ isProgressImageResolving: false,+ };+return {- controller,- marker,- lastRenderedItemNameRef,+ machine,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;+ /** The provider's $gallerySelection subscription. */+ noteSelection: () => machine.noteSelection(selection),+ pendingTimerCount: () => timers.size,+ /** A selection dispatch, as the gallery source listener would publish it. */+ select: (name: string | null, options: { isAutoSwitch?: boolean } = {}) => {+ generation += 1;+ selection = { name, generation, isAutoSwitch: options.isAutoSwitch ?? false };+ },+ /** One effect run. */+ sync: (overrides: Partial<typeof base> = {}) => {+ machine.sync({ selection, ...base, ...overrides });+ },+ /** The viewer showing an item whose media has painted. */+ syncRendered: (itemName: string, overrides: Partial<typeof base> = {}) => {+ machine.sync({ selection, ...base, renderedItemName: itemName, isMediaReady: true, ...overrides });},fireTimers: () => {- for (const [id, fn] of [...timers]) {+ for (const [id, timer] of [...timers]) {timers.delete(id);- fn();+ timer.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', () => {+describe('createSelectedItemRevealMachine', () => {+ it('reveals a mid-render click once its media has painted, then lowers on the timer', () => {const h = createHarness();- h.controller.run(rendering('a.png'));- h.controller.run(rendering('b.png'));+ h.select('b.png');+ h.sync();+ expect(h.isRevealed(), 'not before the media is ready').toBe(false);++ h.syncRendered('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', () => {+ it('does not lift the overlay onto an element that has not painted yet', () => {+ // The video element mounts immediately but shows black until it decodes a frame; revealing+ // then would replace the live preview with a black rectangle.const h = createHarness();- h.controller.run(rendering('a.png'));+ h.select('b.mp4');+ h.sync({ renderedItemName: 'b.mp4', isMediaReady: false });expect(h.isRevealed()).toBe(false);});- it('does not re-reveal when a later run finds the same item and no reveal in flight', () => {+ it('reveals anyway when the media never becomes ready', () => {+ // A failed load or an undecodable codec must not swallow the click for the whole render.const h = createHarness();- h.controller.run(rendering('a.png'));- h.controller.run(rendering('b.png'));+ h.select('broken.mp4');+ h.sync({ renderedItemName: 'broken.mp4', isMediaReady: false });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);+ expect(h.isRevealed()).toBe(true);});- it('does not reveal an auto-switched item', () => {+ it('does not run the grace against an item that has not rendered yet', () => {+ // A slow DTO fetch leaves the component rendering the previous item. Counting the grace from+ // the click would lift the overlay onto that stale content at the deadline — and then leave+ // the real item covered when it finally arrived, the reveal already spent.const h = createHarness();- h.controller.run(rendering('a.png'));- autoSwitchTo(h.marker, 'b.png');- h.controller.run(rendering('b.png'));+ h.select('slow.png');+ h.sync({ renderedItemName: 'previous.png', isMediaReady: true });+ expect(h.pendingTimerCount(), 'no deadline while the item has nothing to show').toBe(0);+ h.fireTimers();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);+ // The item lands long after any selection-anchored deadline would have expired.+ h.syncRendered('slow.png');+ expect(h.isRevealed(), 'the claim is still owed when the item finally renders').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.+ it('starts the media grace only once the item is rendered, and only once', () => {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);+ h.select('b.mp4');+ h.sync();+ expect(h.pendingTimerCount()).toBe(0);++ h.sync({ renderedItemName: 'b.mp4', isMediaReady: false });+ h.sync({ renderedItemName: 'b.mp4', isMediaReady: false });expect(h.pendingTimerCount()).toBe(1);h.fireTimers();- expect(h.isRevealed()).toBe(false);+ expect(h.isRevealed(), 'a frame that never paints still cannot swallow the click').toBe(true);});- it('reveals a click that landed inside a resolve window once the window ends', () => {+ it('re-arms the grace when a hand-off interrupts the wait for a frame', () => {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'));+ h.select('b.mp4');+ h.sync({ renderedItemName: 'b.mp4', isMediaReady: false });+ expect(h.pendingTimerCount()).toBe(1);++ h.sync({ renderedItemName: 'b.mp4', isMediaReady: false, isProgressImageResolving: true });+ expect(h.pendingTimerCount(), 'the hand-off owns the viewer; the deadline pauses with it').toBe(0);++ h.sync({ renderedItemName: 'b.mp4', isMediaReady: false });+ h.fireTimers();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.+ it('never reveals an auto-switch', () => {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'));+ h.select('finished.png', { isAutoSwitch: true });+ h.syncRendered('finished.png');expect(h.isRevealed()).toBe(false);});- it('reveals the selection made after the selection was cleared — including the same item', () => {+ it('reveals the item already on screen when the user picks it again', () => {+ // Nothing about the rendered item changes, so the previous-name comparison this replaces could+ // not see it — the click was simply dead.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);+ h.select('a.png');+ h.syncRendered('a.png');+ h.fireTimers();+ expect(h.isRevealed()).toBe(false);- 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);+ h.select('a.png');+ h.syncRendered('a.png');+ expect(h.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.+ it('does not reveal when the viewer simply opens on an existing selection', () => {+ // No selection was dispatched, so nothing is owed a reveal.const h = createHarness();- h.controller.run(rendering('a.png'));- h.controller.run(inputs({ renderedItemName: null, selectedItemName: 'b.png' }));+ h.syncRendered('a.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', () => {+ it('does not reveal a selection made while no progress was showing', () => {+ // The click was already visible; a later generation starting must not flash it.const h = createHarness();- h.controller.run(rendering('a.png'));- h.controller.run(inputs({ renderedItemName: 'a.png', selectedItemName: 'b.png' }));+ h.select('b.png');+ h.sync({ hasProgressImage: false });+ h.syncRendered('b.png');expect(h.isRevealed()).toBe(false);});- it('lowers the reveal when the overlay is not showing at all', () => {+ it('holds a reveal owed during a resolve window until the window ends', () => {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);+ h.select('b.png');+ h.sync({ isProgressImageResolving: true });+ h.syncRendered('b.png', { isProgressImageResolving: true });+ expect(h.isRevealed(), 'the hand-off owns the viewer while it runs').toBe(false);++ h.syncRendered('b.png');+ expect(h.isRevealed(), 'and the click is honoured once it ends').toBe(true);});- 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.+ it('keeps a reveal already granted when a resolve window starts under it', () => {const h = createHarness();- h.controller.run(rendering('a.png'));- h.controller.run(rendering('b.png'));+ h.select('b.png');+ h.syncRendered('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);+ h.syncRendered('b.png', { isProgressImageResolving: true });+ expect(h.isRevealed()).toBe(true);+ });- // ...and it still ends on its own rather than sticking there.- h.fireTimers();+ it('drops the reveal when the progress overlay goes away', () => {+ const h = createHarness();+ h.select('b.png');+ h.syncRendered('b.png');+ h.syncRendered('b.png', { hasProgressImage: false });expect(h.isRevealed()).toBe(false);+ expect(h.pendingTimerCount(), 'and takes its timer with it').toBe(0);});- it('lowers during a resolve window when the in-flight reveal is for a different item', () => {+ it('drops the reveal when the selection is cleared', () => {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 });+ h.select('b.png');+ h.syncRendered('b.png');+ h.select(null);+ h.sync();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.+ it('keeps at most one timer alive across a run of selections', () => {+ // Two live timers means the older one lowers the newer reveal early.const h = createHarness();- h.controller.run(rendering('a.png'));- h.controller.run(rendering('b.png'));- h.controller.run(rendering('c.png'));+ h.select('a.png');+ h.syncRendered('a.png');+ h.select('b.png');+ h.syncRendered('b.png');+ h.select('c.png');+ h.syncRendered('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.+ it('is idempotent across repeated syncs of the same inputs (StrictMode double-invoke)', () => {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);+ h.select('b.png');+ h.syncRendered('b.png');+ const revealedAfterFirst = h.isRevealed();+ h.syncRendered('b.png');+ h.syncRendered('b.png');+ expect(h.isRevealed()).toBe(revealedAfterFirst);+ expect(h.pendingTimerCount()).toBe(1);});- 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.+ it('holds a claim that has not been shown when a hand-off begins', () => {+ // The reveal is owed but not yet visible: dropping it here would lose the click entirely,+ // since nothing else remembers it.const h = createHarness();- h.controller.run(inputs({ renderedItemName: null, selectedItemName: null }));+ h.select('b.png');+ h.sync({ renderedItemName: 'b.png', isMediaReady: false });+ h.sync({ renderedItemName: 'b.png', isMediaReady: false, isProgressImageResolving: true });+ expect(h.isRevealed()).toBe(false);++ // The media arrives during the window — still not shown, the hand-off owns the viewer.+ h.syncRendered('b.png', { isProgressImageResolving: true });+ expect(h.isRevealed()).toBe(false);- h.controller.run(rendering('first-pick.mp4'));+ // ...and it is honoured once the window ends.+ h.syncRendered('b.png');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.+ it('does not reveal a superseded item when its media finally arrives', () => {+ // The slow video's frame lands after the user has moved on. Revealing it then would show them+ // an item they are no longer looking at, over a live preview.const h = createHarness();- h.controller.run(inputs({ renderedItemName: null, selectedItemName: 'already.png' }));- h.controller.run(rendering('already.png'));- expect(h.isRevealed()).toBe(false);- });+ h.select('slow.mp4');+ h.sync({ renderedItemName: 'slow.mp4', isMediaReady: 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.select('next.png');+ h.sync({ renderedItemName: 'slow.mp4', isMediaReady: false });- h.controller.run(rendering('slow.mp4'));- expect(h.isRevealed(), 'the reveal starts when the frame is there').toBe(true);+ h.syncRendered('slow.mp4');+ expect(h.isRevealed()).toBe(false);});- it('reveals media that never becomes ready rather than swallowing the click', () => {+ it('settles a selection that lands while no preview is mounted, rather than replaying it', () => {+ // Comparison mode keeps the provider (and the progress preview) alive while unmounting both+ // preview components, so nothing syncs. Returning must not fire a reveal for a click made+ // while no overlay was covering anything.const h = createHarness();- h.controller.run(rendering('a.png'));- h.controller.run({ ...rendering('broken.mp4'), isMediaReady: false });+ h.select('a.png');+ h.syncRendered('a.png');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);+ const detach = h.machine.attach();+ detach();+ h.select('picked-while-comparing.png');+ h.noteSelection();- h.controller.run(rendering('slow.mp4'));- expect(h.isRevealed()).toBe(true);+ h.syncRendered('picked-while-comparing.png');+ expect(h.isRevealed()).toBe(false);});- 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.+ it('ignores noteSelection while a preview is mounted, leaving the decision to sync', () => {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);+ const detach = h.machine.attach();+ h.select('b.png');+ h.noteSelection();+ h.syncRendered('b.png');+ expect(h.isRevealed()).toBe(true);+ detach();});});diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.tsindex d385863de2..22b24eae58 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.ts+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/selectedItemReveal.ts@@ -1,85 +1,88 @@+import type { GallerySelectionDescriptor } from 'features/gallery/store/gallerySelectionSource';+/**- * The viewer's "reveal selected item" mechanism, extracted from the preview components so its- * sequencing is testable without rendering.+ * The viewer's "reveal the selected item" mechanism, as one item-owned state machine.** 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.+ * happens. The reveal lifts the overlay for `durationMs` when the *user* picks something, then+ * drops back to the live preview.*- * Sequencing rules the controller encodes (each one has a failure mode without it):+ * The machine is owned by the viewer context, so both preview components drive one instance and a+ * click that switches media type is just another selection. What used to carry that across the+ * component swap — a shared mutable ref holding the previously rendered name, a sentinel value for+ * "the selection was cleared", and one controller per component — is gone: a selection is identified+ * by `generation`, so "the user picked X", "X has been on screen for a while" and "the user picked X+ * again" are three distinguishable events rather than three readings of one string comparison.*- * - 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.+ * A reveal is owed from the moment the selection lands, but it is only *shown* once that item's+ * media can actually be seen. Lifting the overlay onto an element that has not decoded a frame yet+ * shows the user a black rectangle where their click should be — so the machine waits for the item+ * to be rendered and for `isMediaReady`. Once the item is rendered, the wait for its media is+ * bounded by `mediaGraceMs`, so that media which never becomes ready (a failed load, a codec the+ * browser will not decode) still makes the click land rather than swallowing it. Until the item+ * renders there is nothing sensible to lift the overlay onto — only the previous item or a blank+ * element — so the claim stays outstanding instead of running against a deadline.*/-type SelectedItemRevealInputs = {+ /** Who selected what, and which selection it is (see gallerySelectionSource). */+ selection: GallerySelectionDescriptor;+ /** The item the component is rendering right now, or null when it has nothing to show. */+ renderedItemName: string | null;/** 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. */+ * painted. False while the element is still black. */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. */+ /** Whether a live progress preview is 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;+type MachineState =+ /** Nothing revealed, and nothing owed: this selection has had its turn, or never earned one. */+ | { kind: 'idle'; generation: number }+ /** Owed a reveal, but a finished generation is resolving into its final frame and owns the+ * viewer for the moment. Resumes when that window ends. */+ | { kind: 'deferred'; generation: number; itemName: string }+ /** Owed a reveal, waiting for the item to render and its media to paint. The grace deadline+ * runs only while the item is rendered. */+ | { kind: 'awaiting-media'; generation: number; itemName: string }+ /** Showing the selected item; the duration timer is running. */+ | { kind: 'revealing'; generation: number; itemName: string };++export type SelectedItemRevealMachine = {+ /** Fold the current inputs in. Called from the preview components' effects. */+ sync: (inputs: SelectedItemRevealInputs) => void;+ /**+ * Registers a mounted preview component; the returned function unregisters it. While none is+ * registered nothing calls `sync`, so selections have to be settled through `noteSelection`+ * instead.+ */+ attach: () => () => void;+ /**+ * A selection landed. Ignored while a preview is attached — its next `sync` carries the same+ * descriptor and decides properly, with the progress state this cannot see. While none is+ * attached (the viewer is in comparison mode, say) this settles the generation, so returning to+ * the viewer does not fire a reveal for a click made when no overlay was covering anything.+ */+ noteSelection: (selection: GallerySelectionDescriptor) => void;+ /** Drop any reveal and cancel timers. For provider teardown. */+ reset: () => void;+ /** The current state's kind, for tests and debugging. */+ peek: () => MachineState['kind'];};-// 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. */+export const createSelectedItemRevealMachine = (deps: {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. */+ /** How long a reveal waits for its rendered item's media before showing anyway. */mediaGraceMs: number;schedule?: (fn: () => void, ms: number) => number;cancel?: (id: number) => void;-}): SelectedItemRevealController => {+}): SelectedItemRevealMachine => {const {- lastRenderedItemNameRef,- marker,setRevealed,durationMs,mediaGraceMs,@@ -87,165 +90,123 @@ export const createSelectedItemRevealController = (deps: {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 state: MachineState = { kind: 'idle', generation: 0 };let timerId = 0;+ let attachedPreviews = 0;- const lower = () => {- activeRevealItemName = null;- awaitingMediaItemName = null;- setRevealed(false);+ const clearTimer = () => {+ cancel(timerId);+ timerId = 0;};- const reveal = (itemName: string) => {- cancel(timerId);- awaitingMediaItemName = null;- activeRevealItemName = itemName;- setRevealed(true);- timerId = schedule(lower, durationMs);+ const enter = (next: MachineState) => {+ state = next;+ setRevealed(next.kind === 'revealing');};- /** 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 goIdle = (generation: number) => {+ clearTimer();+ enter({ kind: 'idle', generation });};- const run: SelectedItemRevealController['run'] = ({- shouldShowProgressInViewer,- hasProgressImage,- isProgressImageResolving,- renderedItemName,- selectedItemName,- isMediaReady,- }) => {- cancel(timerId);+ const goDeferred = (generation: number, itemName: string) => {+ clearTimer();+ enter({ kind: 'deferred', generation, itemName });+ };- 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;- }+ const startRevealing = (generation: number, itemName: string) => {+ clearTimer();+ enter({ kind: 'revealing', generation, itemName });+ timerId = schedule(() => {+ timerId = 0;+ goIdle(generation);+ }, durationMs);+ };- // 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;- }+ const startAwaitingMedia = (generation: number, itemName: string) => {+ clearTimer();+ enter({ kind: 'awaiting-media', generation, itemName });+ };- // 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;- }+ const sync: SelectedItemRevealMachine['sync'] = (inputs) => {+ const { selection, renderedItemName, isMediaReady } = inputs;+ const { shouldShowProgressInViewer, hasProgressImage, isProgressImageResolving } = inputs;- // 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();+ // Nothing is covering the viewer, so there is nothing to reveal from under — and no reveal to+ // keep alive. Settling the generation here is what keeps a selection made while the overlay was+ // down from firing a reveal when the next generation raises it.+ if (!shouldShowProgressInViewer || !hasProgressImage) {+ goIdle(selection.generation);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;+ if (selection.generation !== state.generation) {+ // A selection landed.+ if (selection.name === null || selection.isAutoSwitch) {+ // An auto-switch is the gallery handing over a finished item, not the user asking to see+ // something: revealing it would flash that item over the next render's live preview.+ goIdle(selection.generation);+ } else if (isProgressImageResolving) {+ goDeferred(selection.generation, selection.name);+ } else {+ startAwaitingMedia(selection.generation, selection.name);}- // 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;+ } else if (state.kind === 'deferred' && !isProgressImageResolving) {+ // The hand-off finished; the reveal this selection is owed can start.+ startAwaitingMedia(state.generation, state.itemName);+ } else if (state.kind === 'awaiting-media' && isProgressImageResolving) {+ // A hand-off began while we were waiting for the media. Hold the claim — dropping it would+ // lose a click that has not been shown yet.+ goDeferred(state.generation, state.itemName);}- 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;+ // Show it the moment the owed item's media is actually on screen. Evaluated in the same pass+ // that entered the state, so a click on an item already rendered and decoded reveals at once.+ if (state.kind === 'awaiting-media' && renderedItemName === state.itemName) {+ if (isMediaReady) {+ startRevealing(state.generation, state.itemName);+ } else if (timerId === 0) {+ // The item is rendered but has not painted a frame. Media that never will (a failed load,+ // a codec the browser cannot decode) must not swallow the click, so the wait is bounded —+ // but the deadline starts here, not at the selection: counted from the click, it would+ // lift the overlay onto whatever was still showing while the item itself was slow to+ // arrive, and then leave the real item covered once it landed. No generation check is+ // needed in the callback — every transition clears this timer first, so it can only fire+ // while this exact claim is still the one outstanding. It is deliberately not cancelled+ // if `renderedItemName` later disagrees: with both previews mounted mid-swap, the stale+ // component's sync must not kill the deadline the matching one armed.+ const { generation, itemName } = state;+ timerId = schedule(() => {+ timerId = 0;+ if (state.kind === 'awaiting-media') {+ startRevealing(generation, itemName);+ }+ }, mediaGraceMs);+ }}- reveal(renderedItemName);+ // A reveal already granted runs out its timer even if a hand-off starts under it: that would+ // slam the overlay back over a click the user has already earned.};return {- run,- clearTimer: () => {- cancel(timerId);+ sync,+ attach: () => {+ attachedPreviews += 1;+ return () => {+ attachedPreviews -= 1;+ };+ },+ noteSelection: (selection) => {+ if (attachedPreviews > 0) {+ return;+ }+ goIdle(selection.generation);+ },+ reset: () => {+ clearTimer();+ enter({ kind: 'idle', generation: state.generation });},+ peek: () => state.kind,};};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.tsxindex 952c1b581f..a434bbd7e7 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.test.tsx+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.test.tsx@@ -1,17 +1,24 @@// @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.+ * Mounted-DOM coverage for the preview components' reveal wiring. The machine's sequencing has its+ * own unit tests; what only a real mount can verify is the wiring the components rely on — effect+ * lifecycles, StrictMode double-invocation, the image <-> video component swap over the one shared+ * machine, and media readiness driven by a real <video> element's event.*/-import { createAutoSwitchedSelectionMarker } from 'features/gallery/store/autoSwitchedImages';+import {+ $gallerySelection,+ markNextSelectionAutoSwitched,+ recordGallerySelection,+ resetGallerySelectionSource,+} from 'features/gallery/store/gallerySelectionSource';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 type { SelectedItemRevealMachine } from './selectedItemReveal';+import { createSelectedItemRevealMachine } from './selectedItemReveal';import { usePaintedItemName, useSelectedItemReveal } from './useSelectedItemReveal';declare global {@@ -22,35 +29,34 @@ 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>;+/** What the viewer context provides: one machine writing one shared flag. */+const createHarness = () => {+ const $revealed = atom(false);+ const machine = createSelectedItemRevealMachine({+ setRevealed: (revealed) => $revealed.set(revealed),+ durationMs: DURATION_MS,+ mediaGraceMs: MEDIA_GRACE_MS,+ });+ return { machine, isRevealed: () => $revealed.get() };+};const RevealProbe = ({- shared,+ machine,itemName,isMediaReady = true,hasProgressImage = true,isProgressImageResolving = false,}: {- shared: Shared;+ machine: SelectedItemRevealMachine;itemName: string | null;isMediaReady?: boolean;hasProgressImage?: boolean;isProgressImageResolving?: boolean;}) => {useSelectedItemReveal({- ...shared,- durationMs: DURATION_MS,- mediaGraceMs: MEDIA_GRACE_MS,+ revealMachine: machine,renderedItemName: itemName,isMediaReady,- selectedItemName: itemName,shouldShowProgressInViewer: true,hasProgressImage,isProgressImageResolving,@@ -59,15 +65,12 @@ const RevealProbe = ({};/** CurrentVideoPreview's readiness wiring: a real <video> element feeding usePaintedItemName. */-const VideoProbe = ({ shared, videoName }: { shared: Shared; videoName: string | null }) => {+const VideoProbe = ({ machine, videoName }: { machine: SelectedItemRevealMachine; videoName: string | null }) => {const { isMediaReady, onPainted } = usePaintedItemName(videoName);useSelectedItemReveal({- ...shared,- durationMs: DURATION_MS,- mediaGraceMs: MEDIA_GRACE_MS,+ revealMachine: machine,renderedItemName: videoName,isMediaReady,- selectedItemName: videoName,shouldShowProgressInViewer: true,hasProgressImage: true,isProgressImageResolving: false,@@ -81,6 +84,7 @@ describe('useSelectedItemReveal (mounted)', () => {beforeEach(() => {vi.useFakeTimers();+ resetGallerySelectionSource();container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -94,160 +98,231 @@ describe('useSelectedItemReveal (mounted)', () => {vi.useRealTimers();});- it('reveals a selection change and lowers when the duration elapses', () => {- const shared = createSharedContext();+ /** The user picks an item: publish the selection the way the store listener would. */+ const select = (itemName: string) => {act(() => {- root.render(<RevealProbe shared={shared} itemName="a.png" />);+ recordGallerySelection(itemName);});- 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();+ it('reveals a mid-render click and lowers when the duration elapses', () => {+ const h = createHarness();act(() => {- root.render(<RevealProbe shared={shared} itemName="a.png" />);+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);});+ select('b.png');act(() => {- root.render(<RevealProbe shared={shared} itemName="b.png" />);- });- expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(true);-- act(() => {- root.unmount();+ root.render(<RevealProbe machine={h.machine} itemName="b.png" />);});- expect(shared.$isTemporarilyShowingSelectedImage.get(), 'a reveal must not outlive its component').toBe(false);+ expect(h.isRevealed()).toBe(true);act(() => {- vi.advanceTimersByTime(DURATION_MS * 2);+ vi.advanceTimersByTime(DURATION_MS);});- expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);- root = createRoot(container); // afterEach unmounts a root; give it a live one+ expect(h.isRevealed()).toBe(false);});it('survives StrictMode double-invoked effects', () => {- const shared = createSharedContext();+ const h = createHarness();act(() => {root.render(<StrictMode>- <RevealProbe shared={shared} itemName="a.png" />+ <RevealProbe machine={h.machine} itemName="a.png" /></StrictMode>);});+ select('b.png');act(() => {root.render(<StrictMode>- <RevealProbe shared={shared} itemName="b.png" />+ <RevealProbe machine={h.machine} itemName="b.png" /></StrictMode>);});- expect(shared.$isTemporarilyShowingSelectedImage.get(), 'the reveal survives the doubled effects').toBe(true);+ expect(h.isRevealed(), '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();+ it('keeps one reveal running across an image -> video component swap mid-reveal', () => {+ // One machine serves both components, so the swap must neither kill the running reveal nor+ // restart its clock.+ const h = createHarness();+ act(() => {+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);+ });+ select('b.png');act(() => {- root.render(<RevealProbe shared={shared} itemName="a.png" />);+ root.render(<RevealProbe machine={h.machine} itemName="b.png" />);});+ expect(h.isRevealed()).toBe(true);act(() => {- root.render(<VideoProbe shared={shared} videoName="b.mp4" />);+ vi.advanceTimersByTime(500);});- expect(shared.$isTemporarilyShowingSelectedImage.get(), 'held for the unpainted video').toBe(false);- const video = container.querySelector('video');- expect(video).not.toBeNull();+ // The other preview component takes over rendering the same item.act(() => {- video?.dispatchEvent(new Event('loadeddata'));+ root.render(<RevealProbe key="video-side" machine={h.machine} itemName="b.png" />);+ });+ expect(h.isRevealed(), 'the reveal survives the swap').toBe(true);++ act(() => {+ vi.advanceTimersByTime(DURATION_MS - 500);});- expect(shared.$isTemporarilyShowingSelectedImage.get(), 'revealed once the frame is there').toBe(true);+ expect(h.isRevealed(), 'and still ends on the original clock').toBe(false);});- it('does not reveal an auto-switched selection', () => {- const shared = createSharedContext();+ it('holds a video click until a real loadeddata event, then reveals', () => {+ const h = createHarness();+ act(() => {+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);+ });+ select('b.mp4');act(() => {- root.render(<RevealProbe shared={shared} itemName="a.png" />);+ root.render(<VideoProbe machine={h.machine} videoName="b.mp4" />);});- shared.marker.record('b.png');- shared.marker.settle('b.png');+ expect(h.isRevealed(), 'held for the unpainted video').toBe(false);++ const video = container.querySelector('video');+ expect(video).not.toBeNull();act(() => {- root.render(<RevealProbe shared={shared} itemName="b.png" />);+ video?.dispatchEvent(new Event('loadeddata'));});- expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ expect(h.isRevealed(), 'revealed once the frame is there').toBe(true);});- it('reveals an unpainted video after the media grace even if loadeddata never fires', () => {- const shared = createSharedContext();+ it('reveals after the media grace even if loadeddata never fires', () => {+ const h = createHarness();act(() => {- root.render(<RevealProbe shared={shared} itemName="a.png" />);+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);});+ select('never-loads.mp4');act(() => {- root.render(<VideoProbe shared={shared} videoName="never-loads.mp4" />);+ root.render(<VideoProbe machine={h.machine} videoName="never-loads.mp4" />);});- expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ expect(h.isRevealed()).toBe(false);act(() => {vi.advanceTimersByTime(MEDIA_GRACE_MS);});- expect(shared.$isTemporarilyShowingSelectedImage.get(), 'the click still lands').toBe(true);+ expect(h.isRevealed(), '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();+ // one — readiness is compared by name, so the swap cannot inherit it.+ const h = createHarness();+ select('a.mp4');act(() => {- root.render(<VideoProbe shared={shared} videoName="a.mp4" />);+ root.render(<VideoProbe machine={h.machine} videoName="a.mp4" />);});act(() => {container.querySelector('video')?.dispatchEvent(new Event('loadeddata'));});act(() => {- root.render(<VideoProbe shared={shared} videoName="b.mp4" />);+ vi.advanceTimersByTime(DURATION_MS);});- expect(shared.$isTemporarilyShowingSelectedImage.get(), 'held: the new element has not painted').toBe(false);++ select('b.mp4');+ act(() => {+ root.render(<VideoProbe machine={h.machine} videoName="b.mp4" />);+ });+ expect(h.isRevealed(), 'held: the new element has not painted').toBe(false);act(() => {container.querySelector('video')?.dispatchEvent(new Event('loadeddata'));});- expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(true);+ expect(h.isRevealed()).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();+ it('does not reveal an auto-switched selection', () => {+ const h = createHarness();act(() => {- root.render(<RevealProbe shared={shared} itemName="a.png" />);+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);});act(() => {- root.render(<RevealProbe shared={shared} itemName="b.png" />);+ markNextSelectionAutoSwitched();+ recordGallerySelection('finished.png');});act(() => {- vi.advanceTimersByTime(500);+ root.render(<RevealProbe machine={h.machine} itemName="finished.png" />);+ });+ expect(h.isRevealed()).toBe(false);+ });++ it('settles a selection made while neither preview was mounted, instead of replaying it', () => {+ // Comparison mode unmounts both previews while the provider (and its machine) stays alive; the+ // provider settles selections through noteSelection. Returning must not fire a reveal for a+ // click that was already visible when it happened.+ const h = createHarness();+ act(() => {+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);+ });+ act(() => {+ root.unmount();+ });+ root = createRoot(container);++ act(() => {+ recordGallerySelection('picked-while-comparing.png');+ h.machine.noteSelection($gallerySelection.get());});+act(() => {- root.render(<RevealProbe shared={shared} itemName="c.png" key="other-component" />);+ root.render(<RevealProbe machine={h.machine} itemName="picked-while-comparing.png" />);});- expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(true);+ expect(h.isRevealed()).toBe(false);+ });- // Past where the outgoing component's timer would have fired, short of the new reveal's end.+ it('lowers everything on provider teardown, with no timer left behind', () => {+ const h = createHarness();+ act(() => {+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);+ });+ select('b.png');act(() => {- vi.advanceTimersByTime(DURATION_MS - 400);+ root.render(<RevealProbe machine={h.machine} itemName="b.png" />);});- expect(shared.$isTemporarilyShowingSelectedImage.get(), 'the new reveal runs its full duration').toBe(true);+ expect(h.isRevealed()).toBe(true);act(() => {- vi.advanceTimersByTime(400);+ h.machine.reset();+ });+ expect(h.isRevealed()).toBe(false);+ act(() => {+ vi.advanceTimersByTime(DURATION_MS * 2);+ });+ expect(h.isRevealed()).toBe(false);+ });++ it('reveals a repeat click on the item already on screen', () => {+ // Re-picking the displayed item changes no state and no rendered name — only the selection+ // generation moves. This is the click the previous name-comparison design could never see.+ const h = createHarness();+ select('a.png');+ act(() => {+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);+ });+ act(() => {+ vi.advanceTimersByTime(DURATION_MS);+ });+ expect(h.isRevealed()).toBe(false);++ select('a.png');+ expect(h.isRevealed(), 'the repeat click is a new selection and reveals').toBe(true);+ });++ it('keeps the reveal when the provider settles selections while a preview is mounted', () => {+ // The provider's subscription calls noteSelection on every selection; while a preview is+ // attached that must be a no-op, or every selection would be settled before the component's+ // own sync can classify it — and no click would ever reveal.+ const h = createHarness();+ act(() => {+ root.render(<RevealProbe machine={h.machine} itemName="a.png" />);+ });+ act(() => {+ recordGallerySelection('b.png');+ h.machine.noteSelection($gallerySelection.get());+ });+ act(() => {+ root.render(<RevealProbe machine={h.machine} itemName="b.png" />);});- expect(shared.$isTemporarilyShowingSelectedImage.get()).toBe(false);+ expect(h.isRevealed(), 'attach makes the provider settle a no-op while mounted').toBe(true);});});diff --git a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.ts b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.tsindex 990ad14d46..7e36d617ed 100644--- a/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.ts+++ b/invokeai/frontend/web/src/features/gallery/components/ImageViewer/useSelectedItemReveal.ts@@ -1,24 +1,17 @@-import type { WritableAtom } from 'nanostores';+import { useStore } from '@nanostores/react';+import { $gallerySelection } from 'features/gallery/store/gallerySelectionSource';import { useCallback, useEffect, useState } from 'react';-import { createSelectedItemRevealController } from './selectedItemReveal';+import type { SelectedItemRevealMachine } 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 viewer context's machine. One instance serves both preview components, so a click that+ * switches media type is just another selection rather than a component swap to reason about. */+ revealMachine: SelectedItemRevealMachine;/** 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;@@ -26,64 +19,46 @@ type UseSelectedItemRevealArgs = {/*** 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:+ * effect lifecycles (see useSelectedItemReveal.test.tsx). The sequencing lives in the machine —+ * 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.+ * - registering as a live driver while mounted (attach), so selections that land with neither+ * preview mounted are settled by the provider instead of replaying as a reveal on return;+ * - syncing the machine on every change of the inputs, with the current selection descriptor.+ *+ * Deliberately nothing else: the machine owns the revealed flag and its timers exclusively —+ * components lowering the flag on unmount is how a provider-owned machine gets desynced.*/export const useSelectedItemReveal = ({- lastRenderedItemNameRef,- $isTemporarilyShowingSelectedImage,- marker,- durationMs,- mediaGraceMs,+ revealMachine,renderedItemName,isMediaReady,- selectedItemName,shouldShowProgressInViewer,hasProgressImage,isProgressImageResolving,}: UseSelectedItemRevealArgs): void => {- const [revealController] = useState(() =>- createSelectedItemRevealController({- lastRenderedItemNameRef,- marker,- setRevealed: (revealed) => $isTemporarilyShowingSelectedImage.set(revealed),- durationMs,- mediaGraceMs,- })- );+ const selection = useStore($gallerySelection);++ useEffect(() => revealMachine.attach(), [revealMachine]);useEffect(() => {- revealController.run({+ revealMachine.sync({+ selection,+ renderedItemName,+ isMediaReady,shouldShowProgressInViewer,hasProgressImage,isProgressImageResolving,- renderedItemName,- isMediaReady,- selectedItemName,});- return () => {- revealController.clearTimer();- };}, [hasProgressImage,isMediaReady,isProgressImageResolving,renderedItemName,- revealController,- selectedItemName,+ revealMachine,+ selection,shouldShowProgressInViewer,]);-- useEffect(() => {- return () => {- $isTemporarilyShowingSelectedImage.set(false);- };- }, [$isTemporarilyShowingSelectedImage]);};/**diff --git a/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.test.ts b/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.test.tsdeleted file mode 100644index 899397eeaa..0000000000--- a/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.test.ts+++ /dev/null@@ -1,79 +0,0 @@-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.tsdeleted file mode 100644index d7ab900345..0000000000--- a/invokeai/frontend/web/src/features/gallery/store/autoSwitchedImages.ts+++ /dev/null@@ -1,61 +0,0 @@-/**- * 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/features/gallery/store/gallerySelectionSource.test.ts b/invokeai/frontend/web/src/features/gallery/store/gallerySelectionSource.test.tsnew file mode 100644index 0000000000..b049865448--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/store/gallerySelectionSource.test.ts@@ -0,0 +1,52 @@+import { beforeEach, describe, expect, it } from 'vitest';++import {+ $gallerySelection,+ markNextSelectionAutoSwitched,+ recordGallerySelection,+ resetGallerySelectionSource,+} from './gallerySelectionSource';++describe('gallery selection source', () => {+ beforeEach(() => {+ resetGallerySelectionSource();+ });++ it('advances the generation on every selection, including a re-selection of the same item', () => {+ recordGallerySelection('a.png');+ const first = $gallerySelection.get();+ recordGallerySelection('a.png');+ const second = $gallerySelection.get();++ expect(second.name).toBe('a.png');+ expect(second.generation, 'picking the item already on screen is a new selection').toBeGreaterThan(+ first.generation+ );+ });++ it('attributes only the selection the mark was set for', () => {+ markNextSelectionAutoSwitched();+ recordGallerySelection('auto.png');+ expect($gallerySelection.get().isAutoSwitch).toBe(true);++ recordGallerySelection('clicked.png');+ expect($gallerySelection.get().isAutoSwitch, 'the mark is spent, not sticky').toBe(false);+ });++ it('does not carry an auto-switch mark across an intervening user selection', () => {+ // The auto-switch dispatch follows its mark synchronously, so anything landing in between is+ // the user's — and inheriting the mark would make their click read as a handoff and go+ // unrevealed, the dead click this whole mechanism exists to prevent.+ markNextSelectionAutoSwitched();+ recordGallerySelection('clicked.png');+ recordGallerySelection('auto.png');++ expect($gallerySelection.get().isAutoSwitch).toBe(false);+ });++ it('records an empty selection', () => {+ recordGallerySelection('a.png');+ recordGallerySelection(null);+ expect($gallerySelection.get().name).toBeNull();+ });+});diff --git a/invokeai/frontend/web/src/features/gallery/store/gallerySelectionSource.ts b/invokeai/frontend/web/src/features/gallery/store/gallerySelectionSource.tsnew file mode 100644index 0000000000..52561ffa13--- /dev/null+++ b/invokeai/frontend/web/src/features/gallery/store/gallerySelectionSource.ts@@ -0,0 +1,56 @@+import { atom } from 'nanostores';++/**+ * Who made the gallery's current selection, and which selection it is.+ *+ * The viewer briefly reveals a newly selected item over an in-progress generation's opaque overlay,+ * so that a mid-render gallery click is not invisible. Deciding whether to do that needs two facts+ * the selection itself does not carry:+ *+ * - **Who selected it.** The gallery auto-switches to a finished item, and that dispatch lands+ * after an async DTO fetch — late enough that the next generation's first progress event can slot+ * in ahead of it. Timing therefore cannot tell the handoff from a click; the source has to be+ * recorded at the dispatch that makes it.+ * - **Which selection it is.** "The user picked X" and "X has been the selection for a while" are+ * different events, and re-picking the item already on screen is a third. A monotonic generation+ * distinguishes all three without keeping a previous-item name around to compare against — the+ * arrangement this replaces, which needed a shared mutable ref between the two preview components+ * and a sentinel value to represent "the selection was cleared".+ */+export type GallerySelectionDescriptor = {+ /** The active item (the last of the selection), or null when nothing is selected. */+ name: string | null;+ /** Incremented for every selection dispatch, including re-selecting the item already active. */+ generation: number;+ /** True when the gallery's auto-switch made this selection rather than the user. */+ isAutoSwitch: boolean;+};++export const $gallerySelection = atom<GallerySelectionDescriptor>({+ name: null,+ generation: 0,+ isAutoSwitch: false,+});++// Set immediately before an auto-switch dispatches its selection, consumed by the very next+// recorded selection. The dispatch follows synchronously, so nothing can slip in between.+let nextSelectionIsAutoSwitch = false;++/** Marks the selection an auto-switch is about to dispatch. See onInvocationComplete. */+export const markNextSelectionAutoSwitched = () => {+ nextSelectionIsAutoSwitch = true;+};++/** Records the selection that just landed. Called by addGallerySelectionSourceListener. */+export const recordGallerySelection = (name: string | null) => {+ const isAutoSwitch = nextSelectionIsAutoSwitch;+ nextSelectionIsAutoSwitch = false;+ const previous = $gallerySelection.get();+ $gallerySelection.set({ name, generation: previous.generation + 1, isAutoSwitch });+};++/** Test seam: drops the pending auto-switch mark and resets the descriptor. */+export const resetGallerySelectionSource = () => {+ nextSelectionIsAutoSwitch = false;+ $gallerySelection.set({ name: null, generation: 0, isAutoSwitch: false });+};diff --git a/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts b/invokeai/frontend/web/src/services/events/onInvocationComplete.test.tsindex a0eb18e986..ba5ece5430 100644--- a/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts+++ b/invokeai/frontend/web/src/services/events/onInvocationComplete.test.ts@@ -125,7 +125,11 @@ vi.mock('services/events/stores', () => ({// 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 {+ $gallerySelection,+ recordGallerySelection,+ resetGallerySelectionSource,+} from 'features/gallery/store/gallerySelectionSource';import { selectAutoSwitch } from 'features/gallery/store/gallerySelectors';import { imageSelected } from 'features/gallery/store/gallerySlice';import { getImageDTOSafe } from 'services/api/endpoints/images';@@ -172,7 +176,7 @@ describe('onInvocationComplete polymorphic gallery cache', () => {// 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);+ resetGallerySelectionSource();});it('invalidates GalleryItemNameList + GalleryItemList when an image output completes', async () => {@@ -350,7 +354,7 @@ describe('onInvocationComplete polymorphic gallery cache', () => {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+ resetGallerySelectionSource(); // module singleton; start from emptyvi.mocked(selectAutoSwitch).mockReturnValueOnce(true);vi.mocked(getVideoDTOSafe).mockResolvedValueOnce({video_name: 'fresh-video.mp4',@@ -392,14 +396,14 @@ describe('onInvocationComplete polymorphic gallery cache', () => {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);+ // The rest of JPPhoto's sequence, against the real selection source: the auto-switched video's+ // selection carries the mark, and a later re-selection of it does not — so the re-click is a+ // click, and the viewer reveals it.+ recordGallerySelection('fresh-video.mp4');+ expect($gallerySelection.get().isAutoSwitch).toBe(true);+ recordGallerySelection('some-other-item.png');+ recordGallerySelection('fresh-video.mp4');+ expect($gallerySelection.get().isAutoSwitch).toBe(false);});it('lets a re-delivery retry when the first attempt lost its DTO to a transient failure', async () => {@@ -551,7 +555,7 @@ describe('onInvocationComplete polymorphic gallery cache', () => {// 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);+ resetGallerySelectionSource();const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));const getState = vi.fn(() => ({}));@@ -566,12 +570,15 @@ describe('onInvocationComplete polymorphic gallery cache', () => {await handler(buildImageCompleteEvent());- expect(autoSwitchedImages.consume('fresh-image.png')).toBe(true);+ // The mark is spent by the selection the auto-switch dispatches; the mocked gallery slice does+ // not run the real reducer, so record it the way the source listener would.+ recordGallerySelection('fresh-image.png');+ expect($gallerySelection.get()).toMatchObject({ name: 'fresh-image.png', isAutoSwitch: 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);+ resetGallerySelectionSource();const dispatch = vi.fn(() => ({ unwrap: () => Promise.resolve(undefined) }));const getState = vi.fn(() => ({}));@@ -586,7 +593,8 @@ describe('onInvocationComplete polymorphic gallery cache', () => {await handler(buildImageCompleteEvent());- expect(autoSwitchedImages.consume('fresh-image.png')).toBe(false);+ recordGallerySelection('fresh-image.png');+ expect($gallerySelection.get().isAutoSwitch).toBe(false);});it('retries only the image half of a mixed result, not the video that landed', async () => {diff --git a/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx b/invokeai/frontend/web/src/services/events/onInvocationComplete.tsxindex f79cea1cf5..ad4f4d1926 100644--- a/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx+++ b/invokeai/frontend/web/src/services/events/onInvocationComplete.tsx@@ -1,7 +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 { markNextSelectionAutoSwitched } from 'features/gallery/store/gallerySelectionSource';import {selectAutoSwitch,selectGalleryView,@@ -283,11 +283,11 @@ 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+ // Both branches below auto-switch the selection to this image. Mark it so the viewer's reveal+ // machine 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);+ markNextSelectionAutoSwitched();// With optimistic updates, we can immediately switch to the new imageconst selectedBoardId = selectSelectedBoardId(getState());@@ -453,12 +453,9 @@ 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);+ // Both branches below auto-switch the selection to this video. Same reasoning as the image+ // path above: the mark is what tells the viewer's reveal machine this is a handoff.+ markNextSelectionAutoSwitched();// Selection is a polymorphic string[]; useGalleryItemDTO discriminates by filename extension.const selectedBoardId = selectSelectedBoardId(getState());