Skip to content

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.

feat(webv2): apply gallery move, delete, and board updates optimistically

joshistoastf41a7d939cf5
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
index 05da5f6c83..1a88ff1861 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
@@ -1,4 +1,5 @@
import type { GalleryItem, GalleryItemMutationResult, GalleryItemsPage } from '@features/gallery/core/items';
+import type { GalleryBoard } from '@features/gallery/core/types';
import type { AccountScope } from '@platform/state/accountLifecycle';
import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
@@ -7,7 +8,13 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { ALL_READABLE_BOARDS_ID } from './backend';
import { canonicalizeGalleryItemsFilter, galleryKeys } from './queries';
-import { invalidateGallery, invalidateGalleryItems, patchGalleryItemCaches } from './queryCache';
+import {
+ getGalleryItemBoardIdsFromCaches,
+ invalidateGallery,
+ invalidateGalleryItems,
+ patchGalleryBoardCaches,
+ patchGalleryItemCaches,
+} from './queryCache';
type GalleryItemsData = InfiniteData<GalleryItemsPage, number>;
@@ -245,6 +252,106 @@ describe('Gallery item cache patches', () => {
});
});
+describe('getGalleryItemBoardIdsFromCaches', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('gallery-query-cache-test');
+ });
+
+ it('reads each requested item’s current board from whichever list holds it', () => {
+ const client = createClient();
+
+ client.setQueryData(getItemsKey('board-1'), createData([[createItem('a.png', 'board-1')]]));
+ client.setQueryData(
+ getItemsKey(ALL_READABLE_BOARDS_ID),
+ createData([[createItem('b.mp4', 'board-2', false, 'video')]])
+ );
+
+ const boardIds = getGalleryItemBoardIdsFromCaches(client, [
+ { kind: 'image', name: 'a.png' },
+ { kind: 'video', name: 'b.mp4' },
+ { kind: 'image', name: 'unloaded.png' },
+ ]);
+
+ expect(boardIds.get('image:a.png')).toBe('board-1');
+ expect(boardIds.get('video:b.mp4')).toBe('board-2');
+ expect(boardIds.has('image:unloaded.png')).toBe(false);
+ });
+});
+
+const createBoard = (id: string, overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({
+ archived: false,
+ assetCount: 0,
+ id,
+ imageCount: 1,
+ kind: 'board',
+ name: `Board ${id}`,
+ projectId: null,
+ videoCount: 0,
+ ...overrides,
+});
+
+describe('patchGalleryBoardCaches', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('gallery-query-cache-test');
+ });
+
+ const getBoardsKey = (owner: AccountScope = captureAccountScope()) =>
+ galleryKeys.boards(owner, {
+ includeArchived: false,
+ includeDateBoards: true,
+ orderBy: 'created_at',
+ orderDir: 'DESC',
+ });
+
+ it('patches the board in every cached list and rolls back to the prior lists', () => {
+ const client = createClient();
+ const key = getBoardsKey();
+ const untouched = createBoard('board-2');
+
+ client.setQueryData(key, [createBoard('board-1'), untouched]);
+ const before = client.getQueryData<GalleryBoard[]>(key);
+
+ const rollback = patchGalleryBoardCaches(client, 'board-1', { archived: true, name: 'Renamed' });
+ const after = client.getQueryData<GalleryBoard[]>(key);
+
+ expect(after?.[0]).toEqual({ ...createBoard('board-1'), archived: true, name: 'Renamed' });
+ expect(after?.[1]).toBe(untouched);
+
+ rollback();
+
+ // Structural sharing rebuilds the array, so compare by value and keep the
+ // untouched board's identity.
+ expect(client.getQueryData(key)).toEqual(before);
+ expect(client.getQueryData<GalleryBoard[]>(key)?.[1]).toBe(untouched);
+ });
+
+ it('does not let rollback clobber a later concurrent boards update', () => {
+ const client = createClient();
+ const key = getBoardsKey();
+
+ client.setQueryData(key, [createBoard('board-1')]);
+ const rollback = patchGalleryBoardCaches(client, 'board-1', { name: 'Renamed' });
+ const concurrent = client.setQueryData<GalleryBoard[]>(key, (boards) =>
+ boards?.map((board) => ({ ...board, imageCount: 9 }))
+ );
+
+ rollback();
+
+ expect(client.getQueryData(key)).toBe(concurrent);
+ });
+
+ it('leaves lists without the board untouched', () => {
+ const client = createClient();
+ const key = getBoardsKey();
+ const boards = [createBoard('board-2')];
+
+ client.setQueryData(key, boards);
+ patchGalleryBoardCaches(client, 'board-1', { archived: true });
+
+ expect(client.getQueryData(key)).toBe(boards);
+ });
+});
+
describe('Gallery cache invalidation', () => {
beforeEach(() => {
accountLifecycle.activate('gallery-query-cache-invalidation-test');
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
index ad7075408e..c7b846e8b7 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
@@ -2,8 +2,10 @@ import type {
GalleryItem,
GalleryItemKey,
GalleryItemMutationResult,
+ GalleryItemRef,
GalleryItemsPage,
} from '@features/gallery/core/items';
+import type { GalleryBoard } from '@features/gallery/core/types';
import type { AccountScope } from '@platform/state/accountLifecycle';
import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query';
@@ -191,6 +193,102 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCa
};
};
+/**
+ * Reads the board each requested item currently sits on, from whichever list
+ * cache holds it. Optimistic moves capture this before patching so a rejected
+ * ref can be put back without waiting for the reconciling refetch.
+ */
+export const getGalleryItemBoardIdsFromCaches = (
+ client: QueryClient,
+ refs: readonly GalleryItemRef[]
+): Map<GalleryItemKey, string> => {
+ const wanted = new Set(refs.map(toGalleryItemKey));
+ const boardIds = new Map<GalleryItemKey, string>();
+
+ for (const query of getGalleryItemListQueries(client)) {
+ if (boardIds.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) && !boardIds.has(key)) {
+ boardIds.set(key, item.boardId);
+ }
+ }
+ }
+ }
+
+ return boardIds;
+};
+
+interface BoardCacheRollbackEntry {
+ after: GalleryBoard[];
+ before: GalleryBoard[];
+ queryKey: QueryKey;
+}
+
+const isGalleryBoardsData = (value: unknown): value is GalleryBoard[] =>
+ Array.isArray(value) && value.every((board) => typeof board === 'object' && board !== null && 'id' in board);
+
+/**
+ * Patches one board across every cached board list and returns a rollback
+ * that restores the prior lists — skipping any list something else has
+ * written to since, the same conflict rule as `patchGalleryItemCaches`.
+ */
+export const patchGalleryBoardCaches = (
+ client: QueryClient,
+ boardId: string,
+ changes: Partial<Pick<GalleryBoard, 'archived' | 'name'>>
+): (() => void) => {
+ const owner = captureAccountScope();
+ const rollbackEntries: BoardCacheRollbackEntry[] = [];
+
+ for (const query of client.getQueryCache().findAll({ queryKey: galleryKeys.boardsForAccount(owner) })) {
+ const before = query.state.data;
+
+ if (!isGalleryBoardsData(before)) {
+ continue;
+ }
+
+ let changed = false;
+ const after = before.map((board) => {
+ if (board.id !== boardId) {
+ return board;
+ }
+
+ changed = true;
+ return { ...board, ...changes };
+ });
+
+ if (!changed) {
+ continue;
+ }
+
+ const applied = client.setQueryData<GalleryBoard[]>(query.queryKey, after);
+
+ if (applied) {
+ rollbackEntries.push({ after: applied, before, queryKey: query.queryKey });
+ }
+ }
+
+ return () => {
+ for (const { after, before, queryKey } of rollbackEntries) {
+ if (client.getQueryData(queryKey) === after) {
+ client.setQueryData(queryKey, before);
+ }
+ }
+ };
+};
+
const runGalleryInvalidation = async (
client: QueryClient,
owner: AccountScope,
diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.ts
index f1333d276e..e1cdc72fcb 100644
--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts
@@ -16,5 +16,10 @@ export type {
GalleryItemsListQueryKey,
GalleryItemsWindow,
} from './data/queries';
-export { invalidateGallery, invalidateGalleryItems, patchGalleryItemCaches } from './data/queryCache';
+export {
+ getGalleryItemBoardIdsFromCaches,
+ invalidateGallery,
+ invalidateGalleryItems,
+ patchGalleryItemCaches,
+} from './data/queryCache';
export type { GalleryItemCachePatch } from './data/queryCache';
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
index dfe02b5bc6..90d350f354 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx
@@ -18,6 +18,8 @@ const mocks = vi.hoisted(() => ({
invalidateGallery: vi.fn(),
notificationsAdd: vi.fn(),
notificationsReportError: vi.fn(),
+ patchGalleryBoardCaches: vi.fn((..._args: unknown[]) => vi.fn()),
+ updateGalleryBoard: vi.fn(),
uploadGalleryImage: vi.fn(),
uploadGalleryVideo: vi.fn(),
}));
@@ -39,7 +41,7 @@ vi.mock('@features/gallery/data/backend', () => ({
deleteGalleryBoard: (...args: unknown[]) => mocks.deleteGalleryBoard(...args),
downloadGalleryArchive: (...args: unknown[]) => mocks.downloadGalleryArchive(...args),
isDateBoardId: (boardId: string) => boardId.startsWith('by_date:'),
- updateGalleryBoard: vi.fn(),
+ updateGalleryBoard: (...args: unknown[]) => mocks.updateGalleryBoard(...args),
uploadGalleryImage: (...args: unknown[]) => mocks.uploadGalleryImage(...args),
uploadGalleryVideo: (...args: unknown[]) => mocks.uploadGalleryVideo(...args),
}));
@@ -82,6 +84,7 @@ vi.mock('react-i18next', () => ({
vi.mock('@features/gallery/data/queryCache', () => ({
invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),
+ patchGalleryBoardCaches: (...args: unknown[]) => mocks.patchGalleryBoardCaches(...args),
}));
vi.mock('@platform/browser/downloadBlob', () => ({
@@ -92,6 +95,7 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
const actionsRef = createRef<GalleryActions>();
const reconcileDeletedBoardOutcome = vi.fn();
+const selectBoard = vi.fn();
const selectItem = vi.fn();
const setItemMultiSelection = vi.fn();
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -155,7 +159,7 @@ const adapter: GalleryUiAdapter = {
exportProject: vi.fn(),
gallery: {
reconcileDeletedBoardOutcome,
- selectBoard: noop,
+ selectBoard,
selectImage: noop,
selectItem,
setCompareImage: noop,
@@ -264,6 +268,97 @@ describe('deleteBoard', () => {
});
});
+describe('optimistic board updates', () => {
+ it('renames before the request and rolls back when the backend rejects', async () => {
+ mocks.updateGalleryBoard.mockRejectedValue(new Error('rename failed'));
+
+ await act(async () => {
+ await actionsRef.current?.renameBoard('board-1', 'Renamed');
+ });
+
+ expect(mocks.patchGalleryBoardCaches).toHaveBeenCalledWith(expect.anything(), 'board-1', { name: 'Renamed' });
+ expect(mocks.patchGalleryBoardCaches.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.updateGalleryBoard.mock.invocationCallOrder[0] ?? 0
+ );
+ expect(mocks.patchGalleryBoardCaches.mock.results[0]?.value).toHaveBeenCalledOnce();
+ expect(mocks.notificationsReportError).toHaveBeenCalledOnce();
+ expect(mocks.invalidateGallery).not.toHaveBeenCalled();
+ });
+
+ it('keeps a successful rename applied without rolling back', async () => {
+ mocks.updateGalleryBoard.mockResolvedValue(undefined);
+
+ await act(async () => {
+ await actionsRef.current?.renameBoard('board-1', 'Renamed');
+ });
+
+ expect(mocks.patchGalleryBoardCaches.mock.results[0]?.value).not.toHaveBeenCalled();
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ });
+
+ it('archives the viewed board and steps off it before the request resolves', async () => {
+ mocks.updateGalleryBoard.mockResolvedValue(undefined);
+
+ await act(async () => {
+ await actionsRef.current?.archiveBoard('board-1', true);
+ });
+
+ expect(mocks.patchGalleryBoardCaches).toHaveBeenCalledWith(expect.anything(), 'board-1', { archived: true });
+ expect(selectBoard).toHaveBeenCalledWith('none');
+ expect(selectBoard.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.updateGalleryBoard.mock.invocationCallOrder[0] ?? 0
+ );
+ });
+
+ it('restores the archived board selection on failure only while still on Uncategorized', async () => {
+ let rejectUpdate: (error: Error) => void = () => undefined;
+ mocks.updateGalleryBoard.mockReturnValue(
+ new Promise((_resolve, reject) => {
+ rejectUpdate = reject;
+ })
+ );
+
+ let archive!: Promise<void>;
+ await act(() => {
+ archive = actionsRef.current!.archiveBoard('board-1', true);
+ });
+
+ // Reflect the optimistic step-off in the live location the failure path reads.
+ selectedBoardId = 'none';
+ await renderProbe();
+ rejectUpdate(new Error('archive failed'));
+ await act(() => archive);
+
+ expect(mocks.patchGalleryBoardCaches.mock.results[0]?.value).toHaveBeenCalledOnce();
+ expect(selectBoard).toHaveBeenNthCalledWith(1, 'none');
+ expect(selectBoard).toHaveBeenNthCalledWith(2, 'board-1');
+ expect(mocks.notificationsReportError).toHaveBeenCalledOnce();
+ });
+
+ it('does not fight a user who navigated elsewhere while an archive was failing', async () => {
+ let rejectUpdate: (error: Error) => void = () => undefined;
+ mocks.updateGalleryBoard.mockReturnValue(
+ new Promise((_resolve, reject) => {
+ rejectUpdate = reject;
+ })
+ );
+
+ let archive!: Promise<void>;
+ await act(() => {
+ archive = actionsRef.current!.archiveBoard('board-1', true);
+ });
+
+ // The user moved on to a different board before the failure arrived.
+ selectedBoardId = 'board-2';
+ await renderProbe();
+ rejectUpdate(new Error('archive failed'));
+ await act(() => archive);
+
+ expect(selectBoard).toHaveBeenCalledOnce();
+ expect(selectBoard).toHaveBeenCalledWith('none');
+ });
+});
+
describe('localized board labels', () => {
it('uses the localized Uncategorized label in board notifications', async () => {
mocks.downloadGalleryArchive.mockResolvedValue({ blob: new Blob(['archive']), fileName: 'gallery.zip' });
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index 48f361ff52..e39fd1f4e1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -8,7 +8,7 @@ import {
downloadGalleryArchive,
updateGalleryBoard,
} from '@features/gallery/data/backend';
-import { invalidateGallery } from '@features/gallery/data/queryCache';
+import { invalidateGallery, patchGalleryBoardCaches } from '@features/gallery/data/queryCache';
import { downloadBlob } from '@platform/browser/downloadBlob';
import {
assertAccountScopeCurrent,
@@ -59,6 +59,14 @@ export const useGalleryActions = ({
return {
archiveBoard: async (boardId, archived) => {
const owner = captureAccountScope();
+ // Optimistic: the board moves between sections immediately, and
+ // archiving the board being viewed steps off it right away.
+ const rollback = patchGalleryBoardCaches(queryClient, boardId, { archived });
+ const movedSelectionAway = archived && boardId === selectedBoardId;
+
+ if (movedSelectionAway) {
+ gallery.selectBoard('none');
+ }
try {
await updateGalleryBoard(boardId, { archived }, owner.signal);
@@ -69,17 +77,18 @@ export const useGalleryActions = ({
name: getBoardName(boardId),
})
);
-
- if (archived && boardId === selectedBoardId) {
- gallery.selectBoard('none');
- }
-
refresh();
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
}
+ rollback();
+
+ if (movedSelectionAway && getCurrentGalleryLocation().selectedBoardId === 'none') {
+ gallery.selectBoard(boardId);
+ }
+
recordError(error);
}
},
@@ -172,6 +181,9 @@ export const useGalleryActions = ({
refresh,
renameBoard: async (boardId, boardName) => {
const owner = captureAccountScope();
+ // Optimistic: the new name paints everywhere at once; the refresh
+ // re-sorts name-ordered lists once the backend confirms.
+ const rollback = patchGalleryBoardCaches(queryClient, boardId, { name: boardName });
try {
await updateGalleryBoard(boardId, { name: boardName }, owner.signal);
@@ -184,6 +196,7 @@ export const useGalleryActions = ({
return;
}
+ rollback();
recordError(error);
}
},
@@ -197,5 +210,16 @@ export const useGalleryActions = ({
updateSettings: gallery.updateSettings,
uploadFiles,
};
- }, [boards, exportProject, gallery, loadMore, notifications, queryClient, selectedBoardId, t, uploadFiles]);
+ }, [
+ boards,
+ exportProject,
+ gallery,
+ getCurrentGalleryLocation,
+ loadMore,
+ notifications,
+ queryClient,
+ selectedBoardId,
+ t,
+ uploadFiles,
+ ]);
};
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.tsx
index 0b90466535..78e79eec6c 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,6 +17,7 @@ const mocks = vi.hoisted(() => ({
downloadBlob: vi.fn(),
galleryRemoveItems: vi.fn(),
galleryPatchItems: vi.fn(),
+ getItemBoardIds: vi.fn((..._args: unknown[]) => new Map<string, string>()),
gallerySelectItem: vi.fn(),
gallerySetItemMultiSelection: vi.fn(),
imageMetadata: vi.fn(),
@@ -56,6 +57,7 @@ vi.mock('@features/gallery', () => ({
}));
vi.mock('@features/gallery/queries', () => ({
+ getGalleryItemBoardIdsFromCaches: (...args: unknown[]) => mocks.getItemBoardIds(...args),
invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),
invalidateGalleryItems: (...args: unknown[]) => mocks.invalidateGalleryItems(...args),
patchGalleryItemCaches: (...args: unknown[]) => mocks.patchGalleryItemCaches(...args),
@@ -280,7 +282,8 @@ describe('image recall capability cancellation', () => {
});
describe('partial image mutation outcomes', () => {
- it('moves and patches only images confirmed by the backend', async () => {
+ it('moves optimistically, then rolls back and re-applies only backend-confirmed images', async () => {
+ mocks.getItemBoardIds.mockReturnValue(new Map([['image:locked.png', 'board-0']]));
mocks.itemMoveToBoard.mockResolvedValue({
affectedBoardIds: ['board-1'],
failed: [{ kind: 'image', name: 'locked.png' }],
@@ -291,18 +294,39 @@ describe('partial image mutation outcomes', () => {
await actionsRef.current?.moveImagesToBoard(['moved.png', 'locked.png'], 'board-1');
});
- const result = {
- affectedBoardIds: ['board-1'],
- failed: [{ kind: 'image', name: 'locked.png' }],
- succeeded: [{ kind: 'image', name: 'moved.png' }],
- };
+ // The whole selection moves before the transport is even asked.
+ expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(1, expect.anything(), {
+ boardId: 'board-1',
+ kind: 'move',
+ result: {
+ failed: [],
+ succeeded: [
+ { kind: 'image', name: 'moved.png' },
+ { kind: 'image', name: 'locked.png' },
+ ],
+ },
+ });
+ expect(mocks.patchGalleryItemCaches.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.itemMoveToBoard.mock.invocationCallOrder[0] ?? 0
+ );
+ expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(1, ['image:moved.png', 'image:locked.png'], {
+ boardId: 'board-1',
+ });
- expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), {
+ // Partial failure: the optimistic patch is rolled back wholesale, the
+ // confirmed subset re-applied, and the rejected ref returns to the board
+ // it was captured on.
+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();
+ expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), {
boardId: 'board-1',
kind: 'move',
- result,
+ result: {
+ affectedBoardIds: ['board-1'],
+ failed: [{ kind: 'image', name: 'locked.png' }],
+ succeeded: [{ kind: 'image', name: 'moved.png' }],
+ },
});
- expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:moved.png'], { boardId: 'board-1' });
+ expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(2, ['image:locked.png'], { boardId: 'board-0' });
});
it('stars optimistically before the request and reverts only backend-rejected images', async () => {
@@ -416,7 +440,7 @@ describe('mixed item mutation outcomes', () => {
});
});
- it('moves mixed refs through the common organization result and patches only confirmed qualified keys', async () => {
+ it('moves mixed refs optimistically and reverts only the failed qualified key', async () => {
const refs = [
{ kind: 'image' as const, name: 'shared' },
{ kind: 'video' as const, name: 'shared' },
@@ -426,6 +450,7 @@ describe('mixed item mutation outcomes', () => {
failed: [refs[1]],
succeeded: [refs[0]],
};
+ mocks.getItemBoardIds.mockReturnValue(new Map([['video:shared', 'board-1']]));
mocks.itemMoveToBoard.mockResolvedValue(result);
await act(async () => {
@@ -433,12 +458,15 @@ describe('mixed item mutation outcomes', () => {
});
expect(mocks.itemMoveToBoard).toHaveBeenCalledWith(refs, 'board-2', expect.any(AbortSignal));
- expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), {
+ expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(1, ['image:shared', 'video:shared'], {
+ boardId: 'board-2',
+ });
+ expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), {
boardId: 'board-2',
kind: 'move',
result,
});
- expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:shared'], { boardId: 'board-2' });
+ expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(2, ['video:shared'], { boardId: 'board-1' });
expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
});
@@ -470,7 +498,7 @@ describe('mixed item mutation outcomes', () => {
expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
});
- it('deletes only confirmed refs and does not prune an ambiguous failed ref', async () => {
+ it('deletes optimistically, then rolls back and re-removes only confirmed refs on partial failure', async () => {
const refs = [
{ kind: 'video' as const, name: 'gone.mp4' },
{ kind: 'image' as const, name: 'locked.png' },
@@ -486,8 +514,21 @@ describe('mixed item mutation outcomes', () => {
await getItemActions().deleteItems(refs);
});
- expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), { kind: 'delete', result });
- expect(mocks.galleryRemoveItems).toHaveBeenCalledWith(['video:gone.mp4']);
+ // Everything requested vanishes before the transport is asked.
+ expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(1, expect.anything(), {
+ kind: 'delete',
+ result: { failed: [], succeeded: refs },
+ });
+ expect(mocks.patchGalleryItemCaches.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.itemDelete.mock.invocationCallOrder[0] ?? 0
+ );
+ expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['video:gone.mp4', 'image:locked.png']);
+
+ // The failed ref is resurrected by the rollback, then only the confirmed
+ // ref is removed again.
+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();
+ expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), { kind: 'delete', result });
+ expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(2, ['video:gone.mp4']);
expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
});
@@ -767,8 +808,14 @@ describe('primary successor after confirmed deletion', () => {
resolveItem(successor);
await act(() => deletion);
- expect(mocks.patchGalleryItemCaches).not.toHaveBeenCalled();
- expect(mocks.galleryRemoveItems).not.toHaveBeenCalled();
+ // The optimistic removal happened up front, on the account that asked for
+ // it; nothing further may apply once the account has changed.
+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledOnce();
+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), {
+ kind: 'delete',
+ result: { failed: [], succeeded: [{ kind: 'image', name: primary.name }] },
+ });
+ expect(mocks.galleryRemoveItems).toHaveBeenCalledOnce();
expect(mocks.gallerySelectItem).not.toHaveBeenCalled();
expect(mocks.invalidateGallery).not.toHaveBeenCalled();
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index c0b06f1359..5a9176168a 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -16,7 +16,7 @@ import {
type GalleryItemRef,
} from '@features/gallery';
import { getGalleryBoardLabel } from '@features/gallery/contracts';
-import { invalidateGallery, patchGalleryItemCaches } from '@features/gallery/queries';
+import { getGalleryItemBoardIdsFromCaches, 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';
@@ -232,7 +232,13 @@ export const useImageActions = ({
reportMutationOutcome(action, requested.length, result, boardId);
};
const deleteItemsConfirmed = (items: GalleryItemRef[]): Promise<void> => {
- let deletionContext: GalleryItemActionContext | null = null;
+ // 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.
+ const deletionContext = getItemActionContext?.() ?? null;
let orderedRefs: GalleryItemRef[] | null = null;
const isDeletionContextCurrent = (): boolean => {
if (!deletionContext || !getItemActionContext) {
@@ -247,10 +253,20 @@ export const useImageActions = ({
current.selectedItemKey === deletionContext.selectedItemKey
);
};
+ const rollbackCaches = patchGalleryItemCaches(queryClient, {
+ kind: 'delete',
+ result: { failed: [], succeeded: items },
+ });
+
+ gallery.removeItems(items.map(toGalleryItemKey));
return runItemMutation({
action: 'delete',
applyConfirmed: async (result, signal) => {
+ if (result.failed.length > 0) {
+ rollbackCaches();
+ }
+
if (result.succeeded.length === 0) {
return;
}
@@ -327,8 +343,6 @@ export const useImageActions = ({
onImagesDeleted?.(result.succeeded.filter((item) => item.kind === 'image').map((item) => item.name));
},
mutate: async (signal) => {
- deletionContext = getItemActionContext?.() ?? null;
-
if (
deletionContext?.selectedItemKey &&
items.some((item) => toGalleryItemKey(item) === deletionContext?.selectedItemKey)
@@ -350,21 +364,45 @@ export const useImageActions = ({
confirmImageDeletion
? requestDeletionConfirmation(items, () => deleteItemsConfirmed(items))
: deleteItemsConfirmed(items);
- const moveItemsToBoard = (items: GalleryItemRef[], boardId: string): Promise<void> =>
- runItemMutation({
+ const moveItemsToBoard = (items: GalleryItemRef[], boardId: string): Promise<void> => {
+ // Optimistic: the items leave the current board view immediately. A
+ // 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);
+ const rollbackCaches = patchGalleryItemCaches(queryClient, {
+ boardId,
+ kind: 'move',
+ result: { failed: [], succeeded: items },
+ });
+
+ gallery.patchItems(items.map(toGalleryItemKey), { boardId });
+
+ return runItemMutation({
action: 'move',
applyConfirmed: (result) => {
- if (result.succeeded.length === 0) {
+ if (result.failed.length === 0) {
return;
}
+ rollbackCaches();
patchGalleryItemCaches(queryClient, { boardId, kind: 'move', result });
- gallery.patchItems(result.succeeded.map(toGalleryItemKey), { boardId });
+
+ for (const ref of result.failed) {
+ const key = toGalleryItemKey(ref);
+ const previousBoardId = previousBoardIds.get(key);
+
+ if (previousBoardId !== undefined) {
+ gallery.patchItems([key], { boardId: previousBoardId });
+ }
+ }
},
boardId,
mutate: (signal) => galleryItemOrganization.moveToBoard(items, boardId, signal),
requested: items,
});
+ };
const patchItemsStarred = (refs: GalleryItemRef[], starred: boolean): void => {
if (refs.length === 0) {
return;