Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

test(webv2): round-trip complete project boards

Josh Corbettf6196919adca
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdx
index 64007efd1b..c3b6cd3bfd 100644
--- a/docs/src/content/docs/development/Front End/project-files.mdx
+++ b/docs/src/content/docs/development/Front End/project-files.mdx
@@ -6,16 +6,26 @@ Workbench projects export to a portable `.invk` archive. The feature lives in `i
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).
+`.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 3. The two are deliberately not interchangeable — see [Versions](#versions).
+
+## Every project owns one board
+
+The backend gives each project exactly one private board (`projects.board_id` is `NOT NULL UNIQUE` with a foreign key to `boards`). The board is the project's workspace: everything it generates lands there, and only the project APIs may touch it.
+
+- **Renaming** a project renames its board in the same transaction. The generic `PATCH /boards/{id}` refuses a claimed board with `409`, so the two names cannot commit independently.
+- **Deleting** a project deletes its board with it, in one transaction. `DELETE /boards/{id}` refuses a claimed board *before* touching any media, and the foreign key is the backstop for a board claimed concurrently.
+- **The media survives.** Deleting a project removes the board and its memberships; the images and videos themselves return to Uncategorized, exactly as they would if the board were deleted without `include_images`.
+- **The document's `projectBoardId` is a cache, never the truth.** Hydration overwrites it from the project record, and export strips it — along with `selectedBoardId` — because a board id means nothing on the install a project arrives at. Board ids elsewhere in a document, such as a workflow node's board input, are deliberately left alone.
## File format
-`.invk` files are ZIP archives. The current manifest version is `2`.
+`.invk` files are ZIP archives. The current manifest version is `3`.
| 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`. |
+| `board.json` | v3 | The project board's visible contents as the exporting server enumerated them: `{version: 1, items: [{kind, category, name, starred}]}`. |
| `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. |
@@ -26,15 +36,23 @@ The manifest is written indented and the document compact: the manifest is the o
## 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.
+A project's media comes from two places that overlap, and the difference between them decides everything about how a transfer treats an item.
+
+**Board membership** is what the project's gallery shows: everything it has produced, including results the canvas never used. It comes from `GET /projects/{id}/board-snapshot` and is written to `board.json`. Enumerating it is fatal if it fails — an archive whose `board.json` silently said "empty" would be a lie the reader has no way to detect.
+
+**Document references** are the pixels the project draws with. They come from `collectLiveAssetRefs()`, exactly as they always did.
+
+An item can be either or both, and the union is fetched once. What travels in `board.json` is only what the gallery would show for that board: the four visible categories (`general`, `control`, `mask`, `user`) and nothing intermediate. The canvas's private `other` category never travels as board membership — the media a document points at is the document, not gallery content — though a document reference under any category still travels as a bundled asset.
-Which ones is decided by `collectLiveAssetRefs()` in `projects/projectAssets.ts`. It walks the document collecting every string found under `imageName` and `image_name` as an image, and under `video_name` as a video — the only keys in the document that hold an asset 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.
+Which document references is decided by `collectLiveAssetRefs()` in `projects/projectAssets.ts`. It walks the document collecting every string found under `imageName` and `image_name` as an image, and under `video_name` as a video — the only keys in the document that hold an asset 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.
`video_name` reaches a document through an imported workflow whose node value was authored elsewhere (`VideoField` in the backend's `fields.py`, consumed by `video_frame_extract` and friends). webv2 cannot author one yet — `VideoField` is absent from `STATEFUL_FIELD_TYPE_NAMES` — but it round-trips one verbatim, so a project file has to carry it.
+**Installation state is excluded.** `stripInstallationState()` removes the gallery's `projectBoardId` and `selectedBoardId` along with its selection, at any depth, before the document is serialized. Both describe *this install*: the board ids mean nothing elsewhere, and the receiving server assigns its own.
+
**The gallery selection is excluded, of either kind.** `selectedImage`, `selectedImageName`, `selectedImageNames` and `compareImage` are pointers into per-install gallery content, not things the document renders; a project arriving on another machine should open with nothing selected rather than drag a stranger's gallery in behind it.
-Exclusion is two things, not one. The collector skips those keys so their pixels are never bundled, and `stripGallerySelection()` removes them from the document before `planInvkExport()` serializes it. Skipping alone would not be enough: an unbundled reference still travels, it just travels broken — and because import collects with the same skip list, the restore pass cannot even report it as dangling. Every reader of these values already parses them with `typeof`/`Array.isArray` guards and falls back to no selection, so removing the key is the same as clearing it.
+Exclusion is two things, not one. The collector skips those keys so their pixels are never bundled, and `stripInstallationState()` removes them from the document before `planInvkExport()` serializes it. Skipping alone would not be enough: an unbundled reference still travels, it just travels broken — and because import collects with the same skip list, the restore pass cannot even report it as dangling. Every reader of these values already parses them with `typeof`/`Array.isArray` guards and falls back to no selection, so removing the key is the same as clearing it.
The skip is by key on purpose, because the members got there differently. `selectedImage` and the name keys were already missed — `GalleryItem` spells its name field `name`, which no collector key matches — but that is an accident of naming that a rename would have undone. `compareImage` is a `GeneratedImageContract` carrying `imageName`, so it was genuinely being bundled until the exclusion became explicit.
@@ -42,19 +60,39 @@ The skip is by key on purpose, because the members got there differently. `selec
## Loading
-`readInvkArchive()` unpacks and validates; `restoreArchiveAssets()` puts the pixels back.
+`readInvkArchive()` unpacks and validates; `restoreProjectMedia()` — shared with duplication — puts the media back.
+
+Import deliberately orders its work as **read → mint identity → validate and canonicalize → stage a board → 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.
-Import 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.
+**Creating the project is the commit point.** When an archive carries board media, the restore first creates an unclaimed private *staging board* and uploads onto it, then passes that board's id to `POST /projects`, which claims and renames it in the same transaction that writes the remapped document. Creating the project first would mean posting the old names and then updating with the remapped ones — making the update the commit point, where a failure leaves a real project full of references to media that never arrived. A v2 archive or a legacy JSON document has no board to stage, so the server simply creates an empty one, exactly as it does for a project made from scratch.
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.
+### Board media always gets a fresh identity
+
+`board_images` has `PRIMARY KEY (image_name)`: an image sits on exactly one board. A restore that saw its own name already on the destination and reused it would not be restoring the project's board — it would be *moving* somebody else's image onto it, and deleting either project's board would then take that image from both. So every board item is uploaded (or, when duplicating, copied) unconditionally, with no existence check, and the document is rewritten to the new name. Its archived category and starring are restored: the category on upload, the starring through the same `POST /images/star` the gallery uses, so import and duplication share one starring path.
+
+Document references outside the board keep the v2 behaviour: an identity the destination already has satisfies them, so nothing is uploaded twice. That is what makes re-importing your own export nearly free.
+
+**A failed board item is forced dangling.** If an item that is both board membership and a document reference cannot be restored, its reference must not be left on the archived name. On the same server — every duplication, every re-import — that name is already taken, by the source project's own image, so the project would open showing the right picture from the wrong owner, and deleting the original would break it with no explanation. Such a reference is remapped to a name derived from the new project id, which resolves to nothing and renders as a missing layer, exactly as a dangling v2 reference already does.
+
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.
+### Duplication
+
+Duplicating a project is the same restore with the bytes taking a shortcut. Both projects live on one server, so `POST /images/copy` and `POST /videos/copy` mint the new identities in place: no bytes reach the browser, and a 2 GiB board costs no traffic rather than 4 GiB and two requests per item. Everything else — the planning, the remapping, the forced-dangling rule, the issue reporting, the rollback ledger — is the code import uses; only the materialization step differs. Document-only references are not copied at all, because the identities they name already exist here.
+
+An open project is flushed to the server before it is read, and a failed flush aborts the duplication: copying what the server last acknowledged would silently drop everything the person can still see.
+
+### Rollback
+
+Restoration records the authoritative server names returned by every successful upload or copy, as it goes rather than at the end, so a restore that is cancelled part way through is still cleanable. 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.
+
+The staging board is deleted last, and with `include_images=false`, so anything that wandered onto it while the import ran — a generation that finished in the meantime — survives as Uncategorized rather than being collected by a cleanup that never meant it.
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.
@@ -70,6 +108,12 @@ A project file is the one operation here whose duration is set by how much someo
Both directions can half-succeed: export skips assets the server will not serve, import leaves references dangling. Both are correct, and both are things the person holding the file needs to know before handing it to someone else — so a lossy run finishes as a warning naming the count, and only a clean run finishes as a plain success. An operation cancelled by the account going away has no verdict to show and dismisses its toast instead.
+**Losses are counted apart, because they cost different things.** A missing board item is a result still findable elsewhere; a missing document reference is a hole in the canvas. One combined number meant anything from "you will not notice" to "the project is broken", so `ProjectTransferIssues` carries `boardItemIssues` and `documentReferenceIssues` separately, each entry typed with a reason (`fetch-failed`, `missing-entry`, `upload-failed`, `star-failed`). An item that was both appears in both arrays — it genuinely failed in both roles. Only the two counts reach the toast; the typed detail stays on the returned outcome.
+
+A media failure is never fatal. The failures that do abort are the ones that would produce a lie or a half-built project: an unreadable archive, a document that will not rehydrate, an enumeration that could not be fetched, a cancelled signal, an expired account.
+
+**Complete export versus media-only download.** A project board's menu offers both. *Export project (.invk)* is the project — its document, its board and the bytes. *Download Board* is the pixels as a ZIP of images, with the count of videos it omits stated in the label. They are different things and neither replaces the other.
+
## 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.
@@ -86,11 +130,13 @@ On import the cover prefers an image the restore already put on this server —
## Versions
+Version 3 requires `board.json` and refuses an archive without it as `damaged`. Version 2 is still read and is deliberately *not* asked to carry board membership: an archive written before boards existed has no board to describe, and inventing an empty one for it would claim knowledge the file does not contain — so a v2 import restores its document references and lets the server create the new project an empty board. The archive's `board.json` carries its own `version: 1`, which is the *file's* version and not the API's: the snapshot endpoint returns `{items}` and nothing else, so neither format is pinned to the other.
+
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.
+The legacy reader is the mirror image: it pins `version: 1` and refuses everything this app writes.
-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.
+Future format changes should add a new member to the union rather than widening version 3, so that every version this app has ever written can be named precisely when refused.
## Guards
@@ -104,7 +150,11 @@ On the way in, the budget is enforced through fflate's entry filter (`createExpa
## HTTP-contract verification
-The mock-backed browser journey exercises the real export action and file chooser: it exports a representative project, resets the backend, imports into a fresh browser context, and verifies the persisted project, remapped image and video references, restored-media retrieval, and cover-index entry through HTTP. Only image upload was missing from the mock backend's project-file media contract; the journey uses the existing video upload path. This verifies the request and persistence contracts, including server-assigned asset names, not binary fidelity between archived and restored bytes.
+The mock-backed browser journey exercises the real export action and file chooser end to end. It opens a fixture project whose board deliberately carries every case — a result the canvas also draws with, one it never used, an asset per visible category, a video, a starred item, an intermediate and an `other` item that must not travel, plus references that live outside the board — exports it, inspects the manifest, `board.json` and the binary entries, then resets the backend *preserving deliberate name collisions* and imports into a fresh browser context.
+
+The collisions are the point: the destination is seeded with images and a video under the archived names, so the journey can prove that board media takes new identities while a document-only reference is satisfied by the identity already there. It then duplicates the imported project and asserts the same rules with no bytes moving, and finally imports a deliberately damaged archive to check that the two warning counts are reported separately and differ.
+
+This verifies the request and persistence contracts, including server-assigned asset names, not binary fidelity between archived and restored bytes. Generation metadata does survive a real round trip: `image_files_disk.save` writes it into the PNG's text chunks and `extract_metadata_from_image` reads it back, which is how `POST /images/copy` carries provenance without any extra plumbing — pinned by `TestProvenanceRoundTrip` in `tests/app/services/image_files/test_image_files_disk.py`.
## Compatibility notes
@@ -112,4 +162,4 @@ Earlier webv2 builds exported `*.invokeproject.json` files containing a version
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.
+**Not exported:** models and LoRAs, workflows from the library, queue history, intermediates, the canvas's private `other` media except where the document references it, gallery boards other than the project's own, and account preferences. A project file carries one project's workspace, not the install around it.
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 1ff4905839..3fb8d05204 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,17 +2,17 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 824604,
+ "brotliBytes": 826351,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 824231,
+ "gzipBytes": 825960,
"imageRawBytes": 156376,
- "initialRawBytes": 1914481,
+ "initialRawBytes": 1919126,
"largestAssetRawBytes": 746170,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 66759,
- "requestCount": 33,
- "scriptRequestCount": 17,
+ "ownedRawBytes": 66207,
+ "requestCount": 35,
+ "scriptRequestCount": 19,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -264,6 +264,7 @@
"source:src/workbench/projects/projectFileErrors.ts",
"source:src/workbench/projects/projectFileToasts.ts",
"source:src/workbench/projects/session.ts",
+ "source:src/workbench/projects/syncStore.ts",
"source:src/workbench/projects/useProjectFileActions.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
@@ -272,17 +273,17 @@
]
},
"limits": {
- "brotliBytes": 832851,
+ "brotliBytes": 834615,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 832474,
+ "gzipBytes": 834220,
"imageRawBytes": 157940,
- "initialRawBytes": 1933626,
+ "initialRawBytes": 1938318,
"largestAssetRawBytes": 753632,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 66759,
- "requestCount": 33,
- "scriptRequestCount": 17
+ "ownedRawBytes": 66207,
+ "requestCount": 35,
+ "scriptRequestCount": 19
},
"owner": "app",
"remediationTicket": "set-performance-budgets",
@@ -290,17 +291,17 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1006358,
+ "brotliBytes": 1009372,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1003881,
+ "gzipBytes": 1006745,
"imageRawBytes": 156376,
- "initialRawBytes": 2463476,
+ "initialRawBytes": 2471744,
"largestAssetRawBytes": 746170,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 113398,
- "requestCount": 77,
- "scriptRequestCount": 61,
+ "ownedRawBytes": 113633,
+ "requestCount": 79,
+ "scriptRequestCount": 63,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -699,6 +700,8 @@
"source:src/workbench/projects/ids.ts",
"source:src/workbench/projects/invk/format.ts",
"source:src/workbench/projects/library.ts",
+ "source:src/workbench/projects/openProjectBroker.ts",
+ "source:src/workbench/projects/openProjects.ts",
"source:src/workbench/projects/projectAssets.ts",
"source:src/workbench/projects/projectDocument.ts",
"source:src/workbench/projects/projectFile.ts",
@@ -793,24 +796,24 @@
]
},
"limits": {
- "brotliBytes": 1016422,
+ "brotliBytes": 1019466,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1013920,
+ "gzipBytes": 1016813,
"imageRawBytes": 157940,
- "initialRawBytes": 2488111,
+ "initialRawBytes": 2496462,
"largestAssetRawBytes": 753632,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 113398,
- "requestCount": 77,
- "scriptRequestCount": 61
+ "ownedRawBytes": 113633,
+ "requestCount": 79,
+ "scriptRequestCount": 63
},
"owner": "workbench",
"remediationTicket": "deepen-widget-registry-loading",
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-08-05",
+ "capturedAt": "2026-08-07",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
@@ -855,7 +858,9 @@
"src/features/queue/ui/launchpad/QueueStatusBand.tsx",
"src/workbench/launchpad/home/livePanels.ts"
],
- "editorForbiddenInitialChunkNames": ["ag-psd"],
+ "editorForbiddenInitialChunkNames": [
+ "ag-psd"
+ ],
"inactiveWidgetGateOwner": "deepen-widget-registry-loading"
}
}
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 043d36ea34..1c3a1bbd17 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1,6 +1,6 @@
{
- "browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome",
- "capturedAt": "2026-08-05",
+ "browserExecutable": "/home/josh/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome",
+ "capturedAt": "2026-08-07",
"routes": [
{
"activatedResourceBaseline": {
@@ -25,11 +25,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 106.19999999925494,
+ "domContentLoadedMedianMs": 148.10000000149012,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 106.19999999925494,
- "longestTaskMaxMs": 65,
+ "loadMedianMs": 148.10000000149012,
+ "longestTaskMaxMs": 95,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -39,24 +39,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 28,
- "scriptRawBytes": 1582132,
- "scriptRequestCount": 24,
- "totalRawBytes": 1733731
+ "otherRawBytes": 126172,
+ "requestCount": 30,
+ "scriptRawBytes": 1586951,
+ "scriptRequestCount": 26,
+ "totalRawBytes": 1738946
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 28,
- "scriptRawBytes": 1597954,
- "scriptRequestCount": 24,
- "totalRawBytes": 1751069
+ "otherRawBytes": 127434,
+ "requestCount": 30,
+ "scriptRawBytes": 1602821,
+ "scriptRequestCount": 26,
+ "totalRawBytes": 1756336
},
- "routeReadyMedianMs": 237.19999999925494,
+ "routeReadyMedianMs": 340.7000000011176,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -83,11 +83,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 108.5,
+ "domContentLoadedMedianMs": 148.90000000037253,
"id": "launchpad",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 108.5,
- "longestTaskMaxMs": 66,
+ "loadMedianMs": 148.90000000037253,
+ "longestTaskMaxMs": 94,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -97,24 +97,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 28,
- "scriptRawBytes": 1582132,
- "scriptRequestCount": 24,
- "totalRawBytes": 1733731
+ "otherRawBytes": 126172,
+ "requestCount": 30,
+ "scriptRawBytes": 1586951,
+ "scriptRequestCount": 26,
+ "totalRawBytes": 1738946
},
"resourceLimits": {
"cssRawBytes": 2181,
"fontRawBytes": 23901,
"imageRawBytes": 0,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 28,
- "scriptRawBytes": 1597954,
- "scriptRequestCount": 24,
- "totalRawBytes": 1751069
+ "otherRawBytes": 127434,
+ "requestCount": 30,
+ "scriptRawBytes": 1602821,
+ "scriptRequestCount": 26,
+ "totalRawBytes": 1756336
},
- "routeReadyMedianMs": 254.39999999850988,
+ "routeReadyMedianMs": 362.3999999985099,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -141,13 +141,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 111.10000000149012,
+ "domContentLoadedMedianMs": 154.2000000011176,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 111.10000000149012,
- "longestTaskMaxMs": 93,
+ "loadMedianMs": 154.30000000074506,
+ "longestTaskMaxMs": 139,
"owner": "workbench",
- "projectSwitchMedianMs": 67.26180899999963,
+ "projectSwitchMedianMs": 303.8221630000007,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -155,24 +155,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 101,
- "scriptRawBytes": 3273241,
- "scriptRequestCount": 95,
- "totalRawBytes": 3596629
+ "otherRawBytes": 126172,
+ "requestCount": 103,
+ "scriptRawBytes": 3280945,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3604729
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 101,
- "scriptRawBytes": 3305974,
- "scriptRequestCount": 95,
- "totalRawBytes": 3632596
+ "otherRawBytes": 127434,
+ "requestCount": 103,
+ "scriptRawBytes": 3313755,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3640777
},
- "routeReadyMedianMs": 624.6999999992549,
+ "routeReadyMedianMs": 770.5,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -199,13 +199,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 107.19999999925494,
+ "domContentLoadedMedianMs": 150.5,
"id": "editor-minimal",
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 107.30000000074506,
- "longestTaskMaxMs": 98,
+ "loadMedianMs": 150.5,
+ "longestTaskMaxMs": 168,
"owner": "workbench",
- "projectSwitchMedianMs": 89.32770100000198,
+ "projectSwitchMedianMs": 367.72414299999946,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -213,24 +213,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 101,
- "scriptRawBytes": 3273241,
- "scriptRequestCount": 95,
- "totalRawBytes": 3596629
+ "otherRawBytes": 126172,
+ "requestCount": 103,
+ "scriptRawBytes": 3280945,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3604729
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 101,
- "scriptRawBytes": 3305974,
- "scriptRequestCount": 95,
- "totalRawBytes": 3632596
+ "otherRawBytes": 127434,
+ "requestCount": 103,
+ "scriptRawBytes": 3313755,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3640777
},
- "routeReadyMedianMs": 672.6000000014901,
+ "routeReadyMedianMs": 829.5999999996275,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -239,7 +239,7 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 135423,
+ "largestAssetRawBytes": 135424,
"otherRawBytes": 0,
"requestCount": 4,
"scriptRawBytes": 277726,
@@ -250,18 +250,18 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 136778,
+ "largestAssetRawBytes": 136779,
"otherRawBytes": 0,
"requestCount": 4,
"scriptRawBytes": 280504,
"scriptRequestCount": 4,
"totalRawBytes": 280504
},
- "domContentLoadedMedianMs": 112.09999999776483,
+ "domContentLoadedMedianMs": 148.7000000011176,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 63.69999999925494,
- "loadMedianMs": 112.09999999776483,
- "longestTaskMaxMs": 91,
+ "layoutSwitchMedianMs": 72.19999999925494,
+ "loadMedianMs": 148.80000000074506,
+ "longestTaskMaxMs": 143,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -271,24 +271,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 105,
- "scriptRawBytes": 3550967,
- "scriptRequestCount": 99,
- "totalRawBytes": 3874355
+ "otherRawBytes": 126172,
+ "requestCount": 107,
+ "scriptRawBytes": 3558671,
+ "scriptRequestCount": 101,
+ "totalRawBytes": 3882455
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 105,
- "scriptRawBytes": 3586477,
- "scriptRequestCount": 99,
- "totalRawBytes": 3913099
+ "otherRawBytes": 127434,
+ "requestCount": 107,
+ "scriptRawBytes": 3594258,
+ "scriptRequestCount": 101,
+ "totalRawBytes": 3921280
},
- "routeReadyMedianMs": 1061.699999999255,
+ "routeReadyMedianMs": 1308,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -297,7 +297,7 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 135423,
+ "largestAssetRawBytes": 135424,
"otherRawBytes": 0,
"requestCount": 4,
"scriptRawBytes": 277726,
@@ -308,18 +308,18 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 136778,
+ "largestAssetRawBytes": 136779,
"otherRawBytes": 0,
"requestCount": 4,
"scriptRawBytes": 280504,
"scriptRequestCount": 4,
"totalRawBytes": 280504
},
- "domContentLoadedMedianMs": 110,
+ "domContentLoadedMedianMs": 154.2000000011176,
"id": "editor-canvas",
- "layoutSwitchMedianMs": 173.39999999850988,
- "loadMedianMs": 110.09999999776483,
- "longestTaskMaxMs": 348,
+ "layoutSwitchMedianMs": 260.09999999962747,
+ "loadMedianMs": 154.2000000011176,
+ "longestTaskMaxMs": 551,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -329,24 +329,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 105,
- "scriptRawBytes": 3550967,
- "scriptRequestCount": 99,
- "totalRawBytes": 3874355
+ "otherRawBytes": 126172,
+ "requestCount": 107,
+ "scriptRawBytes": 3558671,
+ "scriptRequestCount": 101,
+ "totalRawBytes": 3882455
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 105,
- "scriptRawBytes": 3586477,
- "scriptRequestCount": 99,
- "totalRawBytes": 3913099
+ "otherRawBytes": 127434,
+ "requestCount": 107,
+ "scriptRawBytes": 3594258,
+ "scriptRequestCount": 101,
+ "totalRawBytes": 3921280
},
- "routeReadyMedianMs": 1217.5,
+ "routeReadyMedianMs": 1643,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -373,11 +373,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 109.60000000149012,
+ "domContentLoadedMedianMs": 147.7000000011176,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 60.30000000074506,
- "loadMedianMs": 109.60000000149012,
- "longestTaskMaxMs": 89,
+ "layoutSwitchMedianMs": 97.30000000074506,
+ "loadMedianMs": 147.80000000074506,
+ "longestTaskMaxMs": 141,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -387,24 +387,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 101,
- "scriptRawBytes": 3273241,
- "scriptRequestCount": 95,
- "totalRawBytes": 3596629
+ "otherRawBytes": 126172,
+ "requestCount": 103,
+ "scriptRawBytes": 3280945,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3604729
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 101,
- "scriptRawBytes": 3305974,
- "scriptRequestCount": 95,
- "totalRawBytes": 3632596
+ "otherRawBytes": 127434,
+ "requestCount": 103,
+ "scriptRawBytes": 3313755,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3640777
},
- "routeReadyMedianMs": 1049.699999999255,
+ "routeReadyMedianMs": 1298.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -431,11 +431,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 109.40000000223517,
+ "domContentLoadedMedianMs": 149.7999999988824,
"id": "editor-workflow",
- "layoutSwitchMedianMs": 99,
- "loadMedianMs": 109.5,
- "longestTaskMaxMs": 355,
+ "layoutSwitchMedianMs": 158.90000000037253,
+ "loadMedianMs": 149.89999999850988,
+ "longestTaskMaxMs": 544,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -445,24 +445,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 101,
- "scriptRawBytes": 3273241,
- "scriptRequestCount": 95,
- "totalRawBytes": 3596629
+ "otherRawBytes": 126172,
+ "requestCount": 103,
+ "scriptRawBytes": 3280945,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3604729
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 101,
- "scriptRawBytes": 3305974,
- "scriptRequestCount": 95,
- "totalRawBytes": 3632596
+ "otherRawBytes": 127434,
+ "requestCount": 103,
+ "scriptRawBytes": 3313755,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3640777
},
- "routeReadyMedianMs": 1136.9000000022352,
+ "routeReadyMedianMs": 1495.8999999985099,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -489,11 +489,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 109.30000000074506,
+ "domContentLoadedMedianMs": 153,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 26.599999997764826,
- "loadMedianMs": 109.30000000074506,
- "longestTaskMaxMs": 89,
+ "layoutSwitchMedianMs": 40.20000000111759,
+ "loadMedianMs": 153,
+ "longestTaskMaxMs": 144,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -503,24 +503,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 101,
- "scriptRawBytes": 3273241,
- "scriptRequestCount": 95,
- "totalRawBytes": 3596629
+ "otherRawBytes": 126172,
+ "requestCount": 103,
+ "scriptRawBytes": 3280945,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3604729
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 101,
- "scriptRawBytes": 3305974,
- "scriptRequestCount": 95,
- "totalRawBytes": 3632596
+ "otherRawBytes": 127434,
+ "requestCount": 103,
+ "scriptRawBytes": 3313755,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3640777
},
- "routeReadyMedianMs": 1288,
+ "routeReadyMedianMs": 1559.0999999996275,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -547,11 +547,11 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 112.80000000074506,
+ "domContentLoadedMedianMs": 150.2999999988824,
"id": "editor-gallery",
- "layoutSwitchMedianMs": 51.5,
- "loadMedianMs": 112.80000000074506,
- "longestTaskMaxMs": 98,
+ "layoutSwitchMedianMs": 129.10000000149012,
+ "loadMedianMs": 150.40000000037253,
+ "longestTaskMaxMs": 202,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -561,24 +561,24 @@
"fontRawBytes": 23664,
"imageRawBytes": 156376,
"largestAssetRawBytes": 746170,
- "otherRawBytes": 125776,
- "requestCount": 101,
- "scriptRawBytes": 3273241,
- "scriptRequestCount": 95,
- "totalRawBytes": 3596629
+ "otherRawBytes": 126172,
+ "requestCount": 103,
+ "scriptRawBytes": 3280945,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3604729
},
"resourceLimits": {
"cssRawBytes": 17748,
"fontRawBytes": 23901,
"imageRawBytes": 157940,
"largestAssetRawBytes": 753632,
- "otherRawBytes": 127034,
- "requestCount": 101,
- "scriptRawBytes": 3305974,
- "scriptRequestCount": 95,
- "totalRawBytes": 3632596
+ "otherRawBytes": 127434,
+ "requestCount": 103,
+ "scriptRawBytes": 3313755,
+ "scriptRequestCount": 97,
+ "totalRawBytes": 3640777
},
- "routeReadyMedianMs": 1386.1000000014901,
+ "routeReadyMedianMs": 1827.5,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -876,6 +876,7 @@
"source:src/workbench/projects/projectFileErrors.ts",
"source:src/workbench/projects/projectFileToasts.ts",
"source:src/workbench/projects/session.ts",
+ "source:src/workbench/projects/syncStore.ts",
"source:src/workbench/projects/useProjectFileActions.ts",
"source:src/workbench/settings/SettingsButton.tsx",
"source:src/workbench/settings/SettingsDialogHost.tsx",
@@ -1667,6 +1668,7 @@
"source:src/workbench/projects/ids.ts",
"source:src/workbench/projects/invk/format.ts",
"source:src/workbench/projects/library.ts",
+ "source:src/workbench/projects/openProjectBroker.ts",
"source:src/workbench/projects/openProjects.ts",
"source:src/workbench/projects/projectAssets.ts",
"source:src/workbench/projects/projectDocument.ts",
@@ -2587,6 +2589,7 @@
"source:src/workbench/projects/ids.ts",
"source:src/workbench/projects/invk/format.ts",
"source:src/workbench/projects/library.ts",
+ "source:src/workbench/projects/openProjectBroker.ts",
"source:src/workbench/projects/openProjects.ts",
"source:src/workbench/projects/projectAssets.ts",
"source:src/workbench/projects/projectDocument.ts",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
index 2154cbefe1..8e596daa92 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs
@@ -53,12 +53,58 @@ export const assertMockBackendProfileName = (value) => {
return value;
};
+/**
+ * What Fixture Project 002's own board holds, and what sits just outside it.
+ *
+ * The project-file journey is the only place the whole board path runs end to end, and it can only
+ * prove the interesting rules if the fixture actually contains them: a result the canvas draws with
+ * *and* the board owns (so a restore must copy it and rewrite the layer), a result the document
+ * never mentions (which is the entire reason `.invk` carries a board at all), assets under each
+ * visible category, media that must be excluded, and references that live outside the board and so
+ * must be deduplicated rather than copied.
+ *
+ * Every name here is an existing fixture image reassigned to the project's board — the image count
+ * is a pinned dimension of the representative profile, so this composition must not change it.
+ */
+export const PROJECT_FILE_BOARD = Object.freeze({
+ /** Generated, on the board, and drawn by the canvas: the overlap case. */
+ referencedImage: 'fixture-image-0002.png',
+ /** Generated, on the board, referenced by nothing. Travels only because v3 enumerates the board. */
+ unreferencedImage: 'fixture-image-0005.png',
+ /** An upload, filed under the `user` asset category. */
+ userAsset: 'fixture-image-0006.png',
+ /** A control-layer asset, so the restore has more than one category to preserve. */
+ maskAsset: 'fixture-image-0007.png',
+ /** Already starred in the base composition, so starring survives without perturbing any ordering. */
+ starredImage: 'fixture-image-0012.png',
+ /** The canvas's private category. On the board, and it must never travel as board membership. */
+ canvasOwnedImage: 'fixture-image-0008.png',
+ /** Hidden from every gallery view, and from the snapshot with it. */
+ intermediateImage: 'fixture-image-0009.png',
+ /** A visible video on the board, which is a separate namespace and a separate copy path. */
+ video: 'fixture-video-project.mp4',
+ /** Drawn by the canvas but owned by no project: reused on import, never copied. */
+ externalImages: Object.freeze(['fixture-image-0001.png', 'fixture-image-0003.png', 'fixture-image-0004.png']),
+});
+
+/** Category and visibility overrides that put the board composition above onto the project's board. */
+const PROJECT_BOARD_IMAGES = new Map([
+ [PROJECT_FILE_BOARD.referencedImage, { image_category: 'general' }],
+ [PROJECT_FILE_BOARD.unreferencedImage, { image_category: 'general' }],
+ [PROJECT_FILE_BOARD.starredImage, { image_category: 'general', starred: true }],
+ [PROJECT_FILE_BOARD.userAsset, { image_category: 'user' }],
+ [PROJECT_FILE_BOARD.maskAsset, { image_category: 'mask' }],
+ [PROJECT_FILE_BOARD.canvasOwnedImage, { image_category: 'other' }],
+ [PROJECT_FILE_BOARD.intermediateImage, { image_category: 'general', is_intermediate: true }],
+]);
+
const createImages = (count) =>
range(count, (index) => {
const id = ordinal(index, 4);
const imageName = `fixture-image-${id}.png`;
const boardIndex = index % 10;
const imageCategory = index % 10 === 0 ? 'control' : 'general';
+ const projectBoardMembership = PROJECT_BOARD_IMAGES.get(imageName);
return {
board_id: index % 8 === 0 ? null : `fixture-board-${ordinal(boardIndex, 2)}`,
@@ -71,6 +117,9 @@ const createImages = (count) =>
starred: index % 11 === 0,
thumbnail_url: `/api/v1/images/i/${imageName}/thumbnail`,
width: 512 + (index % 4) * 64,
+ ...(projectBoardMembership === undefined
+ ? {}
+ : { board_id: PROJECT_FILE_BOARD_ID, starred: false, ...projectBoardMembership }),
};
});
@@ -170,6 +219,27 @@ const createVideos = () => [
width: 64,
workflow: null,
},
+ {
+ // On Fixture Project 002's own board: videos are a separate namespace with their own copy and
+ // upload routes, so a project file that only ever carried images would prove half the path.
+ board_id: 'fixture-project-board-02',
+ created_at: timestampAt(5),
+ duration: 1,
+ fps: 10,
+ graph: null,
+ height: 64,
+ is_intermediate: false,
+ metadata: { prompt: 'project board fixture' },
+ owner_user_id: 'fixture-user',
+ starred: false,
+ thumbnail_url: '/api/v1/videos/i/fixture-video-project.mp4/thumbnail',
+ video_category: 'general',
+ video_name: 'fixture-video-project.mp4',
+ video_origin: 'internal',
+ video_url: '/api/v1/videos/i/fixture-video-project.mp4/full',
+ width: 64,
+ workflow: null,
+ },
{
board_id: null,
created_at: timestampAt(4),
@@ -216,6 +286,13 @@ const createVideos = () => [
*/
export const projectBoardId = (index) => `fixture-project-board-${ordinal(index, 2)}`;
+/**
+ * The board owned by Fixture Project 002 — the project the project-file journey exports, imports
+ * and duplicates. Declared here rather than inlined so the composition above and the journey's
+ * assertions cannot drift from the project they describe.
+ */
+export const PROJECT_FILE_BOARD_ID = projectBoardId(1);
+
const buildBoard = (boardId, boardName, images, videos, createdAt) => {
const boardImages = images.filter((image) => image.board_id === boardId);
const boardVideos = videos.filter((video) => video.board_id === boardId);
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
index 17776e852d..e6db9dc575 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -9,6 +9,8 @@ import {
MOCK_BACKEND_PROFILE_COUNTS,
MOCK_BACKEND_PROFILE_NAMES,
MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,
+ PROJECT_FILE_BOARD,
+ PROJECT_FILE_BOARD_ID,
validateMockBackendFixture,
} from './mock-backend-fixtures.mjs';
import { startMockBackend } from './mock-backend.mjs';
@@ -96,6 +98,43 @@ test('Fixture Project 002 carries the image and video references used by the pro
});
});
+/**
+ * The board path can only be proved end to end if the fixture contains the cases: an item that is
+ * both board membership and a canvas reference, one that is only membership, each visible category,
+ * the two kinds of media that must be excluded, and references that live outside the board.
+ */
+test('Fixture Project 002 owns a board carrying every case the project-file journey exercises', () => {
+ const fixture = createMockBackendFixture('representative');
+ const project = fixture.projects[1];
+ const byName = new Map(fixture.images.map((image) => [image.image_name, image]));
+ const onBoard = (name) => byName.get(name)?.board_id;
+
+ assert.equal(project.board_id, PROJECT_FILE_BOARD_ID);
+ assert.equal(onBoard(PROJECT_FILE_BOARD.referencedImage), PROJECT_FILE_BOARD_ID);
+ assert.equal(onBoard(PROJECT_FILE_BOARD.unreferencedImage), PROJECT_FILE_BOARD_ID);
+ assert.equal(byName.get(PROJECT_FILE_BOARD.userAsset)?.image_category, 'user');
+ assert.equal(byName.get(PROJECT_FILE_BOARD.maskAsset)?.image_category, 'mask');
+ assert.equal(byName.get(PROJECT_FILE_BOARD.starredImage)?.starred, true);
+ assert.equal(byName.get(PROJECT_FILE_BOARD.canvasOwnedImage)?.image_category, 'other');
+ assert.equal(byName.get(PROJECT_FILE_BOARD.intermediateImage)?.is_intermediate, true);
+ assert.equal(
+ fixture.videos.find((video) => video.video_name === PROJECT_FILE_BOARD.video)?.board_id,
+ PROJECT_FILE_BOARD_ID
+ );
+
+ // The canvas draws with these, and no project owns them: on import they deduplicate against the
+ // destination, and on duplication they are not copied at all.
+ const layerNames = project.data.canvas.document.layers.map((layer) => layer.source.image.imageName);
+
+ for (const name of PROJECT_FILE_BOARD.externalImages) {
+ assert.ok(layerNames.includes(name), `${name} must stay a canvas reference`);
+ assert.notEqual(onBoard(name), PROJECT_FILE_BOARD_ID);
+ }
+
+ assert.ok(layerNames.includes(PROJECT_FILE_BOARD.referencedImage));
+ assert.ok(!layerNames.includes(PROJECT_FILE_BOARD.unreferencedImage));
+});
+
test('the HTTP reset contract selects profiles explicitly and restores the startup profile by default', async () => {
const backend = await startMockBackend(0, { profile: 'empty' });
@@ -134,7 +173,9 @@ test('the HTTP reset contract selects profiles explicitly and restores the start
assert.deepEqual(generationDevices, [{ device: 'cpu', name: 'CPU' }]);
assert.equal(images.items.length, 17);
- assert.equal(images.total, 1_000);
+ // One of the thousand is an intermediate on Fixture Project 002's board, which every gallery
+ // listing hides — it exists so the project-file journey can prove it never travels.
+ assert.equal(images.total, 999);
assert.equal(itemIds.item_ids.length, 500);
assert.equal(models.models.length, 100);
assert.equal(nodeCatalog.node_packs.flatMap((pack) => pack.node_types).length, 100);
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 24cd2bc638..43911fea92 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -79,6 +79,32 @@ const createState = (profile) => {
};
};
+/**
+ * Put media back under names a fresh state does not have, without its projects or boards.
+ *
+ * A restore has to be provably free of name adoption: board media must take a new identity even
+ * when the destination already holds an image with the archived name — on the same server it always
+ * does, and reusing it would move a stranger's picture onto the restored board. Reset alone cannot
+ * express that, because it clears everything, so the journey names the collisions it wants kept.
+ * The media lands unboarded, exactly as media whose board was deleted would.
+ */
+const seedCollisionMedia = (state, names) => {
+ const source = createMockBackendFixture('representative');
+ const requested = new Set(names);
+
+ for (const image of source.images) {
+ if (requested.has(image.image_name)) {
+ state.images.set(image.image_name, { ...clone(image), board_id: null, is_intermediate: false });
+ }
+ }
+
+ for (const video of source.videos) {
+ if (requested.has(video.video_name)) {
+ state.videos.set(video.video_name, { ...clone(video), board_id: null, is_intermediate: false });
+ }
+ }
+};
+
const timestamp = (state) => {
const value = new Date(FIXED_EPOCH_MS + state.mutationClock * 1_000).toISOString();
@@ -593,6 +619,15 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(400, { detail: error instanceof Error ? error.message : String(error) });
}
+ const collisions = [...url.searchParams.getAll('collide'), ...(body.collide ?? [])]
+ .flatMap((value) => String(value).split(','))
+ .map((value) => value.trim())
+ .filter(Boolean);
+
+ if (collisions.length > 0) {
+ seedCollisionMedia(state, collisions);
+ }
+
return json(200, { ok: true, ...getProfileInfo(state) });
}
diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
index 49d2225a75..fd7db77038 100644
--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs
@@ -1,6 +1,7 @@
+import { unzipSync, zipSync } from 'fflate';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
-import { mkdtemp, rm } from 'node:fs/promises';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { performance } from 'node:perf_hooks';
@@ -8,7 +9,12 @@ import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
-import { MOCK_BACKEND_PROFILE_COUNTS, MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME } from './mock-backend-fixtures.mjs';
+import {
+ MOCK_BACKEND_PROFILE_COUNTS,
+ MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,
+ PROJECT_FILE_BOARD,
+ PROJECT_FILE_BOARD_ID,
+} from './mock-backend-fixtures.mjs';
import { startMockBackend } from './mock-backend.mjs';
const root = resolve(import.meta.dirname, '..');
@@ -19,7 +25,7 @@ const backendOrigin = `http://127.0.0.1:${String(backendPort)}`;
const sourceProjectId = 'fixture-project-002';
const sourceProjectName = 'Fixture Project 002';
const sourceProjectPath = `/#/app?project=${sourceProjectId}`;
-const journeyTimeoutMs = 60_000;
+const journeyTimeoutMs = 120_000;
const cleanupTimeoutMs = 2_000;
const delay = (durationMs) =>
@@ -87,7 +93,7 @@ const observeBrowserErrors = (page, phase, errors) => {
// Video existence has no bulk endpoint. Import deliberately probes the
// archived name and treats this exact 404 as the signal to restore it.
if (
- phase === 'import' &&
+ phase.endsWith('import') &&
location.url &&
new URL(location.url).pathname === `/api/v1/videos/i/${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}` &&
message.text().includes('the server responded with a status of 404')
@@ -143,20 +149,126 @@ const waitForProjectCover = async (projectId, restoredImageNames) => {
assert.fail(`The project cover index never mapped ${projectId} to a restored image.`);
};
+/**
+ * What Fixture Project 002's board holds, as the snapshot describes it: kind, category and
+ * starring, with the names left out. Names are exactly what may not survive a transfer — every
+ * board item gets a new identity — so the shape is the part that has to round-trip.
+ */
+const boardShape = (items) => items.map((item) => `${item.kind}:${item.category}:${String(item.starred)}`).sort();
+
+const EXPECTED_BOARD_SHAPE = [
+ 'image:general:false',
+ 'image:general:false',
+ 'image:general:true',
+ 'image:mask:false',
+ 'image:user:false',
+ 'video:general:false',
+].sort();
+
+/** The archived names of everything on the source board, for proving none of them is reused. */
+const ARCHIVED_BOARD_NAMES = [
+ PROJECT_FILE_BOARD.referencedImage,
+ PROJECT_FILE_BOARD.unreferencedImage,
+ PROJECT_FILE_BOARD.starredImage,
+ PROJECT_FILE_BOARD.userAsset,
+ PROJECT_FILE_BOARD.maskAsset,
+ PROJECT_FILE_BOARD.video,
+];
+
+const readArchiveEntries = async (archivePath) => unzipSync(new Uint8Array(await readFile(archivePath)));
+
+const readEntryJson = (entries, name) => {
+ assert.ok(entries[name], `The archive has no ${name}.`);
+
+ return JSON.parse(new TextDecoder().decode(entries[name]));
+};
+
+/** Rewrite an archive without the named entries, to exercise what a damaged one reports. */
+const writeArchiveWithout = async (entries, omitted, targetPath) => {
+ for (const name of omitted) {
+ assert.ok(entries[name], `Cannot omit ${name}: the archive does not carry it.`);
+ }
+
+ const kept = Object.fromEntries(Object.entries(entries).filter(([name]) => !omitted.includes(name)));
+
+ await writeFile(targetPath, Buffer.from(zipSync(kept)));
+
+ return targetPath;
+};
+
+const getBoardSnapshot = (projectId) => fetchJson(`/api/v1/projects/${encodeURIComponent(projectId)}/board-snapshot`);
+
+const getLayerImageNames = (project) =>
+ project.data.canvas.document.layers.map((layer) => layer.source.image.imageName);
+
+const getDocumentVideoName = (project) => project.data.projectGraph.nodes[0]?.data.inputs.video?.value?.video_name;
+
+/** Import the archive at `archivePath` through the Launchpad, exactly as a person would. */
+const importArchive = async ({ archivePath, browser, contexts, errors, phase }) => {
+ const context = await browser.newContext();
+
+ contexts.add(context);
+ const page = await context.newPage();
+
+ observeBrowserErrors(page, phase, errors);
+ await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });
+ await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
+
+ const chooserPromise = page.waitForEvent('filechooser');
+
+ await page.getByRole('button', { exact: true, name: 'Import…' }).click();
+ await (await chooserPromise).setFiles(archivePath);
+ await page.waitForURL(/#\/app\?project=/);
+ await page.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();
+
+ return { context, page };
+};
+
+/**
+ * The complete round trip: export a project *and its board*, restore it somewhere that has none of
+ * its media, then duplicate the result.
+ *
+ * The rules under test are the ones that distinguish a project file from a folder of pictures.
+ * Board media is copied, never adopted — the destination is deliberately seeded with images under
+ * the archived names, and a restore that reused one would be pointing at somebody else's picture.
+ * Document references outside the board are the opposite: an identity the destination already has
+ * satisfies them, so it is reused rather than duplicated. And the things a board holds but no
+ * gallery shows — intermediates and the canvas's private `other` category — never travel at all.
+ */
const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory }) => {
+ const sourceBoard = await getBoardSnapshot(sourceProjectId);
+
+ assert.deepEqual(boardShape(sourceBoard.items), EXPECTED_BOARD_SHAPE);
+
const exportContext = await browser.newContext({ acceptDownloads: true });
contexts.add(exportContext);
const exportPage = await exportContext.newPage();
+
observeBrowserErrors(exportPage, 'export', errors);
await exportPage.goto(`${origin}${sourceProjectPath}`, { waitUntil: 'domcontentloaded' });
await exportPage.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();
+ // The board the server says this project owns is the one the gallery points at, without the
+ // document having to name it.
+ const selectedBoardRow = exportPage.locator('button[aria-current="true"]').filter({ hasText: sourceProjectName });
+
+ await selectedBoardRow.first().waitFor();
+
+ // A project's board offers the whole project as a file, alongside the media-only download that
+ // predates it. Both, because they are different things: one is the project, one is its pixels.
+ await exportPage.getByRole('button', { exact: true, name: `Board actions for ${sourceProjectName}` }).click();
+ await exportPage.getByRole('menuitem', { exact: true, name: 'Export project (.invk)' }).waitFor();
+ await exportPage.getByRole('menuitem', { name: /^Download Board/ }).waitFor();
+ await exportPage.keyboard.press('Escape');
+
const downloadPromise = exportPage.waitForEvent('download');
+
await exportPage
.getByRole('button', { exact: true, name: `Switch project. Current project: ${sourceProjectName}` })
.click();
await exportPage.getByRole('menuitem', { exact: true, name: 'Export' }).click();
+
const download = await downloadPromise;
const archivePath = join(tempDirectory, 'fixture-project-002.invk');
@@ -166,43 +278,52 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory
contexts.delete(exportContext);
assertNoBrowserErrors(errors);
- const reset = await fetchJson('/__reset?profile=empty', { method: 'POST' });
+ const entries = await readArchiveEntries(archivePath);
+ const manifest = readEntryJson(entries, 'manifest.json');
+ const archivedBoard = readEntryJson(entries, 'board.json');
+ const bundledImages = Object.keys(entries).filter((name) => name.startsWith('images/'));
+ const bundledVideos = Object.keys(entries).filter((name) => name.startsWith('videos/'));
+
+ assert.equal(manifest.version, 3);
+ assert.equal(manifest.contents, 'workbench-project');
+ assert.equal(archivedBoard.version, 1);
+ assert.deepEqual(boardShape(archivedBoard.items), EXPECTED_BOARD_SHAPE);
+ assert.deepEqual(archivedBoard.items.map((item) => item.name).sort(), [...ARCHIVED_BOARD_NAMES].sort());
+ // Board membership plus the canvas's own references, each carried once: five board items, three
+ // external images the document draws with, and one external video a workflow node names.
+ assert.deepEqual(
+ bundledImages.sort(),
+ [...ARCHIVED_BOARD_NAMES.filter((name) => name.endsWith('.png')), ...PROJECT_FILE_BOARD.externalImages]
+ .map((name) => `images/${name}`)
+ .sort()
+ );
+ assert.deepEqual(
+ bundledVideos.sort(),
+ [`videos/${PROJECT_FILE_BOARD.video}`, `videos/${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}`].sort()
+ );
+ // Hidden from every gallery view and from the archive with it.
+ assert.equal(entries[`images/${PROJECT_FILE_BOARD.intermediateImage}`], undefined);
+ assert.equal(entries[`images/${PROJECT_FILE_BOARD.canvasOwnedImage}`], undefined);
+
+ // Two collisions survive the reset: one name the restore must *not* adopt because the board owns
+ // it, and one it *must* reuse because the document only points at it.
+ const collide = [PROJECT_FILE_BOARD.referencedImage, PROJECT_FILE_BOARD.video, PROJECT_FILE_BOARD.externalImages[0]];
+ const reset = await fetchJson(`/__reset?profile=empty&collide=${collide.map(encodeURIComponent).join(',')}`, {
+ method: 'POST',
+ });
assert.equal(reset.profile, 'empty');
- assert.deepEqual(reset.counts, MOCK_BACKEND_PROFILE_COUNTS.empty);
+ // Nothing survives the reset except the deliberate collisions, and the profile says so.
+ assert.deepEqual(reset.counts, { ...MOCK_BACKEND_PROFILE_COUNTS.empty, images: 2 });
assert.equal(backend.profile(), 'empty');
- const importContext = await browser.newContext();
-
- contexts.add(importContext);
- const importPage = await importContext.newPage();
- const uploadResponses = [];
-
- importPage.on('response', (response) => {
- const path = new URL(response.url()).pathname;
- const kind = path === '/api/v1/images/upload' ? 'image' : path === '/api/v1/videos/upload' ? 'video' : null;
-
- if (kind !== null && response.request().method() === 'POST') {
- uploadResponses.push(
- response.json().then((dto) => ({
- kind,
- name: kind === 'image' ? dto.image_name : dto.video_name,
- status: response.status(),
- }))
- );
- }
+ const { context: importContext, page: importPage } = await importArchive({
+ archivePath,
+ browser,
+ contexts,
+ errors,
+ phase: 'import',
});
- observeBrowserErrors(importPage, 'import', errors);
- await importPage.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });
- await importPage.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
-
- const chooserPromise = importPage.waitForEvent('filechooser');
- await importPage.getByRole('button', { exact: true, name: 'Import…' }).click();
- const chooser = await chooserPromise;
-
- await chooser.setFiles(archivePath);
- await importPage.waitForURL(/#\/app\?project=/);
- await importPage.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();
const projects = await fetchJson('/api/v1/projects/');
@@ -211,68 +332,177 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory
assert.ok(summary);
assert.notEqual(summary.project_id, sourceProjectId);
+ // The project's board is the server's to mint; the archived one meant nothing here.
+ assert.notEqual(summary.board_id, PROJECT_FILE_BOARD_ID);
assert.equal(importPage.url().includes(`project=${encodeURIComponent(summary.project_id)}`), true);
const imported = await fetchJson(`/api/v1/projects/${encodeURIComponent(summary.project_id)}`);
- const images = await fetchJson('/api/v1/images/?categories=other&limit=100&offset=0');
- const videos = await fetchJson('/api/v1/videos/?categories=other&limit=100&offset=0');
- const uploads = await Promise.all(uploadResponses);
+ const importedBoard = await getBoardSnapshot(summary.project_id);
+ const importedBoardNames = importedBoard.items.map((item) => item.name);
- assert.equal(imported.project_id, summary.project_id);
assert.equal(imported.data.id, summary.project_id);
- assert.equal(images.total, 4);
- assert.equal(images.items.length, 4);
- assert.equal(videos.total, 1);
- assert.equal(videos.items.length, 1);
-
- const restoredImageNames = new Set(images.items.map((image) => image.image_name));
- const restoredVideoNames = new Set(videos.items.map((video) => video.video_name));
- const uploadedImageNames = uploads.filter(({ kind }) => kind === 'image').map(({ name }) => name);
- const uploadedVideoNames = uploads.filter(({ kind }) => kind === 'video').map(({ name }) => name);
- const layerImageNames = imported.data.canvas.document.layers.map((layer) => layer.source.image.imageName);
- const videoName = imported.data.projectGraph.nodes[0]?.data.inputs.video?.value?.video_name;
+ assert.deepEqual(boardShape(importedBoard.items), EXPECTED_BOARD_SHAPE);
- assert.equal(
- uploads.every(({ status }) => status === 201),
- true
- );
- assert.equal(uploadedImageNames.length, 4);
- assert.equal(uploadedVideoNames.length, 1);
- assert.deepEqual([...uploadedImageNames].sort(), [...restoredImageNames].sort());
- assert.deepEqual(uploadedVideoNames, [...restoredVideoNames]);
- assert.equal(layerImageNames.length, 4);
- assert.equal(new Set(layerImageNames).size, 4);
- assert.deepEqual([...layerImageNames].sort(), [...restoredImageNames].sort());
- assert.deepEqual([...restoredVideoNames], [videoName]);
- assert.notEqual(videoName, MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME);
-
- for (const image of images.items) {
- assert.equal(image.image_category, 'other');
- assert.equal(image.is_intermediate, false);
- await assertAssetRoute('/api/v1/images', image.image_name, ['full', 'thumbnail']);
+ for (const name of importedBoardNames) {
+ assert.equal(ARCHIVED_BOARD_NAMES.includes(name), false, `${name} was adopted from the archive instead of copied.`);
}
- for (const video of videos.items) {
- assert.equal(video.video_category, 'other');
- assert.equal(video.is_intermediate, false);
- await assertAssetRoute('/api/v1/videos', video.video_name, ['full', 'thumbnail']);
+ const importedLayers = getLayerImageNames(imported);
+ const [firstExternal, ...otherExternals] = PROJECT_FILE_BOARD.externalImages;
+
+ // The layer whose image the board owned follows the copy; the ones it did not keep pointing
+ // outside the board — the collided name is reused verbatim, the rest were uploaded.
+ assert.equal(importedLayers.filter((name) => importedBoardNames.includes(name)).length, 1);
+ assert.equal(importedLayers.includes(PROJECT_FILE_BOARD.referencedImage), false);
+ assert.equal(importedLayers.includes(firstExternal), true, 'an existing identity must satisfy a reference');
+
+ for (const name of otherExternals) {
+ assert.equal(importedLayers.includes(name), false, `${name} should have been uploaded under a new name`);
}
+ const importedVideoName = getDocumentVideoName(imported);
+ const importedVideos = await fetchJson('/api/v1/videos/?limit=100&offset=0');
+ const importedVideoNames = new Set(importedVideos.items.map((video) => video.video_name));
+
+ assert.notEqual(importedVideoName, MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME);
+ assert.equal(importedVideoNames.has(importedVideoName), true);
+
+ // The media the destination already held under an archived name is untouched: still there, still
+ // on no board. A restore that had adopted it would have moved it onto the project's board.
+ const collidedVideo = importedVideos.items.find((video) => video.video_name === PROJECT_FILE_BOARD.video);
+ const collidedImage = await fetchJson(`/api/v1/images/i/${encodeURIComponent(PROJECT_FILE_BOARD.referencedImage)}`);
+
+ assert.ok(collidedVideo, 'the video collision fixture must survive the reset');
+ assert.equal(collidedVideo.board_id, null);
+ assert.equal(collidedImage.board_id, null);
+
+ // Nothing the source hid came across.
+ for (const hidden of [PROJECT_FILE_BOARD.intermediateImage, PROJECT_FILE_BOARD.canvasOwnedImage]) {
+ const response = await fetch(`${backendOrigin}/api/v1/images/i/${encodeURIComponent(hidden)}`);
+
+ assert.equal(response.status, 404, `${hidden} must not exist on the destination.`);
+ }
+
+ for (const item of importedBoard.items) {
+ const base = item.kind === 'image' ? '/api/v1/images' : '/api/v1/videos';
+
+ await assertAssetRoute(base, item.name, ['full', 'thumbnail']);
+ }
+
+ const restoredImageNames = new Set(
+ (await fetchJson('/api/v1/images/?limit=200&offset=0')).items.map((image) => image.image_name)
+ );
const coverImageName = await waitForProjectCover(summary.project_id, restoredImageNames);
- assert.ok(layerImageNames.includes(coverImageName));
await importContext.close();
contexts.delete(importContext);
assertNoBrowserErrors(errors);
+ await runDuplication({ browser, contexts, errors, imported, importedBoardNames });
+ await runMissingBinaryImport({ browser, contexts, entries, errors, tempDirectory });
+
return {
+ boardItemCount: importedBoard.items.length,
coverImageName,
- imageNames: [...restoredImageNames].sort(),
+ imageNames: [...importedBoardNames].sort(),
projectId: summary.project_id,
- videoName,
+ videoName: importedVideoName,
};
};
+/**
+ * Duplicating the imported project. The copy owns its board media outright — no name is shared with
+ * the project it came from — while the references that live outside both boards are simply reused,
+ * because both projects are on this one server.
+ */
+const runDuplication = async ({ browser, contexts, errors, imported, importedBoardNames }) => {
+ const context = await browser.newContext();
+
+ contexts.add(context);
+ const page = await context.newPage();
+
+ observeBrowserErrors(page, 'duplicate', errors);
+ // Through Home rather than straight at the deep link: a cold context has to finish authenticating
+ // before the library will list anything, and landing on the settled shell is how a person arrives.
+ await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });
+ await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();
+ await page.goto(`${origin}/#/projects`, { waitUntil: 'domcontentloaded' });
+
+ const card = page.getByRole('link', { exact: true, name: `Open ${sourceProjectName}` }).first();
+
+ await card.waitFor();
+ await card.hover();
+ await page.getByRole('button', { exact: true, name: 'Actions' }).first().click();
+ await page.getByRole('menuitem', { exact: true, name: 'Duplicate' }).click();
+ await page.getByText('Project duplicated').waitFor();
+
+ const projects = await fetchJson('/api/v1/projects/');
+
+ assert.equal(projects.length, 2);
+
+ const copy = projects.find((project) => project.project_id !== imported.project_id);
+
+ assert.ok(copy, 'The duplication did not create a second project.');
+ assert.equal(copy.name, `${sourceProjectName} copy`);
+ assert.notEqual(copy.board_id, imported.board_id);
+
+ const copiedBoard = await getBoardSnapshot(copy.project_id);
+ const copiedBoardNames = copiedBoard.items.map((item) => item.name);
+
+ assert.deepEqual(boardShape(copiedBoard.items), EXPECTED_BOARD_SHAPE);
+
+ for (const name of copiedBoardNames) {
+ assert.equal(importedBoardNames.includes(name), false, `${name} is shared with the project it was copied from.`);
+ }
+
+ const copiedRecord = await fetchJson(`/api/v1/projects/${encodeURIComponent(copy.project_id)}`);
+ const copiedLayers = getLayerImageNames(copiedRecord);
+ const importedLayers = getLayerImageNames(imported);
+
+ assert.equal(copiedLayers.filter((name) => copiedBoardNames.includes(name)).length, 1);
+ // Everything outside the board is a pointer, and the pointer is still good.
+ assert.deepEqual(
+ copiedLayers.filter((name) => !copiedBoardNames.includes(name)).sort(),
+ importedLayers.filter((name) => !importedBoardNames.includes(name)).sort()
+ );
+ assert.equal(getDocumentVideoName(copiedRecord), getDocumentVideoName(imported));
+
+ await context.close();
+ contexts.delete(context);
+ assertNoBrowserErrors(errors);
+};
+
+/**
+ * An archive missing some of its bytes. The two losses are counted apart because they cost
+ * different things: a board item is a result still findable elsewhere, a document reference is a
+ * hole in the canvas.
+ */
+const runMissingBinaryImport = async ({ browser, contexts, entries, errors, tempDirectory }) => {
+ const damagedPath = await writeArchiveWithout(
+ entries,
+ [
+ `images/${PROJECT_FILE_BOARD.unreferencedImage}`,
+ `images/${PROJECT_FILE_BOARD.userAsset}`,
+ `images/${PROJECT_FILE_BOARD.externalImages[1]}`,
+ ],
+ join(tempDirectory, 'fixture-project-002-damaged.invk')
+ );
+ const { context, page } = await importArchive({
+ archivePath: damagedPath,
+ browser,
+ contexts,
+ errors,
+ phase: 'damaged-import',
+ });
+
+ await page.getByText('2 board items could not be included.').waitFor();
+ await page.getByText('1 project reference could not be included.').waitFor();
+
+ await context.close();
+ contexts.delete(context);
+ assertNoBrowserErrors(errors);
+};
+
const toError = (error) => (error instanceof Error ? error : new Error(String(error)));
const withTimeout = async (run, durationMs, label) => {
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index 63cb5da1b4..738a6bef6f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -152,6 +152,17 @@ describe('gallery state view', () => {
expect(getGallerySelectedBoardId(values, boards)).toBe('none');
});
+ /**
+ * Never having chosen a destination is not a choice of Uncategorized. A project saved before it
+ * owned a board should still work on its own board, where everything else it has made lives.
+ */
+ it('uses the project board when nothing was ever selected', () => {
+ const projectBoards = [...boards, { ...boards[1]!, id: 'project-board', name: 'My Project', projectId: 'p1' }];
+
+ expect(getGallerySelectedBoardId({ projectBoardId: 'project-board' }, projectBoards)).toBe('project-board');
+ expect(getGallerySelectedBoardId({}, projectBoards)).toBe('none');
+ });
+
it('does not render local fallback images while backend images are loading', () => {
const values = { recentImages: [createImage('local-fallback.png')], selectedBoardId: 'none' };
const gallery = getGalleryStateView(values, boards, null, true);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
index 3e99f56221..17c2d68447 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -235,12 +235,20 @@ export const getGallerySearchTerm = (values: Record<string, unknown>): string =>
* install, or one whose pre-migration board was rejected as ambiguous, names a board id that means
* nothing here, and dropping it to Uncategorized would quietly scatter that project's output.
*
+ * No saved selection at all is the same case, not a choice of Uncategorized. A project saved before
+ * it owned a board — or by a build that never wrote a destination — should still work on its own
+ * board, which is where everything else it has made already lives.
+ *
* An empty board list means "still loading", not "no such board", so nothing is resolved yet.
*/
export const getGallerySelectedBoardId = (values: Record<string, unknown>, backendBoards: GalleryBoard[]): string => {
- const selectedBoardId = typeof values.selectedBoardId === 'string' ? values.selectedBoardId : 'none';
+ const selectedBoardId = typeof values.selectedBoardId === 'string' ? values.selectedBoardId : null;
+
+ if (backendBoards.length === 0) {
+ return selectedBoardId ?? 'none';
+ }
- if (backendBoards.length === 0 || backendBoards.some((board) => board.id === selectedBoardId)) {
+ if (selectedBoardId !== null && backendBoards.some((board) => board.id === selectedBoardId)) {
return selectedBoardId;
}
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
index b05ec24b87..a09f9ec7c0 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts
@@ -681,6 +681,25 @@ describe('authoritative project boards', () => {
expect(galleryBoardIds(hydrated!).selectedBoardId).toBe('deliberate-destination');
});
+ /**
+ * Patching the document is not enough on its own. A project saved by a build that never opened
+ * its Gallery widget has no gallery values for the patch to land in, and the instance the reducer
+ * creates during normalization arrives afterwards, empty — so the board has to be written again
+ * once the project is hydrated.
+ */
+ it('tells a project its board even when its document had no gallery state', async () => {
+ const draft = createDraftProject([]);
+ const document = persistence.serializeProjectDocument(draft) as Record<string, unknown>;
+
+ delete document.widgetInstances;
+ delete document.widgetStates;
+ api.__seed(document);
+
+ const hydrated = await service.hydrateProjectFromServer(draft.id);
+
+ expect(galleryBoardIds(hydrated!).projectBoardId).toBe(`board-for-${draft.id}`);
+ });
+
it('forks rather than resurrects a project deleted on another device', async () => {
const project = seedServerProject('Deleted elsewhere');
const opened = await service.hydrateProjectFromServer(project.id);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
index ebc379f66b..d9c28cc3e7 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts
@@ -8,7 +8,12 @@ import {
stripTransientWorkbenchState,
type WorkbenchPersistenceService,
} from '@workbench/persistence';
-import { createDraftProject, createInitialWorkbenchState, normalizeWorkbenchProject } from '@workbench/workbenchState';
+import {
+ createDraftProject,
+ createInitialWorkbenchState,
+ normalizeWorkbenchProject,
+ withAuthoritativeProjectBoard,
+} from '@workbench/workbenchState';
import {
createProject as apiCreateProject,
@@ -180,8 +185,15 @@ const getSerializedProjectDocument = (
* autosave writes the correction back. The saved destination is left alone: it is a deliberate
* choice, and `getGallerySelectedBoardId` resolves it against the boards that actually exist.
*/
-const deserializeProjectRecord = (record: ProjectRecordDTO): Project | null =>
- deserializeProjectDocument(applyAuthoritativeProjectBoard(record.data, record.board_id, { selectBoard: false }));
+const deserializeProjectRecord = (record: ProjectRecordDTO): Project | null => {
+ const project = deserializeProjectDocument(
+ applyAuthoritativeProjectBoard(record.data, record.board_id, { selectBoard: false })
+ );
+
+ // Again after rehydration, because the document may have had no gallery values for the first
+ // patch to land in — see `withAuthoritativeProjectBoard`.
+ return project === null ? null : withAuthoritativeProjectBoard(project, record.board_id);
+};
/**
* Rehydrate a document into a live project. This is the half of the codec that
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index cd2381e067..c618010de0 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -1317,6 +1317,24 @@ export const normalizeWorkbenchProject = (project: Project): Project => {
};
};
+/**
+ * Write the server's board id into a *hydrated* project's gallery state.
+ *
+ * Patching the document before rehydration is not enough on its own. A project saved by a build
+ * that never opened its Gallery widget — or one whose document predates widget instances entirely —
+ * has no gallery values for the patch to land in, and the instance the reducer creates during
+ * normalization arrives afterwards, empty. Such a project would then show the placeholder board row
+ * forever and route nothing at its own board, which is the one thing the server is authoritative
+ * about.
+ *
+ * Applied after normalization, so the instance exists. A project whose layout has no gallery widget
+ * at all is returned untouched: there is nothing to tell.
+ */
+export const withAuthoritativeProjectBoard = (project: Project, boardId: string): Project =>
+ updateProjectWidgetValues(project, 'gallery', (values) =>
+ values.projectBoardId === boardId ? values : { ...values, projectBoardId: boardId }
+ );
+
const clampPanelSize = (region: WidgetRegion, sizePx: number): number => {
if (region === 'bottom') {
return Math.min(MAX_STATUS_PANEL_SIZE_PX, Math.max(MIN_STATUS_PANEL_SIZE_PX, sizePx));
diff --git a/tests/app/services/image_files/test_image_files_disk.py b/tests/app/services/image_files/test_image_files_disk.py
index 75e5938091..934d4b7dd5 100644
--- a/tests/app/services/image_files/test_image_files_disk.py
+++ b/tests/app/services/image_files/test_image_files_disk.py
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
import pytest
from PIL import Image
+from invokeai.app.api.extract_metadata_from_image import extract_metadata_from_image
from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage, _should_use_png_rle
from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundException
from invokeai.app.util.thumbnails import get_thumbnail_name
@@ -311,3 +312,66 @@ class TestSaveDeleteRoundTrip:
restarted.start(invoker)
assert not list(disk_storage.image_root.glob(".delete_*"))
+
+
+class TestProvenanceRoundTrip:
+ """The property copying and exporting an image both rely on, and nothing else guarded.
+
+ `save()` writes generation metadata, the workflow and the graph into the PNG's text chunks, and
+ `extract_metadata_from_image()` reads them back out of a re-opened image. Nothing else carries
+ that provenance: `POST /images/copy` hands the reopened PIL image straight to the extractor, and
+ an `.invk` archive carries the file's bytes and nothing beside them. If these two ever stopped
+ agreeing, every copy and every restored project would silently lose its metadata while looking
+ entirely successful.
+ """
+
+ def test_saved_provenance_survives_being_read_back(self, disk_storage: DiskImageFileStorage):
+ metadata = '{"positive_prompt": "a cat"}'
+ workflow = '{"name": "Fixture workflow", "nodes": []}'
+ graph = '{"nodes": {}, "edges": []}'
+
+ disk_storage.save(
+ image=Image.new("RGB", (16, 16)),
+ image_name="provenance.png",
+ metadata=metadata,
+ workflow=workflow,
+ graph=graph,
+ )
+ disk_storage.evict_cache_paths([disk_storage.get_path("provenance.png")])
+
+ with Image.open(disk_storage.get_path("provenance.png")) as reopened:
+ reopened.load()
+ extracted = extract_metadata_from_image(
+ pil_image=reopened,
+ invokeai_metadata_override=None,
+ invokeai_workflow_override=None,
+ invokeai_graph_override=None,
+ logger=MagicMock(),
+ )
+
+ # The chunks themselves are what travels: an `.invk` carries the file's bytes and
+ # nothing beside them, and a copy hands the reopened image straight to the extractor.
+ assert reopened.info["invokeai_metadata"] == metadata
+ assert reopened.info["invokeai_workflow"] == workflow
+ assert reopened.info["invokeai_graph"] == graph
+
+ assert extracted.invokeai_metadata == metadata
+ assert extracted.invokeai_graph == graph
+
+ def test_an_image_saved_without_provenance_extracts_none(self, disk_storage: DiskImageFileStorage):
+ disk_storage.save(image=Image.new("RGB", (16, 16)), image_name="bare.png")
+ disk_storage.evict_cache_paths([disk_storage.get_path("bare.png")])
+
+ with Image.open(disk_storage.get_path("bare.png")) as reopened:
+ reopened.load()
+ extracted = extract_metadata_from_image(
+ pil_image=reopened,
+ invokeai_metadata_override=None,
+ invokeai_workflow_override=None,
+ invokeai_graph_override=None,
+ logger=MagicMock(),
+ )
+
+ assert extracted.invokeai_metadata is None
+ assert extracted.invokeai_workflow is None
+ assert extracted.invokeai_graph is None