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(projects): harden media restoration

Josh Corbettb79742cde190
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
new file mode 100644
index 0000000000..736b16f5eb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts
@@ -0,0 +1,58 @@
+import type * as transportModule from '@platform/transport/http';
+
+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const transport = vi.hoisted(() => ({
+ apiFetch: vi.fn(),
+ apiFetchJson: vi.fn(),
+}));
+
+vi.mock('@platform/transport/http', async (importOriginal) => ({
+ ...(await importOriginal<typeof transportModule>()),
+ apiFetch: transport.apiFetch,
+ apiFetchJson: transport.apiFetchJson,
+}));
+
+import { isProjectConfirmedAbsent } from './api';
+
+beforeEach(() => {
+ transport.apiFetch.mockReset();
+ transport.apiFetchJson.mockReset();
+ accountLifecycle.activate('project-api-test-user');
+});
+
+describe('isProjectConfirmedAbsent', () => {
+ it('confirms absence only from an authoritative not-found response in the current account scope', async () => {
+ const owner = captureAccountScope();
+
+ transport.apiFetchJson.mockRejectedValueOnce(new ApiError('not found', 404));
+
+ await expect(isProjectConfirmedAbsent('project/1', owner)).resolves.toBe(true);
+ expect(transport.apiFetchJson).toHaveBeenCalledWith('/api/v1/projects/project%2F1', { signal: owner.signal });
+ });
+
+ it('does not confirm absence when the project exists', async () => {
+ transport.apiFetchJson.mockResolvedValueOnce({ project_id: 'project-1' });
+
+ await expect(isProjectConfirmedAbsent('project-1', captureAccountScope())).resolves.toBe(false);
+ });
+
+ it('does not authorize cleanup after the owning account scope expires', async () => {
+ const owner = captureAccountScope();
+
+ transport.apiFetchJson.mockImplementationOnce(() => {
+ accountLifecycle.invalidate();
+ return Promise.reject(new ApiError('not found', 404));
+ });
+
+ await expect(isProjectConfirmedAbsent('project-1', owner)).resolves.toBe(false);
+ });
+
+ it('does not treat transport or server failures as proof of absence', async () => {
+ transport.apiFetchJson.mockRejectedValueOnce(new ApiError('unavailable', 503));
+
+ await expect(isProjectConfirmedAbsent('project-1', captureAccountScope())).resolves.toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.ts
index 1e7b1f1f10..5adb9d3a35 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts
@@ -1,3 +1,6 @@
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';
/**
@@ -103,6 +106,17 @@ export const isProjectConflictError = (error: unknown): boolean => error instanc
export const isProjectNotFoundError = (error: unknown): boolean => error instanceof ApiError && error.status === 404;
+/** A rejected create is safe to compensate only when its chosen id is authoritatively absent. */
+export const isProjectConfirmedAbsent = async (projectId: string, owner: AccountScope): Promise<boolean> => {
+ try {
+ await getProject(projectId, owner.signal);
+
+ return false;
+ } catch (error) {
+ return isAccountScopeCurrent(owner) && isProjectNotFoundError(error);
+ }
+};
+
export const getClientStateValue = (key: string, signal?: AbortSignal): Promise<string | null> =>
apiFetchJson<string | null>(`${CLIENT_STATE_BASE}/get_by_key?key=${encodeURIComponent(key)}`, { signal });
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts
index 905a532492..9e278c2350 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts
@@ -15,8 +15,11 @@ vi.mock('@platform/transport/http', async (importOriginal) => ({
}));
import {
+ copyImagesToBoard,
+ copyVideosToBoard,
createAssetResponseReader,
createStagingBoard,
+ deleteArchiveVideos,
deleteStagingBoard,
fetchImageBytes,
fetchImageThumbnail,
@@ -61,6 +64,10 @@ describe('findExistingVideoNames', () => {
});
describe('import rollback transport', () => {
+ beforeEach(() => {
+ mocks.apiFetchJson.mockReset();
+ });
+
it('sends authoritative image and video identities to their batch-delete routes', async () => {
const transport = (await import('./assetTransport')) as typeof assetTransportModule & {
deleteArchiveImages?: (names: string[], signal?: AbortSignal) => Promise<void>;
@@ -91,6 +98,18 @@ describe('import rollback transport', () => {
signal,
});
});
+
+ it('chunks video cleanup to the server request ceiling', async () => {
+ const names = Array.from({ length: 1_001 }, (_, index) => `video-${String(index)}.mp4`);
+
+ mocks.apiFetchJson.mockResolvedValue({});
+ await deleteArchiveVideos(names);
+
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(
+ mocks.apiFetchJson.mock.calls.map(([, options]) => JSON.parse(options.body as string).video_names.length)
+ ).toEqual([1_000, 1]);
+ });
});
describe('board media transport', () => {
@@ -162,6 +181,67 @@ describe('board media transport', () => {
expect(mocks.apiFetchJson).not.toHaveBeenCalled();
});
+ it.each([
+ ['images', copyImagesToBoard, 'image_names', 'image_name', 'source_image_name'],
+ ['videos', copyVideosToBoard, 'video_names', 'video_name', 'source_video_name'],
+ ] as const)(
+ 'chunks project %s copies to the server request ceiling',
+ async (_, copy, requestKey, nameKey, sourceKey) => {
+ const extension = requestKey === 'image_names' ? 'png' : 'mp4';
+ const names = Array.from({ length: 1_001 }, (_, index) => `media-${String(index)}.${extension}`);
+
+ mocks.apiFetchJson.mockImplementation((_path: string, options: { body: string }) => {
+ const requested = JSON.parse(options.body)[requestKey] as string[];
+
+ return Promise.resolve({
+ copied: requested.map((name) => ({ [nameKey]: `copy-${name}`, [sourceKey]: name })),
+ failed: [],
+ });
+ });
+
+ await expect(copy(names, 'staging')).resolves.toMatchObject({ copied: { length: names.length }, failed: [] });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ expect(
+ mocks.apiFetchJson.mock.calls.map(([, options]) => JSON.parse(options.body as string)[requestKey].length)
+ ).toEqual([1_000, 1]);
+ }
+ );
+
+ it('finishes an in-flight copy batch after cancellation so its identities remain available for rollback', async () => {
+ const controller = new AbortController();
+ const names = Array.from({ length: 1_001 }, (_, index) => `media-${String(index)}.png`);
+
+ mocks.apiFetchJson.mockImplementation((_path: string, options: { body: string; signal?: AbortSignal }) => {
+ const requested = JSON.parse(options.body).image_names as string[];
+ controller.abort();
+
+ return Promise.resolve({
+ copied: requested.map((name) => ({ image_name: `copy-${name}`, source_image_name: name })),
+ failed: [],
+ });
+ });
+
+ await expect(copyImagesToBoard(names, 'staging', controller.signal)).resolves.toMatchObject({
+ copied: { length: 1_000 },
+ failed: [names.at(-1)],
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
+ expect(mocks.apiFetchJson.mock.calls[0]![1].signal).toBeUndefined();
+ });
+
+ it('chunks video starring to the server request ceiling', async () => {
+ const names = Array.from({ length: 1_001 }, (_, index) => `video-${String(index)}.mp4`);
+
+ mocks.apiFetchJson.mockImplementation((_path: string, options: { body: string }) => {
+ const requested = JSON.parse(options.body).video_names as string[];
+
+ return Promise.resolve({ starred_videos: requested });
+ });
+
+ await expect(starVideos(names)).resolves.toEqual({ failed: [] });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ });
+
it('creates a staging board by name and truncates it as the backend would', async () => {
mocks.apiFetchJson.mockResolvedValue({ board_id: 'staging' });
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
index 2535a0a7b8..9c32fe81e2 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
@@ -93,6 +93,25 @@ const EXISTENCE_BATCH_CONCURRENCY = INVK_TRANSFER_CONCURRENCY;
/** Simultaneous per-name video lookups, matching the image fetch limit. */
const VIDEO_EXISTENCE_CONCURRENCY = INVK_TRANSFER_CONCURRENCY;
+/**
+ * Maximum names accepted by the backend's synchronous media batch routes.
+ *
+ * This is deliberately smaller than the archive's entry ceiling: archive size bounds a complete
+ * transfer, while this bounds one unit of server work. Every adapter below owns the split so callers
+ * can reason in project-sized lists without learning transport limits.
+ */
+const MEDIA_REQUEST_BATCH_SIZE = 1_000;
+
+const toBatches = <T>(items: readonly T[], size: number): T[][] => {
+ const batches: T[][] = [];
+
+ for (let offset = 0; offset < items.length; offset += size) {
+ batches.push(items.slice(offset, offset + size));
+ }
+
+ return batches;
+};
+
/**
* Let go of a response whose body this module is not going to read.
*
@@ -610,6 +629,61 @@ export interface CopyMediaResult {
copied: CopiedMedia[];
}
+interface CopyMediaRequest<Entry> {
+ boardId: string;
+ endpoint: string;
+ names: readonly string[];
+ requestKey: 'image_names' | 'video_names';
+ signal?: AbortSignal;
+ toCopiedMedia: (entry: Entry) => CopiedMedia;
+}
+
+/** Enforce the synchronous-route ceiling once for every server-side copy transport. */
+const copyMediaToBoard = async <Entry>({
+ boardId,
+ endpoint,
+ names,
+ requestKey,
+ signal,
+ toCopiedMedia,
+}: CopyMediaRequest<Entry>): Promise<CopyMediaResult> => {
+ const result: CopyMediaResult = { copied: [], failed: [] };
+ const batches = toBatches(names, MEDIA_REQUEST_BATCH_SIZE);
+
+ for (let batchIndex = 0; batchIndex < batches.length; batchIndex += 1) {
+ const batch = batches[batchIndex]!;
+ if (signal?.aborted) {
+ result.failed.push(...batches.slice(batchIndex).flat());
+ break;
+ }
+
+ try {
+ // Do not abort an in-flight copy request. The server performs synchronous work and may have
+ // created identities even after the browser disconnects; retaining its response is the only
+ // way the restore ledger can remove them. Cancellation is honored between bounded requests.
+ const body = await apiFetchJson<{ copied?: Entry[]; failed?: string[] }>(endpoint, {
+ body: JSON.stringify({ board_id: boardId, [requestKey]: batch }),
+ method: 'POST',
+ });
+
+ result.copied.push(...(body.copied ?? []).map(toCopiedMedia));
+ result.failed.push(...(body.failed ?? []));
+ } catch (error) {
+ if (isRequestCancellation(error)) {
+ throw error;
+ }
+ result.failed.push(...batch);
+ }
+
+ if (signal?.aborted) {
+ result.failed.push(...batches.slice(batchIndex + 1).flat());
+ break;
+ }
+ }
+
+ return result;
+};
+
/**
* Copy media onto a board without the bytes leaving the server.
*
@@ -620,55 +694,35 @@ export interface CopyMediaResult {
* metadata embedded in the PNG; starring is not part of a copy, so callers star afterwards through
* the same path an import uses.
*/
-export const copyImagesToBoard = async (
+export const copyImagesToBoard = (
imageNames: readonly string[],
boardId: string,
signal?: AbortSignal
-): Promise<CopyMediaResult> => {
- if (imageNames.length === 0) {
- return { copied: [], failed: [] };
- }
-
- const body = await apiFetchJson<{
- copied?: { image_name: string; source_image_name: string }[];
- failed?: string[];
- }>(`${IMAGES_BASE}/copy`, {
- body: JSON.stringify({ board_id: boardId, image_names: imageNames }),
- method: 'POST',
+): Promise<CopyMediaResult> =>
+ copyMediaToBoard<{ image_name: string; source_image_name: string }>({
+ boardId,
+ endpoint: `${IMAGES_BASE}/copy`,
+ names: imageNames,
+ requestKey: 'image_names',
signal,
+ toCopiedMedia: (entry) => ({ name: entry.image_name, sourceName: entry.source_image_name }),
});
- return {
- copied: (body.copied ?? []).map((entry) => ({ name: entry.image_name, sourceName: entry.source_image_name })),
- failed: body.failed ?? [],
- };
-};
-
/** The same, for videos. */
-export const copyVideosToBoard = async (
+export const copyVideosToBoard = (
videoNames: readonly string[],
boardId: string,
signal?: AbortSignal
-): Promise<CopyMediaResult> => {
- if (videoNames.length === 0) {
- return { copied: [], failed: [] };
- }
-
- const body = await apiFetchJson<{
- copied?: { source_video_name: string; video_name: string }[];
- failed?: string[];
- }>(`${VIDEOS_BASE}/copy`, {
- body: JSON.stringify({ board_id: boardId, video_names: videoNames }),
- method: 'POST',
+): Promise<CopyMediaResult> =>
+ copyMediaToBoard<{ source_video_name: string; video_name: string }>({
+ boardId,
+ endpoint: `${VIDEOS_BASE}/copy`,
+ names: videoNames,
+ requestKey: 'video_names',
signal,
+ toCopiedMedia: (entry) => ({ name: entry.video_name, sourceName: entry.source_video_name }),
});
- return {
- copied: (body.copied ?? []).map((entry) => ({ name: entry.video_name, sourceName: entry.source_video_name })),
- failed: body.failed ?? [],
- };
-};
-
/** Names the server would not star, out of the names asked for. */
export interface BulkStarResult {
failed: string[];
@@ -711,13 +765,26 @@ export const starVideos = async (videoNames: readonly string[], signal?: AbortSi
return { failed: [] };
}
- const body = await apiFetchJson<{ starred_videos?: string[] }>(`${VIDEOS_BASE}/star`, {
- body: JSON.stringify({ video_names: videoNames }),
- method: 'POST',
- signal,
- });
+ const failed: string[] = [];
- return toBulkStarResult(videoNames, body.starred_videos ?? []);
+ for (const batch of toBatches(videoNames, MEDIA_REQUEST_BATCH_SIZE)) {
+ try {
+ const body = await apiFetchJson<{ starred_videos?: string[] }>(`${VIDEOS_BASE}/star`, {
+ body: JSON.stringify({ video_names: batch }),
+ method: 'POST',
+ signal,
+ });
+
+ failed.push(...toBulkStarResult(batch, body.starred_videos ?? []).failed);
+ } catch (error) {
+ if (isRequestCancellation(error)) {
+ throw error;
+ }
+ failed.push(...batch);
+ }
+ }
+
+ return { failed };
};
/**
@@ -775,11 +842,28 @@ export const deleteArchiveVideos = async (videoNames: string[], signal?: AbortSi
return;
}
- await apiFetchJson<unknown>(`${VIDEOS_BASE}/delete`, {
- body: JSON.stringify({ video_names: videoNames }),
- method: 'POST',
- signal,
- });
+ let firstError: unknown = null;
+
+ for (const batch of toBatches(videoNames, MEDIA_REQUEST_BATCH_SIZE)) {
+ try {
+ await apiFetchJson<unknown>(`${VIDEOS_BASE}/delete`, {
+ body: JSON.stringify({ video_names: batch }),
+ method: 'POST',
+ signal,
+ });
+ } catch (error) {
+ if (isRequestCancellation(error)) {
+ throw error;
+ }
+ firstError ??= error;
+ }
+ }
+
+ if (firstError !== null) {
+ throw firstError instanceof Error
+ ? firstError
+ : new Error('One or more video cleanup requests failed.', { cause: firstError });
+ }
};
const EXTENSION_BY_MIME: Readonly<Record<string, string>> = {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
index 6cdf1cb3a5..1867151a29 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
@@ -1,5 +1,6 @@
import type { AccountScope } from '@platform/state/accountLifecycle';
import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';
+import type * as apiModule from '@workbench/projects/api';
import { createDraftProject } from '@workbench/workbenchState';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -18,6 +19,7 @@ import type * as duplicateProjectModule from './duplicateProject';
const api = vi.hoisted(() => ({
createProject: vi.fn(),
getProject: vi.fn(),
+ isProjectConfirmedAbsent: vi.fn(),
isProjectNotFoundError: (error: unknown) =>
typeof error === 'object' && error !== null && 'status' in error && error.status === 404,
}));
@@ -38,7 +40,10 @@ const transport = vi.hoisted(() => ({
uploadArchiveVideo: vi.fn(() => Promise.reject(new Error('duplication uploads nothing'))),
}));
-vi.mock('@workbench/projects/api', () => api);
+vi.mock('@workbench/projects/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof apiModule>()),
+ ...api,
+}));
// Partial, so the module's constants and pure predicates stay real — a stub of
// `isRequestCancellation` would let the tests agree with a duplication that mistook a
// cancellation for a board's worth of individually failed copies.
@@ -252,11 +257,10 @@ describe('duplicateProjectRecord', () => {
});
it('deletes the copies it made and the staging board when the create fails', async () => {
- const { ApiError } = await import('@platform/transport/http');
const failure = new Error('create rejected');
api.createProject.mockRejectedValue(failure);
- api.getProject.mockRejectedValue(new ApiError('not found', 404));
+ api.isProjectConfirmedAbsent.mockResolvedValueOnce(true);
await expect(
duplicateProject.duplicateProjectRecord({
@@ -275,7 +279,7 @@ describe('duplicateProjectRecord', () => {
const failure = new Error('connection ended after create');
api.createProject.mockRejectedValue(failure);
- api.getProject.mockResolvedValue(sourceRecord());
+ api.isProjectConfirmedAbsent.mockResolvedValueOnce(false);
await expect(
duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record: sourceRecord() })
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
index f99ea5d5ad..ff4c0be63e 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
@@ -1,11 +1,7 @@
import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';
import { type AccountScope, assertAccountScopeCurrent, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
-import {
- createProject as apiCreateProject,
- getProject as apiGetProject,
- isProjectNotFoundError,
-} from '@workbench/projects/api';
+import { createProject as apiCreateProject, isProjectConfirmedAbsent } from '@workbench/projects/api';
import { createProjectId } from '@workbench/projects/ids';
import {
collectLiveAssetRefs,
@@ -70,11 +66,12 @@ export interface DuplicateProjectResult extends ProjectTransferIssues {
}
/**
- * The duplication half of the materialization seam: one request per kind, and the pixels stay put.
+ * The duplication half of the materialization seam: one bounded request sequence per kind, and the
+ * pixels stay put.
*
- * Progress moves per item once each batch answers rather than during it. The copy is a single
- * server-side request per kind, so there is no finer truth to report — and unlike an import, there
- * is no upload to sit and watch.
+ * Progress moves per item once the sequence answers rather than during it. Each request is a
+ * synchronous server-side copy capped by the transport, so there is no finer event to report — and
+ * unlike an import, there is no browser upload to sit and watch.
*
* A batch that does not answer at all — a proxy timing out a large board — is every name in it
* failing, not the duplication failing. The route reports per-item failures precisely so one bad
@@ -121,17 +118,6 @@ export const createCopyMediaMaterializer = (
};
};
-/** A rejected create is safe to clean up only when its client-chosen id is confirmed absent. */
-const isProjectConfirmedAbsent = async (projectId: string, owner: AccountScope): Promise<boolean> => {
- try {
- await apiGetProject(projectId, owner.signal);
-
- return false;
- } catch (error) {
- return isAccountScopeCurrent(owner) && isProjectNotFoundError(error);
- }
-};
-
/**
* Copy a project and everything its board holds, under identities the copy owns.
*
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
index fd50b4c400..d75cc0418d 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
@@ -209,6 +209,14 @@ interface PendingUpload {
name: string;
}
+interface RestoreKindAdapter {
+ addBoardIdentity: (name: string) => void;
+ addDocumentIdentity: (name: string) => void;
+ mapping: Map<string, string>;
+ markResolvable: (name: string) => void;
+ upload: (bytes: Uint8Array, name: string, signal?: AbortSignal) => Promise<string>;
+}
+
const emptyMaterializeResult = (): MaterializeResult => ({ failed: [], materialized: [] });
/**
@@ -310,6 +318,24 @@ export const restoreProjectMedia = async (
/** Names this server can serve once the restore is done, under their final identities. */
const restoredImageNames = new Set<string>();
+ const kindAdapters: Record<InvkMediaKind, RestoreKindAdapter> = {
+ image: {
+ addBoardIdentity: (name) => input.ledger.boardImageNames.push(name),
+ addDocumentIdentity: (name) => input.ledger.imageNames.push(name),
+ mapping: mappings.images,
+ markResolvable: (name) => restoredImageNames.add(name),
+ upload: async (bytes, name, signal) =>
+ (await uploadImage(bytes, name, { contentType: mimeForEntryName(name), signal })).imageName,
+ },
+ video: {
+ addBoardIdentity: (name) => input.ledger.boardVideoNames.push(name),
+ addDocumentIdentity: (name) => input.ledger.videoNames.push(name),
+ mapping: mappings.videos,
+ markResolvable: () => undefined,
+ upload: async (bytes, name, signal) =>
+ (await uploadVideo(bytes, name, { contentType: mimeForEntryName(name, 'video'), signal })).videoName,
+ },
+ };
// Started before the board upload, awaited after it. The existence checks depend only on the
// document's own references, which are known here — and the board upload is the minutes-long part
@@ -345,19 +371,16 @@ export const restoreProjectMedia = async (
for (const entry of boardResult.materialized) {
const key = toMediaKey({ kind: entry.kind, name: entry.sourceName });
+ const adapter = kindAdapters[entry.kind];
settledBoardKeys.add(key);
sourceNamesByFreshName.set(toMediaKey({ kind: entry.kind, name: entry.name }), entry.sourceName);
- if (entry.kind === 'image') {
- input.ledger.boardImageNames.push(entry.name);
- restoredImageNames.add(entry.name);
- } else {
- input.ledger.boardVideoNames.push(entry.name);
- }
+ adapter.addBoardIdentity(entry.name);
+ adapter.markResolvable(entry.name);
if (entry.sourceName !== entry.name) {
- mappings[entry.kind === 'image' ? 'images' : 'videos'].set(entry.sourceName, entry.name);
+ adapter.mapping.set(entry.sourceName, entry.name);
}
if (starredKeys.has(key)) {
@@ -376,7 +399,7 @@ export const restoreProjectMedia = async (
return;
}
- mappings[failure.kind === 'image' ? 'images' : 'videos'].set(
+ kindAdapters[failure.kind].mapping.set(
failure.name,
buildMissingMediaName(input.projectId, failure.kind, descriptorIndexes.get(key) ?? 0)
);
@@ -432,9 +455,7 @@ export const restoreProjectMedia = async (
] as const) {
for (const name of names) {
if (existing.has(name)) {
- if (kind === 'image') {
- restoredImageNames.add(name);
- }
+ kindAdapters[kind].markResolvable(name);
// Satisfied by media that is already here, which is the whole point of the dedup.
total -= 1;
@@ -473,21 +494,14 @@ export const restoreProjectMedia = async (
}
try {
- const options = { contentType: mimeForEntryName(name, kind), signal: deps.signal };
- const restoredName =
- kind === 'image'
- ? (await uploadImage(bytes, name, options)).imageName
- : (await uploadVideo(bytes, name, options)).videoName;
-
- if (kind === 'image') {
- input.ledger.imageNames.push(restoredName);
- restoredImageNames.add(restoredName);
- } else {
- input.ledger.videoNames.push(restoredName);
- }
+ const adapter = kindAdapters[kind];
+ const restoredName = await adapter.upload(bytes, name, deps.signal);
+
+ adapter.addDocumentIdentity(restoredName);
+ adapter.markResolvable(restoredName);
if (restoredName !== name) {
- mappings[kind === 'image' ? 'images' : 'videos'].set(name, restoredName);
+ adapter.mapping.set(name, restoredName);
}
} catch (error) {
// Not a failure of this asset: an aborted signal or an expired account makes every remaining
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 24e3c09cec..d964d0240d 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -2,6 +2,7 @@ import { createDraftProject } from '@workbench/workbenchState';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ProjectBoardItemDTO } from './api';
+import type * as apiModule from './api';
import type * as coversModule from './covers';
import type * as assetTransportModule from './invk/assetTransport';
import type * as projectFileModule from './projectFile';
@@ -21,6 +22,7 @@ const api = vi.hoisted(() => ({
getProject: vi.fn(),
// Every export enumerates the project's board; most of these cases do not care what is on it.
getProjectBoardSnapshot: vi.fn((): Promise<{ items: ProjectBoardItemDTO[] }> => Promise.resolve({ items: [] })),
+ isProjectConfirmedAbsent: vi.fn(),
isProjectNotFoundError: (error: unknown) =>
typeof error === 'object' && error !== null && 'status' in error && error.status === 404,
setClientStateValue: vi.fn(() => Promise.resolve()),
@@ -70,7 +72,10 @@ const transport = vi.hoisted(() => ({
),
}));
-vi.mock('./api', () => api);
+vi.mock('./api', async (importOriginal) => ({
+ ...(await importOriginal<typeof apiModule>()),
+ ...api,
+}));
vi.mock('./covers', async (importOriginal) => ({
...(await importOriginal<typeof coversModule>()),
recordProjectCover: covers.recordProjectCover,
@@ -530,7 +535,6 @@ describe('importing a project board', () => {
});
it('deletes the media it created and then the staging board when the create fails', async () => {
- const { ApiError } = await import('@platform/transport/http');
const account = await import('@platform/state/accountLifecycle');
const primaryFailure = new Error('project create rejected');
@@ -539,7 +543,7 @@ describe('importing a project board', () => {
const archive = await exportedBoardArchive();
api.createProject.mockRejectedValue(primaryFailure);
- api.getProject.mockRejectedValueOnce(new ApiError('not found', 404));
+ api.isProjectConfirmedAbsent.mockResolvedValueOnce(true);
await expect(projectFile.importProjectFile(archive)).rejects.toBe(primaryFailure);
@@ -561,15 +565,7 @@ describe('importing a project board', () => {
const archive = await exportedBoardArchive();
api.createProject.mockRejectedValue(primaryFailure);
- api.getProject.mockResolvedValue({
- board_id: 'staging-board',
- created_at: '2026-06-10 10:00:00.000',
- data: {},
- name: 'Board project',
- project_id: 'committed',
- revision: 1,
- updated_at: '2026-06-10 10:00:00.000',
- });
+ api.isProjectConfirmedAbsent.mockResolvedValueOnce(false);
await expect(projectFile.importProjectFile(archive)).rejects.toBe(primaryFailure);
@@ -840,13 +836,12 @@ describe('importProjectFile', () => {
it('rolls back every authoritative uploaded identity when project creation fails without hiding that failure', async () => {
const account = await import('@platform/state/accountLifecycle');
- const { ApiError } = await import('@platform/transport/http');
const primaryFailure = new Error('project create rejected');
account.accountLifecycle.activate('rollback-user');
await projectFile.exportOpenProject(projectWithRestorableAssets());
api.createProject.mockRejectedValue(primaryFailure);
- api.getProject.mockRejectedValueOnce(new ApiError('not found', 404));
+ api.isProjectConfirmedAbsent.mockResolvedValueOnce(true);
transport.deleteArchiveImages.mockRejectedValueOnce(new Error('image cleanup failed'));
transport.deleteArchiveVideos.mockRejectedValueOnce(new Error('video cleanup failed'));
@@ -864,14 +859,7 @@ describe('importProjectFile', () => {
account.accountLifecycle.activate('ambiguous-response-user');
await projectFile.exportOpenProject(projectWithRestorableAssets(false));
api.createProject.mockRejectedValue(primaryFailure);
- api.getProject.mockResolvedValue({
- created_at: '2026-06-10 10:00:00.000',
- data: {},
- name: 'Committed project',
- project_id: 'committed-project',
- revision: 1,
- updated_at: '2026-06-10 10:00:00.000',
- });
+ api.isProjectConfirmedAbsent.mockResolvedValueOnce(false);
await expect(projectFile.importProjectFile(capturedArchive())).rejects.toBe(primaryFailure);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 3cae079b64..45a590ba94 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -15,7 +15,7 @@ import {
createProject as apiCreateProject,
getProject as apiGetProject,
getProjectBoardSnapshot,
- isProjectNotFoundError,
+ isProjectConfirmedAbsent,
type ProjectRecordDTO,
} from './api';
import { recordProjectCover } from './covers';
@@ -156,17 +156,6 @@ const readProjectDocument = async (file: File) => {
return { contents: await readInvkArchive(file), format: 'invk' as const };
};
-/** A rejected create is safe to clean up only when its client-chosen id is confirmed absent. */
-const isProjectConfirmedAbsent = async (projectId: string, owner: AccountScope): Promise<boolean> => {
- try {
- await apiGetProject(projectId, owner.signal);
-
- return false;
- } catch (error) {
- return isAccountScopeCurrent(owner) && isProjectNotFoundError(error);
- }
-};
-
const exportProjectDocument = async (
name: string,
projectId: string,