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.

fix(webv2): centralize gallery deletion confirmation

joshistoast944e679ed27a
diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx
index 1f28ce84f9..fed38cf7a8 100644
--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx
@@ -12,6 +12,7 @@ import { GalleryImageContextMenu, GalleryItemActionsAdapter } from './GalleryIma
const mocks = vi.hoisted(() => ({
moveItemsToBoard: vi.fn(),
+ requestDeletionConfirmation: vi.fn(),
useImageActions: vi.fn(),
}));
@@ -32,6 +33,10 @@ vi.mock('@workbench/image-actions', () => ({
)}
</output>
),
+ useDeletionConfirmation: () => ({
+ dialog: <output data-testid="deletion-confirmation-dialog" />,
+ requestDeletionConfirmation: mocks.requestDeletionConfirmation,
+ }),
useImageActions: (options: unknown) => {
mocks.useImageActions(options);
return {
@@ -102,6 +107,19 @@ afterEach(async () => {
});
describe('GalleryImageActionsBridge mixed selection boundaries', () => {
+ it('wires the shared deletion-confirmation gate into the actions adapter', async () => {
+ await render(
+ <GalleryItemActionsAdapter boards={[]} generateValues={{}} projectId="project-1">
+ <ActionsProbe ref={actionsRef} />
+ </GalleryItemActionsAdapter>
+ );
+
+ expect(host?.querySelector('[data-testid="deletion-confirmation-dialog"]')).not.toBeNull();
+ expect(mocks.useImageActions).toHaveBeenCalledWith(
+ expect.objectContaining({ requestDeletionConfirmation: mocks.requestDeletionConfirmation })
+ );
+ });
+
it('forwards the complete canonical context target without narrowing a mixed selection', async () => {
const target: GalleryItemContextMenuTarget = {
itemRefs: mixedRefs,
diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
index 88707a26d7..2a11c74e61 100644
--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
@@ -2,7 +2,12 @@ import type { GalleryItemActionsOptions, GalleryItemContextMenuProps } from '@fe
import type { ReactNode } from 'react';
import { GalleryItemActionsProvider } from '@features/gallery/react';
-import { ImageContextMenu, useImageActions, type ImageActions } from '@workbench/image-actions';
+import {
+ ImageContextMenu,
+ useDeletionConfirmation,
+ useImageActions,
+ type ImageActions,
+} from '@workbench/image-actions';
import { createContext, use } from 'react';
const GalleryAppActionsContext = createContext<ImageActions | null>(null);
@@ -24,12 +29,22 @@ const GalleryItemActionsAdapterComponent = ({
getItemActionContext,
projectId,
}: GalleryItemActionsOptions & { children: ReactNode }) => {
- const actions = useImageActions({ boards, generateValues, getItemActionContext, projectId });
+ const { dialog, requestDeletionConfirmation } = useDeletionConfirmation();
+ const actions = useImageActions({
+ boards,
+ generateValues,
+ getItemActionContext,
+ projectId,
+ requestDeletionConfirmation,
+ });
return (
- <GalleryAppActionsContext value={actions}>
- <GalleryItemActionsProvider actions={actions}>{children}</GalleryItemActionsProvider>
- </GalleryAppActionsContext>
+ <>
+ <GalleryAppActionsContext value={actions}>
+ <GalleryItemActionsProvider actions={actions}>{children}</GalleryItemActionsProvider>
+ </GalleryAppActionsContext>
+ {dialog}
+ </>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
index 19df4a928f..e84bbae3fa 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
@@ -6,20 +6,15 @@ import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
import { act, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ImageActions } from './useImageActions';
import { ImageContextMenu, type ImageContextMenuTarget } from './ImageContextMenu';
import { EMPTY_IMAGE_RECALL_CAPABILITIES } from './imageRecall';
-const preferences = vi.hoisted(() => ({ confirmImageDeletion: true }));
const NO_BOARDS: [] = [];
-vi.mock('@workbench/settings/store', () => ({
- useWorkbenchPreferenceSelector: (selector: (value: { confirmImageDeletion: boolean }) => boolean): boolean =>
- selector(preferences),
-}));
vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));
vi.mock('@workbench/WorkbenchContext', () => ({
useWorkbenchCommands: () => ({
@@ -79,18 +74,6 @@ const interact = (action: () => void): Promise<void> =>
});
});
-const getButton = (label: string): HTMLButtonElement => {
- const button = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(
- (candidate) => candidate.textContent?.trim() === label
- );
-
- if (!button) {
- throw new Error(`Could not find button: ${label}`);
- }
-
- return button;
-};
-
const getMenuItem = (label: string): HTMLElement => {
const item = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(
(candidate) => candidate.textContent?.trim() === label
@@ -172,10 +155,6 @@ const renderItemMenu = async (
});
};
-beforeEach(() => {
- preferences.confirmImageDeletion = true;
-});
-
afterEach(async () => {
await interact(() => root?.unmount());
host?.remove();
@@ -183,87 +162,14 @@ afterEach(async () => {
root = null;
});
-describe('ImageContextMenu deletion confirmation', () => {
- it('keeps single-image confirmation mounted after the host clears the menu target', async () => {
- const deleteImages = vi.fn(() => Promise.resolve());
- await renderMenu(createActions(deleteImages), [image('single.png')]);
-
- await interact(() => getMenuItem('Delete Image').click());
-
- expect(getOpenAlertDialog()).not.toBeNull();
- expect(document.body.textContent).toContain('Delete image?');
- expect(deleteImages).not.toHaveBeenCalled();
-
- await interact(() => getButton('Delete').click());
-
- expect(deleteImages).toHaveBeenCalledOnce();
- expect(deleteImages).toHaveBeenCalledWith([{ kind: 'image', name: 'single.png' }]);
- expect(getOpenAlertDialog()).toBeNull();
- });
-
- it('cancels without deleting', async () => {
- const deleteImages = vi.fn(() => Promise.resolve());
- await renderMenu(createActions(deleteImages), [image('cancel.png')]);
-
- await interact(() => getMenuItem('Delete Image').click());
- await interact(() => getButton('Cancel').click());
-
- expect(deleteImages).not.toHaveBeenCalled();
- expect(getOpenAlertDialog()).toBeNull();
- });
-
- it('deletes immediately when confirmation is disabled', async () => {
- preferences.confirmImageDeletion = false;
- const deleteImages = vi.fn(() => Promise.resolve());
- await renderMenu(createActions(deleteImages), [image('immediate.png')]);
+describe('ImageContextMenu deletion delegation', () => {
+ it('delegates deletion to the shared image actions adapter', async () => {
+ const deleteItems = vi.fn(() => Promise.resolve());
+ await renderMenu(createActions(deleteItems), [image('single.png')]);
await interact(() => getMenuItem('Delete Image').click());
- expect(deleteImages).toHaveBeenCalledOnce();
- expect(deleteImages).toHaveBeenCalledWith([{ kind: 'image', name: 'immediate.png' }]);
- expect(getOpenAlertDialog()).toBeNull();
- });
-
- it('captures bulk names and cannot be dismissed or submitted twice while deletion is pending', async () => {
- let resolveDeletion: (() => void) | undefined;
- const deletion = new Promise<void>((resolve) => {
- resolveDeletion = resolve;
- });
- const deleteImages = vi.fn(() => deletion);
- await renderMenu(createActions(deleteImages), [image('first.png'), image('second.png')]);
-
- await interact(() => getMenuItem('Delete Selection').click());
-
- expect(document.body.textContent).toContain('Delete 2 images?');
- expect(document.body.textContent).toContain('This permanently deletes these images');
-
- await interact(() => getButton('Delete').click());
-
- const cancelButton = getButton('Cancel');
- const confirmButton = getButton('Delete');
- const closeButton = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]');
- expect(deleteImages).toHaveBeenCalledOnce();
- expect(deleteImages).toHaveBeenCalledWith([
- { kind: 'image', name: 'first.png' },
- { kind: 'image', name: 'second.png' },
- ]);
- expect(cancelButton.disabled).toBe(true);
- expect(confirmButton.disabled).toBe(true);
- expect(closeButton?.disabled).toBe(true);
-
- await interact(() => {
- confirmButton.click();
- cancelButton.click();
- closeButton?.click();
- document.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' }));
- document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="backdrop"]')?.click();
- });
-
- expect(deleteImages).toHaveBeenCalledOnce();
- expect(getOpenAlertDialog()).not.toBeNull();
-
- await interact(() => resolveDeletion?.());
-
+ expect(deleteItems).toHaveBeenCalledExactlyOnceWith([{ kind: 'image', name: 'single.png' }]);
expect(getOpenAlertDialog()).toBeNull();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 9ecb548a47..5d3d5b3cb6 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -10,8 +10,7 @@ import {
legacyGeneratedImageToGalleryItem,
toGalleryItemKey,
} from '@features/gallery';
-import { ConfirmDialog, MenuContent, Tooltip } from '@platform/ui';
-import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
+import { MenuContent, Tooltip } from '@platform/ui';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
import { useWorkbenchCommands } from '@workbench/WorkbenchContext';
import {
@@ -169,8 +168,6 @@ export const ImageContextMenu = ({
target: ImageContextMenuTarget | null;
onClose: () => void;
}) => {
- const confirmImageDeletion = useWorkbenchPreferenceSelector((preferences) => preferences.confirmImageDeletion);
- const [pendingDeletion, setPendingDeletion] = useState<GalleryItemRef[] | null>(null);
const itemTarget = toGalleryItemContextMenuTarget(target);
const images = getImageContextMenuImages(itemTarget);
const isCompleteImageTarget = Boolean(itemTarget && images.length === itemTarget.itemRefs.length);
@@ -178,79 +175,37 @@ export const ImageContextMenu = ({
() => (itemTarget && isCompleteImageTarget ? { images, x: itemTarget.x, y: itemTarget.y } : null),
[images, isCompleteImageTarget, itemTarget]
);
- const pendingDeletionIsImageOnly = pendingDeletion?.every((item) => item.kind === 'image') ?? false;
-
- const requestDeletion = useCallback(
- (itemRefs: GalleryItemRef[]) => {
- if (confirmImageDeletion) {
- setPendingDeletion([...itemRefs]);
- } else {
- void actions.deleteItems(itemRefs);
- }
- },
- [actions, confirmImageDeletion]
- );
- const handleCancelDeletion = useCallback(() => setPendingDeletion(null), []);
- const handleConfirmDeletion = useCallback(async () => {
- if (!pendingDeletion) {
- return;
- }
-
- await actions.deleteItems(pendingDeletion);
- }, [actions, pendingDeletion]);
+ const requestDeletion = useCallback((itemRefs: GalleryItemRef[]) => void actions.deleteItems(itemRefs), [actions]);
const requestImageDeletion = useCallback(
(imageNames: string[]) => requestDeletion(imageNames.map((name) => ({ kind: 'image', name }))),
[requestDeletion]
);
- return (
- <>
- {itemTarget &&
- (imageTarget ? (
- <ImageContextMenuContent
- key={`${images[0]?.imageName ?? 'image'}:${images.length}`}
- actions={actions}
- boards={boards}
- image={images[0] ?? null}
- images={images}
- target={imageTarget}
- onClose={onClose}
- onRequestDeletion={requestImageDeletion}
- />
- ) : (
- <GalleryItemContextMenuContent
- key={`${itemTarget.itemRefs[0] ? toGalleryItemKey(itemTarget.itemRefs[0]) : 'item'}:${itemTarget.itemRefs.length}`}
- actions={actions}
- boards={boards}
- previewVideoActions={previewVideoActions}
- target={itemTarget}
- onClose={onClose}
- onRequestDeletion={requestDeletion}
- />
- ))}
- <ConfirmDialog
- body={`This permanently deletes ${
- pendingDeletion && pendingDeletion.length > 1
- ? pendingDeletionIsImageOnly
- ? 'these images'
- : 'these items'
- : pendingDeletionIsImageOnly
- ? 'the image'
- : 'the item'
- } from every board and from disk. This cannot be undone. You can disable this confirmation in Settings.`}
- confirmLabel="Delete"
- isOpen={pendingDeletion !== null}
- title={
- pendingDeletion && pendingDeletion.length > 1
- ? `Delete ${pendingDeletion.length} ${pendingDeletionIsImageOnly ? 'images' : 'items'}?`
- : pendingDeletionIsImageOnly
- ? 'Delete image?'
- : 'Delete item?'
- }
- onClose={handleCancelDeletion}
- onConfirm={handleConfirmDeletion}
- />
- </>
+ if (!itemTarget) {
+ return null;
+ }
+
+ return imageTarget ? (
+ <ImageContextMenuContent
+ key={`${images[0]?.imageName ?? 'image'}:${images.length}`}
+ actions={actions}
+ boards={boards}
+ image={images[0] ?? null}
+ images={images}
+ target={imageTarget}
+ onClose={onClose}
+ onRequestDeletion={requestImageDeletion}
+ />
+ ) : (
+ <GalleryItemContextMenuContent
+ key={`${itemTarget.itemRefs[0] ? toGalleryItemKey(itemTarget.itemRefs[0]) : 'item'}:${itemTarget.itemRefs.length}`}
+ actions={actions}
+ boards={boards}
+ previewVideoActions={previewVideoActions}
+ target={itemTarget}
+ onClose={onClose}
+ onRequestDeletion={requestDeletion}
+ />
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
index 78e1fb3c59..d930bfc8fd 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
@@ -19,3 +19,4 @@ export { executeImageRecall, getCurrentGenerateValues } from './executeImageReca
export { RecallActionButtons } from './RecallActionButtons';
export { getSelectedGalleryImage, getSelectedGalleryImageFromValues } from './selectedImage';
export { useImageActions, type ImageActions } from './useImageActions';
+export { useDeletionConfirmation, type RequestDeletionConfirmation } from './useDeletionConfirmation';
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx
new file mode 100644
index 0000000000..c384092629
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx
@@ -0,0 +1,182 @@
+import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { Ref } from 'react';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act, createRef, useImperativeHandle } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import type { RequestDeletionConfirmation } from './useDeletionConfirmation';
+
+import { useDeletionConfirmation } from './useDeletionConfirmation';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ const count = Number(values?.count ?? 0);
+ const messages: Record<string, string> = {
+ 'widgets.gallery.deleteConfirmLabel': 'Delete',
+ 'widgets.gallery.deleteImagesConfirmBody':
+ count === 1 ? 'Permanently delete the image.' : 'Permanently delete these images.',
+ 'widgets.gallery.deleteImagesConfirmTitle': count === 1 ? 'Delete image?' : `Delete ${count} images?`,
+ 'widgets.gallery.deleteItemsConfirmBody':
+ count === 1 ? 'Permanently delete the item.' : 'Permanently delete these items.',
+ 'widgets.gallery.deleteItemsConfirmTitle': count === 1 ? 'Delete item?' : `Delete ${count} items?`,
+ };
+
+ return messages[key] ?? key;
+ },
+ }),
+}));
+
+type ConfirmationHandle = { requestDeletionConfirmation: RequestDeletionConfirmation };
+
+const Probe = ({ ref }: { ref: Ref<ConfirmationHandle> }) => {
+ const { dialog, requestDeletionConfirmation } = useDeletionConfirmation();
+
+ useImperativeHandle(ref, () => ({ requestDeletionConfirmation }), [requestDeletionConfirmation]);
+
+ return dialog;
+};
+
+const imageRefs: GalleryItemRef[] = [{ kind: 'image', name: 'image.png' }];
+const mixedRefs: GalleryItemRef[] = [
+ { kind: 'image', name: 'image.png' },
+ { kind: 'video', name: 'video.mp4' },
+];
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+const confirmationRef = createRef<ConfirmationHandle>();
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderProbe = async () => {
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <Probe ref={confirmationRef} />
+ </ChakraProvider>
+ )
+ );
+};
+
+const clickButton = async (label: string) => {
+ const button = Array.from(document.querySelectorAll('button')).find((candidate) => candidate.textContent === label);
+
+ if (!button) {
+ throw new Error(`Button "${label}" did not render.`);
+ }
+
+ await act(async () => {
+ button.click();
+ await Promise.resolve();
+ });
+};
+
+beforeEach(async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await renderProbe();
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('useDeletionConfirmation', () => {
+ it('waits for confirmation and keeps the dialog pending through deletion', async () => {
+ let resolveDeletion!: () => void;
+ const executeDeletion = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveDeletion = resolve;
+ })
+ );
+ let request!: Promise<void>;
+
+ await act(() => {
+ request = confirmationRef.current!.requestDeletionConfirmation(imageRefs, executeDeletion);
+ });
+
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')?.textContent).toContain('Delete image?');
+ expect(executeDeletion).not.toHaveBeenCalled();
+
+ await clickButton('Delete');
+ expect(executeDeletion).toHaveBeenCalledOnce();
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')).not.toBeNull();
+
+ await act(async () => {
+ resolveDeletion();
+ await request;
+ });
+
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')).toBeNull();
+ });
+
+ it('cancels without executing deletion', async () => {
+ const executeDeletion = vi.fn(async () => {});
+ let request!: Promise<void>;
+
+ await act(() => {
+ request = confirmationRef.current!.requestDeletionConfirmation(mixedRefs, executeDeletion);
+ });
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')?.textContent).toContain('Delete 2 items?');
+
+ await clickButton('Cancel');
+ await request;
+
+ expect(executeDeletion).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')).toBeNull();
+ });
+
+ it('treats Escape as cancellation without executing deletion', async () => {
+ const executeDeletion = vi.fn(async () => {});
+ let request!: Promise<void>;
+
+ await act(() => {
+ request = confirmationRef.current!.requestDeletionConfirmation(imageRefs, executeDeletion);
+ });
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"][data-state="open"]')).not.toBeNull());
+ await act(() => userEvent.keyboard('{Escape}'));
+ await vi.waitFor(() => expect(document.querySelector('[role="alertdialog"][data-state="open"]')).toBeNull());
+ await request;
+
+ expect(executeDeletion).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')).toBeNull();
+ });
+
+ it('ignores a second request while confirmation is pending', async () => {
+ const firstDeletion = vi.fn(async () => {});
+ const secondDeletion = vi.fn(async () => {});
+
+ await act(() => {
+ void confirmationRef.current!.requestDeletionConfirmation(imageRefs, firstDeletion);
+ void confirmationRef.current!.requestDeletionConfirmation(mixedRefs, secondDeletion);
+ });
+
+ expect(document.querySelector('[role="alertdialog"][data-state="open"]')?.textContent).toContain('Delete image?');
+ await clickButton('Delete');
+
+ expect(firstDeletion).toHaveBeenCalledOnce();
+ expect(secondDeletion).not.toHaveBeenCalled();
+ });
+
+ it('settles a pending request safely when the host unmounts', async () => {
+ const executeDeletion = vi.fn(async () => {});
+ let request!: Promise<void>;
+
+ await act(() => {
+ request = confirmationRef.current!.requestDeletionConfirmation(imageRefs, executeDeletion);
+ });
+ await act(() => root?.unmount());
+ await request;
+
+ expect(executeDeletion).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx
new file mode 100644
index 0000000000..70bea56467
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx
@@ -0,0 +1,96 @@
+import type { GalleryItemRef } from '@features/gallery/contracts';
+import type { ReactNode } from 'react';
+
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
+import { useCallback, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+export type RequestDeletionConfirmation = (
+ itemRefs: readonly GalleryItemRef[],
+ executeDeletion: () => Promise<void>
+) => Promise<void>;
+
+interface PendingDeletion {
+ executeDeletion: () => Promise<void>;
+ itemRefs: readonly GalleryItemRef[];
+ resolve: () => void;
+}
+
+export const useDeletionConfirmation = (): {
+ dialog: ReactNode;
+ requestDeletionConfirmation: RequestDeletionConfirmation;
+} => {
+ const { t } = useTranslation();
+ const [pendingDeletion, setPendingDeletion] = useState<PendingDeletion | null>(null);
+ const pendingDeletionRef = useRef<PendingDeletion | null>(null);
+ const deletionInFlightRef = useRef(false);
+
+ const settlePendingDeletion = useCallback(() => {
+ const pending = pendingDeletionRef.current;
+
+ if (!pending) {
+ return;
+ }
+
+ pendingDeletionRef.current = null;
+ deletionInFlightRef.current = false;
+ setPendingDeletion(null);
+ pending.resolve();
+ }, []);
+
+ const requestDeletionConfirmation = useCallback<RequestDeletionConfirmation>((itemRefs, executeDeletion) => {
+ if (pendingDeletionRef.current) {
+ return Promise.resolve();
+ }
+
+ return new Promise<void>((resolve) => {
+ const pending = { executeDeletion, itemRefs: [...itemRefs], resolve };
+
+ pendingDeletionRef.current = pending;
+ setPendingDeletion(pending);
+ });
+ }, []);
+
+ const handleConfirm = useCallback(async () => {
+ const pending = pendingDeletionRef.current;
+
+ if (!pending || deletionInFlightRef.current) {
+ return;
+ }
+
+ deletionInFlightRef.current = true;
+
+ try {
+ await pending.executeDeletion();
+ } finally {
+ if (pendingDeletionRef.current === pending) {
+ pendingDeletionRef.current = null;
+ deletionInFlightRef.current = false;
+ setPendingDeletion(null);
+ pending.resolve();
+ }
+ }
+ }, []);
+
+ useMountEffect(() => settlePendingDeletion);
+
+ const itemCount = pendingDeletion?.itemRefs.length ?? 0;
+ const isImageOnly = pendingDeletion?.itemRefs.every((item) => item.kind === 'image') ?? false;
+ const titleKey = isImageOnly ? 'widgets.gallery.deleteImagesConfirmTitle' : 'widgets.gallery.deleteItemsConfirmTitle';
+ const bodyKey = isImageOnly ? 'widgets.gallery.deleteImagesConfirmBody' : 'widgets.gallery.deleteItemsConfirmBody';
+
+ return {
+ dialog: (
+ <ConfirmDialog
+ body={t(bodyKey, { count: itemCount })}
+ confirmLabel={t('widgets.gallery.deleteConfirmLabel')}
+ isOpen={pendingDeletion !== null}
+ title={t(titleKey, { count: itemCount })}
+ onClose={settlePendingDeletion}
+ onConfirm={handleConfirm}
+ />
+ ),
+ requestDeletionConfirmation,
+ };
+};
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 4242d2de9c..e7904a2d20 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
@@ -30,9 +30,11 @@ const mocks = vi.hoisted(() => ({
patchGalleryItemCaches: vi.fn((..._args: unknown[]) => vi.fn()),
removeFromBoard: vi.fn(),
reportError: vi.fn(),
+ requestDeletionConfirmation: vi.fn(),
resolveItem: vi.fn(),
setStarred: vi.fn(),
}));
+const preferences = vi.hoisted(() => ({ confirmImageDeletion: false }));
vi.mock('@features/gallery', () => ({
galleryImages: { metadata: (...args: unknown[]) => mocks.imageMetadata(...args) },
@@ -84,6 +86,10 @@ vi.mock('@workbench/useOpenWorkbenchWidget', () => ({
useOpenWorkbenchWidget: () => mocks.openWorkbenchWidget,
}));
+vi.mock('@workbench/settings/store', () => ({
+ useWorkbenchPreferenceSelector: (selector: (value: typeof preferences) => boolean) => selector(preferences),
+}));
+
vi.mock('@platform/browser/downloadBlob', () => ({
downloadBlob: (...args: unknown[]) => mocks.downloadBlob(...args),
}));
@@ -119,7 +125,18 @@ vi.mock('@workbench/WorkbenchContext', () => ({
}));
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) => {
+ if (key === 'widgets.gallery.uncategorized') {
+ return 'Uncategorized';
+ }
+ if (key === 'widgets.gallery.itemActions.move.success') {
+ return `Moved to ${String(values?.board)}`;
+ }
+
+ return key;
+ },
+ }),
}));
let host: HTMLDivElement | null = null;
@@ -136,10 +153,21 @@ let currentItemActionContext: ItemActionContext | null = null;
const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<ImageActions> }) => {
const actions = useImageActions({
- boards: [],
+ boards: [
+ {
+ archived: false,
+ assetCount: 0,
+ id: 'none',
+ imageCount: 0,
+ kind: 'uncategorized',
+ name: '',
+ videoCount: 0,
+ },
+ ],
generateValues: { modelKey },
getItemActionContext: () => currentItemActionContext,
projectId: 'project-1',
+ requestDeletionConfirmation: mocks.requestDeletionConfirmation,
});
useImperativeHandle(ref, () => actions, [actions]);
@@ -149,6 +177,10 @@ const Probe = ({ modelKey = 'sd-1-model', ref }: { modelKey?: string; ref: Ref<I
beforeEach(async () => {
vi.clearAllMocks();
+ preferences.confirmImageDeletion = false;
+ mocks.requestDeletionConfirmation.mockImplementation(
+ (_itemRefs: readonly GalleryItemRef[], executeDeletion: () => Promise<void>) => executeDeletion()
+ );
mocks.invalidateGallery.mockResolvedValue(undefined);
accountLifecycle.activate('user-a');
currentItemActionContext = null;
@@ -312,6 +344,63 @@ type ExpectedItemActions = {
const getItemActions = (): ExpectedItemActions => actionsRef.current as unknown as ExpectedItemActions;
describe('mixed item mutation outcomes', () => {
+ it('gates deletion through confirmation when the preference is enabled', async () => {
+ const refs = [{ kind: 'image' as const, name: 'image.png' }];
+ const result = { affectedBoardIds: ['none'], failed: [], succeeded: refs };
+ let executeDeletion: (() => Promise<void>) | null = null;
+ preferences.confirmImageDeletion = true;
+ mocks.requestDeletionConfirmation.mockImplementation((_itemRefs, execute) => {
+ executeDeletion = execute;
+ return Promise.resolve();
+ });
+ mocks.itemDelete.mockResolvedValue(result);
+
+ await act(() => {
+ root?.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <Probe ref={actionsRef} />
+ </QueryClientProvider>
+ );
+ });
+ await act(async () => {
+ await getItemActions().deleteItems(refs);
+ });
+
+ expect(mocks.requestDeletionConfirmation).toHaveBeenCalledWith(refs, expect.any(Function));
+ expect(mocks.itemDelete).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await executeDeletion?.();
+ });
+ expect(mocks.itemDelete).toHaveBeenCalledWith(refs, expect.any(AbortSignal));
+ });
+
+ it('deletes immediately without opening confirmation when the preference is disabled', async () => {
+ const refs = [{ kind: 'image' as const, name: 'image.png' }];
+ mocks.itemDelete.mockResolvedValue({ affectedBoardIds: ['none'], failed: [], succeeded: refs });
+
+ await act(async () => {
+ await getItemActions().deleteItems(refs);
+ });
+
+ expect(mocks.requestDeletionConfirmation).not.toHaveBeenCalled();
+ expect(mocks.itemDelete).toHaveBeenCalledWith(refs, expect.any(AbortSignal));
+ });
+
+ it('uses the localized Uncategorized label in move notifications', async () => {
+ const refs = [{ kind: 'image' as const, name: 'image.png' }];
+ mocks.itemMoveToBoard.mockResolvedValue({ affectedBoardIds: ['none'], failed: [], succeeded: refs });
+
+ await act(async () => {
+ await getItemActions().moveItemsToBoard(refs, 'none');
+ });
+
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith({
+ kind: 'success',
+ title: 'Moved to Uncategorized',
+ });
+ });
+
it('moves mixed refs through the common organization result and patches only confirmed qualified keys', async () => {
const refs = [
{ kind: 'image' as const, name: 'shared' },
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 663e774e95..d82326348b 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -15,6 +15,7 @@ import {
type GalleryItemMutationResult,
type GalleryItemRef,
} from '@features/gallery';
+import { getGalleryBoardLabel } from '@features/gallery/contracts';
import { invalidateGallery, patchGalleryItemCaches } from '@features/gallery/queries';
import { setPendingPromptTemplateDraft } from '@features/generation/react';
import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';
@@ -33,12 +34,15 @@ import {
importGalleryImagesToCanvas,
type GalleryCanvasImportDestination,
} from '@workbench/canvas-operations/api';
+import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import type { RequestDeletionConfirmation } from './useDeletionConfirmation';
+
import { appendReferenceImage } from './appendReferenceImage';
import { recordCanvasImportError } from './canvasImportError';
import { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';
@@ -103,6 +107,7 @@ export const useImageActions = ({
getItemActionContext,
onImagesDeleted,
projectId,
+ requestDeletionConfirmation,
}: {
boards: GalleryBoard[];
generateValues: Record<string, unknown>;
@@ -110,6 +115,7 @@ export const useImageActions = ({
projectId?: string;
/** Called after a successful deletion so the host can select a neighboring image. */
onImagesDeleted?: (imageNames: string[]) => void;
+ requestDeletionConfirmation: RequestDeletionConfirmation;
}): ImageActions => {
const openWorkbenchWidget = useOpenWorkbenchWidget();
const commands = useWorkbenchCommands();
@@ -117,6 +123,7 @@ export const useImageActions = ({
const queries = useWorkbenchQueries();
const queryClient = useQueryClient();
const { t } = useTranslation();
+ const confirmImageDeletion = useWorkbenchPreferenceSelector((preferences) => preferences.confirmImageDeletion);
const models = useModelsSelector((snapshot) => snapshot.models);
const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);
const vaeModels = useMemo(() => models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig), [models]);
@@ -137,8 +144,11 @@ export const useImageActions = ({
projectId,
});
const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });
- const getBoardName = (boardId: string) =>
- boards.find((board) => board.id === boardId)?.name ?? t('widgets.gallery.uncategorized');
+ const getBoardName = (boardId: string) => {
+ const board = boards.find((board) => board.id === boardId);
+
+ return board ? getGalleryBoardLabel(board, t) : t('widgets.gallery.uncategorized');
+ };
const getLatestGenerateValues = () => {
const snapshot = queries.getSnapshot();
const project = projectId
@@ -221,7 +231,7 @@ export const useImageActions = ({
reportMutationOutcome(action, requested.length, result, boardId);
};
- const deleteItems = (items: GalleryItemRef[]): Promise<void> => {
+ const deleteItemsConfirmed = (items: GalleryItemRef[]): Promise<void> => {
let deletionContext: GalleryItemActionContext | null = null;
let orderedRefs: GalleryItemRef[] | null = null;
const isDeletionContextCurrent = (): boolean => {
@@ -336,6 +346,10 @@ export const useImageActions = ({
requested: items,
});
};
+ const deleteItems = (items: GalleryItemRef[]): Promise<void> =>
+ confirmImageDeletion
+ ? requestDeletionConfirmation(items, () => deleteItemsConfirmed(items))
+ : deleteItemsConfirmed(items);
const moveItemsToBoard = (items: GalleryItemRef[], boardId: string): Promise<void> =>
runItemMutation({
action: 'move',
@@ -675,6 +689,7 @@ export const useImageActions = ({
};
}, [
boards,
+ confirmImageDeletion,
currentGenerateValues,
commands,
gallery,
@@ -688,6 +703,7 @@ export const useImageActions = ({
projectId,
queryClient,
queries,
+ requestDeletionConfirmation,
supportedModels,
t,
vaeModels,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
index 1136e048fc..b62dee92e2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
@@ -189,6 +189,10 @@ vi.mock('@workbench/image-actions', () => ({
getImageRecallTitle: () => '',
getSelectedGalleryImage: () => null,
getSelectedGalleryImageFromValues: () => null,
+ useDeletionConfirmation: () => ({
+ dialog: null,
+ requestDeletionConfirmation: (_itemRefs: unknown, executeDeletion: () => Promise<void>) => executeDeletion(),
+ }),
useImageActions: (options: typeof mocks.imageActionOptions) => {
mocks.imageActionOptions = options;
return {};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 43ad98500e..00c8fc410c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -57,6 +57,7 @@ import { useStreamingImageSource } from '@platform/ui/streaming-image/useStreami
import { useInfiniteQuery, useQuery, type InfiniteData } from '@tanstack/react-query';
import {
ImageContextMenu,
+ useDeletionConfirmation,
useImageActions,
type ImageActions,
type ImageContextMenuTarget,
@@ -124,7 +125,7 @@ const fallbackBoards: GalleryBoard[] = [
id: 'none',
imageCount: 0,
kind: 'uncategorized',
- name: 'Uncategorized',
+ name: '',
videoCount: 0,
},
];
@@ -603,11 +604,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
[boardItems, navigationQueryKey, selectedItemKey]
);
const projectId = useActiveProjectId();
+ const { dialog: deletionConfirmationDialog, requestDeletionConfirmation } = useDeletionConfirmation();
const imageActions = useImageActions({
boards,
generateValues,
getItemActionContext,
projectId,
+ requestDeletionConfirmation,
});
const contextMenuItem = useMemo<GalleryItem | null>(() => {
if (!selectedItem) {
@@ -941,6 +944,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
target={contextMenuTarget}
onClose={closeContextMenu}
/>
+ {deletionConfirmationDialog}
</>
) : (
<EmptyPreview />