Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): harden mixed gallery organization transport

joshistoastf46d33e3b571
diff --git a/.superpowers/sdd/mixed-media-gallery-parity/task-7a-report.md b/.superpowers/sdd/mixed-media-gallery-parity/task-7a-report.md
index 6221656006..32933f0b2f 100644
--- a/.superpowers/sdd/mixed-media-gallery-parity/task-7a-report.md
+++ b/.superpowers/sdd/mixed-media-gallery-parity/task-7a-report.md
@@ -179,6 +179,140 @@ and action behavior.
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.
+Task 7B owns consuming the confirmed arrays to patch/prune state, perform one
+operation-level invalidation, and issue one user notification. The subsequent
+independent review and Task 7A fix round are recorded below.
+
+## Independent review fix round
+
+An independent review of `35bf5e98ae` found two transport-boundary gaps:
+
+1. Bulk video delete/star/unstar accepted a success array without validating
+ the backend-required `failed_videos` array.
+2. The bounded video-board worker treated authentication, identity-expiry, and
+ abort failures like isolated item failures, allowing later index claims and
+ potentially retaining video successes from a stale identity lifetime.
+
+### Fix-round RED
+
+The focused organization run after adding the malformed DTO and fatal
+concurrency regressions was:
+
+```sh
+pnpm test src/features/gallery/data/organization.test.ts
+```
+
+```text
+Test Files 1 failed (1)
+Tests 9 failed | 13 passed (22)
+```
+
+Six failures showed that missing or wrong-type `failed_videos` still confirmed
+the requested video across star, unstar, and delete. Two failures showed HTTP
+401 and `HttpRequestIdentityExpiredError` were swallowed: all remaining video
+requests were scheduled and their successes retained. The ninth showed that
+an omitted caller signal did not bind movement to the captured account
+lifetime, so account rotation scheduled eight requests instead of stopping at
+the four already in flight.
+
+### Fix-round implementation
+
+- Added a strict bulk-video result mapper that requires arrays containing only
+ non-empty strings for the operation success field, `affected_boards`, and
+ `failed_videos`.
+- Captured the account scope at the start of video board movement and composed
+ its lifetime signal with an optional caller signal.
+- Added one shared fatal sentinel checked synchronously before every worker
+ index claim.
+- Classified caller/account abort, `AccountScopeExpiredError`,
+ `HttpRequestIdentityExpiredError`, and HTTP 401 as partition-fatal.
+- A fatal outcome rejects the video partition after the current workers settle,
+ so the outer `Promise.allSettled` orchestration confirms no video refs while
+ retaining an independently completed image partition.
+- Kept ordinary HTTP 403/500 and malformed per-item move responses isolated to
+ their requested video; later video requests still run and may confirm.
+
+### Fix-round GREEN and full verification
+
+All commands ran from `invokeai/frontend/webv2` on the final formatted tree.
+
+```sh
+pnpm test src/features/gallery/data/organization.test.ts
+```
+
+```text
+Test Files 1 passed (1)
+Tests 22 passed (22)
+```
+
+```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 82 passed (82)
+```
+
+```sh
+pnpm test
+```
+
+```text
+Test Files 376 passed (376)
+Tests 4973 passed (4973)
+```
+
+```sh
+pnpm test:fixtures
+```
+
+```text
+Tests 4 passed (4)
+```
+
+```sh
+pnpm lint:tsc
+```
+
+```text
+tsc --noEmit: passed
+```
+
+```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 first aggregate lint attempt stopped only on formatting in the expanded
+organization test. The repository formatter was applied to that test, then
+the focused suite, full unit suite, fixtures, and aggregate lint were all run
+again with the final counts above.
+
+### Fix-round self-review
+
+- Confirmed malformed bulk video results cannot contribute successes or
+ affected board IDs.
+- Confirmed fatal 401/identity/account/abort outcomes stop new claims and reject
+ the complete video partition.
+- Confirmed an already completed image partition remains independently
+ confirmable through the existing settled orchestration.
+- Confirmed ordinary 403/500 move failures remain item-local and do not stop
+ later video work.
+- Confirmed every video board request is account-lifetime-scoped even when the
+ caller omits a signal.
+- Confirmed Task 7A still performs no cache patch, invalidation, notification,
+ UI/action, or download work.
+- Confirmed no production module, `useEffect`, `@platform/ui` importer,
+ migration exception, or baseline change was added.
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index e3e9bfb791..b157086e1f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -19,8 +19,19 @@ import type {
} from '@features/gallery/core/types';
import { isTimestampInRange } from '@platform/search/dateTokens';
-import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
-import { absolutizeApiUrl, ApiError, apiFetchJson, apiFetchRaw, sleep } from '@platform/transport/http';
+import {
+ AccountScopeExpiredError,
+ assertAccountScopeCurrent,
+ captureAccountScope,
+} from '@platform/state/accountLifecycle';
+import {
+ absolutizeApiUrl,
+ ApiError,
+ apiFetchJson,
+ apiFetchRaw,
+ HttpRequestIdentityExpiredError,
+ sleep,
+} from '@platform/transport/http';
import { getGalleryImageThumbnailUrl } from './imageUrls';
import { getGalleryVideoThumbnailUrl } from './videoUrls';
@@ -954,6 +965,17 @@ const mapGalleryItemOrganizationTransportResult = (
succeededNames: getRequiredStringArray(body, succeededField),
});
+const mapGalleryVideoOrganizationTransportResult = (
+ body: unknown,
+ succeededField: string
+): GalleryItemOrganizationTransportResult => {
+ const result = mapGalleryItemOrganizationTransportResult(body, succeededField);
+
+ getRequiredStringArray(body, 'failed_videos');
+
+ return result;
+};
+
const emptyGalleryItemOrganizationTransportResult = (): GalleryItemOrganizationTransportResult => ({
affectedBoardIds: [],
succeededNames: [],
@@ -1096,7 +1118,7 @@ const mutateGalleryVideoItems = async (
});
signal?.throwIfAborted();
- return mapGalleryItemOrganizationTransportResult(body, succeededField);
+ return mapGalleryVideoOrganizationTransportResult(body, succeededField);
};
export const deleteGalleryVideoItems = (
@@ -1134,6 +1156,13 @@ const moveGalleryVideoItemToBoard = async (
return mapGalleryItemOrganizationTransportResult(body, removing ? 'removed_videos' : 'added_videos');
};
+const isFatalGalleryVideoMoveError = (error: unknown, signal: AbortSignal): boolean =>
+ signal.aborted ||
+ error instanceof AccountScopeExpiredError ||
+ error instanceof HttpRequestIdentityExpiredError ||
+ (error instanceof ApiError && error.status === 401) ||
+ (error instanceof Error && error.name === 'AbortError');
+
export const moveGalleryVideoItemsToBoard = async (
videoNames: string[],
boardId: string,
@@ -1143,36 +1172,69 @@ export const moveGalleryVideoItemsToBoard = async (
return emptyGalleryItemOrganizationTransportResult();
}
+ const owner = captureAccountScope();
+ const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;
const outcomes: (GalleryItemOrganizationTransportResult | undefined)[] = Array.from({
length: videoNames.length,
});
+ const fatalFailure: { error: unknown; occurred: boolean } = { error: undefined, occurred: false };
let nextIndex = 0;
+ const claimNextVideo = (): { index: number; videoName: string } | null => {
+ if (fatalFailure.occurred || requestSignal.aborted) {
+ return null;
+ }
+
+ const index = nextIndex;
+ const videoName = videoNames[index];
+
+ if (videoName === undefined) {
+ return null;
+ }
+ nextIndex += 1;
+
+ return { index, videoName };
+ };
+
const worker = async (): Promise<void> => {
while (true) {
- if (signal?.aborted) {
- return;
- }
+ const claim = claimNextVideo();
- const index = nextIndex;
- const videoName = videoNames[index];
-
- if (videoName === undefined) {
+ if (!claim) {
return;
}
- nextIndex += 1;
try {
- outcomes[index] = await moveGalleryVideoItemToBoard(videoName, boardId, signal);
- } catch {
+ const outcome = await moveGalleryVideoItemToBoard(claim.videoName, boardId, requestSignal);
+
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+ if (fatalFailure.occurred) {
+ return;
+ }
+ outcomes[claim.index] = outcome;
+ } catch (error: unknown) {
+ if (isFatalGalleryVideoMoveError(error, requestSignal)) {
+ if (!fatalFailure.occurred) {
+ fatalFailure.error = requestSignal.aborted ? (requestSignal.reason ?? error) : error;
+ fatalFailure.occurred = true;
+ }
+ return;
+ }
// A rejected single-video request is unconfirmed. Other videos may still
- // return authoritative successes; abort stops workers before scheduling more.
+ // return authoritative successes.
}
}
};
await Promise.all(Array.from({ length: Math.min(4, videoNames.length) }, () => worker()));
+ if (fatalFailure.occurred) {
+ throw fatalFailure.error;
+ }
+ assertAccountScopeCurrent(owner);
+ requestSignal.throwIfAborted();
+
const affectedBoardIds: string[] = [];
const succeededNames: string[] = [];
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
index 1613ecca68..89f00c45b5 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts
@@ -1,6 +1,7 @@
import type { GalleryItemRef } from '@features/gallery/core/items';
import { galleryItemOrganization } from '@features/gallery/index';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const MockApiError = vi.hoisted(
@@ -15,6 +16,16 @@ const MockApiError = vi.hoisted(
}
);
+const MockHttpRequestIdentityExpiredError = vi.hoisted(
+ () =>
+ class HttpRequestIdentityExpiredError extends Error {
+ constructor() {
+ super('The identity lifetime that started this HTTP request is no longer active.');
+ this.name = 'HttpRequestIdentityExpiredError';
+ }
+ }
+);
+
const mocks = vi.hoisted(() => ({
apiFetchJson: vi.fn(),
}));
@@ -25,6 +36,7 @@ vi.mock('@platform/transport/http', () => ({
apiFetch: vi.fn(),
apiFetchJson: mocks.apiFetchJson,
apiFetchRaw: vi.fn(),
+ HttpRequestIdentityExpiredError: MockHttpRequestIdentityExpiredError,
sleep: vi.fn(),
}));
@@ -33,6 +45,7 @@ const videoRef = (name: string): GalleryItemRef => ({ kind: 'video', name });
describe('galleryItemOrganization transport and confirmed outcomes', () => {
beforeEach(() => {
+ accountLifecycle.activate('organization-test-user');
mocks.apiFetchJson.mockReset();
});
@@ -59,8 +72,8 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
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'], failed_videos: [], starred_videos: ['clip.mp4'] })
+ .mockResolvedValueOnce({ affected_boards: ['board-a'], failed_videos: [], unstarred_videos: ['clip.mp4'] })
.mockResolvedValueOnce({
affected_boards: ['board-a'],
deleted_videos: ['clip.mp4'],
@@ -98,6 +111,47 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
});
});
+ it.each([
+ {
+ label: 'star with missing failed_videos',
+ mutate: () => galleryItemOrganization.setStarred([videoRef('clip.mp4')], true),
+ response: { affected_boards: ['board-a'], starred_videos: ['clip.mp4'] },
+ },
+ {
+ label: 'star with wrong-type failed_videos',
+ mutate: () => galleryItemOrganization.setStarred([videoRef('clip.mp4')], true),
+ response: { affected_boards: ['board-a'], failed_videos: 'locked.mp4', starred_videos: ['clip.mp4'] },
+ },
+ {
+ label: 'unstar with missing failed_videos',
+ mutate: () => galleryItemOrganization.setStarred([videoRef('clip.mp4')], false),
+ response: { affected_boards: ['board-a'], unstarred_videos: ['clip.mp4'] },
+ },
+ {
+ label: 'unstar with wrong-type failed_videos',
+ mutate: () => galleryItemOrganization.setStarred([videoRef('clip.mp4')], false),
+ response: { affected_boards: ['board-a'], failed_videos: 'locked.mp4', unstarred_videos: ['clip.mp4'] },
+ },
+ {
+ label: 'delete with missing failed_videos',
+ mutate: () => galleryItemOrganization.delete([videoRef('clip.mp4')]),
+ response: { affected_boards: ['board-a'], deleted_videos: ['clip.mp4'] },
+ },
+ {
+ label: 'delete with wrong-type failed_videos',
+ mutate: () => galleryItemOrganization.delete([videoRef('clip.mp4')]),
+ response: { affected_boards: ['board-a'], deleted_videos: ['clip.mp4'], failed_videos: 'locked.mp4' },
+ },
+ ])('does not confirm a video bulk success for $label', async ({ mutate, response }) => {
+ mocks.apiFetchJson.mockResolvedValue(response);
+
+ await expect(mutate()).resolves.toEqual({
+ affectedBoardIds: [],
+ failed: [videoRef('clip.mp4')],
+ succeeded: [],
+ });
+ });
+
it('isolates same-name media, deduplicates keys, intersects successes, and preserves request order', async () => {
const refs = [
videoRef('shared'),
@@ -117,6 +171,7 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
return Promise.resolve({
affected_boards: ['board-video', 'none'],
+ failed_videos: [],
starred_videos: ['later.mp4', 'unexpected.mp4', 'shared'],
});
});
@@ -196,7 +251,7 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/videos/board', {
body: JSON.stringify({ board_id: 'destination', video_name: 'one.mp4' }),
method: 'POST',
- signal: undefined,
+ signal: expect.any(AbortSignal),
});
});
@@ -230,7 +285,7 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/videos/board', {
body: JSON.stringify({ video_name: 'clip.mp4' }),
method: 'DELETE',
- signal: undefined,
+ signal: expect.any(AbortSignal),
});
});
@@ -280,6 +335,149 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
expect(mocks.apiFetchJson).toHaveBeenCalledTimes(refs.length);
});
+ it.each([
+ {
+ error: () => new MockApiError('Unauthorized', 401),
+ label: 'HTTP 401',
+ },
+ {
+ error: () => new MockHttpRequestIdentityExpiredError(),
+ label: 'expired HTTP identity',
+ },
+ ])(
+ 'stops scheduling after fatal $label and discards all video outcomes while retaining the image partition',
+ async ({ error }) => {
+ const refs = [imageRef('still.png'), ...Array.from({ length: 8 }, (_, index) => videoRef(`clip-${index}.mp4`))];
+ const initialVideoReleases: (() => void)[] = [];
+ let rejectFatal: ((error: unknown) => void) | undefined;
+ let videoRequests = 0;
+
+ mocks.apiFetchJson.mockImplementation((url: string, init?: RequestInit) => {
+ if (url === '/api/v1/board_images/batch') {
+ return Promise.resolve({
+ added_images: ['still.png'],
+ affected_boards: ['source-image', 'destination'],
+ });
+ }
+
+ const { video_name: videoName } = JSON.parse(String(init?.body)) as { video_name: string };
+ const videoIndex = Number(videoName.slice('clip-'.length, -'.mp4'.length));
+
+ videoRequests += 1;
+
+ if (videoIndex === 0) {
+ return new Promise((_resolve, reject) => {
+ rejectFatal = reject;
+ });
+ }
+ if (videoIndex < 4) {
+ return new Promise((resolve) => {
+ initialVideoReleases.push(() => {
+ resolve({
+ added_videos: [videoName],
+ affected_boards: ['source-video', 'destination'],
+ });
+ });
+ });
+ }
+
+ return Promise.resolve({
+ added_videos: [videoName],
+ affected_boards: ['must-not-be-reported'],
+ });
+ });
+
+ const movement = galleryItemOrganization.moveToBoard(refs, 'destination');
+
+ await vi.waitFor(() => {
+ expect(videoRequests).toBe(4);
+ expect(rejectFatal).toBeDefined();
+ expect(initialVideoReleases).toHaveLength(3);
+ });
+ rejectFatal?.(error());
+ await Promise.resolve();
+ for (const release of initialVideoReleases) {
+ release();
+ }
+
+ await expect(movement).resolves.toEqual({
+ affectedBoardIds: ['destination', 'source-image'],
+ failed: refs.slice(1),
+ succeeded: [imageRef('still.png')],
+ });
+ expect(videoRequests).toBe(4);
+ }
+ );
+
+ it('binds video movement to the captured account lifetime when the caller omits a signal', async () => {
+ const refs = [imageRef('still.png'), ...Array.from({ length: 8 }, (_, index) => videoRef(`clip-${index}.mp4`))];
+ let videoRequests = 0;
+
+ mocks.apiFetchJson.mockImplementation((url: string, init?: RequestInit) => {
+ if (url === '/api/v1/board_images/batch') {
+ return Promise.resolve({
+ added_images: ['still.png'],
+ affected_boards: ['source-image', 'destination'],
+ });
+ }
+
+ videoRequests += 1;
+ const signal = init?.signal;
+
+ if (!signal) {
+ return Promise.reject(new Error('Video movement did not capture the account lifetime 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');
+
+ await vi.waitFor(() => {
+ expect(videoRequests).toBe(4);
+ });
+ accountLifecycle.activate('replacement-user');
+
+ await expect(movement).resolves.toEqual({
+ affectedBoardIds: ['destination', 'source-image'],
+ failed: refs.slice(1),
+ succeeded: [imageRef('still.png')],
+ });
+ expect(videoRequests).toBe(4);
+ });
+
+ it.each([403, 500])('keeps an isolated HTTP %s video move failure item-local', async (status) => {
+ const refs = Array.from({ length: 6 }, (_, index) => videoRef(`clip-${index}.mp4`));
+
+ mocks.apiFetchJson.mockImplementation((_url: string, init?: RequestInit) => {
+ const { video_name: videoName } = JSON.parse(String(init?.body)) as { video_name: string };
+
+ if (videoName === 'clip-0.mp4') {
+ return Promise.reject(new MockApiError('Item move failed', status));
+ }
+
+ return Promise.resolve({
+ added_videos: [videoName],
+ affected_boards: ['destination'],
+ });
+ });
+
+ await expect(galleryItemOrganization.moveToBoard(refs, 'destination')).resolves.toEqual({
+ affectedBoardIds: ['destination'],
+ failed: [videoRef('clip-0.mp4')],
+ succeeded: refs.slice(1),
+ });
+ 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`));
@@ -317,8 +515,8 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {
});
it.each([
- { affected_boards: ['board-a'], starred_videos: 'clip.mp4' },
- { affected_boards: ['unexpected-board'], starred_videos: ['unexpected.mp4'] },
+ { affected_boards: ['board-a'], failed_videos: [], starred_videos: 'clip.mp4' },
+ { affected_boards: ['unexpected-board'], failed_videos: [], starred_videos: ['unexpected.mp4'] },
])('does not confirm malformed or unexpected video success payloads: $starred_videos', async (response) => {
mocks.apiFetchJson.mockResolvedValue(response);