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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): stop one media failure from ending a project restore
Josh Corbett78e285ad2b69
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 1393489954..509356eb0d 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -428,6 +428,8 @@"packing": "Packing the archive…","restoringProgress": "Restoring {{completed}} of {{total}} assets…","tooLarge": "This project file is too large to open.",+ "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."},"gridView": "Grid view",diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.tsindex e6828dc6c7..d371cdc5a8 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts@@ -18,7 +18,13 @@ import type { InvkBoardItem } from './board';import type { MediaMaterializer } from './restoreProjectMedia';import type { ProjectTransferIssues } from './transfer';-import { copyImagesToBoard, copyVideosToBoard, createStagingBoard } from './assetTransport';+import {+ type CopyMediaResult,+ copyImagesToBoard,+ copyVideosToBoard,+ createStagingBoard,+ isRequestCancellation,+} from './assetTransport';import { InvkFormatError } from './format';import { createRestoredMediaLedger, restoreProjectMedia, rollbackRestoredMedia } from './restoreProjectMedia';import { toMediaRefs } from './transfer';@@ -69,19 +75,33 @@ export interface DuplicateProjectResult extends ProjectTransferIssues {* Progress moves per item once each batch answers rather than during it. The copy is a single* server-side request per kind, so there is no finer truth to report — and unlike an import, there* is no upload to sit and watch.+ *+ * A batch that does not answer at all — a proxy timing out a large board — is every name in it+ * failing, not the duplication failing. The route reports per-item failures precisely so one bad+ * source cannot cost the caller the batch; letting a transport error do what the route refuses to+ * would give that guarantee away at the last step.*/export const createCopyMediaMaterializer = (deps: { copyImages?: typeof copyImagesToBoard; copyVideos?: typeof copyVideosToBoard; signal?: AbortSignal } = {}): MediaMaterializer => {const copyImages = deps.copyImages ?? copyImagesToBoard;const copyVideos = deps.copyVideos ?? copyVideosToBoard;+ const allFailed =+ (names: string[]) =>+ (error: unknown): CopyMediaResult => {+ if (isRequestCancellation(error)) {+ throw error;+ }++ return { copied: [], failed: names };+ };return async (items, boardId, onItemSettled) => {const imageNames = items.filter((item) => item.kind === 'image').map((item) => item.name);const videoNames = items.filter((item) => item.kind === 'video').map((item) => item.name);const [images, videos] = await Promise.all([- copyImages(imageNames, boardId, deps.signal),- copyVideos(videoNames, boardId, deps.signal),+ copyImages(imageNames, boardId, deps.signal).catch(allFailed(imageNames)),+ copyVideos(videoNames, boardId, deps.signal).catch(allFailed(videoNames)),]);for (let index = 0; index < items.length; index += 1) {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex a323f98f00..849fff4a21 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -11,7 +11,7 @@ import type {import type { InvkMediaRef } from './transfer';import { INVK_MAX_ARCHIVE_BYTES, readArchive, readEntryText } from './archive';-import { mimeForEntryName, uploadBoardImage, uploadBoardVideo } from './assetTransport';+import { isRequestCancellation, mimeForEntryName, uploadBoardImage, uploadBoardVideo } from './assetTransport';import { parseInvkBoardSnapshot } from './board';import {INVK_BOARD_ENTRY,@@ -229,7 +229,13 @@ export const createArchiveMediaMaterializer = (: (await uploadVideo(bytes, item.name, options)).videoName;result.materialized.push({ kind: item.kind, name, sourceName: item.name });- } catch {+ } 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.+ if (isRequestCancellation(error)) {+ throw error;+ }+result.failed.push({ kind: item.kind, name: item.name, reason: 'upload-failed' });}diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.tsindex 55dd638a88..76d69975da 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts@@ -143,6 +143,29 @@ describe('board media', () => {expect(result.mappings.images.get('board.png')).toBe('staging-board-board.png');});+ /**+ * A rejected star call reaches the caller's rollback, which deletes every asset the restore just+ * uploaded. Trading a whole project's media for a flag is the one thing this must not do.+ */+ it('does not lose the restore when the star request itself fails', async () => {+ const result = await restore(+ { boardItems: [boardItem({ starred: true })], documentRefs: [imageRef('board.png')] },+ { starImages: () => Promise.reject(new Error('500')) }+ );++ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'board.png', reason: 'star-failed' }]);+ expect(result.mappings.images.get('board.png')).toBe('staging-board-board.png');+ expect(result.ledger.boardImageNames).toEqual(['staging-board-board.png']);+ });++ it('ends the restore when starring fails because the operation was cancelled', async () => {+ const cancelled = Object.assign(new Error('aborted'), { name: 'AbortError' });++ await expect(+ restore({ boardItems: [boardItem({ starred: true })] }, { starImages: () => Promise.reject(cancelled) })+ ).rejects.toBe(cancelled);+ });+it('reports a descriptor the source could not materialize', async () => {const result = await restore({ boardItems: [boardItem({ name: 'gone.png' })] },@@ -206,6 +229,36 @@ describe('board media', () => {});describe('document-only references', () => {+ /**+ * The existence check is an optimization — it only decides whether an upload can be skipped. A+ * failed probe should cost bandwidth, never the import.+ */+ it('uploads everything when the existence check fails', async () => {+ const uploadImage = vi.fn((_bytes: Uint8Array, fileName: string) =>+ Promise.resolve({ height: 1, imageName: `uploaded-${fileName}`, width: 1 })+ );+ const result = await restore(+ { documentRefs: [imageRef('external.png')] },+ {+ documentMediaBytes: () => new Uint8Array([1]),+ findExistingImageNames: () => Promise.reject(new Error('500')),+ uploadImage,+ }+ );++ expect(uploadImage).toHaveBeenCalledTimes(1);+ expect(result.mappings.images.get('external.png')).toBe('uploaded-external.png');+ expect(result.documentReferenceIssues).toEqual([]);+ });++ it('ends the restore when the existence check fails because the operation was cancelled', async () => {+ const cancelled = Object.assign(new Error('aborted'), { name: 'AbortError' });++ await expect(+ restore({ documentRefs: [imageRef('external.png')] }, { findExistingImageNames: () => Promise.reject(cancelled) })+ ).rejects.toBe(cancelled);+ });+it('reuses media the destination already has instead of uploading it again', async () => {const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'never', width: 1 }));const result = await restore(diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.tsindex 8f16cdde5c..6d2aef3f6f 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,+ isRequestCancellation,mimeForEntryName,starImages,starVideos,@@ -54,6 +55,27 @@ import { buildMissingMediaName, createTransferIssueLog, toMediaKey } from './tra/** 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.+ *+ * Nothing in a restore is worth the whole restore. Starring is a flag; an existence probe only+ * spares a redundant upload. A batch of either failing should cost what it is worth, not reach the+ * caller's rollback and delete every asset that had already arrived.+ *+ * Cancellation is the exception, and has to be, because it is not a failure of the call: an aborted+ * signal or a rotated account makes *every* remaining call fail. Degrading those would report the+ * project as half-restored and then create it anyway.+ */+const degradeUnlessCancelled =+ <T>(fallback: T) =>+ (error: unknown): T => {+ if (isRequestCancellation(error)) {+ throw error;+ }++ return fallback;+ };+/** One board item that now exists here, under the name this server chose for it. */export interface MaterializedMedia {kind: InvkMediaKind;@@ -335,9 +357,13 @@ export const restoreProjectMedia = async (// Starring is a separate call by design: the same one import and duplication use, and the same// one the gallery uses. A star that fails costs a flag, not the media, so it is reported against// the board item and nowhere else — the document does not care whether a layer is starred.+ //+ // Which is why the call itself must not reject: a rejection here reaches the caller's rollback+ // and deletes every image that was just uploaded, over a flag. A whole batch that failed to send+ // is every name in it failing to be starred.const [imageStars, videoStars] = await Promise.all([- starRestoredImages(starTargets.image, deps.signal),- starRestoredVideos(starTargets.video, deps.signal),+ starRestoredImages(starTargets.image, deps.signal).catch(degradeUnlessCancelled({ failed: starTargets.image })),+ starRestoredVideos(starTargets.video, deps.signal).catch(degradeUnlessCancelled({ failed: starTargets.video })),]);for (const [kind, failed] of [@@ -353,13 +379,17 @@ 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),+ : checkExistingImages(documentOnlyImages, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),documentOnlyVideos.length === 0? Promise.resolve(new Set<string>())- : checkExistingVideos(documentOnlyVideos, deps.signal),+ : checkExistingVideos(documentOnlyVideos, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),]);const pending: PendingUpload[] = [];@@ -416,7 +446,14 @@ export const restoreProjectMedia = async (if (restoredName !== name) {mappings[kind === 'image' ? 'images' : 'videos'].set(name, restoredName);}- } catch {+ } catch (error) {+ // Not a failure of this asset: an aborted signal or an expired account makes every remaining+ // upload fail too, and reporting them one by one would finish with a warning naming hundreds+ // of dangling references and a project created anyway.+ if (isRequestCancellation(error)) {+ throw error;+ }+// A failed upload leaves the reference pointing at a name this server does not have — the// same outcome as an asset the source never carried, and honest for the same reason.issues.addDocumentReferenceIssue({ kind, name }, 'upload-failed');diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.tsindex 1c6279d867..3dfb1e164b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts@@ -1,6 +1,6 @@import { toaster } from '@platform/ui';-import type { ProjectTransferIssues } from './invk/transfer';+import type { InvkMediaIssueReason, ProjectTransferIssues } from './invk/transfer';import type { ProjectFileProgress } from './projectFile';import { describeProjectFileError } from './projectFileErrors';@@ -56,6 +56,24 @@ export interface ProjectFileReporter {fail: (title: string, error: unknown) => void;}+/**+ * The reasons that mean the media is *not here*, as opposed to here without its flag.+ *+ * `star-failed` is the odd one out: the item arrived, it just did not get its star back. Folding it+ * into "could not be included" tells someone their project lost media when nothing was lost, which+ * is the one thing these counts exist to answer accurately.+ *+ * Phrasing a reason is this module's job, so the set lives here — `transfer.ts` owns the taxonomy+ * and is imported type-only, which also keeps it out of the two routes' initial chunks.+ */+const MISSING_REASONS: ReadonlySet<InvkMediaIssueReason> = new Set(['fetch-failed', 'missing-entry', 'upload-failed']);++const countIssues = (issues: ProjectTransferIssues) => ({+ boardItems: issues.boardItemIssues.filter((issue) => MISSING_REASONS.has(issue.reason)).length,+ documentReferences: issues.documentReferenceIssues.filter((issue) => MISSING_REASONS.has(issue.reason)).length,+ unstarred: issues.boardItemIssues.filter((issue) => issue.reason === 'star-failed').length,+});+const describeProgress = (t: Translate, progress: ProjectFileProgress): string => {if (progress.phase === 'packing') {return t('projects.file.packing');@@ -97,10 +115,9 @@ export const startProjectFileReport = (t: Translate, title: string): ProjectFiletoaster.update(id, { description: describeProgress(t, progress) });},succeed: (successTitle, issues) => {- const boardCount = issues.boardItemIssues.length;- const referenceCount = issues.documentReferenceIssues.length;+ const { boardItems, documentReferences, unstarred } = countIssues(issues);- if (boardCount === 0 && referenceCount === 0) {+ if (boardItems === 0 && documentReferences === 0 && unstarred === 0) {settle({ title: successTitle, type: 'success' });return;@@ -109,8 +126,9 @@ export const startProjectFileReport = (t: Translate, title: string): ProjectFile// Counts, never names: a project can lose hundreds of assets at once, and a toast listing// them would be unreadable. The typed detail stays on the outcome for anything that needs it.const parts = [- ...(boardCount === 0 ? [] : [t('projects.file.missingBoardItems', { count: boardCount })]),- ...(referenceCount === 0 ? [] : [t('projects.file.missingReferences', { count: referenceCount })]),+ ...(boardItems === 0 ? [] : [t('projects.file.missingBoardItems', { count: boardItems })]),+ ...(documentReferences === 0 ? [] : [t('projects.file.missingReferences', { count: documentReferences })]),+ ...(unstarred === 0 ? [] : [t('projects.file.unstarredItems', { count: unstarred })]),];settle({ description: parts.join(' '), title: successTitle, type: 'warning' });