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 gallery organization transport

joshistoast35bf5e98ae5e
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-7a-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-7a-report.md
new file mode 100644
index 0000000000..6221656006
--- /dev/null
+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-7a-report.md
@@ -0,0 +1,184 @@
+# Task 7A Report: Mixed-media organization transport and domain results
+
+## Status
+
+Complete.
+
+Task 7A adds the mixed-media `galleryItemOrganization` transport/domain API
+through the existing gallery entry. Delete, star/unstar, and board movement
+partition ordered qualified refs by media kind, trust only backend-confirmed
+success names, and return confirmed successes, unconfirmed failures, and
+deterministic affected board IDs.
+
+This subtask does not patch caches or Workbench state, invalidate queries,
+notify, add action providers, change UI, or implement downloads. Those
+operation-level effects remain Task 7B responsibilities after it consumes the
+confirmed result.
+
+## TDD evidence
+
+### Inherited RED
+
+The original Task 7A implementer captured the focused RED before the production
+edits and handed off this evidence with the uncommitted implementation:
+
+```sh
+pnpm test src/features/gallery/data/organization.test.ts
+```
+
+```text
+Test Files 1 failed (1)
+Tests 11 failed (11)
+```
+
+The failures covered the then-missing mixed organization entry, video bulk
+transports, per-video board movement, confirmed-only result mapping, and abort
+and concurrency behavior.
+
+### GREEN
+
+After independently auditing the inherited diff, the resumed focused run was:
+
+```sh
+pnpm test \
+ src/features/gallery/core/items.test.ts \
+ src/features/gallery/data/backend.test.ts \
+ src/features/gallery/data/organization.test.ts \
+ src/features/gallery/data/queryCache.test.ts \
+ src/features/gallery/data/itemQueryCache.test.ts
+```
+
+```text
+Test Files 5 passed (5)
+Tests 71 passed (71)
+```
+
+Aggregate lint then identified only an OXC structural warning in the bounded
+worker loop (`no-unmodified-loop-condition`). The loop was rewritten without
+changing its early-abort or scheduling behavior. The same focused command
+passed again with 5 files and 71 tests before the full gates were repeated.
+
+## Implementation
+
+### Strict organization transports
+
+- Image move, remove, star/unstar, and delete transports now map the required
+ authoritative success arrays and `affected_boards` array from strict runtime
+ DTOs.
+- Existing image-only gallery organization methods remain available and keep
+ their image-name-only return types.
+- Video delete, star, and unstar use one backend bulk request with the exact
+ `video_names` body.
+- Video board movement uses the existing single-video
+ `POST /api/v1/videos/board` and `DELETE /api/v1/videos/board` contracts.
+- Every request forwards the caller's abort signal and checks it before and
+ after transport resolution so an aborted response cannot become a confirmed
+ success.
+
+### Confirmed mixed-media results
+
+- Input refs are deduplicated by `GalleryItemKey`, retaining first-request
+ order.
+- Image and video names retain their per-kind request order and execute as
+ independent `Promise.allSettled` partitions.
+- Backend success names are intersected with the requested names; malformed or
+ unexpected names confirm nothing.
+- `succeeded` and `failed` are reconstructed in original qualified-ref order,
+ so an image and video with the same name remain independent.
+- A rejected bulk partition confirms none of its requested refs while the
+ independently fulfilled media partition is retained.
+- Affected source/destination board IDs are included only for outcomes with a
+ requested confirmed success, deduplicated, and sorted deterministically.
+ The `none` board is retained.
+- The shared mutation result can carry affected board IDs without weakening
+ its required `succeeded` and `failed` arrays. The public Task 7A API returns
+ affected board IDs as a required array.
+
+### Bounded video movement
+
+- At most four single-video move requests are active at once.
+- A rejected or malformed per-video request remains unconfirmed without
+ converting it into success.
+- Abort stops workers before scheduling another request. Aborted and unstarted
+ refs remain in `failed`.
+- Per-request responses are reduced in input order; transport completion order
+ cannot reorder the domain result.
+
+## Verification
+
+All frontend commands ran from `invokeai/frontend/webv2`.
+
+```sh
+pnpm lint:tsc
+```
+
+```text
+tsc --noEmit: passed
+```
+
+```sh
+pnpm test
+```
+
+```text
+Test Files 376 passed (376)
+Tests 4962 passed (4962)
+```
+
+```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
+```
+
+The final full unit, fixture, and aggregate lint commands were run after the
+worker-loop lint correction.
+
+Browser tests were intentionally not run for this transport/domain-only
+subtask; Task 7A requires proportionate non-UI gates and expressly excludes UI
+and action behavior.
+
+## Self-review
+
+- Confirmed `GeneratedImageContract` and `core/types.ts` are unchanged.
+- Confirmed image-only APIs remain strictly image-name/image typed.
+- Confirmed the diff adds no production module or production file rename.
+- Confirmed no UI, action provider, context menu, hotkey, download, archive, or
+ board UI file changed.
+- Confirmed no cache/Workbench patch, query invalidation, or notification occurs
+ in the backend or domain API.
+- Confirmed no `useEffect`, `@platform/ui` import, migration exception, or
+ performance baseline change was added.
+- Confirmed same-name image/video identity is preserved end to end.
+- Confirmed malformed/unexpected response names and rejected partitions cannot
+ become confirmed successes.
+- Confirmed video board movement has one request per deduplicated video, at
+ most four in flight, and no per-video invalidation or duplicate operation
+ side effect.
+- Confirmed `git diff --check` is clean.
+
+No unresolved Task 7A implementation concern remains. Task 7B owns consuming
+the confirmed arrays to patch/prune state, perform one operation-level
+invalidation, and issue one user notification.
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.ts
index c49f30625e..b2ef8a253b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts
@@ -43,6 +43,8 @@ export interface GalleryItemsPage {
}
export interface GalleryItemMutationResult {
+ /** Boards whose contents/counts changed for at least one confirmed success. */
+ affectedBoardIds?: string[];
failed: GalleryItemRef[];
succeeded: GalleryItemRef[];
}
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index 611edb4ab3..8a6aac006e 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -99,8 +99,8 @@ describe('image mutation outcomes', () => {
it('returns only images confirmed added to or removed from a board', async () => {
mocks.apiFetchJson
- .mockResolvedValueOnce({ added_images: ['moved.png'] })
- .mockResolvedValueOnce({ removed_images: ['removed.png'] });
+ .mockResolvedValueOnce({ added_images: ['moved.png'], affected_boards: ['board-1', 'none'] })
+ .mockResolvedValueOnce({ affected_boards: ['board-1', 'none'], removed_images: ['removed.png'] });
await expect(addImagesToGalleryBoard('board-1', ['moved.png', 'locked.png'])).resolves.toEqual(['moved.png']);
await expect(removeImagesFromGalleryBoard(['removed.png', 'locked.png'])).resolves.toEqual(['removed.png']);
@@ -108,8 +108,8 @@ describe('image mutation outcomes', () => {
it('returns only images confirmed starred or unstarred', async () => {
mocks.apiFetchJson
- .mockResolvedValueOnce({ starred_images: ['starred.png'] })
- .mockResolvedValueOnce({ unstarred_images: ['unstarred.png'] });
+ .mockResolvedValueOnce({ affected_boards: ['board-1'], starred_images: ['starred.png'] })
+ .mockResolvedValueOnce({ affected_boards: ['board-1'], unstarred_images: ['unstarred.png'] });
await expect(starGalleryImages(['starred.png', 'locked.png'])).resolves.toEqual(['starred.png']);
await expect(unstarGalleryImages(['unstarred.png', 'locked.png'])).resolves.toEqual(['unstarred.png']);
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index f550595bc1..e3e9bfb791 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -906,77 +906,157 @@ export const deleteGalleryBoard = async (
};
};
-export const addImagesToGalleryBoard = async (
+export interface GalleryItemOrganizationTransportResult {
+ affectedBoardIds: string[];
+ succeededNames: string[];
+}
+
+interface GalleryImageDeleteTransportResult extends GalleryItemOrganizationTransportResult {
+ failedNames: string[];
+}
+
+const getRequiredStringArray = (body: unknown, field: string): string[] => {
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ throw new TypeError(`Gallery mutation response must be an object with "${field}".`);
+ }
+
+ const value = Reflect.get(body, field);
+
+ if (!Array.isArray(value) || !value.every((item): item is string => typeof item === 'string' && item.length > 0)) {
+ throw new TypeError(`Gallery mutation response field "${field}" must be an array of non-empty strings.`);
+ }
+
+ return value;
+};
+
+const getOptionalStringArray = (body: unknown, field: string): string[] => {
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
+ throw new TypeError(`Gallery mutation response must be an object.`);
+ }
+
+ const value = Reflect.get(body, field);
+
+ if (value === undefined) {
+ return [];
+ }
+ if (!Array.isArray(value) || !value.every((item): item is string => typeof item === 'string' && item.length > 0)) {
+ throw new TypeError(`Gallery mutation response field "${field}" must be an array of non-empty strings.`);
+ }
+
+ return value;
+};
+
+const mapGalleryItemOrganizationTransportResult = (
+ body: unknown,
+ succeededField: string
+): GalleryItemOrganizationTransportResult => ({
+ affectedBoardIds: getRequiredStringArray(body, 'affected_boards'),
+ succeededNames: getRequiredStringArray(body, succeededField),
+});
+
+const emptyGalleryItemOrganizationTransportResult = (): GalleryItemOrganizationTransportResult => ({
+ affectedBoardIds: [],
+ succeededNames: [],
+});
+
+const isInvalidGalleryBoardDestination = (boardId: string): boolean =>
+ boardId === 'generated' || boardId === 'assets' || isDateBoardId(boardId);
+
+export const addGalleryImageItemsToBoard = async (
boardId: string,
imageNames: string[],
signal?: AbortSignal
-): Promise<string[]> => {
- if (
- boardId === 'none' ||
- boardId === 'generated' ||
- boardId === 'assets' ||
- isDateBoardId(boardId) ||
- imageNames.length === 0
- ) {
- return [];
+): Promise<GalleryItemOrganizationTransportResult> => {
+ if (boardId === 'none' || isInvalidGalleryBoardDestination(boardId) || imageNames.length === 0) {
+ return emptyGalleryItemOrganizationTransportResult();
}
- const body = await apiFetchJson<{ added_images: string[] }>('/api/v1/board_images/batch', {
+ signal?.throwIfAborted();
+ const body = await apiFetchJson<unknown>('/api/v1/board_images/batch', {
body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
method: 'POST',
signal,
});
+ signal?.throwIfAborted();
- return body.added_images;
+ return mapGalleryItemOrganizationTransportResult(body, 'added_images');
};
-export const removeImagesFromGalleryBoard = async (imageNames: string[], signal?: AbortSignal): Promise<string[]> => {
+export const addImagesToGalleryBoard = async (
+ boardId: string,
+ imageNames: string[],
+ signal?: AbortSignal
+): Promise<string[]> => (await addGalleryImageItemsToBoard(boardId, imageNames, signal)).succeededNames;
+
+export const removeGalleryImageItemsFromBoard = async (
+ imageNames: string[],
+ signal?: AbortSignal
+): Promise<GalleryItemOrganizationTransportResult> => {
if (imageNames.length === 0) {
- return [];
+ return emptyGalleryItemOrganizationTransportResult();
}
- const body = await apiFetchJson<{ removed_images: string[] }>('/api/v1/board_images/batch/delete', {
+ signal?.throwIfAborted();
+ const body = await apiFetchJson<unknown>('/api/v1/board_images/batch/delete', {
body: JSON.stringify({ image_names: imageNames }),
method: 'POST',
signal,
});
+ signal?.throwIfAborted();
- return body.removed_images;
+ return mapGalleryItemOrganizationTransportResult(body, 'removed_images');
};
-const setGalleryImagesStarred = async (
+export const removeImagesFromGalleryBoard = async (imageNames: string[], signal?: AbortSignal): Promise<string[]> =>
+ (await removeGalleryImageItemsFromBoard(imageNames, signal)).succeededNames;
+
+export const setGalleryImageItemsStarred = async (
imageNames: string[],
starred: boolean,
signal?: AbortSignal
-): Promise<string[]> => {
+): Promise<GalleryItemOrganizationTransportResult> => {
if (imageNames.length === 0) {
- return [];
+ return emptyGalleryItemOrganizationTransportResult();
}
- const body = await apiFetchJson<{ starred_images?: string[]; unstarred_images?: string[] }>(
- `/api/v1/images/${starred ? 'star' : 'unstar'}`,
- {
- body: JSON.stringify({ image_names: imageNames }),
- method: 'POST',
- signal,
- }
- );
+ signal?.throwIfAborted();
+ const body = await apiFetchJson<unknown>(`/api/v1/images/${starred ? 'star' : 'unstar'}`, {
+ body: JSON.stringify({ image_names: imageNames }),
+ method: 'POST',
+ signal,
+ });
+ signal?.throwIfAborted();
- return (starred ? body.starred_images : body.unstarred_images) ?? [];
+ return mapGalleryItemOrganizationTransportResult(body, starred ? 'starred_images' : 'unstarred_images');
};
export const starGalleryImages = (imageNames: string[], signal?: AbortSignal): Promise<string[]> =>
- setGalleryImagesStarred(imageNames, true, signal);
+ setGalleryImageItemsStarred(imageNames, true, signal).then((result) => result.succeededNames);
export const unstarGalleryImages = (imageNames: string[], signal?: AbortSignal): Promise<string[]> =>
- setGalleryImagesStarred(imageNames, false, signal);
+ setGalleryImageItemsStarred(imageNames, false, signal).then((result) => result.succeededNames);
-interface DeleteImagesResponse {
- deleted_images: string[];
- /** Names the backend could not delete. Absent on backends predating partial-failure reporting. */
- failed_images?: string[];
- affected_boards: string[];
-}
+export const deleteGalleryImageItems = async (
+ imageNames: string[],
+ signal?: AbortSignal
+): Promise<GalleryImageDeleteTransportResult> => {
+ if (imageNames.length === 0) {
+ return { ...emptyGalleryItemOrganizationTransportResult(), failedNames: [] };
+ }
+
+ signal?.throwIfAborted();
+ const body = await apiFetchJson<unknown>('/api/v1/images/delete', {
+ body: JSON.stringify({ image_names: imageNames }),
+ method: 'POST',
+ signal,
+ });
+ signal?.throwIfAborted();
+
+ return {
+ ...mapGalleryItemOrganizationTransportResult(body, 'deleted_images'),
+ failedNames: getOptionalStringArray(body, 'failed_images'),
+ };
+};
/**
* Deletes images and reports the outcome per name.
@@ -990,20 +1070,123 @@ export const deleteGalleryImages = async (
imageNames: string[],
signal?: AbortSignal
): Promise<GalleryDeletionResult> => {
- if (imageNames.length === 0) {
- return { deletedImageNames: [], failedImageNames: [] };
+ const result = await deleteGalleryImageItems(imageNames, signal);
+
+ return {
+ deletedImageNames: result.succeededNames,
+ failedImageNames: result.failedNames,
+ };
+};
+
+const mutateGalleryVideoItems = async (
+ videoNames: string[],
+ operation: 'delete' | 'star' | 'unstar',
+ succeededField: 'deleted_videos' | 'starred_videos' | 'unstarred_videos',
+ signal?: AbortSignal
+): Promise<GalleryItemOrganizationTransportResult> => {
+ if (videoNames.length === 0) {
+ return emptyGalleryItemOrganizationTransportResult();
}
- const body = await apiFetchJson<DeleteImagesResponse>('/api/v1/images/delete', {
- body: JSON.stringify({ image_names: imageNames }),
+ signal?.throwIfAborted();
+ const body = await apiFetchJson<unknown>(`/api/v1/videos/${operation}`, {
+ body: JSON.stringify({ video_names: videoNames }),
method: 'POST',
signal,
});
+ signal?.throwIfAborted();
- return {
- deletedImageNames: body.deleted_images,
- failedImageNames: body.failed_images ?? [],
+ return mapGalleryItemOrganizationTransportResult(body, succeededField);
+};
+
+export const deleteGalleryVideoItems = (
+ videoNames: string[],
+ signal?: AbortSignal
+): Promise<GalleryItemOrganizationTransportResult> =>
+ mutateGalleryVideoItems(videoNames, 'delete', 'deleted_videos', signal);
+
+export const setGalleryVideoItemsStarred = (
+ videoNames: string[],
+ starred: boolean,
+ signal?: AbortSignal
+): Promise<GalleryItemOrganizationTransportResult> =>
+ mutateGalleryVideoItems(
+ videoNames,
+ starred ? 'star' : 'unstar',
+ starred ? 'starred_videos' : 'unstarred_videos',
+ signal
+ );
+
+const moveGalleryVideoItemToBoard = async (
+ videoName: string,
+ boardId: string,
+ signal?: AbortSignal
+): Promise<GalleryItemOrganizationTransportResult> => {
+ signal?.throwIfAborted();
+ const removing = boardId === 'none';
+ const body = await apiFetchJson<unknown>('/api/v1/videos/board', {
+ body: JSON.stringify(removing ? { video_name: videoName } : { board_id: boardId, video_name: videoName }),
+ method: removing ? 'DELETE' : 'POST',
+ signal,
+ });
+ signal?.throwIfAborted();
+
+ return mapGalleryItemOrganizationTransportResult(body, removing ? 'removed_videos' : 'added_videos');
+};
+
+export const moveGalleryVideoItemsToBoard = async (
+ videoNames: string[],
+ boardId: string,
+ signal?: AbortSignal
+): Promise<GalleryItemOrganizationTransportResult> => {
+ if (videoNames.length === 0 || isInvalidGalleryBoardDestination(boardId)) {
+ return emptyGalleryItemOrganizationTransportResult();
+ }
+
+ const outcomes: (GalleryItemOrganizationTransportResult | undefined)[] = Array.from({
+ length: videoNames.length,
+ });
+ let nextIndex = 0;
+
+ const worker = async (): Promise<void> => {
+ while (true) {
+ if (signal?.aborted) {
+ return;
+ }
+
+ const index = nextIndex;
+ const videoName = videoNames[index];
+
+ if (videoName === undefined) {
+ return;
+ }
+ nextIndex += 1;
+
+ try {
+ outcomes[index] = await moveGalleryVideoItemToBoard(videoName, boardId, signal);
+ } catch {
+ // A rejected single-video request is unconfirmed. Other videos may still
+ // return authoritative successes; abort stops workers before scheduling more.
+ }
+ }
};
+
+ await Promise.all(Array.from({ length: Math.min(4, videoNames.length) }, () => worker()));
+
+ const affectedBoardIds: string[] = [];
+ const succeededNames: string[] = [];
+
+ for (const [index, outcome] of outcomes.entries()) {
+ const videoName = videoNames[index];
+
+ if (!videoName || !outcome?.succeededNames.includes(videoName)) {
+ continue;
+ }
+ succeededNames.push(videoName);
+ affectedBoardIds.push(...outcome.affectedBoardIds);
+ }
+
+ return { affectedBoardIds, succeededNames };
};
const BULK_DOWNLOAD_POLL_INTERVAL_MS = 2000;
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
new file mode 100644
index 0000000000..1613ecca68
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
@@ -0,0 +1,340 @@
+import type { GalleryItemRef } from '@features/gallery/core/items';
+
+import { galleryItemOrganization } from '@features/gallery/index';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const MockApiError = vi.hoisted(
+ () =>
+ class ApiError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.status = status;
+ }
+ }
+);
+
+const mocks = vi.hoisted(() => ({
+ apiFetchJson: vi.fn(),
+}));
+
+vi.mock('@platform/transport/http', () => ({
+ absolutizeApiUrl: (url: string) => `https://api.test${url}`,
+ ApiError: MockApiError,
+ apiFetch: vi.fn(),
+ apiFetchJson: mocks.apiFetchJson,
+ apiFetchRaw: vi.fn(),
+ sleep: vi.fn(),
+}));
+
+const imageRef = (name: string): GalleryItemRef => ({ kind: 'image', name });
+const videoRef = (name: string): GalleryItemRef => ({ kind: 'video', name });
+
+describe('galleryItemOrganization transport and confirmed outcomes', () => {
+ beforeEach(() => {
+ mocks.apiFetchJson.mockReset();
+ });
+
+ it('stars an image-only request and returns its affected board', async () => {
+ const controller = new AbortController();
+ mocks.apiFetchJson.mockResolvedValue({
+ affected_boards: ['board-image'],
+ starred_images: ['still.png'],
+ });
+
+ await expect(galleryItemOrganization.setStarred([imageRef('still.png')], true, controller.signal)).resolves.toEqual(
+ {
+ affectedBoardIds: ['board-image'],
+ failed: [],
+ succeeded: [imageRef('still.png')],
+ }
+ );
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/images/star', {
+ body: JSON.stringify({ image_names: ['still.png'] }),
+ method: 'POST',
+ signal: controller.signal,
+ });
+ });
+
+ it('uses the video bulk star, unstar, and delete DTOs without inferring success', async () => {
+ mocks.apiFetchJson
+ .mockResolvedValueOnce({ affected_boards: ['board-a'], starred_videos: ['clip.mp4'] })
+ .mockResolvedValueOnce({ affected_boards: ['board-a'], unstarred_videos: ['clip.mp4'] })
+ .mockResolvedValueOnce({
+ affected_boards: ['board-a'],
+ deleted_videos: ['clip.mp4'],
+ failed_videos: [],
+ });
+
+ await expect(galleryItemOrganization.setStarred([videoRef('clip.mp4')], true)).resolves.toMatchObject({
+ failed: [],
+ succeeded: [videoRef('clip.mp4')],
+ });
+ await expect(galleryItemOrganization.setStarred([videoRef('clip.mp4')], false)).resolves.toMatchObject({
+ failed: [],
+ succeeded: [videoRef('clip.mp4')],
+ });
+ await expect(galleryItemOrganization.delete([videoRef('clip.mp4')])).resolves.toEqual({
+ affectedBoardIds: ['board-a'],
+ failed: [],
+ succeeded: [videoRef('clip.mp4')],
+ });
+
+ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(1, '/api/v1/videos/star', {
+ body: JSON.stringify({ video_names: ['clip.mp4'] }),
+ method: 'POST',
+ signal: undefined,
+ });
+ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/videos/unstar', {
+ body: JSON.stringify({ video_names: ['clip.mp4'] }),
+ method: 'POST',
+ signal: undefined,
+ });
+ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(3, '/api/v1/videos/delete', {
+ body: JSON.stringify({ video_names: ['clip.mp4'] }),
+ method: 'POST',
+ signal: undefined,
+ });
+ });
+
+ it('isolates same-name media, deduplicates keys, intersects successes, and preserves request order', async () => {
+ const refs = [
+ videoRef('shared'),
+ imageRef('locked.png'),
+ imageRef('shared'),
+ videoRef('later.mp4'),
+ videoRef('shared'),
+ imageRef('shared'),
+ ];
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url === '/api/v1/images/star') {
+ return Promise.resolve({
+ affected_boards: ['none', 'board-image', 'none'],
+ starred_images: ['unexpected.png', 'shared'],
+ });
+ }
+
+ return Promise.resolve({
+ affected_boards: ['board-video', 'none'],
+ starred_videos: ['later.mp4', 'unexpected.mp4', 'shared'],
+ });
+ });
+
+ await expect(galleryItemOrganization.setStarred(refs, true)).resolves.toEqual({
+ affectedBoardIds: ['board-image', 'board-video', 'none'],
+ failed: [imageRef('locked.png')],
+ succeeded: [videoRef('shared'), imageRef('shared'), videoRef('later.mp4')],
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[0]?.[1]?.body))).toEqual({
+ image_names: ['locked.png', 'shared'],
+ });
+ expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[1]?.[1]?.body))).toEqual({
+ video_names: ['shared', 'later.mp4'],
+ });
+ });
+
+ it('keeps a fulfilled video delete partition when the image partition rejects', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url === '/api/v1/images/delete') {
+ return Promise.reject(new TypeError('image network failed'));
+ }
+
+ return Promise.resolve({
+ affected_boards: ['board-video'],
+ deleted_videos: ['gone.mp4'],
+ failed_videos: ['locked.mp4'],
+ });
+ });
+
+ await expect(
+ galleryItemOrganization.delete([imageRef('gone.png'), videoRef('gone.mp4'), videoRef('locked.mp4')])
+ ).resolves.toEqual({
+ affectedBoardIds: ['board-video'],
+ failed: [imageRef('gone.png'), videoRef('locked.mp4')],
+ succeeded: [videoRef('gone.mp4')],
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ });
+
+ it('moves mixed media to a real board once per deduplicated item and ignores unconfirmed response effects', async () => {
+ const refs = [imageRef('still.png'), videoRef('one.mp4'), videoRef('one.mp4'), videoRef('locked.mp4')];
+ mocks.apiFetchJson.mockImplementation((url: string, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body)) as { image_names?: string[]; video_name?: string };
+
+ if (url === '/api/v1/board_images/batch') {
+ return Promise.resolve({
+ added_images: ['still.png'],
+ affected_boards: ['source-image', 'destination'],
+ });
+ }
+ if (body.video_name === 'one.mp4') {
+ return Promise.resolve({
+ added_videos: ['one.mp4'],
+ affected_boards: ['source-video', 'destination'],
+ });
+ }
+
+ return Promise.resolve({
+ added_videos: ['unexpected.mp4'],
+ affected_boards: ['must-not-be-reported'],
+ });
+ });
+
+ await expect(galleryItemOrganization.moveToBoard(refs, 'destination')).resolves.toEqual({
+ affectedBoardIds: ['destination', 'source-image', 'source-video'],
+ failed: [videoRef('locked.mp4')],
+ succeeded: [imageRef('still.png'), videoRef('one.mp4')],
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(3);
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/board_images/batch', {
+ body: JSON.stringify({ board_id: 'destination', image_names: ['still.png'] }),
+ method: 'POST',
+ signal: undefined,
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/videos/board', {
+ body: JSON.stringify({ board_id: 'destination', video_name: 'one.mp4' }),
+ method: 'POST',
+ signal: undefined,
+ });
+ });
+
+ it('removes images and videos to none with the distinct remove endpoints', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url === '/api/v1/board_images/batch/delete') {
+ return Promise.resolve({
+ affected_boards: ['source-image', 'none'],
+ removed_images: ['still.png'],
+ });
+ }
+
+ return Promise.resolve({
+ affected_boards: ['none', 'source-video'],
+ removed_videos: ['clip.mp4'],
+ });
+ });
+
+ await expect(
+ galleryItemOrganization.moveToBoard([videoRef('clip.mp4'), imageRef('still.png')], 'none')
+ ).resolves.toEqual({
+ affectedBoardIds: ['none', 'source-image', 'source-video'],
+ failed: [],
+ succeeded: [videoRef('clip.mp4'), imageRef('still.png')],
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/board_images/batch/delete', {
+ body: JSON.stringify({ image_names: ['still.png'] }),
+ method: 'POST',
+ signal: undefined,
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/videos/board', {
+ body: JSON.stringify({ video_name: 'clip.mp4' }),
+ method: 'DELETE',
+ signal: undefined,
+ });
+ });
+
+ it('limits video board movement to four requests in flight', async () => {
+ const refs = Array.from({ length: 9 }, (_, index) => videoRef(`clip-${index}.mp4`));
+ const releases: (() => void)[] = [];
+ let active = 0;
+ let maxActive = 0;
+ let started = 0;
+
+ mocks.apiFetchJson.mockImplementation((_url: string, init?: RequestInit) => {
+ const { video_name: videoName } = JSON.parse(String(init?.body)) as { video_name: string };
+ active += 1;
+ started += 1;
+ maxActive = Math.max(maxActive, active);
+
+ return new Promise((resolve) => {
+ releases.push(() => {
+ active -= 1;
+ resolve({
+ added_videos: [videoName],
+ affected_boards: ['destination'],
+ });
+ });
+ });
+ });
+
+ const movement = galleryItemOrganization.moveToBoard(refs, 'destination');
+
+ while (started < refs.length) {
+ await vi.waitFor(() => {
+ expect(releases.length).toBeGreaterThan(0);
+ });
+ releases.shift()?.();
+ await Promise.resolve();
+ }
+ while (releases.length > 0) {
+ releases.shift()?.();
+ }
+
+ await expect(movement).resolves.toEqual({
+ affectedBoardIds: ['destination'],
+ failed: [],
+ succeeded: refs,
+ });
+ expect(maxActive).toBe(4);
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(refs.length);
+ });
+
+ it('stops scheduling video moves after abort and leaves aborted or unstarted refs unconfirmed', async () => {
+ const controller = new AbortController();
+ const refs = Array.from({ length: 8 }, (_, index) => videoRef(`clip-${index}.mp4`));
+
+ mocks.apiFetchJson.mockImplementation((_url: string, init?: RequestInit) => {
+ const signal = init?.signal;
+ if (!signal) {
+ throw new Error('Expected the caller abort signal');
+ }
+
+ return new Promise((_resolve, reject) => {
+ const rejectAborted = () => reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
+
+ if (signal.aborted) {
+ rejectAborted();
+ return;
+ }
+ signal.addEventListener('abort', rejectAborted, { once: true });
+ });
+ });
+
+ const movement = galleryItemOrganization.moveToBoard(refs, 'destination', controller.signal);
+
+ await vi.waitFor(() => {
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(4);
+ });
+ controller.abort(new DOMException('Stopped', 'AbortError'));
+
+ await expect(movement).resolves.toEqual({
+ affectedBoardIds: [],
+ failed: refs,
+ succeeded: [],
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(4);
+ });
+
+ it.each([
+ { affected_boards: ['board-a'], starred_videos: 'clip.mp4' },
+ { affected_boards: ['unexpected-board'], starred_videos: ['unexpected.mp4'] },
+ ])('does not confirm malformed or unexpected video success payloads: $starred_videos', async (response) => {
+ mocks.apiFetchJson.mockResolvedValue(response);
+
+ await expect(galleryItemOrganization.setStarred([videoRef('clip.mp4')], true)).resolves.toEqual({
+ affectedBoardIds: [],
+ failed: [videoRef('clip.mp4')],
+ succeeded: [],
+ });
+ });
+
+ it('does not issue transport requests for an empty operation', async () => {
+ await expect(galleryItemOrganization.delete([])).resolves.toEqual({
+ affectedBoardIds: [],
+ failed: [],
+ succeeded: [],
+ });
+ expect(mocks.apiFetchJson).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/index.ts b/invokeai/frontend/webv2/src/features/gallery/index.ts
index fd41934c28..65459a1b9d 100644
--- a/invokeai/frontend/webv2/src/features/gallery/index.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/index.ts
@@ -30,8 +30,17 @@ export {
type GalleryVideoItem,
} from './core/items';
import {
+ toGalleryItemKey as getGalleryItemKey,
+ type GalleryItemKind as ItemKind,
+ type GalleryItemMutationResult as ItemMutationResult,
+ type GalleryItemRef as ItemRef,
+} from './core/items';
+import {
+ addGalleryImageItemsToBoard,
addImagesToGalleryBoard,
+ deleteGalleryImageItems,
deleteGalleryImages,
+ deleteGalleryVideoItems,
downloadGalleryArchive,
getGalleryImageByName,
getGalleryImageMetadata,
@@ -43,9 +52,14 @@ import {
listGalleryBoards,
makeImageCanvasAsset,
makeImageDurable,
+ moveGalleryVideoItemsToBoard,
+ removeGalleryImageItemsFromBoard,
removeImagesFromGalleryBoard,
saveImageToGallery,
+ setGalleryImageItemsStarred,
+ setGalleryVideoItemsStarred,
starGalleryImages,
+ type GalleryItemOrganizationTransportResult,
unstarGalleryImages,
uploadGalleryImage,
} from './data/backend';
@@ -91,6 +105,143 @@ export const galleryOrganization = {
starred ? starGalleryImages(imageNames, signal) : unstarGalleryImages(imageNames, signal),
} as const;
+type ConfirmedGalleryItemMutationResult = ItemMutationResult & { affectedBoardIds: string[] };
+
+type GalleryItemPartitionMutation = (
+ names: string[],
+ signal?: AbortSignal
+) => Promise<GalleryItemOrganizationTransportResult>;
+
+const emptyGalleryItemTransportResult = (): GalleryItemOrganizationTransportResult => ({
+ affectedBoardIds: [],
+ succeededNames: [],
+});
+
+const deduplicateGalleryItemRefs = (refs: readonly ItemRef[]): ItemRef[] => {
+ const keys = new Set<string>();
+ const unique: ItemRef[] = [];
+
+ for (const ref of refs) {
+ const key = getGalleryItemKey(ref);
+
+ if (keys.has(key)) {
+ continue;
+ }
+ keys.add(key);
+ unique.push(ref);
+ }
+
+ return unique;
+};
+
+const addConfirmedPartition = ({
+ affectedBoardIds,
+ confirmedKeys,
+ kind,
+ names,
+ outcome,
+}: {
+ affectedBoardIds: Set<string>;
+ confirmedKeys: Set<string>;
+ kind: ItemKind;
+ names: string[];
+ outcome: PromiseSettledResult<GalleryItemOrganizationTransportResult>;
+}): void => {
+ if (outcome.status === 'rejected') {
+ return;
+ }
+
+ const requestedNames = new Set(names);
+ let hasConfirmedSuccess = false;
+
+ for (const name of outcome.value.succeededNames) {
+ if (!requestedNames.has(name)) {
+ continue;
+ }
+ confirmedKeys.add(getGalleryItemKey({ kind, name }));
+ hasConfirmedSuccess = true;
+ }
+
+ if (!hasConfirmedSuccess) {
+ return;
+ }
+ for (const boardId of outcome.value.affectedBoardIds) {
+ affectedBoardIds.add(boardId);
+ }
+};
+
+const mutateGalleryItems = async (
+ refs: readonly ItemRef[],
+ imageMutation: GalleryItemPartitionMutation,
+ videoMutation: GalleryItemPartitionMutation,
+ signal?: AbortSignal
+): Promise<ConfirmedGalleryItemMutationResult> => {
+ const requested = deduplicateGalleryItemRefs(refs);
+ const imageNames = requested.filter((ref) => ref.kind === 'image').map((ref) => ref.name);
+ const videoNames = requested.filter((ref) => ref.kind === 'video').map((ref) => ref.name);
+ const [imageOutcome, videoOutcome] = await Promise.allSettled([
+ imageNames.length > 0 ? imageMutation(imageNames, signal) : Promise.resolve(emptyGalleryItemTransportResult()),
+ videoNames.length > 0 ? videoMutation(videoNames, signal) : Promise.resolve(emptyGalleryItemTransportResult()),
+ ]);
+ const affectedBoardIds = new Set<string>();
+ const confirmedKeys = new Set<string>();
+
+ addConfirmedPartition({
+ affectedBoardIds,
+ confirmedKeys,
+ kind: 'image',
+ names: imageNames,
+ outcome: imageOutcome,
+ });
+ addConfirmedPartition({
+ affectedBoardIds,
+ confirmedKeys,
+ kind: 'video',
+ names: videoNames,
+ outcome: videoOutcome,
+ });
+
+ return {
+ affectedBoardIds: [...affectedBoardIds].sort(),
+ failed: requested.filter((ref) => !confirmedKeys.has(getGalleryItemKey(ref))),
+ succeeded: requested.filter((ref) => confirmedKeys.has(getGalleryItemKey(ref))),
+ };
+};
+
+/**
+ * Mixed-media organization transport. Results contain only backend-confirmed
+ * refs and do not patch caches, invalidate queries, or notify.
+ */
+export const galleryItemOrganization = {
+ delete: (refs: readonly ItemRef[], signal?: AbortSignal): Promise<ConfirmedGalleryItemMutationResult> =>
+ mutateGalleryItems(refs, deleteGalleryImageItems, deleteGalleryVideoItems, signal),
+ moveToBoard: (
+ refs: readonly ItemRef[],
+ boardId: string,
+ signal?: AbortSignal
+ ): Promise<ConfirmedGalleryItemMutationResult> =>
+ mutateGalleryItems(
+ refs,
+ (names, requestSignal) =>
+ boardId === 'none'
+ ? removeGalleryImageItemsFromBoard(names, requestSignal)
+ : addGalleryImageItemsToBoard(boardId, names, requestSignal),
+ (names, requestSignal) => moveGalleryVideoItemsToBoard(names, boardId, requestSignal),
+ signal
+ ),
+ setStarred: (
+ refs: readonly ItemRef[],
+ starred: boolean,
+ signal?: AbortSignal
+ ): Promise<ConfirmedGalleryItemMutationResult> =>
+ mutateGalleryItems(
+ refs,
+ (names, requestSignal) => setGalleryImageItemsStarred(names, starred, requestSignal),
+ (names, requestSignal) => setGalleryVideoItemsStarred(names, starred, requestSignal),
+ signal
+ ),
+} as const;
+
/** Destination choices for callers such as Workflow fields. */
export const galleryDestinations = {
list: listGalleryBoards,