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): export complete project boards as .invk v3

joshistoast84c439576265
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 9e09d14cc3..8925702818 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -420,8 +420,10 @@
"bundlingProgress": "Bundling {{completed}} of {{total}} assets…",
"damaged": "This project file is damaged and cannot be opened.",
"legacyCanvasProject": "This is a canvas project from an earlier version of Invoke, which cannot be opened here.",
- "missingAssets_one": "1 asset could not be included.",
- "missingAssets_other": "{{count}} assets could not be included.",
+ "missingBoardItems_one": "1 board item could not be included.",
+ "missingBoardItems_other": "{{count}} board items could not be included.",
+ "missingReferences_one": "1 project reference could not be included.",
+ "missingReferences_other": "{{count}} project references could not be included.",
"notAProject": "This file is not an Invoke project.",
"packing": "Packing the archive…",
"restoringProgress": "Restoring {{completed}} of {{total}} assets…",
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts
new file mode 100644
index 0000000000..c7789711ab
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildInvkBoardSnapshot, parseInvkBoardSnapshot } from './board';
+import { InvkFormatError } from './format';
+
+/**
+ * `board.json` is the only part of an archive that tells the reader what the project *had*, as
+ * opposed to what it draws with. A reader that half-trusted it would restore the wrong thing
+ * quietly, so everything here is a structural refusal rather than a warning.
+ */
+
+const item = (overrides: Partial<Parameters<typeof buildInvkBoardSnapshot>[0][number]> = {}) => ({
+ category: 'general' as const,
+ kind: 'image' as const,
+ name: 'a.png',
+ starred: false,
+ ...overrides,
+});
+
+const expectRefusal = (data: unknown): void => {
+ try {
+ parseInvkBoardSnapshot(data);
+ expect.unreachable('parseInvkBoardSnapshot should have thrown');
+ } catch (error) {
+ expect(error).toBeInstanceOf(InvkFormatError);
+ expect((error as InvkFormatError).reason).toBe('damaged');
+ }
+};
+
+describe('parseInvkBoardSnapshot', () => {
+ it('accepts every visible category of both kinds', () => {
+ const items = [
+ item({ category: 'general' }),
+ item({ category: 'control', name: 'b.png' }),
+ item({ category: 'mask', name: 'c.png' }),
+ item({ category: 'user', name: 'd.png' }),
+ item({ kind: 'video', name: 'e.mp4' }),
+ ];
+
+ expect(parseInvkBoardSnapshot({ items, version: 1 }).items).toHaveLength(5);
+ });
+
+ it('canonicalizes order so exports of the same board compare equal', () => {
+ const shuffled = [item({ kind: 'video', name: 'z.mp4' }), item({ name: 'b.png' }), item({ name: 'a.png' })];
+
+ expect(parseInvkBoardSnapshot({ items: shuffled, version: 1 }).items.map((entry) => entry.name)).toEqual([
+ 'a.png',
+ 'b.png',
+ 'z.mp4',
+ ]);
+ });
+
+ it('treats an image and a video of the same name as different items', () => {
+ const items = [item({ name: 'twin' }), item({ kind: 'video', name: 'twin' })];
+
+ expect(parseInvkBoardSnapshot({ items, version: 1 }).items).toHaveLength(2);
+ });
+
+ it('accepts an empty board', () => {
+ expect(parseInvkBoardSnapshot({ items: [], version: 1 })).toEqual({ items: [], version: 1 });
+ });
+
+ it('refuses a duplicate descriptor', () => {
+ expectRefusal({ items: [item(), item()], version: 1 });
+ });
+
+ /** A name with a separator would either escape `images/` or fail to round-trip through the ZIP. */
+ it.each(['dir/a.png', 'dir\\a.png', '..', '.', '', 'a\0b.png'])('refuses the unsafe name %o', (name) => {
+ expectRefusal({ items: [item({ name })], version: 1 });
+ });
+
+ it('refuses a category the gallery does not show', () => {
+ // `other` is the canvas's private category — it is never board membership.
+ expectRefusal({ items: [item({ category: 'other' as never })], version: 1 });
+ });
+
+ it('refuses an unknown kind, a wrong version, and an unknown key', () => {
+ expectRefusal({ items: [item({ kind: 'audio' as never })], version: 1 });
+ expectRefusal({ items: [], version: 2 });
+ expectRefusal({ extra: true, items: [], version: 1 });
+ });
+
+ it('refuses a descriptor missing its starred flag', () => {
+ expectRefusal({ items: [{ category: 'general', kind: 'image', name: 'a.png' }], version: 1 });
+ });
+});
+
+describe('buildInvkBoardSnapshot', () => {
+ it('sorts and stamps the file version, without touching the input', () => {
+ const items = [item({ name: 'b.png' }), item({ name: 'a.png' })];
+ const snapshot = buildInvkBoardSnapshot(items);
+
+ expect(snapshot).toEqual({
+ items: [item({ name: 'a.png' }), item({ name: 'b.png' })],
+ version: 1,
+ });
+ expect(items[0]!.name).toBe('b.png');
+ });
+
+ it('round-trips through the parser', () => {
+ const snapshot = buildInvkBoardSnapshot([item({ kind: 'video', name: 'v.mp4', starred: true }), item()]);
+
+ expect(parseInvkBoardSnapshot(JSON.parse(JSON.stringify(snapshot)))).toEqual(snapshot);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts
new file mode 100644
index 0000000000..574e4d1a36
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts
@@ -0,0 +1,111 @@
+import { z } from 'zod';
+
+import { INVK_MAX_ENTRIES } from './archive';
+import { InvkFormatError } from './format';
+
+/**
+ * `board.json`: what was on the project's board when the archive was written.
+ *
+ * A project document names only the media it draws with. Everything else the project produced —
+ * results generated but never placed on canvas, uploads kept for later — is board membership and
+ * appears nowhere in the document, so a reader cannot infer it. This entry states it, and is the
+ * difference between an `.invk` carrying a project's canvas and carrying its workspace.
+ *
+ * ```json
+ * { "version": 1, "items": [{ "category": "general", "kind": "image", "name": "…", "starred": false }] }
+ * ```
+ *
+ * The version here is the *file's*, not the API's. The board snapshot endpoint returns the same
+ * items but carries no version of its own, deliberately: an archive format that moved whenever the
+ * wire format did would be pinned to it forever, and vice versa.
+ *
+ * Validation is strict and structural. A duplicate `(kind, name)` or a name that is not a plain
+ * basename is not a warning to be reported alongside the import — it means the file is malformed,
+ * and a malformed archive must be refused before anything is uploaded. Import cannot sensibly
+ * "partially trust" an enumeration: a name containing a path separator is either an attempt to
+ * write outside the archive's namespace or a bug, and neither is something to restore.
+ */
+
+export type InvkMediaKind = 'image' | 'video';
+export type InvkMediaCategory = 'general' | 'control' | 'mask' | 'user';
+
+export interface InvkBoardItem {
+ category: InvkMediaCategory;
+ kind: InvkMediaKind;
+ name: string;
+ starred: boolean;
+}
+
+export interface InvkBoardSnapshot {
+ version: 1;
+ items: InvkBoardItem[];
+}
+
+/**
+ * A media name must be exactly what the server would name a file: no separators, no traversal, no
+ * NUL. The archive stores these under `images/` and `videos/`, so anything else would either
+ * escape that prefix or fail to round-trip through the ZIP.
+ */
+const zMediaName = z
+ .string()
+ .min(1)
+ .refine((name) => !name.includes('/') && !name.includes('\\') && !name.includes('\0'), {
+ message: 'must be a basename',
+ })
+ .refine((name) => name !== '.' && name !== '..', { message: 'must name a file' });
+
+const zBoardItem = z.object({
+ category: z.enum(['general', 'control', 'mask', 'user']),
+ kind: z.enum(['image', 'video']),
+ name: zMediaName,
+ starred: z.boolean(),
+});
+
+const zBoardSnapshot = z
+ .object({
+ // Bounded by the same ceiling as archive entries: every item is at most one entry, so a list
+ // that could not be packed cannot be honest either.
+ items: z.array(zBoardItem).max(INVK_MAX_ENTRIES),
+ version: z.literal(1),
+ })
+ // Unknown keys are refused rather than ignored: this file is small, entirely generated, and a
+ // reader silently dropping a field a later version added would restore the wrong thing quietly.
+ .strict();
+
+/** Sort by kind then name. Images and videos are separate namespaces, so one name can be both. */
+const compareItems = (left: InvkBoardItem, right: InvkBoardItem): number =>
+ left.kind.localeCompare(right.kind) || left.name.localeCompare(right.name);
+
+/**
+ * Parse and canonicalize `board.json`.
+ *
+ * Input order is free — the server's ordering is its own business — but the result is sorted, so
+ * every consumer sees one order and tests can compare whole structures.
+ */
+export const parseInvkBoardSnapshot = (data: unknown): InvkBoardSnapshot => {
+ const parsed = zBoardSnapshot.safeParse(data);
+
+ if (!parsed.success) {
+ throw new InvkFormatError('damaged', `Invalid ${'board.json'}: ${parsed.error.issues[0]?.message ?? 'malformed'}`);
+ }
+
+ const seen = new Set<string>();
+
+ for (const item of parsed.data.items) {
+ const key = `${item.kind}:${item.name}`;
+
+ if (seen.has(key)) {
+ throw new InvkFormatError('damaged', `Duplicate board entry ${key}`);
+ }
+
+ seen.add(key);
+ }
+
+ return { items: [...parsed.data.items].sort(compareItems), version: 1 };
+};
+
+/** Build the entry from a server snapshot. Sorting here is what makes exports byte-comparable. */
+export const buildInvkBoardSnapshot = (items: readonly InvkBoardItem[]): InvkBoardSnapshot => ({
+ items: [...items].sort(compareItems),
+ version: 1,
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts
index 77c14e6295..007b639b42 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts
@@ -31,14 +31,18 @@ const projectDocument = (): Record<string, unknown> => ({
const planInput = {
appVersion: '7.0',
+ boardItems: [],
createdAt: '2026-08-04T00:00:00.000Z',
name: 'My project',
projectDocument: projectDocument(),
};
+/** The names a plan will fetch, in the union's stable order. */
+const plannedNames = (plan: ReturnType<typeof planInvkExport>): string[] => plan.transferItems.map((item) => item.name);
+
describe('planInvkExport', () => {
it('bundles the live document and nothing from history', () => {
- expect(planInvkExport(planInput).imageNames).toEqual(['live-a.png', 'live-b.png']);
+ expect(plannedNames(planInvkExport(planInput))).toEqual(['live-a.png', 'live-b.png']);
});
it('names the file from the project and records the source project id', () => {
@@ -78,14 +82,14 @@ describe('planInvkExport', () => {
expect(plan.documentJson).not.toContain('selected.png');
expect(plan.documentJson).not.toContain('compare.png');
- expect(plan.imageNames).toEqual(['live-a.png', 'live-b.png']);
+ expect(plannedNames(plan)).toEqual(['live-a.png', 'live-b.png']);
});
it('omits the source project id when the document has none', () => {
const plan = planInvkExport({ ...planInput, projectDocument: { canvas: {}, layout: {}, name: 'x' } });
expect(plan.manifestInput.sourceProjectId).toBeUndefined();
- expect(plan.imageNames).toEqual([]);
+ expect(plannedNames(plan)).toEqual([]);
});
});
@@ -105,7 +109,12 @@ describe('executeInvkExport', () => {
Promise.resolve({ bytes: new Uint8Array([1, 2, 3]), contentType: 'image/webp;charset=binary' }),
});
- expect(result).toEqual({ bundledImageCount: 2, bundledVideoCount: 0, missingAssetNames: [] });
+ expect(result).toEqual({
+ boardItemIssues: [],
+ bundledImageCount: 2,
+ bundledVideoCount: 0,
+ documentReferenceIssues: [],
+ });
expect(download).toHaveBeenCalledTimes(1);
const [blob, fileName] = download.mock.calls[0]! as [Blob, string];
@@ -115,6 +124,7 @@ describe('executeInvkExport', () => {
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
expect([...entries.keys()].sort()).toEqual([
+ 'board.json',
'cover.webp',
'images/live-a.png',
'images/live-b.png',
@@ -126,7 +136,7 @@ describe('executeInvkExport', () => {
cover: 'cover.webp',
name: 'My project',
sourceProjectId: 'project-1',
- version: 2,
+ version: 3,
});
expect(JSON.parse(readEntryText(entries.get(INVK_DOCUMENT_ENTRY)!))).toEqual(projectDocument());
});
@@ -139,7 +149,12 @@ describe('executeInvkExport', () => {
fetchImageThumbnail: () => Promise.resolve(null),
});
- expect(result).toEqual({ bundledImageCount: 1, bundledVideoCount: 0, missingAssetNames: ['live-b.png'] });
+ expect(result).toEqual({
+ boardItemIssues: [],
+ bundledImageCount: 1,
+ bundledVideoCount: 0,
+ documentReferenceIssues: [{ kind: 'image', name: 'live-b.png', reason: 'fetch-failed' }],
+ });
expect(download).toHaveBeenCalledTimes(1);
});
@@ -150,7 +165,12 @@ describe('executeInvkExport', () => {
fetchImageThumbnail: () => Promise.reject(new Error('network')),
});
- expect(result.missingAssetNames).toEqual(['live-a.png', 'live-b.png']);
+ // Every one of these is a document reference, so the loss is a hole in the canvas.
+ expect(result.documentReferenceIssues).toEqual([
+ { kind: 'image', name: 'live-a.png', reason: 'fetch-failed' },
+ { kind: 'image', name: 'live-b.png', reason: 'fetch-failed' },
+ ]);
+ expect(result.boardItemIssues).toEqual([]);
});
it('omits the cover entry when there is no cover to fetch', async () => {
@@ -165,7 +185,9 @@ describe('executeInvkExport', () => {
const [blob] = download.mock.calls[0]! as [Blob];
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
- expect([...entries.keys()].sort()).toEqual(['manifest.json', 'project.json']);
+ // `board.json` is written even for a project with no board contents: its absence would be
+ // indistinguishable from a v2 archive that never knew about boards.
+ expect([...entries.keys()].sort()).toEqual(['board.json', 'manifest.json', 'project.json']);
expect(JSON.parse(readEntryText(entries.get(INVK_MANIFEST_ENTRY)!)).cover).toBeUndefined();
});
@@ -179,7 +201,7 @@ describe('executeInvkExport', () => {
},
});
- expect(plan.videoNames).toEqual(['clip.mp4']);
+ expect(plan.transferItems.filter((item) => item.kind === 'video').map((item) => item.name)).toEqual(['clip.mp4']);
const result = await executeInvkExport(plan, {
download,
@@ -188,12 +210,18 @@ describe('executeInvkExport', () => {
fetchVideoBytes: (videoName) => Promise.resolve(bytesFor(videoName)),
});
- expect(result).toEqual({ bundledImageCount: 2, bundledVideoCount: 1, missingAssetNames: [] });
+ expect(result).toEqual({
+ boardItemIssues: [],
+ bundledImageCount: 2,
+ bundledVideoCount: 1,
+ documentReferenceIssues: [],
+ });
const [blob] = download.mock.calls[0]! as [Blob];
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
expect([...entries.keys()].sort()).toEqual([
+ 'board.json',
'images/live-a.png',
'images/live-b.png',
'manifest.json',
@@ -218,7 +246,12 @@ describe('executeInvkExport', () => {
fetchVideoBytes: () => Promise.resolve(null),
});
- expect(result).toEqual({ bundledImageCount: 2, bundledVideoCount: 0, missingAssetNames: ['clip.mp4'] });
+ expect(result).toEqual({
+ boardItemIssues: [],
+ bundledImageCount: 2,
+ bundledVideoCount: 0,
+ documentReferenceIssues: [{ kind: 'video', name: 'clip.mp4', reason: 'fetch-failed' }],
+ });
});
/**
@@ -291,7 +324,7 @@ describe('executeInvkExport', () => {
fetchImageThumbnail: () => Promise.resolve(null),
});
- expect(result.missingAssetNames).toEqual(['live-a.png']);
+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'live-a.png', reason: 'fetch-failed' }]);
expect(download).toHaveBeenCalledTimes(1);
});
@@ -371,3 +404,114 @@ describe('executeInvkExport', () => {
]);
});
});
+
+/**
+ * Version 3's whole point: a project's board is part of the project. A result generated but never
+ * placed on canvas is named nowhere in the document, so without `board.json` it simply vanishes.
+ */
+describe('board membership', () => {
+ const bytesFor = (name: string) => new Uint8Array([...name].map((character) => character.codePointAt(0)!));
+ const boardItem = (name: string, overrides: Record<string, unknown> = {}) => ({
+ category: 'general' as const,
+ kind: 'image' as const,
+ name,
+ starred: false,
+ ...overrides,
+ });
+
+ const readBoard = async (blob: Blob) => {
+ const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
+
+ return JSON.parse(readEntryText(entries.get('board.json')!));
+ };
+
+ it('carries board media the document never references', async () => {
+ const download = vi.fn();
+ const plan = planInvkExport({
+ ...planInput,
+ boardItems: [boardItem('unreferenced.png', { category: 'user', starred: true })],
+ });
+
+ expect(plan.transferItems.map((item) => item.name)).toEqual(['live-a.png', 'live-b.png', 'unreferenced.png']);
+
+ const result = await executeInvkExport(plan, {
+ download,
+ fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
+ fetchImageThumbnail: () => Promise.resolve(null),
+ });
+
+ expect(result.bundledImageCount).toBe(3);
+
+ const [blob] = download.mock.calls[0]! as [Blob];
+ const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
+
+ expect(entries.has('images/unreferenced.png')).toBe(true);
+ // Category and starring travel: they are what the item was, not merely that it existed.
+ expect(await readBoard(blob)).toEqual({
+ items: [{ category: 'user', kind: 'image', name: 'unreferenced.png', starred: true }],
+ version: 1,
+ });
+ });
+
+ it('fetches an item that is both board media and a reference exactly once', async () => {
+ const fetchImageBytes = vi.fn((imageName: string) => Promise.resolve(bytesFor(imageName)));
+
+ await executeInvkExport(planInvkExport({ ...planInput, boardItems: [boardItem('live-a.png')] }), {
+ download: vi.fn(),
+ fetchImageBytes,
+ fetchImageThumbnail: () => Promise.resolve(null),
+ });
+
+ expect(fetchImageBytes.mock.calls.filter(([name]) => name === 'live-a.png')).toHaveLength(1);
+ });
+
+ it('reports an overlapping failure against both roles', async () => {
+ const result = await executeInvkExport(planInvkExport({ ...planInput, boardItems: [boardItem('live-a.png')] }), {
+ download: vi.fn(),
+ fetchImageBytes: (imageName) =>
+ imageName === 'live-a.png' ? Promise.resolve(null) : Promise.resolve(bytesFor(imageName)),
+ fetchImageThumbnail: () => Promise.resolve(null),
+ });
+
+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'live-a.png', reason: 'fetch-failed' }]);
+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'live-a.png', reason: 'fetch-failed' }]);
+ });
+
+ /** The descriptor stays so import can report the loss; dropping it would forget it silently. */
+ it('keeps the descriptor for an item whose bytes could not be fetched', async () => {
+ const download = vi.fn();
+
+ await executeInvkExport(planInvkExport({ ...planInput, boardItems: [boardItem('gone.png')] }), {
+ download,
+ fetchImageBytes: (imageName) =>
+ imageName === 'gone.png' ? Promise.resolve(null) : Promise.resolve(bytesFor(imageName)),
+ fetchImageThumbnail: () => Promise.resolve(null),
+ });
+
+ const [blob] = download.mock.calls[0]! as [Blob];
+ const board = await readBoard(blob);
+
+ expect(board.items.map((item: { name: string }) => item.name)).toEqual(['gone.png']);
+ });
+
+ it('records an empty board rather than omitting the entry', async () => {
+ const download = vi.fn();
+
+ await executeInvkExport(planInvkExport(planInput), {
+ download,
+ fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
+ fetchImageThumbnail: () => Promise.resolve(null),
+ });
+
+ const [blob] = download.mock.calls[0]! as [Blob];
+
+ expect(await readBoard(blob)).toEqual({ items: [], version: 1 });
+ });
+
+ /** Refused before a single round trip: discovering it after hundreds would be the wrong order. */
+ it('refuses a project that could never be packed, before fetching anything', () => {
+ const boardItems = Array.from({ length: 20_001 }, (_unused, index) => boardItem(`image-${index}.png`));
+
+ expect(() => planInvkExport({ ...planInput, boardItems })).toThrowError(/archive entries/u);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
index 3303bbcf78..54a70b72d8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
@@ -3,10 +3,14 @@ import { collectLiveAssetRefs, selectCoverImageName, stripInstallationState } fr
import type { InvkArchiveEntry } from './archive';
import type { FetchedThumbnail } from './assetTransport';
+import type { InvkBoardItem, InvkBoardSnapshot } from './board';
+import type { InvkTransferItem, ProjectTransferIssues } from './transfer';
-import { binaryEntry, textEntry, writeArchive } from './archive';
+import { binaryEntry, INVK_MAX_ENTRIES, textEntry, writeArchive } from './archive';
import { coverExtensionForMime, createAssetExportTransport, isRequestCancellation } from './assetTransport';
+import { buildInvkBoardSnapshot } from './board';
import {
+ INVK_BOARD_ENTRY,
INVK_DOCUMENT_ENTRY,
INVK_IMAGES_PREFIX,
INVK_MANIFEST_ENTRY,
@@ -14,6 +18,7 @@ import {
InvkFormatError,
} from './format';
import { buildInvkManifest, toInvkFileName } from './manifest';
+import { createTransferIssueLog, planMediaTransfer, toMediaRefs } from './transfer';
/**
* Writing an `.invk`, split into a pure planner and an impure executor the same
@@ -43,48 +48,63 @@ import { buildInvkManifest, toInvkFileName } from './manifest';
const ASSET_FETCH_CONCURRENCY = 5;
export interface InvkExportPlan {
+ /** The board's contents exactly as they will be written to `board.json`. */
+ boardSnapshot: InvkBoardSnapshot;
/** Cover image name, or `null` for a project that has produced nothing. */
coverImageName: string | null;
/** The project document, already serialized. */
documentJson: string;
/** Download file name, including the extension. */
fileName: string;
- /** Image names to bundle, in a stable order. */
- imageNames: string[];
manifestInput: { appVersion: string; createdAt: string; name: string; sourceProjectId?: string };
- /** Video names to bundle, in a stable order. */
- videoNames: string[];
+ /** Board membership and document references merged, each item exactly once. */
+ transferItems: InvkTransferItem[];
}
+/**
+ * Fixed entries every archive carries: manifest, document, board. The cover is counted separately
+ * because it is optional.
+ */
+const FIXED_ENTRY_COUNT = 3;
+
export const planInvkExport = (input: {
appVersion: string;
+ boardItems: readonly InvkBoardItem[];
createdAt: string;
name: string;
projectDocument: Record<string, unknown>;
}): InvkExportPlan => {
const sourceProjectId = typeof input.projectDocument.id === 'string' ? input.projectDocument.id : undefined;
- // The selection is dropped here rather than left to the collector's skip
- // list: not bundling a reference does not stop it travelling, it only stops
- // it arriving with pixels. The planner is where "what belongs in a project
- // file" is decided, so it is where the answer is applied.
+ // Installation state is dropped here rather than left to the collector's skip list: not bundling
+ // a reference does not stop it travelling, it only stops it arriving with pixels. The planner is
+ // where "what belongs in a project file" is decided, so it is where the answer is applied.
const projectDocument = stripInstallationState(input.projectDocument);
- const refs = collectLiveAssetRefs(projectDocument);
+ const boardSnapshot = buildInvkBoardSnapshot(input.boardItems);
+ const transferItems = planMediaTransfer(boardSnapshot.items, toMediaRefs(collectLiveAssetRefs(projectDocument)));
+
+ // Refused before a single byte is fetched. An archive that cannot be packed is not worth the
+ // hundreds of round trips it would take to discover that at the end.
+ const worstCaseEntries = FIXED_ENTRY_COUNT + transferItems.length + 1;
+
+ if (worstCaseEntries > INVK_MAX_ENTRIES) {
+ throw new InvkFormatError('too-large', `Project needs ${worstCaseEntries} archive entries`);
+ }
return {
+ boardSnapshot,
coverImageName: selectCoverImageName(projectDocument),
// Compact rather than indented: the document is machine-read, and the two
// bytes per line would be the largest entry in the archive before deflate.
documentJson: JSON.stringify(projectDocument),
fileName: toInvkFileName(input.name),
- imageNames: [...refs.images].sort(),
manifestInput: {
appVersion: input.appVersion,
createdAt: input.createdAt,
name: input.name,
...(sourceProjectId === undefined ? {} : { sourceProjectId }),
},
- videoNames: [...refs.videos].sort(),
+ transferItems,
};
};
@@ -103,13 +123,11 @@ export interface InvkExportDeps {
signal?: AbortSignal;
}
-export interface InvkExportResult {
+export interface InvkExportResult extends ProjectTransferIssues {
/** Images successfully written into `images/`. */
bundledImageCount: number;
/** Videos successfully written into `videos/`. */
bundledVideoCount: number;
- /** Referenced assets the server would not serve. Their references still ship. */
- missingAssetNames: string[];
}
export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDeps): Promise<InvkExportResult> => {
@@ -118,7 +136,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
const readVideo = deps.fetchVideoBytes ?? transport.fetchVideoBytes;
const readThumbnail = deps.fetchImageThumbnail ?? transport.fetchImageThumbnail;
const entries = new Map<string, InvkArchiveEntry>();
- const missingAssetNames: string[] = [];
+ const issues = createTransferIssueLog();
let bundledImageCount = 0;
let bundledVideoCount = 0;
let completed = 0;
@@ -140,14 +158,13 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
plan.coverImageName === null ? null : await skipUnservable(() => readThumbnail(plan.coverImageName!, deps.signal));
const coverEntryName = cover === null ? undefined : `cover.${coverExtensionForMime(cover.contentType)}`;
- // One queue over both kinds: the concurrency limit is there to be kind to the
- // backend, and it would not be if images and videos each got their own.
- const assets = [
- ...plan.imageNames.map((name) => ({ kind: 'image' as const, name })),
- ...plan.videoNames.map((name) => ({ kind: 'video' as const, name })),
- ];
+ // One queue over both kinds and both roles: an item that is on the board *and* referenced by the
+ // document is one fetch, not two. The concurrency limit exists to be kind to the backend, and it
+ // would not be if images and videos each got their own.
+ const assets = plan.transferItems;
- await mapWithConcurrency(assets, ASSET_FETCH_CONCURRENCY, async ({ kind, name }) => {
+ await mapWithConcurrency(assets, ASSET_FETCH_CONCURRENCY, async (item) => {
+ const { kind, name } = item;
const bytes = await skipUnservable(() =>
kind === 'image' ? readImage(name, deps.signal) : readVideo(name, deps.signal)
);
@@ -156,7 +173,15 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
deps.onProgress?.({ completed, phase: 'bundling', total: assets.length });
if (bytes === null) {
- missingAssetNames.push(name);
+ // Reported against every role it filled: the same failure costs a board result and a canvas
+ // layer, and the person holding the file needs to know which.
+ if (item.isBoardItem) {
+ issues.addBoardItemIssue(item, 'fetch-failed');
+ }
+
+ if (item.isDocumentReference) {
+ issues.addDocumentReferenceIssue(item, 'fetch-failed');
+ }
return;
}
@@ -187,6 +212,11 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
// The manifest is the one entry a person may open by hand, so it is indented.
entries.set(INVK_MANIFEST_ENTRY, textEntry(JSON.stringify(manifest, null, 2)));
entries.set(INVK_DOCUMENT_ENTRY, textEntry(plan.documentJson));
+ // Written even when empty. "This project's board held nothing" is a fact the reader needs; its
+ // absence would be indistinguishable from a v2 archive that never knew about boards. The
+ // descriptor is kept for an item whose bytes could not be fetched, so the loss is reported on
+ // import rather than silently forgotten here.
+ entries.set(INVK_BOARD_ENTRY, textEntry(JSON.stringify(plan.boardSnapshot)));
if (cover !== null && coverEntryName !== undefined) {
entries.set(coverEntryName, binaryEntry(cover.bytes));
@@ -198,5 +228,5 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
deps.download(blob, plan.fileName);
- return { bundledImageCount, bundledVideoCount, missingAssetNames: missingAssetNames.sort() };
+ return { bundledImageCount, bundledVideoCount, ...issues.toIssues() };
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts
index e9c89ce284..0b8bc0af72 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts
@@ -12,12 +12,22 @@
export const INVK_EXTENSION = '.invk';
export const INVK_MIME_TYPE = 'application/zip';
-export const INVK_VERSION = 2;
+export const INVK_VERSION = 3;
/** Fixed entry paths. `cover` varies by image format and is named in the manifest. */
export const INVK_MANIFEST_ENTRY = 'manifest.json';
export const INVK_DOCUMENT_ENTRY = 'project.json';
+/**
+ * The project board's contents, as the exporting server enumerated them.
+ *
+ * A project document only references the media it draws with. Everything else the project produced
+ * — results generated but never placed on canvas — is on its board and named nowhere in the
+ * document, so a reader has no way to infer it. Version 3 states it, which is what makes an `.invk`
+ * the project's workspace rather than only its canvas.
+ */
+export const INVK_BOARD_ENTRY = 'board.json';
+
/**
* Bundled bytes are filed by kind, not pooled. Images and videos are separate
* backend namespaces with separate fetch and upload routes, so import has to
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 b5b31d9162..e90a8f81dd 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts
@@ -131,7 +131,7 @@ describe('restoreArchiveAssets', () => {
});
expect(upload).not.toHaveBeenCalled();
- expect(result).toMatchObject({ danglingAssetNames: [], uploadedCount: 0 });
+ expect(result).toMatchObject({ documentReferenceIssues: [], uploadedCount: 0 });
expect(result.mappings.images.size).toBe(0);
});
@@ -187,7 +187,7 @@ describe('restoreArchiveAssets', () => {
uploadArchiveImage: () => Promise.reject(new Error('should not be called')),
});
- expect(result.danglingAssetNames).toEqual(['a.png']);
+ expect(result.documentReferenceIssues.map((issue) => issue.name)).toEqual(['a.png']);
expect(result.uploadedCount).toBe(0);
});
@@ -197,7 +197,7 @@ describe('restoreArchiveAssets', () => {
uploadArchiveImage: () => Promise.reject(new Error('upload failed')),
});
- expect(result.danglingAssetNames).toEqual(['a.png']);
+ expect(result.documentReferenceIssues.map((issue) => issue.name)).toEqual(['a.png']);
expect(result.uploadedCount).toBe(0);
});
@@ -248,7 +248,7 @@ describe('restoreArchiveAssets', () => {
});
expect(result.coverImageName).toBe('server-cover.png');
- expect(result.danglingAssetNames).toEqual(['a.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',
@@ -316,7 +316,7 @@ describe('restoreArchiveAssets', () => {
});
expect(result.coverImageName).toBeNull();
- expect(result.danglingAssetNames).toEqual(['a.png']);
+ expect(result.documentReferenceIssues.map((issue) => issue.name)).toEqual(['a.png']);
});
it('announces a video entry as a video, whatever its extension', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
index 389bb8330d..ccc53e258c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
@@ -3,6 +3,7 @@ import { collectLiveAssetRefs, selectCoverImageName } from '@workbench/projects/
import type { UploadedImage, UploadedVideo } from './assetTransport';
import type { InvkManifest } from './manifest';
+import type { InvkMediaIssue } from './transfer';
import { INVK_MAX_ARCHIVE_BYTES, readArchive, readEntryText } from './archive';
import {
@@ -20,6 +21,7 @@ import {
InvkFormatError,
} from './format';
import { parseInvkManifest } from './manifest';
+import { createTransferIssueLog } from './transfer';
/**
* Reading an `.invk` back, in two steps a caller can put a decision between.
@@ -127,7 +129,8 @@ 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. */
- danglingAssetNames: string[];
+ /** 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. */
@@ -273,7 +276,7 @@ export const restoreArchiveAssets = async (
: checkExistingVideos(referencedVideos, deps.signal),
]);
- const danglingAssetNames: string[] = [];
+ const issues = createTransferIssueLog();
const pending: PendingUpload[] = [];
for (const [names, existing, store, kind] of [
@@ -288,7 +291,7 @@ export const restoreArchiveAssets = async (
const bytes = store.get(name);
if (bytes === undefined) {
- danglingAssetNames.push(name);
+ issues.addDocumentReferenceIssue({ kind, name }, 'missing-entry');
continue;
}
@@ -332,7 +335,7 @@ export const restoreArchiveAssets = async (
} 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.
- danglingAssetNames.push(name);
+ issues.addDocumentReferenceIssue({ kind, name }, 'upload-failed');
}
completed += 1;
@@ -355,7 +358,7 @@ export const restoreArchiveAssets = async (
return {
coverImageName,
- danglingAssetNames: danglingAssetNames.sort(),
+ documentReferenceIssues: issues.toIssues().documentReferenceIssues,
mappings,
uploadedAssets: {
imageNames: [...newlyUploadedImageNames].sort(),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts
index 6dff9c3ab8..4260debaf9 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts
@@ -42,7 +42,7 @@ describe('parseInvkManifest', () => {
});
it('reports an unknown numeric version as unsupported', () => {
- expectReason({ ...v2, version: 3 }, 'unsupported-version');
+ expectReason({ ...v2, version: 4 }, 'unsupported-version');
});
it('rejects a manifest missing the v2 discriminator', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts
index fa296992b7..b6cb04b032 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts
@@ -11,21 +11,28 @@ import { INVK_EXTENSION, INVK_VERSION, InvkFormatError } from './format';
* That container is kept verbatim. Version 2 changes only the payload: where a
* v1 archive carried four canvas-shaped state files, a v2 archive carries one
* `project.json` holding the whole workbench project document, plus an optional
- * cover.
+ * cover. Version 3 adds `board.json`, the project board's contents — the part of
+ * a project that the document does not reference and a reader cannot infer.
*
* ```
* <name>.invk
* ├── manifest.json this file's shape
- * ├── project.json the project document (v2 only)
+ * ├── project.json the project document (v2 and v3)
+ * ├── board.json the project board's visible contents (v3 only)
* ├── cover.<ext> optional preview; the entry name is recorded here
- * └── images/<image_name> referenced bytes, named exactly as the server names them
+ * ├── images/<image_name> bytes, named exactly as the server names them
+ * └── videos/<video_name> the same, for the other namespace
* ```
*
- * Parsing is a discriminated union rather than a strict `z.literal(2)` so that a
- * v1 archive can be recognized and refused *as what it is*. "This is a canvas
- * project from an earlier version" is a sentence someone can act on; a zod issue
- * list is not. The legacy reader is the mirror image — it pins `version: 1` and
- * will refuse a v2 archive, which is correct and needs no change there.
+ * Parsing is a discriminated union rather than a strict `z.literal(3)` so that
+ * every version this app has written can be named precisely when refused. "This
+ * is a canvas project from an earlier version" is a sentence someone can act on;
+ * a zod issue list is not. The legacy reader is the mirror image — it pins
+ * `version: 1` and will refuse the others, which is correct and needs no change.
+ *
+ * Version 2 is still read, and is deliberately not asked to carry board
+ * membership: an archive written before boards existed has no board to describe,
+ * and inventing one for it would claim knowledge the file does not contain.
*
* The names and the error class live in `./format`, which carries no zod, so
* that the file picker and the error toast do not drag the schema into the
@@ -52,12 +59,15 @@ const zManifestV2 = z.object({
version: z.literal(2),
});
-const zManifest = z.discriminatedUnion('version', [zManifestV1, zManifestV2]);
+const zManifestV3 = zManifestV2.extend({ version: z.literal(3) });
+
+const zManifest = z.discriminatedUnion('version', [zManifestV1, zManifestV2, zManifestV3]);
-export type InvkManifest = z.infer<typeof zManifestV2>;
+/** A manifest this app can read: v2 or v3, which differ only in what else the archive holds. */
+export type InvkManifest = z.infer<typeof zManifestV2> | z.infer<typeof zManifestV3>;
/**
- * Accepts a v2 manifest; throws {@link InvkFormatError} for anything else.
+ * Accepts a v2 or v3 manifest; throws {@link InvkFormatError} for anything else.
* Never returns a v1 manifest — recognizing v1 exists only to name the refusal.
*/
export const parseInvkManifest = (data: unknown): InvkManifest => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts
new file mode 100644
index 0000000000..2699c8bb53
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildMissingMediaName, createTransferIssueLog, planMediaTransfer, toMediaKey, toMediaRefs } from './transfer';
+
+const boardItem = (name: string, overrides: Record<string, unknown> = {}) =>
+ ({ category: 'general', kind: 'image', name, starred: false, ...overrides }) as Parameters<
+ typeof planMediaTransfer
+ >[0][number];
+
+describe('toMediaKey', () => {
+ /** Images and videos are separate backend namespaces; one name can legitimately be both. */
+ it('separates the two namespaces', () => {
+ expect(toMediaKey({ kind: 'image', name: 'twin' })).not.toBe(toMediaKey({ kind: 'video', name: 'twin' }));
+ });
+});
+
+describe('toMediaRefs', () => {
+ it('flattens the collector per-kind sets into one sorted list', () => {
+ expect(toMediaRefs({ images: new Set(['b.png', 'a.png']), videos: new Set(['c.mp4']) })).toEqual([
+ { kind: 'image', name: 'a.png' },
+ { kind: 'image', name: 'b.png' },
+ { kind: 'video', name: 'c.mp4' },
+ ]);
+ });
+});
+
+describe('planMediaTransfer', () => {
+ it('marks which side each item came from', () => {
+ const plan = planMediaTransfer(
+ [boardItem('board-only.png'), boardItem('both.png')],
+ [
+ { kind: 'image', name: 'both.png' },
+ { kind: 'image', name: 'document-only.png' },
+ ]
+ );
+
+ expect(
+ plan.map(({ isBoardItem, isDocumentReference, name }) => ({ isBoardItem, isDocumentReference, name }))
+ ).toEqual([
+ { isBoardItem: true, isDocumentReference: false, name: 'board-only.png' },
+ { isBoardItem: true, isDocumentReference: true, name: 'both.png' },
+ { isBoardItem: false, isDocumentReference: true, name: 'document-only.png' },
+ ]);
+ });
+
+ /** Fetching is the expensive half of an export; an overlap must not be paid for twice. */
+ it('yields an overlapping item exactly once', () => {
+ const plan = planMediaTransfer([boardItem('both.png')], [{ kind: 'image', name: 'both.png' }]);
+
+ expect(plan).toHaveLength(1);
+ });
+
+ it('keeps the board descriptor only for board items', () => {
+ const plan = planMediaTransfer([boardItem('a.png', { starred: true })], [{ kind: 'image', name: 'b.png' }]);
+
+ expect(plan[0]!.boardItem).toMatchObject({ starred: true });
+ expect(plan[1]!.boardItem).toBeNull();
+ });
+
+ it('does not merge an image and a video sharing a name', () => {
+ const plan = planMediaTransfer([boardItem('twin')], [{ kind: 'video', name: 'twin' }]);
+
+ expect(plan).toHaveLength(2);
+ expect(plan.map((item) => item.kind)).toEqual(['image', 'video']);
+ });
+
+ it('is stable regardless of input order', () => {
+ const refs = [
+ { kind: 'image' as const, name: 'b.png' },
+ { kind: 'image' as const, name: 'a.png' },
+ ];
+
+ expect(planMediaTransfer([boardItem('c.png')], refs).map((item) => item.name)).toEqual(['a.png', 'b.png', 'c.png']);
+ });
+});
+
+describe('createTransferIssueLog', () => {
+ /**
+ * The same failure can cost a board result and a canvas layer at once. Reporting it against both
+ * roles is not double-counting — it genuinely failed as both.
+ */
+ it('records an overlapping failure against both roles and sorts the result', () => {
+ const log = createTransferIssueLog();
+
+ log.addDocumentReferenceIssue({ kind: 'image', name: 'z.png' }, 'upload-failed');
+ log.addBoardItemIssue({ kind: 'image', name: 'z.png' }, 'upload-failed');
+ log.addBoardItemIssue({ kind: 'image', name: 'a.png' }, 'star-failed');
+
+ expect(log.toIssues()).toEqual({
+ boardItemIssues: [
+ { kind: 'image', name: 'a.png', reason: 'star-failed' },
+ { kind: 'image', name: 'z.png', reason: 'upload-failed' },
+ ],
+ documentReferenceIssues: [{ kind: 'image', name: 'z.png', reason: 'upload-failed' }],
+ });
+ });
+
+ it('reports nothing for a clean transfer', () => {
+ expect(createTransferIssueLog().toIssues()).toEqual({ boardItemIssues: [], documentReferenceIssues: [] });
+ });
+});
+
+describe('buildMissingMediaName', () => {
+ /**
+ * A failed board copy must not leave the document pointing at the old name: the destination may
+ * well have its own media under it — on the same server, during a duplication, it certainly does
+ * — and the project would open showing a stranger's picture with nothing to indicate it is wrong.
+ */
+ it('is stable within one project and distinct across projects, kinds and items', () => {
+ expect(buildMissingMediaName('p1', 'image', 0)).toBe(buildMissingMediaName('p1', 'image', 0));
+ expect(buildMissingMediaName('p1', 'image', 0)).not.toBe(buildMissingMediaName('p2', 'image', 0));
+ expect(buildMissingMediaName('p1', 'image', 0)).not.toBe(buildMissingMediaName('p1', 'video', 0));
+ expect(buildMissingMediaName('p1', 'image', 0)).not.toBe(buildMissingMediaName('p1', 'image', 1));
+ });
+
+ it('is shaped like an ordinary media name so a lookup fails cleanly', () => {
+ const name = buildMissingMediaName('project-abc', 'image', 3);
+
+ expect(name).not.toContain('/');
+ expect(name).not.toContain('\\');
+ expect(name.length).toBeGreaterThan(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts
new file mode 100644
index 0000000000..e5146eda5b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts
@@ -0,0 +1,166 @@
+import type { ProjectAssetRefs } from '@workbench/projects/projectAssets';
+
+import type { InvkBoardItem, InvkMediaKind } from './board';
+
+/**
+ * The vocabulary shared by everything that moves a project's media: export, import, and
+ * duplication.
+ *
+ * All three face the same problem. A project's media comes from two places that overlap — the
+ * board, which is membership, and the document, which is references — and an item can be in
+ * either, or both. What must happen to it differs by which:
+ *
+ * - **Board membership** must be *copied*. `board_images` keys on the image name, so one image sits
+ * on exactly one board; a restored project that reused an existing name would be sharing another
+ * project's media, and deleting either board would take it from both.
+ * - **Document references** may be *reused*. They are pointers, not membership, so an image the
+ * destination already has satisfies the reference without a second copy. This is the v2
+ * behaviour, and it is still right for media that lives outside the project's own board.
+ *
+ * The consequence is the rule this module exists to encode: an item that is *both* is restored as
+ * board media, and its document references are rewritten to the copy. And when that copy fails, the
+ * reference must not be left pointing at the old name — see {@link buildMissingMediaName}.
+ */
+
+/** One item, in whichever namespace it belongs to. */
+export interface InvkMediaRef {
+ kind: InvkMediaKind;
+ name: string;
+}
+
+/** Stable identity across both namespaces. An image and a video may share a name. */
+export const toMediaKey = ({ kind, name }: InvkMediaRef): string => `${kind}:${name}`;
+
+export const compareMediaRefs = (left: InvkMediaRef, right: InvkMediaRef): number =>
+ left.kind.localeCompare(right.kind) || left.name.localeCompare(right.name);
+
+/** Why an item did not make it. Each is reported, never thrown: a partial project beats none. */
+export type InvkMediaIssueReason =
+ /** The exporting server would not serve the bytes. */
+ | 'fetch-failed'
+ /** The archive named the item on its board but carried no bytes for it. */
+ | 'missing-entry'
+ /** The destination server rejected the upload or copy. */
+ | 'upload-failed'
+ /** The media arrived, but could not be re-starred. */
+ | 'star-failed';
+
+export interface InvkMediaIssue extends InvkMediaRef {
+ reason: InvkMediaIssueReason;
+}
+
+/**
+ * What a transfer could not carry, split by what it means to the person holding the file.
+ *
+ * A missing board item costs a result they can still see elsewhere. A missing document reference
+ * costs a layer in the canvas — the project opens with a hole in it. Reporting one number for both
+ * made "12 assets could not be included" mean anything from "nothing you will notice" to "the
+ * canvas is broken", so they are counted apart.
+ *
+ * An item that was both appears in both arrays. That is not double-counting: it genuinely failed
+ * in both roles.
+ */
+export interface ProjectTransferIssues {
+ boardItemIssues: InvkMediaIssue[];
+ documentReferenceIssues: InvkMediaIssue[];
+}
+
+const compareIssues = (left: InvkMediaIssue, right: InvkMediaIssue): number =>
+ compareMediaRefs(left, right) || left.reason.localeCompare(right.reason);
+
+/** Collects issues in whatever order they happen and hands them back in a stable one. */
+export const createTransferIssueLog = (): {
+ addBoardItemIssue: (ref: InvkMediaRef, reason: InvkMediaIssueReason) => void;
+ addDocumentReferenceIssue: (ref: InvkMediaRef, reason: InvkMediaIssueReason) => void;
+ toIssues: () => ProjectTransferIssues;
+} => {
+ const boardItemIssues: InvkMediaIssue[] = [];
+ const documentReferenceIssues: InvkMediaIssue[] = [];
+
+ return {
+ addBoardItemIssue: ({ kind, name }, reason) => boardItemIssues.push({ kind, name, reason }),
+ addDocumentReferenceIssue: ({ kind, name }, reason) => documentReferenceIssues.push({ kind, name, reason }),
+ toIssues: () => ({
+ boardItemIssues: [...boardItemIssues].sort(compareIssues),
+ documentReferenceIssues: [...documentReferenceIssues].sort(compareIssues),
+ }),
+ };
+};
+
+/** Turn the collector's per-kind sets into refs. */
+export const toMediaRefs = (refs: ProjectAssetRefs): InvkMediaRef[] =>
+ [
+ ...[...refs.images].map((name) => ({ kind: 'image' as const, name })),
+ ...[...refs.videos].map((name) => ({ kind: 'video' as const, name })),
+ ].sort(compareMediaRefs);
+
+/** One item of the union, and which side (or sides) it came from. */
+export interface InvkTransferItem extends InvkMediaRef {
+ /** On the project's board, so it must be copied rather than reused. */
+ isBoardItem: boolean;
+ /** Named by the document, so a failure leaves a hole in the canvas. */
+ isDocumentReference: boolean;
+ /** Present only for board items; the category and starring to restore. */
+ boardItem: InvkBoardItem | null;
+}
+
+/**
+ * Merge board membership and document references into one list, each item appearing once.
+ *
+ * Fetching is the expensive half of an export and uploading the expensive half of an import, so an
+ * item that is both must be handled once, not twice — and the union is also what lets a single
+ * failure be reported correctly against both roles.
+ */
+export const planMediaTransfer = (
+ boardItems: readonly InvkBoardItem[],
+ documentRefs: readonly InvkMediaRef[]
+): InvkTransferItem[] => {
+ const byKey = new Map<string, InvkTransferItem>();
+
+ for (const boardItem of boardItems) {
+ byKey.set(toMediaKey(boardItem), {
+ boardItem,
+ isBoardItem: true,
+ isDocumentReference: false,
+ kind: boardItem.kind,
+ name: boardItem.name,
+ });
+ }
+
+ for (const ref of documentRefs) {
+ const key = toMediaKey(ref);
+ const existing = byKey.get(key);
+
+ if (existing) {
+ existing.isDocumentReference = true;
+ continue;
+ }
+
+ byKey.set(key, {
+ boardItem: null,
+ isBoardItem: false,
+ isDocumentReference: true,
+ kind: ref.kind,
+ name: ref.name,
+ });
+ }
+
+ return [...byKey.values()].sort(compareMediaRefs);
+};
+
+/**
+ * A name guaranteed not to resolve, for a document reference whose board media could not be
+ * restored.
+ *
+ * Leaving the original name in place would be worse than a broken reference. Names are assigned by
+ * the exporting server, and the destination may well have its own image under that exact name —
+ * on the same server, during a duplication, it certainly does. The project would then open
+ * pointing at a stranger's picture, silently and plausibly, with nothing to indicate it is the
+ * wrong one. A reference that resolves to nothing is honest: it renders as a missing layer,
+ * exactly as a dangling v2 reference already does.
+ *
+ * Derived from the new project id, so it is stable within one import (every occurrence of the old
+ * name maps to the same placeholder) and unique across imports.
+ */
+export const buildMissingMediaName = (projectId: string, kind: InvkMediaKind, index: number): string =>
+ `${projectId}-missing-${kind}-${index}`;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 9523d428c3..503b2ec46f 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -17,6 +17,8 @@ const api = vi.hoisted(() => ({
deleteClientStateValue: vi.fn(() => Promise.resolve()),
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: [] })),
isProjectNotFoundError: (error: unknown) =>
typeof error === 'object' && error !== null && 'status' in error && error.status === 404,
setClientStateValue: vi.fn(() => Promise.resolve()),
@@ -242,7 +244,7 @@ describe('what a transfer reports', () => {
const outcome = await projectFile.exportLibraryProject('p1');
- expect(outcome.missingAssetNames).toEqual(['b.png']);
+ expect(outcome.documentReferenceIssues).toEqual([{ kind: 'image', name: 'b.png', reason: 'fetch-failed' }]);
expect(outcome.fileName).toBe('Two layers.invk');
});
@@ -253,7 +255,8 @@ describe('what a transfer reports', () => {
const outcome = await projectFile.exportLibraryProject('p1');
- expect(outcome.missingAssetNames).toEqual([]);
+ expect(outcome.documentReferenceIssues).toEqual([]);
+ expect(outcome.boardItemIssues).toEqual([]);
});
it('counts uploads on the way in, and names what stayed dangling', async () => {
@@ -275,7 +278,7 @@ describe('what a transfer reports', () => {
const outcome = await projectFile.importProjectFile(archive, { onProgress });
- expect(outcome.danglingAssetNames).toEqual(['b.png']);
+ expect(outcome.documentReferenceIssues).toEqual([{ kind: 'image', name: 'b.png', reason: 'upload-failed' }]);
expect(onProgress.mock.calls.map(([progress]) => progress.phase)).toContain('restoring');
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index c2cc8bc6ab..9be01dbf77 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -9,9 +9,12 @@ import {
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
+import type { ProjectTransferIssues } from './invk/transfer';
+
import {
createProject as apiCreateProject,
getProject as apiGetProject,
+ getProjectBoardSnapshot,
isProjectNotFoundError,
type ProjectRecordDTO,
} from './api';
@@ -121,16 +124,12 @@ export interface ProjectFileOptions {
owner?: AccountScope;
}
-export interface ProjectExportOutcome {
- /** Assets the server would not serve. Their references still ship. */
- missingAssetNames: string[];
+export interface ProjectExportOutcome extends ProjectTransferIssues {
/** The name the archive was downloaded under. */
fileName: string;
}
-export interface ProjectImportOutcome {
- /** Referenced assets neither the archive nor this server has. */
- danglingAssetNames: string[];
+export interface ProjectImportOutcome extends ProjectTransferIssues {
record: ProjectRecordDTO;
}
@@ -169,6 +168,7 @@ const isProjectConfirmedAbsent = async (projectId: string, owner: AccountScope):
const exportProjectDocument = async (
name: string,
+ projectId: string,
projectDocument: Record<string, unknown>,
options: Required<Pick<ProjectFileOptions, 'owner'>> & ProjectFileOptions
): Promise<ProjectExportOutcome> => {
@@ -177,8 +177,15 @@ const exportProjectDocument = async (
assertAccountScopeCurrent(owner);
+ // Enumerated before anything is planned, and fatal if it fails. An archive whose `board.json`
+ // silently said "empty" would be a lie the reader has no way to detect — worse than no archive.
+ const snapshot = await getProjectBoardSnapshot(projectId, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+
const plan = planInvkExport({
appVersion: APP_VERSION,
+ boardItems: snapshot.items,
createdAt: new Date().toISOString(),
name,
projectDocument,
@@ -192,7 +199,11 @@ const exportProjectDocument = async (
assertAccountScopeCurrent(owner);
- return { fileName: plan.fileName, missingAssetNames: result.missingAssetNames };
+ return {
+ boardItemIssues: result.boardItemIssues,
+ documentReferenceIssues: result.documentReferenceIssues,
+ fileName: plan.fileName,
+ };
};
/** Export a closed project straight from its server record. */
@@ -205,7 +216,7 @@ export const exportLibraryProject = async (
assertAccountScopeCurrent(owner);
- return exportProjectDocument(record.name, record.data, { ...options, owner });
+ return exportProjectDocument(record.name, record.project_id, record.data, { ...options, owner });
};
/** Export an open project from its live in-memory document. */
@@ -218,7 +229,10 @@ export const exportOpenProject = async (
assertAccountScopeCurrent(owner);
- return exportProjectDocument(project.name, serializeProjectDocument(project), { ...options, owner });
+ return exportProjectDocument(project.name, project.id, serializeProjectDocument(project), {
+ ...options,
+ owner,
+ });
};
/**
@@ -293,7 +307,12 @@ export const importProjectFile = async (
recordProjectCover(record.project_id, restored.coverImageName, owner);
}
- return { danglingAssetNames: restored?.danglingAssetNames ?? [], record };
+ return {
+ // Board membership does not travel in a v2 archive, so nothing can be lost from it here.
+ boardItemIssues: [],
+ documentReferenceIssues: restored?.documentReferenceIssues ?? [],
+ record,
+ };
} catch (error) {
const canRollback =
!didCreateProject &&
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
index a4b0b04a2e..973db3476c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
@@ -54,7 +54,7 @@ describe('startProjectFileReport', () => {
report.report({ completed: 1, phase: 'bundling', total: 3 });
report.report({ completed: 2, phase: 'bundling', total: 3 });
- report.succeed('projects.exported', []);
+ report.succeed('projects.exported', { boardItemIssues: [], documentReferenceIssues: [] });
expect(toaster.create).toHaveBeenCalledTimes(1);
expect(toaster.update).toHaveBeenCalledTimes(3);
@@ -86,7 +86,7 @@ describe('startProjectFileReport', () => {
it('finishes a clean run as a plain success with nothing to explain', () => {
const report = toasts.startProjectFileReport(t, 'projects.exporting');
- report.succeed('projects.exported', []);
+ report.succeed('projects.exported', { boardItemIssues: [], documentReferenceIssues: [] });
expect(toaster.update).toHaveBeenCalledWith('toast-1', {
duration: undefined,
@@ -99,10 +99,55 @@ describe('startProjectFileReport', () => {
it('finishes a lossy run as a warning naming the count', () => {
const report = toasts.startProjectFileReport(t, 'projects.exporting');
- report.succeed('projects.exported', ['a.png', 'b.png']);
+ report.succeed('projects.exported', {
+ boardItemIssues: [],
+ documentReferenceIssues: [
+ { kind: 'image', name: 'a.png', reason: 'fetch-failed' },
+ { kind: 'image', name: 'b.png', reason: 'fetch-failed' },
+ ],
+ });
+
+ expect(toaster.update).toHaveBeenCalledWith('toast-1', {
+ description: 'projects.file.missingReferences({"count":2})',
+ duration: undefined,
+ title: 'projects.exported',
+ type: 'warning',
+ });
+ });
+
+ /**
+ * Losing a board result and losing a canvas layer are different sizes of problem, so one count
+ * cannot stand for both.
+ */
+ it('counts board items and document references apart', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.succeed('projects.exported', {
+ boardItemIssues: [{ kind: 'video', name: 'clip.mp4', reason: 'fetch-failed' }],
+ documentReferenceIssues: [
+ { kind: 'image', name: 'a.png', reason: 'fetch-failed' },
+ { kind: 'image', name: 'b.png', reason: 'fetch-failed' },
+ ],
+ });
+
+ expect(toaster.update).toHaveBeenCalledWith('toast-1', {
+ description: 'projects.file.missingBoardItems({"count":1}) projects.file.missingReferences({"count":2})',
+ duration: undefined,
+ title: 'projects.exported',
+ type: 'warning',
+ });
+ });
+
+ it('finishes a run that lost only board items as a warning about those', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.succeed('projects.exported', {
+ boardItemIssues: [{ kind: 'image', name: 'unreferenced.png', reason: 'fetch-failed' }],
+ documentReferenceIssues: [],
+ });
expect(toaster.update).toHaveBeenCalledWith('toast-1', {
- description: 'projects.file.missingAssets({"count":2})',
+ description: 'projects.file.missingBoardItems({"count":1})',
duration: undefined,
title: 'projects.exported',
type: 'warning',
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
index 678908d04a..1c6279d867 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
@@ -1,5 +1,6 @@
import { toaster } from '@platform/ui';
+import type { ProjectTransferIssues } from './invk/transfer';
import type { ProjectFileProgress } from './projectFile';
import { describeProjectFileError } from './projectFileErrors';
@@ -43,10 +44,14 @@ export interface ProjectFileReporter {
/** Update the live toast from a transfer's progress. */
report: (progress: ProjectFileProgress) => void;
/**
- * Finish cleanly, or as a warning naming what was left behind. `lostAssetNames`
- * is the export's `missingAssetNames` or the import's `danglingAssetNames`.
+ * Finish cleanly, or as a warning naming what was left behind.
+ *
+ * Board items and document references are counted apart because they cost different things: a
+ * missing board item is a result still findable elsewhere, a missing document reference is a
+ * hole in the canvas. One combined number meant anything from "you will not notice" to "the
+ * project is broken".
*/
- succeed: (title: string, lostAssetNames: readonly string[]) => void;
+ succeed: (title: string, issues: ProjectTransferIssues) => void;
/** Finish as a failure, translating an `InvkFormatError` reason where there is one. */
fail: (title: string, error: unknown) => void;
}
@@ -91,18 +96,24 @@ export const startProjectFileReport = (t: Translate, title: string): ProjectFile
report: (progress) => {
toaster.update(id, { description: describeProgress(t, progress) });
},
- succeed: (successTitle, lostAssetNames) => {
- if (lostAssetNames.length === 0) {
+ succeed: (successTitle, issues) => {
+ const boardCount = issues.boardItemIssues.length;
+ const referenceCount = issues.documentReferenceIssues.length;
+
+ if (boardCount === 0 && referenceCount === 0) {
settle({ title: successTitle, type: 'success' });
return;
}
- settle({
- description: t('projects.file.missingAssets', { count: lostAssetNames.length }),
- title: successTitle,
- type: 'warning',
- });
+ // Counts, never names: a project can lose hundreds of assets at once, and a toast listing
+ // them would be unreadable. The typed detail stays on the outcome for anything that needs it.
+ const parts = [
+ ...(boardCount === 0 ? [] : [t('projects.file.missingBoardItems', { count: boardCount })]),
+ ...(referenceCount === 0 ? [] : [t('projects.file.missingReferences', { count: referenceCount })]),
+ ];
+
+ settle({ description: parts.join(' '), title: successTitle, type: 'warning' });
},
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
index 2f982b13e4..ffaa4979fe 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
@@ -70,10 +70,10 @@ export const useImportProjectFile = (onImported: (record: ProjectRecordDTO) => P
}
await runReported(t, { failed: t('projects.importFailed'), running: t('projects.importing') }, async (report) => {
- const { danglingAssetNames, record } = await importProjectFile(file, { onProgress: report.report, owner });
+ const { record, ...issues } = await importProjectFile(file, { onProgress: report.report, owner });
assertAccountScopeCurrent(owner);
- report.succeed(t('projects.imported', { name: record.name }), danglingAssetNames);
+ report.succeed(t('projects.imported', { name: record.name }), issues);
await onImported(record);
assertAccountScopeCurrent(owner);
});
@@ -92,9 +92,9 @@ export const useExportLibraryProject = (): ((projectId: string, name: string) =>
t,
{ failed: t('projects.exportFailed'), running: t('projects.exporting', { name }) },
async (report, owner) => {
- const { missingAssetNames } = await exportLibraryProject(projectId, { onProgress: report.report, owner });
+ const issues = await exportLibraryProject(projectId, { onProgress: report.report, owner });
- report.succeed(t('projects.exported', { name }), missingAssetNames);
+ report.succeed(t('projects.exported', { name }), issues);
}
);
},
@@ -112,9 +112,9 @@ export const useExportOpenProject = (): ((project: Project) => void) => {
t,
{ failed: t('projects.exportFailed'), running: t('projects.exporting', { name: project.name }) },
async (report, owner) => {
- const { missingAssetNames } = await exportOpenProject(project, { onProgress: report.report, owner });
+ const issues = await exportOpenProject(project, { onProgress: report.report, owner });
- report.succeed(t('projects.exported', { name: project.name }), missingAssetNames);
+ report.succeed(t('projects.exported', { name: project.name }), issues);
}
);
},