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
feat(webv2): export and import projects as .invk archives
joshistoast5309cd1888a3
diff --git a/docs/src/content/docs/development/Front End/canvas-projects.mdx b/docs/src/content/docs/development/Front End/canvas-projects.mdxindex b36c2ce972..e12db1ba36 100644--- a/docs/src/content/docs/development/Front End/canvas-projects.mdx+++ b/docs/src/content/docs/development/Front End/canvas-projects.mdx@@ -4,6 +4,10 @@ title: Canvas ProjectsCanvas projects serialize the current canvas into a portable `.invk` archive. The feature lives in `invokeai/frontend/web/src/features/controlLayers/` and is exposed in the canvas toolbar archive menu and the canvas context menu under **Project**.+:::note+This page describes **version 1** of the `.invk` container, which is canvas-only and written by this frontend. Workbench projects write version 2 of the same container — see [Project Files (.invk)](/development/front-end/project-files/). The two readers each pin their own version and refuse the other's archives.+:::+## File format`.invk` files are ZIP archives. The current manifest version is `1`.@@ -51,4 +55,4 @@ Image existence checks and uploads are also concurrency-limited.The archive stores references to models, LoRAs, and other generation resources, not the model files themselves. Loading a project on another install can restore the canvas images and state, but missing model resources still need to be installed or replaced by the user.-Future format changes should increment `CANVAS_PROJECT_VERSION` and keep validation in `parseManifest()` explicit so unsupported project files fail early.+Future format changes should increment `CANVAS_PROJECT_VERSION` and keep validation in `parseManifest()` explicit so unsupported project files fail early. Version `2` is taken by the Workbench project archive.diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdxnew file mode 100644index 0000000000..606f368c45--- /dev/null+++ b/docs/src/content/docs/development/Front End/project-files.mdx@@ -0,0 +1,64 @@+---+title: Project Files (.invk)+---++Workbench projects export to a portable `.invk` archive. The feature lives in `invokeai/frontend/webv2/src/workbench/projects/` and is exposed as **Import…** on the Launchpad's Home and Projects pages, **Open project…** in the editor's tab bar, and **Export** in the project switcher and each project card's action menu.++`.invk` is shared with the previous frontend's [canvas projects](/development/front-end/canvas-projects/), which write version 1 of the same container. Workbench projects write version 2. The two are deliberately not interchangeable — see [Versions](#versions).++## File format++`.invk` files are ZIP archives. The current manifest version is `2`.++| Target | Required | Description |+| - | - | - |+| `manifest.json` | yes | Archive version, app version, creation timestamp, project name, and optionally the source project id and the cover entry's path. |+| `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. |++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.++## What gets bundled++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.++**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.++## Loading++`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.++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.++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()`.++**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.++## Covers++`ProjectSummary.coverUrl` comes from a per-user index in the client-state KV (`projects/covers.ts`), not from the archive and not from the document. The library lists projects through `GET /projects`, which returns summaries with no document, so deriving a cover there would mean fetching every project's document to render a page of thumbnails.++The index is written whenever a project is serialized for a save, and on import from the archive's uploaded cover. It is an index and not a truth: a project saved by an older build has no entry and shows the folder glyph, which is also what a project that has produced nothing shows.++## Versions++Manifests parse through a zod discriminated union on `version`, so a version 1 archive is recognized and refused *as what it is* — `InvkFormatError` carries a `reason` (`legacy-canvas-project`, `unsupported-version`, `not-a-project`, `damaged`, `too-large`) that `describeProjectFileError()` maps to a translated string. There is no translation layer from legacy canvas state to `CanvasStateContractV2`.++The legacy reader is the mirror image: it pins `version: 1` and refuses a version 2 archive.++Future format changes should add a new member to the union rather than widening version 2, so that every version this app has ever written can be named precisely when refused.++## Guards++`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.++## 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.++Gallery boards, queue contents and account preferences are not part of a project and are not exported.diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex 423ccce1cd..e4c497d984 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -49,6 +49,7 @@"@tanstack/react-virtual": "^3.14.9","@xyflow/react": "^12.11.2","ag-psd": "^31.0.2",+ "fflate": "^0.8.3","fuzzysort": "^3.1.0","i18next": "^26.3.6","i18next-http-backend": "^4.0.1",diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yamlindex ad37d5a608..bb730bb51b 100644--- a/invokeai/frontend/webv2/pnpm-lock.yaml+++ b/invokeai/frontend/webv2/pnpm-lock.yaml@@ -44,6 +44,9 @@ importers:ag-psd:specifier: ^31.0.2version: 31.0.2+ fflate:+ specifier: ^0.8.3+ version: 0.8.3fuzzysort:specifier: ^3.1.0version: 3.1.0@@ -1507,6 +1510,9 @@ packages:picomatch:optional: true+ resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}+resolution: {integrity: sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==}@@ -3637,6 +3643,8 @@ snapshots:optionalDependencies:picomatch: 4.0.5+ [email protected]: {}+diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 6065ec5ef5..53c70cc097 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -414,6 +414,13 @@"editedRelative": "Edited {{time}}","exportFailed": "Export failed","failedToLoad": "Failed to load your projects.",+ "file": {+ "damaged": "This project file is damaged and cannot be opened.",+ "legacyCanvasProject": "This is a canvas project from an earlier version of Invoke, which cannot be opened here.",+ "notAProject": "This file is not an Invoke project.",+ "tooLarge": "This project file is too large to open.",+ "unsupportedVersion": "This project file was written by a newer version of Invoke."+ },"gridView": "Grid view","groups": {"all": "All projects",diff --git a/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts b/invokeai/frontend/webv2/src/platform/core/concurrency.test.tsnew file mode 100644index 0000000000..6b56fe36ac--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/core/concurrency.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest';++import { mapWithConcurrency } from './concurrency';++const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((settle) => {+ resolve = settle;+ });++ return { promise, resolve };+};++describe('mapWithConcurrency', () => {+ it('returns results in input order, not completion order', async () => {+ const results = await mapWithConcurrency([30, 20, 10], 3, async (delay) => {+ await new Promise<void>((resolve) => {+ setTimeout(resolve, delay);+ });++ return delay;+ });++ expect(results).toEqual([30, 20, 10]);+ });++ it('passes the index alongside each item', async () => {+ const results = await mapWithConcurrency(['a', 'b', 'c'], 2, (item, index) => Promise.resolve(`${index}:${item}`));++ expect(results).toEqual(['0:a', '1:b', '2:c']);+ });++ it('never runs more than `concurrency` mappers at once', async () => {+ const gates = Array.from({ length: 5 }, () => deferred<void>());+ let inFlight = 0;+ let peak = 0;++ const run = mapWithConcurrency(gates, 2, async (gate) => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await gate.promise;+ inFlight -= 1;+ });++ // Release one at a time so the pool must refill rather than burst.+ for (const gate of gates) {+ gate.resolve();+ await Promise.resolve();+ }++ await run;++ expect(peak).toBe(2);+ });++ it('starts no workers for an empty list', async () => {+ let calls = 0;++ const results = await mapWithConcurrency([], 4, () => {+ calls += 1;++ return Promise.resolve(null);+ });++ expect(results).toEqual([]);+ expect(calls).toBe(0);+ });++ it('rejects when a mapper rejects', async () => {+ await expect(+ mapWithConcurrency([1, 2], 2, (item) => (item === 2 ? Promise.reject(new Error('nope')) : Promise.resolve(item)))+ ).rejects.toThrow('nope');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/core/concurrency.ts b/invokeai/frontend/webv2/src/platform/core/concurrency.tsnew file mode 100644index 0000000000..335fe2ef27--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/core/concurrency.ts@@ -0,0 +1,38 @@+/**+ * Run an async mapper over a list with a bounded number of tasks in flight.+ *+ * Every caller here is fanning out HTTP requests — importing gallery images+ * onto the canvas, bundling a project's assets into an archive, restoring them+ * on the way back. `Promise.all` over the whole list is the obvious spelling+ * and the wrong one: a project with three hundred images opens three hundred+ * sockets, the browser queues most of them anyway, and the backend sees a+ * thundering herd it did nothing to deserve.+ *+ * Results keep the input order regardless of completion order, so callers can+ * zip them back against the source list by index.+ *+ * 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.+ */+export const mapWithConcurrency = async <T, R>(+ items: readonly T[],+ concurrency: number,+ mapper: (item: T, index: number) => Promise<R>+): Promise<R[]> => {+ const results: R[] = [];+ let nextIndex = 0;++ const worker = async (): Promise<void> => {+ while (nextIndex < items.length) {+ const index = nextIndex;++ nextIndex += 1;+ results[index] = await mapper(items[index]!, index);+ }+ };++ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));++ return results;+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.tsindex bca89f9596..6b5b306dc6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts@@ -11,6 +11,7 @@ import {normalizeGenerateWidgetValues,} from '@features/generation/settings';import { getModelsSnapshot } from '@features/models';+import { mapWithConcurrency } from '@platform/core/concurrency';import {assertAccountScopeCurrent,captureAccountScope,@@ -166,24 +167,6 @@ const buildLayers = (return layers;};-const mapWithConcurrency = async <T, R>(- items: readonly T[],- concurrency: number,- mapper: (item: T, index: number) => Promise<R>-): Promise<R[]> => {- const results: R[] = [];- let nextIndex = 0;- const worker = async (): Promise<void> => {- while (nextIndex < items.length) {- const index = nextIndex;- nextIndex += 1;- results[index] = await mapper(items[index]!, index);- }- };- await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));- return results;-};-type ResizeResult =| { status: 'fulfilled'; image: LayerImage }| { status: 'rejected'; imageName: string; reason: unknown };diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsxindex a8a970edb3..057095782e 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/HomePage.tsx@@ -20,6 +20,7 @@ import { prunePinnedProjects, toggleProjectPinPreference } from '@workbench/launimport { getProjectLibrary, refreshProjectLibrary, useProjectLibrarySelector } from '@workbench/projects/library';import { refreshOpenProjects } from '@workbench/projects/openProjects';import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';+import { describeProjectFileError } from '@workbench/projects/projectFileErrors';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { FileUpIcon, PlusIcon } from 'lucide-react';import { useCallback } from 'react';@@ -85,7 +86,7 @@ export const HomePage = () => {}toaster.create({- description: error instanceof Error ? error.message : undefined,+ description: describeProjectFileError(error, t),title: t('projects.importFailed'),type: 'error',});diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsxindex 294e81f007..b525cabc63 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/pages/ProjectsPage.tsx@@ -19,6 +19,7 @@ import { ProjectsToolbar } from '@workbench/launchpad/projects/ProjectsToolbar';import { getProjectLibrary, refreshProjectLibrary } from '@workbench/projects/library';import { refreshOpenProjects } from '@workbench/projects/openProjects';import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';+import { describeProjectFileError } from '@workbench/projects/projectFileErrors';import { patchWorkbenchPreferences, useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { FileUpIcon, PlusIcon } from 'lucide-react';import { useCallback, useState } from 'react';@@ -86,7 +87,7 @@ export const ProjectsPage = () => {}toaster.create({- description: error instanceof Error ? error.message : undefined,+ description: describeProjectFileError(error, t),title: t('projects.importFailed'),type: 'error',});diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsxindex 14b58f962c..7ee1b82216 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.browser.test.tsx@@ -7,10 +7,11 @@ import { afterEach, describe, expect, it } from 'vitest';import { ProjectCover } from './ProjectCover';/**- * Nothing populates `coverUrl` until the `.invk` project-file work lands, so- * these assertions are what keep the with-image branch from rotting in the- * meantime — and what prove the box is reserved either way, which is the whole- * reason the component exists now rather than later.+ * The three states a cover has: an image, no image, and an image the browser+ * could not load. The last is the one worth pinning — a cover names a server+ * image that may since have been deleted, and a broken `<img>` reads worse than+ * the glyph. All three reserve the same box, so a grid does not reflow as+ * covers resolve.*/// A 1x1 transparent GIF, so the success path needs no network.diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsxindex 59c4d7cf8c..ff602bbcb5 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCover.tsx@@ -5,10 +5,9 @@ import { useCallback, useState } from 'react';/*** A project's thumbnail.*- * Nothing sets `coverUrl` yet — covers arrive with the `.invk` project-file- * work, where a cover is just another entry in the archive. This exists now so- * that landing them is a data change rather than a layout change: the box is- * reserved unconditionally, so cards do not reflow when images appear.+ * `coverUrl` comes from the per-user cover index (`projects/covers.ts`), which+ * records each project's newest result as it saves. The box is reserved+ * unconditionally, so a card does not reflow when its cover resolves.** The glyph is not a placeholder awaiting an image. It is the permanent state* for a project that has produced nothing, and for a cover whose image hasdiff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.tsindex 85ac037e75..65d1437f3c 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts@@ -6,6 +6,7 @@ import {type ProjectSummary,} from '@workbench/projects/library';import { exportLibraryProject } from '@workbench/projects/projectFile';+import { describeProjectFileError } from '@workbench/projects/projectFileErrors';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -66,7 +67,7 @@ export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActioawait exportLibraryProject(summary.id);} catch (error) {toaster.create({- description: error instanceof Error ? error.message : undefined,+ description: describeProjectFileError(error, t),title: t('projects.exportFailed'),type: 'error',});diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsxindex c81c04541b..2beb6bb974 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx@@ -11,6 +11,7 @@ import { Button, CloseButton, Row, Scrollable } from '@platform/ui';import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';import { refreshProjectLibrary, useProjectLibrarySelector, type ProjectSummary } from '@workbench/projects/library';import { importProjectFile, pickProjectFile } from '@workbench/projects/projectFile';+import { describeProjectFileError } from '@workbench/projects/projectFileErrors';import { useNotify } from '@workbench/useNotify';import {useWorkbenchCommands,@@ -113,7 +114,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosreturn;}- notify.error(t('projects.importFailed'), error instanceof Error ? error.message : undefined);+ notify.error(t('projects.importFailed'), describeProjectFileError(error, t));}}, [notify, onClose, persistence, projects, t]);diff --git a/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.test.tsnew file mode 100644index 0000000000..0be08d668c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts@@ -0,0 +1,138 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as coversModule from './covers';++/**+ * The cover index: a per-user blob that lets the library grid show thumbnails+ * without fetching every project's document. It is an index, not a truth, so+ * every failure here has to degrade to "no cover" rather than to an error.+ */++const api = vi.hoisted(() => {+ const clientState = new Map<string, string>();++ return {+ __clientState: clientState,+ getClientStateValue: vi.fn((key: string) => Promise.resolve(clientState.get(key) ?? null)),+ setClientStateValue: vi.fn((key: string, value: string) => {+ clientState.set(key, value);++ return Promise.resolve();+ }),+ };+});++vi.mock('./api', () => api);++let covers: typeof coversModule;++beforeEach(async () => {+ vi.resetModules();+ api.__clientState.clear();+ api.getClientStateValue.mockClear();+ api.setClientStateValue.mockClear();++ covers = await import('./covers');+});++describe('parseProjectCovers', () => {+ it('reads a well-formed blob', () => {+ expect(covers.parseProjectCovers('{"p1":"a.png"}')).toEqual({ p1: 'a.png' });+ });++ it('treats unreadable or wrongly-shaped blobs as empty', () => {+ expect(covers.parseProjectCovers(null)).toEqual({});+ expect(covers.parseProjectCovers('')).toEqual({});+ expect(covers.parseProjectCovers('not json')).toEqual({});+ expect(covers.parseProjectCovers('[]')).toEqual({});+ expect(covers.parseProjectCovers('"a string"')).toEqual({});+ });++ it('drops entries that are not non-empty strings', () => {+ expect(covers.parseProjectCovers('{"p1":"a.png","p2":7,"p3":null,"p4":""}')).toEqual({ p1: 'a.png' });+ });+});++describe('loadProjectCovers', () => {+ it('reads the index once and shares concurrent calls', async () => {+ api.__clientState.set('webv2:project-covers', '{"p1":"a.png"}');++ await Promise.all([covers.loadProjectCovers(), covers.loadProjectCovers()]);++ expect(api.getClientStateValue).toHaveBeenCalledTimes(1);+ expect(covers.getProjectCoverImageName('p1')).toBe('a.png');+ });++ it('degrades to no covers when the backend is unreachable', async () => {+ api.getClientStateValue.mockRejectedValueOnce(new Error('offline'));++ await expect(covers.loadProjectCovers()).resolves.toBeUndefined();+ expect(covers.getProjectCoverImageName('p1')).toBeUndefined();+ });+});++describe('recordProjectCover', () => {+ it('persists a new cover and reads it back', async () => {+ await covers.loadProjectCovers();+ covers.recordProjectCover('p1', 'a.png');++ expect(covers.getProjectCoverImageName('p1')).toBe('a.png');+ expect(JSON.parse(api.__clientState.get('webv2:project-covers')!)).toEqual({ p1: 'a.png' });+ });++ /** Autosave runs constantly; a cover changes when a generation lands. */+ it('does not write when nothing changed', async () => {+ await covers.loadProjectCovers();+ covers.recordProjectCover('p1', 'a.png');+ api.setClientStateValue.mockClear();+ covers.recordProjectCover('p1', 'a.png');++ expect(api.setClientStateValue).not.toHaveBeenCalled();+ });++ it('clears an entry when a project loses its cover', async () => {+ await covers.loadProjectCovers();+ covers.recordProjectCover('p1', 'a.png');+ covers.recordProjectCover('p1', null);++ expect(covers.getProjectCoverImageName('p1')).toBeUndefined();+ expect(JSON.parse(api.__clientState.get('webv2:project-covers')!)).toEqual({});+ });++ it('notifies subscribers so the library can re-derive', async () => {+ await covers.loadProjectCovers();++ const listener = vi.fn();+ const unsubscribe = covers.subscribeProjectCovers(listener);++ covers.recordProjectCover('p1', 'a.png');+ unsubscribe();+ covers.recordProjectCover('p2', 'b.png');++ expect(listener).toHaveBeenCalledTimes(1);+ });++ it('survives a failed write without throwing at the caller', async () => {+ await covers.loadProjectCovers();+ api.setClientStateValue.mockRejectedValueOnce(new Error('offline'));++ expect(() => covers.recordProjectCover('p1', 'a.png')).not.toThrow();+ expect(covers.getProjectCoverImageName('p1')).toBe('a.png');+ });+});++describe('forgetProjectCover', () => {+ it('drops a deleted project so the blob does not accumulate dead ids', async () => {+ await covers.loadProjectCovers();+ covers.recordProjectCover('p1', 'a.png');+ covers.forgetProjectCover('p1');++ expect(JSON.parse(api.__clientState.get('webv2:project-covers')!)).toEqual({});+ });+});++describe('getProjectCoverUrl', () => {+ it('points at the thumbnail route and escapes the name', () => {+ expect(covers.getProjectCoverUrl('a b.png')).toContain('/api/v1/images/i/a%20b.png/thumbnail');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/covers.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.tsnew file mode 100644index 0000000000..6c4776d35f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.ts@@ -0,0 +1,164 @@+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+ registerAccountOwnedResource,+ type AccountScope,+} from '@platform/state/accountLifecycle';+import { createExternalStore } from '@platform/state/externalStore';+import { createSingleFlight } from '@platform/state/singleFlight';+import { absolutizeApiUrl } from '@platform/transport/http';++import { getClientStateValue, setClientStateValue } from './api';++/**+ * Which image stands for each project, as an index in the per-user client-state+ * KV — the same place the editor session lives (`session.ts`).+ *+ * The project document is the source of truth: `selectCoverImageName` derives a+ * cover from the newest result or the top-most canvas layer, and an `.invk`+ * carries those bytes as its `cover` entry. But the library grid lists projects+ * from `GET /projects`, which returns summaries with no document — deriving a+ * cover there would mean fetching every project's document to render a page of+ * thumbnails. So the answer is written down once, when a project is saved or+ * imported, and read back as one small blob.+ *+ * Being an index and not a truth, it is allowed to be stale or incomplete. A+ * project saved by a build without this has no entry and shows the folder glyph,+ * which is also what a project that has produced nothing shows — the absence is+ * already a state `ProjectCover` handles.+ *+ * Writes are skipped when the value has not changed, which is almost always: a+ * cover changes when a generation lands, not on every autosave.+ */++export const PROJECT_COVERS_KEY = 'webv2:project-covers';++/** Cap on tracked projects, so a long-lived account cannot grow the blob without bound. */+const MAX_TRACKED_COVERS = 500;++interface ProjectCoversSnapshot {+ /** Project id to the server image name of its cover. */+ coverImageNames: Record<string, string>;+ isLoaded: boolean;+}++const EMPTY: ProjectCoversSnapshot = { coverImageNames: {}, isLoaded: false };+const store = createExternalStore<ProjectCoversSnapshot>(EMPTY);++registerAccountOwnedResource({+ clear: () => {+ store.setSnapshot(EMPTY);+ },+ name: 'project-covers',+});++export const parseProjectCovers = (raw: string | null): Record<string, string> => {+ if (!raw) {+ return {};+ }++ try {+ const parsed: unknown = JSON.parse(raw);++ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ return {};+ }++ return Object.fromEntries(+ Object.entries(parsed).filter(+ (entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1] !== ''+ )+ );+ } catch {+ return {};+ }+};++const persist = (coverImageNames: Record<string, string>, owner: AccountScope): void => {+ void setClientStateValue(PROJECT_COVERS_KEY, JSON.stringify(coverImageNames), owner.signal).catch(() => {+ // A cover is a thumbnail on a card. Losing the write costs a glyph until+ // the next save, which is not worth surfacing to anyone.+ });+};++const loadFlight = createSingleFlight<void>();++/** Fetch the index once per account scope; concurrent calls share the request. */+export const loadProjectCovers = (): Promise<void> => {+ const owner = captureAccountScope();++ return loadFlight.run(`project-covers:${owner.epoch}`, async () => {+ let raw: string | null = null;++ try {+ raw = await getClientStateValue(PROJECT_COVERS_KEY, owner.signal);+ } catch {+ // Treated as "no covers yet" — see the module docblock.+ }++ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ store.setSnapshot({ coverImageNames: parseProjectCovers(raw), isLoaded: true });+ });+};++export const getProjectCoverImageName = (projectId: string): string | undefined =>+ store.getSnapshot().coverImageNames[projectId];++export const subscribeProjectCovers = store.subscribe;++/**+ * Record (or clear) a project's cover. A no-op when nothing changed, which is+ * the common case on autosave.+ */+export const recordProjectCover = (+ projectId: string,+ coverImageName: string | null,+ owner: AccountScope = captureAccountScope()+): void => {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ const { coverImageNames } = store.getSnapshot();++ if ((coverImageNames[projectId] ?? null) === coverImageName) {+ return;+ }++ const next = { ...coverImageNames };++ if (coverImageName === null) {+ delete next[projectId];+ } else {+ next[projectId] = coverImageName;+ }++ const entries = Object.entries(next);+ const bounded = entries.length > MAX_TRACKED_COVERS ? Object.fromEntries(entries.slice(-MAX_TRACKED_COVERS)) : next;++ store.setSnapshot({ coverImageNames: bounded, isLoaded: true });+ persist(bounded, owner);+};++/** Drop a deleted project's entry so the blob does not accumulate dead ids. */+export const forgetProjectCover = (projectId: string, owner: AccountScope = captureAccountScope()): void => {+ recordProjectCover(projectId, null, owner);+};++/**+ * Thumbnail URL for a cover image name. Built here rather than imported from+ * `@features/gallery/core/imagePaths`, which is private to that feature; the+ * palette's provider does the same for the same reason.+ */+export const getProjectCoverUrl = (coverImageName: string): string =>+ absolutizeApiUrl(`/api/v1/images/i/${encodeURIComponent(coverImageName)}/thumbnail`);++/** Load the index and report whether it changed anything, for the library's refresh pass. */+export const ensureProjectCoversLoaded = async (owner: AccountScope): Promise<void> => {+ await loadProjectCovers();+ assertAccountScopeCurrent(owner);+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.tsnew file mode 100644index 0000000000..21d9c6c18d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';++import { binaryEntry, readArchive, readEntryText, textEntry, writeArchive } from './archive';+import { InvkFormatError } from './format';++const toBytes = async (blob: Blob): Promise<Uint8Array> => new Uint8Array(await blob.arrayBuffer());++describe('writeArchive / readArchive', () => {+ it('round-trips text and binary entries', async () => {+ const pixels = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 3, 255]);+ const blob = await writeArchive(+ new Map([+ ['manifest.json', textEntry('{"version":2}')],+ ['images/a.png', binaryEntry(pixels)],+ ])+ );++ const entries = await readArchive(await toBytes(blob));++ expect([...entries.keys()].sort()).toEqual(['images/a.png', 'manifest.json']);+ expect(readEntryText(entries.get('manifest.json')!)).toBe('{"version":2}');+ expect([...entries.get('images/a.png')!]).toEqual([...pixels]);+ });++ 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));++ expect(readEntryText(entries.get('project.json')!)).toBe('{"name":"プロジェクト — 1"}');+ });++ it('actually compresses repetitive text', async () => {+ const repetitive = JSON.stringify({+ layers: Array.from({ length: 500 }, (_, index) => ({ id: `layer-${index}` })),+ });+ const blob = await writeArchive(new Map([['project.json', textEntry(repetitive)]]));++ expect(blob.size).toBeLessThan(repetitive.length / 2);+ });++ it('drops directory records', async () => {+ const blob = await writeArchive(+ new Map([+ ['images/a.png', binaryEntry(new Uint8Array([1]))],+ ['images/b.png', binaryEntry(new Uint8Array([2]))],+ ])+ );++ const entries = await readArchive(await toBytes(blob));++ expect([...entries.keys()].sort()).toEqual(['images/a.png', 'images/b.png']);+ });++ it('reports a non-ZIP as not a project', async () => {+ await expect(readArchive(new TextEncoder().encode('this is not a zip'))).rejects.toMatchObject({+ reason: 'not-a-project',+ });+ });++ it('reports an oversized input rather than expanding it', async () => {+ const oversized = { byteLength: 5 * 1024 * 1024 * 1024 } as Uint8Array;++ await expect(readArchive(oversized)).rejects.toBeInstanceOf(InvkFormatError);+ await expect(readArchive(oversized)).rejects.toMatchObject({ reason: 'too-large' });+ });++ it('refuses to write past the archive ceiling', async () => {+ const oversized = new Map([['images/huge.png', { bytes: { byteLength: 5 * 1024 * 1024 * 1024 }, kind: 'binary' }]]);++ await expect(writeArchive(oversized as never)).rejects.toMatchObject({ reason: 'too-large' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.tsnew file mode 100644index 0000000000..dae9a55ffa--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts@@ -0,0 +1,141 @@+import { INVK_MIME_TYPE, InvkFormatError } from './format';++/**+ * The ZIP seam. The only module in the app that knows `.invk` is a ZIP, and the+ * only one that imports fflate.+ *+ * fflate is loaded with `await import()` at call time, exactly as `psdExport.ts`+ * loads ag-psd and `wildcardFiles.ts` loads `yaml`. Reading or writing a project+ * file is a deliberate, occasional act; the bytes that make it possible have no+ * business in the graph a person downloads to look at their projects. The+ * architecture budget enforces this — a new package appearing in a route's+ * initial chunk fails the gate on the source-owner set alone, before anyone+ * looks at kilobytes.+ *+ * ### Compression+ *+ * JSON entries are deflated; image entries are stored. Layer bitmaps and+ * generated results are already PNG or WEBP, so deflating them spends CPU+ * proportional to the archive to save a fraction of a percent. The project+ * document, by contrast, is repetitive JSON that routinely compresses tenfold.+ *+ * ### Guards+ *+ * Both directions are bounded. An `.invk` is a file someone was handed, and an+ * unbounded `unzip` on a hostile one is a way to be handed an out-of-memory+ * crash instead of an error message.+ */++/**+ * Ceiling for a single archive, in either direction. Large enough for a real+ * project with hundreds of full-resolution layers; small enough that a+ * malicious file fails fast rather than exhausting the tab.+ */+export const INVK_MAX_ARCHIVE_BYTES = 4 * 1024 * 1024 * 1024;++/** Ceiling on entry count, which bounds the cost of building the entry map. */+export const INVK_MAX_ENTRIES = 20_000;++/** Deflate level for text entries. 6 is fflate's default: the usual ratio/speed knee. */+const TEXT_DEFLATE_LEVEL = 6;++export interface InvkArchiveEntry {+ bytes: Uint8Array;+ /** Text entries are deflated; binary entries are stored. */+ kind: 'text' | 'binary';+}++export type InvkArchiveEntries = ReadonlyMap<string, InvkArchiveEntry>;++export const textEntry = (value: string): InvkArchiveEntry => ({+ bytes: new TextEncoder().encode(value),+ kind: 'text',+});++export const binaryEntry = (bytes: Uint8Array): InvkArchiveEntry => ({ bytes, kind: 'binary' });++export const readEntryText = (bytes: Uint8Array): string => new TextDecoder().decode(bytes);++/** Pack entries into a ZIP blob. Rejects with {@link InvkFormatError} past the size ceiling. */+export const writeArchive = async (entries: InvkArchiveEntries): Promise<Blob> => {+ let total = 0;++ for (const entry of entries.values()) {+ total += entry.bytes.byteLength;+ }++ if (total > INVK_MAX_ARCHIVE_BYTES) {+ throw new InvkFormatError('too-large', `Project archive would be ${total} bytes.`);+ }++ const { zip } = await import('fflate');+ const zippable: Record<string, [Uint8Array, { level: 0 | 6 }]> = {};++ for (const [path, entry] of entries) {+ zippable[path] = [entry.bytes, { level: entry.kind === 'text' ? TEXT_DEFLATE_LEVEL : 0 }];+ }++ const packed = await new Promise<Uint8Array>((resolve, reject) => {+ zip(zippable, (error, data) => {+ if (error) {+ reject(error);++ return;+ }++ resolve(data);+ });+ });++ return new Blob([packed as BlobPart], { type: INVK_MIME_TYPE });+};++/**+ * Expand a ZIP into its entries. Anything that is not a readable ZIP surfaces as+ * `not-a-project` rather than an fflate error, because from the caller's side+ * "you picked the wrong file" and "this ZIP has a bad central directory" are the+ * same event.+ */+export const readArchive = async (bytes: Uint8Array): Promise<Map<string, Uint8Array>> => {+ if (bytes.byteLength > INVK_MAX_ARCHIVE_BYTES) {+ throw new InvkFormatError('too-large', `Project archive is ${bytes.byteLength} bytes.`);+ }++ const { unzip } = await import('fflate');+ const expanded = await new Promise<Record<string, Uint8Array>>((resolve, reject) => {+ unzip(bytes, (error, data) => {+ if (error) {+ reject(new InvkFormatError('not-a-project', error.message));++ return;+ }++ resolve(data);+ });+ });++ const entries = new Map<string, Uint8Array>();+ let total = 0;++ for (const [path, entry] of Object.entries(expanded)) {+ // Directory records come through as zero-length entries; they carry nothing+ // and only inflate the count toward the guard.+ if (path.endsWith('/')) {+ continue;+ }++ if (entries.size >= INVK_MAX_ENTRIES) {+ throw new InvkFormatError('too-large', `Project archive holds more than ${INVK_MAX_ENTRIES} entries.`);+ }++ total += entry.byteLength;++ if (total > INVK_MAX_ARCHIVE_BYTES) {+ throw new InvkFormatError('too-large', `Project archive expands past ${INVK_MAX_ARCHIVE_BYTES} bytes.`);+ }++ entries.set(path, entry);+ }++ return entries;+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.tsnew file mode 100644index 0000000000..967a595f23--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it, vi } from 'vitest';++import { readArchive, readEntryText } from './archive';+import { executeInvkExport, planInvkExport } from './exportProject';+import { INVK_DOCUMENT_ENTRY, INVK_MANIFEST_ENTRY } from './format';++const imageRef = (imageName: string) => ({ height: 64, imageName, width: 64 });++const projectDocument = (): Record<string, unknown> => ({+ canvas: {+ document: {+ layers: [+ { id: 'l1', source: { image: imageRef('live-a.png'), type: 'image' } },+ { id: 'l2', source: { bitmap: imageRef('live-b.png'), type: 'paint' } },+ ],+ },+ snapshots: [{ document: { layers: [{ id: 'old', source: { image: imageRef('history.png'), type: 'image' } }] } }],+ },+ id: 'project-1',+ layout: {},+ name: 'My project',+ queue: { items: [{ snapshot: { canvas: { document: { layers: [{ source: { image: imageRef('q.png') } }] } } } }] },+});++const planInput = {+ appVersion: '7.0',+ createdAt: '2026-08-04T00:00:00.000Z',+ name: 'My project',+ projectDocument: projectDocument(),+};++describe('planInvkExport', () => {+ it('bundles the live document and nothing from history', () => {+ expect(planInvkExport(planInput).imageNames).toEqual(['live-a.png', 'live-b.png']);+ });++ it('names the file from the project and records the source project id', () => {+ const plan = planInvkExport(planInput);++ expect(plan.fileName).toBe('My project.invk');+ expect(plan.manifestInput.sourceProjectId).toBe('project-1');+ });++ it('picks the top-most canvas layer as the cover when nothing has been generated', () => {+ expect(planInvkExport(planInput).coverImageName).toBe('live-a.png');+ });++ it('is pure — the same input yields the same plan', () => {+ expect(planInvkExport(planInput)).toEqual(planInvkExport(planInput));+ });++ it('omits the source project id when the document has none', () => {+ const plan = planInvkExport({ ...planInput, projectDocument: { canvas: {}, layout: {}, name: 'x' } });++ expect(plan.manifestInput.sourceProjectId).toBeUndefined();+ expect(plan.imageNames).toEqual([]);+ });+});++describe('executeInvkExport', () => {+ const bytesFor = (imageName: string) => new Uint8Array([...imageName].map((character) => character.codePointAt(0)!));++ it('writes a readable archive holding the manifest, document, images and cover', async () => {+ const download = vi.fn();+ const result = await executeInvkExport(planInvkExport(planInput), {+ download,+ fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),+ fetchImageThumbnail: () =>+ Promise.resolve({ bytes: new Uint8Array([1, 2, 3]), contentType: 'image/webp;charset=binary' }),+ });++ expect(result).toEqual({ bundledCount: 2, missingImageNames: [] });+ expect(download).toHaveBeenCalledTimes(1);++ const [blob, fileName] = download.mock.calls[0]! as [Blob, string];++ expect(fileName).toBe('My project.invk');++ const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));++ expect([...entries.keys()].sort()).toEqual([+ 'cover.webp',+ 'images/live-a.png',+ 'images/live-b.png',+ 'manifest.json',+ 'project.json',+ ]);+ expect(JSON.parse(readEntryText(entries.get(INVK_MANIFEST_ENTRY)!))).toMatchObject({+ contents: 'workbench-project',+ cover: 'cover.webp',+ name: 'My project',+ sourceProjectId: 'project-1',+ version: 2,+ });+ expect(JSON.parse(readEntryText(entries.get(INVK_DOCUMENT_ENTRY)!))).toEqual(projectDocument());+ });++ it('skips an image the server will not serve rather than failing the export', async () => {+ const download = vi.fn();+ const result = await executeInvkExport(planInvkExport(planInput), {+ download,+ fetchImageBytes: (imageName) => Promise.resolve(imageName === 'live-b.png' ? null : bytesFor(imageName)),+ fetchImageThumbnail: () => Promise.resolve(null),+ });++ expect(result).toEqual({ bundledCount: 1, missingImageNames: ['live-b.png'] });+ expect(download).toHaveBeenCalledTimes(1);+ });++ it('treats a thrown image fetch the same as a missing one', async () => {+ const result = await executeInvkExport(planInvkExport(planInput), {+ download: vi.fn(),+ fetchImageBytes: () => Promise.reject(new Error('network')),+ fetchImageThumbnail: () => Promise.reject(new Error('network')),+ });++ expect(result.missingImageNames).toEqual(['live-a.png', 'live-b.png']);+ });++ it('omits the cover entry when there is no cover to fetch', async () => {+ const download = vi.fn();++ await executeInvkExport(planInvkExport({ ...planInput, projectDocument: { id: 'p', layout: {}, name: 'n' } }), {+ download,+ fetchImageBytes: () => Promise.resolve(null),+ fetchImageThumbnail: () => Promise.resolve(null),+ });++ const [blob] = download.mock.calls[0]! as [Blob];+ const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));++ expect([...entries.keys()].sort()).toEqual(['manifest.json', 'project.json']);+ expect(JSON.parse(readEntryText(entries.get(INVK_MANIFEST_ENTRY)!)).cover).toBeUndefined();+ });++ it('reports progress through bundling and packing', async () => {+ const onProgress = vi.fn();++ await executeInvkExport(planInvkExport(planInput), {+ download: vi.fn(),+ fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),+ fetchImageThumbnail: () => Promise.resolve(null),+ onProgress,+ });++ expect(onProgress.mock.calls.map(([progress]) => progress)).toEqual([+ { completed: 1, phase: 'bundling', total: 2 },+ { completed: 2, phase: 'bundling', total: 2 },+ { completed: 2, phase: 'packing', total: 2 },+ ]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.tsnew file mode 100644index 0000000000..b462a2c233--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts@@ -0,0 +1,138 @@+import { mapWithConcurrency } from '@platform/core/concurrency';+import { collectLiveImageRefs, selectCoverImageName } from '@workbench/projects/projectAssets';++import type { InvkArchiveEntry } from './archive';+import type { FetchedThumbnail } from './imageTransport';++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 { buildInvkManifest, toInvkFileName } from './manifest';++/**+ * Writing an `.invk`, split into a pure planner and an impure executor the same+ * 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.+ *+ * {@link executeInvkExport} does the parts that can fail: fetching each image,+ * packing the ZIP, handing it to the browser.+ *+ * An image the server will not serve is logged in the result and skipped, never+ * 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.+ */++/** Simultaneous image fetches. Matches the previous frontend's limit. */+const IMAGE_FETCH_CONCURRENCY = 5;++export interface InvkExportPlan {+ /** Cover image name, or `null` for a project that has produced nothing. */+ coverImageName: string | null;+ /** The project document, already serialized. */+ documentJson: string;+ /** Download file name, including the extension. */+ fileName: string;+ /** Image names to bundle, in a stable order. */+ imageNames: string[];+ manifestInput: { appVersion: string; createdAt: string; name: string; sourceProjectId?: string };+}++export const planInvkExport = (input: {+ appVersion: string;+ createdAt: string;+ name: string;+ projectDocument: Record<string, unknown>;+}): InvkExportPlan => {+ const sourceProjectId = typeof input.projectDocument.id === 'string' ? input.projectDocument.id : undefined;++ 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(),+ manifestInput: {+ appVersion: input.appVersion,+ createdAt: input.createdAt,+ name: input.name,+ ...(sourceProjectId === undefined ? {} : { sourceProjectId }),+ },+ };+};++export interface InvkExportProgress {+ completed: number;+ phase: 'bundling' | 'packing';+ total: number;+}++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>;+ 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[];+}++export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDeps): Promise<InvkExportResult> => {+ const readImage = deps.fetchImageBytes ?? fetchImageBytes;+ const readThumbnail = deps.fetchImageThumbnail ?? fetchImageThumbnail;+ const entries = new Map<string, InvkArchiveEntry>();+ const missingImageNames: string[] = [];+ let bundledCount = 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);++ completed += 1;+ deps.onProgress?.({ completed, phase: 'bundling', total: plan.imageNames.length });++ if (bytes === null) {+ missingImageNames.push(imageName);++ return;+ }++ bundledCount += 1;+ entries.set(`${INVK_IMAGES_PREFIX}${imageName}`, binaryEntry(bytes));+ });++ deps.onProgress?.({ completed: plan.imageNames.length, phase: 'packing', total: plan.imageNames.length });++ const manifest = buildInvkManifest({+ ...plan.manifestInput,+ ...(coverEntryName === undefined ? {} : { cover: coverEntryName }),+ });++ // The manifest is the one entry a person may open by hand, so it is indented.+ entries.set(INVK_MANIFEST_ENTRY, textEntry(JSON.stringify(manifest, null, 2)));+ entries.set(INVK_DOCUMENT_ENTRY, textEntry(plan.documentJson));++ if (cover !== null && coverEntryName !== undefined) {+ entries.set(coverEntryName, binaryEntry(cover.bytes));+ }++ const blob = await writeArchive(entries);++ deps.download(blob, plan.fileName);++ return { bundledCount, missingImageNames: missingImageNames.sort() };+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/format.tsnew file mode 100644index 0000000000..a20a285af4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/format.ts@@ -0,0 +1,46 @@+/**+ * What an `.invk` is called and how reading one can fail.+ *+ * Split from `manifest.ts`, which owns the zod schemas, because these few+ * constants and the error class are needed *eagerly*: the file picker names the+ * extension, and every import call site catches the error to translate its+ * reason. The schema is needed only once someone has actually chosen a file.+ * Keeping them apart is what lets the picker and the toast stay in the+ * Launchpad's initial graph while zod and the parser stay behind the lazy+ * import that pulls in the ZIP codec.+ */++export const INVK_EXTENSION = '.invk';+export const INVK_MIME_TYPE = 'application/zip';+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';+export const INVK_IMAGES_PREFIX = 'images/';++export type InvkFormatReason =+ /** A ZIP, but the manifest is a canvas project written by the previous frontend. */+ | 'legacy-canvas-project'+ /** A ZIP with a manifest we recognize the shape of but not the version. */+ | 'unsupported-version'+ /** Not a project archive at all: not a ZIP, no manifest, or an unreadable one. */+ | 'not-a-project'+ /** A project archive whose payload is missing or will not rehydrate. */+ | 'damaged'+ /** The file is larger than the archive budget, or expands past it. */+ | 'too-large';++/**+ * Every way reading an `.invk` can fail, as a value rather than a message. Call+ * sites map `reason` to a translated string; nothing user-facing is built here.+ */+export class InvkFormatError extends Error {+ readonly reason: InvkFormatReason;++ constructor(reason: InvkFormatReason, message = `Invalid .invk archive: ${reason}`) {+ super(message);+ this.name = 'InvkFormatError';+ this.reason = reason;+ }+}diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/imageTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/imageTransport.tsnew file mode 100644index 0000000000..18914f3fa4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/imageTransport.ts@@ -0,0 +1,156 @@+import { apiFetch, apiFetchJson, apiFetchRaw } from '@platform/transport/http';++/**+ * The image 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+ * `canvas-operations/backend/canvasImages.ts`, which does the same upload for+ * paint layers. That module is private to canvas-operations, and exporting it+ * 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.+ */++const IMAGES_BASE = '/api/v1/images';++/**+ * 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+ * slow lookup cannot stall the whole check.+ */+const EXISTENCE_BATCH_SIZE = 500;++export interface UploadedImage {+ height: number;+ imageName: string;+ width: number;+}++interface ImageDTOSubset {+ height: number;+ image_name: string;+ width: number;+}++/**+ * Which of `imageNames` the server already has. The endpoint silently omits+ * names it cannot serve, which is exactly the answer wanted here: anything+ * missing from the response has to come out of the archive.+ */+export const findExistingImageNames = async (+ imageNames: readonly string[],+ signal?: AbortSignal+): Promise<Set<string>> => {+ const existing = new Set<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);+ }+ }++ return existing;+};++/**+ * 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+ * skipped, and a project that exports every layer but one is far more use than+ * one that refuses to export at all.+ */+export const fetchImageBytes = async (imageName: string, signal?: AbortSignal): Promise<Uint8Array | null> => {+ const response = await apiFetchRaw(`${IMAGES_BASE}/i/${encodeURIComponent(imageName)}/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. */+ contentType: string;+}++/** Thumbnail bytes for the cover entry. `null` when the server will not serve it. */+export const fetchImageThumbnail = async (+ imageName: string,+ signal?: AbortSignal+): Promise<FetchedThumbnail | null> => {+ const response = await apiFetchRaw(`${IMAGES_BASE}/i/${encodeURIComponent(imageName)}/thumbnail`, { signal });++ if (!response.ok) {+ return null;+ }++ return {+ bytes: new Uint8Array(await response.arrayBuffer()),+ contentType: response.headers.get('content-type') ?? 'image/webp',+ };+};++/**+ * Put archived bytes back on the server. The returned name is authoritative and+ * frequently differs from the archived one — the server names images itself —+ * which is why every import ends with a remapping pass.+ */+export const uploadArchiveImage = async (+ bytes: Uint8Array,+ fileName: string,+ options: { contentType?: string; signal?: AbortSignal } = {}+): Promise<UploadedImage> => {+ const query = new URLSearchParams({ image_category: 'other', is_intermediate: 'false' });+ const body = new FormData();++ body.append(+ 'file',+ new File([bytes as BlobPart], fileName, { type: options.contentType || 'application/octet-stream' })+ );++ const response = await apiFetch(`${IMAGES_BASE}/upload?${query.toString()}`, {+ body,+ method: 'POST',+ signal: options.signal,+ });+ const dto = (await response.json()) as ImageDTOSubset;++ return { height: dto.height, imageName: dto.image_name, width: dto.width };+};++const EXTENSION_BY_MIME: Readonly<Record<string, string>> = {+ 'image/jpeg': 'jpg',+ 'image/png': 'png',+ 'image/webp': 'webp',+};++/** Extension for a cover entry, given what the server said it served. */+export const coverExtensionForMime = (contentType: string): string =>+ EXTENSION_BY_MIME[contentType.split(';')[0]!.trim().toLowerCase()] ?? 'png';++const MIME_BY_EXTENSION: Readonly<Record<string, string>> = {+ jpeg: 'image/jpeg',+ jpg: 'image/jpeg',+ png: 'image/png',+ webp: 'image/webp',+};++/** Best guess at a bundled entry's MIME type, from its name. */+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/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.tsnew file mode 100644index 0000000000..a171c38848--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it, vi } from 'vitest';++import { binaryEntry, textEntry, writeArchive } from './archive';+import { InvkFormatError } from './format';+import { readInvkArchive, restoreArchiveImages } from './importProject';++const imageRef = (imageName: string) => ({ height: 64, imageName, width: 64 });++const document = () => ({+ canvas: { document: { layers: [{ id: 'l1', source: { image: imageRef('a.png'), type: 'image' } }] } },+ id: 'project-1',+ layout: {},+ name: 'My project',+});++const manifest = (overrides: Record<string, unknown> = {}) => ({+ appVersion: '7.0',+ contents: 'workbench-project',+ createdAt: '2026-08-04T00:00:00.000Z',+ name: 'My project',+ version: 2,+ ...overrides,+});++const archiveFile = async (entries: Record<string, string | Uint8Array>): Promise<File> => {+ const blob = await writeArchive(+ new Map(+ Object.entries(entries).map(([path, value]) => [+ path,+ typeof value === 'string' ? textEntry(value) : binaryEntry(value),+ ])+ )+ );++ return new File([blob], 'project.invk');+};++const validArchive = (overrides: Record<string, string | Uint8Array> = {}) =>+ archiveFile({+ 'images/a.png': new Uint8Array([1, 2, 3]),+ 'manifest.json': JSON.stringify(manifest()),+ 'project.json': JSON.stringify(document()),+ ...overrides,+ });++describe('readInvkArchive', () => {+ it('returns the manifest, document and bundled images', async () => {+ const contents = await readInvkArchive(await validArchive());++ expect(contents.manifest.name).toBe('My project');+ expect(contents.projectDocument).toEqual(document());+ expect([...contents.images.keys()]).toEqual(['a.png']);+ expect(contents.cover).toBeNull();+ });++ it('resolves the cover entry named by the manifest', async () => {+ const contents = await readInvkArchive(+ await archiveFile({+ 'cover.webp': new Uint8Array([9, 9]),+ 'manifest.json': JSON.stringify(manifest({ cover: 'cover.webp' })),+ 'project.json': JSON.stringify(document()),+ })+ );++ expect(contents.cover).toEqual({ bytes: new Uint8Array([9, 9]), entryName: 'cover.webp' });+ });++ it('refuses a legacy canvas project by name', async () => {+ const file = await archiveFile({+ 'canvas_state.json': '{}',+ 'manifest.json': JSON.stringify({ appVersion: '6.9', createdAt: '', name: 'Canvas', version: 1 }),+ });++ await expect(readInvkArchive(file)).rejects.toMatchObject({ reason: 'legacy-canvas-project' });+ });++ it('refuses an archive with no manifest', async () => {+ await expect(readInvkArchive(await archiveFile({ 'project.json': '{}' }))).rejects.toMatchObject({+ reason: 'not-a-project',+ });+ });++ it('refuses a file that is not a ZIP', async () => {+ await expect(readInvkArchive(new File(['not a zip'], 'project.invk'))).rejects.toMatchObject({+ reason: 'not-a-project',+ });+ });++ it('reports a manifest without a document as damaged', async () => {+ const file = await archiveFile({ 'manifest.json': JSON.stringify(manifest()) });++ await expect(readInvkArchive(file)).rejects.toMatchObject({ reason: 'damaged' });+ });++ it('reports an unparseable document as damaged', async () => {+ const file = await validArchive({ 'project.json': 'not json' });++ await expect(readInvkArchive(file)).rejects.toBeInstanceOf(InvkFormatError);+ await expect(readInvkArchive(file)).rejects.toMatchObject({ reason: 'damaged' });+ });++ it('reports a document that is an array as damaged', async () => {+ await expect(readInvkArchive(await validArchive({ 'project.json': '[]' }))).rejects.toMatchObject({+ reason: 'damaged',+ });+ });+});++describe('restoreArchiveImages', () => {+ const contents = async (overrides: Partial<Awaited<ReturnType<typeof readInvkArchive>>> = {}) => ({+ ...(await readInvkArchive(await validArchive())),+ ...overrides,+ });++ it('uploads only what the server is missing', async () => {+ const upload = vi.fn((_bytes: Uint8Array, fileName: string) =>+ Promise.resolve({ height: 1, imageName: fileName, width: 1 })+ );++ const result = await restoreArchiveImages(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);+ });++ it('records the rename when the server assigns a different name', async () => {+ const result = await restoreArchiveImages(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.uploadedCount).toBe(1);+ });++ it('records no rename when the server keeps the name', async () => {+ const result = await restoreArchiveImages(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.uploadedCount).toBe(1);+ });++ it('reports a reference the archive never carried as dangling', async () => {+ const missing = await contents();++ missing.images.delete('a.png');++ const result = await restoreArchiveImages(missing, {+ findExistingImageNames: () => Promise.resolve(new Set()),+ uploadArchiveImage: () => Promise.reject(new Error('should not be called')),+ });++ expect(result.danglingImageNames).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(), {+ findExistingImageNames: () => Promise.resolve(new Set()),+ uploadArchiveImage: () => Promise.reject(new Error('upload failed')),+ });++ expect(result.danglingImageNames).toEqual(['a.png']);+ expect(result.uploadedCount).toBe(0);+ });++ it('uploads the cover alongside and returns its server name', 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 }));++ const result = await restoreArchiveImages(withCover, {+ findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),+ uploadArchiveImage: upload,+ });++ expect(result.coverImageName).toBe('server-cover.png');+ expect(upload).toHaveBeenCalledWith(new Uint8Array([9]), 'cover.webp', {+ contentType: 'image/webp',+ signal: undefined,+ });+ });++ 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, {+ findExistingImageNames: () => Promise.resolve(new Set(['a.png'])),+ uploadArchiveImage: () => Promise.reject(new Error('nope')),+ });++ expect(result.coverImageName).toBeNull();+ expect(result.danglingImageNames).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsnew file mode 100644index 0000000000..97b7121bf1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -0,0 +1,188 @@+import { mapWithConcurrency } from '@platform/core/concurrency';+import { collectLiveImageRefs } from '@workbench/projects/projectAssets';++import type { UploadedImage } from './imageTransport';+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 { parseInvkManifest } from './manifest';++/**+ * Reading an `.invk` back, in two steps a caller can put a decision between.+ *+ * {@link readInvkArchive} is pure inspection: unpack, validate the manifest,+ * parse the document, index the bundled bytes. It touches no network and mutates+ * 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,+ * 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.+ *+ * Deduplication is what makes re-importing cheap and makes importing onto the+ * machine that exported it nearly free: an image already on the server is never+ * uploaded twice, so nothing accumulates.+ */++/** Simultaneous uploads. Matches the previous frontend's limit. */+const IMAGE_UPLOAD_CONCURRENCY = 5;++export interface InvkArchiveContents {+ /** Bundled preview bytes and the entry they came from, when the archive has one. */+ cover: { bytes: Uint8Array; entryName: string } | null;+ /** Bundled image bytes, keyed by the image name the exporting server used. */+ images: Map<string, Uint8Array>;+ manifest: InvkManifest;+ projectDocument: Record<string, unknown>;+}++const parseDocumentEntry = (bytes: Uint8Array): Record<string, unknown> => {+ let parsed: unknown;++ try {+ parsed = JSON.parse(readEntryText(bytes));+ } catch {+ throw new InvkFormatError('damaged', `${INVK_DOCUMENT_ENTRY} is not valid JSON.`);+ }++ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ throw new InvkFormatError('damaged', `${INVK_DOCUMENT_ENTRY} is not a project document.`);+ }++ return parsed as Record<string, unknown>;+};++/** Unpack and validate an archive. Throws {@link InvkFormatError} and nothing else. */+export const readInvkArchive = async (file: File): Promise<InvkArchiveContents> => {+ const entries = await readArchive(new Uint8Array(await file.arrayBuffer()));+ const manifestEntry = entries.get(INVK_MANIFEST_ENTRY);++ if (!manifestEntry) {+ throw new InvkFormatError('not-a-project', `Archive has no ${INVK_MANIFEST_ENTRY}.`);+ }++ let manifestData: unknown;++ try {+ manifestData = JSON.parse(readEntryText(manifestEntry));+ } catch {+ throw new InvkFormatError('not-a-project', `${INVK_MANIFEST_ENTRY} is not valid JSON.`);+ }++ const manifest = parseInvkManifest(manifestData);+ const documentEntry = entries.get(INVK_DOCUMENT_ENTRY);++ if (!documentEntry) {+ throw new InvkFormatError('damaged', `Archive has no ${INVK_DOCUMENT_ENTRY}.`);+ }++ const images = 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);+ }+ }++ const coverBytes = manifest.cover === undefined ? undefined : entries.get(manifest.cover);++ return {+ cover: coverBytes === undefined ? null : { bytes: coverBytes, entryName: manifest.cover! },+ images,+ manifest,+ projectDocument: parseDocumentEntry(documentEntry),+ };+};++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>;+ /** The uploaded cover's server name, when the archive carried one. */+ coverImageName: string | null;+ /** Images uploaded from the archive. */+ uploadedCount: number;+}++export interface RestoreImagesDeps {+ findExistingImageNames?: (imageNames: readonly string[], signal?: AbortSignal) => Promise<Set<string>>;+ onProgress?: (progress: { completed: number; total: number }) => void;+ signal?: AbortSignal;+ uploadArchiveImage?: (+ bytes: Uint8Array,+ fileName: string,+ options?: { contentType?: string; signal?: AbortSignal }+ ) => Promise<UploadedImage>;+}++/**+ * 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+ * 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 (+ 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>();++ // 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;+ let completed = 0;+ let uploadedCount = 0;++ const coverImageName =+ contents.cover === null+ ? null+ : await upload(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: uploadable.length + coverTotal });+ }++ await mapWithConcurrency(uploadable, IMAGE_UPLOAD_CONCURRENCY, async (imageName) => {+ const bytes = contents.images.get(imageName)!;++ try {+ const uploaded = await upload(bytes, imageName, {+ contentType: mimeForEntryName(imageName),+ signal: deps.signal,+ });++ uploadedCount += 1;++ if (uploaded.imageName !== imageName) {+ mapping.set(imageName, uploaded.imageName);+ }+ } 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);+ }++ completed += 1;+ deps.onProgress?.({ completed, total: uploadable.length + coverTotal });+ });++ return { coverImageName, danglingImageNames: danglingImageNames.sort(), mapping, uploadedCount };+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.tsnew file mode 100644index 0000000000..6dff9c3ab8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest';++import { InvkFormatError } from './format';+import { buildInvkManifest, parseInvkManifest, toInvkFileName } from './manifest';++const v2 = {+ appVersion: '7.0',+ contents: 'workbench-project',+ createdAt: '2026-08-04T00:00:00.000Z',+ name: 'My project',+ version: 2,+};++const expectReason = (data: unknown, reason: string): void => {+ try {+ parseInvkManifest(data);+ expect.unreachable('parseInvkManifest should have thrown');+ } catch (error) {+ expect(error).toBeInstanceOf(InvkFormatError);+ expect((error as InvkFormatError).reason).toBe(reason);+ }+};++describe('parseInvkManifest', () => {+ it('accepts a v2 manifest', () => {+ expect(parseInvkManifest(v2)).toEqual(v2);+ });++ it('keeps the optional cover and source project id', () => {+ expect(parseInvkManifest({ ...v2, cover: 'cover.webp', sourceProjectId: 'project-1' })).toMatchObject({+ cover: 'cover.webp',+ sourceProjectId: 'project-1',+ });+ });++ /** The whole reason the schema is a union: naming what a v1 archive is. */+ it('names a legacy canvas project instead of dumping schema issues', () => {+ expectReason(+ { appVersion: '6.9', createdAt: '2026-04-14T00:00:00.000Z', name: 'Canvas', version: 1 },+ 'legacy-canvas-project'+ );+ });++ it('reports an unknown numeric version as unsupported', () => {+ expectReason({ ...v2, version: 3 }, 'unsupported-version');+ });++ it('rejects a manifest missing the v2 discriminator', () => {+ expectReason({ appVersion: '7.0', createdAt: '', name: 'x', version: 2 }, 'unsupported-version');+ });++ it('rejects junk as not a project', () => {+ expectReason(null, 'not-a-project');+ expectReason({}, 'not-a-project');+ expectReason('a string', 'not-a-project');+ });+});++describe('buildInvkManifest', () => {+ it('omits the optional keys rather than writing undefined into the JSON', () => {+ const manifest = buildInvkManifest({ appVersion: '7.0', createdAt: v2.createdAt, name: 'My project' });++ expect(Object.keys(manifest).sort()).toEqual(['appVersion', 'contents', 'createdAt', 'name', 'version']);+ });++ it('round-trips through parse', () => {+ const manifest = buildInvkManifest({+ appVersion: '7.0',+ cover: 'cover.webp',+ createdAt: v2.createdAt,+ name: 'My project',+ sourceProjectId: 'project-1',+ });++ expect(parseInvkManifest(JSON.parse(JSON.stringify(manifest)))).toEqual(manifest);+ });+});++describe('toInvkFileName', () => {+ it('replaces characters filesystems reject', () => {+ expect(toInvkFileName('a/b\\c:d*e?f"g<h>i|j')).toBe('a_b_c_d_e_f_g_h_i_j.invk');+ });++ it('keeps non-Latin names intact', () => {+ expect(toInvkFileName('プロジェクト')).toBe('プロジェクト.invk');+ });++ it('keeps spaces and hyphens', () => {+ expect(toInvkFileName('My cool - project')).toBe('My cool - project.invk');+ });++ it('strips leading and trailing dots', () => {+ expect(toInvkFileName('..hidden..')).toBe('hidden.invk');+ });++ it('falls back for a name that sanitizes to nothing', () => {+ expect(toInvkFileName(' ')).toBe('project.invk');+ expect(toInvkFileName('...')).toBe('project.invk');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.tsnew file mode 100644index 0000000000..fa296992b7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/manifest.ts@@ -0,0 +1,111 @@+import { z } from 'zod';++import { INVK_EXTENSION, INVK_VERSION, InvkFormatError } from './format';++/**+ * The `.invk` manifest: what an archive is, before anything reads what is in it.+ *+ * `.invk` is not new. The canvas project files written by the previous frontend+ * are ZIPs with this same root `manifest.json` — `{version, appVersion,+ * createdAt, name}` — alongside an `images/` folder keyed by backend image name.+ * That container is kept verbatim. Version 2 changes only the payload: where a+ * v1 archive carried four canvas-shaped state files, a v2 archive carries one+ * `project.json` holding the whole workbench project document, plus an optional+ * cover.+ *+ * ```+ * <name>.invk+ * ├── manifest.json this file's shape+ * ├── project.json the project document (v2 only)+ * ├── cover.<ext> optional preview; the entry name is recorded here+ * └── images/<image_name> referenced bytes, named exactly as the server names them+ * ```+ *+ * Parsing is a discriminated union rather than a strict `z.literal(2)` so that a+ * v1 archive can be recognized and refused *as what it is*. "This is a canvas+ * project from an earlier version" is a sentence someone can act on; a zod issue+ * list is not. The legacy reader is the mirror image — it pins `version: 1` and+ * will refuse a v2 archive, which is correct and needs no change there.+ *+ * The names and the error class live in `./format`, which carries no zod, so+ * that the file picker and the error toast do not drag the schema into the+ * Launchpad's initial bundle.+ */++const zManifestV1 = z.object({+ appVersion: z.string(),+ createdAt: z.string(),+ name: z.string(),+ version: z.literal(1),+});++const zManifestV2 = z.object({+ appVersion: z.string(),+ /** Discriminates a workbench project from whatever a later version may carry. */+ contents: z.literal('workbench-project'),+ /** Entry path of the preview image, when the archive carries one. */+ cover: z.string().optional(),+ createdAt: z.string(),+ name: z.string(),+ /** The project this was exported from. Informational — import always mints a fresh id. */+ sourceProjectId: z.string().optional(),+ version: z.literal(2),+});++const zManifest = z.discriminatedUnion('version', [zManifestV1, zManifestV2]);++export type InvkManifest = z.infer<typeof zManifestV2>;++/**+ * Accepts a v2 manifest; throws {@link InvkFormatError} for anything else.+ * Never returns a v1 manifest — recognizing v1 exists only to name the refusal.+ */+export const parseInvkManifest = (data: unknown): InvkManifest => {+ const parsed = zManifest.safeParse(data);++ if (!parsed.success) {+ const version = (data as { version?: unknown } | null)?.version;++ throw new InvkFormatError(typeof version === 'number' ? 'unsupported-version' : 'not-a-project');+ }++ if (parsed.data.version === 1) {+ throw new InvkFormatError('legacy-canvas-project');+ }++ return parsed.data;+};++export const buildInvkManifest = (input: {+ appVersion: string;+ cover?: string;+ createdAt: string;+ name: string;+ sourceProjectId?: string;+}): InvkManifest => ({+ appVersion: input.appVersion,+ contents: 'workbench-project',+ createdAt: input.createdAt,+ name: input.name,+ version: INVK_VERSION,+ ...(input.cover === undefined ? {} : { cover: input.cover }),+ ...(input.sourceProjectId === undefined ? {} : { sourceProjectId: input.sourceProjectId }),+});++/**+ * File name for the download. Replaces what filesystems reject and drops+ * control/format characters, but leaves the rest of unicode alone — a project+ * named in a non-Latin script should not export as `project.invk`.+ */+export const toInvkFileName = (projectName: string): string => {+ const trimmed = projectName+ .replaceAll(/["*/:<>?\\|]/gu, '_')+ .replaceAll(/\p{C}/gu, '')+ .trim()+ // Windows cannot open a name ending in a dot, and a leading one hides the file.+ .replace(/\.+$/u, '')+ .replace(/^\.+/u, '')+ .trim();++ return `${trimmed || 'project'}${INVK_EXTENSION}`;+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex d5a924af92..6969a83e81 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -17,6 +17,13 @@ import {updateProject as apiUpdateProject,type ProjectSummaryDTO,} from './api';+import {+ forgetProjectCover,+ getProjectCoverImageName,+ getProjectCoverUrl,+ loadProjectCovers,+ subscribeProjectCovers,+} from './covers';import { createProjectId } from './ids';/**@@ -38,10 +45,10 @@ export interface ProjectSummary {createdAt: string;updatedAt: string;/**- * Thumbnail for the library grid. Nothing populates this yet — covers land- * with the `.invk` project-file work. Consumers must already handle its- * absence, which is also the permanent state for a project that has produced- * no images.+ * Thumbnail for the library grid, resolved from the per-user cover index+ * (`covers.ts`) rather than from the project document, which listings do not+ * carry. Absent for a project that has produced no images, and for one last+ * saved by a build that did not record covers.*/coverUrl?: string;}@@ -64,12 +71,44 @@ registerAccountOwnedResource({name: 'project-library',});-const toSummary = (dto: ProjectSummaryDTO): ProjectSummary => ({- createdAt: normalizeServerTimestamp(dto.created_at),- id: dto.project_id,- name: dto.name,- revision: dto.revision,- updatedAt: normalizeServerTimestamp(dto.updated_at),+const withCover = <T extends { id: string }>(summary: T): T & { coverUrl?: string } => {+ const coverImageName = getProjectCoverImageName(summary.id);++ return coverImageName === undefined ? summary : { ...summary, coverUrl: getProjectCoverUrl(coverImageName) };+};++const toSummary = (dto: ProjectSummaryDTO): ProjectSummary =>+ withCover({+ createdAt: normalizeServerTimestamp(dto.created_at),+ id: dto.project_id,+ name: dto.name,+ revision: dto.revision,+ updatedAt: normalizeServerTimestamp(dto.updated_at),+ });++/**+ * The cover index loads and updates independently of the listing, so summaries+ * are re-derived whenever it changes. Without this a cover recorded after the+ * library rendered — the first generation in a new project — would not appear+ * until the next refresh.+ */+subscribeProjectCovers(() => {+ const { status, summaries } = store.getSnapshot();++ if (status !== 'ready') {+ return;+ }++ const next = summaries.map((summary) => {+ const coverImageName = getProjectCoverImageName(summary.id);+ const coverUrl = coverImageName === undefined ? undefined : getProjectCoverUrl(coverImageName);++ return coverUrl === summary.coverUrl ? summary : { ...summary, coverUrl };+ });++ if (next.some((summary, index) => summary !== summaries[index])) {+ store.patchSnapshot({ summaries: next });+ }});/** Most recently edited first — the order Home and the Open dialog present. */@@ -99,8 +138,11 @@ export const refreshProjectLibrary = (): Promise<void> =>const owner = captureAccountScope();return refreshFlight.run(`project-library:${owner.epoch}`, () =>- listProjects(owner.signal)- .then((dtos) => {+ // Covers resolve alongside the listing rather than after it: they come+ // from a different store, and seeding without them would show a grid of+ // glyphs that fills in a moment later.+ Promise.all([listProjects(owner.signal), loadProjectCovers()])+ .then(([dtos]) => {seedProjectLibrary(dtos, owner);}).catch((error: unknown) => {@@ -132,13 +174,13 @@ export const upsertProjectSummary = (const { summaries } = store.getSnapshot();const existing = summaries.find((summary) => summary.id === entry.id);const updatedAt = new Date().toISOString();- const next: ProjectSummary = {+ const next: ProjectSummary = withCover({createdAt: existing?.createdAt ?? updatedAt,id: entry.id,name: entry.name,revision: entry.revision ?? existing?.revision ?? 0,updatedAt,- };+ });store.patchSnapshot({status: 'ready',@@ -152,6 +194,7 @@ export const deleteLibraryProject = async (projectId: string): Promise<void> =>await apiDeleteProject(projectId, owner.signal);assertAccountScopeCurrent(owner);+ forgetProjectCover(projectId, owner);store.patchSnapshot({ summaries: store.getSnapshot().summaries.filter((summary) => summary.id !== projectId) });};diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsnew file mode 100644index 0000000000..442e98955d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -0,0 +1,187 @@+import { describe, expect, it } from 'vitest';++import { collectLiveImageRefs, remapImageRefs, 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.+ */++const imageRef = (imageName: string) => ({ height: 512, imageName, width: 512 });++const imageLayer = (id: string, imageName: string) => ({+ id,+ name: id,+ source: { image: imageRef(imageName), type: 'image' },+ type: 'raster',+});++const paintLayer = (id: string, imageName: string | null) => ({+ id,+ name: id,+ source: { bitmap: imageName ? imageRef(imageName) : null, type: 'paint' },+ type: 'raster',+});++const galleryInstance = (recentImageNames: string[]) => ({+ 'gallery-1': {+ state: {+ values: { recentImages: recentImageNames.map((imageName) => ({ ...imageRef(imageName), imageUrl: '' })) },+ },+ typeId: 'gallery',+ },+});++const projectDocument = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({+ canvas: {+ document: { layers: [imageLayer('layer-1', 'live-image.png')], version: 2 },+ snapshots: [{ document: { layers: [imageLayer('layer-old', 'snapshot-image.png')] }, id: 'snap-1' }],+ version: 2,+ },+ events: [{ imageName: 'event-image.png' }],+ graphHistory: [{ document: { nodes: [{ data: { image: { image_name: 'history-image.png' } } }] }, id: 'gh-1' }],+ id: 'project-1',+ layout: {},+ name: 'Project',+ projectGraph: { nodes: [{ data: { inputs: { image: { image_name: 'graph-image.png' } } }, id: 'node-1' }] },+ queue: {+ items: [{ id: 'q-1', snapshot: { canvas: { document: { layers: [imageLayer('l', 'queue-image.png')] } } } }],+ },+ widgetInstances: {+ 'upscale-1': { state: { values: { inputImage: { image_name: 'upscale-input.png' } } }, typeId: 'upscale' },+ },+ ...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'])+ );+ });++ it('leaves history behind — queue snapshots, graph history, events, canvas snapshots', () => {+ const collected = collectLiveImageRefs(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);+ });++ it('leaves the gallery widget recents behind', () => {+ const collected = collectLiveImageRefs(+ projectDocument({ widgetInstances: galleryInstance(['recent-a.png', 'recent-b.png']) })+ );++ expect(collected.has('recent-a.png')).toBe(false);+ });++ it('finds references nested through arrays and mask bitmaps', () => {+ const collected = collectLiveImageRefs(+ projectDocument({+ canvas: {+ document: {+ layers: [+ { id: 'mask-1', mask: { bitmap: imageRef('mask.png'), fill: {} }, type: 'inpaint_mask' },+ {+ id: 'rg-1',+ referenceImages: [{ config: { image: imageRef('reference.png'), type: 'ip_adapter' } }],+ type: 'regional_guidance',+ },+ ],+ },+ },+ })+ );++ expect(collected).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());+ });+});++describe('remapImageRefs', () => {+ it('returns the document unchanged for an empty mapping', () => {+ const document = projectDocument();++ expect(remapImageRefs(document, new Map())).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 } } }[] } };+ };++ 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([+ ['queue-image.png', 'uploaded-queue.png'],+ ['snapshot-image.png', 'uploaded-snapshot.png'],+ ])+ ) as {+ canvas: { snapshots: { document: { layers: { source: { image: { imageName: string } } }[] } }[] };+ queue: {+ items: { snapshot: { canvas: { document: { layers: { source: { image: { imageName: string } } }[] } } } }[];+ };+ };++ expect(remapped.queue.items[0]!.snapshot.canvas.document.layers[0]!.source.image.imageName).toBe(+ 'uploaded-queue.png'+ );+ expect(remapped.canvas.snapshots[0]!.document.layers[0]!.source.image.imageName).toBe('uploaded-snapshot.png');+ });++ 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 } } } }[] };+ };++ 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 {+ canvas: { document: { layers: { source: { image: { imageName: string } } }[] } };+ };++ expect(remapped.canvas.document.layers[0]!.source.image.imageName).toBe('live-image.png');+ });+});++describe('selectCoverImageName', () => {+ it('prefers the newest gallery result', () => {+ expect(+ selectCoverImageName(projectDocument({ widgetInstances: galleryInstance(['newest.png', 'older.png']) }))+ ).toBe('newest.png');+ });++ it('falls back to the top-most canvas layer with pixels', () => {+ expect(selectCoverImageName(projectDocument())).toBe('live-image.png');+ });++ it('skips canvas layers that have no pixels yet', () => {+ expect(+ selectCoverImageName(+ projectDocument({+ canvas: { document: { layers: [paintLayer('empty', null), imageLayer('below', 'below.png')] } },+ })+ )+ ).toBe('below.png');+ });++ it('is null for a project that has produced nothing', () => {+ expect(selectCoverImageName({ canvas: { document: { layers: [] } }, id: 'p', layout: {}, name: 'n' })).toBeNull();+ });++ it('is null for a document missing the canvas entirely', () => {+ expect(selectCoverImageName({ id: 'p', layout: {}, name: 'n' })).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsnew file mode 100644index 0000000000..5e488b89e7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -0,0 +1,210 @@+/**+ * Which images 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+ * enough to autosave, and also what makes a bare document export useless on+ * another install — the names resolve to nothing there. Bundling the bytes into+ * an `.invk` archive means first knowing which names the document actually uses.+ *+ * ### 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.+ *+ * 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+ * fails to resolve on the server and is skipped.+ *+ * ### Collection skips history, remapping does not+ *+ * A project document carries far more than the live document. Every queue entry+ * 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+ * 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+ * 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. */+const IMAGE_NAME_KEYS = new Set(['imageName', 'image_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']);++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 => {+ if (Array.isArray(node)) {+ for (const item of node) {+ collectFrom(item, names);+ }++ return;+ }++ if (!isRecord(node)) {+ return;+ }++ for (const [key, value] of Object.entries(node)) {+ if (PROJECT_HISTORY_KEYS.has(key)) {+ continue;+ }++ if (IMAGE_NAME_KEYS.has(key) && typeof value === 'string' && value !== '') {+ names.add(value);+ continue;+ }++ collectFrom(value, names);+ }+};++/**+ * 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.+ */+export const collectLiveImageRefs = (projectDocument: Record<string, unknown>): Set<string> => {+ const names = new Set<string>();++ for (const [key, value] of Object.entries(projectDocument)) {+ if (PROJECT_HISTORY_ROOT_KEYS.has(key)) {+ continue;+ }++ collectFrom(value, names);+ }++ return names;+};++const remapNode = (node: unknown, mapping: ReadonlyMap<string, string>): unknown => {+ if (Array.isArray(node)) {+ let hasChanged = false;+ const next = node.map((item) => {+ const mapped = remapNode(item, mapping);++ hasChanged ||= mapped !== item;++ return mapped;+ });++ 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 (IMAGE_NAME_KEYS.has(key) && typeof value === 'string') {+ const replacement = mapping.get(value);++ next[key] = replacement ?? value;+ hasChanged ||= replacement !== undefined && replacement !== value;+ continue;+ }++ const mapped = remapNode(value, mapping);++ next[key] = mapped;+ hasChanged ||= mapped !== value;+ }++ return hasChanged ? next : node;+};++/**+ * 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.+ */+export const remapImageRefs = (+ projectDocument: Record<string, unknown>,+ mapping: ReadonlyMap<string, string>+): Record<string, unknown> =>+ mapping.size === 0 ? projectDocument : (remapNode(projectDocument, mapping) as Record<string, unknown>);++const readGalleryRecentImageName = (projectDocument: Record<string, unknown>): string | null => {+ const instances = projectDocument.widgetInstances;++ if (!isRecord(instances)) {+ return null;+ }++ for (const instance of Object.values(instances)) {+ if (!isRecord(instance) || instance.typeId !== 'gallery' || !isRecord(instance.state)) {+ continue;+ }++ const values = instance.state.values;++ if (!isRecord(values) || !Array.isArray(values.recentImages)) {+ continue;+ }++ // `recentImages` is persisted newest-first and bounded (see+ // `getBoundedRecentImages`), so index 0 is the project's latest result.+ for (const image of values.recentImages) {+ if (isRecord(image) && typeof image.imageName === 'string' && image.imageName !== '') {+ return image.imageName;+ }+ }+ }++ return null;+};++const readTopmostCanvasImageName = (projectDocument: Record<string, unknown>): string | null => {+ const canvas = projectDocument.canvas;++ if (!isRecord(canvas) || !isRecord(canvas.document) || !Array.isArray(canvas.document.layers)) {+ return null;+ }++ // Layer index 0 is the top-most layer, which is the one a person would call+ // "what this project looks like".+ for (const layer of canvas.document.layers) {+ if (!isRecord(layer) || !isRecord(layer.source)) {+ continue;+ }++ const source = layer.source;+ const ref = source.type === 'image' ? source.image : source.type === 'paint' ? source.bitmap : null;++ if (isRecord(ref) && typeof ref.imageName === 'string' && ref.imageName !== '') {+ return ref.imageName;+ }+ }++ return null;+};++/**+ * The image that best stands for this project: its newest generated result,+ * falling back to the top-most canvas layer with pixels. `null` for a project+ * that has neither, which is the permanent state for one that has produced+ * nothing — `ProjectCover` renders a glyph for exactly that case.+ */+export const selectCoverImageName = (projectDocument: Record<string, unknown>): string | null =>+ readGalleryRecentImageName(projectDocument) ?? readTopmostCanvasImageName(projectDocument);diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex cdc55e28d9..9b96a56294 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -5,17 +5,36 @@ import type * as projectFileModule from './projectFile';import type * as persistenceModule from './syncedPersistence';/**- * The portable project file format: versioned envelope, defensive parsing,- * and the import rule that a file can never overwrite an existing project- * because it always lands under a fresh id.+ * The `.invk` workflow end to end: export writes an archive that import reads+ * back, an imported project always lands under a fresh id so a file can never+ * overwrite an existing project, and a file that is not ours is refused before+ * anything reaches the server.*/const api = vi.hoisted(() => ({createProject: vi.fn(),+ deleteClientStateValue: vi.fn(() => Promise.resolve()),+ getClientStateValue: vi.fn(() => Promise.resolve(null)),getProject: vi.fn(),+ setClientStateValue: vi.fn(() => Promise.resolve()),+}));++const downloads = vi.hoisted(() => ({ downloadBlob: vi.fn(), downloadText: vi.fn() }));++const transport = vi.hoisted(() => ({+ coverExtensionForMime: () => 'webp',+ fetchImageBytes: vi.fn((imageName: string) => Promise.resolve(new TextEncoder().encode(`bytes:${imageName}`))),+ fetchImageThumbnail: vi.fn(() => Promise.resolve(null)),+ findExistingImageNames: 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 })+ ),}));vi.mock('./api', () => api);+vi.mock('@platform/browser/downloadBlob', () => downloads);+vi.mock('./invk/imageTransport', () => transport);let projectFile: typeof projectFileModule;let persistence: typeof persistenceModule;@@ -29,89 +48,160 @@ const deferred = <T>() => {return { promise, resolve };};+const capturedArchive = (): File => {+ const [blob, fileName] = downloads.downloadBlob.mock.calls.at(-1)! as [Blob, string];++ return new File([blob], fileName);+};++const acceptCreate = (): void => {+ api.createProject.mockImplementation((request: { name: string; project_id?: string }) =>+ Promise.resolve({+ created_at: '2026-06-10 10:00:00.000',+ data: {},+ name: request.name,+ project_id: request.project_id ?? '',+ revision: 1,+ updated_at: '2026-06-10 10:00:00.000',+ })+ );+};+beforeEach(async () => {vi.resetModules();- api.createProject.mockReset();- api.getProject.mockReset();+ vi.clearAllMocks();+ transport.fetchImageBytes.mockImplementation((imageName: string) =>+ Promise.resolve(new TextEncoder().encode(`bytes:${imageName}`))+ );+ transport.fetchImageThumbnail.mockImplementation(() => Promise.resolve(null));+ transport.findExistingImageNames.mockImplementation((_names: readonly string[]) =>+ Promise.resolve(new Set<string>())+ );+ transport.uploadArchiveImage.mockImplementation((_bytes: Uint8Array, fileName: string) =>+ Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 })+ );+ api.getClientStateValue.mockImplementation(() => Promise.resolve(null));projectFile = await import('./projectFile');persistence = await import('./syncedPersistence');});-describe('project file envelope', () => {- it('round-trips a serialized project document', () => {- const project = createDraftProject([]);- const document = persistence.serializeProjectDocument(project);- const file = projectFile.buildProjectFile(document);- const parsed = projectFile.parseProjectFile(JSON.stringify(file));+describe('exportOpenProject', () => {+ it('downloads an archive named after the project', async () => {+ await projectFile.exportOpenProject({ ...createDraftProject([]), name: 'My project' });- expect(parsed).toEqual(document);+ expect(downloads.downloadBlob).toHaveBeenCalledTimes(1);+ expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('My project.invk');});+});++describe('exportLibraryProject', () => {+ it('exports a closed project straight from its server record', async () => {+ const document = persistence.serializeProjectDocument({ ...createDraftProject([]), name: 'Closed' });++ api.getProject.mockResolvedValue({ data: document, name: 'Closed', project_id: 'p1', revision: 3 });++ await projectFile.exportLibraryProject('p1');- it('rejects files that are not project exports', () => {- expect(projectFile.parseProjectFile('not json')).toBeNull();- expect(projectFile.parseProjectFile('{}')).toBeNull();- expect(projectFile.parseProjectFile(JSON.stringify({ document: {}, kind: 'other', version: 1 }))).toBeNull();- expect(- projectFile.parseProjectFile(JSON.stringify({ document: {}, kind: 'invokeai-project', version: 99 }))- ).toBeNull();- expect(projectFile.parseProjectFile(JSON.stringify({ kind: 'invokeai-project', version: 1 }))).toBeNull();+ expect(api.getProject).toHaveBeenCalledWith('p1', expect.anything());+ expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('Closed.invk');});});describe('importProjectFile', () => {- const fileFor = (contents: unknown): File => new File([JSON.stringify(contents)], 'export.invokeproject.json');-- it('creates the project under a fresh id, never the id in the file', async () => {+ it('round-trips an exported project under a fresh id', async () => {const project = { ...createDraftProject([]), name: 'Exported project' };- const document = persistence.serializeProjectDocument(project);-- api.createProject.mockImplementation((request: { project_id?: string; name: string }) =>- Promise.resolve({- created_at: '2026-06-10 10:00:00.000',- data: {},- name: request.name,- project_id: request.project_id ?? '',- revision: 1,- updated_at: '2026-06-10 10:00:00.000',- })- );- const record = await projectFile.importProjectFile(fileFor(projectFile.buildProjectFile(document)));+ acceptCreate();+ await projectFile.exportOpenProject(project);++ const record = await projectFile.importProjectFile(capturedArchive());expect(record.project_id).not.toBe(project.id);expect(record.name).toBe('Exported project');- const createRequest = api.createProject.mock.calls[0][0] as { data: Record<string, unknown>; project_id: string };+ const createRequest = api.createProject.mock.calls[0]![0] as { data: Record<string, unknown>; project_id: string };expect(createRequest.data.id).toBe(createRequest.project_id);});- it('rejects files whose document is not a usable project', async () => {- const file = fileFor(projectFile.buildProjectFile({ name: 'No layout' }));+ it('uploads only the images the server is missing', async () => {+ const project = createDraftProject([]);++ acceptCreate();+ await projectFile.exportOpenProject(project);+ transport.findExistingImageNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));++ await projectFile.importProjectFile(capturedArchive());++ expect(transport.uploadArchiveImage).not.toHaveBeenCalled();+ });++ it('refuses a legacy canvas project by reason', async () => {+ const { binaryEntry, textEntry, writeArchive } = await import('./invk/archive');+ const blob = await writeArchive(+ new Map([+ ['manifest.json', textEntry(JSON.stringify({ appVersion: '6.9', createdAt: '', name: 'C', version: 1 }))],+ ['canvas_state.json', binaryEntry(new Uint8Array([1]))],+ ])+ );- await expect(projectFile.importProjectFile(file)).rejects.toThrow('damaged');+ await expect(projectFile.importProjectFile(new File([blob], 'legacy.invk'))).rejects.toMatchObject({+ reason: 'legacy-canvas-project',+ });expect(api.createProject).not.toHaveBeenCalled();});- it('rejects non-project files before touching the server', async () => {- await expect(projectFile.importProjectFile(fileFor({ some: 'json' }))).rejects.toThrow('not an Invoke project');+ it('refuses a file that is not an archive before touching the server', async () => {+ await expect(projectFile.importProjectFile(new File(['{"some":"json"}'], 'x.invk'))).rejects.toMatchObject({+ reason: 'not-a-project',+ });+ expect(api.createProject).not.toHaveBeenCalled();+ });++ it('refuses an archive whose document is not a usable project', async () => {+ const { textEntry, writeArchive } = await import('./invk/archive');+ const blob = await writeArchive(+ new Map([+ [+ 'manifest.json',+ textEntry(+ JSON.stringify({+ appVersion: '7.0',+ contents: 'workbench-project',+ createdAt: '',+ name: 'No layout',+ version: 2,+ })+ ),+ ],+ ['project.json', textEntry(JSON.stringify({ name: 'No layout' }))],+ ])+ );++ await expect(projectFile.importProjectFile(new File([blob], 'broken.invk'))).rejects.toMatchObject({+ reason: 'damaged',+ });expect(api.createProject).not.toHaveBeenCalled();});it('does not upload an account A file after local parsing completes under account B', async () => {const account = await import('@platform/state/accountLifecycle');- const project = { ...createDraftProject([]), name: 'Account A project' };- const document = persistence.serializeProjectDocument(project);- const contents = deferred<string>();- const file = fileFor('');- vi.spyOn(file, 'text').mockReturnValue(contents.promise);+ acceptCreate();+ await projectFile.exportOpenProject({ ...createDraftProject([]), name: 'Account A project' });++ const file = capturedArchive();+ const bytes = await file.arrayBuffer();+ const contents = deferred<ArrayBuffer>();++ vi.spyOn(file, 'arrayBuffer').mockReturnValue(contents.promise);account.accountLifecycle.activate('project-import-a');+const imported = projectFile.importProjectFile(file);account.accountLifecycle.activate('project-import-b');- contents.resolve(JSON.stringify(projectFile.buildProjectFile(document)));+ contents.resolve(bytes);await expect(imported).rejects.toThrow('no longer active');expect(api.createProject).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 04d49eabd4..6ec0a56102 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -1,6 +1,7 @@import type { Project } from '@workbench/projectContracts';-import { downloadText } from '@platform/browser/downloadBlob';+import { downloadBlob } from '@platform/browser/downloadBlob';+import { APP_VERSION } from '@platform/runtime/appMetadata';import {type AccountScope,assertAccountScopeCurrent,@@ -9,64 +10,64 @@ import {} from '@platform/state/accountLifecycle';import { createProject as apiCreateProject, getProject as apiGetProject, type ProjectRecordDTO } from './api';+import { recordProjectCover } from './covers';import { createProjectId } from './ids';+import { INVK_EXTENSION, InvkFormatError } from './invk/format';import { upsertProjectSummary } from './library';+import { remapImageRefs } from './projectAssets';/**- * The portable project file: a versioned envelope around the same document- * shape the server stores. Export and import both reuse the sync layer's- * serialize/deserialize pair, so the file format inherits its healing of- * partial documents and there is exactly one definition of "a project- * document" in the app.+ * Export and import a project as an `.invk` archive.+ *+ * This module is the workflow; `./invk` is the format. The split matters+ * because the two have different reasons to change: the archive layout is a+ * compatibility surface shared with the previous frontend, while what an export+ * means here — which project, under whose account, landing where — is app+ * behavior.+ *+ * ### Why an archive and not a JSON file+ *+ * A project document references its pixels by server image name. Exporting the+ * document alone produced a file that opened perfectly on the machine that+ * wrote it and showed nothing but missing layers anywhere else. An `.invk`+ * carries the bytes, so the file is the project rather than a description of it.+ *+ * ### Import never overwrites+ *+ * An imported document gets a fresh id, never the one in the file. Two people+ * exchanging a project would otherwise collide the moment both saved, and+ * re-importing your own export would silently replace the original.+ *+ * The heavy halves — the ZIP codec and the workbench reducer — are both loaded+ * with `await import()`. The Launchpad offers Import and Export on a route that+ * never mounts the editor, and it should not pay for either until someone+ * actually picks a file.*/-export const PROJECT_FILE_KIND = 'invokeai-project';-export const PROJECT_FILE_VERSION = 1;--export interface ProjectFile {- kind: typeof PROJECT_FILE_KIND;- version: typeof PROJECT_FILE_VERSION;- exportedAt: string;- document: Record<string, unknown>;-}--export const buildProjectFile = (projectDocument: Record<string, unknown>): ProjectFile => ({- document: projectDocument,- exportedAt: new Date().toISOString(),- kind: PROJECT_FILE_KIND,- version: PROJECT_FILE_VERSION,-});--/** Returns the embedded document, or null when the text is not a project file. */-export const parseProjectFile = (text: string): Record<string, unknown> | null => {- try {- const parsed = JSON.parse(text) as Partial<ProjectFile> | null;-- if (- !parsed ||- parsed.kind !== PROJECT_FILE_KIND ||- parsed.version !== PROJECT_FILE_VERSION ||- !parsed.document ||- typeof parsed.document !== 'object' ||- Array.isArray(parsed.document)- ) {- return null;- }+const readProjectDocument = async (file: File) => {+ const { readInvkArchive } = await import('./invk/importProject');- return parsed.document as Record<string, unknown>;- } catch {- return null;- }+ return readInvkArchive(file);};-const sanitizeFileName = (name: string): string => name.replace(/[^\w\- ]+/gu, '').trim() || 'project';+const exportProjectDocument = async (+ name: string,+ projectDocument: Record<string, unknown>,+ owner: AccountScope+): Promise<void> => {+ const { executeInvkExport, planInvkExport } = await import('./invk/exportProject');++ assertAccountScopeCurrent(owner);++ const plan = planInvkExport({+ appVersion: APP_VERSION,+ createdAt: new Date().toISOString(),+ name,+ projectDocument,+ });-const downloadProjectFile = (name: string, projectDocument: Record<string, unknown>): void => {- downloadText(- JSON.stringify(buildProjectFile(projectDocument), null, 2),- `${sanitizeFileName(name)}.invokeproject.json`,- 'application/json'- );+ await executeInvkExport(plan, { download: downloadBlob, signal: owner.signal });+ assertAccountScopeCurrent(owner);};/** Export a closed project straight from its server record. */@@ -77,39 +78,45 @@ export const exportLibraryProject = async (const record = await apiGetProject(projectId, owner.signal);assertAccountScopeCurrent(owner);- downloadProjectFile(record.name, record.data);+ await exportProjectDocument(record.name, record.data, owner);};/** Export an open project from its live in-memory document. */-export const exportOpenProject = async (project: Project): Promise<void> => {+export const exportOpenProject = async (+ project: Project,+ owner: AccountScope = captureAccountScope()+): Promise<void> => {const { serializeProjectDocument } = await import('./projectDocument');- downloadProjectFile(project.name, serializeProjectDocument(project));+ assertAccountScopeCurrent(owner);+ await exportProjectDocument(project.name, serializeProjectDocument(project), owner);};/**- * Import a project file as a new server project. The document gets a fresh- * id — never the one in the file — so an import can never collide with (and- * overwrite) an existing project. Throws with a user-readable message.+ * Import an `.invk` as a new server project: restore its images, rewrite every+ * reference the server renamed, then create the project. Throws+ * {@link InvkFormatError} so callers can translate the reason rather than+ * surface an internal message.*/export const importProjectFile = async (file: File,owner: AccountScope = captureAccountScope()): Promise<ProjectRecordDTO> => {- const projectDocument = parseProjectFile(await file.text());+ const contents = await readProjectDocument(file);assertAccountScopeCurrent(owner);- if (!projectDocument) {- throw new Error('This file is not an Invoke project export.');- }+ const { restoreArchiveImages } = await import('./invk/importProject');+ const restored = await restoreArchiveImages(contents, { signal: owner.signal });++ assertAccountScopeCurrent(owner);const id = createProjectId();const name =- typeof projectDocument.name === 'string' && projectDocument.name.trim()- ? projectDocument.name.trim()+ typeof contents.projectDocument.name === 'string' && contents.projectDocument.name.trim()+ ? contents.projectDocument.name.trim(): 'Imported project';- const document = { ...projectDocument, id, name };+ const document = { ...remapImageRefs(contents.projectDocument, restored.mapping), 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.@@ -118,7 +125,7 @@ export const importProjectFile = async (assertAccountScopeCurrent(owner);if (!deserializeProjectDocument(document)) {- throw new Error('The project file is damaged and cannot be opened.');+ throw new InvkFormatError('damaged', 'The project document will not rehydrate.');}const record = await apiCreateProject({ data: document, name, project_id: id }, owner.signal);@@ -126,6 +133,10 @@ export const importProjectFile = async (assertAccountScopeCurrent(owner);upsertProjectSummary({ id: record.project_id, name: record.name, revision: record.revision }, owner);+ if (restored.coverImageName !== null) {+ recordProjectCover(record.project_id, restored.coverImageName, owner);+ }+return record;};@@ -149,7 +160,7 @@ export const pickProjectFile = (owner: AccountScope = captureAccountScope()): Prconst handleAbort = (): void => finish(null);input.type = 'file';- input.accept = 'application/json,.json';+ input.accept = INVK_EXTENSION;input.onchange = () => finish(input.files?.[0] ?? null);input.oncancel = () => finish(null);owner.signal.addEventListener('abort', handleAbort, { once: true });diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.tsnew file mode 100644index 0000000000..c74d18abf1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileErrors.ts@@ -0,0 +1,38 @@+import { InvkFormatError } from './invk/format';++/**+ * Turn a failed project-file read 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+ * picked the wrong file got a sentence written for a developer. `InvkFormatError`+ * carries a `reason` instead of a message so the wording lives in the catalog+ * 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.+ *+ * 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 => {+ if (!(error instanceof InvkFormatError)) {+ return error instanceof Error ? error.message : undefined;+ }++ switch (error.reason) {+ case 'legacy-canvas-project': {+ return t('projects.file.legacyCanvasProject');+ }+ case 'unsupported-version': {+ return t('projects.file.unsupportedVersion');+ }+ case 'damaged': {+ return t('projects.file.damaged');+ }+ case 'too-large': {+ return t('projects.file.tooLarge');+ }+ default: {+ return t('projects.file.notAProject');+ }+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex 55ab6fb16a..01187d12a9 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -22,7 +22,9 @@ import {updateProject as apiUpdateProject,type ProjectRecordDTO,} from './api';+import { recordProjectCover } from './covers';import { seedProjectLibrary, upsertProjectSummary } from './library';+import { selectCoverImageName } from './projectAssets';import { isProjectDocumentShape, normalizeLegacyProjectDocument, serializeProjectDocument } from './projectDocument';import { fetchSessionBlob, serializeSessionBlob, SESSION_STATE_KEY } from './session';import { reportProjectSync, type ProjectSyncInfo } from './syncStore';@@ -127,6 +129,12 @@ const getSerializedProjectDocument = (const serialized = { document, json };syncState.projectDocumentJsonCache.set(project, serialized);+ // The cache is keyed by project identity, so this runs once per document+ // version — the only moments a project's cover can have changed. Recording it+ // here rather than after the push keeps one seam instead of three, and costs+ // nothing when the push fails: the cover names an image that exists either+ // way, and `recordProjectCover` is a no-op when the answer has not moved.+ recordProjectCover(project.id, selectCoverImageName(document), syncState.owner);return serialized;};diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxindex 98dd6a6d2a..125cdef867 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -405,10 +405,7 @@ const BehaviorSection = () => {}, []);return (- <SettingsSection- description="Safety checks, prompt editing, and user-assistance behavior."- title="Behavior"- >+ <SettingsSection description="Safety checks, prompt editing, and user-assistance behavior." title="Behavior"><SettingTogglechecked={autoSwitchInvocationRoute}description="Switch the Invoke source and destination to match the surface you are editing. Locked sources and destinations are never changed."diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsxindex 8e4c385931..7262619524 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx@@ -15,7 +15,9 @@ import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';import { OpenProjectDialog } from '@workbench/projects/components';import { refreshProjectLibrary, useProjectLibrarySelector } from '@workbench/projects/library';import { exportOpenProject } from '@workbench/projects/projectFile';+import { describeProjectFileError } from '@workbench/projects/projectFileErrors';import { useProjectActions } from '@workbench/projects/useProjectActions';+import { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import {useActiveProjectSelector,@@ -55,6 +57,7 @@ export const ProjectSwitcher = () => {const queries = useWorkbenchQueries();const { projects } = useWorkbenchCommands();const { closeProject, deleteProject, openProject } = useProjectActions();+ const notify = useNotify();const openWorkbenchWidget = useOpenWorkbenchWidget();const [renameTarget, setRenameTarget] = useState<{ id: string; name: string } | null>(null);const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);@@ -106,10 +109,17 @@ export const ProjectSwitcher = () => {const exportActiveProject = useCallback(() => {const project = getProject(activeProjectId);- if (project) {- void exportOpenProject(project);+ if (!project) {+ return;}- }, [activeProjectId, getProject]);++ // Export bundles every image the project points at, so it can fail on a+ // dropped connection or a project past the archive ceiling. Silence would+ // read as "nothing happened" when the download never arrives.+ void exportOpenProject(project).catch((error: unknown) => {+ notify.error(t('projects.exportFailed'), describeProjectFileError(error, t));+ });+ }, [activeProjectId, getProject, notify, t]);const closeActiveProject = useCallback(() => {const project = getProject(activeProjectId);diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex fb394b032d..5d80b75e8e 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -19,6 +19,7 @@ const ROUTE_SHARED_MODULES = ['/features/nodes/index.ts','/features/nodes/ui/NodesPage.tsx','/platform/browser/downloadBlob.ts',+ '/platform/core/concurrency.ts','/platform/query/client.ts','/platform/time/serverTimestamp.ts','/platform/transport/connectionStore.ts',@@ -32,9 +33,16 @@ const ROUTE_SHARED_MODULES = [// table — a 66 KB, one-extra-request regression on the editor route.'/workbench/launchpad/intents.ts','/workbench/palette/settingsEntryDeps.ts',+ '/workbench/projects/covers.ts','/workbench/projects/ids.ts',+ // The `.invk` surface both routes touch eagerly: the extension for the file+ // picker, and the error class every import call site catches to translate.+ // The schema, the ZIP codec and the archive itself stay behind lazy imports.+ '/workbench/projects/invk/format.ts','/workbench/projects/library.ts',+ '/workbench/projects/projectAssets.ts','/workbench/projects/projectFile.ts',+ '/workbench/projects/projectFileErrors.ts','/workbench/settings/SettingsDialogHost.tsx',] as const;@@ -90,6 +98,12 @@ const getLegacyChunkName = (id: string): string | null => {return 'yaml';}+ // Only `projects/invk/archive.ts` reaches for this, and only when a project+ // file is actually read or written — the same treatment ag-psd gets.+ if (id.includes('/node_modules/fflate/')) {+ return 'fflate';+ }+if (id.includes('/node_modules/react-icons/')) {return 'react-icons';}