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): reuse the restored cover instead of leaking a copy per import
joshistoastebe50cb03635
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.tsindex f991a4d29d..eef3ec51d6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts@@ -171,7 +171,13 @@ describe('restoreArchiveAssets', () => {expect(result.uploadedCount).toBe(0);});- it('uploads the cover alongside and returns its server name', async () => {+ /**+ * The bundled cover is a thumbnail of an image the document also references,+ * and the cover URL asks for a thumbnail anyway — so once that image is on+ * the server, uploading the entry too would leave an orphan nobody can find:+ * covers go up under the `'other'` category, which shows in no gallery view.+ */+ it('reuses the restored cover image instead of uploading a second copy', async () => {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 }));@@ -180,7 +186,39 @@ describe('restoreArchiveAssets', () => {uploadArchiveImage: upload,});+ expect(result.coverImageName).toBe('a.png');+ expect(upload).not.toHaveBeenCalled();+ });++ it('follows the rename when the cover image was uploaded under a new name', async () => {+ const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });+ const upload = vi.fn((_bytes: Uint8Array, fileName: string) =>+ Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 })+ );++ const result = await restoreArchiveAssets(withCover, {+ findExistingImageNames: () => Promise.resolve(new Set()),+ uploadArchiveImage: upload,+ });++ expect(result.coverImageName).toBe('server-a.png');+ // Once for the image itself, never again for the cover.+ expect(upload).toHaveBeenCalledTimes(1);+ });++ it('falls back to the bundled cover when its source image is dangling', async () => {+ const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });++ withCover.images.delete('a.png');++ const upload = vi.fn(() => Promise.resolve({ height: 1, imageName: 'server-cover.png', width: 1 }));+ const result = await restoreArchiveAssets(withCover, {+ findExistingImageNames: () => Promise.resolve(new Set()),+ uploadArchiveImage: upload,+ });+expect(result.coverImageName).toBe('server-cover.png');+ expect(result.danglingAssetNames).toEqual(['a.png']);expect(upload).toHaveBeenCalledWith(new Uint8Array([9]), 'cover.webp', {contentType: 'image/webp',signal: undefined,@@ -236,15 +274,45 @@ describe('restoreArchiveAssets', () => {expect(findVideos).not.toHaveBeenCalled();});- it('survives a cover that fails to upload', async () => {+ it('survives a fallback cover that fails to upload', async () => {const withCover = await contents({ cover: { bytes: new Uint8Array([9]), entryName: 'cover.webp' } });+ withCover.images.delete('a.png');+const result = await restoreArchiveAssets(withCover, {- findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),+ findExistingImageNames: () => Promise.resolve(new Set()),uploadArchiveImage: () => Promise.reject(new Error('nope')),});expect(result.coverImageName).toBeNull();- expect(result.danglingAssetNames).toEqual([]);+ expect(result.danglingAssetNames).toEqual(['a.png']);+ });++ it('announces a video entry as a video, whatever its extension', async () => {+ const videoDocument = {+ ...document(),+ projectGraph: { nodes: [{ data: { inputs: { video: { video_name: 'clip.unknown' } } }, id: 'n' }] },+ };+ const withVideo = await readInvkArchive(+ await archiveFile({+ 'manifest.json': JSON.stringify(manifest()),+ 'project.json': JSON.stringify(videoDocument),+ 'videos/clip.unknown': new Uint8Array([7]),+ })+ );+ const uploadVideo = vi.fn(() => Promise.resolve({ videoName: 'server-clip.mp4' }));++ await restoreArchiveAssets(withVideo, {+ findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),+ findExistingVideoNames: () => Promise.resolve(new Set()),+ uploadArchiveVideo: uploadVideo,+ });++ // `image/png` here would be announced to the video endpoint as an image and+ // refused before the bytes were read.+ expect(uploadVideo).toHaveBeenCalledWith(new Uint8Array([7]), 'clip.unknown', {+ contentType: 'video/mp4',+ signal: undefined,+ });});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex 79d0715afe..74cafcfd70 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -1,5 +1,5 @@import { mapWithConcurrency } from '@platform/core/concurrency';-import { collectLiveAssetRefs } from '@workbench/projects/projectAssets';+import { collectLiveAssetRefs, selectCoverImageName } from '@workbench/projects/projectAssets';import type { UploadedImage, UploadedVideo } from './assetTransport';import type { InvkManifest } from './manifest';@@ -29,8 +29,8 @@ import { parseInvkManifest } from './manifest';* nothing, so a caller can read a file, discover it is a legacy canvas project,* and say so without having created anything.*- * {@link restoreArchiveImages} is the part with consequences: ask the server- * which referenced images it already has, upload the rest out of the archive,+ * {@link restoreArchiveAssets} is the part with consequences: ask the server+ * which referenced assets it already has, upload the rest out of the archive,* and report the old-to-new renames. It deliberately does *not* touch the* document — the caller applies the mapping, because the caller is also the one* assigning the new project id.@@ -153,6 +153,57 @@ interface PendingUpload {name: string;}+/**+ * The cover, preferring an image the restore already put on this server.+ *+ * The archive's `cover` entry is a thumbnail of an image the document also+ * references, and `getProjectCoverUrl` asks for a thumbnail anyway — so once+ * that image is restored, pointing the index at it is the same picture without+ * a second copy. Uploading the entry unconditionally instead left one orphan+ * per import: covers go up under the canvas's private `'other'` category, which+ * appears in no gallery view and no board count, so nobody could ever find or+ * delete them.+ *+ * The bundled bytes are the fallback, for the case that made them worth+ * carrying: a cover whose source image is dangling here.+ */+const resolveCoverImageName = async (input: {+ contents: InvkArchiveContents;+ mappings: { images: Map<string, string> };+ restoredImageNames: ReadonlySet<string>;+ signal?: AbortSignal;+ uploadImage: NonNullable<RestoreAssetsDeps['uploadArchiveImage']>;+}): Promise<string | null> => {+ const documentCoverName = selectCoverImageName(input.contents.projectDocument);++ if (documentCoverName !== null) {+ const restoredName = input.mappings.images.get(documentCoverName) ?? documentCoverName;++ if (input.restoredImageNames.has(restoredName)) {+ return restoredName;+ }+ }++ const { cover } = input.contents;++ if (cover === null) {+ return null;+ }++ try {+ const uploaded = await input.uploadImage(cover.bytes, cover.entryName, {+ contentType: mimeForEntryName(cover.entryName),+ signal: input.signal,+ });++ return uploaded.imageName;+ } catch {+ // A project with no cover shows the folder glyph, which is a state the+ // library already renders. Not worth failing an import over.+ return null;+ }+};+/*** 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@@ -206,31 +257,18 @@ export const restoreArchiveAssets = async (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;+ // The cover is not part of the document, so it does not come through the+ // reference set; it is still counted here so progress spans the whole restore.+ const total = pending.length + (contents.cover === null ? 0 : 1);let completed = 0;let uploadedCount = 0;- const coverImageName =- contents.cover === null- ? null- : await uploadImage(contents.cover.bytes, contents.cover.entryName, {- contentType: mimeForEntryName(contents.cover.entryName),- signal: deps.signal,- })- .then((uploaded) => uploaded.imageName)- .catch(() => null);-- if (contents.cover !== null) {- completed += 1;- deps.onProgress?.({ completed, total });- }+ /** Images this server can serve when the restore is done, under their final names. */+ const restoredImageNames = new Set(referencedImages.filter((name) => existingImages.has(name)));await mapWithConcurrency(pending, ASSET_UPLOAD_CONCURRENCY, async ({ bytes, kind, name }) => {try {- const options = { contentType: mimeForEntryName(name), signal: deps.signal };+ const options = { contentType: mimeForEntryName(name, kind), signal: deps.signal };const restoredName =kind === 'image'? (await uploadImage(bytes, name, options)).imageName@@ -238,6 +276,10 @@ export const restoreArchiveAssets = async (uploadedCount += 1;+ if (kind === 'image') {+ restoredImageNames.add(restoredName);+ }+if (restoredName !== name) {mappings[kind === 'image' ? 'images' : 'videos'].set(name, restoredName);}@@ -251,5 +293,18 @@ export const restoreArchiveAssets = async (deps.onProgress?.({ completed, total });});+ const coverImageName = await resolveCoverImageName({+ contents,+ mappings,+ restoredImageNames,+ signal: deps.signal,+ uploadImage,+ });++ if (contents.cover !== null) {+ completed += 1;+ deps.onProgress?.({ completed, total });+ }+return { coverImageName, danglingAssetNames: danglingAssetNames.sort(), mappings, uploadedCount };};