Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): close project file safety gaps
joshistoastf5ef2ce602d0
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdxindex 4f1d462bdb..64007efd1b 100644--- a/docs/src/content/docs/development/Front End/project-files.mdx+++ b/docs/src/content/docs/development/Front End/project-files.mdx@@ -4,19 +4,21 @@ 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.+Import also accepts the `.invokeproject.json` envelope shipped by earlier webv2 builds. New exports use `.invk`; the JSON path remains read-only compatibility.+`.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. |-| `videos/<video_name>` | no | Video bytes, keyed the same way. |+| 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. |+| `videos/<video_name>` | no | Video bytes, keyed the same way. |Assets are filed by kind rather than pooled. Images and videos are separate backend namespaces with separate fetch and upload routes, so import has to know which an entry is before it can restore it — the folder states that, where a shared one would leave it to be guessed from a file extension. Adding `videos/` needed no version bump: `readInvkArchive` ignores entries it does not recognize, so a reader predating it reads such an archive and simply leaves those references dangling, exactly as it would for an absent image.@@ -44,18 +46,24 @@ The skip is by key on purpose, because the members got there differently. `selecImport deliberately orders its work as **read → mint identity → validate and canonicalize → restore → remap → create**. It first reads the archive without mutating the server, then assigns the imported project a fresh id and name. The candidate is rehydrated through the Workbench reducer and serialized back to its canonical document before any asset is restored. Only then are missing assets restored, their server-assigned names remapped throughout that canonical document, and the new project created. A malformed document therefore cannot leave restored orphan assets behind, and an import can never overwrite the project whose id was recorded in the archive.+The legacy JSON path follows the same fresh-identity validation and canonicalization boundary, then creates the project directly. A JSON envelope carries no bundled media, so it performs no existence checks, uploads, restoration or remapping.+Restoration checks which referenced assets the server already has, uploads only the missing ones out of `images/` and `videos/`, and returns an old-to-new mapping **per kind** — the namespaces are separate, so a single flat map would let an image rewrite a video that happened to share its name. `remapAssetRefs()` 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.The existence check is the one place the two kinds are not symmetric. Images have a bulk `POST /images/images_by_names`; videos have no equivalent, so that check fans out one `GET /videos/i/{name}` per name behind the same concurrency limit of 5. For video lookup, only `403` and `404` mean the asset is absent; every other non-success status aborts the import rather than being mistaken for a missing video. This is what `hydrateVideoRefs` in the gallery's data layer already does for the same reason. A project with no video references never issues the video check at all.Restored assets upload with the 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.+Restoration records the authoritative server names returned by every successful upload. If project creation then rejects while the importing account scope is still current, import checks the client-chosen project id and sends those names to the image and video batch-delete routes only when the server confirms that id is absent with `404`. A found project or an inconclusive lookup is an ambiguous create, so cleanup is skipped rather than deleting assets that the project may already reference. Cleanup is best-effort and never replaces the primary create error. It is also skipped after a create has returned and after a cross-account rotation: issuing destructive deletes with a new account's credentials would be unsafe. That safety boundary means a rotation after upload can still leave private-category media behind when the old account can no longer authorize cleanup.+An asset 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()`, over one queue spanning both kinds — the limit exists to be kind to the backend, and would not be if each kind got its own.**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.**Cancellation is not a skip.** An unservable asset is skipped, but an aborted signal makes every asset unservable at once — so a cancelled export would otherwise pack an archive of nothing and hand it to the browser as a finished download. `isRequestCancellation()` tells the two apart where the request fails. The signal is checked after fetching and again after packing, immediately before the browser download, so cancellation during ZIP creation cannot produce a completed-looking download.+Export from the project switcher flushes Generate's debounced prompt drafts before it reads the active project. An immediate prompt edit is therefore part of the serialized document rather than arriving after export has already started.+## ReportingA project file is the one operation here whose duration is set by how much someone has drawn: a few hundred full-resolution layers is a few hundred round trips and hundreds of megabytes. Every entry point runs through `useProjectFileActions.ts`, which owns the scope capture, the picker, the try/catch, and one live toast per operation (`projectFileToasts.ts`). Keeping the sequence in one place is what stops the five surfaces drifting — they already had, with the import sites checking the account scope before showing an error and the export sites not, so cancelling an export by signing out produced a toast written for a developer.@@ -70,13 +78,15 @@ The index is written whenever a project is serialized for a save, and on import.Each cover write is a complete replacement of that one index value, so writes are serialized. A failed write leaves the optimistic snapshot dirty; a later save or identical cover record retries that complete dirty snapshot instead of silently treating it as clean. Before the index has loaded, pending changes retain both new cover names and clears (`null`), so clearing a cover before load still removes the matching retained server entry once the read succeeds.+A successful load is also final for that account epoch. Later library refreshes reuse the loaded snapshot instead of issuing another blind GET that could overwrite an optimistic cover mutation; a failed initial read remains retryable.+On import the cover prefers an image the restore already put on this server — the archive's `cover` entry is a thumbnail of an image the document also references, and the cover URL asks for a thumbnail anyway, so reusing it is the same picture without a second copy. The bundled bytes are the fallback for a cover whose source image is dangling. Uploading the entry unconditionally left one orphan per import: covers go up under the canvas's private `'other'` category, which appears in no gallery view and no board count, so nobody could find or delete them.-**The whole index is one value, so a write must not precede a read.** `setClientStateValue` replaces the blob outright, so recording a cover from a store that has not loaded would delete every entry but that one — and autosave reaches `recordProjectCover()` from the editor, which loads the index only when the project switcher or the Open dialog opens. Anyone who reloads straight into a project and generates hits exactly that ordering. Records made before the load are held and applied on top of the server's answer once it arrives. A read that *fails* is not a read: the store stays unloaded and the pending records wait, because merging onto a blank answer is the same destructive write by another route.+**The whole index is one value, so a write must not precede a read.** `setClientStateValue` replaces the blob outright, so recording a cover from a store that has not loaded would delete every entry but that one — and autosave reaches `recordProjectCover()` from the editor, which loads the index only when the project switcher or the Open dialog opens. Anyone who reloads straight into a project and generates hits exactly that ordering. Records made before the load are held and applied on top of the server's answer once it arrives. A read that _fails_ is not a read: the store stays unloaded and the pending records wait, because merging onto a blank answer is the same destructive write by another route.## 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`.+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.@@ -86,9 +96,9 @@ Future format changes should add a new member to the union rather than widening`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.-The input `File.size` is rejected before `arrayBuffer()` allocates its bytes. On export, the accumulated entries are checked before packing and the packed ZIP is checked again afterward, because compression can change the final output size.+The input `File.size` is rejected before `arrayBuffer()` allocates its bytes. On export, one shared response reader checks declared `Content-Length` values and streams every asset through the same fixed 2 GiB allocation budget, including concurrent responses. It cancels a response when its declared length, streamed bytes or cumulative retained bytes cross the ceiling. The accumulated entries are checked before packing and the packed ZIP is checked again afterward, because compression can change the final output size.-On the way in, the budget is enforced through fflate's entry filter (`createExpansionBudget()`), not over the result. `unzip` is fully buffered: by the time it returns a record of entries, every one has already been inflated, so a total measured there would describe an out-of-memory crash rather than prevent it. The filter is consulted per entry with the uncompressed size declared in the central directory, and refuses everything from the crossing point on. The refusal is raised after `unzip` settles rather than thrown from inside it, so `too-large` stays distinguishable from `not-a-project` — a throw inside fflate's walk arrives as a decode failure. An entry whose header understates its size is caught by fflate itself, which inflates into a buffer sized from that declaration and fails the decode when the stream overruns it.+On the way in, the budget is enforced through fflate's entry filter (`createExpansionBudget()`), not over the result. `unzip` is fully buffered: by the time it returns a record of entries, every one has already been inflated, so a total measured there would describe an out-of-memory crash rather than prevent it. The filter is consulted per entry with its compression method, compressed `size` and uncompressed `originalSize`. Deflated entries allocate from `originalSize`; stored entries allocate from `size`, so stored entries must declare both sizes identically and the actual allocation size is what counts against the cumulative ceiling. The refusal is raised after `unzip` settles rather than thrown from inside it, so `too-large` stays distinguishable from `not-a-project` — a throw inside fflate's walk arrives as a decode failure.`INVK_MAX_ARCHIVE_BYTES` is 2 GiB — deliberately well under 4 GiB, where ZIP32's 32-bit sizes and offsets stop being able to describe the file. fflate reads zip64 records but `zip()` never writes them, so an archive at that boundary would be produced structurally invalid rather than refused. A single video can be hundreds of megabytes, so this ceiling is reachable in practice; it fails cleanly into the `too-large` reason.@@ -98,6 +108,8 @@ The mock-backed browser journey exercises the real export action and file choose## Compatibility notes+Earlier webv2 builds exported `*.invokeproject.json` files containing a version 1 `invokeai-project` envelope. Import detects that exact extension, validates the envelope, mints a fresh identity, canonicalizes the embedded document and creates it without attempting media restoration. The picker offers both `.invk` and `.invokeproject.json`.+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/src/workbench/projects/covers.test.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.test.tsindex b7e4f9d7b9..0646ba1132 100644--- a/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts@@ -29,9 +29,9 @@ vi.mock('./api', () => api);let covers: typeof coversModule;let lifecycle: typeof accountLifecycleModule;-const createDeferred = () => {- let resolve!: () => void;- const promise = new Promise<void>((resolvePromise) => {+const createDeferred = <T = void>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise) => {resolve = resolvePromise;});@@ -41,8 +41,14 @@ const createDeferred = () => {beforeEach(async () => {vi.resetModules();api.__clientState.clear();- api.getClientStateValue.mockClear();- api.setClientStateValue.mockClear();+ api.getClientStateValue.mockReset();+ api.getClientStateValue.mockImplementation((key: string) => Promise.resolve(api.__clientState.get(key) ?? null));+ api.setClientStateValue.mockReset();+ api.setClientStateValue.mockImplementation((key: string, value: string) => {+ api.__clientState.set(key, value);++ return Promise.resolve();+ });lifecycle = await import('@platform/state/accountLifecycle');covers = await import('./covers');@@ -82,6 +88,25 @@ describe('loadProjectCovers', () => {await expect(covers.loadProjectCovers()).resolves.toBeUndefined();expect(covers.getProjectCoverImageName('p1')).toBeUndefined();});++ it('does not let a later load overwrite a cover mutation after the account index loaded', async () => {+ const staleRead = createDeferred<string | null>();++ api.getClientStateValue.mockResolvedValueOnce('{"p1":"old.png"}').mockImplementationOnce(() => staleRead.promise);++ await covers.loadProjectCovers();++ const laterLoad = covers.loadProjectCovers();+ covers.recordProjectCover('p1', 'new.png');+ staleRead.resolve('{"p1":"old.png"}');+ await laterLoad;++ await vi.waitFor(() => {+ expect(covers.getProjectCoverImageName('p1')).toBe('new.png');+ expect(api.__clientState.get('webv2:project-covers')).toBe('{"p1":"new.png"}');+ });+ expect(api.getClientStateValue).toHaveBeenCalledTimes(1);+ });});/**diff --git a/invokeai/frontend/webv2/src/workbench/projects/covers.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.tsindex cce8565dcf..7df59f65d1 100644--- a/invokeai/frontend/webv2/src/workbench/projects/covers.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.ts@@ -154,6 +154,10 @@ const loadFlight = createSingleFlight<void>();export const loadProjectCovers = (): Promise<void> => {const owner = captureAccountScope();+ if (store.getSnapshot().isLoaded) {+ return Promise.resolve();+ }+return loadFlight.run(`project-covers:${owner.epoch}`, async () => {let raw: string | null = null;diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.tsindex da109475a8..1b4dcf0648 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts@@ -112,7 +112,12 @@ describe('writeArchive / readArchive', () => {* through `readArchive` would mean actually building a multi-gigabyte archive.*/describe('createExpansionBudget', () => {- const entry = (name: string, originalSize: number) => ({ name, originalSize });+ const entry = (name: string, originalSize: number, size = originalSize, compression = 8) => ({+ compression,+ name,+ originalSize,+ size,+ });const GIB = 1024 * 1024 * 1024;it('accepts entries that fit and raises nothing', () => {@@ -168,6 +173,13 @@ describe('createExpansionBudget', () => {expect(budget.getRefusal()).toBe(first);});++ it('refuses a stored entry whose compressed and original sizes disagree', () => {+ const budget = createExpansionBudget();++ expect(budget.accept(entry('images/tampered.png', 1, 1024 * 1024, 0))).toBe(false);+ expect(budget.getRefusal()).toMatchObject({ reason: 'not-a-project' });+ });});describe('readArchive with the budget in the path', () => {@@ -184,4 +196,26 @@ describe('readArchive with the budget in the path', () => {expect([...entries.keys()].sort()).toEqual(['images/a.png', 'project.json']);expect(entries.get('images/a.png')!.byteLength).toBe(4096);});++ it('rejects a stored payload whose central directory understates its allocation', async () => {+ const blob = await writeArchive(+ new Map([['images/tampered.png', binaryEntry(new Uint8Array(1024 * 1024).fill(0xa5))]])+ );+ const bytes = new Uint8Array(await blob.arrayBuffer());+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let centralDirectoryOffset = -1;++ for (let offset = 0; offset <= bytes.byteLength - 4; offset += 1) {+ if (view.getUint32(offset, true) === 0x02014b50) {+ centralDirectoryOffset = offset;+ break;+ }+ }++ expect(centralDirectoryOffset).toBeGreaterThanOrEqual(0);+ // ZIP central-directory uncompressed size. The stored size remains the real 1 MiB.+ view.setUint32(centralDirectoryOffset + 24, 1, true);++ await expect(readArchive(bytes)).rejects.toMatchObject({ reason: 'not-a-project' });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.tsindex 927467e2b7..e50fae6e48 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.ts@@ -33,9 +33,9 @@ import { INVK_MIME_TYPE, InvkFormatError } from './format';* central directory, which is the only place a ceiling can actually stop a zip* bomb rather than describe one.*- * A header that understates its entry's size does not get past this: fflate- * inflates into a buffer sized from that declaration and fails the decode when- * the stream overruns it, which surfaces as `not-a-project`.+ * fflate allocates deflated entries from `originalSize`, but stored entries+ * from `size`. Stored ZIP entries must declare those sizes identically; the+ * filter rejects a mismatch before fflate can copy the payload.*//**@@ -119,7 +119,7 @@ export const writeArchive = async (entries: InvkArchiveEntries): Promise<Blob> =export interface InvkExpansionBudget {/** Consulted per entry before it is inflated; `false` keeps it out of memory. */- accept: (file: { name: string; originalSize: number }) => boolean;+ accept: (file: { compression: number; name: string; originalSize: number; size: number }) => boolean;/** The refusal to raise once `unzip` has settled, or `null` if everything fit. */getRefusal: () => InvkFormatError | null;}@@ -148,12 +148,17 @@ export const createExpansionBudget = (): InvkExpansionBudget => {}entryCount += 1;- expandedBytes += file.originalSize;if (entryCount > INVK_MAX_ENTRIES) {refusal ??= new InvkFormatError('too-large', `Project archive holds more than ${INVK_MAX_ENTRIES} entries.`);- } else if (expandedBytes > INVK_MAX_ARCHIVE_BYTES) {- refusal ??= new InvkFormatError('too-large', `Project archive expands past ${INVK_MAX_ARCHIVE_BYTES} bytes.`);+ } else if (file.compression === 0 && file.size !== file.originalSize) {+ refusal ??= new InvkFormatError('not-a-project', `Stored ZIP entry "${file.name}" has inconsistent sizes.`);+ } else {+ expandedBytes += file.compression === 0 ? file.size : file.originalSize;++ if (expandedBytes > INVK_MAX_ARCHIVE_BYTES) {+ refusal ??= new InvkFormatError('too-large', `Project archive expands past ${INVK_MAX_ARCHIVE_BYTES} bytes.`);+ }}return refusal === null;diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.tsindex 4539aae469..ab220a8cf3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts@@ -1,14 +1,25 @@import { ApiError } from '@platform/transport/http';import { describe, expect, it, vi } from 'vitest';-const mocks = vi.hoisted(() => ({ apiFetchRaw: vi.fn() }));+import type * as assetTransportModule from './assetTransport';++import { INVK_MAX_ARCHIVE_BYTES } from './archive';++const mocks = vi.hoisted(() => ({ apiFetchJson: vi.fn(), apiFetchRaw: vi.fn() }));vi.mock('@platform/transport/http', async (importOriginal) => ({- ...(await importOriginal<typeof import('@platform/transport/http')>()),+ ...(await importOriginal<object>()),+ apiFetchJson: mocks.apiFetchJson,apiFetchRaw: mocks.apiFetchRaw,}));-import { findExistingVideoNames } from './assetTransport';+import {+ createAssetResponseReader,+ fetchImageBytes,+ fetchImageThumbnail,+ fetchVideoBytes,+ findExistingVideoNames,+} from './assetTransport';describe('findExistingVideoNames', () => {it('returns a video name when its lookup succeeds', async () => {@@ -36,3 +47,167 @@ describe('findExistingVideoNames', () => {await expect(findExistingVideoNames(['unreachable.mp4'])).rejects.toBe(networkError);});});++describe('import rollback transport', () => {+ it('sends authoritative image and video identities to their batch-delete routes', async () => {+ const transport = (await import('./assetTransport')) as typeof assetTransportModule & {+ deleteArchiveImages?: (names: string[], signal?: AbortSignal) => Promise<void>;+ deleteArchiveVideos?: (names: string[], signal?: AbortSignal) => Promise<void>;+ };++ expect(transport.deleteArchiveImages).toBeTypeOf('function');+ expect(transport.deleteArchiveVideos).toBeTypeOf('function');++ if (!transport.deleteArchiveImages || !transport.deleteArchiveVideos) {+ return;+ }++ const signal = new AbortController().signal;++ mocks.apiFetchJson.mockResolvedValue({});+ await transport.deleteArchiveImages(['server-image.png'], signal);+ await transport.deleteArchiveVideos(['server-video.mp4'], signal);++ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(1, '/api/v1/images/delete', {+ body: JSON.stringify({ image_names: ['server-image.png'] }),+ method: 'POST',+ signal,+ });+ expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(2, '/api/v1/videos/delete', {+ body: JSON.stringify({ video_names: ['server-video.mp4'] }),+ method: 'POST',+ signal,+ });+ });+});++describe('export asset response limits', () => {+ it('rejects an oversized Content-Length before materializing the body', async () => {+ const response = new Response(null, {+ headers: { 'content-length': String(INVK_MAX_ARCHIVE_BYTES + 1) },+ status: 200,+ });+ const arrayBuffer = vi.spyOn(response, 'arrayBuffer');++ mocks.apiFetchRaw.mockResolvedValue(response);++ await expect(fetchImageBytes('too-large.png')).rejects.toMatchObject({ reason: 'too-large' });+ expect(arrayBuffer).not.toHaveBeenCalled();+ });++ it('rejects and cancels a stream that crosses the per-response ceiling', async () => {+ const cancel = vi.fn();+ const atLimit = { byteLength: INVK_MAX_ARCHIVE_BYTES } as Uint8Array;+ const oneByte = { byteLength: 1 } as Uint8Array;+ let chunk = 0;+ const response = new Response(+ new ReadableStream<Uint8Array>({+ cancel,+ pull(controller) {+ controller.enqueue(chunk === 0 ? atLimit : oneByte);+ chunk += 1;+ },+ }),+ { status: 200 }+ );+ const arrayBuffer = vi.spyOn(response, 'arrayBuffer');++ mocks.apiFetchRaw.mockResolvedValue(response);++ await expect(fetchVideoBytes('too-large.mp4')).rejects.toMatchObject({ reason: 'too-large' });+ expect(cancel).toHaveBeenCalledTimes(1);+ expect(arrayBuffer).not.toHaveBeenCalled();+ });++ it('streams thumbnail chunks into the returned bytes', async () => {+ const response = new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array([1, 2]));+ controller.enqueue(new Uint8Array([3, 4]));+ controller.close();+ },+ }),+ { headers: { 'content-type': 'image/png' }, status: 200 }+ );+ const arrayBuffer = vi.spyOn(response, 'arrayBuffer');++ mocks.apiFetchRaw.mockResolvedValue(response);++ await expect(fetchImageThumbnail('cover.png')).resolves.toEqual({+ bytes: new Uint8Array([1, 2, 3, 4]),+ contentType: 'image/png',+ });+ expect(arrayBuffer).not.toHaveBeenCalled();+ });++ it('accepts the cumulative boundary and refuses the next declared byte before reading it', async () => {+ const readResponse = createAssetResponseReader();+ const atLimit = { byteLength: INVK_MAX_ARCHIVE_BYTES } as Uint8Array;+ const firstResponse = new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(atLimit);+ controller.close();+ },+ })+ );++ await expect(readResponse(firstResponse)).resolves.toBe(atLimit);++ const cancel = vi.fn(() => Promise.resolve());+ const getReader = vi.fn(() => ({+ cancel,+ read: vi+ .fn()+ .mockResolvedValueOnce({ done: false, value: new Uint8Array([1]) })+ .mockResolvedValueOnce({ done: true, value: undefined }),+ releaseLock: vi.fn(),+ }));+ const nextResponse = {+ body: { cancel, getReader },+ headers: new Headers({ 'content-length': '1' }),+ } as unknown as Response;++ await expect(readResponse(nextResponse)).rejects.toMatchObject({ reason: 'too-large' });+ expect(cancel).toHaveBeenCalledTimes(1);+ expect(getReader).not.toHaveBeenCalled();+ });++ it('cancels a pending reader as soon as its signal is aborted', async () => {+ let settleRead: (result: ReadableStreamReadResult<Uint8Array>) => void = () => undefined;+ const pendingRead = new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {+ settleRead = resolve;+ });+ const cancel = vi.fn(() => {+ settleRead({ done: true, value: undefined });++ return Promise.resolve();+ });+ const reader = {+ cancel,+ read: vi.fn(() => pendingRead),+ releaseLock: vi.fn(),+ };+ const response = {+ body: { cancel: vi.fn(() => Promise.resolve()), getReader: vi.fn(() => reader) },+ headers: new Headers(),+ } as unknown as Response;+ const controller = new AbortController();+ const read = createAssetResponseReader()(response, controller.signal);++ controller.abort(new DOMException('The operation was aborted.', 'AbortError'));+ await Promise.resolve();++ const cancellationCallsWhileReadWasPending = cancel.mock.calls.length;++ if (cancellationCallsWhileReadWasPending === 0) {+ settleRead({ done: true, value: undefined });+ }++ await expect(read).rejects.toBe(controller.signal.reason);+ expect(cancellationCallsWhileReadWasPending).toBe(1);+ expect(cancel).toHaveBeenCalledTimes(1);+ expect(reader.releaseLock).toHaveBeenCalledTimes(1);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.tsindex 74b54ac801..357cc73151 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts@@ -1,5 +1,14 @@import { mapWithConcurrency } from '@platform/core/concurrency';-import { apiFetch, apiFetchJson, apiFetchRaw, assertOk, HttpRequestIdentityExpiredError } from '@platform/transport/http';+import {+ apiFetch,+ apiFetchJson,+ apiFetchRaw,+ assertOk,+ HttpRequestIdentityExpiredError,+} from '@platform/transport/http';++import { INVK_MAX_ARCHIVE_BYTES } from './archive';+import { InvkFormatError } from './format';/*** The asset half of a project file: pulling referenced bytes off the server on@@ -77,6 +86,201 @@ interface VideoDTOSubset {video_name: string;}+export type AssetResponseReader = (response: Response, signal?: AbortSignal) => Promise<Uint8Array>;++const createAssetResponseByteWriter = () => {+ const chunks: Uint8Array[] = [];+ let byteLength = 0;++ return {+ finish: () => {+ if (chunks.length === 0) {+ return new Uint8Array();+ }++ if (chunks.length === 1) {+ return chunks[0]!;+ }++ const bytes = new Uint8Array(byteLength);+ let offset = 0;++ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return bytes;+ },+ write: (chunk: Uint8Array) => {+ chunks.push(chunk);+ byteLength += chunk.byteLength;+ },+ };+};++const getDeclaredContentLength = (response: Response): number | null => {+ const value = response.headers.get('content-length')?.trim();++ if (value === undefined || !/^\d+$/.test(value)) {+ return null;+ }++ const byteLength = Number(value);++ return Number.isSafeInteger(byteLength) ? byteLength : Number.POSITIVE_INFINITY;+};++/**+ * A single export-scoped reader. Every response is streamed through the same+ * fixed byte budget, so both one hostile response and many individually-small+ * responses stop before they can materialize an oversized project in memory.+ */+export const createAssetResponseReader = (): AssetResponseReader => {+ type AssetStreamReader = ReadableStreamDefaultReader<Uint8Array>;++ const activeReaders = new Set<AssetStreamReader>();+ const cancellationRequests = new WeakMap<AssetStreamReader, Promise<void>>();+ let fatalRefusal: InvkFormatError | null = null;+ let usedBytes = 0;+ let reservedBytes = 0;++ const cancelReader = (reader: AssetStreamReader, reason: unknown): Promise<void> => {+ const existing = cancellationRequests.get(reader);++ if (existing !== undefined) {+ return existing;+ }++ const request = reader.cancel(reason).catch(() => undefined);++ cancellationRequests.set(reader, request);++ return request;+ };++ const refuseTooLarge = (message: string): InvkFormatError => {+ if (fatalRefusal === null) {+ fatalRefusal = new InvkFormatError('too-large', message);++ for (const reader of activeReaders) {+ void cancelReader(reader, fatalRefusal);+ }+ }++ return fatalRefusal;+ };++ return async (response, signal) => {+ const body = response.body;+ const declaredByteLength = getDeclaredContentLength(response);++ const refuseBeforeReading = async (error: unknown): Promise<never> => {+ try {+ await body?.cancel(error);+ } catch {+ // The refusal is authoritative even if the transport cannot be cancelled.+ }++ throw error;+ };++ if (fatalRefusal !== null) {+ return refuseBeforeReading(fatalRefusal);+ }++ if (signal?.aborted) {+ return refuseBeforeReading(signal.reason);+ }++ if (declaredByteLength !== null && declaredByteLength > INVK_MAX_ARCHIVE_BYTES) {+ return refuseBeforeReading(refuseTooLarge(`Asset response is larger than ${INVK_MAX_ARCHIVE_BYTES} bytes.`));+ }++ if (declaredByteLength !== null && usedBytes + reservedBytes + declaredByteLength > INVK_MAX_ARCHIVE_BYTES) {+ return refuseBeforeReading(refuseTooLarge(`Project assets exceed ${INVK_MAX_ARCHIVE_BYTES} bytes.`));+ }++ const writer = createAssetResponseByteWriter();+ let remainingReservation = declaredByteLength ?? 0;+ let responseBytes = 0;++ reservedBytes += remainingReservation;++ if (body === null) {+ reservedBytes -= remainingReservation;++ return writer.finish();+ }++ const reader = body.getReader();++ activeReaders.add(reader);++ let finished = false;+ const cancelOnAbort = () => {+ void cancelReader(reader, signal?.reason);+ };++ signal?.addEventListener('abort', cancelOnAbort, { once: true });++ try {+ signal?.throwIfAborted();++ while (true) {+ const result = await reader.read();++ if (fatalRefusal !== null) {+ throw fatalRefusal;+ }++ signal?.throwIfAborted();++ if (result.done) {+ finished = true;+ reservedBytes -= remainingReservation;+ remainingReservation = 0;++ return writer.finish();+ }++ const chunkBytes = result.value.byteLength;+ const reservationConsumed = Math.min(remainingReservation, chunkBytes);+ const bytesPastDeclaration = chunkBytes - reservationConsumed;++ if (responseBytes + chunkBytes > INVK_MAX_ARCHIVE_BYTES) {+ throw refuseTooLarge(`Asset response exceeds ${INVK_MAX_ARCHIVE_BYTES} bytes.`);+ }++ if (usedBytes + reservedBytes + bytesPastDeclaration > INVK_MAX_ARCHIVE_BYTES) {+ throw refuseTooLarge(`Project assets exceed ${INVK_MAX_ARCHIVE_BYTES} bytes.`);+ }++ responseBytes += chunkBytes;+ usedBytes += chunkBytes;+ reservedBytes -= reservationConsumed;+ remainingReservation -= reservationConsumed;+ writer.write(result.value);+ }+ } catch (error) {+ usedBytes -= responseBytes;+ reservedBytes -= remainingReservation;+ responseBytes = 0;+ remainingReservation = 0;++ if (!finished) {+ await cancelReader(reader, error);+ }++ throw fatalRefusal ?? error;+ } finally {+ activeReaders.delete(reader);+ signal?.removeEventListener('abort', cancelOnAbort);+ reader.releaseLock();+ }+ };+};+/*** Which of `imageNames` the server already has. The endpoint silently omits* names it cannot serve, which is exactly the answer wanted here: anything@@ -139,27 +343,41 @@ export const findExistingVideoNames = async (* 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 fetchImageBytesWithReader = async (+ imageName: string,+ signal: AbortSignal | undefined,+ readResponse: AssetResponseReader+): 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());+ return readResponse(response, signal);};+export const fetchImageBytes = (imageName: string, signal?: AbortSignal): Promise<Uint8Array | null> =>+ fetchImageBytesWithReader(imageName, signal, createAssetResponseReader());+/** The same, for a video. */-export const fetchVideoBytes = async (videoName: string, signal?: AbortSignal): Promise<Uint8Array | null> => {+const fetchVideoBytesWithReader = async (+ videoName: string,+ signal: AbortSignal | undefined,+ readResponse: AssetResponseReader+): Promise<Uint8Array | null> => {const response = await apiFetchRaw(`${VIDEOS_BASE}/i/${encodeURIComponent(videoName)}/full`, { signal });if (!response.ok) {return null;}- return new Uint8Array(await response.arrayBuffer());+ return readResponse(response, signal);};+export const fetchVideoBytes = (videoName: string, signal?: AbortSignal): Promise<Uint8Array | null> =>+ fetchVideoBytesWithReader(videoName, signal, createAssetResponseReader());+export interface FetchedThumbnail {bytes: Uint8Array;/** Response MIME type, which decides the cover entry's extension. */@@ -167,9 +385,10 @@ export interface FetchedThumbnail {}/** Thumbnail bytes for the cover entry. `null` when the server will not serve it. */-export const fetchImageThumbnail = async (+const fetchImageThumbnailWithReader = async (imageName: string,- signal?: AbortSignal+ signal: AbortSignal | undefined,+ readResponse: AssetResponseReader): Promise<FetchedThumbnail | null> => {const response = await apiFetchRaw(`${IMAGES_BASE}/i/${encodeURIComponent(imageName)}/thumbnail`, { signal });@@ -178,11 +397,28 @@ export const fetchImageThumbnail = async (}return {- bytes: new Uint8Array(await response.arrayBuffer()),+ bytes: await readResponse(response, signal),contentType: response.headers.get('content-type') ?? 'image/webp',};};+export const fetchImageThumbnail = (imageName: string, signal?: AbortSignal): Promise<FetchedThumbnail | null> =>+ fetchImageThumbnailWithReader(imageName, signal, createAssetResponseReader());++/** Production export transport with one cumulative response budget. */+export const createAssetExportTransport = () => {+ const readResponse = createAssetResponseReader();++ return {+ fetchImageBytes: (imageName: string, signal?: AbortSignal) =>+ fetchImageBytesWithReader(imageName, signal, readResponse),+ fetchImageThumbnail: (imageName: string, signal?: AbortSignal) =>+ fetchImageThumbnailWithReader(imageName, signal, readResponse),+ fetchVideoBytes: (videoName: string, signal?: AbortSignal) =>+ fetchVideoBytesWithReader(videoName, signal, readResponse),+ };+};+/*** Put archived bytes back on the server. The returned name is authoritative and* frequently differs from the archived one — the server names images itself —@@ -232,6 +468,32 @@ export const uploadArchiveVideo = async (return { videoName: dto.video_name };};+/** Delete image identities created by a restore whose project could not be created. */+export const deleteArchiveImages = async (imageNames: string[], signal?: AbortSignal): Promise<void> => {+ if (imageNames.length === 0) {+ return;+ }++ await apiFetchJson<unknown>(`${IMAGES_BASE}/delete`, {+ body: JSON.stringify({ image_names: imageNames }),+ method: 'POST',+ signal,+ });+};++/** Delete video identities created by a restore whose project could not be created. */+export const deleteArchiveVideos = async (videoNames: string[], signal?: AbortSignal): Promise<void> => {+ if (videoNames.length === 0) {+ return;+ }++ await apiFetchJson<unknown>(`${VIDEOS_BASE}/delete`, {+ body: JSON.stringify({ video_names: videoNames }),+ method: 'POST',+ signal,+ });+};+const EXTENSION_BY_MIME: Readonly<Record<string, string>> = {'image/jpeg': 'jpg','image/png': 'png',diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.tsindex 4ec4129cf4..77c14e6295 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts@@ -1,6 +1,13 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';-import { readArchive, readEntryText } from './archive';+const transportMocks = vi.hoisted(() => ({ apiFetchRaw: vi.fn() }));++vi.mock('@platform/transport/http', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ apiFetchRaw: transportMocks.apiFetchRaw,+}));++import { INVK_MAX_ARCHIVE_BYTES, readArchive, readEntryText } from './archive';import { executeInvkExport, planInvkExport } from './exportProject';import { INVK_DOCUMENT_ENTRY, INVK_MANIFEST_ENTRY } from './format';@@ -85,6 +92,10 @@ describe('planInvkExport', () => {describe('executeInvkExport', () => {const bytesFor = (imageName: string) => new Uint8Array([...imageName].map((character) => character.codePointAt(0)!));+ beforeEach(() => {+ transportMocks.apiFetchRaw.mockReset();+ });+it('writes a readable archive holding the manifest, document, images and cover', async () => {const download = vi.fn();const result = await executeInvkExport(planInvkExport(planInput), {@@ -284,6 +295,65 @@ describe('executeInvkExport', () => {expect(download).toHaveBeenCalledTimes(1);});+ it('rejects a cumulative response refusal and cancels an active sibling fetch', async () => {+ let settleFirstRead: (result: ReadableStreamReadResult<Uint8Array>) => void = () => undefined;+ const firstRead = new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {+ settleFirstRead = resolve;+ });+ const firstReader = {+ cancel: vi.fn(() => {+ settleFirstRead({ done: true, value: undefined });++ return Promise.resolve();+ }),+ read: vi.fn(() => firstRead),+ releaseLock: vi.fn(),+ };+ const secondReader = {+ cancel: vi.fn(() => Promise.resolve()),+ read: vi+ .fn()+ .mockResolvedValueOnce({ done: false, value: new Uint8Array([1]) })+ .mockResolvedValueOnce({ done: true, value: undefined }),+ releaseLock: vi.fn(),+ };+ const secondBodyCancel = vi.fn(() => Promise.resolve());+ const secondGetReader = vi.fn(() => {+ // With one budget per request, let the first response finish so the+ // broken export resolves instead of hanging in this regression test.+ settleFirstRead({ done: true, value: undefined });++ return secondReader;+ });+ const responses = [+ {+ body: { cancel: vi.fn(() => Promise.resolve()), getReader: vi.fn(() => firstReader) },+ headers: new Headers({ 'content-length': String(INVK_MAX_ARCHIVE_BYTES) }),+ ok: true,+ },+ {+ body: { cancel: secondBodyCancel, getReader: secondGetReader },+ headers: new Headers({ 'content-length': '1' }),+ ok: true,+ },+ ] as unknown as Response[];++ transportMocks.apiFetchRaw.mockImplementation(() => responses.shift());+ const download = vi.fn();++ await expect(+ executeInvkExport(planInvkExport(planInput), {+ download,+ fetchImageThumbnail: () => Promise.resolve(null),+ })+ ).rejects.toMatchObject({ reason: 'too-large' });++ expect(download).not.toHaveBeenCalled();+ expect(secondGetReader).not.toHaveBeenCalled();+ expect(secondBodyCancel).toHaveBeenCalledTimes(1);+ expect(firstReader.cancel).toHaveBeenCalledTimes(1);+ });+it('reports progress through bundling and packing', async () => {const onProgress = vi.fn();diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.tsindex dafbf6cd62..d360b21df6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts@@ -5,14 +5,14 @@ import type { InvkArchiveEntry } from './archive';import type { FetchedThumbnail } from './assetTransport';import { binaryEntry, textEntry, writeArchive } from './archive';+import { coverExtensionForMime, createAssetExportTransport, isRequestCancellation } from './assetTransport';import {- coverExtensionForMime,- fetchImageBytes,- fetchImageThumbnail,- fetchVideoBytes,- isRequestCancellation,-} from './assetTransport';-import { INVK_DOCUMENT_ENTRY, INVK_IMAGES_PREFIX, INVK_MANIFEST_ENTRY, INVK_VIDEOS_PREFIX } from './format';+ INVK_DOCUMENT_ENTRY,+ INVK_IMAGES_PREFIX,+ INVK_MANIFEST_ENTRY,+ INVK_VIDEOS_PREFIX,+ InvkFormatError,+} from './format';import { buildInvkManifest, toInvkFileName } from './manifest';/**@@ -113,9 +113,10 @@ export interface InvkExportResult {}export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDeps): Promise<InvkExportResult> => {- const readImage = deps.fetchImageBytes ?? fetchImageBytes;- const readVideo = deps.fetchVideoBytes ?? fetchVideoBytes;- const readThumbnail = deps.fetchImageThumbnail ?? fetchImageThumbnail;+ const transport = createAssetExportTransport();+ const readImage = deps.fetchImageBytes ?? transport.fetchImageBytes;+ const readVideo = deps.fetchVideoBytes ?? transport.fetchVideoBytes;+ const readThumbnail = deps.fetchImageThumbnail ?? transport.fetchImageThumbnail;const entries = new Map<string, InvkArchiveEntry>();const missingAssetNames: string[] = [];let bundledImageCount = 0;@@ -127,7 +128,7 @@ export const executeInvkExport = async (plan: InvkExportPlan, deps: InvkExportDetry {return await read();} catch (error) {- if (isRequestCancellation(error)) {+ if (isRequestCancellation(error) || (error instanceof InvkFormatError && error.reason === 'too-large')) {throw error;}diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.tsindex 967e66cfe8..b5b31d9162 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts@@ -155,6 +155,28 @@ describe('restoreArchiveAssets', () => {expect(result.uploadedCount).toBe(1);});+ it('returns the authoritative server identities for every newly uploaded asset', async () => {+ const withVideo = await contents();++ withVideo.projectDocument = {+ ...withVideo.projectDocument,+ futureVideoInput: { video_name: 'clip.mp4' },+ };+ withVideo.videos.set('clip.mp4', new Uint8Array([7]));++ const result = await restoreArchiveAssets(withVideo, {+ findExistingImageNames: () => Promise.resolve(new Set()),+ findExistingVideoNames: () => Promise.resolve(new Set()),+ uploadArchiveImage: () => Promise.resolve({ height: 1, imageName: 'server-image.png', width: 1 }),+ uploadArchiveVideo: () => Promise.resolve({ videoName: 'server-video.mp4' }),+ });++ expect(result.uploadedAssets).toEqual({+ imageNames: ['server-image.png'],+ videoNames: ['server-video.mp4'],+ });+ });+it('reports a reference the archive never carried as dangling', async () => {const missing = await contents();@@ -227,6 +249,7 @@ describe('restoreArchiveAssets', () => {expect(result.coverImageName).toBe('server-cover.png');expect(result.danglingAssetNames).toEqual(['a.png']);+ expect(result.uploadedAssets.imageNames).toEqual(['server-cover.png']);expect(upload).toHaveBeenCalledWith(new Uint8Array([9]), 'cover.webp', {contentType: 'image/webp',signal: undefined,diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex bddce813cd..389bb8330d 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -130,10 +130,44 @@ export interface RestoreAssetsResult {danglingAssetNames: string[];/** Old name to new name, per kind. Kept apart because the namespaces are. */mappings: { images: Map<string, string>; videos: Map<string, string> };+ /** Authoritative server identities created by this restore, for failure rollback. */+ uploadedAssets: UploadedArchiveAssets;/** Assets uploaded from the archive, of either kind. */uploadedCount: number;}+export interface UploadedArchiveAssets {+ imageNames: string[];+ videoNames: string[];+}++export interface RollbackArchiveAssetsDeps {+ deleteArchiveImages?: (imageNames: string[], signal?: AbortSignal) => Promise<void>;+ deleteArchiveVideos?: (videoNames: string[], signal?: AbortSignal) => Promise<void>;+ signal?: AbortSignal;+}++/** Best-effort cleanup for server identities created by an import that could not create its project. */+export const rollbackArchiveAssets = async (+ uploadedAssets: UploadedArchiveAssets,+ deps: RollbackArchiveAssetsDeps = {}+): Promise<void> => {+ const transport = await import('./assetTransport');+ const deleteImages = deps.deleteArchiveImages ?? transport.deleteArchiveImages;+ const deleteVideos = deps.deleteArchiveVideos ?? transport.deleteArchiveVideos;+ const deletions: Promise<void>[] = [];++ if (uploadedAssets.imageNames.length > 0) {+ deletions.push(deleteImages(uploadedAssets.imageNames, deps.signal));+ }++ if (uploadedAssets.videoNames.length > 0) {+ deletions.push(deleteVideos(uploadedAssets.videoNames, deps.signal));+ }++ await Promise.allSettled(deletions);+};+export interface RestoreAssetsDeps {findExistingImageNames?: (imageNames: readonly string[], signal?: AbortSignal) => Promise<Set<string>>;findExistingVideoNames?: (videoNames: readonly string[], signal?: AbortSignal) => Promise<Set<string>>;@@ -174,6 +208,7 @@ interface PendingUpload {const resolveCoverImageName = async (input: {contents: InvkArchiveContents;mappings: { images: Map<string, string> };+ newlyUploadedImageNames: Set<string>;restoredImageNames: ReadonlySet<string>;signal?: AbortSignal;uploadImage: NonNullable<RestoreAssetsDeps['uploadArchiveImage']>;@@ -200,6 +235,8 @@ const resolveCoverImageName = async (input: {signal: input.signal,});+ input.newlyUploadedImageNames.add(uploaded.imageName);+return uploaded.imageName;} catch {// A project with no cover shows the folder glyph, which is a state the@@ -266,6 +303,8 @@ export const restoreArchiveAssets = async (const total = pending.length + (contents.cover === null ? 0 : 1);let completed = 0;let uploadedCount = 0;+ const newlyUploadedImageNames = new Set<string>();+ const newlyUploadedVideoNames = new Set<string>();/** Images this server can serve when the restore is done, under their final names. */const restoredImageNames = new Set(referencedImages.filter((name) => existingImages.has(name)));@@ -281,7 +320,10 @@ export const restoreArchiveAssets = async (uploadedCount += 1;if (kind === 'image') {+ newlyUploadedImageNames.add(restoredName);restoredImageNames.add(restoredName);+ } else {+ newlyUploadedVideoNames.add(restoredName);}if (restoredName !== name) {@@ -300,6 +342,7 @@ export const restoreArchiveAssets = async (const coverImageName = await resolveCoverImageName({contents,mappings,+ newlyUploadedImageNames,restoredImageNames,signal: deps.signal,uploadImage,@@ -310,5 +353,14 @@ export const restoreArchiveAssets = async (deps.onProgress?.({ completed, total });}- return { coverImageName, danglingAssetNames: danglingAssetNames.sort(), mappings, uploadedCount };+ return {+ coverImageName,+ danglingAssetNames: danglingAssetNames.sort(),+ mappings,+ uploadedAssets: {+ imageNames: [...newlyUploadedImageNames].sort(),+ videoNames: [...newlyUploadedVideoNames].sort(),+ },+ uploadedCount,+ };};diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex 9376cfd5b1..9523d428c3 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -1,6 +1,7 @@import { createDraftProject } from '@workbench/workbenchState';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type * as coversModule from './covers';import type * as projectFileModule from './projectFile';import type * as persistenceModule from './syncedPersistence';@@ -16,6 +17,8 @@ const api = vi.hoisted(() => ({deleteClientStateValue: vi.fn(() => Promise.resolve()),getClientStateValue: vi.fn(() => Promise.resolve(null)),getProject: vi.fn(),+ isProjectNotFoundError: (error: unknown) =>+ typeof error === 'object' && error !== null && 'status' in error && error.status === 404,setClientStateValue: vi.fn(() => Promise.resolve()),}));@@ -25,6 +28,13 @@ const covers = vi.hoisted(() => ({ recordProjectCover: vi.fn() }));const transport = vi.hoisted(() => ({coverExtensionForMime: () => 'webp',+ createAssetExportTransport: () => ({+ fetchImageBytes: transport.fetchImageBytes,+ fetchImageThumbnail: transport.fetchImageThumbnail,+ fetchVideoBytes: transport.fetchVideoBytes,+ }),+ deleteArchiveImages: vi.fn(() => Promise.resolve()),+ deleteArchiveVideos: vi.fn(() => Promise.resolve()),// `Uint8Array | null` up front: a fetcher that returns `null` is how the// "server would not serve it" path is exercised, and inferring the narrower// type here would make that untypeable at the call site.@@ -48,7 +58,7 @@ const transport = vi.hoisted(() => ({vi.mock('./api', () => api);vi.mock('./covers', async (importOriginal) => ({- ...(await importOriginal<typeof import('./covers')>()),+ ...(await importOriginal<typeof coversModule>()),recordProjectCover: covers.recordProjectCover,}));vi.mock('@platform/browser/downloadBlob', () => downloads);@@ -78,6 +88,22 @@ const rasterImageLayer = (id: string, imageName: string) => ({type: 'raster' as const,});+const projectWithRestorableAssets = (includeVideo = true) => {+ const project = createDraftProject([]);++ return {+ ...project,+ canvas: {+ ...project.canvas,+ document: {+ ...project.canvas.document,+ layers: [rasterImageLayer('restored-image', 'archive-image.png')],+ },+ },+ ...(includeVideo ? { futureVideoInput: { video_name: 'archive-video.mp4' } } : {}),+ };+};+const capturedArchive = (): File => {const [blob, fileName] = downloads.downloadBlob.mock.calls.at(-1)! as [Blob, string];@@ -107,9 +133,17 @@ beforeEach(async () => {transport.findExistingImageNames.mockImplementation((_names: readonly string[]) =>Promise.resolve(new Set<string>()));+ transport.findExistingVideoNames.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 }));+ transport.uploadArchiveVideo.mockImplementation((_bytes: Uint8Array, fileName: string) =>+ Promise.resolve({ videoName: `server-${fileName}` })+ );+ transport.deleteArchiveImages.mockImplementation(() => Promise.resolve());+ transport.deleteArchiveVideos.mockImplementation(() => Promise.resolve());api.getClientStateValue.mockImplementation(() => Promise.resolve(null));projectFile = await import('./projectFile');@@ -389,6 +423,169 @@ describe('importProjectFile', () => {expect(canvas.document.layers[0]?.source.image.imageName).toBe('server-legacy.png');});+ it('imports the shipped legacy JSON envelope under a fresh canonical identity without restoring assets', async () => {+ const legacyDocument = {+ ...persistence.serializeProjectDocument(projectWithRestorableAssets(false)),+ futureDocumentKey: { survives: true },+ id: 'legacy-project-id',+ invocation: { sourceId: 'project-graph' },+ name: ' Legacy JSON project ',+ };+ const file = new File(+ [+ JSON.stringify({+ document: legacyDocument,+ exportedAt: '2026-01-01T00:00:00.000Z',+ kind: 'invokeai-project',+ version: 1,+ }),+ ],+ 'Legacy JSON project.invokeproject.json',+ { type: 'application/json' }+ );++ acceptCreate();++ const { record } = await projectFile.importProjectFile(file);+ const request = api.createProject.mock.calls[0]![0] as {+ data: Record<string, unknown>;+ name: string;+ project_id: string;+ };++ expect(record.name).toBe('Legacy JSON project');+ expect(request.project_id).not.toBe('legacy-project-id');+ expect(request.data.id).toBe(request.project_id);+ expect(request.data.invocation).toMatchObject({ sourceId: 'workflow' });+ expect(request.data.futureDocumentKey).toEqual({ survives: true });+ expect(transport.findExistingImageNames).not.toHaveBeenCalled();+ expect(transport.findExistingVideoNames).not.toHaveBeenCalled();+ expect(transport.uploadArchiveImage).not.toHaveBeenCalled();+ expect(transport.uploadArchiveVideo).not.toHaveBeenCalled();+ });++ it.each([+ ['malformed JSON', '{'],+ ['another product kind', JSON.stringify({ document: {}, kind: 'other', version: 1 })],+ [+ 'an unsupported version',+ JSON.stringify({+ document: {},+ kind: 'invokeai-project',+ version: 2,+ }),+ ],+ ['a missing document', JSON.stringify({ kind: 'invokeai-project', version: 1 })],+ ])('refuses a legacy JSON envelope with %s before any mutation', async (_case, contents) => {+ const file = new File([contents], 'invalid.invokeproject.json', { type: 'application/json' });++ await expect(projectFile.importProjectFile(file)).rejects.toMatchObject({ reason: 'not-a-project' });+ expect(api.createProject).not.toHaveBeenCalled();+ expect(transport.findExistingImageNames).not.toHaveBeenCalled();+ expect(transport.findExistingVideoNames).not.toHaveBeenCalled();+ expect(transport.uploadArchiveImage).not.toHaveBeenCalled();+ expect(transport.uploadArchiveVideo).not.toHaveBeenCalled();+ });++ it('refuses an oversized legacy JSON file before materializing its text', async () => {+ const { INVK_MAX_ARCHIVE_BYTES } = await import('./invk/archive');+ const text = vi.fn(() => Promise.reject(new Error('legacy text was materialized')));+ const file = {+ name: 'oversized.invokeproject.json',+ size: INVK_MAX_ARCHIVE_BYTES + 1,+ text,+ } as unknown as File;++ await expect(projectFile.importProjectFile(file)).rejects.toMatchObject({ reason: 'too-large' });+ expect(text).not.toHaveBeenCalled();+ });++ it('rolls back every authoritative uploaded identity when project creation fails without hiding that failure', async () => {+ const account = await import('@platform/state/accountLifecycle');+ const { ApiError } = await import('@platform/transport/http');+ const primaryFailure = new Error('project create rejected');++ account.accountLifecycle.activate('rollback-user');+ await projectFile.exportOpenProject(projectWithRestorableAssets());+ api.createProject.mockRejectedValue(primaryFailure);+ api.getProject.mockRejectedValueOnce(new ApiError('not found', 404));+ transport.deleteArchiveImages.mockRejectedValueOnce(new Error('image cleanup failed'));+ transport.deleteArchiveVideos.mockRejectedValueOnce(new Error('video cleanup failed'));++ await expect(projectFile.importProjectFile(capturedArchive())).rejects.toBe(primaryFailure);++ expect(transport.deleteArchiveImages).toHaveBeenCalledWith(['server-archive-image.png'], expect.anything());+ expect(transport.deleteArchiveVideos).toHaveBeenCalledWith(['server-archive-video.mp4'], expect.anything());+ account.accountLifecycle.invalidate();+ });++ it('does not roll back when a rejected create may already have committed the project', async () => {+ const account = await import('@platform/state/accountLifecycle');+ const primaryFailure = new Error('connection ended after create');++ account.accountLifecycle.activate('ambiguous-response-user');+ await projectFile.exportOpenProject(projectWithRestorableAssets(false));+ api.createProject.mockRejectedValue(primaryFailure);+ api.getProject.mockResolvedValue({+ created_at: '2026-06-10 10:00:00.000',+ data: {},+ name: 'Committed project',+ project_id: 'committed-project',+ revision: 1,+ updated_at: '2026-06-10 10:00:00.000',+ });++ await expect(projectFile.importProjectFile(capturedArchive())).rejects.toBe(primaryFailure);++ expect(transport.deleteArchiveImages).not.toHaveBeenCalled();+ expect(transport.deleteArchiveVideos).not.toHaveBeenCalled();+ account.accountLifecycle.invalidate();+ });++ it('does not issue destructive rollback requests under a different account', async () => {+ const account = await import('@platform/state/accountLifecycle');++ account.accountLifecycle.activate('rollback-user-a');+ await projectFile.exportOpenProject(projectWithRestorableAssets(false));+ transport.uploadArchiveImage.mockImplementationOnce((_bytes: Uint8Array, fileName: string) => {+ account.accountLifecycle.activate('rollback-user-b');++ return Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 });+ });++ await expect(projectFile.importProjectFile(capturedArchive())).rejects.toThrow('no longer active');++ expect(api.createProject).not.toHaveBeenCalled();+ expect(transport.deleteArchiveImages).not.toHaveBeenCalled();+ expect(transport.deleteArchiveVideos).not.toHaveBeenCalled();+ account.accountLifecycle.invalidate();+ });++ it('does not roll back assets after an ambiguous create that returned before the account changed', async () => {+ const account = await import('@platform/state/accountLifecycle');++ account.accountLifecycle.activate('ambiguous-create-user-a');+ await projectFile.exportOpenProject(projectWithRestorableAssets(false));+ api.createProject.mockImplementation((request: { name: string; project_id?: string }) => {+ account.accountLifecycle.activate('ambiguous-create-user-b');++ return 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',+ });+ });++ await expect(projectFile.importProjectFile(capturedArchive())).rejects.toThrow('no longer active');++ expect(transport.deleteArchiveImages).not.toHaveBeenCalled();+ expect(transport.deleteArchiveVideos).not.toHaveBeenCalled();+ account.accountLifecycle.invalidate();+ });+it('does not upload an account A file after local parsing completes under account B', async () => {const account = await import('@platform/state/accountLifecycle');diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 2b9414fefa..c2cc8bc6ab 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -9,13 +9,59 @@ import {isAccountScopeCurrent,} from '@platform/state/accountLifecycle';-import { createProject as apiCreateProject, getProject as apiGetProject, type ProjectRecordDTO } from './api';+import {+ createProject as apiCreateProject,+ getProject as apiGetProject,+ isProjectNotFoundError,+ type ProjectRecordDTO,+} from './api';import { recordProjectCover } from './covers';import { createProjectId } from './ids';import { INVK_EXTENSION, InvkFormatError } from './invk/format';import { upsertProjectSummary } from './library';import { remapAssetRefs } from './projectAssets';+export const PROJECT_FILE_KIND = 'invokeai-project';+export const PROJECT_FILE_VERSION = 1;+export const LEGACY_PROJECT_FILE_EXTENSION = '.invokeproject.json';++export interface ProjectFile {+ document: Record<string, unknown>;+ exportedAt: string;+ kind: typeof PROJECT_FILE_KIND;+ version: typeof PROJECT_FILE_VERSION;+}++/** Kept for callers that still construct the JSON envelope shipped before `.invk`. */+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 legacy document, or null when the text is not one of our exports. */+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;+ }++ return parsed.document as Record<string, unknown>;+ } catch {+ return null;+ }+};+/*** Export and import a project as an `.invk` archive.*@@ -89,9 +135,36 @@ export interface ProjectImportOutcome {}const readProjectDocument = async (file: File) => {+ if (file.name.toLowerCase().endsWith(LEGACY_PROJECT_FILE_EXTENSION)) {+ const { INVK_MAX_ARCHIVE_BYTES } = await import('./invk/archive');++ if (file.size > INVK_MAX_ARCHIVE_BYTES) {+ throw new InvkFormatError('too-large', `Project file is ${file.size} bytes.`);+ }++ const projectDocument = parseProjectFile(await file.text());++ if (projectDocument === null) {+ throw new InvkFormatError('not-a-project', 'This JSON file is not an Invoke project export.');+ }++ return { format: 'legacy-json' as const, projectDocument };+ }+const { readInvkArchive } = await import('./invk/importProject');- return readInvkArchive(file);+ return { contents: await readInvkArchive(file), format: 'invk' as const };+};++/** A rejected create is safe to clean up only when its client-chosen id is confirmed absent. */+const isProjectConfirmedAbsent = async (projectId: string, owner: AccountScope): Promise<boolean> => {+ try {+ await apiGetProject(projectId, owner.signal);++ return false;+ } catch (error) {+ return isAccountScopeCurrent(owner) && isProjectNotFoundError(error);+ }};const exportProjectDocument = async (@@ -159,16 +232,17 @@ export const importProjectFile = async (options: ProjectFileOptions = {}): Promise<ProjectImportOutcome> => {const owner = options.owner ?? captureAccountScope();- const contents = await readProjectDocument(file);+ const source = await readProjectDocument(file);+ const projectDocument = source.format === 'invk' ? source.contents.projectDocument : source.projectDocument;assertAccountScopeCurrent(owner);const id = createProjectId();const name =- typeof contents.projectDocument.name === 'string' && contents.projectDocument.name.trim()- ? contents.projectDocument.name.trim()+ typeof projectDocument.name === 'string' && projectDocument.name.trim()+ ? projectDocument.name.trim(): 'Imported project';- const candidate = { ...contents.projectDocument, id, name };+ const candidate = { ...projectDocument, 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.@@ -184,30 +258,62 @@ export const importProjectFile = async (const { serializeProjectDocument } = await import('./projectDocument');const canonicalDocument = serializeProjectDocument(project);- const { restoreArchiveAssets } = await import('./invk/importProject');- const restored = await restoreArchiveAssets({ ...contents, projectDocument: canonicalDocument }, {- signal: owner.signal,- ...(options.onProgress === undefined- ? {}- : {- onProgress: ({ completed, total }) => options.onProgress?.({ completed, phase: 'restoring', total }),- }),- });-- assertAccountScopeCurrent(owner);-- const document = remapAssetRefs(canonicalDocument, restored.mappings);-- const record = await apiCreateProject({ data: document, name, project_id: id }, owner.signal);+ const restored =+ source.format === 'invk'+ ? await (async () => {+ const { restoreArchiveAssets } = await import('./invk/importProject');++ return restoreArchiveAssets(+ { ...source.contents, projectDocument: canonicalDocument },+ {+ signal: owner.signal,+ ...(options.onProgress === undefined+ ? {}+ : {+ onProgress: ({ completed, total }) =>+ options.onProgress?.({ completed, phase: 'restoring', total }),+ }),+ }+ );+ })()+ : null;+ let didCreateProject = false;++ try {+ assertAccountScopeCurrent(owner);++ const document = restored === null ? canonicalDocument : remapAssetRefs(canonicalDocument, restored.mappings);+ const record = await apiCreateProject({ data: document, name, project_id: id }, owner.signal);++ didCreateProject = true;+ assertAccountScopeCurrent(owner);+ upsertProjectSummary({ id: record.project_id, name: record.name, revision: record.revision }, owner);++ if (restored?.coverImageName) {+ recordProjectCover(record.project_id, restored.coverImageName, owner);+ }- assertAccountScopeCurrent(owner);- upsertProjectSummary({ id: record.project_id, name: record.name, revision: record.revision }, owner);+ return { danglingAssetNames: restored?.danglingAssetNames ?? [], record };+ } catch (error) {+ const canRollback =+ !didCreateProject &&+ restored !== null &&+ isAccountScopeCurrent(owner) &&+ (await isProjectConfirmedAbsent(id, owner));++ if (canRollback) {+ try {+ const { rollbackArchiveAssets } = await import('./invk/importProject');++ await rollbackArchiveAssets(restored.uploadedAssets, { signal: owner.signal });+ } catch {+ // Cleanup is best-effort. The create/scope failure is the actionable+ // result and must never be replaced by a failed delete request.+ }+ }- if (restored.coverImageName !== null) {- recordProjectCover(record.project_id, restored.coverImageName, owner);+ throw error;}-- return { danglingAssetNames: restored.danglingAssetNames, record };};/** Open the browser's file picker for a project file; null when dismissed. */@@ -230,7 +336,7 @@ export const pickProjectFile = (owner: AccountScope = captureAccountScope()): Prconst handleAbort = (): void => finish(null);input.type = 'file';- input.accept = INVK_EXTENSION;+ input.accept = `${INVK_EXTENSION},${LEGACY_PROJECT_FILE_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/projectFilePicker.browser.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFilePicker.browser.test.tsnew file mode 100644index 0000000000..063d1d1f9a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFilePicker.browser.test.ts@@ -0,0 +1,21 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { pickProjectFile } from './projectFile';++afterEach(() => {+ vi.restoreAllMocks();+});++describe('pickProjectFile', () => {+ it('offers both current archives and shipped legacy JSON project files', async () => {+ let acceptedTypes = '';++ vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(function (this: HTMLInputElement) {+ acceptedTypes = this.accept;+ this.oncancel?.(new Event('cancel'));+ });++ await expect(pickProjectFile()).resolves.toBeNull();+ expect(acceptedTypes.split(',')).toEqual(['.invk', '.invokeproject.json']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsxnew file mode 100644index 0000000000..4ec9e26e19--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx@@ -0,0 +1,172 @@+import type * as chakraUiModule from '@chakra-ui/react';+import type { Project } from '@workbench/projectContracts';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++const harness = vi.hoisted(() => {+ const state = {+ events: [] as string[],+ exportedPrompt: null as string | null,+ prompt: 'prompt before the debounced edit',+ };+ const makeProject = (): Project =>+ ({+ id: 'project-1',+ name: 'Prompt project',+ queue: { items: [] },+ widgetInstances: {+ generate: { values: { positivePrompt: state.prompt } },+ },+ }) as unknown as Project;++ return {+ ...state,+ flushGenerateDrafts: vi.fn(() => {+ state.events.push('flush');+ state.prompt = 'prompt from the immediate debounced edit';+ }),+ getProject: vi.fn(() => {+ state.events.push('read');+ return makeProject();+ }),+ makeProject,+ startExport: vi.fn((project: Project) => {+ state.events.push('export');+ const widgetInstances = project.widgetInstances as unknown as {+ generate: { values: { positivePrompt: string } };+ };++ state.exportedPrompt = widgetInstances.generate.values.positivePrompt;+ }),+ state,+ };+});++vi.mock('@chakra-ui/react', async (importOriginal) => {+ const actual = await importOriginal<typeof chakraUiModule>();+ const Container = ({ children }: { children?: ReactNode }): ReactNode => children ?? null;+ const Item = ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (+ <button role="menuitem" onClick={onClick}>+ {children}+ </button>+ );++ return {+ ...actual,+ Menu: {+ ...actual.Menu,+ Item,+ ItemGroup: Container,+ ItemGroupLabel: Container,+ ItemIndicator: Container,+ ItemText: Container,+ Positioner: Container,+ RadioItem: Item,+ RadioItemGroup: Container,+ Root: Container,+ Separator: () => null,+ Trigger: Container,+ },+ Portal: Container,+ };+});++vi.mock('@features/generation/react', () => ({ flushGenerateDrafts: harness.flushGenerateDrafts }));+vi.mock('@features/models', () => ({ useModelLoads: () => [] }));+vi.mock('@features/queue/contracts', () => ({+ getProjectQueueIndicatorState: () => ({ progressState: 'idle', runningQueueItemId: null }),+}));+vi.mock('@features/queue/react', () => ({ useQueueItemProgress: () => null }));+vi.mock('@platform/ui/ConfirmDialog', () => ({ ConfirmDialog: () => null }));+vi.mock('@platform/ui/Menu', () => ({+ MenuContent: ({ children }: { children?: ReactNode }): ReactNode => children ?? null,+}));+vi.mock('@platform/ui/RenameDialog', () => ({ RenameDialog: () => null }));+vi.mock('@workbench/components/QueueProgressIndicator', () => ({ QueueCircularProgress: () => null }));+vi.mock('@workbench/launchpad/formatRelativeTime', () => ({ formatRelativeTime: () => '' }));+vi.mock('@workbench/projects/components', () => ({ OpenProjectDialog: () => null }));+vi.mock('@workbench/projects/library', () => ({+ refreshProjectLibrary: vi.fn(() => Promise.resolve()),+ useProjectLibrarySelector: (selector: (snapshot: { summaries: [] }) => unknown) => selector({ summaries: [] }),+}));+vi.mock('@workbench/projects/useProjectActions', () => ({+ useProjectActions: () => ({ closeProject: vi.fn(), deleteProject: vi.fn(), openProject: vi.fn() }),+}));+vi.mock('@workbench/projects/useProjectFileActions', () => ({+ useExportOpenProject: () => harness.startExport,+}));+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));+vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.makeProject()),+ useWorkbenchCommands: () => ({ projects: { create: vi.fn(), rename: vi.fn() } }),+ useWorkbenchQueries: () => ({ getProject: harness.getProject }),+ useWorkbenchSelector: (selector: (snapshot: unknown) => unknown) =>+ selector({+ backendConnection: { status: 'connected' },+ projects: [harness.makeProject()],+ }),+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++import { ProjectSwitcher } from './ProjectSwitcher';+import { setProjectSwitcherOpen } from './projectSwitcherStore';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++beforeEach(async () => {+ harness.state.events.length = 0;+ harness.state.exportedPrompt = null;+ harness.state.prompt = 'prompt before the debounced edit';+ harness.flushGenerateDrafts.mockClear();+ harness.getProject.mockClear();+ harness.startExport.mockClear();+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ setProjectSwitcherOpen(true);++ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <ProjectSwitcher />+ </ChakraProvider>+ )+ );+});++afterEach(async () => {+ await act(() => {+ setProjectSwitcherOpen(false);+ root?.unmount();+ });+ host?.remove();+ host = null;+ root = null;+});++describe('ProjectSwitcher export', () => {+ it('flushes an immediate debounced prompt edit before reading and exporting the project', async () => {+ let exportItem: HTMLElement | undefined;++ await vi.waitFor(() => {+ exportItem = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(+ (item) => item.textContent === 'common.export'+ );+ expect(exportItem).toBeDefined();+ });++ await act(() => userEvent.click(exportItem!));++ expect(harness.state.events).toEqual(['flush', 'read', 'export']);+ expect(harness.state.exportedPrompt).toBe('prompt from the immediate debounced edit');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsxindex ff63bd3116..aab3cd3a33 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx@@ -105,6 +105,8 @@ export const ProjectSwitcher = () => {);const showActiveProjectDetails = useCallback(() => openWorkbenchWidget('project'), [openWorkbenchWidget]);const exportActiveProject = useCallback(() => {+ flushGenerateDrafts();+const project = getProject(activeProjectId);if (!project) {