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.

perf(webv2): bound what a project transfer holds and how long it holds it

Josh Corbett0f69b96364ea
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 269516d2e9..3eb0b8b89e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -420,6 +420,7 @@
"file": {
"bundlingProgress": "Bundling {{completed}} of {{total}} assets…",
"damaged": "This project file is damaged and cannot be opened.",
+ "damagedProject": "This project cannot be read and could not be copied.",
"legacyCanvasProject": "This is a canvas project from an earlier version of Invoke, which cannot be opened here.",
"missingBoardItems_one": "1 board item could not be included.",
"missingBoardItems_other": "{{count}} board items could not be included.",
@@ -429,6 +430,7 @@
"packing": "Packing the archive…",
"restoringProgress": "Restoring {{completed}} of {{total}} assets…",
"tooLarge": "This project file is too large to open.",
+ "tooLargeToWrite": "This project is too large to package into a project file.",
"unstarredItems_one": "1 item could not be re-starred.",
"unstarredItems_other": "{{count}} items could not be re-starred.",
"unsupportedVersion": "This project file was written by a newer version of Invoke."
diff --git a/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts b/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts
index 6b56fe36ac..cc47b58839 100644
--- a/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts
+++ b/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts
@@ -71,4 +71,51 @@ describe('mapWithConcurrency', () => {
mapWithConcurrency([1, 2], 2, (item) => (item === 2 ? Promise.reject(new Error('nope')) : Promise.resolve(item)))
).rejects.toThrow('nope');
});
+
+ it('starts no further work after a mapper rejects', async () => {
+ // `Promise.all` stops *waiting* on a rejection; it does not stop the workers. Without an
+ // explicit stop, an export that has already failed goes on to issue one request per asset it
+ // had not reached yet.
+ const started: number[] = [];
+
+ await expect(
+ mapWithConcurrency([1, 2, 3, 4, 5, 6], 1, (item) => {
+ started.push(item);
+
+ return item === 2 ? Promise.reject(new Error('nope')) : Promise.resolve(item);
+ })
+ ).rejects.toThrow('nope');
+
+ expect(started).toEqual([1, 2]);
+ });
+
+ it('stops when its signal aborts', async () => {
+ const controller = new AbortController();
+ const started: number[] = [];
+
+ const results = await mapWithConcurrency(
+ [1, 2, 3, 4],
+ 1,
+ (item) => {
+ started.push(item);
+ if (item === 2) {
+ controller.abort();
+ }
+
+ return Promise.resolve(item);
+ },
+ { signal: controller.signal }
+ );
+
+ expect(started).toEqual([1, 2]);
+ expect(results[0]).toBe(1);
+ });
+
+ it('still runs the list when told a concurrency of zero', async () => {
+ // Spawning `min(0, length)` workers resolved immediately with an empty array, which reads as
+ // "nothing to do" rather than "nothing was done".
+ const results = await mapWithConcurrency([1, 2, 3], 0, (item) => Promise.resolve(item * 2));
+
+ expect(results).toEqual([2, 4, 6]);
+ });
});
diff --git a/invokeai/frontend/webv2/src/platform/core/concurrency.ts b/invokeai/frontend/webv2/src/platform/core/concurrency.ts
index 335fe2ef27..f74d852f57 100644
--- a/invokeai/frontend/webv2/src/platform/core/concurrency.ts
+++ b/invokeai/frontend/webv2/src/platform/core/concurrency.ts
@@ -13,26 +13,46 @@
*
* A rejecting mapper rejects the whole call, exactly as `Promise.all` would;
* callers that want partial success catch inside the mapper and return a
- * result union instead.
+ * result union instead. The first rejection also *stops* the remaining work:
+ * `Promise.all` only stops waiting, so without this a failed export would go on
+ * to issue one request per asset it had not reached yet — hundreds of them, for
+ * an operation that has already failed. Results for items never started are
+ * left as holes, which callers see as `undefined` and never reach, because the
+ * rejection is what they get instead.
*/
export const mapWithConcurrency = async <T, R>(
items: readonly T[],
concurrency: number,
- mapper: (item: T, index: number) => Promise<R>
+ mapper: (item: T, index: number) => Promise<R>,
+ options: { signal?: AbortSignal } = {}
): Promise<R[]> => {
const results: R[] = [];
let nextIndex = 0;
+ let stopped = false;
const worker = async (): Promise<void> => {
while (nextIndex < items.length) {
+ if (stopped || options.signal?.aborted) {
+ return;
+ }
+
const index = nextIndex;
nextIndex += 1;
- results[index] = await mapper(items[index]!, index);
+ try {
+ results[index] = await mapper(items[index]!, index);
+ } catch (error) {
+ stopped = true;
+ throw error;
+ }
}
};
- await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
+ // At least one worker: a concurrency of zero would otherwise spawn none, resolve immediately and
+ // hand back an empty array as though the list had been processed.
+ const workerCount = Math.max(1, Math.min(concurrency, items.length));
+
+ await Promise.all(Array.from({ length: items.length === 0 ? 0 : workerCount }, worker));
return results;
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
index 54f514fdf4..2535a0a7b8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts
@@ -50,6 +50,15 @@ import { InvkFormatError } from './format';
* images before the bulk endpoint existed.
*/
+/**
+ * Simultaneous requests any one transfer may have in flight, in either direction.
+ *
+ * Matches the previous frontend's limit. One number rather than four identical ones, because it is
+ * one budget: the point is to be kind to a backend that is very likely also generating, and a limit
+ * per phase would multiply exactly what it exists to bound.
+ */
+export const INVK_TRANSFER_CONCURRENCY = 5;
+
const BOARDS_BASE = '/api/v1/boards';
const IMAGES_BASE = '/api/v1/images';
const VIDEOS_BASE = '/api/v1/videos';
@@ -78,8 +87,27 @@ export const isRequestCancellation = (error: unknown): boolean =>
*/
const EXISTENCE_BATCH_SIZE = 500;
+/** Simultaneous existence batches, matching the transfer limit. */
+const EXISTENCE_BATCH_CONCURRENCY = INVK_TRANSFER_CONCURRENCY;
+
/** Simultaneous per-name video lookups, matching the image fetch limit. */
-const VIDEO_EXISTENCE_CONCURRENCY = 5;
+const VIDEO_EXISTENCE_CONCURRENCY = INVK_TRANSFER_CONCURRENCY;
+
+/**
+ * Let go of a response whose body this module is not going to read.
+ *
+ * `apiFetchRaw` hands back the response untouched, so a skipped asset or an existence probe leaves
+ * an unconsumed stream holding its connection until the collector gets to it. This module's whole
+ * argument is that it is bounded and kind to the backend; that has to include the requests it
+ * decides not to use.
+ */
+const discardBody = async (response: Response): Promise<void> => {
+ try {
+ await response.body?.cancel();
+ } catch {
+ // A body that cannot be cancelled is already finished with.
+ }
+};
export interface UploadedImage {
height: number;
@@ -305,22 +333,27 @@ export const findExistingImageNames = async (
imageNames: readonly string[],
signal?: AbortSignal
): Promise<Set<string>> => {
- const existing = new Set<string>();
+ const batches: string[][] = [];
for (let offset = 0; offset < imageNames.length; offset += EXISTENCE_BATCH_SIZE) {
- const batch = imageNames.slice(offset, offset + EXISTENCE_BATCH_SIZE);
- const found = await apiFetchJson<ImageDTOSubset[]>(`${IMAGES_BASE}/images_by_names`, {
- body: JSON.stringify({ image_names: batch }),
- method: 'POST',
- signal,
- });
-
- for (const dto of found) {
- existing.add(dto.image_name);
- }
+ batches.push(imageNames.slice(offset, offset + EXISTENCE_BATCH_SIZE));
}
- return existing;
+ // Through the same pool as everything else. Splitting the names was meant to stop one slow
+ // lookup stalling the check, which a sequential loop gives straight back.
+ const found = await mapWithConcurrency(
+ batches,
+ EXISTENCE_BATCH_CONCURRENCY,
+ (batch) =>
+ apiFetchJson<ImageDTOSubset[]>(`${IMAGES_BASE}/images_by_names`, {
+ body: JSON.stringify({ image_names: batch }),
+ method: 'POST',
+ signal,
+ }),
+ { signal }
+ );
+
+ return new Set(found.flat().map((dto) => dto.image_name));
};
/**
@@ -334,20 +367,29 @@ 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 });
+ const found = await mapWithConcurrency(
+ videoNames,
+ VIDEO_EXISTENCE_CONCURRENCY,
+ async (videoName) => {
+ const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}`, { signal });
+
+ if (response.ok) {
+ // The DTO is not wanted, only its existence — but an unread body holds its connection open
+ // until it is collected, and this runs once per referenced video.
+ await discardBody(response);
+ return videoName;
+ }
- if (response.ok) {
- return videoName;
- }
+ if (response.status === 403 || response.status === 404) {
+ await discardBody(response);
+ return null;
+ }
- if (response.status === 403 || response.status === 404) {
+ await assertOk(response);
return null;
- }
-
- await assertOk(response);
- return null;
- });
+ },
+ { signal }
+ );
return new Set(found.filter((videoName): videoName is string => videoName !== null));
};
@@ -366,6 +408,7 @@ const fetchImageBytesWithReader = async (
const response = await apiFetchRaw(`${IMAGES_BASE}/i/${encodeURIComponent(imageName)}/full`, { signal });
if (!response.ok) {
+ await discardBody(response);
return null;
}
@@ -384,6 +427,7 @@ const fetchVideoBytesWithReader = async (
const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}/full`, { signal });
if (!response.ok) {
+ await discardBody(response);
return null;
}
@@ -408,6 +452,7 @@ const fetchImageThumbnailWithReader = async (
const response = await apiFetchRaw(`${IMAGES_BASE}/i/${encodeURIComponent(imageName)}/thumbnail`, { signal });
if (!response.ok) {
+ await discardBody(response);
return null;
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
index a5dd8b6b83..6cdf1cb3a5 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
@@ -4,6 +4,7 @@ import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/
import { createDraftProject } from '@workbench/workbenchState';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as assetTransportModule from './assetTransport';
import type * as duplicateProjectModule from './duplicateProject';
/**
@@ -38,7 +39,13 @@ const transport = vi.hoisted(() => ({
}));
vi.mock('@workbench/projects/api', () => api);
-vi.mock('./assetTransport', () => transport);
+// Partial, so the module's constants and pure predicates stay real — a stub of
+// `isRequestCancellation` would let the tests agree with a duplication that mistook a
+// cancellation for a board's worth of individually failed copies.
+vi.mock('./assetTransport', async (importOriginal) => ({
+ ...(await importOriginal<typeof assetTransportModule>()),
+ ...transport,
+}));
let duplicateProject: typeof duplicateProjectModule;
let owner: AccountScope;
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
index d371cdc5a8..f99ea5d5ad 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
@@ -185,6 +185,11 @@ export const duplicateProjectRecord = async (
projectId: id,
},
{
+ // Both projects live on this server, so every document-only reference resolves here by
+ // definition — the check would ask the server whether it has media it just told us about.
+ // For videos that is one request per referenced video, against a certain answer.
+ findExistingImageNames: (names) => Promise.resolve(new Set(names)),
+ findExistingVideoNames: (names) => Promise.resolve(new Set(names)),
materializeBoardMedia: createCopyMediaMaterializer({
...(deps.copyImages === undefined ? {} : { copyImages: deps.copyImages }),
...(deps.copyVideos === undefined ? {} : { copyVideos: deps.copyVideos }),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
index 54a70b72d8..2a0bcf8b57 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts
@@ -7,7 +7,12 @@ import type { InvkBoardItem, InvkBoardSnapshot } from './board';
import type { InvkTransferItem, ProjectTransferIssues } from './transfer';
import { binaryEntry, INVK_MAX_ENTRIES, textEntry, writeArchive } from './archive';
-import { coverExtensionForMime, createAssetExportTransport, isRequestCancellation } from './assetTransport';
+import {
+ coverExtensionForMime,
+ createAssetExportTransport,
+ INVK_TRANSFER_CONCURRENCY,
+ isRequestCancellation,
+} from './assetTransport';
import { buildInvkBoardSnapshot } from './board';
import {
INVK_BOARD_ENTRY,
@@ -44,9 +49,6 @@ import { createTransferIssueLog, planMediaTransfer, toMediaRefs } from './transf
* written — nothing reaches the disk after the export stopped being wanted.
*/
-/** Simultaneous asset fetches. Matches the previous frontend's limit. */
-const ASSET_FETCH_CONCURRENCY = 5;
-
export interface InvkExportPlan {
/** The board's contents exactly as they will be written to `board.json`. */
boardSnapshot: InvkBoardSnapshot;
@@ -163,7 +165,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDe
// would not be if images and videos each got their own.
const assets = plan.transferItems;
- await mapWithConcurrency(assets, ASSET_FETCH_CONCURRENCY, async (item) => {
+ await mapWithConcurrency(assets, INVK_TRANSFER_CONCURRENCY, async (item) => {
const { kind, name } = item;
const bytes = await skipUnservable(() =>
kind === 'image' ? readImage(name, deps.signal) : readVideo(name, deps.signal)
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
index 849fff4a21..514109b29a 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts
@@ -11,7 +11,13 @@ import type {
import type { InvkMediaRef } from './transfer';
import { INVK_MAX_ARCHIVE_BYTES, readArchive, readEntryText } from './archive';
-import { isRequestCancellation, mimeForEntryName, uploadBoardImage, uploadBoardVideo } from './assetTransport';
+import {
+ INVK_TRANSFER_CONCURRENCY,
+ isRequestCancellation,
+ mimeForEntryName,
+ uploadBoardImage,
+ uploadBoardVideo,
+} from './assetTransport';
import { parseInvkBoardSnapshot } from './board';
import {
INVK_BOARD_ENTRY,
@@ -42,9 +48,6 @@ import { toMediaRefs } from './transfer';
* the one assigning the new project id.
*/
-/** Simultaneous uploads. Matches the previous frontend's limit. */
-const BOARD_UPLOAD_CONCURRENCY = 5;
-
export interface InvkArchiveContents {
/**
* What the project's board held, or `null` for an archive that names no board.
@@ -195,6 +198,10 @@ export interface ArchiveBoardUploadDeps {
* media can never reuse a name the destination already has. A descriptor the archive carries no
* bytes for is reported rather than skipped silently: the exporting server told us it was there,
* so its absence is a loss worth naming.
+ *
+ * Each entry is dropped from the archive as it lands. An `.invk` may be two gigabytes, and holding
+ * every entry until the import finishes means holding the whole archive *and* everything unpacked
+ * from it through the restore and the create that follows — for bytes the server already has.
*/
export const createArchiveMediaMaterializer = (
archive: Pick<InvkArchiveContents, 'images' | 'videos'>,
@@ -206,8 +213,9 @@ export const createArchiveMediaMaterializer = (
return async (items, boardId, onItemSettled) => {
const result: Awaited<ReturnType<MediaMaterializer>> = { failed: [], materialized: [] };
- await mapWithConcurrency(items, BOARD_UPLOAD_CONCURRENCY, async (item) => {
- const bytes = (item.kind === 'image' ? archive.images : archive.videos).get(item.name);
+ await mapWithConcurrency(items, INVK_TRANSFER_CONCURRENCY, async (item) => {
+ const entries = item.kind === 'image' ? archive.images : archive.videos;
+ const bytes = entries.get(item.name);
if (bytes === undefined) {
result.failed.push({ kind: item.kind, name: item.name, reason: 'missing-entry' });
@@ -229,6 +237,7 @@ export const createArchiveMediaMaterializer = (
: (await uploadVideo(bytes, item.name, options)).videoName;
result.materialized.push({ kind: item.kind, name, sourceName: item.name });
+ entries.delete(item.name);
} catch (error) {
// A cancelled signal or an expired account is not this item failing — it is every
// remaining item failing at once, which is an ended operation rather than a lossy one.
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 4260debaf9..ce3fb3c2be 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts
@@ -45,8 +45,14 @@ describe('parseInvkManifest', () => {
expectReason({ ...v2, version: 4 }, 'unsupported-version');
});
- it('rejects a manifest missing the v2 discriminator', () => {
- expectReason({ appVersion: '7.0', createdAt: '', name: 'x', version: 2 }, 'unsupported-version');
+ /**
+ * A version this app writes is a version it can read, so one that still fails to parse is a
+ * broken file — not a newer Invoke. Telling someone to upgrade over a truncated manifest sends
+ * them somewhere that cannot help.
+ */
+ it('reports a malformed manifest at a version it knows as damaged', () => {
+ expectReason({ appVersion: '7.0', createdAt: '', name: 'x', version: 2 }, 'damaged');
+ expectReason({ version: 1 }, 'damaged');
});
it('rejects junk as not a project', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts
index 333fe41ecd..3dbabf8769 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts
@@ -62,6 +62,9 @@ const zManifestV2 = z.object({
const zManifest = z.discriminatedUnion('version', [zManifestV1, zManifestV2]);
+/** Every version this app has ever written or can name. Anything else genuinely is from the future. */
+const KNOWN_VERSIONS: ReadonlySet<number> = new Set([1, 2]);
+
/** A manifest this app can read: the workbench project container. */
export type InvkManifest = z.infer<typeof zManifestV2>;
@@ -75,7 +78,14 @@ export const parseInvkManifest = (data: unknown): InvkManifest => {
if (!parsed.success) {
const version = (data as { version?: unknown } | null)?.version;
- throw new InvkFormatError(typeof version === 'number' ? 'unsupported-version' : 'not-a-project');
+ if (typeof version !== 'number') {
+ throw new InvkFormatError('not-a-project');
+ }
+
+ // A version this app has written is a version it can read, so a manifest that still fails to
+ // parse at one of them is damaged — a truncated name, a missing timestamp. Calling that
+ // "written by a newer version of Invoke" tells someone to go and upgrade over a broken file.
+ throw new InvkFormatError(KNOWN_VERSIONS.has(version) ? 'damaged' : 'unsupported-version');
}
if (parsed.data.version === 1) {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
index 6d2aef3f6f..fd50b4c400 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts
@@ -9,6 +9,7 @@ import {
deleteStagingBoard,
findExistingImageNames,
findExistingVideoNames,
+ INVK_TRANSFER_CONCURRENCY,
isRequestCancellation,
mimeForEntryName,
starImages,
@@ -52,9 +53,6 @@ import { buildMissingMediaName, createTransferIssueLog, toMediaKey } from './tra
* a missing layer, exactly as a dangling v2 reference already does.
*/
-/** Simultaneous uploads. Matches the previous frontend's limit. */
-const ASSET_UPLOAD_CONCURRENCY = 5;
-
/**
* A `catch` handler that degrades to `fallback`, except for the errors that must end the restore.
*
@@ -66,6 +64,26 @@ const ASSET_UPLOAD_CONCURRENCY = 5;
* signal or a rotated account makes *every* remaining call fail. Degrading those would report the
* project as half-restored and then create it anyway.
*/
+/**
+ * Hold a check's outcome — value or failure — so an early-started promise cannot become an
+ * unhandled rejection while the restore is busy elsewhere.
+ */
+type SettledExisting = { names: Set<string> } | { error: unknown };
+
+const settleExisting = (promise: Promise<Set<string>>): Promise<SettledExisting> =>
+ promise.then(
+ (names) => ({ names }),
+ (error: unknown) => ({ error })
+ );
+
+const unwrapExisting = (settled: SettledExisting): Set<string> => {
+ if ('error' in settled) {
+ throw settled.error;
+ }
+
+ return settled.names;
+};
+
const degradeUnlessCancelled =
<T>(fallback: T) =>
(error: unknown): T => {
@@ -185,7 +203,8 @@ export interface RestoreProjectMediaResult extends ProjectTransferIssues {
}
interface PendingUpload {
- bytes: Uint8Array;
+ /** Cleared once uploaded, so a queue of hundreds does not pin every asset's bytes to the end. */
+ bytes: Uint8Array | null;
kind: InvkMediaKind;
name: string;
}
@@ -292,6 +311,29 @@ export const restoreProjectMedia = async (
/** Names this server can serve once the restore is done, under their final identities. */
const restoredImageNames = new Set<string>();
+ // Started before the board upload, awaited after it. The existence checks depend only on the
+ // document's own references, which are known here — and the board upload is the minutes-long part
+ // of a large import, so waiting it out first meant the video probe, which is one request per
+ // name, began only once everything else had finished.
+ //
+ // An empty answer is the safe degradation: the check exists only to skip uploading something the
+ // destination already has, so failing it costs bandwidth, never correctness. Aborting the import
+ // over it would be losing the project to save a request.
+ //
+ // Settled rather than left to reject: a promise started here but not awaited until after the
+ // board upload would surface as an unhandled rejection if the upload threw first. Cancellation
+ // still ends the restore — it is re-thrown at the await below, in its proper order.
+ const existingImagesPromise = settleExisting(
+ documentOnlyImages.length === 0
+ ? Promise.resolve(new Set<string>())
+ : checkExistingImages(documentOnlyImages, deps.signal).catch(degradeUnlessCancelled(new Set<string>()))
+ );
+ const existingVideosPromise = settleExisting(
+ documentOnlyVideos.length === 0
+ ? Promise.resolve(new Set<string>())
+ : checkExistingVideos(documentOnlyVideos, deps.signal).catch(degradeUnlessCancelled(new Set<string>()))
+ );
+
const boardResult =
stagingBoardId === null
? emptyMaterializeResult()
@@ -377,20 +419,9 @@ export const restoreProjectMedia = async (
}
}
- // Both existence checks go out before either upload does; they are independent, and a project
- // with videos should not wait out the image pass.
- //
- // An empty answer is the safe degradation: the check exists only to skip uploading something the
- // destination already has, so failing it costs bandwidth, never correctness. Aborting the import
- // over it would be losing the project to save a request.
- const [existingImages, existingVideos] = await Promise.all([
- documentOnlyImages.length === 0
- ? Promise.resolve(new Set<string>())
- : checkExistingImages(documentOnlyImages, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),
- documentOnlyVideos.length === 0
- ? Promise.resolve(new Set<string>())
- : checkExistingVideos(documentOnlyVideos, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),
- ]);
+ const [existingImages, existingVideos] = (await Promise.all([existingImagesPromise, existingVideosPromise])).map(
+ unwrapExisting
+ ) as [Set<string>, Set<string>];
const pending: PendingUpload[] = [];
const plannedTotal = total;
@@ -428,7 +459,19 @@ export const restoreProjectMedia = async (
deps.onProgress?.({ completed, total });
}
- await mapWithConcurrency(pending, ASSET_UPLOAD_CONCURRENCY, async ({ bytes, kind, name }) => {
+ await mapWithConcurrency(pending, INVK_TRANSFER_CONCURRENCY, async (item) => {
+ const { kind, name } = item;
+ const bytes = item.bytes;
+
+ // Dropped from the queue before the request, not after: the upload body holds its own
+ // reference for as long as it needs one, and the queue was the reason a restore of a large
+ // project held every asset it had not sent yet.
+ item.bytes = null;
+
+ if (bytes === null) {
+ return;
+ }
+
try {
const options = { contentType: mimeForEntryName(name, kind), signal: deps.signal };
const restoredName =
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts
index c74d18abf1..dd11092e61 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts
@@ -1,7 +1,7 @@
import { InvkFormatError } from './invk/format';
/**
- * Turn a failed project-file read into something worth showing.
+ * Turn a failed project-file read or write into something worth showing.
*
* Every import entry point — Home, the Projects page, the in-editor Open dialog
* — used to pass `error.message` straight into a toast, which meant a person who
@@ -10,10 +10,23 @@ import { InvkFormatError } from './invk/format';
* and, importantly, says something different for each way this can go wrong:
* the fix for a legacy canvas project is not the fix for a corrupt archive.
*
+ * The direction matters for the two reasons both halves can raise. `too-large`
+ * comes from the export planner, the archive writer and the response reader as
+ * readily as from opening a file, and `damaged` is raised by duplication for a
+ * document that will not rehydrate. Telling someone their project "is too large
+ * to open" while they were exporting it names the wrong operation and the wrong
+ * file — theirs, not one they were handed.
+ *
* Anything that is not an `InvkFormatError` reached us from the network or the
* reducer. Those already carry messages meant for people, so they pass through.
*/
-export const describeProjectFileError = (error: unknown, t: (key: string) => string): string | undefined => {
+export type ProjectFileDirection = 'read' | 'write';
+
+export const describeProjectFileError = (
+ error: unknown,
+ t: (key: string) => string,
+ direction: ProjectFileDirection = 'read'
+): string | undefined => {
if (!(error instanceof InvkFormatError)) {
return error instanceof Error ? error.message : undefined;
}
@@ -26,10 +39,10 @@ export const describeProjectFileError = (error: unknown, t: (key: string) => str
return t('projects.file.unsupportedVersion');
}
case 'damaged': {
- return t('projects.file.damaged');
+ return t(direction === 'write' ? 'projects.file.damagedProject' : 'projects.file.damaged');
}
case 'too-large': {
- return t('projects.file.tooLarge');
+ return t(direction === 'write' ? 'projects.file.tooLargeToWrite' : 'projects.file.tooLarge');
}
default: {
return t('projects.file.notAProject');
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
index 973db3476c..3fa1a4daae 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts
@@ -57,20 +57,73 @@ describe('startProjectFileReport', () => {
report.succeed('projects.exported', { boardItemIssues: [], documentReferenceIssues: [] });
expect(toaster.create).toHaveBeenCalledTimes(1);
- expect(toaster.update).toHaveBeenCalledTimes(3);
expect(toaster.update.mock.calls.every(([id]) => id === 'toast-1')).toBe(true);
});
+ /**
+ * Progress arrives once per asset and a project can hold hundreds of them, during the phase
+ * already saturating the network. The first count shows at once; the rest coalesce.
+ */
+ it('redraws at most once per interval while assets settle', () => {
+ vi.useFakeTimers();
+
+ try {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.report({ completed: 1, phase: 'bundling', total: 300 });
+ report.report({ completed: 2, phase: 'bundling', total: 300 });
+ report.report({ completed: 3, phase: 'bundling', total: 300 });
+
+ expect(toaster.update).toHaveBeenCalledTimes(1);
+ expect(toaster.update.mock.calls[0]![1].description).toBe(
+ 'projects.file.bundlingProgress({"completed":1,"total":300})'
+ );
+
+ // Whatever the latest count is when the interval expires — never a stale one.
+ vi.advanceTimersByTime(500);
+ expect(toaster.update).toHaveBeenCalledTimes(2);
+ expect(toaster.update.mock.calls[1]![1].description).toBe(
+ 'projects.file.bundlingProgress({"completed":3,"total":300})'
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('counts assets while bundling and stops counting while packing', () => {
- const report = toasts.startProjectFileReport(t, 'projects.exporting');
+ vi.useFakeTimers();
+
+ try {
+ const report = toasts.startProjectFileReport(t, 'projects.exporting');
+
+ report.report({ completed: 2, phase: 'bundling', total: 7 });
+ expect(toaster.update.mock.calls[0]![1].description).toBe(
+ 'projects.file.bundlingProgress({"completed":2,"total":7})'
+ );
+
+ vi.advanceTimersByTime(500);
+ report.report({ completed: 7, phase: 'packing', total: 7 });
+ expect(toaster.update.mock.calls[1]![1].description).toBe('projects.file.packing');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
- report.report({ completed: 2, phase: 'bundling', total: 7 });
- expect(toaster.update.mock.calls[0]![1].description).toBe(
- 'projects.file.bundlingProgress({"completed":2,"total":7})'
- );
+ /**
+ * `succeed` runs before a caller's own follow-up work — the navigation after an import. A
+ * failure there is not a failure of the transfer, and saying so after it demonstrably worked is
+ * the worse lie.
+ */
+ it('does not take back a verdict it has already given', () => {
+ const report = toasts.startProjectFileReport(t, 'projects.importing');
+
+ report.succeed('projects.imported', { boardItemIssues: [], documentReferenceIssues: [] });
+ report.fail('projects.importFailed', new Error('navigation blew up'));
+
+ const settles = toaster.update.mock.calls.filter(([, options]) => options.duration === undefined);
- report.report({ completed: 7, phase: 'packing', total: 7 });
- expect(toaster.update.mock.calls[1]![1].description).toBe('projects.file.packing');
+ expect(settles).toHaveLength(1);
+ expect(settles[0]![1]).toMatchObject({ title: 'projects.imported', type: 'success' });
});
it('counts uploads on the way back in', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
index 3dfb1e164b..48d0c4c1a6 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts
@@ -3,7 +3,7 @@ import { toaster } from '@platform/ui';
import type { InvkMediaIssueReason, ProjectTransferIssues } from './invk/transfer';
import type { ProjectFileProgress } from './projectFile';
-import { describeProjectFileError } from './projectFileErrors';
+import { describeProjectFileError, type ProjectFileDirection } from './projectFileErrors';
/**
* How a project file reports itself while it runs, and what it says when it is
@@ -84,12 +84,30 @@ const describeProgress = (t: Translate, progress: ProjectFileProgress): string =
return t(key, { completed: progress.completed, total: progress.total });
};
+/**
+ * How often the live toast may redraw while a transfer runs.
+ *
+ * Progress arrives once per asset, and a project can have hundreds — each one otherwise a toaster
+ * state update, during the phase that is already saturating the network. A count that moves five
+ * times a second is as much as anyone reads, and the final value is always drawn, so the number a
+ * person is left looking at is never a stale one.
+ */
+const PROGRESS_REDRAW_INTERVAL_MS = 200;
+
/**
* Open the live toast for a transfer that is starting. The returned reporter
* owns that toast for the rest of the operation; every path through a caller's
* `try`/`catch` has to end in `succeed` or `fail`, or the toast stays up.
+ *
+ * `direction` decides how a failure is worded: the same `too-large` reason is raised by opening a
+ * file someone handed you and by exporting a project of your own, and those need different
+ * sentences.
*/
-export const startProjectFileReport = (t: Translate, title: string): ProjectFileReporter => {
+export const startProjectFileReport = (
+ t: Translate,
+ title: string,
+ direction: ProjectFileDirection = 'read'
+): ProjectFileReporter => {
const id = toaster.create({
// No duration: a transfer ends when it ends, and a toast that expired
// mid-export would leave the operation invisible again.
@@ -98,21 +116,65 @@ export const startProjectFileReport = (t: Translate, title: string): ProjectFile
type: 'loading',
});
+ let isSettled = false;
+ let redrawTimer: ReturnType<typeof setTimeout> | null = null;
+ let pendingDescription: string | null = null;
+
+ const clearRedraw = (): void => {
+ if (redrawTimer !== null) {
+ clearTimeout(redrawTimer);
+ redrawTimer = null;
+ }
+ pendingDescription = null;
+ };
+
const settle = (options: { description?: string; title: string; type: 'error' | 'success' | 'warning' }): void => {
+ isSettled = true;
+ clearRedraw();
toaster.update(id, { ...options, duration: undefined });
};
return {
dismiss: () => {
+ isSettled = true;
+ clearRedraw();
toaster.dismiss(id);
},
fail: (failureTitle, error) => {
- const description = describeProjectFileError(error, t);
+ // A verdict is not taken back. `succeed` runs before the caller's own follow-up work — the
+ // navigation after an import, say — and a failure there is not a failure of the transfer:
+ // telling someone their import failed after it demonstrably worked is the worse lie.
+ if (isSettled) {
+ return;
+ }
+
+ const description = describeProjectFileError(error, t, direction);
settle({ ...(description === undefined ? {} : { description }), title: failureTitle, type: 'error' });
},
report: (progress) => {
- toaster.update(id, { description: describeProgress(t, progress) });
+ if (isSettled) {
+ return;
+ }
+
+ pendingDescription = describeProgress(t, progress);
+
+ if (redrawTimer !== null) {
+ return;
+ }
+
+ // Leading edge, then trailing: the first count appears at once, and whatever the latest is
+ // when the interval expires replaces it.
+ toaster.update(id, { description: pendingDescription });
+ pendingDescription = null;
+ redrawTimer = setTimeout(() => {
+ redrawTimer = null;
+
+ if (pendingDescription !== null && !isSettled) {
+ toaster.update(id, { description: pendingDescription });
+ pendingDescription = null;
+ }
+ }, PROGRESS_REDRAW_INTERVAL_MS);
},
succeed: (successTitle, issues) => {
const { boardItems, documentReferences, unstarred } = countIssues(issues);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
index 86621e5815..932a130f4c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectFileActions.ts
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import type { ProjectRecordDTO } from './api';
import type { DuplicatedProject } from './library';
+import type { ProjectFileDirection } from './projectFileErrors';
import { duplicateLibraryProject } from './library';
import { exportLibraryProject, exportOpenProject, importProjectFile, pickProjectFile } from './projectFile';
@@ -34,11 +35,11 @@ import { startProjectFileReport } from './projectFileToasts';
/** Runs the sequence, keeping the toast and the account scope in step. */
const runReported = async <T>(
t: (key: string, options?: Record<string, unknown>) => string,
- titles: { failed: string; running: string },
+ titles: { direction?: ProjectFileDirection; failed: string; running: string },
run: (report: ReturnType<typeof startProjectFileReport>, owner: ReturnType<typeof captureAccountScope>) => Promise<T>
): Promise<void> => {
const owner = captureAccountScope();
- const report = startProjectFileReport(t, titles.running);
+ const report = startProjectFileReport(t, titles.running, titles.direction);
try {
await run(report, owner);
@@ -92,7 +93,7 @@ export const useExportLibraryProject = (): ((projectId: string, name: string) =>
(projectId: string, name: string) => {
void runReported(
t,
- { failed: t('projects.exportFailed'), running: t('projects.exporting', { name }) },
+ { direction: 'write', failed: t('projects.exportFailed'), running: t('projects.exporting', { name }) },
async (report, owner) => {
const issues = await exportLibraryProject(projectId, { onProgress: report.report, owner });
@@ -120,7 +121,7 @@ export const useDuplicateProject = (
(projectId: string) => {
void runReported(
t,
- { failed: t('projects.duplicateFailed'), running: t('projects.duplicating') },
+ { direction: 'write', failed: t('projects.duplicateFailed'), running: t('projects.duplicating') },
async (report, owner) => {
const duplicated = await duplicateLibraryProject(projectId, {
// Everything a duplication moves is restored onto the copy's board, so the phase is
@@ -148,7 +149,11 @@ export const useExportOpenProject = (): ((project: Project) => void) => {
(project: Project) => {
void runReported(
t,
- { failed: t('projects.exportFailed'), running: t('projects.exporting', { name: project.name }) },
+ {
+ direction: 'write',
+ failed: t('projects.exportFailed'),
+ running: t('projects.exporting', { name: project.name }),
+ },
async (report, owner) => {
const issues = await exportOpenProject(project, { onProgress: report.report, owner });