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): add mixed-media gallery actions

joshistoasta1ec2acbcb8a
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-7b-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-7b-report.md
new file mode 100644
index 0000000000..df593a970d
--- /dev/null
+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-7b-report.md
@@ -0,0 +1,309 @@
+# Task 7B Report: Mixed-media gallery actions and downloads
+
+## Status
+
+Complete.
+
+Task 7B consumes the reviewed Task 7A `galleryItemOrganization` result and
+finishes Task 7's App/action/UI integration. Gallery now receives an honest
+common `GalleryItemActions` port, while App-owned `ImageActions` retains the
+strict `GalleryImage` operations. Mixed image/video selections can be moved,
+starred, deleted, and downloaded without narrowing or unqualified-name
+collisions.
+
+Confirmed mutation results are applied once at the operation boundary: only
+`result.succeeded` patches caches and Workbench state, one all-gallery
+invalidation follows the confirmed patch, and one success/partial/failure
+notification is emitted.
+
+## TDD evidence
+
+All frontend commands ran from `invokeai/frontend/webv2`.
+
+### Common action port and confirmed mutations
+
+The first focused RED was:
+
+```sh
+pnpm test:browser src/workbench/image-actions/useImageActions.browser.test.tsx
+```
+
+```text
+Test Files 1 failed (1)
+Tests 6 failed | 2 passed (8)
+```
+
+The failures covered the then-missing common delete/download/move/star methods,
+confirmed-only patching, same-name image/video identity, mixed download order,
+continuation, and operation-level invalidation/notification. The first common
+action implementation made the file green with 8 tests.
+
+The lazy App bridge then captured RED for the canonical mixed target and real
+mixed board move:
+
+```text
+Test Files 1 failed (1)
+Tests 2 failed (2)
+```
+
+After removing the unsafe cast and image-only move bridge, it passed with 2
+tests. A later live-successor-context regression failed 1 of 3 tests before
+the getter was forwarded. The honest item-named provider/export cleanup was
+also test-first: all 3 bridge tests failed against the missing item-aware
+symbols, then all 3 passed.
+
+### Context menus and keyboard actions
+
+The context-menu regression run was:
+
+```sh
+pnpm test:browser src/workbench/image-actions/ImageContextMenu.browser.test.tsx
+```
+
+```text
+Test Files 1 failed (1)
+Tests 2 failed | 4 passed (6)
+```
+
+It showed that single-video and mixed selections had no common menu. The green
+run passed all 6 tests with image-only actions hidden for video,
+mixed-media, and unresolved selections.
+
+The grid/hotkey regression run was:
+
+```sh
+pnpm test:browser src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+```
+
+```text
+Test Files 1 failed (1)
+Tests 2 failed | 12 passed (14)
+```
+
+It showed that mixed hotkeys were rejected and videos had no star affordance.
+The green run passed all 14 tests with qualified refs, the required
+inside/outside right-click semantics, unloaded selection preservation, and
+same-name media isolation.
+
+### Delete successor guards
+
+Adding ordered predecessor/successor, unloaded resolution, failed-ref, and
+stale filter/selection cases produced:
+
+```text
+Test Files 1 failed (1)
+Tests 5 failed | 8 passed (13)
+```
+
+All 13 passed after the ordered-names implementation. Two additional
+regressions were captured and fixed independently:
+
+- a captured names list without the deleted primary attempted to promote an
+ unrelated item;
+- an account rotation while `galleryItems.resolve(ref)` was pending still
+ applied confirmed deletion side effects.
+
+The stale-account test failed 1 of 18 tests before the post-resolution abort
+guard and then passed all 18.
+
+### Downloads and board archive wording
+
+The board preparation-toast regression failed 1 of 3
+`useGalleryActions.browser.test.tsx` tests against the old generic archive
+message. The new board-menu regression failed its only test against
+`Download Board`. Both passed after the exact `board.videoCount` omission
+wording was added without a fetch.
+
+Download regressions cover:
+
+- one existing archive for an image-only selection;
+- a protected single-video `fullUrl` download using the actual name;
+- image archive first, then sequential videos for a mixed selection;
+- continuation after rejected or unresolved videos;
+- one partial/skipped summary.
+
+### Final focused GREEN
+
+```sh
+pnpm test \
+ src/features/gallery/ui/GalleryBoardSelect.test.ts \
+ src/workbench/image-actions/ImageContextMenu.test.ts \
+ src/features/gallery/ui/GalleryWidgetView.test.ts \
+ src/features/gallery/ui/useGalleryData.test.ts \
+ src/features/gallery/data/queryCache.test.ts \
+ src/workbench/workbenchState.test.ts
+```
+
+```text
+Test Files 6 passed (6)
+Tests 183 passed (183)
+```
+
+```sh
+pnpm test:browser \
+ src/app/GalleryImageActionsBridge.browser.test.tsx \
+ src/workbench/image-actions/useImageActions.browser.test.tsx \
+ src/workbench/image-actions/ImageContextMenu.browser.test.tsx \
+ src/features/gallery/ui/GalleryImageGrid.browser.test.tsx \
+ src/features/gallery/ui/useGalleryActions.browser.test.tsx \
+ src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
+```
+
+```text
+Test Files 6 passed (6)
+Tests 45 passed (45)
+```
+
+## Implementation
+
+### Honest common and image-only ports
+
+- `GalleryItemActions` accepts ordered qualified refs and canonical loaded
+ items for delete, download, move, preview/new-tab, and star operations.
+- Gallery's provider, hook, widget context, and adapter field are item-named
+ and expose only that common surface.
+- App `ImageActions` extends the common port and keeps canvas, reference,
+ compare, clipboard, prompt-template, and metadata-recall inputs strictly
+ `GalleryImage`.
+- The lazy App bridge keeps the full `ImageActions` only in an App-local
+ context for the image-capable context menu. The retained
+ `as unknown as ImageActions` cast and all-image mixed-board bridge are gone.
+
+### Confirmed operation boundary
+
+- Delete, move, star, and unstar call the Task 7A
+ `galleryItemOrganization` methods directly.
+- Cache and Workbench changes use only `result.succeeded` qualified keys;
+ `result.failed` remains materialized and selected.
+- Every completed operation attempts exactly one `invalidateGallery` after
+ confirmed patches and emits one localized success, partial, or failure
+ notification.
+- Account ownership is checked before patches, after async successor
+ resolution, before invalidation, and before notification.
+
+### Primary selection after deletion
+
+- The current filter and selection plus materialized items are captured before
+ transport.
+- The ordered names query is captured before deletion and searched for the
+ nearest surviving predecessor, then successor.
+- Every confirmed deletion and failed deletion is ineligible for promotion.
+- An unloaded candidate resolves through `galleryItems.resolve(ref, signal)`.
+- Failed names lookup falls back to materialized order.
+- Account, filter, and selection currency are rechecked before selecting an
+ asynchronously resolved candidate.
+
+### UI actions
+
+- Board drops forward the complete ordered image/video/mixed ref payload.
+- Keyboard delete/star uses common refs, including unloaded selected refs.
+- Right-click outside a selection targets one item; right-click inside a
+ multi-selection keeps its complete ordered qualified selection.
+- Single-video and mixed/unresolved menus show only supported common actions.
+ Fully resolved image-only targets retain the existing strict image menu.
+- Video thumbnails now expose the shared star affordance. Compare and every
+ other image-only path remain image-gated.
+
+### Downloads and archives
+
+- Single video uses its protected `fullUrl` and actual file name.
+- Image selections reuse the existing single archive transport.
+- Mixed selection downloads the image archive first, then video files
+ sequentially in video-selection order.
+- Rejected or unresolved videos do not prevent later videos from downloading;
+ the operation emits one summary.
+- Board archive remains image-only. Its menu label and preparation toast state
+ the exact omitted video count from the already-loaded board; no count fetch
+ was added.
+
+## Full verification
+
+```sh
+pnpm lint:tsc
+```
+
+```text
+tsc --noEmit: passed
+```
+
+```sh
+pnpm test
+```
+
+```text
+Test Files 376 passed (376)
+Tests 4973 passed (4973)
+```
+
+```sh
+pnpm test:browser
+```
+
+```text
+Test Files 64 passed (64)
+Tests 290 passed (290)
+```
+
+The browser suite emitted its existing React `act(...)`,
+missing-i18n-instance, and intentional error-boundary diagnostics and exited
+successfully.
+
+```sh
+pnpm test:fixtures
+```
+
+```text
+Tests 4 passed (4)
+```
+
+```sh
+pnpm architecture:check
+```
+
+```text
+Test Files 3 passed (3)
+Tests 34 passed (34)
+```
+
+```sh
+pnpm lint
+```
+
+```text
+format: all matched files correctly formatted
+oxlint: zero warnings/errors
+tsc --noEmit: passed
+architecture: 3 files passed, 34 tests passed
+```
+
+## Self-review
+
+- Confirmed no production module or production file rename was added; the one
+ new source-tree file is a browser test.
+- Confirmed no `useEffect`, platform UI barrel importer, migration exception,
+ or performance baseline was added.
+- Confirmed `GeneratedImageContract` and the strict image-only action inputs
+ remain unchanged.
+- Confirmed there is no mixed-to-image cast in the lazy bridge.
+- Confirmed every mutation carries qualified identity end to end and only
+ confirmed successes can patch or prune state.
+- Confirmed one operation cannot issue per-partition invalidations or
+ notifications.
+- Confirmed `git diff --check` is clean.
+
+## Retained Task 8–10 seams
+
+- Task 8 retains native video rendering/controls in Preview. Task 7B opens the
+ selected video item and leaves the current image-only preview renderer
+ unchanged.
+- Task 9 retains preview-only copy-current-frame and video Details/metadata.
+ Video and mixed gallery menus deliberately hide the existing image clipboard
+ and metadata-recall actions.
+- Task 10 retains video upload, mock-backend fixture, broad accessibility, and
+ full gallery translation follow-through. Task 7B neither widens the current
+ image upload accept list nor changes mock fixtures or accessibility
+ exceptions.
+
+## Concerns
+
+None.
diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx
index c75d0968bf..1f28ce84f9 100644
--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.browser.test.tsx
@@ -1,30 +1,52 @@
/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-object-as-prop */
import type { GalleryImageItem, GalleryItemRef } from '@features/gallery/contracts';
-import type { GalleryImageActions, GalleryItemContextMenuTarget } from '@features/gallery/react';
+import type { GalleryItemActions, GalleryItemContextMenuTarget } from '@features/gallery/react';
import type { ReactNode, Ref } from 'react';
-import { useGalleryImageActions } from '@features/gallery/ui/GalleryUiContext';
+import { useGalleryItemActions } from '@features/gallery/ui/GalleryUiContext';
import { act, createRef, useImperativeHandle } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { GalleryImageActionsAdapter, GalleryImageContextMenu } from './GalleryImageActionsBridge';
+import { GalleryImageContextMenu, GalleryItemActionsAdapter } from './GalleryImageActionsBridge';
const mocks = vi.hoisted(() => ({
- moveImagesToBoard: vi.fn(),
+ moveItemsToBoard: vi.fn(),
+ useImageActions: vi.fn(),
}));
vi.mock('@workbench/image-actions', () => ({
- ImageContextMenu: ({ target }: { target: { images: Array<{ imageName: string }> } | null }) => (
+ ImageContextMenu: ({
+ target,
+ }: {
+ target: { itemRefs: GalleryItemRef[]; items: Array<{ kind: string; name: string }> } | null;
+ }) => (
<output data-testid="image-context-target">
- {JSON.stringify(target?.images.map((image) => image.imageName) ?? null)}
+ {JSON.stringify(
+ target
+ ? {
+ itemRefs: target.itemRefs,
+ items: target.items.map(({ kind, name }) => ({ kind, name })),
+ }
+ : null
+ )}
</output>
),
- useImageActions: () => ({
- deleteImages: vi.fn(),
- moveImagesToBoard: mocks.moveImagesToBoard,
- setImagesStarred: vi.fn(),
- }),
+ useImageActions: (options: unknown) => {
+ mocks.useImageActions(options);
+ return {
+ deleteItems: vi.fn(),
+ deleteImages: vi.fn(),
+ downloadItem: vi.fn(),
+ downloadItems: vi.fn(),
+ moveImagesToBoard: vi.fn(),
+ moveItemsToBoard: mocks.moveItemsToBoard,
+ openItemInNewTab: vi.fn(),
+ openItemInPreview: vi.fn(),
+ setItemsStarred: vi.fn(),
+ setImagesStarred: vi.fn(),
+ };
+ },
}));
const loadedImage: GalleryImageItem = {
@@ -45,20 +67,14 @@ const mixedRefs: GalleryItemRef[] = [
{ kind: 'video', name: 'unloaded.mp4' },
];
const noop = vi.fn();
-const directActions: GalleryImageActions = {
- deleteImages: vi.fn(),
- moveImagesToBoard: mocks.moveImagesToBoard,
- moveItemsToBoard: vi.fn(),
- setImagesStarred: vi.fn(),
-};
let host: HTMLDivElement | null = null;
let root: Root | null = null;
-const actionsRef = createRef<GalleryImageActions>();
+const actionsRef = createRef<GalleryItemActions>();
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const ActionsProbe = ({ ref }: { ref: Ref<GalleryImageActions> }) => {
- const actions = useGalleryImageActions();
+const ActionsProbe = ({ ref }: { ref: Ref<GalleryItemActions> }) => {
+ const actions = useGalleryItemActions();
useImperativeHandle(ref, () => actions, [actions]);
return null;
};
@@ -86,7 +102,7 @@ afterEach(async () => {
});
describe('GalleryImageActionsBridge mixed selection boundaries', () => {
- it('does not expose a partial image context target when an unloaded video ref is selected', async () => {
+ it('forwards the complete canonical context target without narrowing a mixed selection', async () => {
const target: GalleryItemContextMenuTarget = {
itemRefs: mixedRefs,
items: [loadedImage],
@@ -94,22 +110,52 @@ describe('GalleryImageActionsBridge mixed selection boundaries', () => {
y: 40,
};
- await render(<GalleryImageContextMenu actions={directActions} boards={[]} target={target} onClose={noop} />);
+ await render(
+ <GalleryItemActionsAdapter boards={[]} generateValues={{}} projectId="project-1">
+ <GalleryImageContextMenu boards={[]} target={target} onClose={noop} />
+ </GalleryItemActionsAdapter>
+ );
- expect(host?.querySelector('[data-testid="image-context-target"]')?.textContent).toBe('null');
+ expect(host?.querySelector('[data-testid="image-context-target"]')?.textContent).toBe(
+ JSON.stringify({
+ itemRefs: mixedRefs,
+ items: [{ kind: 'image', name: loadedImage.name }],
+ })
+ );
});
- it('does not move the loaded image subset of an image plus unloaded-video ref vector', async () => {
+ it('forwards an ordered mixed board move through the common action port', async () => {
await render(
- <GalleryImageActionsAdapter boards={[]} generateValues={{}} projectId="project-1" onImagesDeleted={noop}>
+ <GalleryItemActionsAdapter boards={[]} generateValues={{}} projectId="project-1">
<ActionsProbe ref={actionsRef} />
- </GalleryImageActionsAdapter>
+ </GalleryItemActionsAdapter>
);
await act(async () => {
await actionsRef.current?.moveItemsToBoard(mixedRefs, 'board-b');
});
- expect(mocks.moveImagesToBoard).not.toHaveBeenCalled();
+ expect(mocks.moveItemsToBoard).toHaveBeenCalledWith(mixedRefs, 'board-b');
+ });
+
+ it('forwards the live gallery action context getter used by guarded delete successor selection', async () => {
+ const getItemActionContext = vi.fn(() => null);
+
+ await render(
+ <GalleryItemActionsAdapter
+ boards={[]}
+ generateValues={{}}
+ getItemActionContext={getItemActionContext}
+ projectId="project-1"
+ >
+ <ActionsProbe ref={actionsRef} />
+ </GalleryItemActionsAdapter>
+ );
+
+ expect(mocks.useImageActions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ getItemActionContext,
+ })
+ );
});
});
diff --git a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
index 7c65ac0100..88707a26d7 100644
--- a/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryImageActionsBridge.tsx
@@ -1,84 +1,37 @@
-import type {
- GalleryImageActions,
- GalleryImageActionsOptions,
- GalleryItemContextMenuProps,
-} from '@features/gallery/react';
+import type { GalleryItemActionsOptions, GalleryItemContextMenuProps } from '@features/gallery/react';
import type { ReactNode } from 'react';
-import { galleryImageItemToGalleryImage, isGalleryImageItem, toGalleryItemKey } from '@features/gallery/contracts';
-import { GalleryImageActionsProvider } from '@features/gallery/react';
-import { getGalleryItemDragData, isGalleryImageDragData } from '@features/gallery/utility';
+import { GalleryItemActionsProvider } from '@features/gallery/react';
import { ImageContextMenu, useImageActions, type ImageActions } from '@workbench/image-actions';
-import { useMemo } from 'react';
+import { createContext, use } from 'react';
-const GalleryImageContextMenuComponent = ({ actions, boards, onClose, target }: GalleryItemContextMenuProps) => {
- // TODO(Task 7): The current App action menu is image-only. Keep its input
- // strict until the canonical mixed-media context menu/actions port lands.
- const imageTarget = useMemo(() => {
- if (!target || target.itemRefs.length === 0 || target.itemRefs.some((ref) => ref.kind !== 'image')) {
- return null;
- }
+const GalleryAppActionsContext = createContext<ImageActions | null>(null);
- const loadedItemsByKey = new Map(target.items.map((item) => [toGalleryItemKey(item), item]));
- const imageItems = target.itemRefs.flatMap((ref) => {
- const item = loadedItemsByKey.get(toGalleryItemKey(ref));
+const GalleryImageContextMenuComponent = ({ boards, onClose, target }: GalleryItemContextMenuProps) => {
+ const actions = use(GalleryAppActionsContext);
- return item && isGalleryImageItem(item) ? [item] : [];
- });
+ if (!actions) {
+ throw new Error('Gallery item context menus require the App-owned action adapter.');
+ }
- if (imageItems.length !== target.itemRefs.length) {
- return null;
- }
-
- return {
- images: imageItems.map(galleryImageItemToGalleryImage),
- x: target.x,
- y: target.y,
- };
- }, [target]);
-
- return (
- <ImageContextMenu
- actions={actions as unknown as ImageActions}
- boards={boards}
- target={imageTarget}
- onClose={onClose}
- />
- );
+ return <ImageContextMenu actions={actions} boards={boards} target={target} onClose={onClose} />;
};
-const GalleryImageActionsAdapterComponent = ({
+const GalleryItemActionsAdapterComponent = ({
boards,
children,
generateValues,
- onImagesDeleted,
+ getItemActionContext,
projectId,
-}: GalleryImageActionsOptions & { children: ReactNode }) => {
- const actions = useImageActions({ boards, generateValues, onImagesDeleted, projectId });
- const galleryActions = useMemo<GalleryImageActions>(
- () => ({
- ...actions,
- // TODO(Task 7): Replace with the canonical mixed-media organization
- // action. This compatibility bridge deliberately rejects video/mixed
- // refs instead of silently moving only their image subset.
- moveItemsToBoard: async (items, boardId) => {
- const dragData = getGalleryItemDragData(items);
+}: GalleryItemActionsOptions & { children: ReactNode }) => {
+ const actions = useImageActions({ boards, generateValues, getItemActionContext, projectId });
- if (!isGalleryImageDragData(dragData)) {
- return;
- }
-
- await actions.moveImagesToBoard(
- dragData.items.map((item) => item.name),
- boardId
- );
- },
- }),
- [actions]
+ return (
+ <GalleryAppActionsContext value={actions}>
+ <GalleryItemActionsProvider actions={actions}>{children}</GalleryItemActionsProvider>
+ </GalleryAppActionsContext>
);
-
- return <GalleryImageActionsProvider actions={galleryActions}>{children}</GalleryImageActionsProvider>;
};
-export const GalleryImageActionsAdapter = GalleryImageActionsAdapterComponent;
+export const GalleryItemActionsAdapter = GalleryItemActionsAdapterComponent;
export const GalleryImageContextMenu = GalleryImageContextMenuComponent;
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
index 39d4b723b9..3e73a6e54c 100644
--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
@@ -15,8 +15,8 @@ import { lazy, useMemo } from 'react';
const selectWidgetValues = (values: Record<string, unknown>): Record<string, unknown> => values;
-const GalleryImageActionsAdapter = lazy(() =>
- import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryImageActionsAdapter }))
+const GalleryItemActionsAdapter = lazy(() =>
+ import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryItemActionsAdapter }))
);
const GalleryImageContextMenu = lazy(() =>
import('./GalleryImageActionsBridge').then((module) => ({ default: module.GalleryImageContextMenu }))
@@ -45,7 +45,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })
gallery,
galleryValues,
generateValues,
- ImageActionsProvider: GalleryImageActionsAdapter,
+ ItemActionsProvider: GalleryItemActionsAdapter,
ImageContextMenu: GalleryImageContextMenu,
liveFollowEnabled,
liveProgressTarget,
diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.ts
index 6b49447ebf..c7681a9e5a 100644
--- a/invokeai/frontend/webv2/src/features/gallery/react.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts
@@ -1,8 +1,9 @@
export {
GalleryUiProvider,
- GalleryImageActionsProvider,
- type GalleryImageActions,
- type GalleryImageActionsOptions,
+ GalleryItemActionsProvider,
+ type GalleryItemActionContext,
+ type GalleryItemActions,
+ type GalleryItemActionsOptions,
type GalleryItemContextMenuProps,
type GalleryItemContextMenuTarget,
type GalleryUiAdapter,
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
new file mode 100644
index 0000000000..5056bc88bb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx
@@ -0,0 +1,77 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import type { GalleryWidgetContextValue } from './GalleryWidgetContext';
+
+import { GalleryBoardMenu } from './GalleryBoardMenu';
+import { GalleryWidgetContext } from './GalleryWidgetContext';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ (
+ ({
+ 'widgets.gallery.downloadBoard': 'Download Board',
+ }) as Record<string, string>
+ )[key] ?? key,
+ }),
+}));
+
+const board = {
+ archived: false,
+ assetCount: 0,
+ id: 'board-1',
+ imageCount: 2,
+ kind: 'board',
+ name: 'Board 1',
+ videoCount: 1,
+} as const;
+const target = { board, x: 20, y: 20 };
+const noop = vi.fn();
+const context = {
+ actions: {
+ archiveBoard: vi.fn(),
+ deleteBoard: vi.fn(),
+ downloadBoard: vi.fn(),
+ renameBoard: vi.fn(),
+ },
+ gallery: {
+ projectBoardId: null,
+ },
+} as unknown as GalleryWidgetContextValue;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeEach(async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(async () => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <GalleryWidgetContext value={context}>
+ <GalleryBoardMenu target={target} onClose={noop} />
+ </GalleryWidgetContext>
+ </ChakraProvider>
+ );
+ await Promise.resolve();
+ });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+it('states the exact number of videos omitted from the image-only board archive', () => {
+ expect(document.body.textContent).toContain('Download Board (1 video omitted)');
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
index 036948af7b..0680427da6 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx
@@ -141,7 +141,7 @@ export const GalleryBoardMenu = ({
<Menu.Positioner>
{board && (
<Menu.Content minW="12rem" py="1" px={MENU_CONTENT_PADDING_X}>
- <BoardDownloadMenuItem boardId={board.id} />
+ <BoardDownloadMenuItem board={board} />
{isManagedBoard && (
<>
<BoardRenameMenuItem board={board} onRename={setRenameTarget} onRenameValue={setRenameValue} />
@@ -232,15 +232,16 @@ export const GalleryBoardMenu = ({
);
};
-const BoardDownloadMenuItem = ({ boardId }: { boardId: string }) => {
+const BoardDownloadMenuItem = ({ board }: { board: GalleryBoard }) => {
const { t } = useTranslation();
const { actions } = useGalleryWidget();
- const handleClick = useCallback(() => void actions.downloadBoard(boardId), [actions, boardId]);
+ const handleClick = useCallback(() => void actions.downloadBoard(board.id), [actions, board.id]);
+ const omittedVideos = `${board.videoCount} ${board.videoCount === 1 ? 'video' : 'videos'} omitted`;
return (
<BoardMenuItem
icon={DownloadIcon}
- label={t('widgets.gallery.downloadBoard')}
+ label={`${t('widgets.gallery.downloadBoard')} (${omittedVideos})`}
value="download-board"
onClick={handleClick}
/>
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
index 32b93d33bf..da654c65ea 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSelect.tsx
@@ -77,7 +77,7 @@ export const forwardGalleryBoardDrop = ({
export const GalleryBoardSelect = () => {
const { t } = useTranslation();
- const { actions, gallery, imageActions, projectName } = useGalleryWidget();
+ const { actions, gallery, itemActions, projectName } = useGalleryWidget();
const { active } = useDndContext();
const [isOpen, setIsOpen] = useState(false);
const [boardSearchTerm, setBoardSearchTerm] = useState('');
@@ -127,7 +127,7 @@ export const GalleryBoardSelect = () => {
forwardGalleryBoardDrop({
activeData: dragData,
loadedItems: gallery.items,
- moveItemsToBoard: (items, boardId) => void imageActions.moveItemsToBoard(items, boardId),
+ moveItemsToBoard: (items, boardId) => void itemActions.moveItemsToBoard(items, boardId),
overData: dropData,
});
@@ -136,7 +136,7 @@ export const GalleryBoardSelect = () => {
closeAndReset();
}
},
- [closeAndReset, gallery.items, imageActions]
+ [closeAndReset, gallery.items, itemActions]
);
const handleDragCancel = useCallback(() => {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
index 380bc0bbc4..6ba93fb6e6 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx
@@ -199,9 +199,15 @@ const actionMocks = {
toggleItemInSelection: vi.fn(),
};
const imageActionMocks = {
+ deleteItems: vi.fn(),
deleteImages: vi.fn(),
+ downloadItem: vi.fn(),
+ downloadItems: vi.fn(),
moveImagesToBoard: vi.fn(),
moveItemsToBoard: vi.fn(),
+ openItemInNewTab: vi.fn(),
+ openItemInPreview: vi.fn(),
+ setItemsStarred: vi.fn(),
setImagesStarred: vi.fn(),
};
const noop = vi.fn();
@@ -262,7 +268,7 @@ const NoopProvider = ({ children }: { children: ReactNode }) => children;
const createAdapter = (): GalleryUiAdapter =>
({
- ImageActionsProvider: NoopProvider,
+ ItemActionsProvider: NoopProvider,
ImageContextMenu: ContextMenuProbe,
account: { enableLiveFollow: noop },
antialiasProgressImages: false,
@@ -321,7 +327,7 @@ const Harness = ({
const contextValue: GalleryWidgetContextValue = {
actions: createActions(),
gallery,
- imageActions: imageActionMocks,
+ itemActions: imageActionMocks,
isWindowTruncated: false,
projectName: 'Project',
runtime,
@@ -588,7 +594,7 @@ describe('GalleryImageGrid mixed item cells', () => {
);
});
- it('select-all targets ordered mixed refs while image-only hotkeys reject a mixed selection', async () => {
+ it('select-all and common hotkeys target ordered same-name mixed refs independently', async () => {
const items = [createItem('image', 'shared'), createItem('video', 'shared')];
await renderGallery(
createGallery({
@@ -609,8 +615,31 @@ describe('GalleryImageGrid mixed item cells', () => {
],
items[0]
);
- expect(imageActionMocks.deleteImages).not.toHaveBeenCalled();
- expect(imageActionMocks.setImagesStarred).not.toHaveBeenCalled();
+ expect(imageActionMocks.deleteItems).toHaveBeenCalledWith([
+ { kind: 'image', name: 'shared' },
+ { kind: 'video', name: 'shared' },
+ ]);
+ expect(imageActionMocks.setItemsStarred).toHaveBeenCalledWith(
+ [
+ { kind: 'image', name: 'shared' },
+ { kind: 'video', name: 'shared' },
+ ],
+ true
+ );
+ });
+
+ it('stars a video from its grid affordance through the common qualified action', async () => {
+ await renderGallery(
+ createGallery({
+ items: [createItem('video', 'clip.mp4')],
+ selectedItemKey: 'video:clip.mp4',
+ selectedItemKeys: ['video:clip.mp4'],
+ })
+ );
+
+ await click(getButton('Star clip.mp4'));
+
+ expect(imageActionMocks.setItemsStarred).toHaveBeenCalledWith([{ kind: 'video', name: 'clip.mp4' }], true);
});
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index fc6b0ca3bb..69ce6e0cf0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -1,4 +1,4 @@
-import type { GalleryImageItem, GalleryItem, GalleryItemRef } from '@features/gallery/core/items';
+import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';
import type { GalleryThumbnailFit } from '@features/gallery/core/settings';
import { Badge, Box, Flex, ProgressCircle, ScrollArea, Skeleton, Spinner, Text } from '@chakra-ui/react';
@@ -98,7 +98,7 @@ type GridCell =
export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {
const { t } = useTranslation();
- const { actions, gallery, imageActions, isWindowTruncated, runtime } = useGalleryWidget();
+ const { actions, gallery, isWindowTruncated, itemActions, runtime } = useGalleryWidget();
const { account, antialiasProgressImages, ImageContextMenu, widgets } = useGalleryUi();
const queryClient = useQueryClient();
const [contextMenuTarget, setContextMenuTarget] = useState<GalleryItemContextMenuTarget | null>(null);
@@ -415,30 +415,21 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
}, [account]);
const handleToggleStarred = useCallback(
- (item: GalleryImageItem) => void imageActions.setImagesStarred([item.name], !item.starred),
- [imageActions]
+ (item: GalleryItem) => void itemActions.setItemsStarred([toGalleryItemRef(item)], !item.starred),
+ [itemActions]
);
const handleCloseContextMenu = useCallback(() => setContextMenuTarget(null), []);
- // TODO(Task 7): Common item actions will consume the canonical selection.
- // Until then, reject video, mixed, or unresolved selections at the existing
- // image-only hotkey boundary.
- const imageOnlyActionSelection = useMemo<GalleryImageItem[] | null>(() => {
- const itemKeys =
- gallery.selectedItemKeys.length > 0
- ? gallery.selectedItemKeys
+ const actionSelectionRefs = useMemo(
+ () =>
+ selectedItemRefs.length > 0
+ ? selectedItemRefs
: gallery.selectedItemKey
- ? [gallery.selectedItemKey]
- : [];
- const items = itemKeys.flatMap((itemKey) => {
- const item = gallery.items.find((candidate) => toGalleryItemKey(candidate) === itemKey);
-
- return item ? [item] : [];
- });
-
- return items.length === itemKeys.length && items.every(isGalleryImageItem) ? items : null;
- }, [gallery.items, gallery.selectedItemKey, gallery.selectedItemKeys]);
+ ? [parseGalleryItemKey(gallery.selectedItemKey)]
+ : [],
+ [gallery.selectedItemKey, selectedItemRefs]
+ );
const navigate = useEffectEvent((direction: 'down' | 'left' | 'right' | 'up') => {
const itemCount = gallery.items.length;
@@ -479,18 +470,16 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
return;
}
- if (commandId === 'gallery.deleteSelection' && imageOnlyActionSelection?.length) {
- void imageActions.deleteImages(imageOnlyActionSelection.map((item) => item.name));
+ if (commandId === 'gallery.deleteSelection' && actionSelectionRefs.length > 0) {
+ void itemActions.deleteItems(actionSelectionRefs);
return;
}
- if (commandId === 'gallery.starImage' && imageOnlyActionSelection?.length) {
- const shouldStar = imageOnlyActionSelection.some((item) => !item.starred);
+ if (commandId === 'gallery.starImage' && actionSelectionRefs.length > 0) {
+ const loadedItemsByKey = new Map(gallery.items.map((item) => [toGalleryItemKey(item), item]));
+ const shouldStar = actionSelectionRefs.some((ref) => !loadedItemsByKey.get(toGalleryItemKey(ref))?.starred);
- void imageActions.setImagesStarred(
- imageOnlyActionSelection.map((item) => item.name),
- shouldStar
- );
+ void itemActions.setItemsStarred(actionSelectionRefs, shouldStar);
}
});
@@ -645,12 +634,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
</Text>
</DropZone>
)}
- <ImageContextMenu
- actions={imageActions}
- boards={gallery.boards}
- target={activeContextMenuTarget}
- onClose={handleCloseContextMenu}
- />
+ <ImageContextMenu boards={gallery.boards} target={activeContextMenuTarget} onClose={handleCloseContextMenu} />
</Box>
);
};
@@ -762,7 +746,7 @@ const GalleryThumbnail = ({
isSelected: boolean;
onClick: (item: GalleryItem, event: MouseEvent) => void;
onContextMenu: (item: GalleryItem, x: number, y: number) => void;
- onToggleStarred: (item: GalleryImageItem) => void;
+ onToggleStarred: (item: GalleryItem) => void;
}) => {
const { t } = useTranslation();
const isCompared = compareRole !== null;
@@ -803,9 +787,7 @@ const GalleryThumbnail = ({
(event: MouseEvent<HTMLButtonElement>) => {
event.stopPropagation();
- if (isGalleryImageItem(item)) {
- onToggleStarred(item);
- }
+ onToggleStarred(item);
},
[item, onToggleStarred]
);
@@ -865,28 +847,26 @@ const GalleryThumbnail = ({
{compareRole}
</Badge>
)}
- {item.kind === 'image' ? (
- <IconButton
- aria-label={
- item.starred
- ? t('widgets.gallery.unstarImage', { name: item.name })
- : t('widgets.gallery.starImage', { name: item.name })
- }
- className="gallery-thumb-overlay"
- colorPalette={item.starred ? 'yellow' : 'gray'}
- insetInlineEnd="1"
- opacity={item.starred ? 1 : 0}
- position="absolute"
- size="2xs"
- top="1"
- transition="opacity var(--wb-motion-duration-medium) ease"
- variant="solid"
- zIndex="1"
- onClick={handleToggleStarred}
- >
- <StarIcon fill={item.starred ? 'currentColor' : 'none'} />
- </IconButton>
- ) : null}
+ <IconButton
+ aria-label={
+ item.starred
+ ? t('widgets.gallery.unstarImage', { name: item.name })
+ : t('widgets.gallery.starImage', { name: item.name })
+ }
+ className="gallery-thumb-overlay"
+ colorPalette={item.starred ? 'yellow' : 'gray'}
+ insetInlineEnd="1"
+ opacity={item.starred ? 1 : 0}
+ position="absolute"
+ size="2xs"
+ top="1"
+ transition="opacity var(--wb-motion-duration-medium) ease"
+ variant="solid"
+ zIndex="1"
+ onClick={handleToggleStarred}
+ >
+ <StarIcon fill={item.starred ? 'currentColor' : 'none'} />
+ </IconButton>
{item.kind === 'image' && item.width > 0 && item.height > 0 && (
<Badge
bottom="1"
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
index c46ad1aeea..dccb3424df 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx
@@ -7,21 +7,27 @@ import { createContext, use, type ComponentType, type ReactNode } from 'react';
import type { GalleryLiveTarget } from './galleryStateView';
-export interface GalleryImageActions {
- deleteImages(imageNames: string[]): Promise<void>;
- /**
- * TODO(Task 7): Move this narrow board-drop intent to `GalleryItemActions`
- * when common item mutations gain their mixed-media implementation.
- */
+export interface GalleryItemActions {
+ deleteItems(items: GalleryItemRef[]): Promise<void>;
+ downloadItem(item: GalleryItem): Promise<void>;
+ downloadItems(items: GalleryItemRef[], loadedItems?: GalleryItem[]): Promise<void>;
moveItemsToBoard(items: GalleryItemRef[], boardId: string): Promise<void>;
- moveImagesToBoard(imageNames: string[], boardId: string): Promise<void>;
- setImagesStarred(imageNames: string[], starred: boolean): Promise<void>;
+ openItemInNewTab(item: GalleryItem): void;
+ openItemInPreview(item: GalleryItem): void;
+ setItemsStarred(items: GalleryItemRef[], starred: boolean): Promise<void>;
}
-export interface GalleryImageActionsOptions {
+export interface GalleryItemActionContext {
+ filterIdentity: string;
+ items: GalleryItem[];
+ loadOrderedRefs(signal: AbortSignal): Promise<GalleryItemRef[]>;
+ selectedItemKey: GalleryItemKey | null;
+}
+
+export interface GalleryItemActionsOptions {
boards: GalleryBoard[];
generateValues: Record<string, unknown>;
- onImagesDeleted(imageNames: string[]): void;
+ getItemActionContext?(): GalleryItemActionContext | null;
projectId: string;
}
@@ -33,7 +39,6 @@ export interface GalleryItemContextMenuTarget {
}
export interface GalleryItemContextMenuProps {
- actions: GalleryImageActions;
boards: GalleryBoard[];
target: GalleryItemContextMenuTarget | null;
onClose(): void;
@@ -83,7 +88,7 @@ export interface GalleryWidgetProps {
* may not import workbench), not a test seam; no second adapter is expected.
*/
export interface GalleryUiAdapter {
- ImageActionsProvider: ComponentType<GalleryImageActionsOptions & { children: ReactNode }>;
+ ItemActionsProvider: ComponentType<GalleryItemActionsOptions & { children: ReactNode }>;
ImageContextMenu: ComponentType<GalleryItemContextMenuProps>;
account: { enableLiveFollow(): void };
antialiasProgressImages: boolean;
@@ -100,21 +105,21 @@ export interface GalleryUiAdapter {
}
const GalleryUiContext = createContext<GalleryUiAdapter | null>(null);
-const GalleryImageActionsContext = createContext<GalleryImageActions | null>(null);
+const GalleryItemActionsContext = createContext<GalleryItemActions | null>(null);
-export const GalleryImageActionsProvider = ({
+export const GalleryItemActionsProvider = ({
actions,
children,
}: {
- actions: GalleryImageActions;
+ actions: GalleryItemActions;
children: ReactNode;
-}) => <GalleryImageActionsContext value={actions}>{children}</GalleryImageActionsContext>;
+}) => <GalleryItemActionsContext value={actions}>{children}</GalleryItemActionsContext>;
-export const useGalleryImageActions = (): GalleryImageActions => {
- const actions = use(GalleryImageActionsContext);
+export const useGalleryItemActions = (): GalleryItemActions => {
+ const actions = use(GalleryItemActionsContext);
if (!actions) {
- throw new Error('Gallery image actions require the App-owned image-actions adapter.');
+ throw new Error('Gallery item actions require the App-owned action adapter.');
}
return actions;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
index 5efc81e33b..1d9e8de574 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx
@@ -5,7 +5,7 @@ import type { GalleryView } from '@features/gallery/core/types';
import { createContext, use } from 'react';
import type { GalleryStateView } from './galleryStateView';
-import type { GalleryImageActions, GalleryWidgetRuntime } from './GalleryUiContext';
+import type { GalleryItemActions, GalleryWidgetRuntime } from './GalleryUiContext';
/**
* Gallery-widget intents. The provider (GalleryWidgetView) is the only place
@@ -36,7 +36,7 @@ export interface GalleryActions {
export interface GalleryWidgetContextValue {
gallery: GalleryStateView;
actions: GalleryActions;
- imageActions: GalleryImageActions;
+ itemActions: GalleryItemActions;
/** The infinite window is full and the board holds images it cannot reach. */
isWindowTruncated: boolean;
projectName: string;
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
index 069b6408a4..4e010125c8 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx
@@ -1,8 +1,8 @@
-import { toGalleryItemKey } from '@features/gallery/core/items';
import { getBoundedRecentImages } from '@features/gallery/core/recentImages';
import { getGallerySettings } from '@features/gallery/core/settings';
-import { GALLERY_PAGE_SIZE } from '@features/gallery/data/queries';
+import { GALLERY_PAGE_SIZE, galleryItemNamesOptions } from '@features/gallery/data/queries';
import { StatusWidgetChip } from '@platform/ui';
+import { useQueryClient } from '@tanstack/react-query';
import { ImageIcon } from 'lucide-react';
import { useCallback, useEffect, useEffectEvent, useMemo, useRef } from 'react';
@@ -19,8 +19,9 @@ import {
getGalleryView,
} from './galleryStateView';
import {
- useGalleryImageActions,
+ useGalleryItemActions,
useGalleryUi,
+ type GalleryItemActionContext,
type GalleryWidgetProps,
type GalleryWidgetRuntime,
} from './GalleryUiContext';
@@ -49,7 +50,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
projectId,
projectName,
queueItems,
- ImageActionsProvider,
+ ItemActionsProvider,
} = useGalleryUi();
const galleryView = getGalleryView(galleryValues);
const searchTerm = getGallerySearchTerm(galleryValues);
@@ -57,6 +58,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
const page = getGalleryPage(galleryValues);
const knownTotalImages = getGalleryTotalImages(galleryValues);
const settings = getGallerySettings(galleryValues);
+ const queryClient = useQueryClient();
const data = useGalleryData({
galleryView,
page,
@@ -78,37 +80,31 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
liveProgressTarget
);
const lastPublishedTotalRef = useRef<number | null>(null);
-
- // After a deletion that takes out the previewed item, move the selection to
- // the item that now occupies the old index, else the one before it.
- const onImagesDeleted = useCallback(
- (imageNames: string[]) => {
- const deletedItemKeys = new Set(imageNames.map((name) => toGalleryItemKey({ kind: 'image', name })));
- const items = gallery.items;
- const anchorKey = gallery.selectedItemKey;
-
- if (!anchorKey || !deletedItemKeys.has(anchorKey)) {
- return;
- }
-
- const anchorIndex = items.findIndex((item) => toGalleryItemKey(item) === anchorKey);
-
- if (anchorIndex === -1) {
- return;
- }
-
- const remaining = items.filter((item) => !deletedItemKeys.has(toGalleryItemKey(item)));
- const remainingBeforeAnchor = items
- .slice(0, anchorIndex)
- .filter((item) => !deletedItemKeys.has(toGalleryItemKey(item))).length;
- const nextItem = remaining[remainingBeforeAnchor] ?? remaining[remainingBeforeAnchor - 1] ?? null;
-
- if (nextItem) {
- galleryCommands.selectItem(nextItem);
- }
+ const itemActionFilterIdentity = useMemo(() => JSON.stringify(data.filter), [data.filter]);
+ const loadOrderedItemRefs = useCallback(
+ async (signal: AbortSignal) => {
+ signal.throwIfAborted();
+ const result = await queryClient.fetchQuery(galleryItemNamesOptions(data.filter));
+
+ signal.throwIfAborted();
+ return result.items;
},
- [gallery.items, gallery.selectedItemKey, galleryCommands]
+ [data.filter, queryClient]
);
+ const itemActionContextRef = useRef<GalleryItemActionContext | null>(null);
+
+ // This ref is a live read port for an in-flight deletion. An effect would
+ // leave a commit-sized stale window, while the action must compare against
+ // the exact filter and selection from the latest render.
+ // eslint-disable-next-line react/react-compiler
+ itemActionContextRef.current = {
+ filterIdentity: itemActionFilterIdentity,
+ items: gallery.items,
+ loadOrderedRefs: loadOrderedItemRefs,
+ selectedItemKey: gallery.selectedItemKey,
+ };
+
+ const getItemActionContext = useCallback(() => itemActionContextRef.current, []);
const actions = useGalleryActions({
boards: data.boards,
@@ -165,11 +161,11 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
}
return (
- <ImageActionsProvider
+ <ItemActionsProvider
boards={data.boards}
generateValues={generateValues}
+ getItemActionContext={getItemActionContext}
projectId={projectId}
- onImagesDeleted={onImagesDeleted}
>
<GalleryWidgetContent
actions={actions}
@@ -179,7 +175,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg
projectName={projectName}
runtime={runtime}
/>
- </ImageActionsProvider>
+ </ItemActionsProvider>
);
};
@@ -198,10 +194,10 @@ const GalleryWidgetContent = ({
projectName: string;
runtime: GalleryWidgetRuntime;
}) => {
- const imageActions = useGalleryImageActions();
+ const itemActions = useGalleryItemActions();
const contextValue = useMemo<GalleryWidgetContextValue>(
- () => ({ actions, gallery, imageActions, isWindowTruncated, projectName, runtime }),
- [actions, gallery, imageActions, isWindowTruncated, projectName, runtime]
+ () => ({ actions, gallery, isWindowTruncated, itemActions, projectName, runtime }),
+ [actions, gallery, isWindowTruncated, itemActions, projectName, runtime]
);
return (
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 d9c1672245..5be6ace3f8 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
@@ -13,13 +13,16 @@ import { useGalleryActions } from './useGalleryActions';
const mocks = vi.hoisted(() => ({
deleteGalleryBoard: vi.fn(),
+ downloadBlob: vi.fn(),
+ downloadGalleryArchive: vi.fn(),
invalidateGallery: vi.fn(),
+ notificationsAdd: vi.fn(),
}));
vi.mock('@features/gallery/data/backend', () => ({
createGalleryBoard: vi.fn(),
deleteGalleryBoard: (...args: unknown[]) => mocks.deleteGalleryBoard(...args),
- downloadGalleryArchive: vi.fn(),
+ downloadGalleryArchive: (...args: unknown[]) => mocks.downloadGalleryArchive(...args),
updateGalleryBoard: vi.fn(),
uploadGalleryImage: vi.fn(),
}));
@@ -28,6 +31,10 @@ vi.mock('@features/gallery/data/queryCache', () => ({
invalidateGallery: (...args: unknown[]) => mocks.invalidateGallery(...args),
}));
+vi.mock('@platform/browser/downloadBlob', () => ({
+ downloadBlob: (...args: unknown[]) => mocks.downloadBlob(...args),
+}));
+
let host: HTMLDivElement | null = null;
let root: Root | null = null;
const actionsRef = createRef<GalleryActions>();
@@ -63,7 +70,7 @@ const NoopProvider = ({ children }: { children: ReactNode }) => children;
const NoopContextMenu = () => null;
const noop = vi.fn();
const adapter: GalleryUiAdapter = {
- ImageActionsProvider: NoopProvider,
+ ItemActionsProvider: NoopProvider,
ImageContextMenu: NoopContextMenu,
account: { enableLiveFollow: noop },
antialiasProgressImages: false,
@@ -89,7 +96,7 @@ const adapter: GalleryUiAdapter = {
generateValues: {},
liveFollowEnabled: false,
liveProgressTarget: null,
- notifications: { add: noop, reportError: noop },
+ notifications: { add: (...args: unknown[]) => mocks.notificationsAdd(...args), reportError: noop },
projectId: 'project-1',
projectName: 'Project',
queueItems: [],
@@ -171,3 +178,26 @@ describe('mixed item selection', () => {
expect(setItemMultiSelection).toHaveBeenCalledWith(['image:shared', 'video:shared'], primaryItem);
});
});
+
+describe('board image archive omission', () => {
+ it('states the exact existing board video count in the preparation notification without fetching it', async () => {
+ mocks.downloadGalleryArchive.mockResolvedValue({
+ blob: new Blob(['archive']),
+ fileName: 'board-1.zip',
+ });
+
+ await act(async () => {
+ await actionsRef.current?.downloadBoard('board-1');
+ });
+
+ expect(mocks.notificationsAdd).toHaveBeenNthCalledWith(1, {
+ kind: 'info',
+ message: 'Preparing an image archive of "Board 1". 1 video will be omitted.',
+ title: 'Preparing download',
+ });
+ expect(mocks.downloadGalleryArchive).toHaveBeenCalledWith({
+ boardId: 'board-1',
+ signal: expect.any(AbortSignal),
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
index 7785774bba..9b1f5d32b0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts
@@ -47,7 +47,8 @@ export const useGalleryActions = ({
notifications.reportError({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery' });
const recordSuccess = (title: string, message?: string) => notifications.add({ kind: 'success', message, title });
const refresh = () => void invalidateGallery(queryClient);
- const getBoardName = (boardId: string) => boards.find((board) => board.id === boardId)?.name ?? 'Uncategorized';
+ const getBoard = (boardId: string) => boards.find((board) => board.id === boardId);
+ const getBoardName = (boardId: string) => getBoard(boardId)?.name ?? 'Uncategorized';
return {
archiveBoard: async (boardId, archived) => {
@@ -118,9 +119,14 @@ export const useGalleryActions = ({
const owner = captureAccountScope();
try {
+ const board = getBoard(boardId);
+ const videoCount = board?.videoCount ?? 0;
+
notifications.add({
kind: 'info',
- message: `Preparing an archive of "${getBoardName(boardId)}".`,
+ message: `Preparing an image archive of "${getBoardName(boardId)}". ${videoCount} ${
+ videoCount === 1 ? 'video' : 'videos'
+ } will be omitted.`,
title: 'Preparing download',
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
index cb5e73a987..441634ab75 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts
@@ -19,6 +19,7 @@ import { useCallback, useMemo } from 'react';
export interface GalleryData {
boards: GalleryBoard[];
+ filter: GalleryItemsFilter;
hasMore: boolean;
isLoadingItems: boolean;
/**
@@ -242,5 +243,5 @@ export const useGalleryData = ({
void fetchNextPage();
}, [fetchNextPage, hasMore, isFetchingNextPage]);
- return { boards, hasMore, isLoadingItems: isFetching, isWindowTruncated, items, loadMore, total };
+ return { boards, filter, hasMore, isLoadingItems: isFetching, isWindowTruncated, items, loadMore, total };
};
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 f8822728ae..a0fd1bb0c7 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
@@ -1,4 +1,5 @@
-import type { GalleryImage } from '@features/gallery';
+import type { GalleryImage, GalleryItem } from '@features/gallery';
+import type { GalleryItemContextMenuTarget } from '@features/gallery/react';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import { ChakraProvider } from '@chakra-ui/react';
@@ -41,18 +42,25 @@ const image = (imageName: string): GalleryImage => ({
width: 512,
});
-const createActions = (deleteImages: ImageActions['deleteImages']): ImageActions => ({
+const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions => ({
canUseAsReferenceImage: false,
copyImage: vi.fn(() => Promise.resolve()),
- deleteImages,
+ deleteItems,
+ deleteImages: vi.fn(() => Promise.resolve()),
+ downloadItem: vi.fn(() => Promise.resolve()),
+ downloadItems: vi.fn(() => Promise.resolve()),
downloadImage: vi.fn(() => Promise.resolve()),
downloadImages: vi.fn(() => Promise.resolve()),
getImageRecallCapabilities: vi.fn(() => Promise.resolve(EMPTY_IMAGE_RECALL_CAPABILITIES)),
+ moveItemsToBoard: vi.fn(() => Promise.resolve()),
moveImagesToBoard: vi.fn(() => Promise.resolve()),
+ openItemInNewTab: vi.fn(),
+ openItemInPreview: vi.fn(),
openImageInPreview: vi.fn(),
recallImageData: vi.fn(() => Promise.resolve()),
selectForCompare: vi.fn(),
sendToCanvas: vi.fn(() => Promise.resolve()),
+ setItemsStarred: vi.fn(() => Promise.resolve()),
setImagesStarred: vi.fn(() => Promise.resolve()),
savePromptAsTemplate: vi.fn(),
useAsReferenceImage: vi.fn(),
@@ -117,6 +125,42 @@ const renderMenu = async (actions: ImageActions, images: GalleryImage[]) => {
});
};
+const item = (kind: GalleryItem['kind'], name: string): GalleryItem => {
+ const base = {
+ boardId: 'none',
+ category: 'general' as const,
+ createdAt: '2026-06-15T00:00:00Z',
+ fullUrl: `/full/${name}`,
+ height: 512,
+ isIntermediate: false,
+ name,
+ starred: false,
+ thumbnailUrl: `/thumb-${name}`,
+ width: 512,
+ };
+
+ return kind === 'video' ? { ...base, durationSeconds: 12, kind } : { ...base, kind };
+};
+
+const renderItemMenu = async (actions: ImageActions, target: GalleryItemContextMenuTarget) => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await interact(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <ImageContextMenu
+ actions={actions}
+ boards={NO_BOARDS}
+ target={target as unknown as ImageContextMenuTarget}
+ onClose={vi.fn()}
+ />
+ </ChakraProvider>
+ );
+ });
+};
+
beforeEach(() => {
preferences.confirmImageDeletion = true;
});
@@ -142,7 +186,7 @@ describe('ImageContextMenu deletion confirmation', () => {
await interact(() => getButton('Delete').click());
expect(deleteImages).toHaveBeenCalledOnce();
- expect(deleteImages).toHaveBeenCalledWith(['single.png']);
+ expect(deleteImages).toHaveBeenCalledWith([{ kind: 'image', name: 'single.png' }]);
expect(getOpenAlertDialog()).toBeNull();
});
@@ -165,7 +209,7 @@ describe('ImageContextMenu deletion confirmation', () => {
await interact(() => getMenuItem('Delete Image').click());
expect(deleteImages).toHaveBeenCalledOnce();
- expect(deleteImages).toHaveBeenCalledWith(['immediate.png']);
+ expect(deleteImages).toHaveBeenCalledWith([{ kind: 'image', name: 'immediate.png' }]);
expect(getOpenAlertDialog()).toBeNull();
});
@@ -188,7 +232,10 @@ describe('ImageContextMenu deletion confirmation', () => {
const confirmButton = getButton('Delete');
const closeButton = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]');
expect(deleteImages).toHaveBeenCalledOnce();
- expect(deleteImages).toHaveBeenCalledWith(['first.png', 'second.png']);
+ 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);
@@ -209,3 +256,52 @@ describe('ImageContextMenu deletion confirmation', () => {
expect(getOpenAlertDialog()).toBeNull();
});
});
+
+describe('ImageContextMenu mixed-media action visibility', () => {
+ it('shows common actions for a single video and hides every image-only action', async () => {
+ const video = item('video', 'clip.mp4');
+ await renderItemMenu(createActions(vi.fn()), {
+ itemRefs: [{ kind: 'video', name: video.name }],
+ items: [video],
+ x: 20,
+ y: 20,
+ });
+
+ expect(document.querySelector('[aria-label="Open in new tab"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Download video"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Open in preview"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Star video"]')).not.toBeNull();
+ expect(document.body.textContent).toContain('Change Board');
+ expect(document.body.textContent).toContain('Delete Video');
+ expect(document.body.textContent).not.toContain('Copy to clipboard');
+ expect(document.body.textContent).not.toContain('Recall Metadata');
+ expect(document.body.textContent).not.toContain('Send to Upscale');
+ expect(document.body.textContent).not.toContain('Select for Compare');
+ expect(document.body.textContent).not.toContain('New from Image');
+ });
+
+ it('keeps complete mixed refs for common bulk actions and hides image-only bulk actions when a ref is unresolved', async () => {
+ const loadedImage = item('image', 'still.png');
+ const actions = createActions(vi.fn());
+ const refs = [
+ { kind: 'image' as const, name: loadedImage.name },
+ { kind: 'video' as const, name: 'unloaded.mp4' },
+ ];
+ await renderItemMenu(actions, {
+ itemRefs: refs,
+ items: [loadedImage],
+ x: 20,
+ y: 20,
+ });
+
+ expect(document.body.textContent).toContain('2 items selected');
+ expect(document.body.textContent).toContain('Star All');
+ expect(document.body.textContent).toContain('Download Selection');
+ expect(document.body.textContent).toContain('Change Board');
+ expect(document.body.textContent).toContain('Delete Selection');
+ expect(document.body.textContent).not.toContain('New from Images');
+
+ await interact(() => getMenuItem('Star All').click());
+ expect(actions.setItemsStarred).toHaveBeenCalledWith(refs, true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 5a8a47b6ce..8fe28c5023 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -1,8 +1,15 @@
-import type { GalleryBoard, GalleryImage } from '@features/gallery';
+import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemRef } from '@features/gallery';
+import type { GalleryItemContextMenuTarget } from '@features/gallery/react';
/* eslint-disable react/react-compiler */
import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';
import { HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';
+import {
+ galleryImageItemToGalleryImage,
+ isGalleryImageItem,
+ legacyGeneratedImageToGalleryItem,
+ toGalleryItemKey,
+} from '@features/gallery';
import { ConfirmDialog, MenuContent, Tooltip } from '@platform/ui';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
@@ -38,13 +45,15 @@ import type { ImageActions } from './useImageActions';
import { EMPTY_IMAGE_RECALL_CAPABILITIES, type ImageRecallCapabilities } from './imageRecall';
-export interface ImageContextMenuTarget {
+export interface LegacyImageContextMenuTarget {
/** Right-clicked image first; more entries switch the menu into bulk mode. */
images: GalleryImage[];
x: number;
y: number;
}
+export type ImageContextMenuTarget = LegacyImageContextMenuTarget | GalleryItemContextMenuTarget;
+
/** Extras on top of the shared MenuContent surface styling. */
const MENU_CONTENT_PROPS = {
minW: '13rem',
@@ -83,6 +92,17 @@ export const getGalleryCanvasImportMenuItems = (isBulk: boolean): GalleryCanvasI
}));
export const getImageContextMenuImages = (target: ImageContextMenuTarget | null): GalleryImage[] => {
+ if (target && 'itemRefs' in target) {
+ const loadedItemsByKey = new Map(target.items.map((item) => [toGalleryItemKey(item), item]));
+ const imageItems = target.itemRefs.flatMap((ref) => {
+ const item = loadedItemsByKey.get(toGalleryItemKey(ref));
+
+ return item && isGalleryImageItem(item) ? [item] : [];
+ });
+
+ return imageItems.length === target.itemRefs.length ? imageItems.map(galleryImageItemToGalleryImage) : [];
+ }
+
if (!Array.isArray(target?.images)) {
return [];
}
@@ -90,6 +110,26 @@ export const getImageContextMenuImages = (target: ImageContextMenuTarget | null)
return target.images.filter(isUsableGalleryImage);
};
+const toGalleryItemContextMenuTarget = (target: ImageContextMenuTarget | null): GalleryItemContextMenuTarget | null => {
+ if (!target) {
+ return null;
+ }
+
+ if ('itemRefs' in target) {
+ return target;
+ }
+
+ const images = getImageContextMenuImages(target);
+ const items = images.map(legacyGeneratedImageToGalleryItem);
+
+ return {
+ itemRefs: items.map(({ kind, name }) => ({ kind, name })),
+ items,
+ x: target.x,
+ y: target.y,
+ };
+};
+
export const getImageContextMenuRecallRequestKey = (image: GalleryImage | null, isBulk: boolean): string | null => {
if (!image || isBulk) {
return null;
@@ -115,16 +155,22 @@ export const ImageContextMenu = ({
onClose: () => void;
}) => {
const confirmImageDeletion = useWorkbenchPreferenceSelector((preferences) => preferences.confirmImageDeletion);
- const [pendingDeletion, setPendingDeletion] = useState<string[] | null>(null);
- const images = getImageContextMenuImages(target);
- const image = images[0] ?? null;
+ const [pendingDeletion, setPendingDeletion] = useState<GalleryItemRef[] | null>(null);
+ const itemTarget = toGalleryItemContextMenuTarget(target);
+ const images = getImageContextMenuImages(itemTarget);
+ const isCompleteImageTarget = Boolean(itemTarget && images.length === itemTarget.itemRefs.length);
+ const imageTarget = useMemo<LegacyImageContextMenuTarget | null>(
+ () => (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(
- (imageNames: string[]) => {
+ (itemRefs: GalleryItemRef[]) => {
if (confirmImageDeletion) {
- setPendingDeletion([...imageNames]);
+ setPendingDeletion([...itemRefs]);
} else {
- void actions.deleteImages(imageNames);
+ void actions.deleteItems(itemRefs);
}
},
[actions, confirmImageDeletion]
@@ -135,29 +181,55 @@ export const ImageContextMenu = ({
return;
}
- await actions.deleteImages(pendingDeletion);
+ await actions.deleteItems(pendingDeletion);
}, [actions, pendingDeletion]);
+ const requestImageDeletion = useCallback(
+ (imageNames: string[]) => requestDeletion(imageNames.map((name) => ({ kind: 'image', name }))),
+ [requestDeletion]
+ );
return (
<>
- {target && image && (
- <ImageContextMenuContent
- key={`${image.imageName}:${images.length}`}
- actions={actions}
- boards={boards}
- image={image}
- images={images}
- target={target}
- onClose={onClose}
- onRequestDeletion={requestDeletion}
- />
- )}
+ {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}
+ target={itemTarget}
+ onClose={onClose}
+ onRequestDeletion={requestDeletion}
+ />
+ ))}
<ConfirmDialog
- body={`This permanently deletes ${pendingDeletion && pendingDeletion.length > 1 ? 'these images' : 'the image'} from every board and from disk. This cannot be undone. You can disable this confirmation in Settings.`}
+ 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} images?` : 'Delete image?'
+ pendingDeletion && pendingDeletion.length > 1
+ ? `Delete ${pendingDeletion.length} ${pendingDeletionIsImageOnly ? 'images' : 'items'}?`
+ : pendingDeletionIsImageOnly
+ ? 'Delete image?'
+ : 'Delete item?'
}
onClose={handleCancelDeletion}
onConfirm={handleConfirmDeletion}
@@ -166,6 +238,202 @@ export const ImageContextMenu = ({
);
};
+const GalleryItemContextMenuContent = ({
+ actions,
+ boards,
+ target,
+ onClose,
+ onRequestDeletion,
+}: {
+ actions: ImageActions;
+ boards: GalleryBoard[];
+ target: GalleryItemContextMenuTarget;
+ onClose: () => void;
+ onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
+}) => {
+ const targetRef = useRef(target);
+ const item = target.items[0] ?? null;
+ const itemRef = target.itemRefs[0] ?? null;
+ const isBulk = target.itemRefs.length > 1;
+
+ targetRef.current = target;
+
+ const positioning = useMemo(
+ () => ({
+ getAnchorRect: () => {
+ const currentTarget = targetRef.current;
+
+ return { height: 1, width: 1, x: currentTarget.x, y: currentTarget.y };
+ },
+ placement: 'bottom-start' as const,
+ }),
+ []
+ );
+ const handleOpenChange = useCallback(
+ (event: { open: boolean }) => {
+ if (!event.open) {
+ onClose();
+ }
+ },
+ [onClose]
+ );
+
+ if (!item || !itemRef) {
+ return null;
+ }
+
+ return (
+ <Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={handleOpenChange}>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent {...MENU_CONTENT_PROPS} maxH="min(28rem, calc(100vh - 2rem))" minW="16rem" overflowY="auto">
+ {isBulk ? (
+ <BulkItemMenuItems
+ actions={actions}
+ boards={boards}
+ itemRefs={target.itemRefs}
+ loadedItems={target.items}
+ onRequestDeletion={onRequestDeletion}
+ />
+ ) : (
+ <SingleItemMenuItems
+ actions={actions}
+ boards={boards}
+ item={item}
+ itemRef={itemRef}
+ onRequestDeletion={onRequestDeletion}
+ />
+ )}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ );
+};
+
+const SingleItemMenuItems = ({
+ actions,
+ boards,
+ item,
+ itemRef,
+ onRequestDeletion,
+}: {
+ actions: ImageActions;
+ boards: GalleryBoard[];
+ item: GalleryItem;
+ itemRef: GalleryItemRef;
+ onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
+}) => {
+ const mediaLabel = item.kind === 'video' ? 'video' : 'item';
+ const handleOpenInNewTab = useCallback(() => actions.openItemInNewTab(item), [actions, item]);
+ const handleDownload = useCallback(() => void actions.downloadItem(item), [actions, item]);
+ const handleOpenPreview = useCallback(() => actions.openItemInPreview(item), [actions, item]);
+ const handleToggleStarred = useCallback(
+ () => void actions.setItemsStarred([itemRef], !item.starred),
+ [actions, item.starred, itemRef]
+ );
+ const handleMove = useCallback(
+ (boardId: string) => void actions.moveItemsToBoard([itemRef], boardId),
+ [actions, itemRef]
+ );
+ const handleDelete = useCallback(() => onRequestDeletion([itemRef]), [itemRef, onRequestDeletion]);
+
+ return (
+ <>
+ <HStack gap="1">
+ <QuickMenuItem
+ icon={ExternalLinkIcon}
+ label="Open in new tab"
+ value="open-in-new-tab"
+ onClick={handleOpenInNewTab}
+ />
+ <QuickMenuItem
+ icon={DownloadIcon}
+ label={`Download ${mediaLabel}`}
+ value="download-item"
+ onClick={handleDownload}
+ />
+ <QuickMenuItem icon={EyeIcon} label="Open in preview" value="open-in-preview" onClick={handleOpenPreview} />
+ <QuickMenuItem
+ icon={StarIcon}
+ label={`${item.starred ? 'Unstar' : 'Star'} ${mediaLabel}`}
+ value="toggle-starred"
+ onClick={handleToggleStarred}
+ />
+ </HStack>
+ <Menu.Separator borderColor="border.subtle" />
+ <ChangeBoardSubMenu boards={boards} currentBoardId={item.boardId} onMove={handleMove} />
+ <Menu.Separator borderColor="border.subtle" />
+ <ContextMenuItem
+ color="fg.error"
+ icon={Trash2Icon}
+ label={item.kind === 'video' ? 'Delete Video' : 'Delete Item'}
+ value="delete-item"
+ onClick={handleDelete}
+ />
+ </>
+ );
+};
+
+const BulkItemMenuItems = ({
+ actions,
+ boards,
+ itemRefs,
+ loadedItems,
+ onRequestDeletion,
+}: {
+ actions: ImageActions;
+ boards: GalleryBoard[];
+ itemRefs: GalleryItemRef[];
+ loadedItems: GalleryItem[];
+ onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
+}) => {
+ const allStarred = loadedItems.length === itemRefs.length && loadedItems.every((item) => item.starred);
+ const handleToggleStarred = useCallback(
+ () => void actions.setItemsStarred(itemRefs, !allStarred),
+ [actions, allStarred, itemRefs]
+ );
+ const handleDownload = useCallback(
+ () => void actions.downloadItems(itemRefs, loadedItems),
+ [actions, itemRefs, loadedItems]
+ );
+ const handleMove = useCallback(
+ (boardId: string) => void actions.moveItemsToBoard(itemRefs, boardId),
+ [actions, itemRefs]
+ );
+ const handleDelete = useCallback(() => onRequestDeletion(itemRefs), [itemRefs, onRequestDeletion]);
+
+ return (
+ <>
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="3" py="1.5" textTransform="uppercase">
+ {itemRefs.length} items selected
+ </Text>
+ <Menu.Separator borderColor="border.subtle" />
+ <ContextMenuItem
+ icon={StarIcon}
+ label={allStarred ? 'Unstar All' : 'Star All'}
+ value="toggle-starred-all"
+ onClick={handleToggleStarred}
+ />
+ <ContextMenuItem
+ icon={DownloadIcon}
+ label="Download Selection"
+ value="download-selection"
+ onClick={handleDownload}
+ />
+ <ChangeBoardSubMenu boards={boards} currentBoardId={null} onMove={handleMove} />
+ <Menu.Separator borderColor="border.subtle" />
+ <ContextMenuItem
+ color="fg.error"
+ icon={Trash2Icon}
+ label="Delete Selection"
+ value="delete-selection"
+ onClick={handleDelete}
+ />
+ </>
+ );
+};
+
const ImageContextMenuContent = ({
actions,
boards,
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 5a6cc0d9e2..589d4bee2f 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
@@ -1,3 +1,5 @@
+import type { GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
+
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, createRef, type Ref, useImperativeHandle } from 'react';
@@ -11,26 +13,42 @@ import { useImageActions } from './useImageActions';
const mocks = vi.hoisted(() => ({
addToBoard: vi.fn(),
deleteImages: vi.fn(),
+ downloadArchive: vi.fn(),
+ downloadBlob: vi.fn(),
+ galleryRemoveItems: vi.fn(),
galleryPatchItems: vi.fn(),
+ gallerySelectItem: vi.fn(),
invalidateGallery: vi.fn(),
invalidateGalleryItems: vi.fn(),
+ itemDelete: vi.fn(),
+ itemMoveToBoard: vi.fn(),
+ itemSetStarred: vi.fn(),
+ notificationsAdd: vi.fn(),
openWorkbenchWidget: vi.fn(),
patchGalleryItemCaches: vi.fn((..._args: unknown[]) => vi.fn()),
removeFromBoard: vi.fn(),
reportError: vi.fn(),
+ resolveItem: vi.fn(),
setStarred: vi.fn(),
}));
vi.mock('@features/gallery', () => ({
galleryImages: { metadata: vi.fn() },
+ galleryItemOrganization: {
+ delete: (...args: unknown[]) => mocks.itemDelete(...args),
+ moveToBoard: (...args: unknown[]) => mocks.itemMoveToBoard(...args),
+ setStarred: (...args: unknown[]) => mocks.itemSetStarred(...args),
+ },
+ galleryItems: { resolve: (...args: unknown[]) => mocks.resolveItem(...args) },
galleryOrganization: {
addToBoard: (...args: unknown[]) => mocks.addToBoard(...args),
deleteImages: (...args: unknown[]) => mocks.deleteImages(...args),
removeFromBoard: (...args: unknown[]) => mocks.removeFromBoard(...args),
setStarred: (...args: unknown[]) => mocks.setStarred(...args),
},
- galleryTransfers: { downloadArchive: vi.fn() },
+ galleryTransfers: { downloadArchive: (...args: unknown[]) => mocks.downloadArchive(...args) },
toGalleryItemKey: ({ kind, name }: { kind: string; name: string }) => `${kind}:${name}`,
+ toGalleryItemRef: ({ kind, name }: { kind: 'image' | 'video'; name: string }) => ({ kind, name }),
}));
vi.mock('@features/gallery/queries', () => ({
@@ -49,6 +67,10 @@ vi.mock('@workbench/useOpenWorkbenchWidget', () => ({
useOpenWorkbenchWidget: () => mocks.openWorkbenchWidget,
}));
+vi.mock('@platform/browser/downloadBlob', () => ({
+ downloadBlob: (...args: unknown[]) => mocks.downloadBlob(...args),
+}));
+
vi.mock('@workbench/canvas-operations/api', () => ({
getCanvasEngine: vi.fn(),
getCanvasImportNotice: vi.fn(),
@@ -60,12 +82,16 @@ vi.mock('@workbench/WorkbenchContext', () => ({
canvas: { apply: vi.fn() },
gallery: {
patchItems: (...args: unknown[]) => mocks.galleryPatchItems(...args),
- removeItems: vi.fn(),
+ removeItems: (...args: unknown[]) => mocks.galleryRemoveItems(...args),
selectImage: vi.fn(),
+ selectItem: (...args: unknown[]) => mocks.gallerySelectItem(...args),
setCompareImage: vi.fn(),
},
generation: { patchSettings: vi.fn() },
- notifications: { add: vi.fn(), reportError: (...args: unknown[]) => mocks.reportError(...args) },
+ notifications: {
+ add: (...args: unknown[]) => mocks.notificationsAdd(...args),
+ reportError: (...args: unknown[]) => mocks.reportError(...args),
+ },
}),
useWorkbenchQueries: () => ({
getProject: vi.fn(),
@@ -81,12 +107,20 @@ vi.mock('react-i18next', () => ({
let host: HTMLDivElement | null = null;
let root: Root | null = null;
const actionsRef = createRef<ImageActions>();
+interface ItemActionContext {
+ filterIdentity: string;
+ items: GalleryItem[];
+ loadOrderedRefs(): Promise<GalleryItemRef[]>;
+ selectedItemKey: GalleryItemKey | null;
+}
+let currentItemActionContext: ItemActionContext | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const Probe = ({ ref }: { ref: Ref<ImageActions> }) => {
const actions = useImageActions({
boards: [],
generateValues: {},
+ getItemActionContext: () => currentItemActionContext,
projectId: 'project-1',
});
@@ -97,7 +131,9 @@ const Probe = ({ ref }: { ref: Ref<ImageActions> }) => {
beforeEach(async () => {
vi.clearAllMocks();
+ mocks.invalidateGallery.mockResolvedValue(undefined);
accountLifecycle.activate('user-a');
+ currentItemActionContext = null;
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -120,13 +156,18 @@ afterEach(async () => {
describe('partial image mutation outcomes', () => {
it('moves and patches only images confirmed by the backend', async () => {
- mocks.addToBoard.mockResolvedValue(['moved.png']);
+ mocks.itemMoveToBoard.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [{ kind: 'image', name: 'locked.png' }],
+ succeeded: [{ kind: 'image', name: 'moved.png' }],
+ });
await act(async () => {
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' }],
};
@@ -140,13 +181,18 @@ describe('partial image mutation outcomes', () => {
});
it('stars and patches only images confirmed by the backend', async () => {
- mocks.setStarred.mockResolvedValue(['starred.png']);
+ mocks.itemSetStarred.mockResolvedValue({
+ affectedBoardIds: [],
+ failed: [{ kind: 'image', name: 'locked.png' }],
+ succeeded: [{ kind: 'image', name: 'starred.png' }],
+ });
await act(async () => {
await actionsRef.current?.setImagesStarred(['starred.png', 'locked.png'], true);
});
const result = {
+ affectedBoardIds: [],
failed: [{ kind: 'image', name: 'locked.png' }],
succeeded: [{ kind: 'image', name: 'starred.png' }],
};
@@ -159,3 +205,473 @@ describe('partial image mutation outcomes', () => {
expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:starred.png'], { starred: true });
});
});
+
+type ExpectedItemActions = {
+ deleteItems(refs: Array<{ kind: 'image' | 'video'; name: string }>): Promise<void>;
+ downloadItem(item: { fullUrl: string; kind: 'image' | 'video'; name: string }): Promise<void>;
+ downloadItems(
+ refs: Array<{ kind: 'image' | 'video'; name: string }>,
+ loadedItems?: Array<{ fullUrl: string; kind: 'image' | 'video'; name: string }>
+ ): Promise<void>;
+ moveItemsToBoard(refs: Array<{ kind: 'image' | 'video'; name: string }>, boardId: string): Promise<void>;
+ setItemsStarred(refs: Array<{ kind: 'image' | 'video'; name: string }>, starred: boolean): Promise<void>;
+};
+
+const getItemActions = (): ExpectedItemActions => actionsRef.current as unknown as ExpectedItemActions;
+
+describe('mixed item mutation outcomes', () => {
+ it('moves mixed refs through the common organization result and patches only confirmed qualified keys', async () => {
+ const refs = [
+ { kind: 'image' as const, name: 'shared' },
+ { kind: 'video' as const, name: 'shared' },
+ ];
+ const result = {
+ affectedBoardIds: ['board-1', 'board-2'],
+ failed: [refs[1]],
+ succeeded: [refs[0]],
+ };
+ mocks.itemMoveToBoard.mockResolvedValue(result);
+
+ await act(async () => {
+ await getItemActions().moveItemsToBoard(refs, 'board-2');
+ });
+
+ expect(mocks.itemMoveToBoard).toHaveBeenCalledWith(refs, 'board-2', expect.any(AbortSignal));
+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), {
+ boardId: 'board-2',
+ kind: 'move',
+ result,
+ });
+ expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:shared'], { boardId: 'board-2' });
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
+ });
+
+ it('stars same-name media independently and preserves a failed selected item', async () => {
+ const refs = [
+ { kind: 'image' as const, name: 'shared' },
+ { kind: 'video' as const, name: 'shared' },
+ ];
+ const result = {
+ affectedBoardIds: [],
+ failed: [refs[0]],
+ succeeded: [refs[1]],
+ };
+ mocks.itemSetStarred.mockResolvedValue(result);
+
+ await act(async () => {
+ await getItemActions().setItemsStarred(refs, true);
+ });
+
+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), {
+ kind: 'star',
+ result,
+ starred: true,
+ });
+ expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['video:shared'], { starred: true });
+ expect(mocks.galleryRemoveItems).not.toHaveBeenCalled();
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ 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 () => {
+ const refs = [
+ { kind: 'video' as const, name: 'gone.mp4' },
+ { kind: 'image' as const, name: 'locked.png' },
+ ];
+ const result = {
+ affectedBoardIds: ['board-1'],
+ failed: [refs[1]],
+ succeeded: [refs[0]],
+ };
+ mocks.itemDelete.mockResolvedValue(result);
+
+ await act(async () => {
+ await getItemActions().deleteItems(refs);
+ });
+
+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), { kind: 'delete', result });
+ expect(mocks.galleryRemoveItems).toHaveBeenCalledWith(['video:gone.mp4']);
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
+ });
+
+ it('attempts operation-level invalidation only once when invalidation itself rejects', async () => {
+ const ref = { kind: 'video' as const, name: 'clip.mp4' };
+ mocks.itemSetStarred.mockResolvedValue({
+ affectedBoardIds: [],
+ failed: [],
+ succeeded: [ref],
+ });
+ mocks.invalidateGallery.mockRejectedValue(new Error('invalidation failed'));
+
+ await act(async () => {
+ await getItemActions().setItemsStarred([ref], true);
+ });
+
+ expect(mocks.invalidateGallery).toHaveBeenCalledOnce();
+ expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
+ });
+});
+
+const galleryItem = (kind: GalleryItem['kind'], name: string): GalleryItem => {
+ const base = {
+ boardId: 'board-1',
+ category: 'general' as const,
+ createdAt: '2026-07-30T00:00:00.000Z',
+ fullUrl: `/full/${name}`,
+ height: 64,
+ isIntermediate: false,
+ name,
+ starred: false,
+ thumbnailUrl: `/thumb/${name}`,
+ width: 64,
+ };
+
+ return kind === 'video' ? { ...base, durationSeconds: 4, kind } : { ...base, kind };
+};
+
+describe('primary successor after confirmed deletion', () => {
+ it('selects the nearest surviving predecessor from ordered names before a successor', async () => {
+ const before = galleryItem('video', 'before.mp4');
+ const primary = galleryItem('image', 'primary.png');
+ const after = galleryItem('image', 'after.png');
+ const refs = [before, primary, after].map(({ kind, name }) => ({ kind, name }));
+ currentItemActionContext = {
+ filterIdentity: 'filter-a',
+ items: [before, primary, after],
+ loadOrderedRefs: () => Promise.resolve(refs),
+ selectedItemKey: 'image:primary.png',
+ };
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [],
+ succeeded: [{ kind: 'image', name: 'primary.png' }],
+ });
+
+ await act(async () => {
+ await getItemActions().deleteItems([{ kind: 'image', name: 'primary.png' }]);
+ });
+
+ expect(mocks.gallerySelectItem).toHaveBeenCalledWith(before, 'project-1');
+ });
+
+ it('resolves an unloaded predecessor by qualified ref', async () => {
+ const primary = galleryItem('image', 'primary.png');
+ const after = galleryItem('image', 'after.png');
+ const unloaded = galleryItem('video', 'unloaded.mp4');
+ currentItemActionContext = {
+ filterIdentity: 'filter-a',
+ items: [primary, after],
+ loadOrderedRefs: () =>
+ Promise.resolve([
+ { kind: 'video' as const, name: unloaded.name },
+ { kind: 'image' as const, name: primary.name },
+ { kind: 'image' as const, name: after.name },
+ ]),
+ selectedItemKey: 'image:primary.png',
+ };
+ mocks.resolveItem.mockResolvedValue(unloaded);
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [],
+ succeeded: [{ kind: 'image', name: primary.name }],
+ });
+
+ await act(async () => {
+ await getItemActions().deleteItems([{ kind: 'image', name: primary.name }]);
+ });
+
+ expect(mocks.resolveItem).toHaveBeenCalledWith({ kind: 'video', name: unloaded.name }, expect.any(AbortSignal));
+ expect(mocks.gallerySelectItem).toHaveBeenCalledWith(unloaded, 'project-1');
+ });
+
+ it('falls back to materialized order and then the nearest successor when names fail', async () => {
+ const primary = galleryItem('image', 'primary.png');
+ const after = galleryItem('video', 'after.mp4');
+ currentItemActionContext = {
+ filterIdentity: 'filter-a',
+ items: [primary, after],
+ loadOrderedRefs: () => Promise.reject(new Error('names unavailable')),
+ selectedItemKey: 'image:primary.png',
+ };
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [],
+ succeeded: [{ kind: 'image', name: primary.name }],
+ });
+
+ await act(async () => {
+ await getItemActions().deleteItems([{ kind: 'image', name: primary.name }]);
+ });
+
+ expect(mocks.gallerySelectItem).toHaveBeenCalledWith(after, 'project-1');
+ });
+
+ it('does not promote a failed deletion and keeps a failed primary selected', async () => {
+ const failedBefore = galleryItem('video', 'failed-before.mp4');
+ const survivingBefore = galleryItem('image', 'surviving-before.png');
+ const primary = galleryItem('image', 'primary.png');
+ currentItemActionContext = {
+ filterIdentity: 'filter-a',
+ items: [survivingBefore, failedBefore, primary],
+ loadOrderedRefs: () =>
+ Promise.resolve([
+ { kind: 'image' as const, name: survivingBefore.name },
+ { kind: 'video' as const, name: failedBefore.name },
+ { kind: 'image' as const, name: primary.name },
+ ]),
+ selectedItemKey: 'image:primary.png',
+ };
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [{ kind: 'video', name: failedBefore.name }],
+ succeeded: [{ kind: 'image', name: primary.name }],
+ });
+
+ await act(async () => {
+ await getItemActions().deleteItems([
+ { kind: 'video', name: failedBefore.name },
+ { kind: 'image', name: primary.name },
+ ]);
+ });
+
+ expect(mocks.gallerySelectItem).toHaveBeenCalledWith(survivingBefore, 'project-1');
+
+ mocks.gallerySelectItem.mockClear();
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: [],
+ failed: [{ kind: 'image', name: primary.name }],
+ succeeded: [],
+ });
+
+ await act(async () => {
+ await getItemActions().deleteItems([{ kind: 'image', name: primary.name }]);
+ });
+
+ expect(mocks.gallerySelectItem).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unloaded successor after the filter or selection becomes stale', async () => {
+ const primary = galleryItem('image', 'primary.png');
+ const successor = galleryItem('video', 'successor.mp4');
+ let resolveItem = (_item: GalleryItem): void => undefined;
+ currentItemActionContext = {
+ filterIdentity: 'filter-a',
+ items: [primary],
+ loadOrderedRefs: () =>
+ Promise.resolve([
+ { kind: 'image' as const, name: primary.name },
+ { kind: 'video' as const, name: successor.name },
+ ]),
+ selectedItemKey: 'image:primary.png',
+ };
+ mocks.resolveItem.mockReturnValue(
+ new Promise((resolve) => {
+ resolveItem = resolve;
+ })
+ );
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [],
+ succeeded: [{ kind: 'image', name: primary.name }],
+ });
+
+ const deletion = getItemActions().deleteItems([{ kind: 'image', name: primary.name }]);
+ await vi.waitFor(() => expect(mocks.resolveItem).toHaveBeenCalledOnce());
+ currentItemActionContext = {
+ filterIdentity: 'filter-b',
+ items: [],
+ loadOrderedRefs: () => Promise.resolve([]),
+ selectedItemKey: 'video:other.mp4',
+ };
+ resolveItem(successor);
+ await act(() => deletion);
+
+ expect(mocks.gallerySelectItem).not.toHaveBeenCalled();
+ });
+
+ it('does not apply confirmed deletion side effects after the account changes while resolving a successor', async () => {
+ const primary = galleryItem('image', 'primary.png');
+ const successor = galleryItem('video', 'successor.mp4');
+ let resolveItem = (_item: GalleryItem): void => undefined;
+ currentItemActionContext = {
+ filterIdentity: 'filter-a',
+ items: [primary],
+ loadOrderedRefs: () =>
+ Promise.resolve([
+ { kind: 'image' as const, name: primary.name },
+ { kind: 'video' as const, name: successor.name },
+ ]),
+ selectedItemKey: 'image:primary.png',
+ };
+ mocks.resolveItem.mockReturnValue(
+ new Promise((resolve) => {
+ resolveItem = resolve;
+ })
+ );
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [],
+ succeeded: [{ kind: 'image', name: primary.name }],
+ });
+
+ const deletion = getItemActions().deleteItems([{ kind: 'image', name: primary.name }]);
+ await vi.waitFor(() => expect(mocks.resolveItem).toHaveBeenCalledOnce());
+ accountLifecycle.activate('user-b');
+ resolveItem(successor);
+ await act(() => deletion);
+
+ expect(mocks.patchGalleryItemCaches).not.toHaveBeenCalled();
+ expect(mocks.galleryRemoveItems).not.toHaveBeenCalled();
+ expect(mocks.gallerySelectItem).not.toHaveBeenCalled();
+ expect(mocks.invalidateGallery).not.toHaveBeenCalled();
+ });
+
+ it('does not promote an unrelated item when the captured order does not contain the deleted primary', async () => {
+ const primary = galleryItem('image', 'primary.png');
+ const unrelated = galleryItem('video', 'unrelated.mp4');
+ currentItemActionContext = {
+ filterIdentity: 'filter-a',
+ items: [primary, unrelated],
+ loadOrderedRefs: () => Promise.resolve([{ kind: 'video', name: unrelated.name }]),
+ selectedItemKey: 'image:primary.png',
+ };
+ mocks.itemDelete.mockResolvedValue({
+ affectedBoardIds: ['board-1'],
+ failed: [],
+ succeeded: [{ kind: 'image', name: primary.name }],
+ });
+
+ await act(async () => {
+ await getItemActions().deleteItems([{ kind: 'image', name: primary.name }]);
+ });
+
+ expect(mocks.gallerySelectItem).not.toHaveBeenCalled();
+ });
+});
+
+describe('mixed item downloads', () => {
+ const image = { fullUrl: '/full/still.png', kind: 'image' as const, name: 'still.png' };
+ const firstVideo = { fullUrl: '/full/first.mp4', kind: 'video' as const, name: 'first.mp4' };
+ const secondVideo = { fullUrl: '/full/second.mp4', kind: 'video' as const, name: 'second.mp4' };
+
+ it('creates exactly one existing archive for an image-only selection', async () => {
+ mocks.downloadArchive.mockResolvedValue({
+ blob: new Blob(['archive']),
+ fileName: 'images.zip',
+ });
+ vi.stubGlobal('fetch', vi.fn());
+
+ await act(async () => {
+ await getItemActions().downloadItems([{ kind: 'image', name: image.name }], [image]);
+ });
+
+ expect(mocks.downloadArchive).toHaveBeenCalledOnce();
+ expect(mocks.downloadArchive).toHaveBeenCalledWith({
+ imageNames: [image.name],
+ signal: expect.any(AbortSignal),
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ expect(mocks.downloadBlob).toHaveBeenCalledWith(expect.any(Blob), 'images.zip');
+ });
+
+ it('downloads a single video from its protected full URL with its actual name', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('video-one')));
+
+ await act(async () => {
+ await getItemActions().downloadItem(firstVideo);
+ });
+
+ expect(fetch).toHaveBeenCalledWith(firstVideo.fullUrl, { signal: expect.any(AbortSignal) });
+ expect(mocks.downloadBlob).toHaveBeenCalledWith(expect.any(Blob), firstVideo.name);
+ });
+
+ it('downloads a mixed selection archive-first and videos sequentially', async () => {
+ const order: string[] = [];
+ mocks.downloadArchive.mockImplementation(() => {
+ order.push('archive');
+ return Promise.resolve({ blob: new Blob(['archive']), fileName: 'images.zip' });
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockImplementation((url: string) => {
+ order.push(url);
+ return Promise.resolve(new Response(url));
+ })
+ );
+ mocks.downloadBlob.mockImplementation((_blob: Blob, name: string) => order.push(`save:${name}`));
+
+ await act(async () => {
+ await getItemActions().downloadItems(
+ [
+ { kind: 'video', name: firstVideo.name },
+ { kind: 'image', name: image.name },
+ { kind: 'video', name: secondVideo.name },
+ ],
+ [image, firstVideo, secondVideo]
+ );
+ });
+
+ expect(mocks.downloadArchive).toHaveBeenCalledWith({
+ imageNames: [image.name],
+ signal: expect.any(AbortSignal),
+ });
+ expect(order).toEqual([
+ 'archive',
+ 'save:images.zip',
+ firstVideo.fullUrl,
+ `save:${firstVideo.name}`,
+ secondVideo.fullUrl,
+ `save:${secondVideo.name}`,
+ ]);
+ });
+
+ it('continues after a failed video and summarizes the partial outcome once', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockRejectedValueOnce(new Error('first failed')).mockResolvedValueOnce(new Response('video-two'))
+ );
+
+ await act(async () => {
+ await getItemActions().downloadItems(
+ [
+ { kind: 'video', name: firstVideo.name },
+ { kind: 'video', name: secondVideo.name },
+ ],
+ [firstVideo, secondVideo]
+ );
+ });
+
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(mocks.downloadBlob).toHaveBeenCalledOnce();
+ expect(mocks.downloadBlob).toHaveBeenCalledWith(expect.any(Blob), secondVideo.name);
+ expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
+ });
+
+ it('skips an unresolved video and continues with the next video in order', async () => {
+ mocks.resolveItem.mockRejectedValueOnce(new Error('missing video')).mockResolvedValueOnce(secondVideo);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('video-two')));
+
+ await act(async () => {
+ await getItemActions().downloadItems([
+ { kind: 'video', name: firstVideo.name },
+ { kind: 'video', name: secondVideo.name },
+ ]);
+ });
+
+ expect(mocks.resolveItem).toHaveBeenNthCalledWith(
+ 1,
+ { kind: 'video', name: firstVideo.name },
+ expect.any(AbortSignal)
+ );
+ expect(mocks.resolveItem).toHaveBeenNthCalledWith(
+ 2,
+ { kind: 'video', name: secondVideo.name },
+ expect.any(AbortSignal)
+ );
+ expect(fetch).toHaveBeenCalledOnce();
+ expect(mocks.downloadBlob).toHaveBeenCalledWith(expect.any(Blob), secondVideo.name);
+ expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index afc021def6..64a54746bc 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -1,15 +1,20 @@
+import type { GalleryItemActionContext, GalleryItemActions } from '@features/gallery/react';
import type { VaeModelConfig } from '@features/generation/contracts';
import {
galleryImages,
- galleryOrganization,
+ galleryItemOrganization,
+ galleryItems,
galleryTransfers,
toGalleryItemKey,
+ toGalleryItemRef,
type GalleryBoard,
type GalleryImage,
+ type GalleryItem,
type GalleryItemMutationResult,
+ type GalleryItemRef,
} from '@features/gallery';
-import { invalidateGallery, invalidateGalleryItems, patchGalleryItemCaches } from '@features/gallery/queries';
+import { 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';
@@ -49,7 +54,7 @@ import {
* grid, preview, image context menus). Mutations patch the shared Gallery cache
* when possible and explicitly invalidate the affected server state.
*/
-export interface ImageActions {
+export interface ImageActions extends GalleryItemActions {
/** Whether the generate widget's current model can accept another reference image. */
canUseAsReferenceImage: boolean;
copyImage: (image: GalleryImage) => Promise<void>;
@@ -70,27 +75,6 @@ export interface ImageActions {
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
-const getImageMutationResult = (
- succeededImageNames: readonly string[],
- failedImageNames: readonly string[] = []
-): GalleryItemMutationResult => ({
- failed: failedImageNames.map((name) => ({ kind: 'image', name })),
- succeeded: succeededImageNames.map((name) => ({ kind: 'image', name })),
-});
-
-const getConfirmedImageMutationResult = (
- requestedImageNames: readonly string[],
- confirmedImageNames: readonly string[]
-): GalleryItemMutationResult => {
- const confirmed = new Set(confirmedImageNames);
- const requested = [...new Set(requestedImageNames)];
-
- return getImageMutationResult(
- requested.filter((name) => confirmed.has(name)),
- requested.filter((name) => !confirmed.has(name))
- );
-};
-
const toPngBlob = async (blob: Blob): Promise<Blob> => {
if (blob.type === 'image/png') {
return blob;
@@ -110,11 +94,13 @@ const toPngBlob = async (blob: Blob): Promise<Blob> => {
export const useImageActions = ({
boards,
generateValues,
+ getItemActionContext,
onImagesDeleted,
projectId,
}: {
boards: GalleryBoard[];
generateValues: Record<string, unknown>;
+ getItemActionContext?: () => GalleryItemActionContext | null;
projectId?: string;
/** Called after a successful deletion so the host can select a neighboring image. */
onImagesDeleted?: (imageNames: string[]) => void;
@@ -154,82 +140,349 @@ export const useImageActions = ({
return project ? getProjectWidgetValues(project, 'generate') : {};
};
+ const reportMutationOutcome = (
+ action: 'delete' | 'move' | 'star' | 'unstar',
+ requestedCount: number,
+ result: GalleryItemMutationResult,
+ boardId?: string
+ ) => {
+ if (result.failed.length > 0) {
+ recordError(
+ new Error(
+ t(`widgets.gallery.itemActions.${action}.${result.succeeded.length > 0 ? 'partial' : 'failure'}`, {
+ board: boardId ? getBoardName(boardId) : undefined,
+ count: requestedCount,
+ defaultValue:
+ result.succeeded.length > 0
+ ? `${result.succeeded.length} of ${requestedCount} items succeeded; ${result.failed.length} failed.`
+ : `Could not ${action} ${requestedCount === 1 ? 'item' : `${requestedCount} items`}.`,
+ failed: result.failed.length,
+ succeeded: result.succeeded.length,
+ })
+ )
+ );
+ return;
+ }
+
+ recordSuccess(
+ t(`widgets.gallery.itemActions.${action}.success`, {
+ board: boardId ? getBoardName(boardId) : undefined,
+ count: result.succeeded.length,
+ defaultValue:
+ action === 'move'
+ ? `Moved ${result.succeeded.length === 1 ? 'item' : `${result.succeeded.length} items`} to ${getBoardName(
+ boardId ?? 'none'
+ )}.`
+ : `${action === 'delete' ? 'Deleted' : action === 'star' ? 'Starred' : 'Unstarred'} ${
+ result.succeeded.length === 1 ? 'item' : `${result.succeeded.length} items`
+ }.`,
+ })
+ );
+ };
+ const runItemMutation = async ({
+ action,
+ applyConfirmed,
+ boardId,
+ mutate,
+ requested,
+ }: {
+ action: 'delete' | 'move' | 'star' | 'unstar';
+ applyConfirmed: (result: GalleryItemMutationResult, signal: AbortSignal) => Promise<void> | void;
+ boardId?: string;
+ mutate: (signal: AbortSignal) => Promise<GalleryItemMutationResult>;
+ requested: GalleryItemRef[];
+ }): Promise<void> => {
+ const owner = captureAccountScope();
+ let error: unknown = null;
+ let result: GalleryItemMutationResult | null = null;
+
+ try {
+ result = await mutate(owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ await applyConfirmed(result, owner.signal);
+ } catch (caught: unknown) {
+ error = caught;
+ }
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ try {
+ await invalidateGallery(queryClient, owner);
+ } catch (caught: unknown) {
+ error ??= caught;
+ }
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ if (error || !result) {
+ recordError(error ?? new Error('Gallery item mutation did not return a result.'));
+ return;
+ }
+
+ reportMutationOutcome(action, requested.length, result, boardId);
+ };
+ const deleteItems = (items: GalleryItemRef[]): Promise<void> => {
+ let deletionContext: GalleryItemActionContext | null = null;
+ let orderedRefs: GalleryItemRef[] | null = null;
+ const isDeletionContextCurrent = (): boolean => {
+ if (!deletionContext || !getItemActionContext) {
+ return false;
+ }
- return {
- copyImage: async (image) => {
- const owner = captureAccountScope();
+ const current = getItemActionContext();
- try {
- const response = await fetch(image.imageUrl, { signal: owner.signal });
- const sourceBlob = await response.blob();
+ return Boolean(
+ current &&
+ current.filterIdentity === deletionContext.filterIdentity &&
+ current.selectedItemKey === deletionContext.selectedItemKey
+ );
+ };
- assertAccountScopeCurrent(owner);
- const blob = await toPngBlob(sourceBlob);
+ return runItemMutation({
+ action: 'delete',
+ applyConfirmed: async (result, signal) => {
+ if (result.succeeded.length === 0) {
+ return;
+ }
- assertAccountScopeCurrent(owner);
- await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
- assertAccountScopeCurrent(owner);
- recordSuccess('Copied image to clipboard');
- } catch (error: unknown) {
- if (!isAccountScopeCurrent(owner)) {
+ let successor: GalleryItem | null = null;
+ const primaryKey = deletionContext?.selectedItemKey ?? null;
+ const succeededKeys = new Set(result.succeeded.map(toGalleryItemKey));
+
+ if (deletionContext && primaryKey && succeededKeys.has(primaryKey) && isDeletionContextCurrent()) {
+ const refs = orderedRefs ?? deletionContext.items.map(toGalleryItemRef);
+ const primaryIndex = refs.findIndex((ref) => toGalleryItemKey(ref) === primaryKey);
+ const ineligibleKeys = new Set([
+ ...result.succeeded.map(toGalleryItemKey),
+ ...result.failed.map(toGalleryItemKey),
+ ]);
+ let successorRef: GalleryItemRef | null = null;
+
+ if (primaryIndex >= 0) {
+ for (let index = primaryIndex - 1; index >= 0; index -= 1) {
+ const candidate = refs[index];
+
+ if (candidate && !ineligibleKeys.has(toGalleryItemKey(candidate))) {
+ successorRef = candidate;
+ break;
+ }
+ }
+
+ if (!successorRef) {
+ for (let index = primaryIndex + 1; index < refs.length; index += 1) {
+ const candidate = refs[index];
+
+ if (candidate && !ineligibleKeys.has(toGalleryItemKey(candidate))) {
+ successorRef = candidate;
+ break;
+ }
+ }
+ }
+ }
+
+ if (successorRef) {
+ successor =
+ deletionContext.items.find((item) => toGalleryItemKey(item) === toGalleryItemKey(successorRef)) ?? null;
+
+ if (!successor) {
+ try {
+ successor = await galleryItems.resolve(successorRef, signal);
+ } catch {
+ successor = null;
+ }
+ }
+
+ signal.throwIfAborted();
+
+ if (!isDeletionContextCurrent()) {
+ successor = null;
+ }
+ }
+ }
+
+ patchGalleryItemCaches(queryClient, { kind: 'delete', result });
+ gallery.removeItems(result.succeeded.map(toGalleryItemKey));
+ if (successor) {
+ gallery.selectItem(successor, projectId);
+ }
+ 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)
+ ) {
+ try {
+ orderedRefs = await deletionContext.loadOrderedRefs(signal);
+ } catch {
+ orderedRefs = deletionContext.items.map(toGalleryItemRef);
+ }
+ }
+
+ signal.throwIfAborted();
+ return galleryItemOrganization.delete(items, signal);
+ },
+ requested: items,
+ });
+ };
+ const moveItemsToBoard = (items: GalleryItemRef[], boardId: string): Promise<void> =>
+ runItemMutation({
+ action: 'move',
+ applyConfirmed: (result) => {
+ if (result.succeeded.length === 0) {
return;
}
+ patchGalleryItemCaches(queryClient, { boardId, kind: 'move', result });
+ gallery.patchItems(result.succeeded.map(toGalleryItemKey), { boardId });
+ },
+ boardId,
+ mutate: (signal) => galleryItemOrganization.moveToBoard(items, boardId, signal),
+ requested: items,
+ });
+ const setItemsStarred = (items: GalleryItemRef[], starred: boolean): Promise<void> =>
+ runItemMutation({
+ action: starred ? 'star' : 'unstar',
+ applyConfirmed: (result) => {
+ if (result.succeeded.length === 0) {
+ return;
+ }
+
+ patchGalleryItemCaches(queryClient, { kind: 'star', result, starred });
+ gallery.patchItems(result.succeeded.map(toGalleryItemKey), { starred });
+ },
+ mutate: (signal) => galleryItemOrganization.setStarred(items, starred, signal),
+ requested: items,
+ });
+ const fetchItemBlob = async (item: GalleryItem, signal: AbortSignal): Promise<Blob> => {
+ const response = await fetch(item.fullUrl, { signal });
+
+ if (!response.ok) {
+ throw new Error(`Download failed with status ${response.status}.`);
+ }
+
+ return response.blob();
+ };
+ const downloadItem = async (item: GalleryItem): Promise<void> => {
+ const owner = captureAccountScope();
+
+ try {
+ const blob = await fetchItemBlob(item, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ downloadBlob(blob, item.name);
+ } catch (error: unknown) {
+ if (isAccountScopeCurrent(owner)) {
recordError(error);
}
- },
- deleteImages: async (imageNames) => {
- const owner = captureAccountScope();
-
+ }
+ };
+ const downloadItems = async (items: GalleryItemRef[], loadedItems: GalleryItem[] = []): Promise<void> => {
+ const owner = captureAccountScope();
+ const loadedByKey = new Map(loadedItems.map((item) => [toGalleryItemKey(item), item]));
+ const imageNames = items.filter((item) => item.kind === 'image').map((item) => item.name);
+ const videoRefs = items.filter((item) => item.kind === 'video');
+ let failedCount = 0;
+ let succeededCount = 0;
+
+ if (imageNames.length > 0) {
try {
- const { deletedImageNames, failedImageNames } = await galleryOrganization.deleteImages(
+ const { blob, fileName } = await galleryTransfers.downloadArchive({
imageNames,
- owner.signal
- );
+ signal: owner.signal,
+ });
assertAccountScopeCurrent(owner);
- // Evict only what the backend actually deleted. A name it refused is still on the
- // server, so dropping it from the cache would hide a live image until a full refresh.
- if (deletedImageNames.length > 0) {
- const result = getImageMutationResult(deletedImageNames, failedImageNames);
-
- patchGalleryItemCaches(queryClient, { kind: 'delete', result });
- gallery.removeItems(result.succeeded.map(toGalleryItemKey));
- onImagesDeleted?.(deletedImageNames);
+ downloadBlob(blob, fileName);
+ succeededCount += imageNames.length;
+ } catch {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
}
- if (failedImageNames.length > 0) {
- recordError(
- new Error(
- failedImageNames.length === 1
- ? `Could not delete ${failedImageNames[0]}`
- : `Could not delete ${failedImageNames.length} of ${imageNames.length} images`
- )
- );
- } else {
- recordSuccess(
- deletedImageNames.length === 1 ? 'Deleted image' : `Deleted ${deletedImageNames.length} images`
- );
+ failedCount += imageNames.length;
+ }
+ }
+
+ for (const ref of videoRefs) {
+ try {
+ const loadedItem = loadedByKey.get(toGalleryItemKey(ref));
+ const item = loadedItem ?? (await galleryItems.resolve(ref, owner.signal));
+
+ assertAccountScopeCurrent(owner);
+ if (item.kind !== 'video') {
+ throw new Error(`Resolved ${ref.name} as the wrong media kind.`);
}
- void invalidateGallery(queryClient);
- } catch (error: unknown) {
+ const blob = await fetchItemBlob(item, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ downloadBlob(blob, item.name);
+ succeededCount += 1;
+ } catch {
if (!isAccountScopeCurrent(owner)) {
return;
}
- recordError(error);
+ failedCount += 1;
}
+ }
+
+ if (failedCount > 0) {
+ recordError(
+ new Error(
+ t('widgets.gallery.itemActions.download.partial', {
+ count: items.length,
+ defaultValue: `${succeededCount} of ${items.length} items downloaded; ${failedCount} failed or skipped.`,
+ failed: failedCount,
+ succeeded: succeededCount,
+ })
+ )
+ );
+ } else {
+ recordSuccess(
+ t('widgets.gallery.itemActions.download.success', {
+ count: succeededCount,
+ defaultValue: 'Download ready',
+ })
+ );
+ }
+ };
+
+ return {
+ deleteItems,
+ downloadItem,
+ downloadItems,
+ moveItemsToBoard,
+ openItemInNewTab: (item) => {
+ window.open(item.fullUrl, '_blank', 'noopener');
},
- downloadImage: async (image) => {
+ openItemInPreview: (item) => {
+ gallery.selectItem(item, projectId);
+ openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });
+ },
+ setItemsStarred,
+ copyImage: async (image) => {
const owner = captureAccountScope();
try {
const response = await fetch(image.imageUrl, { signal: owner.signal });
- const blob = await response.blob();
+ const sourceBlob = await response.blob();
assertAccountScopeCurrent(owner);
- downloadBlob(blob, image.imageName);
+ const blob = await toPngBlob(sourceBlob);
+
+ assertAccountScopeCurrent(owner);
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ assertAccountScopeCurrent(owner);
+ recordSuccess('Copied image to clipboard');
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
@@ -238,21 +491,16 @@ export const useImageActions = ({
recordError(error);
}
},
- downloadImages: async (imageNames) => {
+ deleteImages: (imageNames) => deleteItems(imageNames.map((name) => ({ kind: 'image', name }))),
+ downloadImage: async (image) => {
const owner = captureAccountScope();
try {
- notifications.add({
- kind: 'info',
- message: `Preparing an archive of ${imageNames.length} images.`,
- title: 'Preparing download',
- });
-
- const { blob, fileName } = await galleryTransfers.downloadArchive({ imageNames, signal: owner.signal });
+ const response = await fetch(image.imageUrl, { signal: owner.signal });
+ const blob = await response.blob();
assertAccountScopeCurrent(owner);
- downloadBlob(blob, fileName);
- recordSuccess('Download ready');
+ downloadBlob(blob, image.imageName);
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
return;
@@ -261,6 +509,7 @@ export const useImageActions = ({
recordError(error);
}
},
+ downloadImages: (imageNames) => downloadItems(imageNames.map((name) => ({ kind: 'image', name }))),
getImageRecallCapabilities: async (image) => {
const owner = captureAccountScope();
@@ -319,47 +568,11 @@ export const useImageActions = ({
recordError(error);
}
},
- moveImagesToBoard: async (imageNames, boardId) => {
- const owner = captureAccountScope();
-
- try {
- const confirmedImageNames =
- boardId === 'none'
- ? await galleryOrganization.removeFromBoard(imageNames, owner.signal)
- : await galleryOrganization.addToBoard(boardId, imageNames, owner.signal);
-
- assertAccountScopeCurrent(owner);
- const result = getConfirmedImageMutationResult(imageNames, confirmedImageNames);
-
- if (result.succeeded.length > 0) {
- patchGalleryItemCaches(queryClient, { boardId, kind: 'move', result });
- gallery.patchItems(result.succeeded.map(toGalleryItemKey), { boardId });
- }
-
- if (result.failed.length > 0) {
- recordError(
- new Error(
- result.failed.length === 1
- ? `Could not move ${result.failed[0]?.name}`
- : `Could not move ${result.failed.length} of ${imageNames.length} images`
- )
- );
- } else {
- recordSuccess(
- imageNames.length === 1
- ? `Moved image to ${getBoardName(boardId)}`
- : `Moved ${imageNames.length} images to ${getBoardName(boardId)}`
- );
- }
- void invalidateGallery(queryClient);
- } catch (error: unknown) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- recordError(error);
- }
- },
+ moveImagesToBoard: (imageNames, boardId) =>
+ moveItemsToBoard(
+ imageNames.map((name) => ({ kind: 'image', name })),
+ boardId
+ ),
openImageInPreview: (image) => {
gallery.selectImage(image, projectId);
openWorkbenchWidget('preview', { preferredRegions: ['center'], requireCenterView: true });
@@ -426,39 +639,11 @@ export const useImageActions = ({
});
}
},
- setImagesStarred: async (imageNames, starred) => {
- const owner = captureAccountScope();
-
- try {
- const confirmedImageNames = await galleryOrganization.setStarred(imageNames, starred, owner.signal);
-
- assertAccountScopeCurrent(owner);
- const result = getConfirmedImageMutationResult(imageNames, confirmedImageNames);
-
- if (result.succeeded.length > 0) {
- patchGalleryItemCaches(queryClient, { kind: 'star', result, starred });
- gallery.patchItems(result.succeeded.map(toGalleryItemKey), { starred });
- }
-
- if (result.failed.length > 0) {
- recordError(
- new Error(
- result.failed.length === 1
- ? `Could not ${starred ? 'star' : 'unstar'} ${result.failed[0]?.name}`
- : `Could not ${starred ? 'star' : 'unstar'} ${result.failed.length} of ${imageNames.length} images`
- )
- );
- }
- void invalidateGalleryItems(queryClient);
- } catch (error: unknown) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- void invalidateGalleryItems(queryClient);
- recordError(error);
- }
- },
+ setImagesStarred: (imageNames, starred) =>
+ setItemsStarred(
+ imageNames.map((name) => ({ kind: 'image', name })),
+ starred
+ ),
canUseAsReferenceImage: Boolean(
currentGenerateValues &&
currentGenerateValues.referenceImages.length < getMaxReferenceImages(currentGenerateValues.model)
@@ -481,6 +666,7 @@ export const useImageActions = ({
gallery,
generateValues,
generation,
+ getItemActionContext,
models,
notifications,
onImagesDeleted,