Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): roll back optimistic gallery mutations on total transport failure
joshistoasta454f3967e12
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex c7b846e8b7..ecd8e61b08 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -230,6 +230,44 @@ export const getGalleryItemBoardIdsFromCaches = (return boardIds;};+/**+ * Reads the starred flag each requested item currently has, from whichever+ * list cache holds it. Optimistic star/unstar captures this before patching+ * so a totally-failed batch can restore each item's actual prior flag rather+ * than blanket-inverting the whole request.+ */+export const getGalleryItemStarredFromCaches = (+ client: QueryClient,+ refs: readonly GalleryItemRef[]+): Map<GalleryItemKey, boolean> => {+ const wanted = new Set(refs.map(toGalleryItemKey));+ const starred = new Map<GalleryItemKey, boolean>();++ for (const query of getGalleryItemListQueries(client)) {+ if (starred.size === wanted.size) {+ break;+ }++ const data = query.state.data;++ if (!isGalleryItemsData(data)) {+ continue;+ }++ for (const page of data.pages) {+ for (const item of page.items) {+ const key = toGalleryItemKey(item);++ if (wanted.has(key) && !starred.has(key)) {+ starred.set(key, item.starred);+ }+ }+ }+ }++ return starred;+};+interface BoardCacheRollbackEntry {after: GalleryBoard[];before: GalleryBoard[];diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex e1cdc72fcb..0591f9fb0e 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -18,6 +18,7 @@ export type {} from './data/queries';export {getGalleryItemBoardIdsFromCaches,+ getGalleryItemStarredFromCaches,invalidateGallery,invalidateGalleryItems,patchGalleryItemCaches,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.tsnew file mode 100644index 0000000000..8dfbf0866f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.test.ts@@ -0,0 +1,182 @@+import type { GalleryItem } from '@features/gallery';+import type { Project, WorkbenchState } from '@workbench/projectContracts';++import { getProjectWidgetValues } from '@workbench/widgetState';+import { createInitialWorkbenchState, workbenchReducer, type WorkbenchAction } from '@workbench/workbenchState.testing';+import { describe, expect, it } from 'vitest';++import {+ captureGalleryWidgetKeyValues,+ diffGalleryWidgetKeyValues,+ selectRestorableGalleryWidgetPatches,+ type GalleryWidgetRestorePatch,+} from './galleryOptimisticRollback';++/**+ * Reducer-level coverage for the delete-rollback widget-store restore+ * mechanism (Task 7 review finding #6): exercises the real `workbenchState`+ * reducer end to end, rather than a mocked store, so the capture/diff/select+ * functions are proven against the actual `removeGalleryItems` and+ * `patchWidgetValues` contracts instead of a hand-rolled stand-in that could+ * silently drift from them.+ */++const galleryItem: GalleryItem = {+ boardId: 'none',+ category: 'general',+ createdAt: '2026-07-30T00:00:00.000Z',+ fullUrl: '/api/v1/images/i/a.png/full',+ height: 512,+ isIntermediate: false,+ kind: 'image',+ name: 'a.png',+ starred: false,+ thumbnailUrl: '/api/v1/images/i/a.png/thumbnail',+ width: 512,+};++const recentImage = {+ boardId: 'none',+ height: 512,+ imageName: 'a.png',+ imageUrl: galleryItem.fullUrl,+ queuedAt: galleryItem.createdAt,+ sourceQueueItemId: 'backend-gallery',+ thumbnailUrl: galleryItem.thumbnailUrl,+ width: 512,+};++const upscaleInputImage = { height: 512, image_name: 'a.png', width: 512 };++const getProject = (state: WorkbenchState, projectId: string): Project => {+ const project = state.projects.find((candidate) => candidate.id === projectId);++ expect(project).toBeDefined();++ return project as Project;+};++/** Seeds a fresh project with `a.png` selected, compared, in the recent-image+ * overlay, and locked as the upscale widget's input — everything+ * `removeGalleryItemsFromAllProjects` can touch. */+const seedProjectWithItem = (): { projectId: string; state: WorkbenchState } => {+ let state = createInitialWorkbenchState();+ const projectId = state.activeProjectId;++ state = workbenchReducer(state, {+ projectId,+ type: 'patchWidgetValues',+ values: {+ compareImage: galleryItem,+ recentImages: [recentImage],+ selectedImage: galleryItem,+ selectedImageName: 'image:a.png',+ selectedImageNames: ['image:a.png'],+ },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, {+ projectId,+ type: 'patchWidgetValues',+ values: { inputImage: upscaleInputImage },+ widgetId: 'upscale',+ });++ return { projectId, state };+};++const applyRestorePatches = (state: WorkbenchState, patches: GalleryWidgetRestorePatch[]): WorkbenchState =>+ patches.reduce<WorkbenchState>(+ (nextState, patch) =>+ workbenchReducer(nextState, {+ projectId: patch.projectId,+ type: 'patchWidgetValues',+ values: patch.values,+ widgetId: patch.widgetId,+ } as WorkbenchAction),+ state+ );++describe('gallery optimistic rollback against the real reducer', () => {+ it('restores recentImages, selection, compareImage, and upscale.inputImage after a totally-failed delete', () => {+ const { projectId, state } = seedProjectWithItem();++ const before = captureGalleryWidgetKeyValues(state.projects);+ const afterRemoval = workbenchReducer(state, { itemKeys: ['image:a.png'], type: 'removeGalleryItems' });++ // Sanity: the removal really did clear everything we're about to assert+ // gets restored, otherwise this test would pass trivially.+ const clearedValues = getProjectWidgetValues(getProject(afterRemoval, projectId), 'gallery');++ expect(clearedValues).toMatchObject({+ compareImage: null,+ recentImages: [],+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });+ expect(getProjectWidgetValues(getProject(afterRemoval, projectId), 'upscale').inputImage).toBeNull();++ const entries = diffGalleryWidgetKeyValues(before, afterRemoval.projects);++ expect(entries.length).toBeGreaterThan(0);++ const patches = selectRestorableGalleryWidgetPatches(entries, afterRemoval.projects);+ const restored = applyRestorePatches(afterRemoval, patches);++ const restoredGalleryValues = getProjectWidgetValues(getProject(restored, projectId), 'gallery');++ expect(restoredGalleryValues).toMatchObject({+ compareImage: galleryItem,+ recentImages: [recentImage],+ selectedImage: galleryItem,+ selectedImageName: 'image:a.png',+ selectedImageNames: ['image:a.png'],+ });+ expect(getProjectWidgetValues(getProject(restored, projectId), 'upscale').inputImage).toEqual(upscaleInputImage);+ });++ it('does not clobber a field a concurrent mutation changed after the diff was captured', () => {+ const { projectId, state } = seedProjectWithItem();++ const before = captureGalleryWidgetKeyValues(state.projects);+ const afterRemoval = workbenchReducer(state, { itemKeys: ['image:a.png'], type: 'removeGalleryItems' });+ const entries = diffGalleryWidgetKeyValues(before, afterRemoval.projects);++ // A new generation completes mid-flight and rewrites `recentImages`+ // before the rollback runs. Nothing else changes.+ const concurrentImage = { ...recentImage, imageName: 'new-generation.png' };+ const concurrentlyChanged = workbenchReducer(afterRemoval, {+ projectId,+ type: 'patchWidgetValues',+ values: { recentImages: [concurrentImage] },+ widgetId: 'gallery',+ });++ const patches = selectRestorableGalleryWidgetPatches(entries, concurrentlyChanged.projects);+ const restored = applyRestorePatches(concurrentlyChanged, patches);++ const restoredGalleryValues = getProjectWidgetValues(getProject(restored, projectId), 'gallery');++ // The concurrent write to `recentImages` survives untouched...+ expect(restoredGalleryValues.recentImages).toEqual([concurrentImage]);+ // ...while every field nothing else touched still restores correctly.+ expect(restoredGalleryValues.compareImage).toEqual(galleryItem);+ expect(restoredGalleryValues.selectedImage).toEqual(galleryItem);+ expect(restoredGalleryValues.selectedImageName).toBe('image:a.png');+ expect(restoredGalleryValues.selectedImageNames).toEqual(['image:a.png']);+ expect(getProjectWidgetValues(getProject(restored, projectId), 'upscale').inputImage).toEqual(upscaleInputImage);+ });++ it('restores nothing when the optimistic removal did not actually change anything', () => {+ const { state } = seedProjectWithItem();+ const before = captureGalleryWidgetKeyValues(state.projects);++ // Removing an unrelated key changes nothing in this project.+ const afterRemoval = workbenchReducer(state, { itemKeys: ['image:unrelated.png'], type: 'removeGalleryItems' });+ const entries = diffGalleryWidgetKeyValues(before, afterRemoval.projects);++ expect(entries).toEqual([]);+ expect(selectRestorableGalleryWidgetPatches(entries, afterRemoval.projects)).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.tsnew file mode 100644index 0000000000..d22f16d43b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-actions/galleryOptimisticRollback.ts@@ -0,0 +1,225 @@+import type {+ GalleryImage,+ GalleryItem,+ GalleryItemKey,+ GalleryItemRef,+ GeneratedImageContract,+} from '@features/gallery';+import type { Project } from '@workbench/projectContracts';+import type { WidgetTypeId } from '@workbench/widgetContracts';++import { legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery';+import {+ getBoundedRecentImages,+ getGalleryCompareImage,+ getSelectedGalleryItemFromValues,+} from '@features/gallery/contracts';+import { getProjectWidgetValues } from '@workbench/widgetState';++/**+ * Fields `removeGalleryItemsFromAllProjects` (workbenchState.ts) can mutate,+ * across every project: it strips a removed item from any project's+ * recent-generation overlay and selection, and clears the upscale widget's+ * locked input if it pointed at a removed image. None of that is visible to+ * `patchGalleryItemCaches`, which only ever touches the query cache.+ */+const TRACKED_GALLERY_REMOVAL_FIELDS: ReadonlyArray<{ key: string; widgetId: WidgetTypeId }> = [+ { key: 'compareImage', widgetId: 'gallery' },+ { key: 'recentImages', widgetId: 'gallery' },+ { key: 'selectedImage', widgetId: 'gallery' },+ { key: 'selectedImageName', widgetId: 'gallery' },+ { key: 'selectedImageNames', widgetId: 'gallery' },+ { key: 'inputImage', widgetId: 'upscale' },+];++const trackedFieldKey = (projectId: string, widgetId: WidgetTypeId, key: string): string =>+ `${projectId}:${widgetId}:${key}`;++const widgetGroupKey = (projectId: string, widgetId: WidgetTypeId): string => `${projectId}:${widgetId}`;++export type GalleryWidgetKeyValueMap = Map<string, unknown>;++/** Reads every tracked field's current value, per project. Call before the optimistic mutation. */+export const captureGalleryWidgetKeyValues = (projects: readonly Project[]): GalleryWidgetKeyValueMap => {+ const values: GalleryWidgetKeyValueMap = new Map();++ for (const project of projects) {+ for (const field of TRACKED_GALLERY_REMOVAL_FIELDS) {+ const widgetValues = getProjectWidgetValues(project, field.widgetId);++ values.set(trackedFieldKey(project.id, field.widgetId, field.key), widgetValues[field.key]);+ }+ }++ return values;+};++export interface GalleryWidgetKeySnapshotEntry {+ after: unknown;+ before: unknown;+ key: string;+ projectId: string;+ widgetId: WidgetTypeId;+}++/**+ * Diffs the tracked fields' current value against a `before` snapshot and+ * returns only the entries the optimistic mutation actually changed, each+ * carrying both the pre-mutation and post-mutation ("after") value — the same+ * shape `patchGalleryItemCaches`'s rollback closure captures+ * (`queryCache.ts` `ItemCacheRollbackEntry`), so the restore can apply the+ * same conflict rule: only put a key back if nothing else wrote to it since.+ * Call immediately after the optimistic mutation.+ */+export const diffGalleryWidgetKeyValues = (+ before: GalleryWidgetKeyValueMap,+ projects: readonly Project[]+): GalleryWidgetKeySnapshotEntry[] => {+ const entries: GalleryWidgetKeySnapshotEntry[] = [];++ for (const project of projects) {+ for (const field of TRACKED_GALLERY_REMOVAL_FIELDS) {+ const mapKey = trackedFieldKey(project.id, field.widgetId, field.key);++ if (!before.has(mapKey)) {+ continue;+ }++ const beforeValue = before.get(mapKey);+ const afterValue = getProjectWidgetValues(project, field.widgetId)[field.key];++ if (afterValue === beforeValue) {+ continue;+ }++ entries.push({+ after: afterValue,+ before: beforeValue,+ key: field.key,+ projectId: project.id,+ widgetId: field.widgetId,+ });+ }+ }++ return entries;+};++export interface GalleryWidgetRestorePatch {+ projectId: string;+ values: Record<string, unknown>;+ widgetId: WidgetTypeId;+}++/**+ * Selects which snapshot entries are still safe to restore: a key restores+ * only if its current value is still reference-equal to what our own+ * mutation left it at — mirroring `patchGalleryItemCaches`'s rollback rule+ * (`if (client.getQueryData(queryKey) === after)`). A key something else+ * wrote to since (a generation completing, a user re-selecting) is left+ * alone rather than clobbered. Entries for the same project+widget are+ * merged into a single patch.+ */+export const selectRestorableGalleryWidgetPatches = (+ entries: readonly GalleryWidgetKeySnapshotEntry[],+ projects: readonly Project[]+): GalleryWidgetRestorePatch[] => {+ const projectsById = new Map(projects.map((project) => [project.id, project]));+ const patchesByGroup = new Map<string, GalleryWidgetRestorePatch>();++ for (const entry of entries) {+ const project = projectsById.get(entry.projectId);++ if (!project) {+ continue;+ }++ const currentValue = getProjectWidgetValues(project, entry.widgetId)[entry.key];++ if (currentValue !== entry.after) {+ continue;+ }++ const groupKey = widgetGroupKey(entry.projectId, entry.widgetId);+ const patch = patchesByGroup.get(groupKey) ?? { projectId: entry.projectId, values: {}, widgetId: entry.widgetId };++ patch.values[entry.key] = entry.before;+ patchesByGroup.set(groupKey, patch);+ }++ return [...patchesByGroup.values()];+};++export interface GalleryStoreKnownItemFields {+ boardId: string;+ starred: boolean;+}++/**+ * Reads the board and starred state of each requested item from whichever+ * project widget state holds it locally: the recent-generation overlay, the+ * current selection, or the compare slot. `getGalleryItemBoardIdsFromCaches`+ * /`getGalleryItemStarredFromCaches` only see items a list query has already+ * fetched; a just-generated image can be known *only* here.+ */+export const collectGalleryStoreKnownItemFields = (+ projects: readonly Project[],+ refs: readonly GalleryItemRef[]+): Map<GalleryItemKey, GalleryStoreKnownItemFields> => {+ const wanted = new Set(refs.map(toGalleryItemKey));+ const found = new Map<GalleryItemKey, GalleryStoreKnownItemFields>();+ const record = (item: GalleryItem) => {+ const key = toGalleryItemKey(item);++ if (wanted.has(key) && !found.has(key)) {+ found.set(key, { boardId: item.boardId, starred: item.starred });+ }+ };++ for (const project of projects) {+ if (found.size === wanted.size) {+ break;+ }++ const values = getProjectWidgetValues(project, 'gallery');++ for (const image of getBoundedRecentImages(values.recentImages)) {+ record(legacyGeneratedImageToGalleryItem(image as GeneratedImageContract & Partial<GalleryImage>));+ }++ const selectedItem = getSelectedGalleryItemFromValues(values);++ if (selectedItem) {+ record(selectedItem);+ }++ const compareImage = getGalleryCompareImage(values);++ if (compareImage) {+ record(legacyGeneratedImageToGalleryItem(compareImage));+ }+ }++ return found;+};++/**+ * Filters `keys` down to those still safe to roll back: a key restores only+ * if its current value (as read by `readCurrent`) is either unknown (nothing+ * locally to protect) or still equal to `paintedValue` — the value *this*+ * optimistic mutation painted it to. A key a second, later mutation already+ * moved on from (e.g. a subsequent drag to a different board, or another+ * star toggle) is excluded, the per-item analogue of+ * `selectRestorableGalleryWidgetPatches`'s reference-equality CAS check and+ * `patchGalleryItemCaches`'s own `if (current === after)` rollback rule.+ */+export const selectItemKeysUnchangedSince = <Value>(+ keys: readonly GalleryItemKey[],+ paintedValue: Value,+ readCurrent: (key: GalleryItemKey) => Value | undefined+): GalleryItemKey[] =>+ keys.filter((key) => {+ const current = readCurrent(key);++ return current === undefined || current === paintedValue;+ });diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsxindex 78e79eec6c..246ee12d3c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx@@ -17,7 +17,10 @@ const mocks = vi.hoisted(() => ({downloadBlob: vi.fn(),galleryRemoveItems: vi.fn(),galleryPatchItems: vi.fn(),+ galleryWidgetsPatchValues: vi.fn(),getItemBoardIds: vi.fn((..._args: unknown[]) => new Map<string, string>()),+ getItemStarred: vi.fn((..._args: unknown[]) => new Map<string, boolean>()),+ getSnapshot: vi.fn(),gallerySelectItem: vi.fn(),gallerySetItemMultiSelection: vi.fn(),imageMetadata: vi.fn(),@@ -27,6 +30,7 @@ const mocks = vi.hoisted(() => ({itemMoveToBoard: vi.fn(),itemSetStarred: vi.fn(),notificationsAdd: vi.fn(),+ onImagesDeleted: vi.fn(),openWorkbenchWidget: vi.fn(),patchGalleryItemCaches: vi.fn((..._args: unknown[]) => vi.fn()),removeFromBoard: vi.fn(),@@ -52,12 +56,19 @@ vi.mock('@features/gallery', () => ({setStarred: (...args: unknown[]) => mocks.setStarred(...args),},galleryTransfers: { downloadArchive: (...args: unknown[]) => mocks.downloadArchive(...args) },+ legacyGeneratedImageToGalleryItem: (image: { boardId?: string; imageName: string; starred?: boolean }) => ({+ boardId: image.boardId ?? 'none',+ kind: 'image' as const,+ name: image.imageName,+ starred: image.starred ?? false,+ }),toGalleryItemKey: ({ kind, name }: { kind: string; name: string }) => `${kind}:${name}`,toGalleryItemRef: ({ kind, name }: { kind: 'image' | 'video'; name: string }) => ({ kind, name }),}));vi.mock('@features/gallery/queries', () => ({getGalleryItemBoardIdsFromCaches: (...args: unknown[]) => mocks.getItemBoardIds(...args),+ getGalleryItemStarredFromCaches: (...args: unknown[]) => mocks.getItemStarred(...args),invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),invalidateGalleryItems: (...args: unknown[]) => mocks.invalidateGalleryItems(...args),patchGalleryItemCaches: (...args: unknown[]) => mocks.patchGalleryItemCaches(...args),@@ -118,10 +129,13 @@ vi.mock('@workbench/WorkbenchContext', () => ({add: (...args: unknown[]) => mocks.notificationsAdd(...args),reportError: (...args: unknown[]) => mocks.reportError(...args),},+ widgets: {+ patchValues: (...args: unknown[]) => mocks.galleryWidgetsPatchValues(...args),+ },}),useWorkbenchQueries: () => ({getProject: vi.fn(),- getSnapshot: () => ({ activeProject: { id: 'project-1' }, projects: [] }),+ getSnapshot: (...args: unknown[]) => mocks.getSnapshot(...args),isActiveProject: vi.fn(() => true),}),}));@@ -153,6 +167,30 @@ interface ItemActionContext {let currentItemActionContext: ItemActionContext | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+/** A `Project`-shaped stub with just enough of `widgetInstances` for the real+ * `getProjectWidgetValues` (unmocked) to read `gallery`/`upscale` values. */+const makeMockProject = (+ id: string,+ galleryValues: Record<string, unknown> = {},+ upscaleValues: Record<string, unknown> = {}+) => ({+ id,+ widgetInstances: {+ gallery: {+ createdAt: '2026-01-01T00:00:00.000Z',+ id: 'gallery',+ state: { id: 'gallery' as const, label: 'gallery', values: galleryValues, version: 1 as const },+ typeId: 'gallery' as const,+ },+ upscale: {+ createdAt: '2026-01-01T00:00:00.000Z',+ id: 'upscale',+ state: { id: 'upscale' as const, label: 'upscale', values: upscaleValues, version: 1 as const },+ typeId: 'upscale' as const,+ },+ },+});+const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<ImageActions> }) => {const actions = useImageActions({boards: [@@ -169,6 +207,7 @@ const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<I],generateValues: { modelKey },getItemActionContext: () => currentItemActionContext,+ onImagesDeleted: mocks.onImagesDeleted,projectId: 'project-1',requestDeletionConfirmation: mocks.requestDeletionConfirmation,});@@ -185,6 +224,11 @@ beforeEach(async () => {(_itemRefs: readonly GalleryItemRef[], executeDeletion: () => Promise<void>) => executeDeletion());mocks.invalidateGallery.mockResolvedValue(undefined);+ mocks.getSnapshot.mockImplementation(() => {+ const project = makeMockProject('project-1');++ return { activeProject: project, projects: [project] };+ });accountLifecycle.activate('user-a');currentItemActionContext = null;host = document.createElement('div');@@ -551,6 +595,273 @@ describe('mixed item mutation outcomes', () => {});});+describe('total transport failure rollback', () => {+ const recentImageFixture = {+ height: 512,+ imageName: 'gone.png',+ imageUrl: '/full/gone.png',+ queuedAt: '2026-07-30T00:00:00.000Z',+ sourceQueueItemId: 'queue-gone',+ thumbnailUrl: '/thumb/gone.png',+ width: 512,+ };++ it('restores optimistically removed items when the delete transport fails entirely', async () => {+ const refs = [{ kind: 'image' as const, name: 'gone.png' }];+ mocks.itemDelete.mockRejectedValue(new Error('network down'));+ mocks.invalidateGallery.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await getItemActions().deleteItems(refs);+ });++ // The optimistic removal happened up front, before the transport was asked.+ expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['image:gone.png']);++ // The transport threw outright: the cache rollback captured before the+ // mutate call must run on the throw path rather than waiting on the+ // (also-failing) trailing invalidation.+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();++ // `gallery.removeItems` is a no-op stub here, so the pre/post-removal+ // widget snapshot never actually diverges — nothing to restore, and the+ // CAS-guarded restore correctly does nothing. Real restore correctness+ // (recentImages, selection, upscale.inputImage, and the concurrent-change+ // guard) is covered against the real reducer in galleryOptimisticRollback.test.ts.+ expect(mocks.galleryWidgetsPatchValues).not.toHaveBeenCalled();++ expect(mocks.reportError).toHaveBeenCalledOnce();+ expect(mocks.notificationsAdd).not.toHaveBeenCalled();+ });++ it('restores the gallery widget store when the optimistic removal actually changed it', async () => {+ const refs = [{ kind: 'image' as const, name: 'gone.png' }];+ const before = makeMockProject('project-1', { recentImages: [recentImageFixture] });+ const afterRemoval = makeMockProject('project-1', { recentImages: [] });++ // First call is the pre-removal capture; every call after simulates the+ // store having actually applied the optimistic removal.+ mocks.getSnapshot.mockReturnValueOnce({ activeProject: before, projects: [before] }).mockReturnValue({+ activeProject: afterRemoval,+ projects: [afterRemoval],+ });+ mocks.itemDelete.mockRejectedValue(new Error('network down'));+ mocks.invalidateGallery.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await getItemActions().deleteItems(refs);+ });++ expect(mocks.galleryWidgetsPatchValues).toHaveBeenCalledWith(+ 'gallery',+ { recentImages: [recentImageFixture] },+ 'project-1',+ 'system'+ );+ });++ it('does not clobber a gallery widget field something else changed before the rollback runs', async () => {+ const refs = [{ kind: 'image' as const, name: 'gone.png' }];+ const before = makeMockProject('project-1', { recentImages: [recentImageFixture] });+ const afterRemoval = makeMockProject('project-1', { recentImages: [] });+ const concurrentlyChanged = makeMockProject('project-1', {+ recentImages: [{ ...recentImageFixture, imageName: 'new-generation.png' }],+ });++ mocks.getSnapshot+ .mockReturnValueOnce({ activeProject: before, projects: [before] }) // capture, pre-removal+ .mockReturnValueOnce({ activeProject: afterRemoval, projects: [afterRemoval] }) // diff, post-removal+ .mockReturnValue({ activeProject: concurrentlyChanged, projects: [concurrentlyChanged] }); // restore-time read+ mocks.itemDelete.mockRejectedValue(new Error('network down'));+ mocks.invalidateGallery.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await getItemActions().deleteItems(refs);+ });++ // A generation completed mid-flight and rewrote recentImages: the CAS+ // check must see that and skip the restore rather than clobbering it.+ expect(mocks.galleryWidgetsPatchValues).not.toHaveBeenCalled();+ });++ it('does not roll back caches or the widget store once a partial success has been confirmed', async () => {+ const refs = [{ kind: 'image' as const, name: 'done.png' }];+ const result = { affectedBoardIds: ['none'], failed: [], succeeded: refs };+ mocks.itemDelete.mockResolvedValue(result);+ mocks.onImagesDeleted.mockImplementation(() => {+ throw new Error('caller-supplied callback exploded');+ });++ await act(async () => {+ await getItemActions().deleteItems(refs);+ });++ // The confirmed deletion cache patch applied before the callback threw.+ expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), {+ kind: 'delete',+ result,+ });+ // The `rollbackCaches` closure returned for the *optimistic* patch (call+ // 1) must never fire once confirmation has begun applying.+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).not.toHaveBeenCalled();+ expect(mocks.galleryWidgetsPatchValues).not.toHaveBeenCalled();+ // The callback's own throw is still surfaced as an error.+ expect(mocks.reportError).toHaveBeenCalledOnce();+ });++ it('restores the previous board ids when the move transport fails entirely, including items known only to the store', async () => {+ const refs = [+ { kind: 'image' as const, name: 'moved.png' },+ { kind: 'image' as const, name: 'overlay-only.png' },+ ];+ mocks.getItemBoardIds.mockReturnValue(new Map([['image:moved.png', 'board-0']]));+ const beforePaint = makeMockProject('project-1', {+ recentImages: [{ ...recentImageFixture, boardId: 'board-overlay', imageName: 'overlay-only.png' }],+ });+ // `gallery.patchItems` is a no-op stub here, so simulate its real effect+ // by having the snapshot reflect the optimistic paint from the second+ // call onward (the first call is the pre-paint `previousBoardIds` capture).+ const afterPaint = makeMockProject('project-1', {+ recentImages: [{ ...recentImageFixture, boardId: 'board-1', imageName: 'overlay-only.png' }],+ });+ mocks.getSnapshot+ .mockReturnValueOnce({ activeProject: beforePaint, projects: [beforePaint] })+ .mockReturnValue({ activeProject: afterPaint, projects: [afterPaint] });+ mocks.itemMoveToBoard.mockRejectedValue(new Error('network down'));+ mocks.invalidateGallery.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await getItemActions().moveItemsToBoard(refs, 'board-1');+ });++ // The optimistic move happened up front, before the transport was asked.+ expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(1, ['image:moved.png', 'image:overlay-only.png'], {+ boardId: 'board-1',+ });++ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();++ // The cache-known item and the overlay-only item both return to their+ // captured prior board.+ expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:moved.png'], { boardId: 'board-0' });+ expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:overlay-only.png'], { boardId: 'board-overlay' });++ expect(mocks.reportError).toHaveBeenCalledOnce();+ expect(mocks.notificationsAdd).not.toHaveBeenCalled();+ });++ it('does not clobber a store-known board id a concurrent move already carried onto a different board', async () => {+ const refs = [{ kind: 'image' as const, name: 'overlay-only.png' }];+ mocks.getItemBoardIds.mockReturnValue(new Map());+ const beforeFirstMove = makeMockProject('project-1', {+ recentImages: [{ ...recentImageFixture, boardId: 'board-A', imageName: 'overlay-only.png' }],+ });+ // A second, concurrent `moveItemsToBoard` call already carried the item+ // from this move's target ('board-B') onward to 'board-C' by the time+ // this (first) request's rollback runs.+ const concurrentlyMovedOn = makeMockProject('project-1', {+ recentImages: [{ ...recentImageFixture, boardId: 'board-C', imageName: 'overlay-only.png' }],+ });+ mocks.getSnapshot+ .mockReturnValueOnce({ activeProject: beforeFirstMove, projects: [beforeFirstMove] })+ .mockReturnValue({ activeProject: concurrentlyMovedOn, projects: [concurrentlyMovedOn] });+ mocks.itemMoveToBoard.mockRejectedValue(new Error('network down'));+ mocks.invalidateGallery.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await getItemActions().moveItemsToBoard(refs, 'board-B');+ });++ // The rollback must not force the item back to 'board-A': it's no+ // longer on 'board-B' (this move's target), so something else already+ // moved it on and that later write must win.+ expect(mocks.galleryPatchItems).not.toHaveBeenCalledWith(['image:overlay-only.png'], { boardId: 'board-A' });+ // Only the initial optimistic paint touched the store.+ expect(mocks.galleryPatchItems).toHaveBeenCalledOnce();+ });++ it('reverts the optimistic star paint per item when the transport fails entirely, not by blanket inversion', async () => {+ const refs = [+ { kind: 'image' as const, name: 'was-starred.png' },+ { kind: 'image' as const, name: 'was-unstarred.png' },+ ];+ // One of the two requested items was already starred before this batch;+ // a blanket invert-everything rollback would wrongly unstar it too. The+ // cache reflects each item's real prior flag pre-paint, then (since+ // `patchGalleryItemCaches` is a no-op stub here) the painted flag+ // (`true`, this action's target) from the rollback's read onward,+ // simulating the optimistic paint having actually landed.+ mocks.getItemStarred+ .mockReturnValueOnce(+ new Map([+ ['image:was-starred.png', true],+ ['image:was-unstarred.png', false],+ ])+ )+ .mockReturnValue(+ new Map([+ ['image:was-starred.png', true],+ ['image:was-unstarred.png', true],+ ])+ );+ mocks.itemSetStarred.mockRejectedValue(new Error('network down'));+ mocks.invalidateGallery.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await getItemActions().setItemsStarred(refs, true);+ });++ expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(1, ['image:was-starred.png', 'image:was-unstarred.png'], {+ starred: true,+ });++ // Each item reverts to its own prior flag, not a single blanket value.+ expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:was-starred.png'], { starred: true });+ expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:was-unstarred.png'], { starred: false });+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), {+ kind: 'star',+ result: { failed: [], succeeded: [refs[1]] },+ starred: false,+ });++ expect(mocks.reportError).toHaveBeenCalledOnce();+ expect(mocks.notificationsAdd).not.toHaveBeenCalled();+ });++ it('does not clobber a star toggle a concurrent mutation already applied, in either the cache or the store', async () => {+ const refs = [{ kind: 'image' as const, name: 'shared.png' }];+ // Prior: unstarred. This action stars it (painted = true). By the time+ // the rollback reads current state, a concurrent toggle already left it+ // somewhere other than what this action painted, in both the cache and+ // the store overlay.+ mocks.getItemStarred+ .mockReturnValueOnce(new Map([['image:shared.png', false]]))+ .mockReturnValue(new Map([['image:shared.png', false]]));+ const beforePaint = makeMockProject('project-1', {+ recentImages: [{ ...recentImageFixture, imageName: 'shared.png', starred: false }],+ });+ const concurrentToggle = makeMockProject('project-1', {+ recentImages: [{ ...recentImageFixture, imageName: 'shared.png', starred: false }],+ });+ mocks.getSnapshot+ .mockReturnValueOnce({ activeProject: beforePaint, projects: [beforePaint] })+ .mockReturnValue({ activeProject: concurrentToggle, projects: [concurrentToggle] });+ mocks.itemSetStarred.mockRejectedValue(new Error('network down'));+ mocks.invalidateGallery.mockRejectedValue(new Error('network down'));++ await act(async () => {+ await getItemActions().setItemsStarred(refs, true);+ });++ // Neither the cache nor the store restore ran: the rollback's read of+ // current state never matched what this batch painted (`true`), so it+ // correctly assumed something else had already written a newer value+ // and left it alone instead of forcing it back to the prior flag.+ expect(mocks.galleryPatchItems).toHaveBeenCalledOnce();+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledOnce();+ });+});+const galleryItem = (kind: GalleryItem['kind'], name: string): GalleryItem => {const base = {boardId: 'board-1',diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 5a9176168a..c8d944897c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -12,11 +12,17 @@ import {type GalleryImage,type GalleryImageMetadata,type GalleryItem,+ type GalleryItemKey,type GalleryItemMutationResult,type GalleryItemRef,} from '@features/gallery';import { getGalleryBoardLabel } from '@features/gallery/contracts';-import { getGalleryItemBoardIdsFromCaches, invalidateGallery, patchGalleryItemCaches } from '@features/gallery/queries';+import {+ getGalleryItemBoardIdsFromCaches,+ getGalleryItemStarredFromCaches,+ invalidateGallery,+ patchGalleryItemCaches,+} from '@features/gallery/queries';import { setPendingPromptTemplateDraft } from '@features/generation/react';import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';@@ -46,6 +52,14 @@ import type { RequestDeletionConfirmation } from './useDeletionConfirmation';import { appendReferenceImage } from './appendReferenceImage';import { recordCanvasImportError } from './canvasImportError';import { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';+import {+ captureGalleryWidgetKeyValues,+ collectGalleryStoreKnownItemFields,+ diffGalleryWidgetKeyValues,+ selectItemKeysUnchangedSince,+ selectRestorableGalleryWidgetPatches,+ type GalleryWidgetKeySnapshotEntry,+} from './galleryOptimisticRollback';import {getMetadataPrompts,EMPTY_IMAGE_RECALL_CAPABILITIES,@@ -157,6 +171,34 @@ export const useImageActions = ({return project ? getProjectWidgetValues(project, 'generate') : {};};+ // A deleted item can be visible only through a project's `gallery` widget+ // values (e.g. the `recentImages` overlay for a just-generated image that+ // hasn't reached the backend query cache yet) or the `upscale` widget's+ // locked input, none of which `patchGalleryItemCaches` can restore.+ // Snapshot the fields `removeGalleryItems` can touch, across every open+ // project (images aren't project-scoped), diffed before/after so the+ // restore can apply the same "still current" conflict rule+ // `patchGalleryItemCaches`'s own rollback uses instead of clobbering+ // whatever a concurrent generation or selection wrote in the meantime.+ const applyGalleryItemRemoval = (itemKeys: GalleryItemKey[]): GalleryWidgetKeySnapshotEntry[] => {+ const before = captureGalleryWidgetKeyValues(queries.getSnapshot().projects);++ gallery.removeItems(itemKeys);++ return diffGalleryWidgetKeyValues(before, queries.getSnapshot().projects);+ };+ const restoreGalleryItemRemoval = (entries: GalleryWidgetKeySnapshotEntry[]) => {+ const patches = selectRestorableGalleryWidgetPatches(entries, queries.getSnapshot().projects);++ for (const patch of patches) {+ // `patchWidgetValues` is documented "not undoable" (workbenchState.ts);+ // this restore works around that by re-applying the exact prior values+ // as a forward patch, guarded by the CAS check above. `origin: 'system'`+ // keeps it from tripping the auto-route side effects a user-driven+ // widget patch would trigger.+ commands.widgets.patchValues(patch.widgetId, patch.values, patch.projectId, 'system');+ }+ };const reportMutationOutcome = (action: 'delete' | 'move' | 'star' | 'unstar',requestedCount: number,@@ -190,12 +232,16 @@ export const useImageActions = ({boardId,mutate,requested,+ rollback,}: {action: 'delete' | 'move' | 'star' | 'unstar';applyConfirmed: (result: GalleryItemMutationResult, signal: AbortSignal) => Promise<void> | void;boardId?: string;mutate: (signal: AbortSignal) => Promise<GalleryItemMutationResult>;requested: GalleryItemRef[];+ /** Undo the optimistic apply. Runs once, only when the account scope that requested+ * it is still current, before the (likely also-failing) trailing invalidation. */+ rollback?: () => void;}): Promise<void> => {const owner = captureAccountScope();let error: unknown = null;@@ -208,6 +254,12 @@ export const useImageActions = ({await applyConfirmed(result, owner.signal);} catch (caught: unknown) {error = caught;+ // The whole mutation failed — nothing was confirmed, so the optimistic+ // apply must not stand. The trailing invalidation cannot be relied on+ // here: whatever killed the mutation (offline) usually kills it too.+ if (isAccountScopeCurrent(owner)) {+ rollback?.();+ }}if (!isAccountScopeCurrent(owner)) {@@ -235,9 +287,10 @@ export const useImageActions = ({// Optimistic: the items vanish immediately. Capture the action context// first — successor selection reasons about the pre-removal item list —// and keep a snapshot rollback so a failed delete resurrects the lists- // before the confirmed subset is re-applied. Recent-image overlay- // entries cannot be restored the same way; the trailing invalidation- // brings a failed ref back from the backend list instead.+ // before the confirmed subset is re-applied. On a partial failure, the+ // trailing invalidation is left to bring a failed ref's recent-image+ // overlay entry back from the backend list; on a total failure it can't+ // be relied on, so the gallery widget snapshot restores it directly.const deletionContext = getItemActionContext?.() ?? null;let orderedRefs: GalleryItemRef[] | null = null;const isDeletionContextCurrent = (): boolean => {@@ -257,14 +310,32 @@ export const useImageActions = ({kind: 'delete',result: { failed: [], succeeded: items },});+ // `rollbackCaches` is invoked from two independent places below (the+ // partial-failure branch inside `applyConfirmed`, and the total-failure+ // `rollback`): guard so an `applyConfirmed` that throws after already+ // rolling back a partial failure can't undo the cache patch twice.+ let cachesRolledBack = false;+ const rollbackCachesOnce = () => {+ if (cachesRolledBack) {+ return;+ }- gallery.removeItems(items.map(toGalleryItemKey));+ cachesRolledBack = true;+ rollbackCaches();+ };+ // Once `applyConfirmed` starts applying a backend-confirmed result (some+ // items really were deleted), nothing after that point may trigger a+ // full rollback even if it throws — `onImagesDeleted` is a caller-+ // supplied callback invoked after confirmation and can throw for+ // reasons that have nothing to do with the mutation itself.+ let confirmedApplied = false;+ const galleryWidgetSnapshot = applyGalleryItemRemoval(items.map(toGalleryItemKey));return runItemMutation({action: 'delete',applyConfirmed: async (result, signal) => {if (result.failed.length > 0) {- rollbackCaches();+ rollbackCachesOnce();}if (result.succeeded.length === 0) {@@ -326,6 +397,7 @@ export const useImageActions = ({}}+ confirmedApplied = true;patchGalleryItemCaches(queryClient, { kind: 'delete', result });gallery.removeItems(result.succeeded.map(toGalleryItemKey));if (successor) {@@ -358,6 +430,14 @@ export const useImageActions = ({return galleryItemOrganization.delete(items, signal);},requested: items,+ rollback: () => {+ if (confirmedApplied) {+ return;+ }++ rollbackCachesOnce();+ restoreGalleryItemRemoval(galleryWidgetSnapshot);+ },});};const deleteItems = (items: GalleryItemRef[]): Promise<void> =>@@ -369,13 +449,73 @@ export const useImageActions = ({// vanished item cannot be restored by another patch, so the failure// path rolls the lists back wholesale and re-applies the confirmed// subset; the trailing invalidation reconciles anything the rollback- // had to skip as conflicted.- const previousBoardIds = getGalleryItemBoardIdsFromCaches(queryClient, items);+ // had to skip as conflicted. `getGalleryItemBoardIdsFromCaches` only+ // sees items a list query has already fetched, so a just-generated+ // image known only through the recent-image overlay would otherwise+ // have no prior board to restore — read that from the store too, cache+ // taking precedence where both know the item.+ const previousBoardIds = new Map<GalleryItemKey, string>(+ [...collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items)].map(([key, fields]) => [+ key,+ fields.boardId,+ ])+ );++ for (const [key, cachedBoardId] of getGalleryItemBoardIdsFromCaches(queryClient, items)) {+ previousBoardIds.set(key, cachedBoardId);+ }+const rollbackCaches = patchGalleryItemCaches(queryClient, {boardId,kind: 'move',result: { failed: [], succeeded: items },});+ // See the delete path's `cachesRolledBack` note: `rollbackCaches` is+ // reachable both from the partial-failure branch below and from the+ // total-failure `rollback`, so guard against undoing it twice.+ let cachesRolledBack = false;+ const rollbackCachesOnce = () => {+ if (cachesRolledBack) {+ return;+ }++ cachesRolledBack = true;+ rollbackCaches();+ };+ // The cache rollback above is already CAS-guarded per query+ // (`patchGalleryItemCaches`'s own `if (current === after)` rule), but+ // the store patch below is a separate, unconditional write: a second+ // move that painted this item onto yet another board while the first+ // request was still hanging offline must not get clobbered back to the+ // first move's prior board. Only restore items still on the board+ // *this* move painted them onto, and group survivors by prior board id+ // to dispatch one store patch per group instead of one per item.+ const restorePreviousBoardIds = () => {+ const currentStoreBoardIds = collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items);+ const safeKeys = new Set(+ selectItemKeysUnchangedSince(+ [...previousBoardIds.keys()],+ boardId,+ (key) => currentStoreBoardIds.get(key)?.boardId+ )+ );+ const restoreByPreviousBoardId = new Map<string, GalleryItemKey[]>();++ for (const [key, previousBoardId] of previousBoardIds) {+ if (!safeKeys.has(key)) {+ continue;+ }++ const group = restoreByPreviousBoardId.get(previousBoardId) ?? [];++ group.push(key);+ restoreByPreviousBoardId.set(previousBoardId, group);+ }++ for (const [previousBoardId, keys] of restoreByPreviousBoardId) {+ gallery.patchItems(keys, { boardId: previousBoardId });+ }+ };gallery.patchItems(items.map(toGalleryItemKey), { boardId });@@ -386,7 +526,7 @@ export const useImageActions = ({return;}- rollbackCaches();+ rollbackCachesOnce();patchGalleryItemCaches(queryClient, { boardId, kind: 'move', result });for (const ref of result.failed) {@@ -401,6 +541,10 @@ export const useImageActions = ({boardId,mutate: (signal) => galleryItemOrganization.moveToBoard(items, boardId, signal),requested: items,+ rollback: () => {+ rollbackCachesOnce();+ restorePreviousBoardIds();+ },});};const patchItemsStarred = (refs: GalleryItemRef[], starred: boolean): void => {@@ -411,11 +555,44 @@ export const useImageActions = ({patchGalleryItemCaches(queryClient, { kind: 'star', result: { failed: [], succeeded: refs }, starred });gallery.patchItems(refs.map(toGalleryItemKey), { starred });};+ // Split cache/store writers used only by the CAS-guarded rollback below,+ // where the two sides can pass or fail the "still current" check+ // independently (e.g. a trailing invalidation already reconciled the+ // cache but the store overlay wasn't touched).+ const patchStarredCacheOnly = (refs: GalleryItemRef[], starred: boolean): void => {+ if (refs.length === 0) {+ return;+ }++ patchGalleryItemCaches(queryClient, { kind: 'star', result: { failed: [], succeeded: refs }, starred });+ };+ const patchStarredStoreOnly = (keys: GalleryItemKey[], starred: boolean): void => {+ if (keys.length === 0) {+ return;+ }++ gallery.patchItems(keys, { starred });+ };const setItemsStarred = (items: GalleryItemRef[], starred: boolean): Promise<void> => {// Optimistic: a star toggle's outcome is the request itself except for// the rare rejected ref, so paint the whole selection immediately and// flip back only what the backend refuses. The trailing gallery- // invalidation reconciles either path with the server.+ // invalidation reconciles either path with the server. A total failure+ // can't rely on that invalidation, so capture each item's actual prior+ // flag up front (cache, falling back to the store overlay for items a+ // list query hasn't fetched) — blanket-inverting the whole batch would+ // wrongly flip items that already matched the target flag beforehand.+ const previousStarred = new Map<GalleryItemKey, boolean>(+ [...collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items)].map(([key, fields]) => [+ key,+ fields.starred,+ ])+ );++ for (const [key, cachedStarred] of getGalleryItemStarredFromCaches(queryClient, items)) {+ previousStarred.set(key, cachedStarred);+ }+patchItemsStarred(items, starred);return runItemMutation({@@ -423,6 +600,51 @@ export const useImageActions = ({applyConfirmed: (result) => patchItemsStarred(result.failed, !starred),mutate: (signal) => galleryItemOrganization.setStarred(items, starred, signal),requested: items,+ // Total failure: nothing was confirmed. Restore each item to its+ // actual prior flag rather than blanket-inverting the batch. An item+ // with no known prior flag is left as painted — there's nothing safe+ // to revert it to. Unlike the cache half of delete/move,+ // `patchGalleryItemCaches` here is a fresh forward patch with no+ // built-in CAS of its own (star's optimistic apply is a value flip,+ // not a snapshot/restore pair) — so both the cache and the store+ // writes need their own "still painted, nothing moved on" check+ // before a concurrent single-item toggle gets clobbered.+ rollback: () => {+ const requestedKeys = items.map(toGalleryItemKey);+ const currentCacheStarred = getGalleryItemStarredFromCaches(queryClient, items);+ const currentStoreFields = collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items);+ const safeCacheKeys = new Set(+ selectItemKeysUnchangedSince(requestedKeys, starred, (key) => currentCacheStarred.get(key))+ );+ const safeStoreKeys = new Set(+ selectItemKeysUnchangedSince(requestedKeys, starred, (key) => currentStoreFields.get(key)?.starred)+ );+ const restoreGroups = new Map<boolean, GalleryItemRef[]>();++ for (const item of items) {+ const priorStarred = previousStarred.get(toGalleryItemKey(item));++ if (priorStarred === undefined) {+ continue;+ }++ const group = restoreGroups.get(priorStarred) ?? [];++ group.push(item);+ restoreGroups.set(priorStarred, group);+ }++ for (const [priorStarred, refs] of restoreGroups) {+ patchStarredCacheOnly(+ refs.filter((ref) => safeCacheKeys.has(toGalleryItemKey(ref))),+ priorStarred+ );+ patchStarredStoreOnly(+ refs.filter((ref) => safeStoreKeys.has(toGalleryItemKey(ref))).map(toGalleryItemKey),+ priorStarred+ );+ }+ },});};const fetchItemBlob = async (item: GalleryItem, signal: AbortSignal): Promise<Blob> => {