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): carry videos in .invk archives

joshistoast9d36d6d6bed0
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdx
index 606f368c45..e6e81ccc74 100644
--- a/docs/src/content/docs/development/Front End/project-files.mdx
+++ b/docs/src/content/docs/development/Front End/project-files.mdx
@@ -16,6 +16,9 @@ Workbench projects export to a portable `.invk` archive. The feature lives in `i
| `project.json` | yes | The whole project document — the same payload the backend stores as the project record's opaque `data`. |
| `cover.<ext>` | no | Thumbnail of the project's newest result. The extension varies by what the server served, so the entry path is recorded in the manifest. |
| `images/<image_name>` | no | Image bytes, keyed by the exact `image_name` the exporting server used. |
+| `videos/<video_name>` | no | Video bytes, keyed the same way. |
+
+Assets are filed by kind rather than pooled. Images and videos are separate backend namespaces with separate fetch and upload routes, so import has to know which an entry is before it can restore it — the folder states that, where a shared one would leave it to be guessed from a file extension. Adding `videos/` needed no version bump: `readInvkArchive` ignores entries it does not recognize, so a reader predating it reads such an archive and simply leaves those references dangling, exactly as it would for an absent image.
The manifest is written indented and the document compact: the manifest is the one entry someone might open by hand, and the document is the largest thing in the archive before compression. Text entries are deflated; image entries are stored, since PNG and WEBP are already compressed.
@@ -23,7 +26,11 @@ The manifest is written indented and the document compact: the manifest is the o
A project document references its pixels by server image name, never by URL or inline data (see `CanvasImageRef` in `canvas-engine/contracts.ts`). Without the bytes, an exported project opens with nothing but missing layers anywhere except the machine that wrote it. The archive carries them.
-Which ones is decided by `collectLiveImageRefs()` in `projects/projectAssets.ts`. It walks the document collecting every string found under the keys `imageName` and `image_name` — the only two keys in the document that hold an image name. Collecting by key rather than by path is what makes it complete: a new control-adapter kind or node field is picked up without touching the collector.
+Which ones is decided by `collectLiveAssetRefs()` in `projects/projectAssets.ts`. It walks the document collecting every string found under `imageName` and `image_name` as an image, and under `video_name` as a video — the only keys in the document that hold an asset name. Collecting by key rather than by path is what makes it complete: a new control-adapter kind or node field is picked up without touching the collector.
+
+`video_name` reaches a document through an imported workflow whose node value was authored elsewhere (`VideoField` in the backend's `fields.py`, consumed by `video_frame_extract` and friends). webv2 cannot author one yet — `VideoField` is absent from `STATEFUL_FIELD_TYPE_NAMES` — but it round-trips one verbatim, so a project file has to carry it.
+
+**The gallery selection is excluded, of either kind.** `selectedImage`, `selectedImageName` and `selectedImageNames` are pointers into per-install gallery content, not things the document renders; a project arriving on another machine should open with nothing selected rather than drag a stranger's gallery in behind it. The skip is by key on purpose: `GalleryItem` happens to spell its name field `name`, which no collector key matches, so these would be missed anyway — but that is an accident of naming, and the explicit skip is what stops a future rename from silently changing what a project file contains.
**History is excluded.** The walker skips the `queue`, `graphHistory` and `events` roots, and the `snapshot`, `snapshots` and `recentImages` keys at any depth. Every queue entry embeds a full canvas snapshot and the gallery widget keeps up to sixty recent results, so bundling all of it would turn a working project into a multi-gigabyte archive. References into history survive in the document and resolve on any install that still has those images.
@@ -31,11 +38,13 @@ Which ones is decided by `collectLiveImageRefs()` in `projects/projectAssets.ts`
`readInvkArchive()` unpacks and validates; `restoreArchiveImages()` puts the pixels back.
-Restoration checks which referenced images the server already has in one bulk `POST /images/images_by_names` call, uploads only the missing ones out of `images/`, and returns an old-to-new mapping for any the server renamed. `remapImageRefs()` then rewrites the document — the whole document this time, including the history the export left behind, so nothing keeps pointing at a pre-import name.
+Restoration checks which referenced assets the server already has, uploads only the missing ones out of `images/` and `videos/`, and returns an old-to-new mapping **per kind** — the namespaces are separate, so a single flat map would let an image rewrite a video that happened to share its name. `remapAssetRefs()` then rewrites the document — the whole document this time, including the history the export left behind, so nothing keeps pointing at a pre-import name.
-Restored images upload with `image_category: 'other'`, the canvas's private category: they appear in no gallery view and no board count. The previous frontend used `general`, which empties a stranger's project into your gallery.
+The existence check is the one place the two kinds are not symmetric. Images have a bulk `POST /images/images_by_names`; videos have no equivalent, so that check fans out one `GET /videos/i/{name}` per name behind the same concurrency limit of 5. This is what `hydrateVideoRefs` in the gallery's data layer already does for the same reason. A project with no video references never issues the video check at all.
-An image that is neither on the server nor in the archive is reported as dangling and its reference is left alone, so the project opens with one broken layer rather than not at all. Both fetches and uploads are concurrency-limited to five by `mapWithConcurrency()`.
+Restored assets upload with the category `'other'`, the canvas's private category: they appear in no gallery view and no board count. The previous frontend used `general`, which empties a stranger's project into your gallery.
+
+An asset that is neither on the server nor in the archive is reported as dangling and its reference is left alone, so the project opens with one broken layer rather than not at all. Both fetches and uploads are concurrency-limited to five by `mapWithConcurrency()`, over one queue spanning both kinds — the limit exists to be kind to the backend, and would not be if each kind got its own.
**Import never overwrites.** The document always lands under a freshly minted project id, never the one in the file, so exchanging a project cannot collide and re-importing your own export cannot replace the original.
@@ -57,6 +66,8 @@ Future format changes should add a new member to the union rather than widening
`archive.ts` is the only module that imports fflate, and it does so with `await import()` so the ZIP codec never enters an initial chunk — the architecture budget fails on a new package appearing in a route's source-owner set. Both directions are bounded by `INVK_MAX_ARCHIVE_BYTES` and `INVK_MAX_ENTRIES`, because an `.invk` is a file someone was handed.
+`INVK_MAX_ARCHIVE_BYTES` is 4 GB, a figure chosen when the only payload was layer bitmaps. A single video can be hundreds of megabytes, so hitting the ceiling has gone from theoretical to plausible. The guard fails cleanly into the `too-large` reason, which is the right behavior, but the constant now has a second and much heavier consumer.
+
## Compatibility notes
The archive stores references to models, LoRAs and other generation resources, not the model files themselves. Loading a project on another install restores its canvas and images, but missing models still need to be installed or replaced.
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts
index 21d9c6c18d..6350a8d4d4 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts
@@ -22,6 +22,20 @@ describe('writeArchive / readArchive', () => {
expect([...entries.get('images/a.png')!]).toEqual([...pixels]);
});
+ it('round-trips entries from both asset folders', async () => {
+ const blob = await writeArchive(
+ new Map([
+ ['images/a.png', binaryEntry(new Uint8Array([1, 2]))],
+ ['videos/clip.mp4', binaryEntry(new Uint8Array([3, 4, 5]))],
+ ])
+ );
+
+ const entries = await readArchive(await toBytes(blob));
+
+ expect([...entries.keys()].sort()).toEqual(['images/a.png', 'videos/clip.mp4']);
+ expect([...entries.get('videos/clip.mp4')!]).toEqual([3, 4, 5]);
+ });
+
it('preserves unicode in text entries', async () => {
const blob = await writeArchive(new Map([['project.json', textEntry('{"name":"プロジェクト — 1"}')]]));
const entries = await readArchive(await toBytes(blob));
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/imageTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
similarity index 56%
rename from invokeai/frontend/webv2/src/workbench/projects/invk/imageTransport.ts
rename to invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
index 18914f3fa4..5e8ecbdc08 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/imageTransport.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
@@ -1,7 +1,8 @@
+import { mapWithConcurrency } from '@platform/core/concurrency';
import { apiFetch, apiFetchJson, apiFetchRaw } from '@platform/transport/http';
/**
- * The image half of a project file: pulling referenced bytes off the server on
+ * The asset half of a project file: pulling referenced bytes off the server on
* the way out, and putting the missing ones back on the way in.
*
* This lives beside the archive rather than reaching for
@@ -10,16 +11,27 @@ import { apiFetch, apiFetchJson, apiFetchRaw } from '@platform/transport/http';
* 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 images are uploaded with `image_category: 'other'`. 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`).
- * The previous frontend uploaded restored images as `'general'`, which empties
- * a stranger's project into your gallery; the pixels a document points at are
- * not gallery content, they are the document.
+ * Restored assets are uploaded with the category `'other'`. 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`).
+ * The previous frontend uploaded restored images as `'general'`, which empties a
+ * stranger's project into your gallery; the pixels a document points at are not
+ * gallery content, they are the document.
+ *
+ * ### Images and videos are not symmetric
+ *
+ * Everything here exists twice because the backend keeps the two in separate
+ * namespaces with separate routes. The one place they genuinely differ in shape
+ * is the existence check: images have a bulk `images_by_names`, videos have no
+ * equivalent, so the video check fans out one request per name behind a
+ * concurrency limit. That is what `hydrateVideoRefs` in the gallery's data layer
+ * already does for the same reason, and what the previous frontend did for
+ * images before the bulk endpoint existed.
*/
const IMAGES_BASE = '/api/v1/images';
+const VIDEOS_BASE = '/api/v1/videos';
/**
* Names per existence request. The endpoint answers any length, but a URL-free
@@ -28,18 +40,29 @@ const IMAGES_BASE = '/api/v1/images';
*/
const EXISTENCE_BATCH_SIZE = 500;
+/** Simultaneous per-name video lookups, matching the image fetch limit. */
+const VIDEO_EXISTENCE_CONCURRENCY = 5;
+
export interface UploadedImage {
height: number;
imageName: string;
width: number;
}
+export interface UploadedVideo {
+ videoName: string;
+}
+
interface ImageDTOSubset {
height: number;
image_name: string;
width: number;
}
+interface VideoDTOSubset {
+ video_name: string;
+}
+
/**
* Which of `imageNames` the server already has. The endpoint silently omits
* names it cannot serve, which is exactly the answer wanted here: anything
@@ -67,9 +90,29 @@ export const findExistingImageNames = async (
return existing;
};
+/**
+ * Which of `videoNames` the server already has.
+ *
+ * There is no bulk equivalent of `images_by_names` for videos, so this asks per
+ * name behind a concurrency limit. A 404 is the answer, not an error — the whole
+ * question is which names are absent.
+ */
+export const findExistingVideoNames = async (
+ videoNames: readonly string[],
+ signal?: AbortSignal
+): Promise<Set<string>> => {
+ const found = await mapWithConcurrency(videoNames, VIDEO_EXISTENCE_CONCURRENCY, async (videoName) => {
+ const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}`, { signal });
+
+ return response.ok ? videoName : null;
+ });
+
+ return new Set(found.filter((videoName): videoName is string => videoName !== null));
+};
+
/**
* Full-resolution bytes for one image, or `null` when the server will not serve
- * it. A missing image is not an export failure: the previous frontend logged and
+ * it. A missing asset is not an export failure: the previous frontend logged and
* skipped, and a project that exports every layer but one is far more use than
* one that refuses to export at all.
*/
@@ -83,6 +126,17 @@ export const fetchImageBytes = async (imageName: string, signal?: AbortSignal):
return new Uint8Array(await response.arrayBuffer());
};
+/** The same, for a video. */
+export const fetchVideoBytes = async (videoName: string, signal?: AbortSignal): Promise<Uint8Array | null> => {
+ const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}/full`, { signal });
+
+ if (!response.ok) {
+ return null;
+ }
+
+ return new Uint8Array(await response.arrayBuffer());
+};
+
export interface FetchedThumbnail {
bytes: Uint8Array;
/** Response MIME type, which decides the cover entry's extension. */
@@ -134,6 +188,27 @@ export const uploadArchiveImage = async (
return { height: dto.height, imageName: dto.image_name, width: dto.width };
};
+/** The same, for a video. Dimensions are not read: nothing in the document needs them. */
+export const uploadArchiveVideo = async (
+ bytes: Uint8Array,
+ fileName: string,
+ options: { contentType?: string; signal?: AbortSignal } = {}
+): Promise<UploadedVideo> => {
+ const query = new URLSearchParams({ is_intermediate: 'false', video_category: 'other' });
+ 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 };
+};
+
const EXTENSION_BY_MIME: Readonly<Record<string, string>> = {
'image/jpeg': 'jpg',
'image/png': 'png',
@@ -147,10 +222,18 @@ export const coverExtensionForMime = (contentType: string): string =>
const MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
+ mkv: 'video/x-matroska',
+ mov: 'video/quicktime',
+ mp4: 'video/mp4',
png: 'image/png',
+ webm: 'video/webm',
webp: 'image/webp',
};
-/** Best guess at a bundled entry's MIME type, from its name. */
+/**
+ * Best guess at a bundled entry's MIME type, from its name. Only ever a hint for
+ * the upload's multipart part — the entry's folder already decided its kind, so
+ * an unrecognized extension falling back to PNG cannot misroute a video.
+ */
export const mimeForEntryName = (entryName: string): string =>
MIME_BY_EXTENSION[entryName.split('.').pop()?.toLowerCase() ?? ''] ?? 'image/png';
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 967a595f23..5bea53fdbb 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts
@@ -69,7 +69,7 @@ describe('executeInvkExport', () => {
Promise.resolve({ bytes: new Uint8Array([1, 2, 3]), contentType: 'image/webp;charset=binary' }),
});
- expect(result).toEqual({ bundledCount: 2, missingImageNames: [] });
+ expect(result).toEqual({ bundledImageCount: 2, bundledVideoCount: 0, missingAssetNames: [] });
expect(download).toHaveBeenCalledTimes(1);
const [blob, fileName] = download.mock.calls[0]! as [Blob, string];
@@ -103,7 +103,7 @@ describe('executeInvkExport', () => {
fetchImageThumbnail: () => Promise.resolve(null),
});
- expect(result).toEqual({ bundledCount: 1, missingImageNames: ['live-b.png'] });
+ expect(result).toEqual({ bundledImageCount: 1, bundledVideoCount: 0, missingAssetNames: ['live-b.png'] });
expect(download).toHaveBeenCalledTimes(1);
});
@@ -114,7 +114,7 @@ describe('executeInvkExport', () => {
fetchImageThumbnail: () => Promise.reject(new Error('network')),
});
- expect(result.missingImageNames).toEqual(['live-a.png', 'live-b.png']);
+ expect(result.missingAssetNames).toEqual(['live-a.png', 'live-b.png']);
});
it('omits the cover entry when there is no cover to fetch', async () => {
@@ -133,6 +133,58 @@ describe('executeInvkExport', () => {
expect(JSON.parse(readEntryText(entries.get(INVK_MANIFEST_ENTRY)!)).cover).toBeUndefined();
});
+ it('writes videos under their own prefix, beside the images', async () => {
+ const download = vi.fn();
+ const plan = planInvkExport({
+ ...planInput,
+ projectDocument: {
+ ...projectDocument(),
+ projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.mp4' } } }, id: 'n' }] },
+ },
+ });
+
+ expect(plan.videoNames).toEqual(['clip.mp4']);
+
+ const result = await executeInvkExport(plan, {
+ download,
+ fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
+ fetchImageThumbnail: () => Promise.resolve(null),
+ fetchVideoBytes: (videoName) => Promise.resolve(bytesFor(videoName)),
+ });
+
+ expect(result).toEqual({ bundledImageCount: 2, bundledVideoCount: 1, missingAssetNames: [] });
+
+ const [blob] = download.mock.calls[0]! as [Blob];
+ const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
+
+ expect([...entries.keys()].sort()).toEqual([
+ 'images/live-a.png',
+ 'images/live-b.png',
+ 'manifest.json',
+ 'project.json',
+ 'videos/clip.mp4',
+ ]);
+ });
+
+ it('skips a video the server will not serve, exactly as it skips an image', async () => {
+ const plan = planInvkExport({
+ ...planInput,
+ projectDocument: {
+ ...projectDocument(),
+ projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.mp4' } } }, id: 'n' }] },
+ },
+ });
+
+ const result = await executeInvkExport(plan, {
+ download: vi.fn(),
+ fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),
+ fetchImageThumbnail: () => Promise.resolve(null),
+ fetchVideoBytes: () => Promise.resolve(null),
+ });
+
+ expect(result).toEqual({ bundledImageCount: 2, bundledVideoCount: 0, missingAssetNames: ['clip.mp4'] });
+ });
+
it('reports progress through bundling and packing', async () => {
const onProgress = vi.fn();
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
index b462a2c233..c496564996 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
@@ -1,12 +1,12 @@
import { mapWithConcurrency } from '@platform/core/concurrency';
-import { collectLiveImageRefs, selectCoverImageName } from '@workbench/projects/projectAssets';
+import { collectLiveAssetRefs, selectCoverImageName } from '@workbench/projects/projectAssets';
import type { InvkArchiveEntry } from './archive';
-import type { FetchedThumbnail } from './imageTransport';
+import type { FetchedThumbnail } from './assetTransport';
import { binaryEntry, textEntry, writeArchive } from './archive';
-import { INVK_DOCUMENT_ENTRY, INVK_IMAGES_PREFIX, INVK_MANIFEST_ENTRY } from './format';
-import { coverExtensionForMime, fetchImageBytes, fetchImageThumbnail } from './imageTransport';
+import { coverExtensionForMime, fetchImageBytes, fetchImageThumbnail, fetchVideoBytes } from './assetTransport';
+import { INVK_DOCUMENT_ENTRY, INVK_IMAGES_PREFIX, INVK_MANIFEST_ENTRY, INVK_VIDEOS_PREFIX } from './format';
import { buildInvkManifest, toInvkFileName } from './manifest';
/**
@@ -14,9 +14,9 @@ import { buildInvkManifest, toInvkFileName } from './manifest';
* way `canvas-engine/export/psdExport.ts` splits PSD export.
*
* {@link planInvkExport} decides what the archive contains — entry names, which
- * image names to bundle, which one becomes the cover — from the document alone.
- * No network, no DOM, no fflate, so the interesting decision (what belongs in a
- * project file) is a node test rather than a manual round trip.
+ * asset names to bundle and of which kind, which image becomes the cover — from
+ * the document alone. No network, no DOM, no fflate, so the interesting decision
+ * (what belongs in a project file) is a node test rather than a manual round trip.
*
* {@link executeInvkExport} does the parts that can fail: fetching each image,
* packing the ZIP, handing it to the browser.
@@ -27,8 +27,8 @@ import { buildInvkManifest, toInvkFileName } from './manifest';
* resolves it.
*/
-/** Simultaneous image fetches. Matches the previous frontend's limit. */
-const IMAGE_FETCH_CONCURRENCY = 5;
+/** Simultaneous asset fetches. Matches the previous frontend's limit. */
+const ASSET_FETCH_CONCURRENCY = 5;
export interface InvkExportPlan {
/** Cover image name, or `null` for a project that has produced nothing. */
@@ -40,6 +40,8 @@ export interface InvkExportPlan {
/** 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[];
}
export const planInvkExport = (input: {
@@ -50,19 +52,22 @@ export const planInvkExport = (input: {
}): InvkExportPlan => {
const sourceProjectId = typeof input.projectDocument.id === 'string' ? input.projectDocument.id : undefined;
+ const refs = collectLiveAssetRefs(input.projectDocument);
+
return {
coverImageName: selectCoverImageName(input.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(input.projectDocument),
fileName: toInvkFileName(input.name),
- imageNames: [...collectLiveImageRefs(input.projectDocument)].sort(),
+ imageNames: [...refs.images].sort(),
manifestInput: {
appVersion: input.appVersion,
createdAt: input.createdAt,
name: input.name,
...(sourceProjectId === undefined ? {} : { sourceProjectId }),
},
+ videoNames: [...refs.videos].sort(),
};
};
@@ -76,46 +81,67 @@ export interface InvkExportDeps {
download: (blob: Blob, fileName: string) => void;
fetchImageBytes?: (imageName: string, signal?: AbortSignal) => Promise<Uint8Array | null>;
fetchImageThumbnail?: (imageName: string, signal?: AbortSignal) => Promise<FetchedThumbnail | null>;
+ fetchVideoBytes?: (videoName: string, signal?: AbortSignal) => Promise<Uint8Array | null>;
onProgress?: (progress: InvkExportProgress) => void;
signal?: AbortSignal;
}
export interface InvkExportResult {
/** Images successfully written into `images/`. */
- bundledCount: number;
- /** Referenced images the server would not serve. Their references still ship. */
- missingImageNames: string[];
+ 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> => {
const readImage = deps.fetchImageBytes ?? fetchImageBytes;
+ const readVideo = deps.fetchVideoBytes ?? fetchVideoBytes;
const readThumbnail = deps.fetchImageThumbnail ?? fetchImageThumbnail;
const entries = new Map<string, InvkArchiveEntry>();
- const missingImageNames: string[] = [];
- let bundledCount = 0;
+ const missingAssetNames: string[] = [];
+ let bundledImageCount = 0;
+ let bundledVideoCount = 0;
let completed = 0;
const cover =
plan.coverImageName === null ? null : await readThumbnail(plan.coverImageName, deps.signal).catch(() => null);
const coverEntryName = cover === null ? undefined : `cover.${coverExtensionForMime(cover.contentType)}`;
- await mapWithConcurrency(plan.imageNames, IMAGE_FETCH_CONCURRENCY, async (imageName) => {
- const bytes = await readImage(imageName, deps.signal).catch(() => null);
+ // 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 })),
+ ];
+
+ await mapWithConcurrency(assets, ASSET_FETCH_CONCURRENCY, async ({ kind, name }) => {
+ const bytes = await (kind === 'image' ? readImage(name, deps.signal) : readVideo(name, deps.signal)).catch(
+ () => null
+ );
completed += 1;
- deps.onProgress?.({ completed, phase: 'bundling', total: plan.imageNames.length });
+ deps.onProgress?.({ completed, phase: 'bundling', total: assets.length });
if (bytes === null) {
- missingImageNames.push(imageName);
+ missingAssetNames.push(name);
+
+ return;
+ }
+
+ if (kind === 'image') {
+ bundledImageCount += 1;
+ entries.set(`${INVK_IMAGES_PREFIX}${name}`, binaryEntry(bytes));
return;
}
- bundledCount += 1;
- entries.set(`${INVK_IMAGES_PREFIX}${imageName}`, binaryEntry(bytes));
+ bundledVideoCount += 1;
+ entries.set(`${INVK_VIDEOS_PREFIX}${name}`, binaryEntry(bytes));
});
- deps.onProgress?.({ completed: plan.imageNames.length, phase: 'packing', total: plan.imageNames.length });
+ deps.onProgress?.({ completed: assets.length, phase: 'packing', total: assets.length });
const manifest = buildInvkManifest({
...plan.manifestInput,
@@ -134,5 +160,5 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
deps.download(blob, plan.fileName);
- return { bundledCount, missingImageNames: missingImageNames.sort() };
+ return { bundledImageCount, bundledVideoCount, missingAssetNames: missingAssetNames.sort() };
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts
index a20a285af4..e9c89ce284 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts
@@ -17,7 +17,21 @@ export const INVK_VERSION = 2;
/** 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';
+
+/**
+ * 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
+ * know which an entry is before it can restore it — and a folder states that
+ * where a shared one would leave it to be guessed from a file extension.
+ *
+ * `images/` is also byte-identical to the legacy v1 container, which is the
+ * continuity this format was built around. Adding `videos/` needs no version
+ * bump: `readInvkArchive` ignores entries it does not recognize, so a reader
+ * predating videos reads such an archive and simply leaves those references
+ * dangling — the same degradation an absent image already gets.
+ */
export const INVK_IMAGES_PREFIX = 'images/';
+export const INVK_VIDEOS_PREFIX = 'videos/';
export type InvkFormatReason =
/** A ZIP, but the manifest is a canvas project written by the previous frontend. */
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 a171c38848..f991a4d29d 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { binaryEntry, textEntry, writeArchive } from './archive';
import { InvkFormatError } from './format';
-import { readInvkArchive, restoreArchiveImages } from './importProject';
+import { readInvkArchive, restoreArchiveAssets } from './importProject';
const imageRef = (imageName: string) => ({ height: 64, imageName, width: 64 });
@@ -106,7 +106,7 @@ describe('readInvkArchive', () => {
});
});
-describe('restoreArchiveImages', () => {
+describe('restoreArchiveAssets', () => {
const contents = async (overrides: Partial<Awaited<ReturnType<typeof readInvkArchive>>> = {}) => ({
...(await readInvkArchive(await validArchive())),
...overrides,
@@ -117,33 +117,33 @@ describe('restoreArchiveImages', () => {
Promise.resolve({ height: 1, imageName: fileName, width: 1 })
);
- const result = await restoreArchiveImages(await contents(), {
+ const result = await restoreArchiveAssets(await contents(), {
findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
uploadArchiveImage: upload,
});
expect(upload).not.toHaveBeenCalled();
- expect(result).toMatchObject({ danglingImageNames: [], uploadedCount: 0 });
- expect(result.mapping.size).toBe(0);
+ expect(result).toMatchObject({ danglingAssetNames: [], uploadedCount: 0 });
+ expect(result.mappings.images.size).toBe(0);
});
it('records the rename when the server assigns a different name', async () => {
- const result = await restoreArchiveImages(await contents(), {
+ const result = await restoreArchiveAssets(await contents(), {
findExistingImageNames: () => Promise.resolve(new Set()),
uploadArchiveImage: () => Promise.resolve({ height: 1, imageName: 'server-1.png', width: 1 }),
});
- expect([...result.mapping]).toEqual([['a.png', 'server-1.png']]);
+ expect([...result.mappings.images]).toEqual([['a.png', 'server-1.png']]);
expect(result.uploadedCount).toBe(1);
});
it('records no rename when the server keeps the name', async () => {
- const result = await restoreArchiveImages(await contents(), {
+ const result = await restoreArchiveAssets(await contents(), {
findExistingImageNames: () => Promise.resolve(new Set()),
uploadArchiveImage: (_bytes, fileName) => Promise.resolve({ height: 1, imageName: fileName, width: 1 }),
});
- expect(result.mapping.size).toBe(0);
+ expect(result.mappings.images.size).toBe(0);
expect(result.uploadedCount).toBe(1);
});
@@ -152,22 +152,22 @@ describe('restoreArchiveImages', () => {
missing.images.delete('a.png');
- const result = await restoreArchiveImages(missing, {
+ const result = await restoreArchiveAssets(missing, {
findExistingImageNames: () => Promise.resolve(new Set()),
uploadArchiveImage: () => Promise.reject(new Error('should not be called')),
});
- expect(result.danglingImageNames).toEqual(['a.png']);
+ expect(result.danglingAssetNames).toEqual(['a.png']);
expect(result.uploadedCount).toBe(0);
});
it('reports a failed upload as dangling rather than failing the import', async () => {
- const result = await restoreArchiveImages(await contents(), {
+ const result = await restoreArchiveAssets(await contents(), {
findExistingImageNames: () => Promise.resolve(new Set()),
uploadArchiveImage: () => Promise.reject(new Error('upload failed')),
});
- expect(result.danglingImageNames).toEqual(['a.png']);
+ expect(result.danglingAssetNames).toEqual(['a.png']);
expect(result.uploadedCount).toBe(0);
});
@@ -175,7 +175,7 @@ describe('restoreArchiveImages', () => {
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 restoreArchiveImages(withCover, {
+ const result = await restoreArchiveAssets(withCover, {
findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
uploadArchiveImage: upload,
});
@@ -187,15 +187,64 @@ describe('restoreArchiveImages', () => {
});
});
+ 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]),
+ })
+ );
+
+ expect([...withVideo.videos.keys()]).toEqual(['clip.mp4']);
+
+ const uploadImage = vi.fn((_bytes: Uint8Array, fileName: string) =>
+ Promise.resolve({ height: 1, imageName: fileName, width: 1 })
+ );
+ 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);
+ });
+
+ it('never asks the video endpoint about an images-only archive', async () => {
+ const findVideos = vi.fn(() => Promise.resolve(new Set<string>()));
+
+ await restoreArchiveAssets(await contents(), {
+ findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
+ findExistingVideoNames: findVideos,
+ uploadArchiveImage: () => Promise.reject(new Error('should not be called')),
+ });
+
+ expect(findVideos).not.toHaveBeenCalled();
+ });
+
it('survives a cover that fails to upload', async () => {
const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });
- const result = await restoreArchiveImages(withCover, {
+ const result = await restoreArchiveAssets(withCover, {
findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),
uploadArchiveImage: () => Promise.reject(new Error('nope')),
});
expect(result.coverImageName).toBeNull();
- expect(result.danglingImageNames).toEqual([]);
+ expect(result.danglingAssetNames).toEqual([]);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
index 97b7121bf1..79d0715afe 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
@@ -1,12 +1,24 @@
import { mapWithConcurrency } from '@platform/core/concurrency';
-import { collectLiveImageRefs } from '@workbench/projects/projectAssets';
+import { collectLiveAssetRefs } from '@workbench/projects/projectAssets';
-import type { UploadedImage } from './imageTransport';
+import type { UploadedImage, UploadedVideo } from './assetTransport';
import type { InvkManifest } from './manifest';
import { readArchive, readEntryText } from './archive';
-import { INVK_DOCUMENT_ENTRY, INVK_IMAGES_PREFIX, INVK_MANIFEST_ENTRY, InvkFormatError } from './format';
-import { findExistingImageNames, mimeForEntryName, uploadArchiveImage } from './imageTransport';
+import {
+ findExistingImageNames,
+ findExistingVideoNames,
+ mimeForEntryName,
+ uploadArchiveImage,
+ uploadArchiveVideo,
+} from './assetTransport';
+import {
+ INVK_DOCUMENT_ENTRY,
+ INVK_IMAGES_PREFIX,
+ INVK_MANIFEST_ENTRY,
+ INVK_VIDEOS_PREFIX,
+ InvkFormatError,
+} from './format';
import { parseInvkManifest } from './manifest';
/**
@@ -29,7 +41,7 @@ import { parseInvkManifest } from './manifest';
*/
/** Simultaneous uploads. Matches the previous frontend's limit. */
-const IMAGE_UPLOAD_CONCURRENCY = 5;
+const ASSET_UPLOAD_CONCURRENCY = 5;
export interface InvkArchiveContents {
/** Bundled preview bytes and the entry they came from, when the archive has one. */
@@ -38,6 +50,8 @@ export interface InvkArchiveContents {
images: Map<string, Uint8Array>;
manifest: InvkManifest;
projectDocument: Record<string, unknown>;
+ /** Bundled video bytes, keyed by the video name the exporting server used. */
+ videos: Map<string, Uint8Array>;
}
const parseDocumentEntry = (bytes: Uint8Array): Record<string, unknown> => {
@@ -81,10 +95,16 @@ export const readInvkArchive = async (file: File): Promise<InvkArchiveContents>
}
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;
+ }
+
+ if (path.startsWith(INVK_VIDEOS_PREFIX)) {
+ videos.set(path.slice(INVK_VIDEOS_PREFIX.length), bytes);
}
}
@@ -95,22 +115,24 @@ export const readInvkArchive = async (file: File): Promise<InvkArchiveContents>
images,
manifest,
projectDocument: parseDocumentEntry(documentEntry),
+ videos,
};
};
-export interface RestoreImagesResult {
- /** Referenced images the archive did not carry and the server does not have. */
- danglingImageNames: string[];
- /** Old name to new name, for the images the server renamed on upload. */
- mapping: Map<string, string>;
+export interface RestoreAssetsResult {
/** The uploaded cover's server name, when the archive carried one. */
coverImageName: string | null;
- /** Images uploaded from the archive. */
+ /** Referenced assets the archive did not carry and the server does not have, of either kind. */
+ danglingAssetNames: string[];
+ /** Old name to new name, per kind. Kept apart because the namespaces are. */
+ mappings: { images: Map<string, string>; videos: Map<string, string> };
+ /** Assets uploaded from the archive, of either kind. */
uploadedCount: number;
}
-export interface RestoreImagesDeps {
+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;
signal?: AbortSignal;
uploadArchiveImage?: (
@@ -118,37 +140,83 @@ export interface RestoreImagesDeps {
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;
}
/**
- * Make the archive's images available on this server. Only what is missing gets
- * uploaded; a referenced image that is neither on the server nor in the archive
+ * 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 restoreArchiveImages = async (
+export const restoreArchiveAssets = async (
contents: InvkArchiveContents,
- deps: RestoreImagesDeps = {}
-): Promise<RestoreImagesResult> => {
- const checkExisting = deps.findExistingImageNames ?? findExistingImageNames;
- const upload = deps.uploadArchiveImage ?? uploadArchiveImage;
- const referenced = [...collectLiveImageRefs(contents.projectDocument)].sort();
- const existing = await checkExisting(referenced, deps.signal);
- const missing = referenced.filter((imageName) => !existing.has(imageName));
- const uploadable = missing.filter((imageName) => contents.images.has(imageName));
- const danglingImageNames = missing.filter((imageName) => !contents.images.has(imageName));
- const mapping = new Map<string, string>();
+ 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 danglingAssetNames: string[] = [];
+ 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;
+ }
+
+ const bytes = store.get(name);
+
+ if (bytes === undefined) {
+ danglingAssetNames.push(name);
+ continue;
+ }
+
+ pending.push({ bytes, kind, name });
+ }
+ }
+
+ const mappings = { images: new Map<string, string>(), videos: new Map<string, string>() };
// The cover is not part of the document, so it is uploaded alongside rather
// than through the reference set.
const coverTotal = contents.cover === null ? 0 : 1;
+ const total = pending.length + coverTotal;
let completed = 0;
let uploadedCount = 0;
const coverImageName =
contents.cover === null
? null
- : await upload(contents.cover.bytes, contents.cover.entryName, {
+ : await uploadImage(contents.cover.bytes, contents.cover.entryName, {
contentType: mimeForEntryName(contents.cover.entryName),
signal: deps.signal,
})
@@ -157,32 +225,31 @@ export const restoreArchiveImages = async (
if (contents.cover !== null) {
completed += 1;
- deps.onProgress?.({ completed, total: uploadable.length + coverTotal });
+ deps.onProgress?.({ completed, total });
}
- await mapWithConcurrency(uploadable, IMAGE_UPLOAD_CONCURRENCY, async (imageName) => {
- const bytes = contents.images.get(imageName)!;
-
+ await mapWithConcurrency(pending, ASSET_UPLOAD_CONCURRENCY, async ({ bytes, kind, name }) => {
try {
- const uploaded = await upload(bytes, imageName, {
- contentType: mimeForEntryName(imageName),
- signal: deps.signal,
- });
+ const options = { contentType: mimeForEntryName(name), signal: deps.signal };
+ const restoredName =
+ kind === 'image'
+ ? (await uploadImage(bytes, name, options)).imageName
+ : (await uploadVideo(bytes, name, options)).videoName;
uploadedCount += 1;
- if (uploaded.imageName !== imageName) {
- mapping.set(imageName, uploaded.imageName);
+ 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 image the archive never carried.
- danglingImageNames.push(imageName);
+ // not have — the same outcome as an asset the archive never carried.
+ danglingAssetNames.push(name);
}
completed += 1;
- deps.onProgress?.({ completed, total: uploadable.length + coverTotal });
+ deps.onProgress?.({ completed, total });
});
- return { coverImageName, danglingImageNames: danglingImageNames.sort(), mapping, uploadedCount };
+ return { coverImageName, danglingAssetNames: danglingAssetNames.sort(), mappings, uploadedCount };
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
index 442e98955d..6b9c089bfc 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { collectLiveImageRefs, remapImageRefs, selectCoverImageName } from './projectAssets';
+import { collectLiveAssetRefs, remapAssetRefs, selectCoverImageName } from './projectAssets';
/**
* The walker's contract, stated as documents rather than as paths: what an
- * archive must bundle, what it must leave behind, and what has to be rewritten
- * when the server hands back a different name.
+ * archive must bundle, what it must leave behind, which kind each name is, and
+ * what has to be rewritten when the server hands back a different name.
*/
const imageRef = (imageName: string) => ({ height: 512, imageName, width: 512 });
@@ -33,6 +33,8 @@ const galleryInstance = (recentImageNames: string[]) => ({
},
});
+const noMappings = { images: new Map<string, string>(), videos: new Map<string, string>() };
+
const projectDocument = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
canvas: {
document: { layers: [imageLayer('layer-1', 'live-image.png')], version: 2 },
@@ -54,32 +56,33 @@ const projectDocument = (overrides: Record<string, unknown> = {}): Record<string
...overrides,
});
-describe('collectLiveImageRefs', () => {
- it('collects canvas, widget value and graph node references', () => {
- expect(collectLiveImageRefs(projectDocument())).toEqual(
- new Set(['live-image.png', 'graph-image.png', 'upscale-input.png'])
- );
+describe('collectLiveAssetRefs', () => {
+ it('collects canvas, widget value and graph node references as images', () => {
+ const refs = collectLiveAssetRefs(projectDocument());
+
+ expect(refs.images).toEqual(new Set(['live-image.png', 'graph-image.png', 'upscale-input.png']));
+ expect(refs.videos).toEqual(new Set());
});
it('leaves history behind — queue snapshots, graph history, events, canvas snapshots', () => {
- const collected = collectLiveImageRefs(projectDocument());
+ const { images } = collectLiveAssetRefs(projectDocument());
- expect(collected.has('queue-image.png')).toBe(false);
- expect(collected.has('history-image.png')).toBe(false);
- expect(collected.has('event-image.png')).toBe(false);
- expect(collected.has('snapshot-image.png')).toBe(false);
+ expect(images.has('queue-image.png')).toBe(false);
+ expect(images.has('history-image.png')).toBe(false);
+ expect(images.has('event-image.png')).toBe(false);
+ expect(images.has('snapshot-image.png')).toBe(false);
});
it('leaves the gallery widget recents behind', () => {
- const collected = collectLiveImageRefs(
+ const { images } = collectLiveAssetRefs(
projectDocument({ widgetInstances: galleryInstance(['recent-a.png', 'recent-b.png']) })
);
- expect(collected.has('recent-a.png')).toBe(false);
+ expect(images.has('recent-a.png')).toBe(false);
});
it('finds references nested through arrays and mask bitmaps', () => {
- const collected = collectLiveImageRefs(
+ const { images } = collectLiveAssetRefs(
projectDocument({
canvas: {
document: {
@@ -96,37 +99,114 @@ describe('collectLiveImageRefs', () => {
})
);
- expect(collected).toEqual(new Set(['mask.png', 'reference.png', 'graph-image.png', 'upscale-input.png']));
+ expect(images).toEqual(new Set(['mask.png', 'reference.png', 'graph-image.png', 'upscale-input.png']));
});
it('ignores empty names and non-string values', () => {
- expect(collectLiveImageRefs({ canvas: { imageName: '' }, settings: { image_name: 7 } })).toEqual(new Set());
+ const refs = collectLiveAssetRefs({ canvas: { imageName: '' }, settings: { image_name: 7, video_name: null } });
+
+ expect(refs.images).toEqual(new Set());
+ expect(refs.videos).toEqual(new Set());
+ });
+
+ /**
+ * `VideoField { video_name }` reaches `projectGraph` through an imported
+ * workflow. It is a separate namespace from images and must not be conflated.
+ */
+ it('collects a graph node video as a video, never as an image', () => {
+ const refs = collectLiveAssetRefs(
+ projectDocument({
+ projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.mp4' } } }, id: 'extract-1' }] },
+ })
+ );
+
+ expect(refs.videos).toEqual(new Set(['clip.mp4']));
+ expect(refs.images.has('clip.mp4')).toBe(false);
+ });
+
+ it('returns both sets for a document carrying both kinds', () => {
+ const refs = collectLiveAssetRefs(
+ projectDocument({
+ projectGraph: {
+ nodes: [
+ { data: { inputs: { image: { image_name: 'frame.png' }, video: { video_name: 'clip.mp4' } } }, id: 'n' },
+ ],
+ },
+ })
+ );
+
+ expect(refs.images).toEqual(new Set(['live-image.png', 'frame.png', 'upscale-input.png']));
+ expect(refs.videos).toEqual(new Set(['clip.mp4']));
+ });
+
+ /**
+ * The gallery selection is a pointer into per-install gallery content, not
+ * something the document renders, so neither kind is bundled. The second
+ * assertion is the regression guard: the exclusion is by key, so it survives
+ * `GalleryItem` spelling its name field the same way the canvas does.
+ */
+ it('excludes the gallery selection, of either kind', () => {
+ const refs = collectLiveAssetRefs(
+ projectDocument({
+ widgetInstances: {
+ 'gallery-1': {
+ state: {
+ values: {
+ selectedImage: { fullUrl: '', kind: 'video', name: 'selected.mp4' },
+ selectedImageName: 'video:selected.mp4',
+ selectedImageNames: ['video:selected.mp4'],
+ },
+ },
+ typeId: 'gallery',
+ },
+ },
+ })
+ );
+
+ expect(refs.videos).toEqual(new Set());
+ expect(refs.images.has('selected.mp4')).toBe(false);
+ });
+
+ it('keeps excluding the gallery selection even if it starts spelling its name `imageName`', () => {
+ const { images } = collectLiveAssetRefs(
+ projectDocument({
+ widgetInstances: {
+ 'gallery-1': {
+ state: { values: { selectedImage: { imageName: 'selected.png', kind: 'image' } } },
+ typeId: 'gallery',
+ },
+ },
+ })
+ );
+
+ expect(images.has('selected.png')).toBe(false);
});
});
-describe('remapImageRefs', () => {
- it('returns the document unchanged for an empty mapping', () => {
+describe('remapAssetRefs', () => {
+ it('returns the document unchanged for empty mappings', () => {
const document = projectDocument();
- expect(remapImageRefs(document, new Map())).toBe(document);
+ expect(remapAssetRefs(document, noMappings)).toBe(document);
});
it('rewrites live references', () => {
- const remapped = remapImageRefs(projectDocument(), new Map([['live-image.png', 'uploaded-1.png']])) as {
- canvas: { document: { layers: { source: { image: { imageName: string } } }[] } };
- };
+ const remapped = remapAssetRefs(projectDocument(), {
+ ...noMappings,
+ images: new Map([['live-image.png', 'uploaded-1.png']]),
+ }) as { canvas: { document: { layers: { source: { image: { imageName: string } } }[] } } };
expect(remapped.canvas.document.layers[0]!.source.image.imageName).toBe('uploaded-1.png');
});
it('rewrites history references too, so nothing keeps pointing at the pre-import name', () => {
- const remapped = remapImageRefs(
- projectDocument(),
- new Map([
+ const remapped = remapAssetRefs(projectDocument(), {
+ ...noMappings,
+ images: new Map([
['queue-image.png', 'uploaded-queue.png'],
['snapshot-image.png', 'uploaded-snapshot.png'],
- ])
- ) as {
+ ]),
+ }) as {
canvas: { snapshots: { document: { layers: { source: { image: { imageName: string } } }[] } }[] };
queue: {
items: { snapshot: { canvas: { document: { layers: { source: { image: { imageName: string } } }[] } } } }[];
@@ -140,18 +220,50 @@ describe('remapImageRefs', () => {
});
it('rewrites the backend spelling of the key as well', () => {
- const remapped = remapImageRefs(projectDocument(), new Map([['graph-image.png', 'uploaded-graph.png']])) as {
- projectGraph: { nodes: { data: { inputs: { image: { image_name: string } } } }[] };
- };
+ const remapped = remapAssetRefs(projectDocument(), {
+ ...noMappings,
+ images: new Map([['graph-image.png', 'uploaded-graph.png']]),
+ }) as { projectGraph: { nodes: { data: { inputs: { image: { image_name: string } } } }[] } };
expect(remapped.projectGraph.nodes[0]!.data.inputs.image.image_name).toBe('uploaded-graph.png');
});
- it('leaves names absent from the mapping alone', () => {
- const remapped = remapImageRefs(projectDocument(), new Map([['not-present.png', 'other.png']])) as {
+ it('rewrites a video through the video mapping', () => {
+ const document = projectDocument({
+ projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.mp4' } } }, id: 'n' }] },
+ });
+ const remapped = remapAssetRefs(document, {
+ ...noMappings,
+ videos: new Map([['clip.mp4', 'server-clip.mp4']]),
+ }) as { projectGraph: { nodes: { data: { inputs: { video: { video_name: string } } } }[] } };
+
+ expect(remapped.projectGraph.nodes[0]!.data.inputs.video.video_name).toBe('server-clip.mp4');
+ });
+
+ /** The namespaces are separate, so a shared name must not cross over. */
+ it('never rewrites an image through the video mapping, or the reverse', () => {
+ const document = projectDocument({
+ canvas: { document: { layers: [imageLayer('l', 'shared')] } },
+ projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'shared' } } }, id: 'n' }] },
+ });
+ const remapped = remapAssetRefs(document, {
+ images: new Map([['shared', 'image-side']]),
+ videos: new Map([['shared', 'video-side']]),
+ }) as {
canvas: { document: { layers: { source: { image: { imageName: string } } }[] } };
+ projectGraph: { nodes: { data: { inputs: { video: { video_name: string } } } }[] };
};
+ expect(remapped.canvas.document.layers[0]!.source.image.imageName).toBe('image-side');
+ expect(remapped.projectGraph.nodes[0]!.data.inputs.video.video_name).toBe('video-side');
+ });
+
+ it('leaves names absent from the mapping alone', () => {
+ const remapped = remapAssetRefs(projectDocument(), {
+ ...noMappings,
+ images: new Map([['not-present.png', 'other.png']]),
+ }) as { canvas: { document: { layers: { source: { image: { imageName: string } } }[] } } };
+
expect(remapped.canvas.document.layers[0]!.source.image.imageName).toBe('live-image.png');
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
index 5e488b89e7..22ac148273 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
@@ -1,5 +1,5 @@
/**
- * Which images a project document points at, and how to rewrite those pointers.
+ * Which assets a project document points at, and how to rewrite those pointers.
*
* The document stores pixels the way `canvas-engine/contracts.ts` describes:
* by name, never by URL or inline data. That is what makes the document small
@@ -7,19 +7,29 @@
* another install — the names resolve to nothing there. Bundling the bytes into
* an `.invk` archive means first knowing which names the document actually uses.
*
+ * ### Two kinds, kept apart
+ *
+ * Images and videos live in separate backend namespaces, with separate tables,
+ * separate fetch and upload routes, and no shared name space. A document can
+ * carry both — `video_name` reaches `projectGraph` through an imported workflow
+ * whose node value was authored elsewhere (`VideoField` in the backend's
+ * `fields.py`; webv2 cannot author one yet, but it round-trips one verbatim).
+ * So collection returns a set per kind and remapping takes a mapping per kind:
+ * an image and a video could in principle share a name, and a single flat map
+ * would let one rewrite the other.
+ *
* ### Collection is by key, not by path
*
- * Exactly two keys in the document hold an image name: `imageName` (the webv2
- * canvas and gallery contracts) and `image_name` (graph node values, which
- * mirror the backend's field naming). Collecting every string found at those two
- * keys is complete by construction — a new control-adapter kind, a new node
- * field, a widget nobody has written yet, all get picked up without touching
- * this file.
+ * Three keys in the document hold an asset name: `imageName` (the webv2 canvas
+ * contracts), `image_name` and `video_name` (graph node values, which mirror the
+ * backend's field naming). Collecting every string found at those keys is
+ * complete by construction — a new control-adapter kind, a new node field, a
+ * widget nobody has written yet, all get picked up without touching this file.
*
* The alternative, walking a hand-written list of paths, is what the legacy
* frontend does, and it is why its collector enumerates `ip_adapter` and
* `flux_redux` by name and silently drops the pixels of any adapter added since.
- * A false positive here costs nothing: a string that is not really an image name
+ * A false positive here costs nothing: a string that is not really an asset name
* fails to resolve on the server and is skipped.
*
* ### Collection skips history, remapping does not
@@ -28,31 +38,59 @@
* embeds a whole canvas snapshot, `canvas.snapshots` holds full document copies,
* and the gallery widget keeps up to sixty recent results. Bundling all of that
* turns a working project into a multi-gigabyte archive, so
- * {@link collectLiveImageRefs} walks only what the project needs in order to
+ * {@link collectLiveAssetRefs} walks only what the project needs in order to
* open correctly.
*
- * {@link remapImageRefs} walks everything, with no skips. The asymmetry is the
- * point: if a bundled image comes back from the server under a new name, every
+ * {@link remapAssetRefs} walks everything, with no skips. The asymmetry is the
+ * point: if a bundled asset comes back from the server under a new name, every
* reference to it has to follow — including the ones in history we chose not to
* bundle, which would otherwise point at the pre-import name forever.
*/
-/** Keys whose string values are image names. */
+/** Keys whose string values name an image. */
const IMAGE_NAME_KEYS = new Set(['imageName', 'image_name']);
+/** Keys whose string values name a video. */
+const VIDEO_NAME_KEYS = new Set(['video_name']);
+
/** Top-level document keys that are history rather than live content. */
export const PROJECT_HISTORY_ROOT_KEYS: ReadonlySet<string> = new Set(['events', 'graphHistory', 'queue']);
/** Keys that introduce history at any depth (`canvas.snapshots`, the gallery's recents). */
export const PROJECT_HISTORY_KEYS: ReadonlySet<string> = new Set(['recentImages', 'snapshot', 'snapshots']);
+/**
+ * The gallery widget's selection, which is a pointer into gallery content rather
+ * than anything the document renders. `selectedImage` holds a whole polymorphic
+ * `GalleryItem` (image or video), and the two name keys hold `"<kind>:<name>"`.
+ *
+ * These are skipped deliberately. The gallery is per-install content: a project
+ * that arrives on another machine should open with nothing selected, not drag a
+ * stranger's gallery in behind it.
+ *
+ * The skip is by key rather than incidental. `GalleryItem` happens to spell its
+ * name field `name`, which no collector key matches, so today these would be
+ * missed anyway — but that is an accident of naming, and renaming that field
+ * would otherwise change what a project file silently contains.
+ */
+export const GALLERY_SELECTION_KEYS: ReadonlySet<string> = new Set([
+ 'selectedImage',
+ 'selectedImageName',
+ 'selectedImageNames',
+]);
+
+export interface ProjectAssetRefs {
+ images: Set<string>;
+ videos: Set<string>;
+}
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
-const collectFrom = (node: unknown, names: Set<string>): void => {
+const collectFrom = (node: unknown, refs: ProjectAssetRefs): void => {
if (Array.isArray(node)) {
for (const item of node) {
- collectFrom(item, names);
+ collectFrom(item, refs);
}
return;
@@ -63,43 +101,55 @@ const collectFrom = (node: unknown, names: Set<string>): void => {
}
for (const [key, value] of Object.entries(node)) {
- if (PROJECT_HISTORY_KEYS.has(key)) {
+ if (PROJECT_HISTORY_KEYS.has(key) || GALLERY_SELECTION_KEYS.has(key)) {
continue;
}
- if (IMAGE_NAME_KEYS.has(key) && typeof value === 'string' && value !== '') {
- names.add(value);
- continue;
+ if (typeof value === 'string' && value !== '') {
+ if (IMAGE_NAME_KEYS.has(key)) {
+ refs.images.add(value);
+ continue;
+ }
+
+ if (VIDEO_NAME_KEYS.has(key)) {
+ refs.videos.add(value);
+ continue;
+ }
}
- collectFrom(value, names);
+ collectFrom(value, refs);
}
};
/**
- * Every image name the project needs in order to open: canvas layers and masks,
- * reference images, widget values, and graph node inputs. History is excluded —
- * see the module docblock.
+ * Every asset name the project needs in order to open: canvas layers and masks,
+ * reference images, widget values, and graph node inputs. History and gallery
+ * selections are excluded — see the module docblock.
*/
-export const collectLiveImageRefs = (projectDocument: Record<string, unknown>): Set<string> => {
- const names = new Set<string>();
+export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>): ProjectAssetRefs => {
+ const refs: ProjectAssetRefs = { images: new Set<string>(), videos: new Set<string>() };
for (const [key, value] of Object.entries(projectDocument)) {
if (PROJECT_HISTORY_ROOT_KEYS.has(key)) {
continue;
}
- collectFrom(value, names);
+ collectFrom(value, refs);
}
- return names;
+ return refs;
};
-const remapNode = (node: unknown, mapping: ReadonlyMap<string, string>): unknown => {
+export interface ProjectAssetMappings {
+ images: ReadonlyMap<string, string>;
+ videos: ReadonlyMap<string, string>;
+}
+
+const remapNode = (node: unknown, mappings: ProjectAssetMappings): unknown => {
if (Array.isArray(node)) {
let hasChanged = false;
const next = node.map((item) => {
- const mapped = remapNode(item, mapping);
+ const mapped = remapNode(item, mappings);
hasChanged ||= mapped !== item;
@@ -117,15 +167,19 @@ const remapNode = (node: unknown, mapping: ReadonlyMap<string, string>): unknown
const next: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node)) {
- if (IMAGE_NAME_KEYS.has(key) && typeof value === 'string') {
- const replacement = mapping.get(value);
+ if (typeof value === 'string') {
+ const mapping = IMAGE_NAME_KEYS.has(key) ? mappings.images : VIDEO_NAME_KEYS.has(key) ? mappings.videos : null;
- next[key] = replacement ?? value;
- hasChanged ||= replacement !== undefined && replacement !== value;
- continue;
+ if (mapping) {
+ const replacement = mapping.get(value);
+
+ next[key] = replacement ?? value;
+ hasChanged ||= replacement !== undefined && replacement !== value;
+ continue;
+ }
}
- const mapped = remapNode(value, mapping);
+ const mapped = remapNode(value, mappings);
next[key] = mapped;
hasChanged ||= mapped !== value;
@@ -135,15 +189,18 @@ const remapNode = (node: unknown, mapping: ReadonlyMap<string, string>): unknown
};
/**
- * Rewrite every image reference in the document through `mapping`. Names absent
- * from the mapping are left alone, and subtrees with nothing to rewrite keep
- * their identity, so an empty mapping returns the document unchanged.
+ * Rewrite every asset reference in the document through the mapping for its
+ * kind. Names absent from their mapping are left alone, and subtrees with
+ * nothing to rewrite keep their identity, so empty mappings return the document
+ * unchanged.
*/
-export const remapImageRefs = (
+export const remapAssetRefs = (
projectDocument: Record<string, unknown>,
- mapping: ReadonlyMap<string, string>
+ mappings: ProjectAssetMappings
): Record<string, unknown> =>
- mapping.size === 0 ? projectDocument : (remapNode(projectDocument, mapping) as Record<string, unknown>);
+ mappings.images.size === 0 && mappings.videos.size === 0
+ ? projectDocument
+ : (remapNode(projectDocument, mappings) as Record<string, unknown>);
const readGalleryRecentImageName = (projectDocument: Record<string, unknown>): string | null => {
const instances = projectDocument.widgetInstances;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 9b96a56294..6edf216cf9 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -25,16 +25,21 @@ const transport = vi.hoisted(() => ({
coverExtensionForMime: () => 'webp',
fetchImageBytes: vi.fn((imageName: string) => Promise.resolve(new TextEncoder().encode(`bytes:${imageName}`))),
fetchImageThumbnail: vi.fn(() => Promise.resolve(null)),
+ fetchVideoBytes: vi.fn((videoName: string) => Promise.resolve(new TextEncoder().encode(`bytes:${videoName}`))),
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',
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}` })
+ ),
}));
vi.mock('./api', () => api);
vi.mock('@platform/browser/downloadBlob', () => downloads);
-vi.mock('./invk/imageTransport', () => transport);
+vi.mock('./invk/assetTransport', () => transport);
let projectFile: typeof projectFileModule;
let persistence: typeof persistenceModule;
@@ -93,6 +98,30 @@ describe('exportOpenProject', () => {
expect(downloads.downloadBlob).toHaveBeenCalledTimes(1);
expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('My project.invk');
});
+
+ /**
+ * The transport is mocked by module path, and every assertion below about what
+ * did *not* reach the server is vacuous if that path stops resolving. This one
+ * fails loudly instead: a document with a known image reference must reach the
+ * mock on the way out.
+ */
+ it('reaches the server through the mocked transport', async () => {
+ api.getProject.mockResolvedValue({
+ data: {
+ canvas: { document: { layers: [{ id: 'l', source: { image: { imageName: 'pinned.png' }, type: 'image' } }] } },
+ id: 'p1',
+ layout: {},
+ name: 'Pinned',
+ },
+ name: 'Pinned',
+ project_id: 'p1',
+ revision: 1,
+ });
+
+ await projectFile.exportLibraryProject('p1');
+
+ expect(transport.fetchImageBytes).toHaveBeenCalledWith('pinned.png', expect.anything());
+ });
});
describe('exportLibraryProject', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 6ec0a56102..b40fa44ddf 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -14,7 +14,7 @@ import { recordProjectCover } from './covers';
import { createProjectId } from './ids';
import { INVK_EXTENSION, InvkFormatError } from './invk/format';
import { upsertProjectSummary } from './library';
-import { remapImageRefs } from './projectAssets';
+import { remapAssetRefs } from './projectAssets';
/**
* Export and import a project as an `.invk` archive.
@@ -106,8 +106,8 @@ export const importProjectFile = async (
assertAccountScopeCurrent(owner);
- const { restoreArchiveImages } = await import('./invk/importProject');
- const restored = await restoreArchiveImages(contents, { signal: owner.signal });
+ const { restoreArchiveAssets } = await import('./invk/importProject');
+ const restored = await restoreArchiveAssets(contents, { signal: owner.signal });
assertAccountScopeCurrent(owner);
@@ -116,7 +116,7 @@ export const importProjectFile = async (
typeof contents.projectDocument.name === 'string' && contents.projectDocument.name.trim()
? contents.projectDocument.name.trim()
: 'Imported project';
- const document = { ...remapImageRefs(contents.projectDocument, restored.mapping), id, name };
+ const document = { ...remapAssetRefs(contents.projectDocument, restored.mappings), id, name };
// Full validation rehydrates the document through the Workbench reducer, so
// it is loaded here rather than imported: the Launchpad should not carry the
// editor's aggregate state just to offer an Import button.