Skip to content

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

fix(webv2): keep cancelled exports and gallery selections out of .invk

joshistoastee62d748eeab
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
index 5e8ecbdc08..b99b93a977 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
@@ -1,5 +1,5 @@
import { mapWithConcurrency } from '@platform/core/concurrency';
-import { apiFetch, apiFetchJson, apiFetchRaw } from '@platform/transport/http';
+import { apiFetch, apiFetchJson, apiFetchRaw, HttpRequestIdentityExpiredError } from '@platform/transport/http';
/**
* The asset half of a project file: pulling referenced bytes off the server on
@@ -33,6 +33,20 @@ import { apiFetch, apiFetchJson, apiFetchRaw } from '@platform/transport/http';
const IMAGES_BASE = '/api/v1/images';
const VIDEOS_BASE = '/api/v1/videos';
+/**
+ * Whether a failed request means "the work this belonged to is over" rather
+ * than "this one asset could not be served".
+ *
+ * Export treats an unservable asset as a skip, which is right — half a
+ * project's pixels beats none. But an aborted signal makes *every* asset
+ * unservable, and a skip-everything export writes an archive full of nothing
+ * and hands it to the browser as though it had succeeded. The two have to be
+ * told apart at the point the request fails, because by the time the archive is
+ * packed they look identical.
+ */
+export const isRequestCancellation = (error: unknown): boolean =>
+ error instanceof HttpRequestIdentityExpiredError || (error instanceof Error && error.name === 'AbortError');
+
/**
* Names per existence request. The endpoint answers any length, but a URL-free
* POST body of ten thousand names is still a request worth splitting so that one
@@ -219,21 +233,40 @@ const EXTENSION_BY_MIME: Readonly<Record<string, string>> = {
export const coverExtensionForMime = (contentType: string): string =>
EXTENSION_BY_MIME[contentType.split(';')[0]!.trim().toLowerCase()] ?? 'png';
-const MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
+const IMAGE_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
+ png: 'image/png',
+ webp: 'image/webp',
+};
+
+/**
+ * Only MP4 survives the backend's upload path — it probes the container and
+ * 415s anything else (`_is_mp4_file` in `videos.py`) — so this is a table of
+ * what a bundled entry might be *named*, not of what will be accepted.
+ */
+const VIDEO_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
+ m4v: 'video/mp4',
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. 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.
+ * Best guess at a bundled entry's MIME type, from its name and the folder it
+ * came out of. Only ever a hint for the upload's multipart part.
+ *
+ * The fallback is per kind because the receiving endpoint checks it. A video
+ * whose extension is not in the table falling back to `image/png` would be
+ * announced to `/videos/upload` as an image and refused before its bytes were
+ * ever read — the entry's folder already established what it is, so the guess
+ * should never contradict it.
*/
-export const mimeForEntryName = (entryName: string): string =>
- MIME_BY_EXTENSION[entryName.split('.').pop()?.toLowerCase() ?? ''] ?? 'image/png';
+export const mimeForEntryName = (entryName: string, kind: 'image' | 'video' = 'image'): string => {
+ const extension = entryName.split('.').pop()?.toLowerCase() ?? '';
+
+ return kind === 'video'
+ ? (VIDEO_MIME_BY_EXTENSION[extension] ?? 'video/mp4')
+ : (IMAGE_MIME_BY_EXTENSION[extension] ?? '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 5bea53fdbb..9079beceea 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts
@@ -49,6 +49,31 @@ describe('planInvkExport', () => {
expect(planInvkExport(planInput)).toEqual(planInvkExport(planInput));
});
+ /**
+ * The selection was already excluded from bundling; this is the other half —
+ * it must not reach the archive at all, or the imported project opens
+ * pointing at images the receiving server has never had.
+ */
+ it('writes a document carrying no gallery selection', () => {
+ const plan = planInvkExport({
+ ...planInput,
+ projectDocument: {
+ ...projectDocument(),
+ widgetInstances: {
+ 'gallery-1': {
+ state: { values: { selectedImageName: 'image:selected.png', selectedImageNames: ['image:selected.png'] } },
+ typeId: 'gallery',
+ },
+ 'preview-1': { state: { values: { compareImage: imageRef('compare.png') } }, typeId: 'preview' },
+ },
+ },
+ });
+
+ expect(plan.documentJson).not.toContain('selected.png');
+ expect(plan.documentJson).not.toContain('compare.png');
+ expect(plan.imageNames).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' } });
@@ -185,6 +210,59 @@ describe('executeInvkExport', () => {
expect(result).toEqual({ bundledImageCount: 2, bundledVideoCount: 0, missingAssetNames: ['clip.mp4'] });
});
+ /**
+ * A cancelled export must not look like a successful one. Every fetch fails
+ * when the signal aborts, so treating those as "the server would not serve
+ * it" would pack an archive holding nothing and download it.
+ */
+ it('rejects rather than downloading an archive when the fetches are aborted', async () => {
+ const download = vi.fn();
+ const abort = () => Promise.reject(new DOMException('The operation was aborted.', 'AbortError'));
+
+ await expect(
+ executeInvkExport(planInvkExport(planInput), {
+ download,
+ fetchImageBytes: abort,
+ fetchImageThumbnail: abort,
+ })
+ ).rejects.toMatchObject({ name: 'AbortError' });
+
+ expect(download).not.toHaveBeenCalled();
+ });
+
+ it('rejects when the signal aborts after the last fetch but before packing', async () => {
+ const download = vi.fn();
+ const controller = new AbortController();
+
+ await expect(
+ executeInvkExport(planInvkExport(planInput), {
+ download,
+ fetchImageBytes: (imageName) => {
+ controller.abort();
+
+ return Promise.resolve(bytesFor(imageName));
+ },
+ fetchImageThumbnail: () => Promise.resolve(null),
+ signal: controller.signal,
+ })
+ ).rejects.toMatchObject({ name: 'AbortError' });
+
+ expect(download).not.toHaveBeenCalled();
+ });
+
+ it('still treats an unservable asset as a skip, not a cancellation', async () => {
+ const download = vi.fn();
+ const result = await executeInvkExport(planInvkExport(planInput), {
+ download,
+ fetchImageBytes: (imageName) =>
+ imageName === 'live-a.png' ? Promise.reject(new Error('500')) : Promise.resolve(bytesFor(imageName)),
+ fetchImageThumbnail: () => Promise.resolve(null),
+ });
+
+ expect(result.missingAssetNames).toEqual(['live-a.png']);
+ expect(download).toHaveBeenCalledTimes(1);
+ });
+
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 c496564996..c5557d653d 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
@@ -1,11 +1,17 @@
import { mapWithConcurrency } from '@platform/core/concurrency';
-import { collectLiveAssetRefs, selectCoverImageName } from '@workbench/projects/projectAssets';
+import { collectLiveAssetRefs, selectCoverImageName, stripGallerySelection } from '@workbench/projects/projectAssets';
import type { InvkArchiveEntry } from './archive';
import type { FetchedThumbnail } from './assetTransport';
import { binaryEntry, textEntry, writeArchive } from './archive';
-import { coverExtensionForMime, fetchImageBytes, fetchImageThumbnail, fetchVideoBytes } from './assetTransport';
+import {
+ coverExtensionForMime,
+ fetchImageBytes,
+ fetchImageThumbnail,
+ fetchVideoBytes,
+ isRequestCancellation,
+} from './assetTransport';
import { INVK_DOCUMENT_ENTRY, INVK_IMAGES_PREFIX, INVK_MANIFEST_ENTRY, INVK_VIDEOS_PREFIX } from './format';
import { buildInvkManifest, toInvkFileName } from './manifest';
@@ -25,6 +31,12 @@ import { buildInvkManifest, toInvkFileName } from './manifest';
* fatal. Half a project's pixels beats none, and the reference survives in the
* document either way — importing onto the machine that still has the image
* resolves it.
+ *
+ * Cancellation is the one failure that is *not* a skip. An aborted signal makes
+ * every asset unservable at once, and skipping all of them would pack an archive
+ * of nothing and hand it to the browser as a finished download. So a cancelled
+ * request propagates, and the signal is checked once more before the archive is
+ * written — nothing reaches the disk after the export stopped being wanted.
*/
/** Simultaneous asset fetches. Matches the previous frontend's limit. */
@@ -52,13 +64,18 @@ export const planInvkExport = (input: {
}): InvkExportPlan => {
const sourceProjectId = typeof input.projectDocument.id === 'string' ? input.projectDocument.id : undefined;
- const refs = collectLiveAssetRefs(input.projectDocument);
+ // 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.
+ const projectDocument = stripGallerySelection(input.projectDocument);
+ const refs = collectLiveAssetRefs(projectDocument);
return {
- coverImageName: selectCoverImageName(input.projectDocument),
+ 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(input.projectDocument),
+ documentJson: JSON.stringify(projectDocument),
fileName: toInvkFileName(input.name),
imageNames: [...refs.images].sort(),
manifestInput: {
@@ -105,8 +122,21 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
let bundledVideoCount = 0;
let completed = 0;
+ /** Unservable is `null`; cancelled rethrows. */
+ const skipUnservable = async <T>(read: () => Promise<T | null>): Promise<T | null> => {
+ try {
+ return await read();
+ } catch (error) {
+ if (isRequestCancellation(error)) {
+ throw error;
+ }
+
+ return null;
+ }
+ };
+
const cover =
- plan.coverImageName === null ? null : await readThumbnail(plan.coverImageName, deps.signal).catch(() => null);
+ 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
@@ -117,8 +147,8 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
];
await mapWithConcurrency(assets, ASSET_FETCH_CONCURRENCY, async ({ kind, name }) => {
- const bytes = await (kind === 'image' ? readImage(name, deps.signal) : readVideo(name, deps.signal)).catch(
- () => null
+ const bytes = await skipUnservable(() =>
+ kind === 'image' ? readImage(name, deps.signal) : readVideo(name, deps.signal)
);
completed += 1;
@@ -141,6 +171,11 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
entries.set(`${INVK_VIDEOS_PREFIX}${name}`, binaryEntry(bytes));
});
+ // The last fetch may have completed just as the export stopped being wanted;
+ // no fetch would have rejected in that window, and packing is the expensive
+ // step that precedes handing a file to the browser.
+ deps.signal?.throwIfAborted();
+
deps.onProgress?.({ completed: assets.length, phase: 'packing', total: assets.length });
const manifest = buildInvkManifest({
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
index f97eb1acf9..02b52a925a 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { collectLiveAssetRefs, remapAssetRefs, selectCoverImageName } from './projectAssets';
+import { collectLiveAssetRefs, remapAssetRefs, selectCoverImageName, stripGallerySelection } from './projectAssets';
/**
* The walker's contract, stated as documents rather than as paths: what an
@@ -202,6 +202,59 @@ describe('collectLiveAssetRefs', () => {
});
});
+/**
+ * Not bundling the selection is only half of leaving it behind. A reference
+ * that is skipped by the collector but left in the document still travels —
+ * broken, and invisible to the restore pass that would otherwise report it as
+ * dangling.
+ */
+describe('stripGallerySelection', () => {
+ it('drops every selection key at any depth', () => {
+ const stripped = stripGallerySelection({
+ widgetInstances: {
+ 'gallery-1': {
+ state: {
+ values: {
+ recentImages: [{ ...imageRef('recent.png'), imageUrl: '' }],
+ selectedImage: { imageName: 'selected.png', kind: 'image' },
+ selectedImageName: 'image:selected.png',
+ selectedImageNames: ['image:selected.png'],
+ },
+ },
+ typeId: 'gallery',
+ },
+ 'preview-1': {
+ state: { values: { compareImage: { ...imageRef('compare.png'), imageUrl: '' } } },
+ typeId: 'preview',
+ },
+ },
+ });
+
+ expect(JSON.stringify(stripped)).not.toContain('selected.png');
+ expect(JSON.stringify(stripped)).not.toContain('compare.png');
+ // History is not selection: those references travel deliberately.
+ expect(JSON.stringify(stripped)).toContain('recent.png');
+ });
+
+ it('leaves a document with no selection identical', () => {
+ const document = { canvas: { document: { layers: [imageLayer('l1', 'a.png')] } }, id: 'p1' };
+
+ expect(stripGallerySelection(document)).toBe(document);
+ });
+
+ it('keeps the surrounding widget state intact', () => {
+ const stripped = stripGallerySelection({
+ widgetInstances: {
+ 'gallery-1': { state: { values: { boardId: 'b1', selectedImageName: 'image:x.png' } }, typeId: 'gallery' },
+ },
+ });
+
+ expect(stripped).toEqual({
+ widgetInstances: { 'gallery-1': { state: { values: { boardId: 'b1' } }, typeId: 'gallery' } },
+ });
+ });
+});
+
describe('remapAssetRefs', () => {
it('returns the document unchanged for empty mappings', () => {
const document = projectDocument();
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
index e7d12b8514..9325e9bd40 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
@@ -69,6 +69,13 @@ export const PROJECT_HISTORY_KEYS: ReadonlySet<string> = new Set(['recentImages'
* that arrives on another machine should open with nothing selected, not drag a
* stranger's gallery in behind it.
*
+ * Skipping them during collection is only half of that. A reference that is not
+ * bundled and not stripped still travels — it simply travels broken, pointing at
+ * an image the receiving server has never had, and import cannot even report it
+ * as dangling because the same skip hides it from the restore pass.
+ * {@link stripGallerySelection} is the other half, and the export planner
+ * applies it before the document is serialized.
+ *
* The two halves got here differently, which is why the skip is by key rather
* than left to chance. `selectedImage` and the name keys were already missed,
* but only because `GalleryItem` spells its name field `name` and no collector
@@ -145,6 +152,55 @@ export const collectLiveAssetRefs = (projectDocument: Record<string, unknown>):
return refs;
};
+const stripNode = (node: unknown): unknown => {
+ if (Array.isArray(node)) {
+ let hasChanged = false;
+ const next = node.map((item) => {
+ const stripped = stripNode(item);
+
+ hasChanged ||= stripped !== item;
+
+ return stripped;
+ });
+
+ return hasChanged ? next : node;
+ }
+
+ if (!isRecord(node)) {
+ return node;
+ }
+
+ let hasChanged = false;
+ const next: Record<string, unknown> = {};
+
+ for (const [key, value] of Object.entries(node)) {
+ if (GALLERY_SELECTION_KEYS.has(key)) {
+ hasChanged = true;
+ continue;
+ }
+
+ const stripped = stripNode(value);
+
+ next[key] = stripped;
+ hasChanged ||= stripped !== value;
+ }
+
+ return hasChanged ? next : node;
+};
+
+/**
+ * Drop the gallery's selection keys at every depth, so an exported project
+ * opens with nothing selected rather than with pointers into the exporting
+ * install's gallery.
+ *
+ * Every reader of these values already tolerates their absence — selection is
+ * parsed with `typeof`/`Array.isArray` guards and falls back to nothing — so
+ * removing the key is the same as clearing it, without inventing a shape.
+ * Subtrees with nothing to drop keep their identity.
+ */
+export const stripGallerySelection = (projectDocument: Record<string, unknown>): Record<string, unknown> =>
+ stripNode(projectDocument) as Record<string, unknown>;
+
export interface ProjectAssetMappings {
images: ReadonlyMap<string, string>;
videos: ReadonlyMap<string, string>;