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): restore project boards from archives

Josh Corbettae9de6981149
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 ab220a8cf3..905a532492 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts
@@ -1,26 +1,38 @@
import { ApiError } from '@platform/transport/http';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as assetTransportModule from './assetTransport';
import { INVK_MAX_ARCHIVE_BYTES } from './archive';
-const mocks = vi.hoisted(() => ({ apiFetchJson: vi.fn(), apiFetchRaw: vi.fn() }));
+const mocks = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn(), apiFetchRaw: vi.fn() }));
vi.mock('@platform/transport/http', async (importOriginal) => ({
...(await importOriginal<object>()),
+ apiFetch: mocks.apiFetch,
apiFetchJson: mocks.apiFetchJson,
apiFetchRaw: mocks.apiFetchRaw,
}));
import {
createAssetResponseReader,
+ createStagingBoard,
+ deleteStagingBoard,
fetchImageBytes,
fetchImageThumbnail,
fetchVideoBytes,
findExistingVideoNames,
+ starImages,
+ starVideos,
+ uploadArchiveImage,
+ uploadBoardImage,
+ uploadBoardVideo,
} from './assetTransport';
+/** The query string is the contract with the upload route; these pin it by hand. */
+const uploadQuery = (): URLSearchParams =>
+ new URLSearchParams((mocks.apiFetch.mock.calls.at(-1)![0] as string).split('?')[1]);
+
describe('findExistingVideoNames', () => {
it('returns a video name when its lookup succeeds', async () => {
mocks.apiFetchRaw.mockResolvedValue(new Response(null, { status: 200 }));
@@ -81,6 +93,99 @@ describe('import rollback transport', () => {
});
});
+describe('board media transport', () => {
+ beforeEach(() => {
+ mocks.apiFetch.mockReset();
+ mocks.apiFetchJson.mockReset();
+ });
+
+ it('uploads an image onto the staging board under its archived category', async () => {
+ mocks.apiFetch.mockResolvedValue(
+ new Response(JSON.stringify({ height: 2, image_name: 'fresh.png', width: 3 }), { status: 201 })
+ );
+
+ await expect(
+ uploadBoardImage(new Uint8Array([1]), 'archived.png', {
+ boardId: 'staging',
+ category: 'control',
+ contentType: 'image/png',
+ })
+ ).resolves.toEqual({ height: 2, imageName: 'fresh.png', width: 3 });
+
+ expect(Object.fromEntries(uploadQuery())).toEqual({
+ board_id: 'staging',
+ image_category: 'control',
+ is_intermediate: 'false',
+ });
+ });
+
+ it('uploads a video onto the staging board under its archived category', async () => {
+ mocks.apiFetch.mockResolvedValue(new Response(JSON.stringify({ video_name: 'fresh.mp4' }), { status: 201 }));
+
+ await expect(
+ uploadBoardVideo(new Uint8Array([1]), 'archived.mp4', { boardId: 'staging', category: 'user' })
+ ).resolves.toEqual({ videoName: 'fresh.mp4' });
+
+ expect(Object.fromEntries(uploadQuery())).toEqual({
+ board_id: 'staging',
+ is_intermediate: 'false',
+ video_category: 'user',
+ });
+ });
+
+ /**
+ * A document reference is not gallery content: it goes up unboarded, under the canvas's private
+ * category. The two upload paths must not drift into each other.
+ */
+ it('keeps document-reference uploads unboarded and private', async () => {
+ mocks.apiFetch.mockResolvedValue(
+ new Response(JSON.stringify({ height: 1, image_name: 'fresh.png', width: 1 }), { status: 201 })
+ );
+
+ await uploadArchiveImage(new Uint8Array([1]), 'referenced.png');
+
+ expect(Object.fromEntries(uploadQuery())).toEqual({ image_category: 'other', is_intermediate: 'false' });
+ });
+
+ it('reports every name the star endpoints did not confirm', async () => {
+ mocks.apiFetchJson
+ .mockResolvedValueOnce({ starred_images: ['kept.png'] })
+ .mockResolvedValueOnce({ starred_videos: ['kept.mp4'] });
+
+ await expect(starImages(['kept.png', 'skipped.png'])).resolves.toEqual({ failed: ['skipped.png'] });
+ await expect(starVideos(['kept.mp4', 'skipped.mp4'])).resolves.toEqual({ failed: ['skipped.mp4'] });
+ });
+
+ it('asks for nothing when there is nothing to star', async () => {
+ await expect(starImages([])).resolves.toEqual({ failed: [] });
+ await expect(starVideos([])).resolves.toEqual({ failed: [] });
+ expect(mocks.apiFetchJson).not.toHaveBeenCalled();
+ });
+
+ it('creates a staging board by name and truncates it as the backend would', async () => {
+ mocks.apiFetchJson.mockResolvedValue({ board_id: 'staging' });
+
+ await expect(createStagingBoard('x'.repeat(320))).resolves.toBe('staging');
+
+ const [url, options] = mocks.apiFetchJson.mock.calls[0]! as [string, { method: string }];
+
+ expect(new URLSearchParams(url.split('?')[1]).get('board_name')).toBe('x'.repeat(300));
+ expect(options.method).toBe('POST');
+ });
+
+ /** Untracked media that landed on the board while the import ran must survive as Uncategorized. */
+ it('deletes a staging board without taking its media with it', async () => {
+ mocks.apiFetchJson.mockResolvedValue({});
+
+ await deleteStagingBoard('staging');
+
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/boards/staging?include_images=false', {
+ method: 'DELETE',
+ signal: undefined,
+ });
+ });
+});
+
describe('export asset response limits', () => {
it('rejects an oversized Content-Length before materializing the body', async () => {
const response = new Response(null, {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
index 357cc73151..d0edf360cc 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
@@ -7,6 +7,8 @@ import {
HttpRequestIdentityExpiredError,
} from '@platform/transport/http';
+import type { InvkMediaCategory } from './board';
+
import { INVK_MAX_ARCHIVE_BYTES } from './archive';
import { InvkFormatError } from './format';
@@ -20,7 +22,10 @@ import { InvkFormatError } from './format';
* would make importing a project file — a Launchpad action, on a route that
* deliberately never loads the editor — pull the canvas graph behind it.
*
- * Restored assets are uploaded with the category `'other'`. That is the canvas's
+ * ### Two upload paths, because a restore carries two kinds of media
+ *
+ * A document *reference* is a pointer to pixels the project draws with. Those go
+ * up under the category `'other'` and onto no board — that is the canvas's
* private category: the backend lists it in neither `IMAGE_CATEGORIES` nor
* `ASSETS_CATEGORIES`, so it appears in no gallery view and no board count (the
* reasoning is written out in full at `canvas-operations/backend/canvasImages.ts`).
@@ -28,6 +33,12 @@ import { InvkFormatError } from './format';
* stranger's project into your gallery; the pixels a document points at are not
* gallery content, they are the document.
*
+ * A project *board item* is the opposite: it is gallery content, and the archive
+ * recorded the category it was filed under. {@link uploadBoardImage} and its
+ * video twin put it back under that category, on the project's staging board, so
+ * the restored board looks like the exported one rather than like a pile of
+ * uncategorized uploads.
+ *
* ### Images and videos are not symmetric
*
* Everything here exists twice because the backend keeps the two in separate
@@ -39,9 +50,13 @@ import { InvkFormatError } from './format';
* images before the bulk endpoint existed.
*/
+const BOARDS_BASE = '/api/v1/boards';
const IMAGES_BASE = '/api/v1/images';
const VIDEOS_BASE = '/api/v1/videos';
+/** The backend truncates board names at 300 characters; doing it here keeps the name we chose. */
+const MAX_BOARD_NAME_LENGTH = 300;
+
/**
* Whether a failed request means "the work this belonged to is over" rather
* than "this one asset could not be served".
@@ -468,6 +483,163 @@ export const uploadArchiveVideo = async (
return { videoName: dto.video_name };
};
+export interface BoardUploadOptions {
+ /** The project's staging board. Board media is never uploaded unboarded. */
+ boardId: string;
+ /** The category the exporting server had it filed under. */
+ category: InvkMediaCategory;
+ contentType?: string;
+ signal?: AbortSignal;
+}
+
+/**
+ * Put one of the project board's images back, under its archived category and on
+ * the staging board the new project is about to claim.
+ *
+ * The returned name is a genuinely new identity, always — `board_images` has
+ * `PRIMARY KEY (image_name)`, so an image sits on exactly one board and a restore
+ * that reused an existing name would be moving a stranger's picture onto this
+ * project's board rather than copying it.
+ */
+export const uploadBoardImage = async (
+ bytes: Uint8Array,
+ fileName: string,
+ options: BoardUploadOptions
+): Promise<UploadedImage> => {
+ const query = new URLSearchParams({
+ board_id: options.boardId,
+ image_category: options.category,
+ is_intermediate: 'false',
+ });
+ const body = new FormData();
+
+ body.append(
+ 'file',
+ new File([bytes as BlobPart], fileName, { type: options.contentType || 'application/octet-stream' })
+ );
+
+ const response = await apiFetch(`${IMAGES_BASE}/upload?${query.toString()}`, {
+ body,
+ method: 'POST',
+ signal: options.signal,
+ });
+ const dto = (await response.json()) as ImageDTOSubset;
+
+ return { height: dto.height, imageName: dto.image_name, width: dto.width };
+};
+
+/** The same, for one of the board's videos. */
+export const uploadBoardVideo = async (
+ bytes: Uint8Array,
+ fileName: string,
+ options: BoardUploadOptions
+): Promise<UploadedVideo> => {
+ const query = new URLSearchParams({
+ board_id: options.boardId,
+ is_intermediate: 'false',
+ video_category: options.category,
+ });
+ const body = new FormData();
+
+ body.append('file', new File([bytes as BlobPart], fileName, { type: options.contentType || 'video/mp4' }));
+
+ const response = await apiFetch(`${VIDEOS_BASE}/upload?${query.toString()}`, {
+ body,
+ method: 'POST',
+ signal: options.signal,
+ });
+ const dto = (await response.json()) as VideoDTOSubset;
+
+ return { videoName: dto.video_name };
+};
+
+/** Names the server would not star, out of the names asked for. */
+export interface BulkStarResult {
+ failed: string[];
+}
+
+/**
+ * What a bulk star actually achieved.
+ *
+ * Both endpoints answer with the names they *did* star, and only the video one
+ * also lists failures — a name it skipped (a foreign one, or one deleted between
+ * the upload and the star) appears in neither list. Deriving the failures from
+ * the success list rather than reading `failed_*` therefore covers both routes
+ * with one rule, and the rule is the honest one: anything not reported as starred
+ * did not get starred.
+ */
+const toBulkStarResult = (requested: readonly string[], starred: readonly string[]): BulkStarResult => {
+ const succeeded = new Set(starred);
+
+ return { failed: requested.filter((name) => !succeeded.has(name)) };
+};
+
+/** Star restored images. Starring is never part of an upload or a copy — it is always this call. */
+export const starImages = async (imageNames: readonly string[], signal?: AbortSignal): Promise<BulkStarResult> => {
+ if (imageNames.length === 0) {
+ return { failed: [] };
+ }
+
+ const body = await apiFetchJson<{ starred_images?: string[] }>(`${IMAGES_BASE}/star`, {
+ body: JSON.stringify({ image_names: imageNames }),
+ method: 'POST',
+ signal,
+ });
+
+ return toBulkStarResult(imageNames, body.starred_images ?? []);
+};
+
+/** The same, for videos. */
+export const starVideos = async (videoNames: readonly string[], signal?: AbortSignal): Promise<BulkStarResult> => {
+ if (videoNames.length === 0) {
+ return { failed: [] };
+ }
+
+ const body = await apiFetchJson<{ starred_videos?: string[] }>(`${VIDEOS_BASE}/star`, {
+ body: JSON.stringify({ video_names: videoNames }),
+ method: 'POST',
+ signal,
+ });
+
+ return toBulkStarResult(videoNames, body.starred_videos ?? []);
+};
+
+/**
+ * An unclaimed private board for a restore to upload into, which project creation
+ * then claims and renames.
+ *
+ * Creating the project first would mean posting it with the old asset names and
+ * then updating it with the remapped ones, making the *update* the commit point:
+ * a failure there leaves a real project full of references to media that never
+ * arrived. Staging inverts that — the media is in place before the project
+ * exists, and the create either claims the board and its contents or leaves
+ * nothing a person can see.
+ */
+export const createStagingBoard = async (boardName: string, signal?: AbortSignal): Promise<string> => {
+ const query = new URLSearchParams({ board_name: boardName.slice(0, MAX_BOARD_NAME_LENGTH) });
+ const dto = await apiFetchJson<{ board_id: string }>(`${BOARDS_BASE}/?${query.toString()}`, {
+ method: 'POST',
+ signal,
+ });
+
+ return dto.board_id;
+};
+
+/**
+ * Drop a staging board whose project was never created.
+ *
+ * `include_images=false` deliberately: the restore deletes the identities it
+ * created itself, one by one, and anything else that wandered onto the board in
+ * the meantime — a generation that finished while the import ran — must survive
+ * as Uncategorized rather than be collected by a cleanup that never meant it.
+ */
+export const deleteStagingBoard = async (boardId: string, signal?: AbortSignal): Promise<void> => {
+ await apiFetchJson<unknown>(`${BOARDS_BASE}/${encodeURIComponent(boardId)}?include_images=false`, {
+ method: 'DELETE',
+ signal,
+ });
+};
+
/** Delete image identities created by a restore whose project could not be created. */
export const deleteArchiveImages = async (imageNames: string[], signal?: AbortSignal): Promise<void> => {
if (imageNames.length === 0) {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts
index e90a8f81dd..bacca30884 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts
@@ -1,8 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
+import type { InvkBoardItem } from './board';
+
import { binaryEntry, INVK_MAX_ARCHIVE_BYTES, textEntry, writeArchive } from './archive';
import { InvkFormatError } from './format';
-import { readInvkArchive, restoreArchiveAssets } from './importProject';
+import { createArchiveMediaMaterializer, readInvkArchive, restoreArchiveMedia } from './importProject';
+import { createRestoredMediaLedger } from './restoreProjectMedia';
const imageRef = (imageName: string) => ({ height: 64, imageName, width: 64 });
@@ -22,6 +25,16 @@ const manifest = (overrides: Record<string, unknown> = {}) => ({
...overrides,
});
+const boardItem = (overrides: Partial<InvkBoardItem> = {}): InvkBoardItem => ({
+ category: 'general',
+ kind: 'image',
+ name: 'a.png',
+ starred: false,
+ ...overrides,
+});
+
+const boardEntry = (items: InvkBoardItem[] = [boardItem()]) => JSON.stringify({ items, version: 1 });
+
const archiveFile = async (entries: Record<string, string | Uint8Array>): Promise<File> => {
const blob = await writeArchive(
new Map(
@@ -43,6 +56,15 @@ const validArchive = (overrides: Record<string, string | Uint8Array> = {}) =>
...overrides,
});
+const v3Archive = (overrides: Record<string, string | Uint8Array> = {}) =>
+ archiveFile({
+ 'board.json': boardEntry(),
+ 'images/a.png': new Uint8Array([1, 2, 3]),
+ 'manifest.json': JSON.stringify(manifest({ version: 3 })),
+ 'project.json': JSON.stringify(document()),
+ ...overrides,
+ });
+
describe('readInvkArchive', () => {
it('refuses an oversized file before allocating its bytes', async () => {
const arrayBuffer = vi.fn(() => Promise.resolve(new ArrayBuffer(0)));
@@ -61,6 +83,70 @@ describe('readInvkArchive', () => {
expect(contents.cover).toBeNull();
});
+ /**
+ * An archive that predates boards genuinely has none, and an archive whose board was empty says
+ * so. Discriminating on the version keeps those apart: only the first may have a board invented
+ * for it.
+ */
+ it('reads a v2 archive as having no board at all', async () => {
+ const contents = await readInvkArchive(await validArchive());
+
+ expect(contents.version).toBe(2);
+ expect(contents.boardSnapshot).toBeNull();
+ });
+
+ it('reads and canonicalizes a v3 board enumeration', async () => {
+ const contents = await readInvkArchive(
+ await v3Archive({
+ 'board.json': boardEntry([boardItem({ name: 'z.png' }), boardItem({ kind: 'video', name: 'a.mp4' })]),
+ })
+ );
+
+ expect(contents.version).toBe(3);
+ // Sorted by kind then name, whatever order the writer used.
+ expect(contents.boardSnapshot?.items.map((item) => item.name)).toEqual(['z.png', 'a.mp4']);
+ });
+
+ it('reads an empty v3 board without inventing anything', async () => {
+ const contents = await readInvkArchive(await v3Archive({ 'board.json': boardEntry([]) }));
+
+ expect(contents.boardSnapshot).toEqual({ items: [], version: 1 });
+ });
+
+ it('reports a v3 archive with no board enumeration as damaged', async () => {
+ const blob = await writeArchive(
+ new Map([
+ ['manifest.json', textEntry(JSON.stringify(manifest({ version: 3 })))],
+ ['project.json', textEntry(JSON.stringify(document()))],
+ ])
+ );
+
+ await expect(readInvkArchive(new File([blob], 'project.invk'))).rejects.toMatchObject({ reason: 'damaged' });
+ });
+
+ it.each([
+ ['unparseable', 'not json'],
+ ['a duplicate descriptor', JSON.stringify({ items: [boardItem(), boardItem()], version: 1 })],
+ ['an unsafe name', JSON.stringify({ items: [boardItem({ name: '../escape.png' })], version: 1 })],
+ ['an unknown version', JSON.stringify({ items: [], version: 2 })],
+ ])('reports a board enumeration that is %s as damaged', async (_case, contents) => {
+ await expect(readInvkArchive(await v3Archive({ 'board.json': contents }))).rejects.toMatchObject({
+ reason: 'damaged',
+ });
+ });
+
+ /** A ZIP path is attacker-controlled text; a media name from the server never has a separator. */
+ it('ignores bundled entries whose names are not plain basenames', async () => {
+ const contents = await readInvkArchive(
+ await validArchive({
+ 'images/': new Uint8Array([]),
+ 'images/nested/deep.png': new Uint8Array([4]),
+ })
+ );
+
+ expect([...contents.images.keys()]).toEqual(['a.png']);
+ });
+
it('resolves the cover entry named by the manifest', async () => {
const contents = await readInvkArchive(
await archiveFile({
@@ -114,236 +200,203 @@ describe('readInvkArchive', () => {
});
});
-describe('restoreArchiveAssets', () => {
- const contents = async (overrides: Partial<Awaited<ReturnType<typeof readInvkArchive>>> = {}) => ({
- ...(await readInvkArchive(await validArchive())),
- ...overrides,
+describe('createArchiveMediaMaterializer', () => {
+ const bytes = (value: number) => new Uint8Array([value]);
+ const archive = () => ({
+ images: new Map([['a.png', bytes(1)]]),
+ videos: new Map([['clip.mp4', bytes(2)]]),
});
- it('uploads only what the server is missing', async () => {
- const upload = vi.fn((_bytes: Uint8Array, fileName: string) =>
- Promise.resolve({ height: 1, imageName: fileName, width: 1 })
+ it('uploads each descriptor to the staging board under its archived category', async () => {
+ const uploadBoardImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'fresh.png', width: 1 }));
+ const uploadBoardVideo = vi.fn(() => Promise.resolve({ videoName: 'fresh.mp4' }));
+ const materialize = createArchiveMediaMaterializer(archive(), { uploadBoardImage, uploadBoardVideo });
+ const settled = vi.fn();
+
+ const result = await materialize(
+ [boardItem({ category: 'control' }), boardItem({ category: 'user', kind: 'video', name: 'clip.mp4' })],
+ 'staging',
+ settled
);
- const result = await restoreArchiveAssets(await contents(), {
- findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
- uploadArchiveImage: upload,
+ expect(uploadBoardImage).toHaveBeenCalledWith(bytes(1), 'a.png', {
+ boardId: 'staging',
+ category: 'control',
+ contentType: 'image/png',
});
-
- expect(upload).not.toHaveBeenCalled();
- expect(result).toMatchObject({ documentReferenceIssues: [], uploadedCount: 0 });
- expect(result.mappings.images.size).toBe(0);
- });
-
- it('records the rename when the server assigns a different name', async () => {
- const result = await restoreArchiveAssets(await contents(), {
- findExistingImageNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: () => Promise.resolve({ height: 1, imageName: 'server-1.png', width: 1 }),
+ expect(uploadBoardVideo).toHaveBeenCalledWith(bytes(2), 'clip.mp4', {
+ boardId: 'staging',
+ category: 'user',
+ contentType: 'video/mp4',
});
-
- expect([...result.mappings.images]).toEqual([['a.png', 'server-1.png']]);
- expect(result.uploadedCount).toBe(1);
+ expect(result.materialized).toEqual([
+ { kind: 'image', name: 'fresh.png', sourceName: 'a.png' },
+ { kind: 'video', name: 'fresh.mp4', sourceName: 'clip.mp4' },
+ ]);
+ expect(settled).toHaveBeenCalledTimes(2);
});
- it('records no rename when the server keeps the name', async () => {
- const result = await restoreArchiveAssets(await contents(), {
- findExistingImageNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: (_bytes, fileName) => Promise.resolve({ height: 1, imageName: fileName, width: 1 }),
- });
+ /** Never an existence check: board media is copied, never adopted. See `restoreProjectMedia`. */
+ it('uploads a descriptor whose name the destination may already hold', async () => {
+ const uploadBoardImage = vi.fn((_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 })
+ );
+ const result = await createArchiveMediaMaterializer(archive(), { uploadBoardImage })(
+ [boardItem()],
+ 'staging',
+ () => undefined
+ );
- expect(result.mappings.images.size).toBe(0);
- expect(result.uploadedCount).toBe(1);
+ expect(result.materialized).toEqual([{ kind: 'image', name: 'server-a.png', sourceName: 'a.png' }]);
});
- it('returns the authoritative server identities for every newly uploaded asset', async () => {
- const withVideo = await contents();
-
- withVideo.projectDocument = {
- ...withVideo.projectDocument,
- futureVideoInput: { video_name: 'clip.mp4' },
- };
- withVideo.videos.set('clip.mp4', new Uint8Array([7]));
-
- const result = await restoreArchiveAssets(withVideo, {
- findExistingImageNames: () => Promise.resolve(new Set()),
- findExistingVideoNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: () => Promise.resolve({ height: 1, imageName: 'server-image.png', width: 1 }),
- uploadArchiveVideo: () => Promise.resolve({ videoName: 'server-video.mp4' }),
- });
+ it('reports a descriptor the archive carried no bytes for', async () => {
+ const uploadBoardImage = vi.fn(() => Promise.reject(new Error('should not be called')));
+ const result = await createArchiveMediaMaterializer(archive(), { uploadBoardImage })(
+ [boardItem({ name: 'absent.png' })],
+ 'staging',
+ () => undefined
+ );
- expect(result.uploadedAssets).toEqual({
- imageNames: ['server-image.png'],
- videoNames: ['server-video.mp4'],
- });
+ expect(result.failed).toEqual([{ kind: 'image', name: 'absent.png', reason: 'missing-entry' }]);
+ expect(uploadBoardImage).not.toHaveBeenCalled();
});
- it('reports a reference the archive never carried as dangling', async () => {
- const missing = await contents();
+ it('reports a rejected upload without abandoning the rest of the board', async () => {
+ const uploadBoardImage = vi.fn((_bytes: Uint8Array, fileName: string) =>
+ fileName === 'a.png'
+ ? Promise.reject(new Error('rejected'))
+ : Promise.resolve({ height: 1, imageName: 'fresh.png', width: 1 })
+ );
+ const withSecond = archive();
- missing.images.delete('a.png');
+ withSecond.images.set('b.png', bytes(3));
- const result = await restoreArchiveAssets(missing, {
- findExistingImageNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: () => Promise.reject(new Error('should not be called')),
- });
+ const result = await createArchiveMediaMaterializer(withSecond, { uploadBoardImage })(
+ [boardItem(), boardItem({ name: 'b.png' })],
+ 'staging',
+ () => undefined
+ );
- expect(result.documentReferenceIssues.map((issue) => issue.name)).toEqual(['a.png']);
- expect(result.uploadedCount).toBe(0);
+ expect(result.failed).toEqual([{ kind: 'image', name: 'a.png', reason: 'upload-failed' }]);
+ expect(result.materialized).toEqual([{ kind: 'image', name: 'fresh.png', sourceName: 'b.png' }]);
});
+});
- it('reports a failed upload as dangling rather than failing the import', async () => {
- const result = await restoreArchiveAssets(await contents(), {
- findExistingImageNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: () => Promise.reject(new Error('upload failed')),
- });
-
- expect(result.documentReferenceIssues.map((issue) => issue.name)).toEqual(['a.png']);
- expect(result.uploadedCount).toBe(0);
+describe('restoreArchiveMedia', () => {
+ const restoreDeps = (overrides = {}) => ({
+ findExistingImageNames: () => Promise.resolve(new Set<string>()),
+ findExistingVideoNames: () => Promise.resolve(new Set<string>()),
+ starImages: () => Promise.resolve({ failed: [] }),
+ starVideos: () => Promise.resolve({ failed: [] }),
+ uploadBoardImage: (_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ height: 1, imageName: `board-${fileName}`, width: 1 }),
+ uploadBoardVideo: (_bytes: Uint8Array, fileName: string) => Promise.resolve({ videoName: `board-${fileName}` }),
+ uploadImage: (_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ height: 1, imageName: `loose-${fileName}`, width: 1 }),
+ uploadVideo: (_bytes: Uint8Array, fileName: string) => Promise.resolve({ videoName: `loose-${fileName}` }),
+ ...overrides,
});
/**
- * The bundled cover is a thumbnail of an image the document also references,
- * and the cover URL asks for a thumbnail anyway — so once that image is on
- * the server, uploading the entry too would leave an orphan nobody can find:
- * covers go up under the `'other'` category, which shows in no gallery view.
+ * The overlap case: `a.png` is both on the board and drawn by the canvas. It travels once, as
+ * board media, and the layer follows it to the copy.
*/
- it('reuses the restored cover image instead of uploading a second copy', async () => {
- const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });
- const upload = vi.fn(() => Promise.resolve({ height: 1, imageName: 'server-cover.png', width: 1 }));
-
- const result = await restoreArchiveAssets(withCover, {
- findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
- uploadArchiveImage: upload,
- });
-
- expect(result.coverImageName).toBe('a.png');
- expect(upload).not.toHaveBeenCalled();
- });
-
- it('follows the rename when the cover image was uploaded under a new name', async () => {
- const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });
- const upload = vi.fn((_bytes: Uint8Array, fileName: string) =>
- Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 })
+ it('restores an overlapping item once and points the document at the copy', async () => {
+ const archive = await readInvkArchive(await v3Archive());
+ const ledger = createRestoredMediaLedger('staging');
+ const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'never', width: 1 }));
+
+ const result = await restoreArchiveMedia(
+ archive,
+ { boardId: 'staging', ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },
+ restoreDeps({ uploadImage })
);
- const result = await restoreArchiveAssets(withCover, {
- findExistingImageNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: upload,
- });
-
- expect(result.coverImageName).toBe('server-a.png');
- // Once for the image itself, never again for the cover.
- expect(upload).toHaveBeenCalledTimes(1);
- });
-
- it('falls back to the bundled cover when its source image is dangling', async () => {
- const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });
-
- withCover.images.delete('a.png');
-
- const upload = vi.fn(() => Promise.resolve({ height: 1, imageName: 'server-cover.png', width: 1 }));
- const result = await restoreArchiveAssets(withCover, {
- findExistingImageNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: upload,
- });
-
- expect(result.coverImageName).toBe('server-cover.png');
- expect(result.documentReferenceIssues.map((issue) => issue.name)).toEqual(['a.png']);
- expect(result.uploadedAssets.imageNames).toEqual(['server-cover.png']);
- expect(upload).toHaveBeenCalledWith(new Uint8Array([9]), 'cover.webp', {
- contentType: 'image/webp',
- signal: undefined,
- });
+ expect(uploadImage).not.toHaveBeenCalled();
+ expect([...result.mappings.images]).toEqual([['a.png', 'board-a.png']]);
+ expect(ledger).toMatchObject({ boardImageNames: ['board-a.png'], imageNames: [] });
});
- it('restores a video through the video endpoints, never the image ones', async () => {
- const videoDocument = {
- ...document(),
- projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.mp4' } } }, id: 'n' }] },
- };
- const withVideo = await readInvkArchive(
- await archiveFile({
- 'images/a.png': new Uint8Array([1]),
- 'manifest.json': JSON.stringify(manifest()),
- 'project.json': JSON.stringify(videoDocument),
- 'videos/clip.mp4': new Uint8Array([7, 7, 7]),
+ /** Unreferenced board media is exactly what v3 exists to carry. */
+ it('restores board media the document never mentions', async () => {
+ const archive = await readInvkArchive(
+ await v3Archive({
+ 'board.json': boardEntry([boardItem({ name: 'unreferenced.png', starred: true })]),
+ 'images/unreferenced.png': new Uint8Array([5]),
})
);
+ const ledger = createRestoredMediaLedger('staging');
+ const starImages = vi.fn(() => Promise.resolve({ failed: [] }));
- expect([...withVideo.videos.keys()]).toEqual(['clip.mp4']);
-
- const uploadImage = vi.fn((_bytes: Uint8Array, fileName: string) =>
- Promise.resolve({ height: 1, imageName: fileName, width: 1 })
+ const result = await restoreArchiveMedia(
+ archive,
+ { boardId: 'staging', ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },
+ restoreDeps({ starImages })
);
- const uploadVideo = vi.fn(() => Promise.resolve({ videoName: 'server-clip.mp4' }));
-
- const result = await restoreArchiveAssets(withVideo, {
- findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
- findExistingVideoNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: uploadImage,
- uploadArchiveVideo: uploadVideo,
- });
- expect(uploadImage).not.toHaveBeenCalled();
- expect(uploadVideo).toHaveBeenCalledWith(new Uint8Array([7, 7, 7]), 'clip.mp4', {
- contentType: 'video/mp4',
- signal: undefined,
- });
- expect([...result.mappings.videos]).toEqual([['clip.mp4', 'server-clip.mp4']]);
- expect(result.mappings.images.size).toBe(0);
+ expect(ledger.boardImageNames).toEqual(['board-unreferenced.png']);
+ expect(starImages).toHaveBeenCalledWith(['board-unreferenced.png'], undefined);
+ // The document's own `a.png` is not board media here, so it deduplicates as a plain reference.
+ expect(result.mappings.images.get('a.png')).toBe('loose-a.png');
+ expect(ledger.imageNames).toEqual(['loose-a.png']);
});
- it('never asks the video endpoint about an images-only archive', async () => {
- const findVideos = vi.fn(() => Promise.resolve(new Set<string>()));
+ it('restores a v2 archive as document references only, with no board media', async () => {
+ const archive = await readInvkArchive(await validArchive());
+ const ledger = createRestoredMediaLedger(null);
- await restoreArchiveAssets(await contents(), {
- findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
- findExistingVideoNames: findVideos,
- uploadArchiveImage: () => Promise.reject(new Error('should not be called')),
- });
+ const result = await restoreArchiveMedia(
+ archive,
+ { boardId: null, ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },
+ restoreDeps()
+ );
- expect(findVideos).not.toHaveBeenCalled();
+ expect(result.boardItemIssues).toEqual([]);
+ expect(ledger).toMatchObject({ boardImageNames: [], boardVideoNames: [], imageNames: ['loose-a.png'] });
});
- it('survives a fallback cover that fails to upload', async () => {
- const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });
+ it('deduplicates a v2 reference the destination already has', async () => {
+ const archive = await readInvkArchive(await validArchive());
+ const ledger = createRestoredMediaLedger(null);
+ const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'never', width: 1 }));
- withCover.images.delete('a.png');
-
- const result = await restoreArchiveAssets(withCover, {
- findExistingImageNames: () => Promise.resolve(new Set()),
- uploadArchiveImage: () => Promise.reject(new Error('nope')),
- });
+ const result = await restoreArchiveMedia(
+ archive,
+ { boardId: null, ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },
+ restoreDeps({ findExistingImageNames: () => Promise.resolve(new Set(['a.png'])), uploadImage })
+ );
- expect(result.coverImageName).toBeNull();
- expect(result.documentReferenceIssues.map((issue) => issue.name)).toEqual(['a.png']);
+ expect(uploadImage).not.toHaveBeenCalled();
+ expect(result.mappings.images.size).toBe(0);
});
- it('announces a video entry as a video, whatever its extension', async () => {
- const videoDocument = {
- ...document(),
- projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.unknown' } } }, id: 'n' }] },
- };
- const withVideo = await readInvkArchive(
- await archiveFile({
- 'manifest.json': JSON.stringify(manifest()),
- 'project.json': JSON.stringify(videoDocument),
+ it('announces a bundled video as a video, whatever its extension', async () => {
+ const archive = await readInvkArchive(
+ await v3Archive({
+ 'board.json': boardEntry([boardItem({ kind: 'video', name: 'clip.unknown' })]),
'videos/clip.unknown': new Uint8Array([7]),
})
);
- const uploadVideo = vi.fn(() => Promise.resolve({ videoName: 'server-clip.mp4' }));
-
- await restoreArchiveAssets(withVideo, {
- findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
- findExistingVideoNames: () => Promise.resolve(new Set()),
- uploadArchiveVideo: uploadVideo,
- });
+ const uploadBoardVideo = vi.fn(() => Promise.resolve({ videoName: 'board-clip.mp4' }));
+
+ await restoreArchiveMedia(
+ archive,
+ {
+ boardId: 'staging',
+ ledger: createRestoredMediaLedger('staging'),
+ projectDocument: archive.projectDocument,
+ projectId: 'project-new',
+ },
+ restoreDeps({ uploadBoardVideo })
+ );
- // `image/png` here would be announced to the video endpoint as an image and
- // refused before the bytes were read.
- expect(uploadVideo).toHaveBeenCalledWith(new Uint8Array([7]), 'clip.unknown', {
+ // `image/png` here would be announced to the video endpoint as an image and refused before the
+ // bytes were read.
+ expect(uploadBoardVideo).toHaveBeenCalledWith(new Uint8Array([7]), 'clip.unknown', {
+ boardId: 'staging',
+ category: 'general',
contentType: 'video/mp4',
- signal: undefined,
});
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
index ccc53e258c..6cc26cefcd 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
@@ -1,51 +1,51 @@
import { mapWithConcurrency } from '@platform/core/concurrency';
import { collectLiveAssetRefs, selectCoverImageName } from '@workbench/projects/projectAssets';
-import type { UploadedImage, UploadedVideo } from './assetTransport';
-import type { InvkManifest } from './manifest';
-import type { InvkMediaIssue } from './transfer';
+import type { InvkBoardSnapshot } from './board';
+import type {
+ MediaMaterializer,
+ RestoredMediaLedger,
+ RestoreProjectMediaDeps,
+ RestoreProjectMediaResult,
+} from './restoreProjectMedia';
+import type { InvkMediaRef } from './transfer';
import { INVK_MAX_ARCHIVE_BYTES, readArchive, readEntryText } from './archive';
+import { mimeForEntryName, uploadBoardImage, uploadBoardVideo } from './assetTransport';
+import { parseInvkBoardSnapshot } from './board';
import {
- findExistingImageNames,
- findExistingVideoNames,
- mimeForEntryName,
- uploadArchiveImage,
- uploadArchiveVideo,
-} from './assetTransport';
-import {
+ INVK_BOARD_ENTRY,
INVK_DOCUMENT_ENTRY,
INVK_IMAGES_PREFIX,
INVK_MANIFEST_ENTRY,
INVK_VIDEOS_PREFIX,
InvkFormatError,
} from './format';
-import { parseInvkManifest } from './manifest';
-import { createTransferIssueLog } from './transfer';
+import { type InvkManifest, parseInvkManifest } from './manifest';
+import { restoreProjectMedia } from './restoreProjectMedia';
+import { toMediaRefs } from './transfer';
/**
* Reading an `.invk` back, in two steps a caller can put a decision between.
*
- * {@link readInvkArchive} is pure inspection: unpack, validate the manifest,
- * parse the document, index the bundled bytes. It touches no network and mutates
- * nothing, so a caller can read a file, discover it is a legacy canvas project,
- * and say so without having created anything.
+ * {@link readInvkArchive} is pure inspection: unpack, validate the manifest, parse the document and
+ * — for a v3 archive — the board enumeration, then index the bundled bytes. It touches no network
+ * and mutates nothing, so a caller can read a file, discover it is a legacy canvas project, and say
+ * so without having created anything. Everything structural fails here, before a board or a single
+ * uploaded image exists.
*
- * {@link restoreArchiveAssets} is the part with consequences: ask the server
- * which referenced assets it already has, upload the rest out of the archive,
- * and report the old-to-new renames. It deliberately does *not* touch the
- * document — the caller applies the mapping, because the caller is also the one
- * assigning the new project id.
+ * {@link restoreArchiveMedia} is the part with consequences. It is a thin wiring of
+ * `restoreProjectMedia`, which is shared with duplication: this module supplies the one thing that
+ * differs, namely that the bytes come out of the archive.
*
- * Deduplication is what makes re-importing cheap and makes importing onto the
- * machine that exported it nearly free: an image already on the server is never
- * uploaded twice, so nothing accumulates.
+ * Neither touches the document. The caller applies the returned mapping, because the caller is also
+ * the one assigning the new project id.
*/
/** Simultaneous uploads. Matches the previous frontend's limit. */
-const ASSET_UPLOAD_CONCURRENCY = 5;
+const BOARD_UPLOAD_CONCURRENCY = 5;
-export interface InvkArchiveContents {
+interface InvkArchiveBase {
/** Bundled preview bytes and the entry they came from, when the archive has one. */
cover: { bytes: Uint8Array; entryName: string } | null;
/** Bundled image bytes, keyed by the image name the exporting server used. */
@@ -56,6 +56,25 @@ export interface InvkArchiveContents {
videos: Map<string, Uint8Array>;
}
+/** An archive written before board membership travelled: the document and its bytes, nothing else. */
+export interface InvkArchiveV2 extends InvkArchiveBase {
+ boardSnapshot: null;
+ version: 2;
+}
+
+/** An archive that also states what was on the project's board. */
+export interface InvkArchiveV3 extends InvkArchiveBase {
+ boardSnapshot: InvkBoardSnapshot;
+ version: 3;
+}
+
+/**
+ * Discriminated on the version rather than carrying an optional snapshot, so "this archive predates
+ * boards" and "this archive's board was empty" cannot be confused — they call for different
+ * restores, and only one of them is allowed to invent an empty board.
+ */
+export type InvkArchiveContents = InvkArchiveV2 | InvkArchiveV3;
+
const parseDocumentEntry = (bytes: Uint8Array): Record<string, unknown> => {
let parsed: unknown;
@@ -72,6 +91,38 @@ const parseDocumentEntry = (bytes: Uint8Array): Record<string, unknown> => {
return parsed as Record<string, unknown>;
};
+const parseBoardEntry = (entries: ReadonlyMap<string, Uint8Array>): InvkBoardSnapshot => {
+ const entry = entries.get(INVK_BOARD_ENTRY);
+
+ if (!entry) {
+ throw new InvkFormatError('damaged', `Archive has no ${INVK_BOARD_ENTRY}.`);
+ }
+
+ try {
+ return parseInvkBoardSnapshot(JSON.parse(readEntryText(entry)));
+ } catch (error) {
+ if (error instanceof InvkFormatError) {
+ throw error;
+ }
+
+ throw new InvkFormatError('damaged', `${INVK_BOARD_ENTRY} is not valid JSON.`);
+ }
+};
+
+/**
+ * The part of `images/<name>` that is a name, or `null` for anything that is not.
+ *
+ * A ZIP path is attacker-controlled text. `images/../../x.png` and `images/nested/x.png` both have a
+ * remainder that is not a file name, and either would let an entry masquerade as media the board
+ * enumeration then asks for by name. Media names on the server never contain a separator, so the
+ * check costs nothing legitimate.
+ */
+const toSafeBasename = (path: string, prefix: string): string | null => {
+ const name = path.slice(prefix.length);
+
+ return name === '' || name === '.' || name === '..' || /[/\\\0]/u.test(name) ? null : name;
+};
+
/** Unpack and validate an archive. Throws {@link InvkFormatError} and nothing else. */
export const readInvkArchive = async (file: File): Promise<InvkArchiveContents> => {
if (file.size > INVK_MAX_ARCHIVE_BYTES) {
@@ -100,270 +151,150 @@ export const readInvkArchive = async (file: File): Promise<InvkArchiveContents>
throw new InvkFormatError('damaged', `Archive has no ${INVK_DOCUMENT_ENTRY}.`);
}
+ // Before the bytes are indexed: a v3 archive whose enumeration is malformed must create nothing,
+ // and the enumeration is what decides which of those bytes are board media at all.
+ const boardSnapshot = manifest.version === 3 ? parseBoardEntry(entries) : null;
const images = new Map<string, Uint8Array>();
const videos = new Map<string, Uint8Array>();
for (const [path, bytes] of entries) {
- if (path.startsWith(INVK_IMAGES_PREFIX)) {
- images.set(path.slice(INVK_IMAGES_PREFIX.length), bytes);
- continue;
- }
+ for (const [prefix, store] of [
+ [INVK_IMAGES_PREFIX, images],
+ [INVK_VIDEOS_PREFIX, videos],
+ ] as const) {
+ if (!path.startsWith(prefix)) {
+ continue;
+ }
+
+ const name = toSafeBasename(path, prefix);
- if (path.startsWith(INVK_VIDEOS_PREFIX)) {
- videos.set(path.slice(INVK_VIDEOS_PREFIX.length), bytes);
+ if (name !== null) {
+ store.set(name, bytes);
+ }
}
}
const coverBytes = manifest.cover === undefined ? undefined : entries.get(manifest.cover);
-
- return {
+ const contents = {
cover: coverBytes === undefined ? null : { bytes: coverBytes, entryName: manifest.cover! },
images,
manifest,
projectDocument: parseDocumentEntry(documentEntry),
videos,
};
-};
-
-export interface RestoreAssetsResult {
- /** The uploaded cover's server name, when the archive carried one. */
- coverImageName: string | null;
- /** Referenced assets the archive did not carry and the server does not have, of either kind. */
- /** References neither the archive nor this server could satisfy, with the reason. */
- documentReferenceIssues: InvkMediaIssue[];
- /** Old name to new name, per kind. Kept apart because the namespaces are. */
- mappings: { images: Map<string, string>; videos: Map<string, string> };
- /** Authoritative server identities created by this restore, for failure rollback. */
- uploadedAssets: UploadedArchiveAssets;
- /** Assets uploaded from the archive, of either kind. */
- uploadedCount: number;
-}
-
-export interface UploadedArchiveAssets {
- imageNames: string[];
- videoNames: string[];
-}
-
-export interface RollbackArchiveAssetsDeps {
- deleteArchiveImages?: (imageNames: string[], signal?: AbortSignal) => Promise<void>;
- deleteArchiveVideos?: (videoNames: string[], signal?: AbortSignal) => Promise<void>;
- signal?: AbortSignal;
-}
-
-/** Best-effort cleanup for server identities created by an import that could not create its project. */
-export const rollbackArchiveAssets = async (
- uploadedAssets: UploadedArchiveAssets,
- deps: RollbackArchiveAssetsDeps = {}
-): Promise<void> => {
- const transport = await import('./assetTransport');
- const deleteImages = deps.deleteArchiveImages ?? transport.deleteArchiveImages;
- const deleteVideos = deps.deleteArchiveVideos ?? transport.deleteArchiveVideos;
- const deletions: Promise<void>[] = [];
-
- if (uploadedAssets.imageNames.length > 0) {
- deletions.push(deleteImages(uploadedAssets.imageNames, deps.signal));
- }
-
- if (uploadedAssets.videoNames.length > 0) {
- deletions.push(deleteVideos(uploadedAssets.videoNames, deps.signal));
- }
- await Promise.allSettled(deletions);
+ return boardSnapshot === null
+ ? { ...contents, boardSnapshot: null, version: 2 }
+ : { ...contents, boardSnapshot, version: 3 };
};
-export interface RestoreAssetsDeps {
- findExistingImageNames?: (imageNames: readonly string[], signal?: AbortSignal) => Promise<Set<string>>;
- findExistingVideoNames?: (videoNames: readonly string[], signal?: AbortSignal) => Promise<Set<string>>;
- onProgress?: (progress: { completed: number; total: number }) => void;
+export interface ArchiveBoardUploadDeps {
signal?: AbortSignal;
- uploadArchiveImage?: (
- bytes: Uint8Array,
- fileName: string,
- options?: { contentType?: string; signal?: AbortSignal }
- ) => Promise<UploadedImage>;
- uploadArchiveVideo?: (
- bytes: Uint8Array,
- fileName: string,
- options?: { contentType?: string; signal?: AbortSignal }
- ) => Promise<UploadedVideo>;
-}
-
-interface PendingUpload {
- bytes: Uint8Array;
- kind: 'image' | 'video';
- name: string;
+ uploadBoardImage?: typeof uploadBoardImage;
+ uploadBoardVideo?: typeof uploadBoardVideo;
}
/**
- * The cover, preferring an image the restore already put on this server.
+ * The import half of the materialization seam: board media comes out of the archive.
*
- * The archive's `cover` entry is a thumbnail of an image the document also
- * references, and `getProjectCoverUrl` asks for a thumbnail anyway — so once
- * that image is restored, pointing the index at it is the same picture without
- * a second copy. Uploading the entry unconditionally instead left one orphan
- * per import: covers go up under the canvas's private `'other'` category, which
- * appears in no gallery view and no board count, so nobody could ever find or
- * delete them.
- *
- * The bundled bytes are the fallback, for the case that made them worth
- * carrying: a cover whose source image is dangling here.
+ * Every descriptor is uploaded, with no existence check — see `restoreProjectMedia` for why board
+ * media can never reuse a name the destination already has. A descriptor the archive carries no
+ * bytes for is reported rather than skipped silently: the exporting server told us it was there,
+ * so its absence is a loss worth naming.
*/
-const resolveCoverImageName = async (input: {
- contents: InvkArchiveContents;
- mappings: { images: Map<string, string> };
- newlyUploadedImageNames: Set<string>;
- restoredImageNames: ReadonlySet<string>;
- signal?: AbortSignal;
- uploadImage: NonNullable<RestoreAssetsDeps['uploadArchiveImage']>;
-}): Promise<string | null> => {
- const documentCoverName = selectCoverImageName(input.contents.projectDocument);
-
- if (documentCoverName !== null) {
- const restoredName = input.mappings.images.get(documentCoverName) ?? documentCoverName;
-
- if (input.restoredImageNames.has(restoredName)) {
- return restoredName;
- }
- }
-
- const { cover } = input.contents;
+export const createArchiveMediaMaterializer = (
+ archive: Pick<InvkArchiveBase, 'images' | 'videos'>,
+ deps: ArchiveBoardUploadDeps = {}
+): MediaMaterializer => {
+ const uploadImage = deps.uploadBoardImage ?? uploadBoardImage;
+ const uploadVideo = deps.uploadBoardVideo ?? uploadBoardVideo;
- if (cover === null) {
- return null;
- }
+ return async (items, boardId, onItemSettled) => {
+ const result: Awaited<ReturnType<MediaMaterializer>> = { failed: [], materialized: [] };
- try {
- const uploaded = await input.uploadImage(cover.bytes, cover.entryName, {
- contentType: mimeForEntryName(cover.entryName),
- signal: input.signal,
- });
+ await mapWithConcurrency(items, BOARD_UPLOAD_CONCURRENCY, async (item) => {
+ const bytes = (item.kind === 'image' ? archive.images : archive.videos).get(item.name);
- input.newlyUploadedImageNames.add(uploaded.imageName);
-
- return uploaded.imageName;
- } catch {
- // A project with no cover shows the folder glyph, which is a state the
- // library already renders. Not worth failing an import over.
- return null;
- }
-};
+ if (bytes === undefined) {
+ result.failed.push({ kind: item.kind, name: item.name, reason: 'missing-entry' });
+ onItemSettled();
-/**
- * Make the archive's assets available on this server. Only what is missing gets
- * uploaded; a referenced asset that is neither on the server nor in the archive
- * is reported as dangling and its reference is left exactly as it is, so the
- * project still opens with one broken layer rather than not at all.
- */
-export const restoreArchiveAssets = async (
- contents: InvkArchiveContents,
- deps: RestoreAssetsDeps = {}
-): Promise<RestoreAssetsResult> => {
- const checkExistingImages = deps.findExistingImageNames ?? findExistingImageNames;
- const checkExistingVideos = deps.findExistingVideoNames ?? findExistingVideoNames;
- const uploadImage = deps.uploadArchiveImage ?? uploadArchiveImage;
- const uploadVideo = deps.uploadArchiveVideo ?? uploadArchiveVideo;
-
- const referenced = collectLiveAssetRefs(contents.projectDocument);
- const referencedImages = [...referenced.images].sort();
- const referencedVideos = [...referenced.videos].sort();
-
- // Both existence checks go out before either upload does; they are
- // independent, and a project with videos should not wait out the image pass.
- const [existingImages, existingVideos] = await Promise.all([
- checkExistingImages(referencedImages, deps.signal),
- referencedVideos.length === 0
- ? Promise.resolve(new Set<string>())
- : checkExistingVideos(referencedVideos, deps.signal),
- ]);
-
- const issues = createTransferIssueLog();
- const pending: PendingUpload[] = [];
-
- for (const [names, existing, store, kind] of [
- [referencedImages, existingImages, contents.images, 'image'],
- [referencedVideos, existingVideos, contents.videos, 'video'],
- ] as const) {
- for (const name of names) {
- if (existing.has(name)) {
- continue;
+ return;
}
- const bytes = store.get(name);
-
- if (bytes === undefined) {
- issues.addDocumentReferenceIssue({ kind, name }, 'missing-entry');
- continue;
+ try {
+ const options = {
+ boardId,
+ category: item.category,
+ contentType: mimeForEntryName(item.name, item.kind),
+ ...(deps.signal === undefined ? {} : { signal: deps.signal }),
+ };
+ const name =
+ item.kind === 'image'
+ ? (await uploadImage(bytes, item.name, options)).imageName
+ : (await uploadVideo(bytes, item.name, options)).videoName;
+
+ result.materialized.push({ kind: item.kind, name, sourceName: item.name });
+ } catch {
+ result.failed.push({ kind: item.kind, name: item.name, reason: 'upload-failed' });
}
- pending.push({ bytes, kind, name });
- }
- }
+ onItemSettled();
+ });
- const mappings = { images: new Map<string, string>(), videos: new Map<string, string>() };
-
- // The cover is not part of the document, so it does not come through the
- // reference set; it is still counted here so progress spans the whole restore.
- const total = pending.length + (contents.cover === null ? 0 : 1);
- let completed = 0;
- let uploadedCount = 0;
- const newlyUploadedImageNames = new Set<string>();
- const newlyUploadedVideoNames = new Set<string>();
-
- /** Images this server can serve when the restore is done, under their final names. */
- const restoredImageNames = new Set(referencedImages.filter((name) => existingImages.has(name)));
-
- await mapWithConcurrency(pending, ASSET_UPLOAD_CONCURRENCY, async ({ bytes, kind, name }) => {
- 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;
-
- uploadedCount += 1;
-
- if (kind === 'image') {
- newlyUploadedImageNames.add(restoredName);
- restoredImageNames.add(restoredName);
- } else {
- newlyUploadedVideoNames.add(restoredName);
- }
+ return result;
+ };
+};
- if (restoredName !== name) {
- mappings[kind === 'image' ? 'images' : 'videos'].set(name, restoredName);
- }
- } catch {
- // A failed upload leaves the reference pointing at a name this server does
- // not have — the same outcome as an asset the archive never carried.
- issues.addDocumentReferenceIssue({ kind, name }, 'upload-failed');
- }
+export interface RestoreArchiveMediaInput {
+ /** The staging board for this archive's board media, or `null` when it carries none. */
+ boardId: string | null;
+ /** The canonical document, already rehydrated and re-serialized. */
+ projectDocument: Record<string, unknown>;
+ /** The id the project will be created under. */
+ projectId: string;
+ /** Written as the restore runs, so a failure can undo exactly what it made. */
+ ledger: RestoredMediaLedger;
+}
- completed += 1;
- deps.onProgress?.({ completed, total });
- });
-
- const coverImageName = await resolveCoverImageName({
- contents,
- mappings,
- newlyUploadedImageNames,
- restoredImageNames,
- signal: deps.signal,
- uploadImage,
- });
-
- if (contents.cover !== null) {
- completed += 1;
- deps.onProgress?.({ completed, total });
- }
+export type RestoreArchiveMediaDeps = ArchiveBoardUploadDeps &
+ Omit<RestoreProjectMediaDeps, 'documentMediaBytes' | 'materializeBoardMedia'>;
- return {
- coverImageName,
- documentReferenceIssues: issues.toIssues().documentReferenceIssues,
- mappings,
- uploadedAssets: {
- imageNames: [...newlyUploadedImageNames].sort(),
- videoNames: [...newlyUploadedVideoNames].sort(),
+/**
+ * Make an archive's media exist on this server: board items onto the staging board under fresh
+ * identities, document-only references deduplicated against what is already here.
+ *
+ * A v2 archive has no board, so this is exactly the v2 restore it always was — the shared engine
+ * simply sees an empty descriptor list.
+ */
+export const restoreArchiveMedia = (
+ archive: InvkArchiveContents,
+ input: RestoreArchiveMediaInput,
+ deps: RestoreArchiveMediaDeps = {}
+): Promise<RestoreProjectMediaResult> => {
+ const { signal, uploadBoardImage: overrideImage, uploadBoardVideo: overrideVideo, ...restoreDeps } = deps;
+ const bytesFor = (ref: InvkMediaRef): Uint8Array | undefined =>
+ (ref.kind === 'image' ? archive.images : archive.videos).get(ref.name);
+
+ return restoreProjectMedia(
+ {
+ boardId: input.boardId,
+ boardItems: archive.boardSnapshot?.items ?? [],
+ coverBytes: archive.cover,
+ coverSourceImageName: selectCoverImageName(input.projectDocument),
+ documentRefs: toMediaRefs(collectLiveAssetRefs(input.projectDocument)),
+ ledger: input.ledger,
+ projectId: input.projectId,
},
- uploadedCount,
- };
+ {
+ ...restoreDeps,
+ documentMediaBytes: bytesFor,
+ materializeBoardMedia: createArchiveMediaMaterializer(archive, {
+ ...(signal === undefined ? {} : { signal }),
+ ...(overrideImage === undefined ? {} : { uploadBoardImage: overrideImage }),
+ ...(overrideVideo === undefined ? {} : { uploadBoardVideo: overrideVideo }),
+ }),
+ ...(signal === undefined ? {} : { signal }),
+ }
+ );
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts
new file mode 100644
index 0000000000..55dd638a88
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts
@@ -0,0 +1,409 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { InvkBoardItem } from './board';
+import type { MaterializeResult, MediaMaterializer, RestoreProjectMediaDeps } from './restoreProjectMedia';
+import type { InvkMediaRef } from './transfer';
+
+import { createRestoredMediaLedger, restoreProjectMedia, rollbackRestoredMedia } from './restoreProjectMedia';
+
+/**
+ * The restore engine, with the byte source and the transport replaced.
+ *
+ * These are the rules that make a restored project *its own* project rather than a second view of
+ * somebody else's: board media always gets a new identity, a board item that fails takes its
+ * document references down with it rather than letting them resolve to a stranger, and everything
+ * that could not be carried is reported against the role it failed in.
+ */
+
+const BOARD_ID = 'staging-board';
+const PROJECT_ID = 'project-new';
+
+const boardItem = (overrides: Partial<InvkBoardItem> = {}): InvkBoardItem => ({
+ category: 'general',
+ kind: 'image',
+ name: 'board.png',
+ starred: false,
+ ...overrides,
+});
+
+const imageRef = (name: string): InvkMediaRef => ({ kind: 'image', name });
+
+/** Materializes everything, under the fresh names the destination server would assign. */
+const freshNameMaterializer =
+ (options: { fail?: ReadonlySet<string> } = {}): MediaMaterializer =>
+ (items, boardId, onItemSettled) => {
+ const result: MaterializeResult = { failed: [], materialized: [] };
+
+ for (const item of items) {
+ if (options.fail?.has(item.name)) {
+ result.failed.push({ kind: item.kind, name: item.name, reason: 'upload-failed' });
+ } else {
+ result.materialized.push({ kind: item.kind, name: `${boardId}-${item.name}`, sourceName: item.name });
+ }
+
+ onItemSettled();
+ }
+
+ return Promise.resolve(result);
+ };
+
+const restore = (
+ input: {
+ boardItems?: readonly InvkBoardItem[];
+ coverBytes?: { bytes: Uint8Array; entryName: string } | null;
+ coverSourceImageName?: string | null;
+ documentRefs?: readonly InvkMediaRef[];
+ boardId?: string | null;
+ },
+ deps: Partial<RestoreProjectMediaDeps> = {}
+) => {
+ const ledger = createRestoredMediaLedger(input.boardId === undefined ? BOARD_ID : input.boardId);
+
+ return restoreProjectMedia(
+ {
+ boardId: input.boardId === undefined ? BOARD_ID : input.boardId,
+ boardItems: input.boardItems ?? [],
+ coverBytes: input.coverBytes ?? null,
+ coverSourceImageName: input.coverSourceImageName ?? null,
+ documentRefs: input.documentRefs ?? [],
+ ledger,
+ projectId: PROJECT_ID,
+ },
+ {
+ findExistingImageNames: () => Promise.resolve(new Set<string>()),
+ findExistingVideoNames: () => Promise.resolve(new Set<string>()),
+ materializeBoardMedia: freshNameMaterializer(),
+ starImages: () => Promise.resolve({ failed: [] }),
+ starVideos: () => Promise.resolve({ failed: [] }),
+ uploadImage: (_bytes, fileName) => Promise.resolve({ height: 1, imageName: `uploaded-${fileName}`, width: 1 }),
+ uploadVideo: (_bytes, fileName) => Promise.resolve({ videoName: `uploaded-${fileName}` }),
+ ...deps,
+ }
+ ).then((result) => ({ ...result, ledger }));
+};
+
+describe('board media', () => {
+ /**
+ * `board_images` has `PRIMARY KEY (image_name)`, so reusing a name would move the destination's
+ * image onto this project's board rather than copy it — and deleting either board would then take
+ * it from both. The existence check that document references get is deliberately not run here.
+ */
+ it('takes a fresh identity even when the destination already has that name', async () => {
+ const findExisting = vi.fn(() => Promise.resolve(new Set(['board.png'])));
+ const result = await restore(
+ { boardItems: [boardItem()], documentRefs: [imageRef('board.png')] },
+ { findExistingImageNames: findExisting }
+ );
+
+ expect(findExisting).not.toHaveBeenCalled();
+ expect(result.mappings.images.get('board.png')).toBe('staging-board-board.png');
+ expect(result.ledger.boardImageNames).toEqual(['staging-board-board.png']);
+ });
+
+ it('files images and videos in their own ledgers', async () => {
+ const result = await restore({
+ boardItems: [boardItem({ category: 'user' }), boardItem({ kind: 'video', name: 'clip.mp4' })],
+ });
+
+ expect(result.ledger).toMatchObject({
+ boardImageNames: ['staging-board-board.png'],
+ boardVideoNames: ['staging-board-clip.mp4'],
+ });
+ expect(result.boardItemIssues).toEqual([]);
+ });
+
+ it('stars exactly the descriptors that were starred, per kind', async () => {
+ const starImages = vi.fn(() => Promise.resolve({ failed: [] }));
+ const starVideos = vi.fn(() => Promise.resolve({ failed: [] }));
+
+ await restore(
+ {
+ boardItems: [
+ boardItem({ name: 'plain.png' }),
+ boardItem({ name: 'starred.png', starred: true }),
+ boardItem({ kind: 'video', name: 'starred.mp4', starred: true }),
+ ],
+ },
+ { starImages, starVideos }
+ );
+
+ expect(starImages).toHaveBeenCalledWith(['staging-board-starred.png'], undefined);
+ expect(starVideos).toHaveBeenCalledWith(['staging-board-starred.mp4'], undefined);
+ });
+
+ /** A star is a flag. Losing it is worth a warning, never worth losing the media or the mapping. */
+ it('keeps the media and the mapping when starring fails', async () => {
+ const result = await restore(
+ { boardItems: [boardItem({ starred: true })], documentRefs: [imageRef('board.png')] },
+ { starImages: () => Promise.resolve({ failed: ['staging-board-board.png'] }) }
+ );
+
+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'board.png', reason: 'star-failed' }]);
+ expect(result.documentReferenceIssues).toEqual([]);
+ expect(result.mappings.images.get('board.png')).toBe('staging-board-board.png');
+ });
+
+ it('reports a descriptor the source could not materialize', async () => {
+ const result = await restore(
+ { boardItems: [boardItem({ name: 'gone.png' })] },
+ {
+ materializeBoardMedia: (items, _boardId, onItemSettled) => {
+ onItemSettled();
+
+ return Promise.resolve({
+ failed: items.map((item) => ({ kind: item.kind, name: item.name, reason: 'missing-entry' as const })),
+ materialized: [],
+ });
+ },
+ }
+ );
+
+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'gone.png', reason: 'missing-entry' }]);
+ expect(result.documentReferenceIssues).toEqual([]);
+ expect(result.ledger.boardImageNames).toEqual([]);
+ });
+
+ /**
+ * The invariant this module exists for. The old name is not neutral: on the same server it is
+ * already taken, by the source project's own image.
+ */
+ it('forces an overlapping reference dangling when its board item fails', async () => {
+ const result = await restore(
+ { boardItems: [boardItem({ name: 'both.png' })], documentRefs: [imageRef('both.png')] },
+ { materializeBoardMedia: freshNameMaterializer({ fail: new Set(['both.png']) }) }
+ );
+
+ expect(result.mappings.images.get('both.png')).toBe(`${PROJECT_ID}-missing-image-0`);
+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'both.png', reason: 'upload-failed' }]);
+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'both.png', reason: 'upload-failed' }]);
+ });
+
+ it('gives every occurrence of a failed reference the same placeholder', async () => {
+ const items = [boardItem({ name: 'a.png' }), boardItem({ name: 'b.png' })];
+ const result = await restore(
+ { boardItems: items, documentRefs: [imageRef('a.png'), imageRef('b.png')] },
+ { materializeBoardMedia: freshNameMaterializer({ fail: new Set(['a.png', 'b.png']) }) }
+ );
+
+ // Derived from the descriptor's position, not from the order the failures arrived in, so two
+ // failed items can never collapse onto one placeholder.
+ expect([...result.mappings.images]).toEqual([
+ ['a.png', `${PROJECT_ID}-missing-image-0`],
+ ['b.png', `${PROJECT_ID}-missing-image-1`],
+ ]);
+ });
+
+ /** A materializer that answers neither way has still not delivered the media. */
+ it('treats an unaccounted descriptor as a failure rather than a silent success', async () => {
+ const result = await restore(
+ { boardItems: [boardItem({ name: 'ignored.png' })], documentRefs: [imageRef('ignored.png')] },
+ { materializeBoardMedia: () => Promise.resolve({ failed: [], materialized: [] }) }
+ );
+
+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'ignored.png', reason: 'upload-failed' }]);
+ expect(result.mappings.images.get('ignored.png')).toBe(`${PROJECT_ID}-missing-image-0`);
+ });
+});
+
+describe('document-only references', () => {
+ it('reuses media the destination already has instead of uploading it again', async () => {
+ const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'never', width: 1 }));
+ const result = await restore(
+ { documentRefs: [imageRef('external.png')] },
+ { findExistingImageNames: () => Promise.resolve(new Set(['external.png'])), uploadImage }
+ );
+
+ expect(uploadImage).not.toHaveBeenCalled();
+ expect(result.mappings.images.size).toBe(0);
+ expect(result.documentReferenceIssues).toEqual([]);
+ });
+
+ it('uploads a missing reference and records the rename', async () => {
+ const result = await restore(
+ { documentRefs: [imageRef('external.png')] },
+ { documentMediaBytes: () => new Uint8Array([1]) }
+ );
+
+ expect([...result.mappings.images]).toEqual([['external.png', 'uploaded-external.png']]);
+ expect(result.ledger.imageNames).toEqual(['uploaded-external.png']);
+ });
+
+ it('reports a reference with no bytes and carries on', async () => {
+ const result = await restore(
+ { documentRefs: [imageRef('a.png'), imageRef('b.png')] },
+ {
+ documentMediaBytes: (ref) => (ref.name === 'b.png' ? new Uint8Array([1]) : undefined),
+ }
+ );
+
+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'a.png', reason: 'missing-entry' }]);
+ expect(result.ledger.imageNames).toEqual(['uploaded-b.png']);
+ });
+
+ it('reports a failed upload as dangling rather than failing the restore', async () => {
+ const result = await restore(
+ { documentRefs: [imageRef('external.png')] },
+ { documentMediaBytes: () => new Uint8Array([1]), uploadImage: () => Promise.reject(new Error('rejected')) }
+ );
+
+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'external.png', reason: 'upload-failed' }]);
+ expect(result.ledger.imageNames).toEqual([]);
+ });
+
+ /** An item that is both is board media; asking the destination about it would be the wrong question. */
+ it('never checks the destination for a reference the board already owns', async () => {
+ const findExisting = vi.fn(() => Promise.resolve(new Set<string>()));
+
+ await restore(
+ { boardItems: [boardItem({ name: 'both.png' })], documentRefs: [imageRef('both.png')] },
+ { findExistingImageNames: findExisting }
+ );
+
+ expect(findExisting).not.toHaveBeenCalled();
+ });
+
+ it('leaves the video endpoints alone for an images-only restore', async () => {
+ const findVideos = vi.fn(() => Promise.resolve(new Set<string>()));
+
+ await restore({ documentRefs: [imageRef('a.png')] }, { findExistingVideoNames: findVideos });
+
+ expect(findVideos).not.toHaveBeenCalled();
+ });
+});
+
+describe('the cover', () => {
+ const cover = { bytes: new Uint8Array([9]), entryName: 'cover.webp' };
+
+ it('points at the restored board image rather than uploading the thumbnail again', async () => {
+ const result = await restore({
+ boardItems: [boardItem()],
+ coverBytes: cover,
+ coverSourceImageName: 'board.png',
+ });
+
+ expect(result.coverImageName).toBe('staging-board-board.png');
+ expect(result.ledger.coverImageName).toBeNull();
+ });
+
+ it('falls back to the bundled thumbnail when its source could not be restored', async () => {
+ const result = await restore(
+ { boardItems: [boardItem()], coverBytes: cover, coverSourceImageName: 'board.png' },
+ { materializeBoardMedia: freshNameMaterializer({ fail: new Set(['board.png']) }) }
+ );
+
+ expect(result.coverImageName).toBe('uploaded-cover.webp');
+ expect(result.ledger.coverImageName).toBe('uploaded-cover.webp');
+ });
+
+ it('survives a fallback cover that will not upload', async () => {
+ const result = await restore(
+ { coverBytes: cover, coverSourceImageName: 'gone.png' },
+ { uploadImage: () => Promise.reject(new Error('nope')) }
+ );
+
+ expect(result.coverImageName).toBeNull();
+ });
+});
+
+describe('progress', () => {
+ it('counts each board item as it settles, then each upload', async () => {
+ const onProgress = vi.fn();
+
+ await restore(
+ {
+ boardItems: [boardItem({ name: 'one.png' }), boardItem({ name: 'two.png' })],
+ documentRefs: [imageRef('external.png')],
+ },
+ { documentMediaBytes: () => new Uint8Array([1]), onProgress }
+ );
+
+ expect(onProgress.mock.calls.map(([progress]) => progress)).toEqual([
+ { completed: 1, total: 3 },
+ { completed: 2, total: 3 },
+ { completed: 3, total: 3 },
+ ]);
+ });
+
+ it('drops a deduplicated reference out of the total rather than leaving it unfinished', async () => {
+ const onProgress = vi.fn();
+
+ await restore(
+ { boardItems: [boardItem()], documentRefs: [imageRef('external.png')] },
+ { findExistingImageNames: () => Promise.resolve(new Set(['external.png'])), onProgress }
+ );
+
+ expect(onProgress.mock.calls.at(-1)?.[0]).toEqual({ completed: 1, total: 1 });
+ });
+});
+
+describe('rollbackRestoredMedia', () => {
+ const ledger = () => ({
+ boardId: BOARD_ID,
+ boardImageNames: ['board-image'],
+ boardVideoNames: ['board-video'],
+ coverImageName: 'cover-image',
+ imageNames: ['document-image'],
+ videoNames: ['document-video'],
+ });
+
+ it('deletes exactly what the restore created, then the board it created them on', async () => {
+ const order: string[] = [];
+ const deleteImages = vi.fn((names: string[]) => {
+ order.push(`images:${names.join(',')}`);
+
+ return Promise.resolve();
+ });
+ const deleteVideos = vi.fn((names: string[]) => {
+ order.push(`videos:${names.join(',')}`);
+
+ return Promise.resolve();
+ });
+ const deleteBoard = vi.fn((boardId: string) => {
+ order.push(`board:${boardId}`);
+
+ return Promise.resolve();
+ });
+
+ await rollbackRestoredMedia(ledger(), { deleteBoard, deleteImages, deleteVideos });
+
+ expect(deleteImages).toHaveBeenCalledWith(['board-image', 'cover-image', 'document-image'], undefined);
+ expect(deleteVideos).toHaveBeenCalledWith(['board-video', 'document-video'], undefined);
+ // The board goes last, and without `include_images`, so anything that wandered onto it while
+ // the import ran survives as Uncategorized.
+ expect(order.at(-1)).toBe(`board:${BOARD_ID}`);
+ });
+
+ it('still drops the board when the media deletions fail', async () => {
+ const deleteBoard = vi.fn(() => Promise.resolve());
+
+ await rollbackRestoredMedia(ledger(), {
+ deleteBoard,
+ deleteImages: () => Promise.reject(new Error('image cleanup failed')),
+ deleteVideos: () => Promise.reject(new Error('video cleanup failed')),
+ });
+
+ expect(deleteBoard).toHaveBeenCalledWith(BOARD_ID, undefined);
+ });
+
+ it('never rejects, whatever the cleanup does', async () => {
+ await expect(
+ rollbackRestoredMedia(ledger(), {
+ deleteBoard: () => Promise.reject(new Error('board cleanup failed')),
+ deleteImages: () => Promise.resolve(),
+ deleteVideos: () => Promise.resolve(),
+ })
+ ).resolves.toBeUndefined();
+ });
+
+ it('issues no requests for a restore that created nothing', async () => {
+ const deleteImages = vi.fn(() => Promise.resolve());
+ const deleteVideos = vi.fn(() => Promise.resolve());
+ const deleteBoard = vi.fn(() => Promise.resolve());
+
+ await rollbackRestoredMedia(createRestoredMediaLedger(null), { deleteBoard, deleteImages, deleteVideos });
+
+ expect(deleteImages).not.toHaveBeenCalled();
+ expect(deleteVideos).not.toHaveBeenCalled();
+ expect(deleteBoard).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
new file mode 100644
index 0000000000..8f16cdde5c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
@@ -0,0 +1,490 @@
+import { mapWithConcurrency } from '@platform/core/concurrency';
+
+import type { InvkBoardItem, InvkMediaKind } from './board';
+import type { InvkMediaRef, ProjectTransferIssues } from './transfer';
+
+import {
+ deleteArchiveImages,
+ deleteArchiveVideos,
+ deleteStagingBoard,
+ findExistingImageNames,
+ findExistingVideoNames,
+ mimeForEntryName,
+ starImages,
+ starVideos,
+ type UploadedImage,
+ type UploadedVideo,
+ uploadArchiveImage,
+ uploadArchiveVideo,
+} from './assetTransport';
+import { buildMissingMediaName, createTransferIssueLog, toMediaKey } from './transfer';
+
+/**
+ * Putting a project's media on this server, for whichever direction needs it.
+ *
+ * Import and duplication ask the same question — "make this project's media exist here, under
+ * identities this project owns" — and differ in exactly one step: where the bytes come from.
+ * Import has them in the archive; duplication has them already on this server and copies them
+ * without a byte ever reaching the browser. That step is {@link MediaMaterializer}, and everything
+ * around it — planning, remapping, starring, issue reporting, the rollback ledger — is shared.
+ *
+ * ### Board media always gets a new identity; document references may be reused
+ *
+ * `board_images` has `PRIMARY KEY (image_name)`: an image sits on exactly one board. A restore that
+ * saw its own name already on the destination and reused it would not be restoring the project's
+ * board, it would be *moving* somebody else's image onto it — and deleting either project's board
+ * would then take that image from both. So every board item is materialized fresh, with no
+ * existence check, and the document is rewritten to the new name.
+ *
+ * Document-only references are pointers rather than membership, so an image the destination already
+ * has satisfies them. That is the v2 behaviour and it is still right: it is what makes re-importing
+ * your own export nearly free instead of doubling your disk.
+ *
+ * ### A failed board item must not resolve to a stranger
+ *
+ * The dangerous case is an item that is *both* on the board and referenced by the document, whose
+ * materialization fails. Leaving the reference on the old name is not "no worse than before": on the
+ * same server — every duplication, and every re-import — that name is already taken, by the source
+ * project's own image. The project would open showing the right picture from the wrong owner, and
+ * deleting the original would break it with no explanation. So a failed board item forces its
+ * document references onto {@link buildMissingMediaName}, which resolves to nothing and renders as
+ * a missing layer, exactly as a dangling v2 reference already does.
+ */
+
+/** Simultaneous uploads. Matches the previous frontend's limit. */
+const ASSET_UPLOAD_CONCURRENCY = 5;
+
+/** One board item that now exists here, under the name this server chose for it. */
+export interface MaterializedMedia {
+ kind: InvkMediaKind;
+ /** The authoritative identity this server assigned. */
+ name: string;
+ /** The name the exporting server used, which the document still refers to. */
+ sourceName: string;
+}
+
+export interface MaterializeFailure {
+ kind: InvkMediaKind;
+ /** The source name, so a caller can match it against the descriptor it came from. */
+ name: string;
+ reason: 'missing-entry' | 'upload-failed';
+}
+
+export interface MaterializeResult {
+ failed: MaterializeFailure[];
+ materialized: MaterializedMedia[];
+}
+
+/**
+ * Make board media exist on `boardId`, however this direction gets its bytes.
+ *
+ * `onItemSettled` is called once per descriptor, succeeded or failed. Restoring a board is the bulk
+ * of an import's wall time, so a progress count that only moved once the whole board was done would
+ * sit at zero through the part people actually wait for.
+ */
+export type MediaMaterializer = (
+ items: readonly InvkBoardItem[],
+ boardId: string,
+ onItemSettled: () => void
+) => Promise<MaterializeResult>;
+
+/**
+ * Every identity a restore created, so a failure can undo exactly what it did and nothing else.
+ *
+ * Filled in as the restore runs rather than returned at the end: a restore that throws part way —
+ * a cancelled signal, an account rotation — has still created things, and a ledger only handed back
+ * on success would leave them behind.
+ */
+export interface RestoredMediaLedger {
+ /** The staging board these were created on, when this restore created one. */
+ boardId: string | null;
+ boardImageNames: string[];
+ boardVideoNames: string[];
+ /** A cover thumbnail uploaded as a fallback, unboarded. */
+ coverImageName: string | null;
+ /** Unboarded uploads made to satisfy document-only references. */
+ imageNames: string[];
+ videoNames: string[];
+}
+
+export const createRestoredMediaLedger = (boardId: string | null): RestoredMediaLedger => ({
+ boardId,
+ boardImageNames: [],
+ boardVideoNames: [],
+ coverImageName: null,
+ imageNames: [],
+ videoNames: [],
+});
+
+export interface RestoreProjectMediaInput {
+ /** The staging board to materialize onto, or `null` when this project has no board media. */
+ boardId: string | null;
+ /** The board's contents as the source enumerated them, canonically ordered. */
+ boardItems: readonly InvkBoardItem[];
+ /** Bundled cover bytes, for the case where the cover's source image cannot be restored. */
+ coverBytes: { bytes: Uint8Array; entryName: string } | null;
+ /** The image the document nominates as its cover, under its pre-restore name. */
+ coverSourceImageName: string | null;
+ /** Live references collected from the canonical document. */
+ documentRefs: readonly InvkMediaRef[];
+ /** Written as the restore runs; the caller keeps it for rollback. */
+ ledger: RestoredMediaLedger;
+ /** The id the project will be created under. Placeholder names derive from it. */
+ projectId: string;
+}
+
+export interface RestoreProjectMediaDeps {
+ /** Bytes for a document-only reference this server is missing, when the source carries any. */
+ documentMediaBytes?: (ref: InvkMediaRef) => Uint8Array | undefined;
+ findExistingImageNames?: (imageNames: readonly string[], signal?: AbortSignal) => Promise<Set<string>>;
+ findExistingVideoNames?: (videoNames: readonly string[], signal?: AbortSignal) => Promise<Set<string>>;
+ materializeBoardMedia: MediaMaterializer;
+ onProgress?: (progress: { completed: number; total: number }) => void;
+ signal?: AbortSignal;
+ starImages?: (imageNames: readonly string[], signal?: AbortSignal) => Promise<{ failed: string[] }>;
+ starVideos?: (videoNames: readonly string[], signal?: AbortSignal) => Promise<{ failed: string[] }>;
+ uploadImage?: (
+ bytes: Uint8Array,
+ fileName: string,
+ options?: { contentType?: string; signal?: AbortSignal }
+ ) => Promise<UploadedImage>;
+ uploadVideo?: (
+ bytes: Uint8Array,
+ fileName: string,
+ options?: { contentType?: string; signal?: AbortSignal }
+ ) => Promise<UploadedVideo>;
+}
+
+export interface RestoreProjectMediaResult extends ProjectTransferIssues {
+ /** The image to record as this project's cover, or `null` for a project that has none. */
+ coverImageName: string | null;
+ /** Old name to new name, per kind, for the document rewrite. */
+ mappings: { images: Map<string, string>; videos: Map<string, string> };
+}
+
+interface PendingUpload {
+ bytes: Uint8Array;
+ kind: InvkMediaKind;
+ name: string;
+}
+
+const emptyMaterializeResult = (): MaterializeResult => ({ failed: [], materialized: [] });
+
+/**
+ * The cover, preferring an image the restore already put on this server.
+ *
+ * The archive's `cover` entry is a thumbnail of an image the document also references, and
+ * `getProjectCoverUrl` asks for a thumbnail anyway — so once that image is restored, pointing the
+ * index at it is the same picture without a second copy. Uploading the entry unconditionally
+ * instead left one orphan per import: covers go up under the canvas's private `'other'` category,
+ * which appears in no gallery view and no board count, so nobody could ever find or delete them.
+ *
+ * The bundled bytes are the fallback, for the case that made them worth carrying: a cover whose
+ * source image is dangling here.
+ */
+const resolveCoverImageName = async (input: {
+ coverBytes: { bytes: Uint8Array; entryName: string } | null;
+ coverSourceImageName: string | null;
+ ledger: RestoredMediaLedger;
+ mappings: { images: ReadonlyMap<string, string> };
+ restoredImageNames: ReadonlySet<string>;
+ signal?: AbortSignal;
+ uploadImage: NonNullable<RestoreProjectMediaDeps['uploadImage']>;
+}): Promise<string | null> => {
+ if (input.coverSourceImageName !== null) {
+ const restoredName = input.mappings.images.get(input.coverSourceImageName) ?? input.coverSourceImageName;
+
+ if (input.restoredImageNames.has(restoredName)) {
+ return restoredName;
+ }
+ }
+
+ if (input.coverBytes === null) {
+ return null;
+ }
+
+ try {
+ const uploaded = await input.uploadImage(input.coverBytes.bytes, input.coverBytes.entryName, {
+ contentType: mimeForEntryName(input.coverBytes.entryName),
+ signal: input.signal,
+ });
+
+ input.ledger.coverImageName = uploaded.imageName;
+
+ return uploaded.imageName;
+ } catch {
+ // A project with no cover shows the folder glyph, which is a state the library already
+ // renders. Not worth failing an import over.
+ return null;
+ }
+};
+
+/**
+ * Restore a project's media and report what could not be carried.
+ *
+ * Nothing here throws for a media failure — a project that opens with two broken layers is worth
+ * far more than no project at all — so the only rejections are the ones that end the whole
+ * operation: a cancelled signal, an expired account.
+ */
+export const restoreProjectMedia = async (
+ input: RestoreProjectMediaInput,
+ deps: RestoreProjectMediaDeps
+): Promise<RestoreProjectMediaResult> => {
+ const checkExistingImages = deps.findExistingImageNames ?? findExistingImageNames;
+ const checkExistingVideos = deps.findExistingVideoNames ?? findExistingVideoNames;
+ const uploadImage = deps.uploadImage ?? uploadArchiveImage;
+ const uploadVideo = deps.uploadVideo ?? uploadArchiveVideo;
+ const starRestoredImages = deps.starImages ?? starImages;
+ const starRestoredVideos = deps.starVideos ?? starVideos;
+
+ const issues = createTransferIssueLog();
+ const mappings = { images: new Map<string, string>(), videos: new Map<string, string>() };
+ const documentKeys = new Set(input.documentRefs.map(toMediaKey));
+ const boardKeys = new Set(input.boardItems.map(toMediaKey));
+ /** Descriptor position, so a placeholder name does not depend on the order failures happened in. */
+ const descriptorIndexes = new Map(input.boardItems.map((item, index) => [toMediaKey(item), index]));
+ const starredKeys = new Set(input.boardItems.filter((item) => item.starred).map(toMediaKey));
+
+ // Document-only references are the ones the board does not own; those the board owns are
+ // restored as board media and their references follow the copy.
+ const documentOnlyRefs = input.documentRefs.filter((ref) => !boardKeys.has(toMediaKey(ref)));
+ const documentOnlyImages = documentOnlyRefs.filter((ref) => ref.kind === 'image').map((ref) => ref.name);
+ const documentOnlyVideos = documentOnlyRefs.filter((ref) => ref.kind === 'video').map((ref) => ref.name);
+
+ // A board with no staging board to put it on cannot be materialized; every descriptor then falls
+ // through to the unsettled pass below, which is the honest reading of "the media did not arrive".
+ const stagingBoardId = input.boardItems.length === 0 ? null : input.boardId;
+
+ let completed = 0;
+ // The document-only total is only known once the existence checks answer, so progress is reported
+ // against the worst case: every reference needing an upload. It can only finish early.
+ let total =
+ (stagingBoardId === null ? 0 : input.boardItems.length) +
+ documentOnlyRefs.length +
+ (input.coverBytes === null ? 0 : 1);
+ const advance = (): void => {
+ completed += 1;
+ deps.onProgress?.({ completed, total });
+ };
+
+ /** Names this server can serve once the restore is done, under their final identities. */
+ const restoredImageNames = new Set<string>();
+
+ const boardResult =
+ stagingBoardId === null
+ ? emptyMaterializeResult()
+ : await deps.materializeBoardMedia(input.boardItems, stagingBoardId, advance);
+
+ const starTargets = { image: [] as string[], video: [] as string[] };
+ const sourceNamesByFreshName = new Map<string, string>();
+ const settledBoardKeys = new Set<string>();
+
+ for (const entry of boardResult.materialized) {
+ const key = toMediaKey({ kind: entry.kind, name: entry.sourceName });
+
+ 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);
+ }
+
+ if (entry.sourceName !== entry.name) {
+ mappings[entry.kind === 'image' ? 'images' : 'videos'].set(entry.sourceName, entry.name);
+ }
+
+ if (starredKeys.has(key)) {
+ starTargets[entry.kind].push(entry.name);
+ }
+ }
+
+ /** A board item that did not arrive: reported, and forced dangling if the document wanted it. */
+ const failBoardItem = (failure: MaterializeFailure): void => {
+ settledBoardKeys.add(toMediaKey(failure));
+ issues.addBoardItemIssue(failure, failure.reason);
+
+ const key = toMediaKey(failure);
+
+ if (!documentKeys.has(key)) {
+ return;
+ }
+
+ mappings[failure.kind === 'image' ? 'images' : 'videos'].set(
+ failure.name,
+ buildMissingMediaName(input.projectId, failure.kind, descriptorIndexes.get(key) ?? 0)
+ );
+ issues.addDocumentReferenceIssue(failure, failure.reason);
+ };
+
+ for (const failure of boardResult.failed) {
+ failBoardItem(failure);
+ }
+
+ // A descriptor the materializer reported neither way is a failure too. Silently dropping it would
+ // leave its document reference on the old name, which is the one outcome this module exists to
+ // prevent.
+ for (const item of input.boardItems) {
+ if (!settledBoardKeys.has(toMediaKey(item))) {
+ failBoardItem({ kind: item.kind, name: item.name, reason: 'upload-failed' });
+ }
+ }
+
+ // Starring is a separate call by design: the same one import and duplication use, and the same
+ // one the gallery uses. A star that fails costs a flag, not the media, so it is reported against
+ // the board item and nowhere else — the document does not care whether a layer is starred.
+ const [imageStars, videoStars] = await Promise.all([
+ starRestoredImages(starTargets.image, deps.signal),
+ starRestoredVideos(starTargets.video, deps.signal),
+ ]);
+
+ for (const [kind, failed] of [
+ ['image', imageStars.failed],
+ ['video', videoStars.failed],
+ ] as const) {
+ for (const freshName of failed) {
+ const sourceName = sourceNamesByFreshName.get(toMediaKey({ kind, name: freshName })) ?? freshName;
+
+ issues.addBoardItemIssue({ kind, name: sourceName }, 'star-failed');
+ }
+ }
+
+ // Both existence checks go out before either upload does; they are independent, and a project
+ // with videos should not wait out the image pass.
+ const [existingImages, existingVideos] = await Promise.all([
+ documentOnlyImages.length === 0
+ ? Promise.resolve(new Set<string>())
+ : checkExistingImages(documentOnlyImages, deps.signal),
+ documentOnlyVideos.length === 0
+ ? Promise.resolve(new Set<string>())
+ : checkExistingVideos(documentOnlyVideos, deps.signal),
+ ]);
+
+ const pending: PendingUpload[] = [];
+ const plannedTotal = total;
+
+ for (const [names, existing, kind] of [
+ [documentOnlyImages, existingImages, 'image'],
+ [documentOnlyVideos, existingVideos, 'video'],
+ ] as const) {
+ for (const name of names) {
+ if (existing.has(name)) {
+ if (kind === 'image') {
+ restoredImageNames.add(name);
+ }
+
+ // Satisfied by media that is already here, which is the whole point of the dedup.
+ total -= 1;
+ continue;
+ }
+
+ const bytes = deps.documentMediaBytes?.({ kind, name });
+
+ if (bytes === undefined) {
+ issues.addDocumentReferenceIssue({ kind, name }, 'missing-entry');
+ total -= 1;
+ continue;
+ }
+
+ pending.push({ bytes, kind, name });
+ }
+ }
+
+ // Deduplication and missing bytes both shrink the work; say so, or a restore that ends with
+ // nothing left to upload reports its last count against a total it will never reach.
+ if (total !== plannedTotal) {
+ deps.onProgress?.({ completed, total });
+ }
+
+ await mapWithConcurrency(pending, ASSET_UPLOAD_CONCURRENCY, async ({ bytes, kind, name }) => {
+ 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);
+ }
+
+ if (restoredName !== name) {
+ mappings[kind === 'image' ? 'images' : 'videos'].set(name, restoredName);
+ }
+ } catch {
+ // A failed upload leaves the reference pointing at a name this server does not have — the
+ // same outcome as an asset the source never carried, and honest for the same reason.
+ issues.addDocumentReferenceIssue({ kind, name }, 'upload-failed');
+ }
+
+ advance();
+ });
+
+ const coverImageName = await resolveCoverImageName({
+ coverBytes: input.coverBytes,
+ coverSourceImageName: input.coverSourceImageName,
+ ledger: input.ledger,
+ mappings,
+ restoredImageNames,
+ ...(deps.signal === undefined ? {} : { signal: deps.signal }),
+ uploadImage,
+ });
+
+ if (input.coverBytes !== null) {
+ advance();
+ }
+
+ return { coverImageName, mappings, ...issues.toIssues() };
+};
+
+export interface RollbackRestoredMediaDeps {
+ deleteBoard?: (boardId: string, signal?: AbortSignal) => Promise<void>;
+ deleteImages?: (imageNames: string[], signal?: AbortSignal) => Promise<void>;
+ deleteVideos?: (videoNames: string[], signal?: AbortSignal) => Promise<void>;
+ signal?: AbortSignal;
+}
+
+/**
+ * Undo a restore whose project was never created — exactly the identities it made, then the board
+ * it made them on.
+ *
+ * Best-effort throughout: the failure that brought us here is the actionable one, and a cleanup
+ * that threw would replace it with a message about a delete request nobody asked for. The board
+ * goes last and without `include_images`, so a generation that landed on the staging board while
+ * the import ran survives as Uncategorized instead of being collected by a cleanup that never
+ * meant it.
+ */
+export const rollbackRestoredMedia = async (
+ ledger: RestoredMediaLedger,
+ deps: RollbackRestoredMediaDeps = {}
+): Promise<void> => {
+ const deleteImages = deps.deleteImages ?? deleteArchiveImages;
+ const deleteVideos = deps.deleteVideos ?? deleteArchiveVideos;
+ const deleteBoard = deps.deleteBoard ?? deleteStagingBoard;
+ const imageNames = [
+ ...ledger.boardImageNames,
+ ...ledger.imageNames,
+ ...(ledger.coverImageName === null ? [] : [ledger.coverImageName]),
+ ].sort();
+ const videoNames = [...ledger.boardVideoNames, ...ledger.videoNames].sort();
+
+ await Promise.allSettled([
+ imageNames.length === 0 ? Promise.resolve() : deleteImages(imageNames, deps.signal),
+ videoNames.length === 0 ? Promise.resolve() : deleteVideos(videoNames, deps.signal),
+ ]);
+
+ if (ledger.boardId === null) {
+ return;
+ }
+
+ try {
+ await deleteBoard(ledger.boardId, deps.signal);
+ } catch {
+ // An unclaimed private board is invisible clutter, not a broken state.
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 503b2ec46f..a439d86cd9 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -1,6 +1,7 @@
import { createDraftProject } from '@workbench/workbenchState';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ProjectBoardItemDTO } from './api';
import type * as coversModule from './covers';
import type * as projectFileModule from './projectFile';
import type * as persistenceModule from './syncedPersistence';
@@ -18,7 +19,7 @@ const api = vi.hoisted(() => ({
getClientStateValue: vi.fn(() => Promise.resolve(null)),
getProject: vi.fn(),
// Every export enumerates the project's board; an empty one is the v2-shaped default.
- getProjectBoardSnapshot: vi.fn(() => Promise.resolve({ items: [] })),
+ getProjectBoardSnapshot: vi.fn((): Promise<{ items: ProjectBoardItemDTO[] }> => Promise.resolve({ items: [] })),
isProjectNotFoundError: (error: unknown) =>
typeof error === 'object' && error !== null && 'status' in error && error.status === 404,
setClientStateValue: vi.fn(() => Promise.resolve()),
@@ -35,8 +36,10 @@ const transport = vi.hoisted(() => ({
fetchImageThumbnail: transport.fetchImageThumbnail,
fetchVideoBytes: transport.fetchVideoBytes,
}),
+ createStagingBoard: vi.fn(() => Promise.resolve('staging-board')),
deleteArchiveImages: vi.fn(() => Promise.resolve()),
deleteArchiveVideos: vi.fn(() => Promise.resolve()),
+ deleteStagingBoard: vi.fn(() => Promise.resolve()),
// `Uint8Array | null` up front: a fetcher that returns `null` is how the
// "server would not serve it" path is exercised, and inferring the narrower
// type here would make that untypeable at the call site.
@@ -50,12 +53,20 @@ const transport = vi.hoisted(() => ({
findExistingImageNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),
findExistingVideoNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),
mimeForEntryName: () => 'image/png',
+ starImages: vi.fn((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] })),
+ starVideos: vi.fn((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] })),
uploadArchiveImage: vi.fn((_bytes: Uint8Array, fileName: string) =>
Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 })
),
uploadArchiveVideo: vi.fn((_bytes: Uint8Array, fileName: string) =>
Promise.resolve({ videoName: `server-${fileName}` })
),
+ uploadBoardImage: vi.fn((_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ height: 1, imageName: `board-${fileName}`, width: 1 })
+ ),
+ uploadBoardVideo: vi.fn((_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ videoName: `board-${fileName}` })
+ ),
}));
vi.mock('./api', () => api);
@@ -112,16 +123,19 @@ const capturedArchive = (): File => {
return new File([blob], fileName);
};
+/** The server answers with the board it claimed, or with the one it created for a boardless create. */
const acceptCreate = (): void => {
- api.createProject.mockImplementation((request: { name: string; project_id?: string }) =>
- Promise.resolve({
- created_at: '2026-06-10 10:00:00.000',
- data: {},
- name: request.name,
- project_id: request.project_id ?? '',
- revision: 1,
- updated_at: '2026-06-10 10:00:00.000',
- })
+ api.createProject.mockImplementation(
+ (request: { board_id?: string; data?: Record<string, unknown>; name: string; project_id?: string }) =>
+ Promise.resolve({
+ board_id: request.board_id ?? 'server-created-board',
+ created_at: '2026-06-10 10:00:00.000',
+ data: request.data ?? {},
+ name: request.name,
+ project_id: request.project_id ?? '',
+ revision: 1,
+ updated_at: '2026-06-10 10:00:00.000',
+ })
);
};
@@ -144,8 +158,19 @@ beforeEach(async () => {
transport.uploadArchiveVideo.mockImplementation((_bytes: Uint8Array, fileName: string) =>
Promise.resolve({ videoName: `server-${fileName}` })
);
+ transport.uploadBoardImage.mockImplementation((_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ height: 1, imageName: `board-${fileName}`, width: 1 })
+ );
+ transport.uploadBoardVideo.mockImplementation((_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ videoName: `board-${fileName}` })
+ );
+ transport.starImages.mockImplementation((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] }));
+ transport.starVideos.mockImplementation((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] }));
+ transport.createStagingBoard.mockImplementation(() => Promise.resolve('staging-board'));
+ transport.deleteStagingBoard.mockImplementation(() => Promise.resolve());
transport.deleteArchiveImages.mockImplementation(() => Promise.resolve());
transport.deleteArchiveVideos.mockImplementation(() => Promise.resolve());
+ api.getProjectBoardSnapshot.mockImplementation(() => Promise.resolve({ items: [] }));
api.getClientStateValue.mockImplementation(() => Promise.resolve(null));
projectFile = await import('./projectFile');
@@ -283,6 +308,217 @@ describe('what a transfer reports', () => {
});
});
+/**
+ * The v3 half: an archive carries the project's board, and importing it gives that board's media
+ * new identities on a staging board the create then claims. Nothing here may reuse a name the
+ * destination already holds — `board_images` keys on the image name, so a reused name would move a
+ * stranger's picture onto this project's board instead of copying it.
+ */
+describe('importing a project board', () => {
+ const boardProject = () => {
+ const project = createDraftProject([]);
+
+ return {
+ ...project,
+ canvas: {
+ ...project.canvas,
+ document: { ...project.canvas.document, layers: [rasterImageLayer('l1', 'shared.png')] },
+ },
+ name: 'Board project',
+ };
+ };
+
+ const boardSnapshot = (): { items: ProjectBoardItemDTO[] } => ({
+ items: [
+ { category: 'general', kind: 'image', name: 'shared.png', starred: true },
+ { category: 'user', kind: 'image', name: 'unreferenced.png', starred: false },
+ { category: 'general', kind: 'video', name: 'clip.mp4', starred: false },
+ ],
+ });
+
+ const exportedBoardArchive = async (): Promise<File> => {
+ api.getProjectBoardSnapshot.mockResolvedValue(boardSnapshot());
+ await projectFile.exportOpenProject(boardProject());
+
+ return capturedArchive();
+ };
+
+ const uploadedBoardNames = () => transport.uploadBoardImage.mock.calls.map(([, fileName]) => fileName);
+
+ it('stages the board, restores its media under fresh names, and claims it on create', async () => {
+ acceptCreate();
+
+ const archive = await exportedBoardArchive();
+ const outcome = await projectFile.importProjectFile(archive);
+
+ expect(transport.createStagingBoard).toHaveBeenCalledWith('Board project', expect.anything());
+ expect(uploadedBoardNames().sort()).toEqual(['shared.png', 'unreferenced.png']);
+ expect(transport.uploadBoardImage).toHaveBeenCalledWith(expect.anything(), 'unreferenced.png', {
+ boardId: 'staging-board',
+ category: 'user',
+ contentType: 'image/png',
+ signal: expect.anything(),
+ });
+ expect(transport.uploadBoardVideo).toHaveBeenCalledWith(expect.anything(), 'clip.mp4', expect.anything());
+ expect(api.createProject.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-board' });
+ expect(outcome.boardItemIssues).toEqual([]);
+ expect(outcome.documentReferenceIssues).toEqual([]);
+ });
+
+ it('stars only the descriptors that were starred', async () => {
+ acceptCreate();
+ await projectFile.importProjectFile(await exportedBoardArchive());
+
+ expect(transport.starImages).toHaveBeenCalledWith(['board-shared.png'], expect.anything());
+ expect(transport.starVideos).toHaveBeenCalledWith([], expect.anything());
+ });
+
+ it('rewrites the document onto the copy rather than the archived name', async () => {
+ acceptCreate();
+ await projectFile.importProjectFile(await exportedBoardArchive());
+
+ const { data } = api.createProject.mock.calls[0]![0] as {
+ data: { canvas: { document: { layers: Array<{ source: { image: { imageName: string } } }> } } };
+ };
+
+ expect(data.canvas.document.layers[0]?.source.image.imageName).toBe('board-shared.png');
+ });
+
+ /** The dedup that document references get is deliberately not applied to board membership. */
+ it('copies board media even when this server already has that name', async () => {
+ acceptCreate();
+ transport.findExistingImageNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));
+
+ await projectFile.importProjectFile(await exportedBoardArchive());
+
+ expect(uploadedBoardNames().sort()).toEqual(['shared.png', 'unreferenced.png']);
+ });
+
+ /**
+ * The failure that must never bind to a stranger: on this server `shared.png` is taken, by the
+ * project this archive came from.
+ */
+ it('forces an overlapping reference dangling when its board upload fails', async () => {
+ acceptCreate();
+ // The destination has an image called `shared.png` — it is the source project's own. Falling
+ // back to that name would open the copy pointing at somebody else's picture.
+ transport.findExistingImageNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));
+ transport.uploadBoardImage.mockImplementation((_bytes: Uint8Array, fileName: string) =>
+ fileName === 'shared.png'
+ ? Promise.reject(new Error('rejected'))
+ : Promise.resolve({ height: 1, imageName: `board-${fileName}`, width: 1 })
+ );
+
+ const outcome = await projectFile.importProjectFile(await exportedBoardArchive());
+ const { data } = api.createProject.mock.calls[0]![0] as {
+ data: { canvas: { document: { layers: Array<{ source: { image: { imageName: string } } }> } } };
+ };
+ const restoredName = data.canvas.document.layers[0]!.source.image.imageName;
+
+ expect(restoredName).not.toBe('shared.png');
+ expect(restoredName).toContain('-missing-image-');
+ expect(outcome.boardItemIssues).toEqual([{ kind: 'image', name: 'shared.png', reason: 'upload-failed' }]);
+ expect(outcome.documentReferenceIssues).toEqual([{ kind: 'image', name: 'shared.png', reason: 'upload-failed' }]);
+ });
+
+ it('points the imported document at the board the server says it claimed', async () => {
+ acceptCreate();
+
+ const { record } = await projectFile.importProjectFile(await exportedBoardArchive());
+ const values = Object.values(record.data.widgetInstances as Record<string, { state?: { values?: unknown } }>)
+ .map((instance) => instance.state?.values as { projectBoardId?: string; selectedBoardId?: string } | undefined)
+ .filter((instanceValues) => instanceValues?.projectBoardId !== undefined);
+
+ expect(values.length).toBeGreaterThan(0);
+ expect(values[0]).toMatchObject({ projectBoardId: 'staging-board', selectedBoardId: 'staging-board' });
+ });
+
+ it('creates no staging board for an archive whose board was empty', async () => {
+ acceptCreate();
+ await projectFile.exportOpenProject(boardProject());
+ await projectFile.importProjectFile(capturedArchive());
+
+ expect(transport.createStagingBoard).not.toHaveBeenCalled();
+ expect(api.createProject.mock.calls[0]![0]).not.toHaveProperty('board_id');
+ });
+
+ it('creates no staging board for a document that will not rehydrate', async () => {
+ const { textEntry, writeArchive } = await import('./invk/archive');
+ const blob = await writeArchive(
+ new Map([
+ [
+ 'manifest.json',
+ textEntry(
+ JSON.stringify({
+ appVersion: '7.0',
+ contents: 'workbench-project',
+ createdAt: '',
+ name: 'No layout',
+ version: 3,
+ })
+ ),
+ ],
+ ['board.json', textEntry(JSON.stringify({ items: [], version: 1 }))],
+ ['project.json', textEntry(JSON.stringify({ name: 'No layout' }))],
+ ])
+ );
+
+ await expect(projectFile.importProjectFile(new File([blob], 'broken.invk'))).rejects.toMatchObject({
+ reason: 'damaged',
+ });
+ expect(transport.createStagingBoard).not.toHaveBeenCalled();
+ });
+
+ 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');
+
+ account.accountLifecycle.activate('board-rollback-user');
+
+ const archive = await exportedBoardArchive();
+
+ api.createProject.mockRejectedValue(primaryFailure);
+ api.getProject.mockRejectedValueOnce(new ApiError('not found', 404));
+
+ await expect(projectFile.importProjectFile(archive)).rejects.toBe(primaryFailure);
+
+ expect(transport.deleteArchiveImages).toHaveBeenCalledWith(
+ ['board-shared.png', 'board-unreferenced.png'],
+ expect.anything()
+ );
+ expect(transport.deleteArchiveVideos).toHaveBeenCalledWith(['board-clip.mp4'], expect.anything());
+ expect(transport.deleteStagingBoard).toHaveBeenCalledWith('staging-board', expect.anything());
+ account.accountLifecycle.invalidate();
+ });
+
+ it('leaves the staging board alone when a rejected create may already have claimed it', async () => {
+ const account = await import('@platform/state/accountLifecycle');
+ const primaryFailure = new Error('connection ended after create');
+
+ account.accountLifecycle.activate('board-ambiguous-user');
+
+ 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',
+ });
+
+ await expect(projectFile.importProjectFile(archive)).rejects.toBe(primaryFailure);
+
+ expect(transport.deleteStagingBoard).not.toHaveBeenCalled();
+ expect(transport.deleteArchiveImages).not.toHaveBeenCalled();
+ account.accountLifecycle.invalidate();
+ });
+});
+
describe('importProjectFile', () => {
it('round-trips an exported project under a fresh id', async () => {
const project = { ...createDraftProject([]), name: 'Exported project' };
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 9be01dbf77..1782e56555 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -236,10 +236,24 @@ export const exportOpenProject = async (
};
/**
- * Import an `.invk` as a new server project: restore its images, rewrite every
- * reference the server renamed, then create the project. Throws
- * {@link InvkFormatError} so callers can translate the reason rather than
- * surface an internal message.
+ * Import an `.invk` as a new server project: restore its media, rewrite every
+ * reference the server renamed, then create the project — claiming the board its
+ * media was staged on, in the same request. Throws {@link InvkFormatError} so
+ * callers can translate the reason rather than surface an internal message.
+ *
+ * ### Creating the project is the commit point
+ *
+ * Everything before it is either free to abandon or cleaned up: the document is
+ * canonicalized before a board exists, the board is created before any media is
+ * uploaded, and the create either claims that board with its contents or leaves
+ * nothing a person can see. The alternative — create the project, upload, then
+ * update it with the remapped names — makes the *update* the commit point, and a
+ * failure there leaves a real project full of references to media that never
+ * arrived.
+ *
+ * A v2 archive and a legacy JSON document have no board to stage, so they create
+ * no staging board and the server gives the new project an empty one, exactly as
+ * it does for a project made from scratch.
*/
export const importProjectFile = async (
file: File,
@@ -270,34 +284,63 @@ export const importProjectFile = async (
throw new InvkFormatError('damaged', 'The project document will not rehydrate.');
}
- const { serializeProjectDocument } = await import('./projectDocument');
+ const { applyAuthoritativeProjectBoard, serializeProjectDocument } = await import('./projectDocument');
const canonicalDocument = serializeProjectDocument(project);
- const restored =
- source.format === 'invk'
+ const archive = source.format === 'invk' ? source.contents : null;
+ // Loaded only for an archive: a legacy JSON document restores nothing, so it has nothing to undo.
+ const restoreMedia = archive === null ? null : await import('./invk/restoreProjectMedia');
+
+ assertAccountScopeCurrent(owner);
+
+ // Only an archive that actually carries board media needs somewhere to put it. An empty board is
+ // the server's to create, and staging one would be an unclaimed board to leak for no gain.
+ const stagingBoardId =
+ archive?.boardSnapshot && archive.boardSnapshot.items.length > 0
? await (async () => {
- const { restoreArchiveAssets } = await import('./invk/importProject');
-
- return restoreArchiveAssets(
- { ...source.contents, projectDocument: canonicalDocument },
- {
- signal: owner.signal,
- ...(options.onProgress === undefined
- ? {}
- : {
- onProgress: ({ completed, total }) =>
- options.onProgress?.({ completed, phase: 'restoring', total }),
- }),
- }
- );
+ const { createStagingBoard } = await import('./invk/assetTransport');
+
+ return createStagingBoard(name, owner.signal);
})()
: null;
+ const ledger = restoreMedia?.createRestoredMediaLedger(stagingBoardId) ?? null;
let didCreateProject = false;
try {
assertAccountScopeCurrent(owner);
+ const restored =
+ archive === null || ledger === null
+ ? null
+ : await (async () => {
+ const { restoreArchiveMedia } = await import('./invk/importProject');
+
+ return restoreArchiveMedia(
+ archive,
+ { boardId: stagingBoardId, ledger, projectDocument: canonicalDocument, projectId: id },
+ {
+ signal: owner.signal,
+ ...(options.onProgress === undefined
+ ? {}
+ : {
+ onProgress: ({ completed, total }) =>
+ options.onProgress?.({ completed, phase: 'restoring', total }),
+ }),
+ }
+ );
+ })();
+
+ assertAccountScopeCurrent(owner);
+
const document = restored === null ? canonicalDocument : remapAssetRefs(canonicalDocument, restored.mappings);
- const record = await apiCreateProject({ data: document, name, project_id: id }, owner.signal);
+ const record = await apiCreateProject(
+ {
+ data: document,
+ name,
+ project_id: id,
+ ...(stagingBoardId === null ? {} : { board_id: stagingBoardId }),
+ },
+ owner.signal
+ );
didCreateProject = true;
assertAccountScopeCurrent(owner);
@@ -308,23 +351,26 @@ export const importProjectFile = async (
}
return {
- // Board membership does not travel in a v2 archive, so nothing can be lost from it here.
- boardItemIssues: [],
+ boardItemIssues: restored?.boardItemIssues ?? [],
documentReferenceIssues: restored?.documentReferenceIssues ?? [],
- record,
+ // The board the server says it claimed, not the one we asked it to: a project meeting its
+ // owner for the first time is also pointed at its board, which is what `selectBoard` means.
+ record: {
+ ...record,
+ data: applyAuthoritativeProjectBoard(record.data, record.board_id, { selectBoard: true }),
+ },
};
} catch (error) {
const canRollback =
!didCreateProject &&
- restored !== null &&
+ ledger !== null &&
+ restoreMedia !== null &&
isAccountScopeCurrent(owner) &&
(await isProjectConfirmedAbsent(id, owner));
if (canRollback) {
try {
- const { rollbackArchiveAssets } = await import('./invk/importProject');
-
- await rollbackArchiveAssets(restored.uploadedAssets, { signal: owner.signal });
+ await restoreMedia.rollbackRestoredMedia(ledger, { signal: owner.signal });
} catch {
// Cleanup is best-effort. The create/scope failure is the actionable
// result and must never be replaced by a failed delete request.