Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(projects): carry every board of a project through export, import and duplicate
Josh Corbettf43a9d1d41cc
diff --git a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdxindex 3f187ef184..36ac974798 100644--- a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx+++ b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx@@ -121,7 +121,7 @@ Right-click a project, or use its **Actions** button, for **Open**, **Pin**, **R**Rename…** changes the project name; its Inbox and the heading of its boards in the gallery follow.-**Duplicate** creates a complete copy called "*name* copy", including copies of every image and video in the project's Inbox. Its other boards are not copied. Use it to try a different direction without disturbing the original.+**Duplicate** creates a complete copy called "*name* copy", including copies of every image and video on each of the project's boards. Use it to try a different direction without disturbing the original.**Delete…** removes the project permanently. There is no trash to recover it from.@@ -136,7 +136,7 @@ Generation also leaves temporary files behind in each project. **Delete intermed## Exporting and importing-**Export** packages a project into a single `.invk` file named after it. The file contains the project itself, every image and video in its Inbox, and any other media the project uses, such as reference images, so it opens complete on another installation. The project's other boards are not included. Temporary intermediates are left out.+**Export** packages a project into a single `.invk` file named after it. The file contains the project itself, every image and video on each of its boards, and any other media the project uses, such as reference images, so it opens complete on another installation, boards and all. Temporary intermediates are left out. If a board cannot be placed in the imported project, Invoke says so and leaves that board, with everything on it, in the Library, where you can move it in from its menu.Before exporting, Invoke asks whether to **Include font files** used by text layers. It is off by default. Leave it off unless you have permission to redistribute the fonts; recipients can install or replace missing fonts themselves.diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdxindex e37a8b489b..27733ffd91 100644--- a/docs/src/content/docs/development/Front End/project-files.mdx+++ b/docs/src/content/docs/development/Front End/project-files.mdx@@ -78,7 +78,7 @@ Import verifies dependency paths and hashes before any mutation, preflights font| --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- || `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` | yes\* | The project board's visible contents as the exporting server enumerated them: `{version: 1, items: [{kind, category, name, starred}]}`. |+| `board.json` | yes\* | Every board of the project as the exporting server enumerated them: `{version: 2, boards: [{name, isInbox, archived, items: [{kind, category, name, starred}]}]}`, the inbox first. Version 1 (the inbox alone, as `{version: 1, items}`) is still read. || `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. |@@ -93,7 +93,7 @@ The manifest is written indented and the document compact: the manifest is the oA 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.+**Board membership** is what the project's gallery shows: everything it has produced, including results the canvas never used, on every board of the project — the inbox and the boards made inside it. It comes from `GET /projects/{id}/board-snapshot` and is written to `board.json`, board by board. 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.@@ -117,9 +117,9 @@ The skip is by key on purpose, because the members got there differently. `selec`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 → stage boards → restore → remap → create → place the other boards**. 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.+**Creating the project is the commit point.** When an archive carries `board.json`, the restore first creates an unclaimed private *staging board* per board, in the archive's order so creation order survives — the inbox's named after the project, the others after themselves — and uploads onto them, then passes the inbox's id to `POST /projects`, which claims and renames it in the same transaction that writes the remapped document. The other staged boards are moved into the project with `PATCH /boards/{id}` once it exists, archived as the source had them. That placement is reported, never fatal: a project with most of its boards beats none, and a staged board that could not move is still in the Library with everything on it, which is what the import's toast says. Every staging board joins the rollback ledger the moment it exists, so a restore abandoned between two creates leaves nothing behind. 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. An archive without `board.json`, like 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.@@ -147,7 +147,7 @@ An open project is flushed to the server before it is read, and a failed flush aRestoration 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.+Each 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.@@ -221,6 +221,6 @@ Earlier webv2 builds exported `*.invokeproject.json` files containing a versionThe 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.-**Not exported:** models and LoRAs, library templates themselves, queue history, intermediates, the canvas's private `other` media except where the document references it, gallery boards other than the project's inbox, and account preferences. A project file carries one project's workspace, not the install around it.+**Not exported:** models and LoRAs, library templates themselves, queue history, intermediates, the canvas's private `other` media except where the document references it, and account preferences. A project file carries one project's workspace, not the install around it.**Workflows travel with the project.** A schema-3 document carries the project's whole workflow collection (`workflows.entries`, each with its document and optional source and last-run metadata) and its active selection, so an archive holds every workflow the project owns, active or not, and every media reference they name is bundled like any other document reference. Source metadata names the library template a copy came from; import clears it, because a template id on one install names nothing on another and a portable file must never inherit a library write target. Same-server duplication keeps it. Older archives that carry a schema-2 `projectGraph` load through the same migration as older server documents: that graph becomes the project's first and only workflow.diff --git a/invokeai/app/api/routers/projects.py b/invokeai/app/api/routers/projects.pyindex 9331e9b977..71cbe527ae 100644--- a/invokeai/app/api/routers/projects.py+++ b/invokeai/app/api/routers/projects.py@@ -216,15 +216,15 @@ def update_project()def get_project_board_snapshot(current_user: CurrentUserOrDefault,- project_id: str = Path(description="The id of the project whose board to enumerate"),+ project_id: str = Path(description="The id of the project whose boards to enumerate"),) -> ProjectBoardSnapshotDTO:- """Lists everything on the project's inbox that the gallery would show.+ """Lists everything on the project's boards that the gallery would show, inbox first.Intermediates and the canvas's private `other` category are excluded. Unpaginated: the caller- that needs this — exporting a project — has to hold the whole list anyway. It is still bounded,- because the answer is built entirely in memory and any client with a project id can ask for it;- a board past the ceiling is one an export could not have packed either, so it is refused as a- 413 rather than paged.+ that needs this — exporting a project — has to hold the whole list anyway. It is still bounded+ over all the boards together, because the answer is built entirely in memory and any client+ with a project id can ask for it; a project past the ceiling is one an export could not have+ packed either, so it is refused as a 413 rather than paged."""try:return ApiDependencies.invoker.services.project_records.get_board_snapshot(current_user.user_id, project_id)diff --git a/invokeai/app/services/project_records/project_records_base.py b/invokeai/app/services/project_records/project_records_base.pyindex 1f4a7db10a..faf1a95b5d 100644--- a/invokeai/app/services/project_records/project_records_base.py+++ b/invokeai/app/services/project_records/project_records_base.py@@ -118,11 +118,11 @@ class ProjectRecordsStorageBase(ABC):@abstractmethoddef get_board_snapshot(self, user_id: str, project_id: str) -> ProjectBoardSnapshotDTO:- """Enumerate everything on the project's inbox that the gallery would show.+ """Enumerate everything on the project's boards that the gallery would show, inbox first.- Excludes intermediates and the canvas's private `other` category, so the result is exactly- the board as the user sees it. Exports use this to carry a project's whole workspace rather- than only the media its document references.+ Excludes intermediates and the canvas's private `other` category, so each board is exactly+ what the user sees on it. Exports use this to carry a project's whole workspace rather than+ only the media its document references.Raises:ProjectRecordNotFoundError: No such project for this user.diff --git a/invokeai/app/services/project_records/project_records_common.py b/invokeai/app/services/project_records/project_records_common.pyindex f6dd4b864b..2b0a173bce 100644--- a/invokeai/app/services/project_records/project_records_common.py+++ b/invokeai/app/services/project_records/project_records_common.py@@ -107,7 +107,7 @@ class ProjectBoardUnavailableError(Exception):PROJECT_BOARD_SNAPSHOT_MAX_ITEMS = 20_000-"""The largest board the snapshot route will enumerate.+"""The most items, over all of a project's boards, the snapshot route will enumerate.The snapshot is unpaginated on purpose — the caller that needs it, exporting a project, has to holdthe whole list anyway. That is a reason not to page it, not a reason to have no ceiling: the answer@@ -118,10 +118,10 @@ packed either.class ProjectBoardTooLargeError(Exception):- """Raised when a project's board holds more than the snapshot route will enumerate."""+ """Raised when a project's boards hold more than the snapshot route will enumerate."""def __init__(self, project_id: str, limit: int) -> None:- super().__init__(f"Project {project_id} has more than {limit} items on its board")+ super().__init__(f"Project {project_id} has more than {limit} items on its boards")class ProjectSummaryDTO(BaseModel):@@ -153,15 +153,27 @@ class ProjectBoardItemDTO(BaseModel):starred: bool = Field(description="Whether the item is starred")+class ProjectBoardSnapshotBoardDTO(BaseModel):+ """One of the project's boards and the visible items on it."""++ board_id: str = Field(description="The board's id on this install")+ name: str = Field(description="The board's name; the inbox carries the project's")+ is_inbox: bool = Field(description="Whether this is the project's inbox, which every project has exactly one of")+ archived: bool = Field(description="Whether the board is archived")+ items: list[ProjectBoardItemDTO] = Field(description="The board's visible items, ordered by kind then name")++class ProjectBoardSnapshotDTO(BaseModel):- """Everything a project's board holds that the gallery would show.+ """Everything a project's boards hold that the gallery would show.This is the enumeration an export needs in order to carry a project's whole workspace ratherthan only the media its document happens to reference. Intermediates and the canvas's private- `other` category are excluded, because neither is something the gallery shows on the board.+ `other` category are excluded, because neither is something the gallery shows on a board.Deliberately unversioned: `.invk`'s `board.json` carries its own version, so the archive formatis free to change without the wire format following it, and vice versa."""- items: list[ProjectBoardItemDTO] = Field(description="The board's visible items, ordered by kind then name")+ boards: list[ProjectBoardSnapshotBoardDTO] = Field(+ description="The project's boards, inbox first, then the rest in creation order"+ )diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.pyindex a8c81c34b2..3b512da0db 100644--- a/invokeai/app/services/project_records/project_records_sqlite.py+++ b/invokeai/app/services/project_records/project_records_sqlite.py@@ -13,6 +13,7 @@ from invokeai.app.services.project_records.project_records_common import (PROJECT_DOCUMENT_MAX_BYTES,ProjectBoardItemDTO,ProjectBoardNotFoundError,+ ProjectBoardSnapshotBoardDTO,ProjectBoardSnapshotDTO,ProjectBoardTooLargeError,ProjectBoardUnavailableError,@@ -389,8 +390,29 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):if row is None:raise ProjectRecordNotFoundError(project_id)+ inbox_id = row[0]+ # Both keys: project ids are unique per user only. The inbox leads; the rest follow in+ # the order they were made, which is what the gallery's default sort shows.+ cursor.execute(+ """--sql+ SELECT board_id, board_name, archived+ FROM boards+ WHERE user_id = ? AND project_id = ?+ ORDER BY CASE WHEN board_id = ? THEN 0 ELSE 1 END, created_at ASC, board_id ASC;+ """,+ (user_id, project_id, inbox_id),+ )+ board_rows = cursor.fetchall()+ board_ids = [board_row[0] for board_row in board_rows]+ if inbox_id not in board_ids:+ # Only raw SQL can leave an inbox outside its project; the snapshot still leads with it.+ cursor.execute("SELECT board_id, board_name, archived FROM boards WHERE board_id = ?;", (inbox_id,))+ board_rows = [cursor.fetchone(), *board_rows]+ board_ids = [inbox_id, *board_ids]+ board_placeholders = ", ".join("?" for _ in board_ids)+# One union over both namespaces, shaped like `get_board_media_summaries`. The filters- # are what make the result match what the gallery shows for this board: intermediates+ # are what make the result match what the gallery shows for these boards: intermediates# are hidden, and the categories come from IMAGE_CATEGORIES/ASSETS_CATEGORIES, which# `other` — the canvas's private category — is deliberately in neither of.#@@ -398,43 +420,56 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):# board query consults it, so filtering here would make the snapshot disagree with the# counts shown beside the board.#- # Bounded, unlike the counts: the caller holds the whole answer in memory and so does- # this, and the route is reachable by anyone with a project id.+ # Bounded over the whole project, unlike the counts: the caller holds the whole answer+ # in memory and so does this, and the route is reachable by anyone with a project id.cursor.execute(f"""--sql- SELECT 'image' AS kind, images.image_name AS name,+ SELECT board_images.board_id AS board_id, 'image' AS kind, images.image_name AS name,images.image_category AS category, images.starred AS starredFROM board_imagesINNER JOIN images ON board_images.image_name = images.image_name- WHERE board_images.board_id = ?+ WHERE board_images.board_id IN ({board_placeholders})AND images.is_intermediate = FALSEAND images.image_category IN ({_VISIBLE_CATEGORY_PLACEHOLDERS})UNION ALL- SELECT 'video' AS kind, videos.video_name AS name,+ SELECT board_videos.board_id AS board_id, 'video' AS kind, videos.video_name AS name,videos.video_category AS category, videos.starred AS starredFROM board_videosINNER JOIN videos ON board_videos.video_name = videos.video_name- WHERE board_videos.board_id = ?+ WHERE board_videos.board_id IN ({board_placeholders})AND videos.is_intermediate = FALSEAND videos.video_category IN ({_VISIBLE_CATEGORY_PLACEHOLDERS})ORDER BY kind ASC, name ASCLIMIT ?;""",(- row[0],+ *board_ids,*_VISIBLE_BOARD_CATEGORIES,- row[0],+ *board_ids,*_VISIBLE_BOARD_CATEGORIES,PROJECT_BOARD_SNAPSHOT_MAX_ITEMS + 1,),)- rows = cursor.fetchall()+ item_rows = cursor.fetchall()- if len(rows) > PROJECT_BOARD_SNAPSHOT_MAX_ITEMS:+ if len(item_rows) > PROJECT_BOARD_SNAPSHOT_MAX_ITEMS:raise ProjectBoardTooLargeError(project_id, PROJECT_BOARD_SNAPSHOT_MAX_ITEMS)+ items_by_board: dict[str, list[ProjectBoardItemDTO]] = {board_id: [] for board_id in board_ids}+ for r in item_rows:+ items_by_board[r[0]].append(ProjectBoardItemDTO(kind=r[1], name=r[2], category=r[3], starred=bool(r[4])))+return ProjectBoardSnapshotDTO(- items=[ProjectBoardItemDTO(kind=r[0], name=r[1], category=r[2], starred=bool(r[3])) for r in rows]+ boards=[+ ProjectBoardSnapshotBoardDTO(+ board_id=board_row[0],+ name=board_row[1],+ is_inbox=board_row[0] == inbox_id,+ archived=bool(board_row[2]),+ items=items_by_board[board_row[0]],+ )+ for board_row in board_rows+ ])def get_board_id(self, user_id: str, project_id: str) -> str:diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex b2c7190350..1de58c1696 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -15839,7 +15839,7 @@"get": {"tags": ["projects"],"summary": "Get Project Board Snapshot",- "description": "Lists everything on the project's inbox that the gallery would show.\n\nIntermediates and the canvas's private `other` category are excluded. Unpaginated: the caller\nthat needs this \u2014 exporting a project \u2014 has to hold the whole list anyway. It is still bounded,\nbecause the answer is built entirely in memory and any client with a project id can ask for it;\na board past the ceiling is one an export could not have packed either, so it is refused as a\n413 rather than paged.",+ "description": "Lists everything on the project's boards that the gallery would show, inbox first.\n\nIntermediates and the canvas's private `other` category are excluded. Unpaginated: the caller\nthat needs this \u2014 exporting a project \u2014 has to hold the whole list anyway. It is still bounded\nover all the boards together, because the answer is built entirely in memory and any client\nwith a project id can ask for it; a project past the ceiling is one an export could not have\npacked either, so it is refused as a 413 rather than paged.","operationId": "get_project_board_snapshot","security": [{@@ -15853,10 +15853,10 @@"required": true,"schema": {"type": "string",- "description": "The id of the project whose board to enumerate",+ "description": "The id of the project whose boards to enumerate","title": "Project Id"},- "description": "The id of the project whose board to enumerate"+ "description": "The id of the project whose boards to enumerate"}],"responses": {@@ -90118,8 +90118,28 @@"title": "ProjectBoardItemDTO","description": "One visible item on a project's board."},- "ProjectBoardSnapshotDTO": {+ "ProjectBoardSnapshotBoardDTO": {"properties": {+ "board_id": {+ "type": "string",+ "title": "Board Id",+ "description": "The board's id on this install"+ },+ "name": {+ "type": "string",+ "title": "Name",+ "description": "The board's name; the inbox carries the project's"+ },+ "is_inbox": {+ "type": "boolean",+ "title": "Is Inbox",+ "description": "Whether this is the project's inbox, which every project has exactly one of"+ },+ "archived": {+ "type": "boolean",+ "title": "Archived",+ "description": "Whether the board is archived"+ },"items": {"items": {"$ref": "#/components/schemas/ProjectBoardItemDTO"@@ -90130,9 +90150,25 @@}},"type": "object",- "required": ["items"],+ "required": ["board_id", "name", "is_inbox", "archived", "items"],+ "title": "ProjectBoardSnapshotBoardDTO",+ "description": "One of the project's boards and the visible items on it."+ },+ "ProjectBoardSnapshotDTO": {+ "properties": {+ "boards": {+ "items": {+ "$ref": "#/components/schemas/ProjectBoardSnapshotBoardDTO"+ },+ "type": "array",+ "title": "Boards",+ "description": "The project's boards, inbox first, then the rest in creation order"+ }+ },+ "type": "object",+ "required": ["boards"],"title": "ProjectBoardSnapshotDTO",- "description": "Everything a project's board holds that the gallery would show.\n\nThis is the enumeration an export needs in order to carry a project's whole workspace rather\nthan only the media its document happens to reference. Intermediates and the canvas's private\n`other` category are excluded, because neither is something the gallery shows on the board.\n\nDeliberately unversioned: `.invk`'s `board.json` carries its own version, so the archive format\nis free to change without the wire format following it, and vice versa."+ "description": "Everything a project's boards hold that the gallery would show.\n\nThis is the enumeration an export needs in order to carry a project's whole workspace rather\nthan only the media its document happens to reference. Intermediates and the canvas's private\n`other` category are excluded, because neither is something the gallery shows on a board.\n\nDeliberately unversioned: `.invk`'s `board.json` carries its own version, so the archive format\nis free to change without the wire format following it, and vice versa."},"ProjectCreateRequest": {"properties": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 986c443b9a..7cedc8936b 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -4075,13 +4075,13 @@ export type paths = {};/*** Get Project Board Snapshot- * @description Lists everything on the project's inbox that the gallery would show.+ * @description Lists everything on the project's boards that the gallery would show, inbox first.** Intermediates and the canvas's private `other` category are excluded. Unpaginated: the caller- * that needs this — exporting a project — has to hold the whole list anyway. It is still bounded,- * because the answer is built entirely in memory and any client with a project id can ask for it;- * a board past the ceiling is one an export could not have packed either, so it is refused as a- * 413 rather than paged.+ * that needs this — exporting a project — has to hold the whole list anyway. It is still bounded+ * over all the boards together, because the answer is built entirely in memory and any client+ * with a project id can ask for it; a project past the ceiling is one an export could not have+ * packed either, so it is refused as a 413 rather than paged.*/get: operations["get_project_board_snapshot"];put?: never;@@ -38528,23 +38528,54 @@ export type components = {*/starred: boolean;};+ /**+ * ProjectBoardSnapshotBoardDTO+ * @description One of the project's boards and the visible items on it.+ */+ ProjectBoardSnapshotBoardDTO: {+ /**+ * Board Id+ * @description The board's id on this install+ */+ board_id: string;+ /**+ * Name+ * @description The board's name; the inbox carries the project's+ */+ name: string;+ /**+ * Is Inbox+ * @description Whether this is the project's inbox, which every project has exactly one of+ */+ is_inbox: boolean;+ /**+ * Archived+ * @description Whether the board is archived+ */+ archived: boolean;+ /**+ * Items+ * @description The board's visible items, ordered by kind then name+ */+ items: components["schemas"]["ProjectBoardItemDTO"][];+ };/*** ProjectBoardSnapshotDTO- * @description Everything a project's board holds that the gallery would show.+ * @description Everything a project's boards hold that the gallery would show.** This is the enumeration an export needs in order to carry a project's whole workspace rather* than only the media its document happens to reference. Intermediates and the canvas's private- * `other` category are excluded, because neither is something the gallery shows on the board.+ * `other` category are excluded, because neither is something the gallery shows on a board.** Deliberately unversioned: `.invk`'s `board.json` carries its own version, so the archive format* is free to change without the wire format following it, and vice versa.*/ProjectBoardSnapshotDTO: {/**- * Items- * @description The board's visible items, ordered by kind then name+ * Boards+ * @description The project's boards, inbox first, then the rest in creation order*/- items: components["schemas"]["ProjectBoardItemDTO"][];+ boards: components["schemas"]["ProjectBoardSnapshotBoardDTO"][];};/*** ProjectCreateRequest@@ -59991,7 +60022,7 @@ export interface operations {query?: never;header?: never;path: {- /** @description The id of the project whose board to enumerate */+ /** @description The id of the project whose boards to enumerate */project_id: string;};cookie?: never;diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex b1946cb307..de9346667c 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -489,6 +489,8 @@"legacyCanvasProject": "This is a canvas project from an earlier version of Invoke, which cannot be opened here.","missingBoardItems_one": "1 board item could not be included.","missingBoardItems_other": "{{count}} board items could not be included.",+ "unplacedBoards_one": "1 board could not be moved into the project and is in the Library.",+ "unplacedBoards_other": "{{count}} boards could not be moved into the project and are in the Library.","missingReferences_one": "1 project reference could not be included.","missingReferences_other": "{{count}} project references could not be included.","notAProject": "This file is not an Invoke project.",diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjsindex 7ff1d9bdaf..b29a99707e 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs@@ -69,8 +69,13 @@ export const PROJECT_FILE_BOARD = Object.freeze({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']),+ /** On the project's other board, so an archive carries more than the inbox. */+ memberImages: Object.freeze(['fixture-image-0013.png', 'fixture-image-0014.png']),});+/** The journey project's board other than its inbox; see `createBoards`. */+export const PROJECT_FILE_MEMBER_BOARD = Object.freeze({ id: 'fixture-member-board-02', name: 'Site plan refs' });+/** 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' }],@@ -81,6 +86,7 @@ const PROJECT_BOARD_IMAGES = new Map([[PROJECT_FILE_BOARD.canvasOwnedImage, { image_category: 'other' }],[PROJECT_FILE_BOARD.intermediateImage, { image_category: 'general', is_intermediate: true }],]);+const MEMBER_BOARD_IMAGES = new Set(PROJECT_FILE_BOARD.memberImages);const createImages = (count) =>range(count, (index) => {@@ -104,6 +110,9 @@ const createImages = (count) =>...(projectBoardMembership === undefined? {}: { board_id: PROJECT_FILE_BOARD_ID, starred: false, ...projectBoardMembership }),+ ...(MEMBER_BOARD_IMAGES.has(imageName)+ ? { board_id: PROJECT_FILE_MEMBER_BOARD.id, image_category: 'general', starred: false }+ : {}),};});diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex 9e2923c521..bd5fbbffaa 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -3,6 +3,7 @@ import { readFile } from 'node:fs/promises';import test from 'node:test';import {+ PROJECT_FILE_MEMBER_BOARD,assertMockBackendFixture,collectCanvasLeaves,createMockBackendFixture,@@ -728,10 +729,12 @@ test('the board snapshot lists only what the gallery would show on a project boaconst snapshot = await getJson(backend, `/api/v1/projects/${project.project_id}/board-snapshot`);// `other` is the canvas's private category and intermediates are hidden — neither travels.- assert.deepEqual(snapshot.items.map((item) => item.name).sort(), [control, general].sort());- assert.deepEqual(snapshot.items.map((item) => item.category).sort(), ['control', 'general']);+ const [inbox] = snapshot.boards;+ assert.equal(inbox.is_inbox, true);+ assert.deepEqual(inbox.items.map((item) => item.name).sort(), [control, general].sort());+ assert.deepEqual(inbox.items.map((item) => item.category).sort(), ['control', 'general']);assert.equal(- snapshot.items.every((item) => item.kind === 'image' && item.starred === false),+ inbox.items.every((item) => item.kind === 'image' && item.starred === false),true);@@ -741,12 +744,30 @@ test('the board snapshot lists only what the gallery would show on a project boamethod: 'POST',});const starred = await getJson(backend, `/api/v1/projects/${project.project_id}/board-snapshot`);- assert.equal(starred.items.find((item) => item.name === general).starred, true);+ assert.equal(starred.boards[0].items.find((item) => item.name === general).starred, true);assert.equal((await fetch(`${backend.origin}/api/v1/projects/nope/board-snapshot`)).status, 404);});});+test('the board snapshot lists the project other boards after the inbox, with their own items', async () => {+ await withRepresentativeBackend(async (backend) => {+ const snapshot = await getJson(backend, '/api/v1/projects/fixture-project-002/board-snapshot');++ assert.deepEqual(+ snapshot.boards.map((board) => [board.board_id, board.is_inbox, board.name, board.items.length]),+ [+ [PROJECT_FILE_BOARD_ID, true, 'Fixture Project 002', 6],+ [PROJECT_FILE_MEMBER_BOARD.id, false, PROJECT_FILE_MEMBER_BOARD.name, 2],+ ]+ );+ assert.deepEqual(+ snapshot.boards[1].items.map((item) => item.name).sort(),+ [...PROJECT_FILE_BOARD.memberImages].sort()+ );+ });+});+test('copying media mints fresh identities and deleting a project keeps its media', async () => {await withRepresentativeBackend(async (backend) => {const [project] = await getJson(backend, '/api/v1/projects/');diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex a9e98cbe0f..72ef1cbc21 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -1068,9 +1068,28 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {if (method === 'GET' && boardSnapshotMatch) {const project = state.projects.get(decodeURIComponent(boardSnapshotMatch[1]));- return project- ? json(200, { items: boardSnapshotItems(state, project.board_id) })- : json(404, { detail: 'Project not found' });+ if (!project) {+ return json(404, { detail: 'Project not found' });+ }++ // The inbox first, then the project's other boards in creation order — as the backend lists them.+ const members = [...state.boards.values()]+ .filter((board) => (board.project_id ?? null) === project.project_id && board.board_id !== project.board_id)+ .sort(+ (left, right) =>+ left.created_at.localeCompare(right.created_at) || left.board_id.localeCompare(right.board_id)+ );+ const boards = [state.boards.get(project.board_id), ...members]+ .filter((board) => board !== undefined)+ .map((board) => ({+ archived: board.archived,+ board_id: board.board_id,+ is_inbox: board.board_id === project.board_id,+ items: boardSnapshotItems(state, board.board_id),+ name: board.board_name,+ }));++ return json(200, { boards });}if (path.startsWith('/api/v1/client_state/')) {diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex 61f6480e2c..db10cf4195 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -14,6 +14,7 @@ import {MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,PROJECT_FILE_BOARD,PROJECT_FILE_BOARD_ID,+ PROJECT_FILE_MEMBER_BOARD,} from './mock-backend-fixtures.mjs';import { startMockBackend } from './mock-backend.mjs';import { killPreview, spawnPreview } from './preview-server.mjs';@@ -159,7 +160,10 @@ const EXPECTED_BOARD_SHAPE = ['video:general:false',].sort();-/** The archived names of everything on the source board, for proving none of them is reused. */+/** The source's other board, as it must travel: two plain generated images. */+const EXPECTED_MEMBER_BOARD_SHAPE = ['image:general:false', 'image:general:false'];++/** The archived names of everything on the source's boards, for proving none of them is reused. */const ARCHIVED_BOARD_NAMES = [PROJECT_FILE_BOARD.referencedImage,PROJECT_FILE_BOARD.unreferencedImage,@@ -167,8 +171,12 @@ const ARCHIVED_BOARD_NAMES = [PROJECT_FILE_BOARD.userAsset,PROJECT_FILE_BOARD.maskAsset,PROJECT_FILE_BOARD.video,+ ...PROJECT_FILE_BOARD.memberImages,];+/** Every item of every board of a snapshot, with the board each came from. */+const snapshotItems = (snapshot) => snapshot.boards.flatMap((board) => board.items);+const readArchiveEntries = async (archivePath) => unzipSync(new Uint8Array(await readFile(archivePath)));const readEntryJson = (entries, name) => {@@ -267,7 +275,8 @@ const importArchive = async ({ archivePath, browser, contexts, errors, phase })const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectory }) => {const sourceBoard = await getBoardSnapshot(sourceProjectId);- assert.deepEqual(boardShape(sourceBoard.items), EXPECTED_BOARD_SHAPE);+ assert.deepEqual(boardShape(sourceBoard.boards[0].items), EXPECTED_BOARD_SHAPE);+ assert.deepEqual(boardShape(sourceBoard.boards[1].items), EXPECTED_MEMBER_BOARD_SHAPE);const exportContext = await browser.newContext({ acceptDownloads: true });@@ -315,10 +324,22 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryassert.equal(manifest.version, 2);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());- // Expect five board items plus three external images and one external video, deduplicated across references.+ assert.equal(archivedBoard.version, 2);+ // The inbox leads, then the project's other board, each with its own media.+ assert.deepEqual(+ archivedBoard.boards.map((board) => [board.name, board.isInbox, board.archived]),+ [+ [sourceProjectName, true, false],+ [PROJECT_FILE_MEMBER_BOARD.name, false, false],+ ]+ );+ assert.deepEqual(boardShape(archivedBoard.boards[0].items), EXPECTED_BOARD_SHAPE);+ assert.deepEqual(boardShape(archivedBoard.boards[1].items), EXPECTED_MEMBER_BOARD_SHAPE);+ assert.deepEqual(+ archivedBoard.boards.flatMap((board) => board.items.map((item) => item.name)).sort(),+ [...ARCHIVED_BOARD_NAMES].sort()+ );+ // Expect the board items plus three external images and one external video, deduplicated across references.assert.deepEqual(bundledImages.sort(),[...ARCHIVED_BOARD_NAMES.filter((name) => name.endsWith('.png')), ...PROJECT_FILE_BOARD.externalImages]@@ -366,10 +387,20 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryconst imported = await fetchJson(`/api/v1/projects/${encodeURIComponent(summary.project_id)}`);const importedBoard = await getBoardSnapshot(summary.project_id);- const importedBoardNames = importedBoard.items.map((item) => item.name);+ const importedBoardNames = snapshotItems(importedBoard).map((item) => item.name);assert.equal(imported.data.id, summary.project_id);- assert.deepEqual(boardShape(importedBoard.items), EXPECTED_BOARD_SHAPE);+ // The project's other board came across as a board of its own, under its name, with its media.+ assert.deepEqual(+ importedBoard.boards.map((board) => [board.is_inbox, board.name]),+ [+ [true, summary.name],+ [false, PROJECT_FILE_MEMBER_BOARD.name],+ ]+ );+ assert.notEqual(importedBoard.boards[1].board_id, PROJECT_FILE_MEMBER_BOARD.id);+ assert.deepEqual(boardShape(importedBoard.boards[0].items), EXPECTED_BOARD_SHAPE);+ assert.deepEqual(boardShape(importedBoard.boards[1].items), EXPECTED_MEMBER_BOARD_SHAPE);for (const name of importedBoardNames) {assert.equal(ARCHIVED_BOARD_NAMES.includes(name), false, `${name} was adopted from the archive instead of copied.`);@@ -408,7 +439,7 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryassert.equal(response.status, 404, `${hidden} must not exist on the destination.`);}- for (const item of importedBoard.items) {+ for (const item of snapshotItems(importedBoard)) {const base = item.kind === 'image' ? '/api/v1/images' : '/api/v1/videos';await assertAssetRoute(base, item.name, ['full', 'thumbnail']);@@ -436,7 +467,7 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryawait runMissingBinaryImport({ browser, contexts, entries, errors, tempDirectory });return {- boardItemCount: importedBoard.items.length,+ boardItemCount: snapshotItems(importedBoard).length,coverImageName,imageNames: [...importedBoardNames].sort(),projectId: summary.project_id,@@ -476,9 +507,18 @@ const runDuplication = async ({ browser, contexts, errors, imported, importedBoaassert.notEqual(copy.board_id, imported.board_id);const copiedBoard = await getBoardSnapshot(copy.project_id);- const copiedBoardNames = copiedBoard.items.map((item) => item.name);+ const copiedBoardNames = snapshotItems(copiedBoard).map((item) => item.name);- assert.deepEqual(boardShape(copiedBoard.items), EXPECTED_BOARD_SHAPE);+ // The copy has the same boards, each copied with its own media.+ assert.deepEqual(+ copiedBoard.boards.map((board) => [board.is_inbox, board.name]),+ [+ [true, `${sourceProjectName} copy`],+ [false, PROJECT_FILE_MEMBER_BOARD.name],+ ]+ );+ assert.deepEqual(boardShape(copiedBoard.boards[0].items), EXPECTED_BOARD_SHAPE);+ assert.deepEqual(boardShape(copiedBoard.boards[1].items), EXPECTED_MEMBER_BOARD_SHAPE);for (const name of copiedBoardNames) {assert.equal(importedBoardNames.includes(name), false, `${name} is shared with the project it was copied from.`);diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsxindex aafe34edb8..caf9b05316 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx@@ -53,6 +53,8 @@ vi.mock('@workbench/WorkbenchContext', () => ({shallowEqual),useWorkbenchCommands: () => store.commands,+ useWorkbenchInternalStore: () => store,+ useWorkbenchPersistenceService: () => ({ ensureProjectOnServer: () => Promise.resolve() }),useWorkbenchQueries: () => store.queries,}));diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex 27e7534f03..f479c2444e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -51,8 +51,17 @@ export interface ProjectBoardItemDTO {starred: boolean;}-export interface ProjectBoardSnapshotDTO {+export interface ProjectBoardSnapshotBoardDTO {+ archived: boolean;+ board_id: string;+ is_inbox: boolean;items: ProjectBoardItemDTO[];+ name: string;+}++export interface ProjectBoardSnapshotDTO {+ /** The inbox first, then the project's other boards in creation order. */+ boards: ProjectBoardSnapshotBoardDTO[];}export interface ProjectUpdateRequest {@@ -209,7 +218,7 @@ export const deleteProject = async (await apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}${query}`, { method: 'DELETE', signal });};-/** Includes unreferenced visible board media; excludes intermediate/other categories. */+/** Every board of the project with its visible media; excludes intermediate/other categories. */export const getProjectBoardSnapshot = (projectId: string, signal?: AbortSignal): Promise<ProjectBoardSnapshotDTO> =>apiFetchJson<ProjectBoardSnapshotDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}/board-snapshot`, {signal,diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.tsindex a845c9272c..eedf9afc91 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts@@ -24,6 +24,7 @@ import {fetchImageThumbnail,fetchVideoBytes,findExistingVideoNames,+ placeBoardInProject,starImages,starVideos,uploadArchiveImage,@@ -231,6 +232,19 @@ describe('board media transport', () => {expect(options.method).toBe('POST');});+ it('moves a staging board into a project, archiving it only when the source had', async () => {+ mocks.apiFetchJson.mockResolvedValue({});++ await placeBoardInProject('staged', 'project-1', false);+ await placeBoardInProject('staged', 'project-1', true);++ expect(mocks.apiFetchJson.mock.calls.map(([url, options]) => [url, (options as { body: string }).body])).toEqual([+ ['/api/v1/boards/staged', '{"project_id":"project-1"}'],+ ['/api/v1/boards/staged', '{"project_id":"project-1","archived":true}'],+ ]);+ expect((mocks.apiFetchJson.mock.calls[0]![1] as { method: string }).method).toBe('PATCH');+ });+/** Untracked media that landed on the board while the import ran must survive as Uncategorized. */it('deletes a staging board without taking its media with it', async () => {mocks.apiFetchJson.mockResolvedValue({});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.tsindex 18956411f9..7eb246a777 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts@@ -645,6 +645,23 @@ export const createStagingBoard = async (boardName: string, signal?: AbortSignalreturn dto.board_id;};+/**+ * Move a staging board that holds a member board's media into the project it now belongs to, and archive it if+ * the source had. Only after the project exists: a board is a member of a project the server already has.+ */+export const placeBoardInProject = async (+ boardId: string,+ projectId: string,+ archived: boolean,+ signal?: AbortSignal+): Promise<void> => {+ await apiFetchJson<unknown>(`${BOARDS_BASE}/${encodeURIComponent(boardId)}`, {+ body: JSON.stringify({ project_id: projectId, ...(archived ? { archived: true } : {}) }),+ method: 'PATCH',+ signal,+ });+};+/*** Drop a staging board whose project was never created. `include_images=false` deliberately: the* restore deletes its own identities one by one, and a generation that landed on the boarddiff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.tsindex 7d53ecc0b4..89daf4969a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/board.test.ts@@ -1,25 +1,33 @@import { describe, expect, it } from 'vitest';-import { buildInvkBoardSnapshot, parseInvkBoardSnapshot } from './board';+import { buildInvkBoardSnapshot, flattenInvkBoardItems, parseInvkBoardSnapshot, type InvkBoardItem } from './board';import { InvkFormatError } from './format';/** Malformed board enumeration must fail before restore creates resources. */-const item = (overrides: Partial<Parameters<typeof buildInvkBoardSnapshot>[0][number]> = {}) => ({- category: 'general' as const,- kind: 'image' as const,+const item = (overrides: Partial<InvkBoardItem> = {}): InvkBoardItem => ({+ category: 'general',+ kind: 'image',name: 'a.png',starred: false,...overrides,});-const expectRefusal = (data: unknown): void => {+const inbox = (items: InvkBoardItem[], name = 'Project') => ({ archived: false, isInbox: true, items, name });+const member = (items: InvkBoardItem[], name = 'Member', archived = false) => ({+ archived,+ isInbox: false,+ items,+ name,+});++const expectRefusal = (data: unknown, reason = 'damaged'): void => {try {parseInvkBoardSnapshot(data);expect.unreachable('parseInvkBoardSnapshot should have thrown');} catch (error) {expect(error).toBeInstanceOf(InvkFormatError);- expect((error as InvkFormatError).reason).toBe('damaged');+ expect((error as InvkFormatError).reason).toBe(reason);}};@@ -33,68 +41,126 @@ describe('parseInvkBoardSnapshot', () => {item({ kind: 'video', name: 'e.mp4' }),];- expect(parseInvkBoardSnapshot({ items, version: 1 }).items).toHaveLength(5);+ expect(parseInvkBoardSnapshot({ boards: [inbox(items)], version: 2 }).boards[0]?.items).toHaveLength(5);});- it('canonicalizes order so exports of the same board compare equal', () => {+ it('canonicalizes item order so exports of the same board compare equal', () => {const shuffled = [item({ kind: 'video', name: 'z.mp4' }), item({ name: 'b.png' }), item({ name: 'a.png' })];- expect(parseInvkBoardSnapshot({ items: shuffled, version: 1 }).items.map((entry) => entry.name)).toEqual([- 'a.png',- 'b.png',- 'z.mp4',+ expect(+ parseInvkBoardSnapshot({ boards: [inbox(shuffled)], version: 2 }).boards[0]?.items.map((entry) => entry.name)+ ).toEqual(['a.png', 'b.png', 'z.mp4']);+ });++ it('puts the inbox first whatever order the file lists the boards in', () => {+ const parsed = parseInvkBoardSnapshot({+ boards: [member([item({ name: 'm.png' })], 'Site plan refs', true), inbox([item()])],+ version: 2,+ });++ expect(parsed.boards.map((board) => [board.name, board.isInbox, board.archived])).toEqual([+ ['Project', true, false],+ ['Site plan refs', false, true],]);+ expect(flattenInvkBoardItems(parsed).map((entry) => entry.name)).toEqual(['a.png', 'm.png']);+ });++ /** Dev builds wrote version 1 with the inbox alone; it reads as a project with no other boards. */+ it('reads a version 1 entry as a lone inbox', () => {+ expect(parseInvkBoardSnapshot({ items: [item({ name: 'b.png' }), item()], version: 1 })).toEqual({+ boards: [{ archived: false, isInbox: true, items: [item(), item({ name: 'b.png' })], name: '' }],+ version: 2,+ });});it('treats an image and a video of the same name as different items', () => {const items = [item({ name: 'twin' }), item({ kind: 'video', name: 'twin' })];- expect(parseInvkBoardSnapshot({ items, version: 1 }).items).toHaveLength(2);+ expect(parseInvkBoardSnapshot({ boards: [inbox(items)], version: 2 }).boards[0]?.items).toHaveLength(2);});- it('accepts an empty board', () => {- expect(parseInvkBoardSnapshot({ items: [], version: 1 })).toEqual({ items: [], version: 1 });+ it('accepts an empty inbox', () => {+ expect(parseInvkBoardSnapshot({ boards: [inbox([])], version: 2 })).toEqual({+ boards: [inbox([])],+ version: 2,+ });});- it('refuses a duplicate descriptor', () => {- expectRefusal({ items: [item(), item()], version: 1 });+ it('refuses a duplicate descriptor, on one board or across two', () => {+ expectRefusal({ boards: [inbox([item(), item()])], version: 2 });+ expectRefusal({ boards: [inbox([item()]), member([item()])], version: 2 });+ });++ it('refuses a file without exactly one inbox', () => {+ expectRefusal({ boards: [member([])], version: 2 });+ expectRefusal({ boards: [inbox([]), inbox([])], version: 2 });+ expectRefusal({ boards: [], version: 2 });+ });++ /** The server allows a blank board name, so an export can carry one; refusing it would break the round-trip. */+ it('keeps a blank name on a board other than the inbox', () => {+ expect(parseInvkBoardSnapshot({ boards: [inbox([]), member([], ' ')], version: 2 }).boards[1]?.name).toBe(' ');+ });++ it('caps the items of all boards together, not each board alone', () => {+ const items = (count: number, prefix: string) =>+ Array.from({ length: count }, (_, index) => item({ name: `${prefix}${String(index)}.png` }));++ expect(+ parseInvkBoardSnapshot({ boards: [inbox(items(10_000, 'a')), member(items(10_000, 'b'))], version: 2 }).boards+ ).toHaveLength(2);+ expectRefusal({ boards: [inbox(items(10_001, 'a')), member(items(10_000, 'b'))], version: 2 });});/** A name with a separator would either escape `images/` or fail to round-trip through the ZIP. */it.each(['dir/a.png', 'dir\\a.png', '..', '.', '', 'a\0b.png'])('refuses the unsafe name %o', (name) => {- expectRefusal({ items: [item({ name })], version: 1 });+ expectRefusal({ boards: [inbox([item({ name })])], version: 2 });});it('refuses a category the gallery does not show', () => {// `other` is the canvas's private category — it is never board membership.- expectRefusal({ items: [item({ category: 'other' as never })], version: 1 });+ expectRefusal({ boards: [inbox([item({ category: 'other' as never })])], version: 2 });});- it('refuses an unknown kind, a wrong version, and an unknown key', () => {- expectRefusal({ items: [item({ kind: 'audio' as never })], version: 1 });+ it('refuses an unknown kind, a malformed known version, and an unknown key', () => {+ expectRefusal({ boards: [inbox([item({ kind: 'audio' as never })])], version: 2 });expectRefusal({ items: [], version: 2 });- expectRefusal({ extra: true, items: [], version: 1 });+ expectRefusal({ boards: [inbox([])], extra: true, version: 2 });+ expectRefusal({ boards: [{ ...inbox([]), extra: true }], version: 2 });+ });++ it('tells a newer version apart from a damaged file', () => {+ expectRefusal({ boards: [inbox([])], version: 3 }, 'unsupported-version');+ expectRefusal({ version: 'two' });});it('refuses a descriptor missing its starred flag', () => {- expectRefusal({ items: [{ category: 'general', kind: 'image', name: 'a.png' }], version: 1 });+ expectRefusal({+ boards: [+ { archived: false, isInbox: true, items: [{ category: 'general', kind: 'image', name: 'a.png' }], name: 'P' },+ ],+ version: 2,+ });});});describe('buildInvkBoardSnapshot', () => {- it('sorts and stamps the file version, without touching the input', () => {+ it('sorts items, leads with the inbox and stamps the file version, without touching the input', () => {const items = [item({ name: 'b.png' }), item({ name: 'a.png' })];- const snapshot = buildInvkBoardSnapshot(items);+ const snapshot = buildInvkBoardSnapshot([member([item({ name: 'm.png' })]), inbox(items)]);expect(snapshot).toEqual({- items: [item({ name: 'a.png' }), item({ name: 'b.png' })],- version: 1,+ boards: [inbox([item({ name: 'a.png' }), item({ name: 'b.png' })]), member([item({ name: 'm.png' })])],+ version: 2,});expect(items[0]!.name).toBe('b.png');});it('round-trips through the parser', () => {- const snapshot = buildInvkBoardSnapshot([item({ kind: 'video', name: 'v.mp4', starred: true }), item()]);+ const snapshot = buildInvkBoardSnapshot([+ inbox([item({ kind: 'video', name: 'v.mp4', starred: true }), item()]),+ member([item({ name: 'm.png' })], 'Old', true),+ ]);expect(parseInvkBoardSnapshot(JSON.parse(JSON.stringify(snapshot)))).toEqual(snapshot);});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/board.tsindex b7945995e1..bf95d085b4 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/board.ts@@ -6,6 +6,9 @@ import { InvkFormatError } from './format';/*** The independently versioned board entry includes unreferenced media. Validate it strictly before uploading* anything.+ *+ * Version 2 carries every board of the project: the inbox first, then the boards made inside it. Version 1 carried+ * the inbox alone, as a flat item list; it is still read, as a project with no other boards.*/export type InvkMediaKind = 'image' | 'video';@@ -18,11 +21,25 @@ export interface InvkBoardItem {starred: boolean;}-export interface InvkBoardSnapshot {- version: 1;+export interface InvkBoard {+ /** Whether the board is archived; restored as such, since an archived board is still the user's. */+ archived: boolean;+ /** The project's inbox, which the destination mints or claims rather than creates by name. */+ isInbox: boolean;items: InvkBoardItem[];+ /** The board's name. For the inbox it is informational: the inbox takes the project's name. */+ name: string;}+export interface InvkBoardSnapshot {+ version: 2;+ /** The inbox first, then the project's other boards in the order the source listed them. */+ boards: InvkBoard[];+}++/** The longest board name the backend accepts. */+const MAX_BOARD_NAME_LENGTH = 300;+/** Names must be basenames without separators, traversal, or NUL to round-trip safely as archive paths. */const zMediaName = z.string()@@ -39,7 +56,7 @@ const zBoardItem = z.object({starred: z.boolean(),});-const zBoardSnapshot = z+const zBoardSnapshotV1 = z.object({// Board item count cannot exceed the archive entry capacity.items: z.array(zBoardItem).max(INVK_MAX_ENTRIES),@@ -48,35 +65,91 @@ const zBoardSnapshot = z// Reject unknown fields rather than silently discard future semantics..strict();+const zBoard = z+ .object({+ archived: z.boolean(),+ isInbox: z.boolean(),+ items: z.array(zBoardItem).max(INVK_MAX_ENTRIES),+ name: z.string().max(MAX_BOARD_NAME_LENGTH),+ })+ .strict();++const zBoardSnapshotV2 = z+ .object({+ boards: z.array(zBoard).min(1),+ version: z.literal(2),+ })+ .strict();++const zBoardSnapshot = z.union([zBoardSnapshotV1, zBoardSnapshotV2]);+const KNOWN_VERSIONS: ReadonlySet<number> = new Set([1, 2]);+/** Sort by kind then name. Images and videos are separate namespaces, so one name can be both. */const compareItems = (left: InvkBoardItem, right: InvkBoardItem): number =>left.kind.localeCompare(right.kind) || left.name.localeCompare(right.name);+/** Every item of every board, in board order. An item is on one board, so this is a set. */+export const flattenInvkBoardItems = (snapshot: InvkBoardSnapshot): InvkBoardItem[] =>+ snapshot.boards.flatMap((board) => board.items);+/** Accept arbitrary input order; emit deterministic order. */export const parseInvkBoardSnapshot = (data: unknown): InvkBoardSnapshot => {const parsed = zBoardSnapshot.safeParse(data);if (!parsed.success) {+ const version = (data as { version?: unknown } | null)?.version;++ // A board.json this reader does not know is a newer app's, not a broken file; a known version that fails is.+ if (typeof version === 'number' && !KNOWN_VERSIONS.has(version)) {+ throw new InvkFormatError('unsupported-version', `board.json version ${String(version)} is newer than this app`);+ }+throw new InvkFormatError('damaged', `Invalid ${'board.json'}: ${parsed.error.issues[0]?.message ?? 'malformed'}`);}+ const boards: InvkBoard[] =+ parsed.data.version === 1+ ? [{ archived: false, isInbox: true, items: parsed.data.items, name: '' }]+ : parsed.data.boards;++ if (boards.filter((board) => board.isInbox).length !== 1) {+ throw new InvkFormatError('damaged', 'board.json must name exactly one inbox');+ }++ if (boards.reduce((count, board) => count + board.items.length, 0) > INVK_MAX_ENTRIES) {+ throw new InvkFormatError('damaged', 'board.json names more items than an archive can hold');+ }+const seen = new Set<string>();- for (const item of parsed.data.items) {- const key = `${item.kind}:${item.name}`;+ for (const board of boards) {+ for (const item of board.items) {+ const key = `${item.kind}:${item.name}`;- if (seen.has(key)) {- throw new InvkFormatError('damaged', `Duplicate board entry ${key}`);- }+ if (seen.has(key)) {+ throw new InvkFormatError('damaged', `Duplicate board entry ${key}`);+ }- seen.add(key);+ seen.add(key);+ }}- return { items: [...parsed.data.items].sort(compareItems), version: 1 };+ return {+ boards: [...boards.filter((board) => board.isInbox), ...boards.filter((board) => !board.isInbox)].map((board) => ({+ ...board,+ items: [...board.items].sort(compareItems),+ })),+ version: 2,+ };};/** Build the entry from a server snapshot. Sorting here is what makes exports byte-comparable. */-export const buildInvkBoardSnapshot = (items: readonly InvkBoardItem[]): InvkBoardSnapshot => ({- items: [...items].sort(compareItems),- version: 1,+export const buildInvkBoardSnapshot = (boards: readonly InvkBoard[]): InvkBoardSnapshot => ({+ boards: [...boards.filter((board) => board.isInbox), ...boards.filter((board) => !board.isInbox)].map((board) => ({+ archived: board.archived,+ isInbox: board.isInbox,+ items: [...board.items].sort(compareItems),+ name: board.name,+ })),+ version: 2,});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.tsindex a2bc87f2e7..034bd50ab4 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts@@ -33,6 +33,7 @@ const transport = vi.hoisted(() => ({findExistingImageNames: vi.fn((names: readonly string[]) => Promise.resolve(new Set(names))),findExistingVideoNames: vi.fn((names: readonly string[]) => Promise.resolve(new Set(names))),mimeForEntryName: () => 'image/png',+ placeBoardInProject: vi.fn(() => Promise.resolve()),starImages: vi.fn(() => Promise.resolve({ failed: [] as string[] })),starVideos: vi.fn(() => Promise.resolve({ failed: [] as string[] })),uploadArchiveImage: vi.fn(() => Promise.reject(new Error('duplication uploads nothing'))),@@ -145,10 +146,15 @@ beforeEach(async () => {duplicateProject = await import('./duplicateProject');});+/** The source's boards as the snapshot lists them: the inbox alone unless a test adds members. */+const inboxOf = (items: ReturnType<typeof boardItem>[]) => [+ { archived: false, board_id: 'source-board', is_inbox: true, items, name: 'Source' },+];+describe('duplicateProjectRecord', () => {it('copies every board item onto a staging board the create then claims', async () => {const result = await duplicateProject.duplicateProjectRecord({- boardItems: [boardItem(), boardItem({ category: 'user', name: 'unreferenced.png' })],+ boards: inboxOf([boardItem(), boardItem({ category: 'user', name: 'unreferenced.png' })]),owner,record: sourceRecord(),});@@ -170,7 +176,7 @@ describe('duplicateProjectRecord', () => {it('uses a caller-reserved identity for retry-safe conflict copies', async () => {await duplicateProject.duplicateProjectRecord({- boardItems: [],+ boards: inboxOf([]),identity: { id: 'reserved-copy', name: 'Source (copy)' },owner,record: sourceRecord(),@@ -185,7 +191,7 @@ describe('duplicateProjectRecord', () => {/** The whole reason duplication needs its own copies rather than a second reference. */it('points the copy at its own media, never the original name', async () => {await duplicateProject.duplicateProjectRecord({- boardItems: [boardItem()],+ boards: inboxOf([boardItem()]),owner,record: sourceRecord(),});@@ -195,7 +201,7 @@ describe('duplicateProjectRecord', () => {it('stars the copies whose descriptor was starred', async () => {await duplicateProject.duplicateProjectRecord({- boardItems: [boardItem({ name: 'plain.png' }), boardItem({ name: 'starred.png', starred: true })],+ boards: inboxOf([boardItem({ name: 'plain.png' }), boardItem({ name: 'starred.png', starred: true })]),owner,record: sourceRecord(),});@@ -205,7 +211,7 @@ describe('duplicateProjectRecord', () => {it('copies videos through the video endpoint with their category', async () => {await duplicateProject.duplicateProjectRecord({- boardItems: [boardItem({ category: 'user', kind: 'video', name: 'clip.mp4' })],+ boards: inboxOf([boardItem({ category: 'user', kind: 'video', name: 'clip.mp4' })]),owner,record: sourceRecord(),});@@ -218,7 +224,7 @@ describe('duplicateProjectRecord', () => {it('reuses a document reference the board does not own, copying nothing', async () => {const record = sourceRecord({ futureImageInput: { image_name: 'external.png' } });- await duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record });+ await duplicateProject.duplicateProjectRecord({ boards: inboxOf([boardItem()]), owner, record });expect(transport.copyImagesToBoard).toHaveBeenCalledWith(['shared.png'], 'staging-board', owner.signal);expect((createdData().futureImageInput as { image_name: string }).image_name).toBe('external.png');@@ -229,7 +235,7 @@ describe('duplicateProjectRecord', () => {transport.copyImagesToBoard.mockResolvedValue({ copied: [], failed: ['shared.png'] });const result = await duplicateProject.duplicateProjectRecord({- boardItems: [boardItem()],+ boards: inboxOf([boardItem()]),owner,record: sourceRecord(),});@@ -245,7 +251,7 @@ describe('duplicateProjectRecord', () => {widgetStates: { gallery: { values: { projectBoardId: 'source-board', selectedBoardId: 'source-board' } } },});- const result = await duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record });+ const result = await duplicateProject.duplicateProjectRecord({ boards: inboxOf([boardItem()]), owner, record });const gallery = (createdData().widgetStates as { gallery: { values: Record<string, unknown> } }).gallery.values;// The document that goes to the server carries neither the original's board nor its selection.@@ -272,7 +278,7 @@ describe('duplicateProjectRecord', () => {},});- await duplicateProject.duplicateProjectRecord({ boardItems: [], owner, record });+ await duplicateProject.duplicateProjectRecord({ boards: inboxOf([]), owner, record });const workflows = createdData().workflows as { entries: { source?: unknown }[] };@@ -280,11 +286,82 @@ describe('duplicateProjectRecord', () => {expect(createdData().documentSchemaVersion).toBe(3);});- it('creates no staging board for a project whose board is empty', async () => {- await duplicateProject.duplicateProjectRecord({ boardItems: [], owner, record: sourceRecord() });+ it('stages, copies and places every other board of the source, empty ones included', async () => {+ transport.createStagingBoard+ .mockResolvedValueOnce('staging-board')+ .mockResolvedValueOnce('member-staging')+ .mockResolvedValueOnce('empty-staging');++ const result = await duplicateProject.duplicateProjectRecord({+ boards: [+ ...inboxOf([boardItem()]),+ { archived: true, board_id: 'old', is_inbox: false, items: [boardItem({ name: 'old.png' })], name: 'Old' },+ { archived: false, board_id: 'empty', is_inbox: false, items: [], name: 'Empty' },+ ],+ owner,+ record: sourceRecord(),+ });++ // In source order, so the copy's boards keep their creation order; the empty one has nothing to copy.+ expect((transport.createStagingBoard.mock.calls as unknown[][]).map((call) => call[0])).toEqual([+ 'Source copy',+ 'Old',+ 'Empty',+ ]);+ expect(transport.copyImagesToBoard).toHaveBeenCalledWith(['old.png'], 'member-staging', owner.signal);+ expect(transport.copyImagesToBoard).toHaveBeenCalledTimes(2);+ expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-board' });+ // Only once the copy exists: the staged members move in, archived as they were.+ expect(transport.placeBoardInProject.mock.calls).toEqual([+ ['member-staging', result.record.project_id, true, owner.signal],+ ['empty-staging', result.record.project_id, false, owner.signal],+ ]);+ expect(result.boardIssues).toEqual([]);+ });++ it('reports a board that could not be placed and keeps the copy', async () => {+ transport.placeBoardInProject.mockRejectedValueOnce(new Error('move refused'));+ transport.createStagingBoard.mockResolvedValueOnce('staging-board').mockResolvedValueOnce('member-staging');++ const result = await duplicateProject.duplicateProjectRecord({+ boards: [+ ...inboxOf([]),+ { archived: false, board_id: 'old', is_inbox: false, items: [boardItem({ name: 'old.png' })], name: 'Old' },+ ],+ owner,+ record: sourceRecord(),+ });++ expect(result.record.project_id).not.toBe('source');+ expect(result.boardIssues).toEqual([{ name: 'Old' }]);+ expect(transport.deleteStagingBoard).not.toHaveBeenCalled();+ });++ it('stages and claims the inbox even when it is empty, copying nothing', async () => {+ await duplicateProject.duplicateProjectRecord({ boards: inboxOf([]), owner, record: sourceRecord() });++ expect(transport.createStagingBoard).toHaveBeenCalledTimes(1);+ expect(transport.copyImagesToBoard).not.toHaveBeenCalled();+ expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-board' });+ });++ it('deletes the boards it had staged when staging a later one fails', async () => {+ transport.createStagingBoard.mockResolvedValueOnce('staging-board').mockRejectedValueOnce(new Error('refused'));++ await expect(+ duplicateProject.duplicateProjectRecord({+ boards: [+ ...inboxOf([boardItem()]),+ { archived: false, board_id: 'old', is_inbox: false, items: [boardItem({ name: 'old.png' })], name: 'Old' },+ ],+ owner,+ record: sourceRecord(),+ })+ ).rejects.toThrow('refused');- expect(transport.createStagingBoard).not.toHaveBeenCalled();- expect(api.createProjectSettled.mock.calls[0]![0]).not.toHaveProperty('board_id');+ expect(transport.copyImagesToBoard).not.toHaveBeenCalled();+ expect(transport.deleteStagingBoard).toHaveBeenCalledExactlyOnceWith('staging-board', owner.signal);+ expect(api.createProjectSettled).not.toHaveBeenCalled();});it('deletes the copies it made and the staging board when the create provably did not happen', async () => {@@ -294,7 +371,7 @@ describe('duplicateProjectRecord', () => {await expect(duplicateProject.duplicateProjectRecord({- boardItems: [boardItem(), boardItem({ kind: 'video', name: 'clip.mp4' })],+ boards: inboxOf([boardItem(), boardItem({ kind: 'video', name: 'clip.mp4' })]),owner,record: sourceRecord(),})@@ -312,7 +389,7 @@ describe('duplicateProjectRecord', () => {api.createProjectSettled.mockRejectedValue(failure);await expect(- duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record: sourceRecord() })+ duplicateProject.duplicateProjectRecord({ boards: inboxOf([boardItem()]), owner, record: sourceRecord() })).rejects.toBe(failure);expect(transport.deleteArchiveImages).not.toHaveBeenCalled();@@ -329,7 +406,7 @@ describe('duplicateProjectRecord', () => {});await expect(- duplicateProject.duplicateProjectRecord({ boardItems: [boardItem()], owner, record: sourceRecord() })+ duplicateProject.duplicateProjectRecord({ boards: inboxOf([boardItem()]), owner, record: sourceRecord() })).rejects.toThrow();expect(transport.deleteArchiveImages).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.tsindex 7fb8c551d6..dd32cf1561 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts@@ -1,6 +1,6 @@-import type { ProjectBoardItemDTO, ProjectRecordDTO } from '@workbench/projects/api';+import type { ProjectBoardSnapshotBoardDTO, ProjectRecordDTO } from '@workbench/projects/api';-import { type AccountScope, assertAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { type AccountScope, assertAccountScopeCurrent, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { createProjectSettled } from '@workbench/projects/api';import { createProjectId } from '@workbench/projects/ids';import {@@ -10,18 +10,13 @@ import {stripInstallationState,} from '@workbench/projects/projectAssets';-import type { InvkBoardItem } from './board';+import type { InvkBoard } from './board';import type { MediaMaterializer } from './restoreProjectMedia';import type { ProjectTransferIssues } from './transfer';-import {- type CopyMediaResult,- copyImagesToBoard,- copyVideosToBoard,- createStagingBoard,- isRequestCancellation,-} from './assetTransport';+import { type CopyMediaResult, copyImagesToBoard, copyVideosToBoard, isRequestCancellation } from './assetTransport';import { InvkFormatError, toInvkFormatReason } from './format';+import { createStagingBoards, findInboxStagingBoardId, placeMemberBoards } from './memberBoards';import {createRestoredMediaLedger,restoreProjectMedia,@@ -33,8 +28,8 @@ import { toMediaRefs } from './transfer';/** Copy board media server-side and reuse external reference identities. */export interface DuplicateProjectInput {- /** The board's visible contents, enumerated for the source project. */- boardItems: readonly ProjectBoardItemDTO[];+ /** The source project's boards with their visible contents, inbox first. */+ boards: readonly ProjectBoardSnapshotBoardDTO[];owner: AccountScope;/** The acknowledged source record — for an open project, flushed first. */record: ProjectRecordDTO;@@ -98,7 +93,7 @@ export const createCopyMediaMaterializer = (};};-/** Project creation commits the staging board; precommit rollback deletes only ledger-owned resources. */+/** Project creation commits the staging boards; precommit rollback deletes only ledger-owned resources. */export const duplicateProjectRecord = async (input: DuplicateProjectInput,deps: DuplicateProjectDeps = {}@@ -129,18 +124,29 @@ export const duplicateProjectRecord = async (const { applyAuthoritativeProjectBoard, serializeProjectDocument } =await import('@workbench/projects/projectDocument');const canonicalDocument = serializeProjectDocument(project);- const boardItems = input.boardItems as readonly InvkBoardItem[];- const stagingBoardId = boardItems.length === 0 ? null : await createStagingBoard(name, owner.signal);- const ledger = createRestoredMediaLedger(stagingBoardId);+ const boards: InvkBoard[] = input.boards.map((board) => ({+ archived: board.archived,+ isInbox: board.is_inbox,+ items: board.items,+ name: board.name,+ }));+ // Made before anything is staged: every staging board joins it as it is created, so a copy abandoned at any point+ // can delete them all.+ const ledger = createRestoredMediaLedger([]);let didCreateProject = false;+ let didAttemptProjectCreate = false;try {assertAccountScopeCurrent(owner);+ const stagedBoards = await createStagingBoards(boards, name, ledger, owner.signal);+ const inboxStagingBoardId = findInboxStagingBoardId(stagedBoards);++ assertAccountScopeCurrent(owner);+const restored = await restoreProjectMedia({- boardId: stagingBoardId,- boardItems,+ boards: stagedBoards.map(({ board, stagingBoardId }) => ({ items: board.items, stagingBoardId })),// Same-server duplication needs no bundled bytes and inherits unresolved external references.coverBytes: null,coverSourceImageName: selectCoverImageName(canonicalDocument),@@ -163,6 +169,7 @@ export const duplicateProjectRecord = async ();assertAccountScopeCurrent(owner);+ didAttemptProjectCreate = true;const record = await createProjectSettled({@@ -170,15 +177,19 @@ export const duplicateProjectRecord = async (minimum_canvas_schema_version: input.record.minimum_canvas_schema_version,name,project_id: id,- ...(stagingBoardId === null ? {} : { board_id: stagingBoardId }),+ ...(inboxStagingBoardId === null ? {} : { board_id: inboxStagingBoardId }),},owner);didCreateProject = true;assertAccountScopeCurrent(owner);+ // The copy exists; its other boards can now belong to it. Reported, never fatal, from here on.+ const boardIssues = await placeMemberBoards(stagedBoards, record.project_id, { signal: owner.signal });+ assertAccountScopeCurrent(owner);return {+ boardIssues,boardItemIssues: restored.boardItemIssues,coverImageName: restored.coverImageName,documentReferenceIssues: restored.documentReferenceIssues,@@ -188,9 +199,14 @@ export const duplicateProjectRecord = async (},};} catch (error) {- await rollbackUnlessProjectExists(error, didCreateProject, owner, () =>- rollbackRestoredMedia(ledger, { signal: owner.signal })- );+ const rollback = () => rollbackRestoredMedia(ledger, { signal: owner.signal });++ // Before the create was even attempted nothing is ambiguous: whatever was staged or copied is ours to drop.+ if (!didAttemptProjectCreate && isAccountScopeCurrent(owner)) {+ await rollback();+ } else {+ await rollbackUnlessProjectExists(error, didCreateProject, owner, rollback);+ }throw error;}diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.tsindex 1265542204..01f82436ad 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts@@ -37,7 +37,7 @@ const projectDocument = (): Record<string, unknown> => ({const planInput = {appVersion: '7.0',- boardItems: [],+ boards: [{ archived: false, isInbox: true, items: [], name: 'My project' }],createdAt: '2026-08-04T00:00:00.000Z',minimumCanvasSchemaVersion: 3,name: 'My project',@@ -110,6 +110,7 @@ describe('executeInvkExport', () => {});expect(result).toEqual({+ boardIssues: [],boardItemIssues: [],bundledImageCount: 2,bundledVideoCount: 0,@@ -151,6 +152,7 @@ describe('executeInvkExport', () => {});expect(result).toEqual({+ boardIssues: [],boardItemIssues: [],bundledImageCount: 1,bundledVideoCount: 0,@@ -211,6 +213,7 @@ describe('executeInvkExport', () => {});expect(result).toEqual({+ boardIssues: [],boardItemIssues: [],bundledImageCount: 2,bundledVideoCount: 1,@@ -247,6 +250,7 @@ describe('executeInvkExport', () => {});expect(result).toEqual({+ boardIssues: [],boardItemIssues: [],bundledImageCount: 2,bundledVideoCount: 0,@@ -414,13 +418,14 @@ describe('board membership', () => {return JSON.parse(readEntryText(entries.get('board.json')!));};+ const withInbox = (items: ReturnType<typeof boardItem>[]) => ({+ ...planInput,+ boards: [{ archived: false, isInbox: true, items, name: 'My project' }],+ });it('carries board media the document never references', async () => {const download = vi.fn();- const plan = planInvkExport({- ...planInput,- boardItems: [boardItem('unreferenced.png', { category: 'user', starred: true })],- });+ const plan = planInvkExport(withInbox([boardItem('unreferenced.png', { category: 'user', starred: true })]));expect(plan.transferItems.map((item) => item.name)).toEqual(['live-a.png', 'live-b.png', 'unreferenced.png']);@@ -438,15 +443,54 @@ describe('board membership', () => {expect(entries.has('images/unreferenced.png')).toBe(true);// Category and starring travel: they are what the item was, not merely that it existed.expect(await readBoard(blob)).toEqual({- items: [{ category: 'user', kind: 'image', name: 'unreferenced.png', starred: true }],- version: 1,+ boards: [+ {+ archived: false,+ isInbox: true,+ items: [{ category: 'user', kind: 'image', name: 'unreferenced.png', starred: true }],+ name: 'My project',+ },+ ],+ version: 2,});});+ it('carries every board of the project, each with its own media', async () => {+ const download = vi.fn();+ const plan = planInvkExport({+ ...planInput,+ boards: [+ { archived: true, isInbox: false, items: [boardItem('old.png')], name: 'Old façades' },+ { archived: false, isInbox: true, items: [boardItem('inbox.png')], name: 'My project' },+ ],+ });++ // Items of every board are fetched once each; the inbox leads in the plan as in the file.+ expect(plan.transferItems.map((item) => item.name)).toEqual(['inbox.png', 'live-a.png', 'live-b.png', 'old.png']);++ await executeInvkExport(plan, {+ download,+ fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),+ fetchImageThumbnail: () => Promise.resolve(null),+ });++ const [blob] = download.mock.calls[0]! as [Blob];++ expect(+ (await readBoard(blob)).boards.map((board: { name: string; items: { name: string }[] }) => [+ board.name,+ board.items.map((item) => item.name),+ ])+ ).toEqual([+ ['My project', ['inbox.png']],+ ['Old façades', ['old.png']],+ ]);+ });+it('fetches an item that is both board media and a reference exactly once', async () => {const fetchImageBytes = vi.fn((imageName: string) => Promise.resolve(bytesFor(imageName)));- await executeInvkExport(planInvkExport({ ...planInput, boardItems: [boardItem('live-a.png')] }), {+ await executeInvkExport(planInvkExport(withInbox([boardItem('live-a.png')])), {download: vi.fn(),fetchImageBytes,fetchImageThumbnail: () => Promise.resolve(null),@@ -456,7 +500,7 @@ describe('board membership', () => {});it('reports an overlapping failure against both roles', async () => {- const result = await executeInvkExport(planInvkExport({ ...planInput, boardItems: [boardItem('live-a.png')] }), {+ const result = await executeInvkExport(planInvkExport(withInbox([boardItem('live-a.png')])), {download: vi.fn(),fetchImageBytes: (imageName) =>imageName === 'live-a.png' ? Promise.resolve(null) : Promise.resolve(bytesFor(imageName)),@@ -471,7 +515,7 @@ describe('board membership', () => {it('keeps the descriptor for an item whose bytes could not be fetched', async () => {const download = vi.fn();- await executeInvkExport(planInvkExport({ ...planInput, boardItems: [boardItem('gone.png')] }), {+ await executeInvkExport(planInvkExport(withInbox([boardItem('gone.png')])), {download,fetchImageBytes: (imageName) =>imageName === 'gone.png' ? Promise.resolve(null) : Promise.resolve(bytesFor(imageName)),@@ -481,7 +525,7 @@ describe('board membership', () => {const [blob] = download.mock.calls[0]! as [Blob];const board = await readBoard(blob);- expect(board.items.map((item: { name: string }) => item.name)).toEqual(['gone.png']);+ expect(board.boards[0].items.map((item: { name: string }) => item.name)).toEqual(['gone.png']);});it('records an empty board rather than omitting the entry', async () => {@@ -495,13 +539,16 @@ describe('board membership', () => {const [blob] = download.mock.calls[0]! as [Blob];- expect(await readBoard(blob)).toEqual({ items: [], version: 1 });+ expect(await readBoard(blob)).toEqual({+ boards: [{ archived: false, isInbox: true, items: [], name: 'My project' }],+ version: 2,+ });});/** Refused before a single round trip: discovering it after hundreds would be the wrong order. */it('refuses a project that could never be packed, before fetching anything', () => {const boardItems = Array.from({ length: 20_001 }, (_unused, index) => boardItem(`image-${index}.png`));- expect(() => planInvkExport({ ...planInput, boardItems })).toThrowError(/archive entries/u);+ expect(() => planInvkExport(withInbox(boardItems))).toThrowError(/archive entries/u);});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.tsindex 27e29b80fb..4043f35c8a 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.ts@@ -4,7 +4,7 @@ import { collectLiveAssetRefs, selectCoverImageName, stripInstallationState } frimport type { InvkArchiveEntry } from './archive';import type { FetchedThumbnail } from './assetTransport';-import type { InvkBoardItem, InvkBoardSnapshot } from './board';+import type { InvkBoard, InvkBoardSnapshot } from './board';import type { InvkTransferItem, ProjectTransferIssues } from './transfer';import { binaryEntry, INVK_MAX_ENTRIES, textEntry, writeArchive } from './archive';@@ -14,7 +14,7 @@ import {INVK_TRANSFER_CONCURRENCY,isRequestCancellation,} from './assetTransport';-import { buildInvkBoardSnapshot } from './board';+import { buildInvkBoardSnapshot, flattenInvkBoardItems } from './board';import {collectFontDependencies,INVK_MAX_FONT_BYTES,@@ -35,7 +35,7 @@ import { createTransferIssueLog, planMediaTransfer, toMediaRefs } from './transf/** Skip unavailable assets, but abort on cancellation before packing. */export interface InvkExportPlan {- /** The board's contents exactly as they will be written to `board.json`. */+ /** The project's boards exactly as they will be written to `board.json`. */boardSnapshot: InvkBoardSnapshot;/** Cover image name, or `null` for a project that has produced nothing. */coverImageName: string | null;@@ -61,7 +61,8 @@ const FIXED_ENTRY_COUNT = 3;export const planInvkExport = (input: {appVersion: string;- boardItems: readonly InvkBoardItem[];+ /** The project's boards as the server enumerated them, the inbox among them. */+ boards: readonly InvkBoard[];createdAt: string;minimumCanvasSchemaVersion: number;name: string;@@ -72,8 +73,11 @@ export const planInvkExport = (input: {// Strip installation state during planning; excluding its bytes alone leaves dangling references.const projectDocument = stripInstallationState(input.projectDocument);- const boardSnapshot = buildInvkBoardSnapshot(input.boardItems);- const transferItems = planMediaTransfer(boardSnapshot.items, toMediaRefs(collectLiveAssetRefs(projectDocument)));+ const boardSnapshot = buildInvkBoardSnapshot(input.boards);+ const transferItems = planMediaTransfer(+ flattenInvkBoardItems(boardSnapshot),+ toMediaRefs(collectLiveAssetRefs(projectDocument))+ );const fonts = collectFontDependencies(projectDocument);// Check the archive budget before downloading assets.diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.test.tsindex e554d17a1d..1922315754 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/fonts.test.ts@@ -41,7 +41,7 @@ const documentWith = (const planFor = async (includeFonts: boolean) =>planInvkExport({appVersion: '7',- boardItems: [],+ boards: [{ archived: false, isInbox: true, items: [], name: 'Fonts' }],createdAt: '2026-09-07',includeFonts,minimumCanvasSchemaVersion: 4,diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.tsindex f660fd092a..f2dbc29fe2 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts@@ -3,9 +3,18 @@ import { describe, expect, it, vi } from 'vitest';import type { InvkBoardItem } from './board';import { binaryEntry, INVK_MAX_ARCHIVE_BYTES, textEntry, writeArchive } from './archive';-import { createArchiveMediaMaterializer, readInvkArchive, restoreArchiveMedia } from './importProject';+import {+ createArchiveMediaMaterializer,+ type InvkArchiveContents,+ readInvkArchive,+ restoreArchiveMedia,+} from './importProject';import { createRestoredMediaLedger } from './restoreProjectMedia';+/** The archive's boards, every one staged on the same board: these archives carry only an inbox. */+const stagedOn = (archive: InvkArchiveContents, stagingBoardId: string) =>+ (archive.boardSnapshot?.boards ?? []).map((board) => ({ board, stagingBoardId }));+const imageRef = (imageName: string) => ({ height: 64, imageName, width: 64 });const document = () => ({@@ -32,7 +41,10 @@ const boardItem = (overrides: Partial<InvkBoardItem> = {}): InvkBoardItem => ({...overrides,});-const boardEntry = (items: InvkBoardItem[] = [boardItem()]) => JSON.stringify({ items, version: 1 });+const inboxBoard = (items: InvkBoardItem[]) => ({ archived: false, isInbox: true, items, name: 'My project' });++const boardEntry = (items: InvkBoardItem[] = [boardItem()]) =>+ JSON.stringify({ boards: [inboxBoard(items)], version: 2 });const archiveFile = async (entries: Record<string, string | Uint8Array>): Promise<File> => {const blob = await writeArchive(@@ -98,20 +110,19 @@ describe('readInvkArchive', () => {);// Sorted by kind then name, whatever order the writer used.- expect(contents.boardSnapshot?.items.map((item) => item.name)).toEqual(['z.png', 'a.mp4']);+ expect(contents.boardSnapshot?.boards[0]?.items.map((item) => item.name)).toEqual(['z.png', 'a.mp4']);});it('reads an empty board without inventing anything', async () => {const contents = await readInvkArchive(await boardArchive({ 'board.json': boardEntry([]) }));- expect(contents.boardSnapshot).toEqual({ items: [], version: 1 });+ expect(contents.boardSnapshot).toEqual({ boards: [inboxBoard([])], version: 2 });});it.each([['unparseable', 'not json'],- ['a duplicate descriptor', JSON.stringify({ items: [boardItem(), boardItem()], version: 1 })],- ['an unsafe name', JSON.stringify({ items: [boardItem({ name: '../escape.png' })], version: 1 })],- ['an unknown version', JSON.stringify({ items: [], version: 2 })],+ ['a duplicate descriptor', JSON.stringify({ boards: [inboxBoard([boardItem(), boardItem()])], version: 2 })],+ ['an unsafe name', JSON.stringify({ boards: [inboxBoard([boardItem({ name: '../escape.png' })])], version: 2 })],])('reports a board enumeration that is %s as damaged', async (_case, contents) => {await expect(readInvkArchive(await boardArchive({ 'board.json': contents }))).rejects.toMatchObject({reason: 'damaged',@@ -263,12 +274,17 @@ describe('restoreArchiveMedia', () => {/** Transfer media shared by board and document once, remapping the document to the copy. */it('restores an overlapping item once and points the document at the copy', async () => {const archive = await readInvkArchive(await boardArchive());- const ledger = createRestoredMediaLedger('staging');+ const ledger = createRestoredMediaLedger([]);const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'never', width: 1 }));const result = await restoreArchiveMedia(archive,- { boardId: 'staging', ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },+ {+ ledger,+ projectDocument: archive.projectDocument,+ projectId: 'project-new',+ stagedBoards: stagedOn(archive, 'staging'),+ },restoreDeps({ uploadImage }));@@ -285,12 +301,17 @@ describe('restoreArchiveMedia', () => {'images/unreferenced.png': new Uint8Array([5]),}));- const ledger = createRestoredMediaLedger('staging');+ const ledger = createRestoredMediaLedger([]);const starImages = vi.fn(() => Promise.resolve({ failed: [] }));const result = await restoreArchiveMedia(archive,- { boardId: 'staging', ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },+ {+ ledger,+ projectDocument: archive.projectDocument,+ projectId: 'project-new',+ stagedBoards: stagedOn(archive, 'staging'),+ },restoreDeps({ starImages }));@@ -303,11 +324,11 @@ describe('restoreArchiveMedia', () => {it('restores an archive with no board as document references only', async () => {const archive = await readInvkArchive(await validArchive());- const ledger = createRestoredMediaLedger(null);+ const ledger = createRestoredMediaLedger([]);const result = await restoreArchiveMedia(archive,- { boardId: null, ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },+ { ledger, projectDocument: archive.projectDocument, projectId: 'project-new', stagedBoards: [] },restoreDeps());@@ -317,12 +338,12 @@ describe('restoreArchiveMedia', () => {it('deduplicates a document reference the destination already has', async () => {const archive = await readInvkArchive(await validArchive());- const ledger = createRestoredMediaLedger(null);+ const ledger = createRestoredMediaLedger([]);const uploadImage = vi.fn(() => Promise.resolve({ height: 1, imageName: 'never', width: 1 }));const result = await restoreArchiveMedia(archive,- { boardId: null, ledger, projectDocument: archive.projectDocument, projectId: 'project-new' },+ { ledger, projectDocument: archive.projectDocument, projectId: 'project-new', stagedBoards: [] },restoreDeps({ findExistingImageNames: () => Promise.resolve(new Set(['a.png'])), uploadImage }));@@ -342,10 +363,10 @@ describe('restoreArchiveMedia', () => {await restoreArchiveMedia(archive,{- boardId: 'staging',- ledger: createRestoredMediaLedger('staging'),+ ledger: createRestoredMediaLedger([]),projectDocument: archive.projectDocument,projectId: 'project-new',+ stagedBoards: stagedOn(archive, 'staging'),},restoreDeps({ uploadBoardVideo }));diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.tsindex 43948220b3..6b6ea19a55 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.ts@@ -2,6 +2,7 @@ import { mapWithConcurrency } from '@platform/core/concurrency';import { collectLiveAssetRefs, selectCoverImageName } from '@workbench/projects/projectAssets';import type { InvkBoardSnapshot } from './board';+import type { StagedBoard } from './memberBoards';import type {MediaMaterializer,RestoredMediaLedger,@@ -36,8 +37,8 @@ import { toMediaRefs } from './transfer';export interface InvkArchiveContents {/**- * What the project's board held, or `null` for an archive that names no board. `null` and- * `{items: []}` are different answers: only the first may have a board invented for it.+ * What the project's boards held, or `null` for an archive that names no board — which is not an empty inbox:+ * nothing is staged for it, and the server makes the project's inbox itself.*/boardSnapshot: InvkBoardSnapshot | null;/** Bundled preview bytes and the entry they came from, when the archive has one. */@@ -217,8 +218,8 @@ export const createArchiveMediaMaterializer = (};export interface RestoreArchiveMediaInput {- /** The staging board for this archive's board media, or `null` when it carries none. */- boardId: string | null;+ /** The archive's boards with the Library boards staged for them. */+ stagedBoards: readonly StagedBoard[];/** The canonical document, already rehydrated and re-serialized. */projectDocument: Record<string, unknown>;/** The id the project will be created under. */@@ -245,8 +246,7 @@ export const restoreArchiveMedia = (return restoreProjectMedia({- boardId: input.boardId,- boardItems: archive.boardSnapshot?.items ?? [],+ boards: input.stagedBoards.map(({ board, stagingBoardId }) => ({ items: board.items, stagingBoardId })),coverBytes: archive.cover,coverSourceImageName: selectCoverImageName(input.projectDocument),documentRefs: toMediaRefs(collectLiveAssetRefs(input.projectDocument)),diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.test.tsnew file mode 100644index 0000000000..defe2fc1cf--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest';++import type { InvkBoard } from './board';++import { createStagingBoards, findInboxStagingBoardId, placeMemberBoards } from './memberBoards';+import { createRestoredMediaLedger } from './restoreProjectMedia';++const item = { category: 'general' as const, kind: 'image' as const, name: 'a.png', starred: false };+const inbox: InvkBoard = { archived: false, isInbox: true, items: [item], name: 'Stored name' };+const old: InvkBoard = { archived: true, isInbox: false, items: [{ ...item, name: 'old.png' }], name: 'Old' };+const empty: InvkBoard = { archived: false, isInbox: false, items: [], name: 'Empty' };++describe('createStagingBoards', () => {+ it('stages every board in order, naming the inbox after the project, and finds the inbox among them', async () => {+ const ledger = createRestoredMediaLedger([]);+ const create = vi.fn((name: string) => Promise.resolve(`staged:${name}`));++ const staged = await createStagingBoards([inbox, old, empty], 'Project', ledger, undefined, create);++ expect(staged.map(({ stagingBoardId }) => stagingBoardId)).toEqual([+ 'staged:Project',+ 'staged:Old',+ 'staged:Empty',+ ]);+ expect(staged.map(({ board }) => board)).toEqual([inbox, old, empty]);+ expect(findInboxStagingBoardId(staged)).toBe('staged:Project');+ expect(findInboxStagingBoardId([])).toBeNull();+ });++ it('puts each staging board on the ledger as it is made, so a failed later create leaves none unowned', async () => {+ const ledger = createRestoredMediaLedger([]);+ const create = vi+ .fn<(name: string) => Promise<string>>()+ .mockResolvedValueOnce('staged-inbox')+ .mockRejectedValueOnce(new Error('refused'));++ await expect(createStagingBoards([inbox, old], 'Project', ledger, undefined, create)).rejects.toThrow('refused');+ expect(ledger.boardIds).toEqual(['staged-inbox']);+ });+});++describe('placeMemberBoards', () => {+ const staged = [+ { board: inbox, stagingBoardId: 'staged-inbox' },+ { board: old, stagingBoardId: 'staged-old' },+ { board: empty, stagingBoardId: 'staged-empty' },+ ];+ const deps = () => ({ placeBoardInProject: vi.fn(() => Promise.resolve()) });++ it('moves every board but the inbox into the project as it was', async () => {+ const d = deps();++ await expect(placeMemberBoards(staged, 'p1', d)).resolves.toEqual([]);+ expect(d.placeBoardInProject.mock.calls).toEqual([+ ['staged-old', 'p1', true, undefined],+ ['staged-empty', 'p1', false, undefined],+ ]);+ });++ it('reports each board that could not move and carries on with the rest', async () => {+ const d = deps();+ d.placeBoardInProject.mockRejectedValueOnce(new Error('refused'));++ await expect(placeMemberBoards(staged, 'p1', d)).resolves.toEqual([{ name: 'Old' }]);+ expect(d.placeBoardInProject).toHaveBeenCalledTimes(2);+ });++ it('ends the placement when the operation was cancelled', async () => {+ const d = deps();+ d.placeBoardInProject.mockRejectedValueOnce(new DOMException('gone', 'AbortError'));++ await expect(placeMemberBoards(staged, 'p1', d)).rejects.toThrow('gone');+ expect(d.placeBoardInProject).toHaveBeenCalledTimes(1);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.tsnew file mode 100644index 0000000000..c2e519afdf--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/memberBoards.ts@@ -0,0 +1,82 @@+import type { InvkBoard } from './board';+import type { RestoredMediaLedger } from './restoreProjectMedia';+import type { InvkBoardIssue } from './transfer';++import { createStagingBoard, isRequestCancellation, placeBoardInProject } from './assetTransport';++/**+ * A project's boards travel as a set, but only the inbox rides the project create: the server claims it in the same+ * transaction that writes the document. So every board is staged alike — a private Library board, made in source+ * order so creation order survives — media lands on it before the commit point, and the others are moved into the+ * project once it exists.+ */++export interface StagedBoard {+ board: InvkBoard;+ /** The Library board standing in for `board` until the project exists. */+ stagingBoardId: string;+}++export interface MemberBoardPlacementDeps {+ placeBoardInProject?: typeof placeBoardInProject;+ signal?: AbortSignal;+}++/**+ * One staging board per board, in `boards` order, each on the ledger the moment it exists so a restore abandoned+ * part-way can delete it. The inbox's is named after the project, the others after themselves.+ */+export const createStagingBoards = async (+ boards: readonly InvkBoard[],+ projectName: string,+ ledger: RestoredMediaLedger,+ signal?: AbortSignal,+ create: typeof createStagingBoard = createStagingBoard+): Promise<StagedBoard[]> => {+ const staged: StagedBoard[] = [];++ for (const board of boards) {+ const stagingBoardId = await create(board.isInbox ? projectName : board.name, signal);++ ledger.boardIds.push(stagingBoardId);+ staged.push({ board, stagingBoardId });+ }++ return staged;+};++/** The staging board the project create claims as its inbox; `null` when nothing was staged. */+export const findInboxStagingBoardId = (staged: readonly StagedBoard[]): string | null =>+ staged.find(({ board }) => board.isInbox)?.stagingBoardId ?? null;++/**+ * Move every board but the inbox into the created project, archived as the source had it. Each settles on its own,+ * because a project with most of its boards beats none: a board that could not move is reported, and stays in the+ * Library with everything on it. Cancellation and account expiry still abort.+ */+export const placeMemberBoards = async (+ staged: readonly StagedBoard[],+ projectId: string,+ deps: MemberBoardPlacementDeps = {}+): Promise<InvkBoardIssue[]> => {+ const place = deps.placeBoardInProject ?? placeBoardInProject;+ const issues: InvkBoardIssue[] = [];++ for (const { board, stagingBoardId } of staged) {+ if (board.isInbox) {+ continue;+ }++ try {+ await place(stagingBoardId, projectId, board.archived, deps.signal);+ } catch (error) {+ if (isRequestCancellation(error)) {+ throw error;+ }++ issues.push({ name: board.name });+ }+ }++ return issues;+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.tsindex 0c62f3d875..eb5c7206ca 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts@@ -43,19 +43,20 @@ const freshNameMaterializer =const restore = (input: {boardItems?: readonly InvkBoardItem[];+ /** Several boards at once; `boardItems` describes the one-board case. */+ boards?: readonly { items: readonly InvkBoardItem[]; stagingBoardId: string }[];coverBytes?: { bytes: Uint8Array; entryName: string } | null;coverSourceImageName?: string | null;documentRefs?: readonly InvkMediaRef[];- boardId?: string | null;},deps: Partial<RestoreProjectMediaDeps> = {}) => {- const ledger = createRestoredMediaLedger(input.boardId === undefined ? BOARD_ID : input.boardId);+ const boards = input.boards ?? [{ items: input.boardItems ?? [], stagingBoardId: BOARD_ID }];+ const ledger = createRestoredMediaLedger(boards.map((board) => board.stagingBoardId));return restoreProjectMedia({- boardId: input.boardId === undefined ? BOARD_ID : input.boardId,- boardItems: input.boardItems ?? [],+ boards,coverBytes: input.coverBytes ?? null,coverSourceImageName: input.coverSourceImageName ?? null,documentRefs: input.documentRefs ?? [],@@ -409,6 +410,34 @@ describe('progress', () => {]);});+ it('counts the items of every staged board, each materialized onto its own board', async () => {+ const onProgress = vi.fn();+ const targets: [string, string][] = [];+ const materializeBoardMedia: MediaMaterializer = (items, boardId, onItemSettled) => {+ targets.push(...items.map((item): [string, string] => [item.name, boardId]));++ return freshNameMaterializer()(items, boardId, onItemSettled);+ };++ await restore(+ {+ boards: [+ { items: [boardItem({ name: 'one.png' }), boardItem({ name: 'two.png' })], stagingBoardId: 'staged-inbox' },+ { items: [], stagingBoardId: 'staged-empty' },+ { items: [boardItem({ name: 'three.png' })], stagingBoardId: 'staged-old' },+ ],+ },+ { materializeBoardMedia, onProgress }+ );++ expect(targets).toEqual([+ ['one.png', 'staged-inbox'],+ ['two.png', 'staged-inbox'],+ ['three.png', 'staged-old'],+ ]);+ expect(onProgress.mock.calls.at(-1)?.[0]).toEqual({ completed: 3, total: 3 });+ });+it('drops a deduplicated reference out of the total rather than leaving it unfinished', async () => {const onProgress = vi.fn();@@ -423,7 +452,7 @@ describe('progress', () => {describe('rollbackRestoredMedia', () => {const ledger = () => ({- boardId: BOARD_ID,+ boardIds: [BOARD_ID],boardImageNames: ['board-image'],boardVideoNames: ['board-video'],coverImageName: 'cover-image',@@ -469,6 +498,20 @@ describe('rollbackRestoredMedia', () => {expect(deleteBoard).toHaveBeenCalledWith(BOARD_ID, undefined);});+ it('tries every staging board even when deleting one of them fails', async () => {+ const deleteBoard = vi+ .fn<(boardId: string) => Promise<void>>()+ .mockRejectedValueOnce(new Error('first board refused'))+ .mockResolvedValue(undefined);++ await rollbackRestoredMedia(+ { ...ledger(), boardIds: ['staged-inbox', 'staged-old'] },+ { deleteBoard, deleteImages: () => Promise.resolve(), deleteVideos: () => Promise.resolve() }+ );++ expect(deleteBoard.mock.calls.map(([boardId]) => boardId)).toEqual(['staged-inbox', 'staged-old']);+ });+it('never rejects, whatever the cleanup does', async () => {await expect(rollbackRestoredMedia(ledger(), {@@ -484,7 +527,7 @@ describe('rollbackRestoredMedia', () => {const deleteVideos = vi.fn(() => Promise.resolve());const deleteBoard = vi.fn(() => Promise.resolve());- await rollbackRestoredMedia(createRestoredMediaLedger(null), { deleteBoard, deleteImages, deleteVideos });+ await rollbackRestoredMedia(createRestoredMediaLedger([]), { deleteBoard, deleteImages, deleteVideos });expect(deleteImages).not.toHaveBeenCalled();expect(deleteVideos).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.tsindex cbd6c5cf2b..fba7fd6050 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.ts@@ -74,8 +74,8 @@ export type MediaMaterializer = (* runs, not returned at the end: a restore that throws part way has still created things.*/export interface RestoredMediaLedger {- /** The staging board these were created on, when this restore created one. */- boardId: string | null;+ /** The staging boards these were created on: one per archive board that carried media. */+ boardIds: string[];boardImageNames: string[];boardVideoNames: string[];/** A cover thumbnail uploaded as a fallback, unboarded. */@@ -85,8 +85,8 @@ export interface RestoredMediaLedger {videoNames: string[];}-export const createRestoredMediaLedger = (boardId: string | null): RestoredMediaLedger => ({- boardId,+export const createRestoredMediaLedger = (boardIds: readonly string[]): RestoredMediaLedger => ({+ boardIds: [...boardIds],boardImageNames: [],boardVideoNames: [],coverImageName: null,@@ -94,11 +94,17 @@ export const createRestoredMediaLedger = (boardId: string | null): RestoredMediavideoNames: [],});-export interface RestoreProjectMediaInput {- /** The staging board to materialize onto, or `null` when this project has no board media. */- boardId: string | null;+/** One of the source's boards and where its media lands here. */+export interface RestoreBoardInput {/** The board's contents as the source enumerated them, canonically ordered. */- boardItems: readonly InvkBoardItem[];+ items: readonly InvkBoardItem[];+ /** The staging board to materialize onto. */+ stagingBoardId: string;+}++export interface RestoreProjectMediaInput {+ /** The source's boards, inbox first; an item is on exactly one of them. */+ boards: readonly RestoreBoardInput[];/** Bundled cover bytes, for the case where the cover's source image cannot be restored. */coverBytes: { bytes: Uint8Array; entryName: string } | null;/** The image the document nominates as its cover, under its pre-restore name. */@@ -207,11 +213,13 @@ export const restoreProjectMedia = async (const issues = createTransferIssueLog();const mappings = { images: new Map<string, string>(), videos: new Map<string, string>() };const documentKeys = new Set(input.documentRefs.map(toMediaKey));- const boardKeys = new Set(input.boardItems.map(toMediaKey));+ /** Every board item in board order; an item is on one board, so this is a set. */+ const boardItems = input.boards.flatMap((board) => board.items);+ const boardKeys = new Set(boardItems.map(toMediaKey));/** Descriptor position, so a placeholder name does not depend on the order failures happened in. */- const descriptorIndexes = new Map(input.boardItems.map((item, index) => [toMediaKey(item), index]));+ const descriptorIndexes = new Map(boardItems.map((item, index) => [toMediaKey(item), index]));/** Allocate unique placeholders even without descriptor positions. */- let nextUnknownIndex = input.boardItems.length;+ let nextUnknownIndex = boardItems.length;const missingNameIndex = (key: string): number => {const index = descriptorIndexes.get(key);@@ -223,19 +231,18 @@ export const restoreProjectMedia = async (return nextUnknownIndex - 1;};- const starredKeys = new Set(input.boardItems.filter((item) => item.starred).map(toMediaKey));+ const starredKeys = new Set(boardItems.filter((item) => item.starred).map(toMediaKey));const documentOnlyRefs = input.documentRefs.filter((ref) => !boardKeys.has(toMediaKey(ref)));const documentOnlyImages = documentOnlyRefs.filter((ref) => ref.kind === 'image').map((ref) => ref.name);const documentOnlyVideos = documentOnlyRefs.filter((ref) => ref.kind === 'video').map((ref) => ref.name);- // Descriptors without a staging board still require explicit failure reporting.- const stagingBoardId = input.boardItems.length === 0 ? null : input.boardId;+ const stagedBoards = input.boards.filter((board) => board.items.length > 0);let completed = 0;// Use the worst-case progress total until existence probes resolve.let total =- (stagingBoardId === null ? 0 : input.boardItems.length) ++ stagedBoards.reduce((count, board) => count + board.items.length, 0) +documentOnlyRefs.length +(input.coverBytes === null ? 0 : 1);const advance = (): void => {@@ -275,10 +282,15 @@ export const restoreProjectMedia = async (: checkExistingVideos(documentOnlyVideos, deps.signal).catch(degradeUnlessCancelled(new Set<string>())),]);- const boardResult =- stagingBoardId === null- ? ({ failed: [], materialized: [] } satisfies MaterializeResult)- : await deps.materializeBoardMedia(input.boardItems, stagingBoardId, advance);+ // Board by board, in order: a staging board holds exactly its source board's media.+ const boardResult: MaterializeResult = { failed: [], materialized: [] };++ for (const board of stagedBoards) {+ const result = await deps.materializeBoardMedia(board.items, board.stagingBoardId, advance);++ boardResult.failed.push(...result.failed);+ boardResult.materialized.push(...result.materialized);+ }const starTargets = { image: [] as string[], video: [] as string[] };const sourceNamesByFreshName = new Map<string, string>();@@ -331,7 +343,7 @@ export const restoreProjectMedia = async (}// Treat unreported descriptors as failures with missing placeholders.- for (const item of input.boardItems) {+ for (const item of boardItems) {if (!settledBoardKeys.has(toMediaKey(item))) {failBoardItem({ kind: item.kind, name: item.name, reason: 'upload-failed' });}@@ -494,13 +506,8 @@ export const rollbackRestoredMedia = async (videoNames.length === 0 ? Promise.resolve() : deleteVideos(videoNames, deps.signal),]);- if (ledger.boardId === null) {- return;- }-- try {- await deleteBoard(ledger.boardId, deps.signal);- } catch {- // An unclaimed private board is invisible clutter, not a broken state.- }+ await Promise.allSettled(+ // An unclaimed private board is invisible clutter, not a broken state, so each is best-effort.+ ledger.boardIds.map((boardId) => deleteBoard(boardId, deps.signal))+ );};diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.tsindex ad7159d633..c088320f7b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.test.ts@@ -84,6 +84,7 @@ describe('createTransferIssueLog', () => {log.addBoardItemIssue({ kind: 'image', name: 'a.png' }, 'star-failed');expect(log.toIssues()).toEqual({+ boardIssues: [],boardItemIssues: [{ kind: 'image', name: 'a.png', reason: 'star-failed' },{ kind: 'image', name: 'z.png', reason: 'upload-failed' },@@ -93,7 +94,11 @@ describe('createTransferIssueLog', () => {});it('reports nothing for a clean transfer', () => {- expect(createTransferIssueLog().toIssues()).toEqual({ boardItemIssues: [], documentReferenceIssues: [] });+ expect(createTransferIssueLog().toIssues()).toEqual({+ boardIssues: [],+ boardItemIssues: [],+ documentReferenceIssues: [],+ });});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.tsindex 16de69d9c3..68b5cbd429 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/transfer.ts@@ -34,8 +34,16 @@ export interface InvkMediaIssue extends InvkMediaRef {reason: InvkMediaIssueReason;}+/** A board of the project, other than the inbox, that could not be set up at the destination. Its media is+ * reported through the item issues; this is about the board itself. */+/** A board that exists with everything on it, but could not be moved into the project: it stays in the Library. */+export interface InvkBoardIssue {+ name: string;+}+/** Report losses separately by role; an item may fail in both. */export interface ProjectTransferIssues {+ boardIssues: InvkBoardIssue[];boardItemIssues: InvkMediaIssue[];documentReferenceIssues: InvkMediaIssue[];}@@ -45,17 +53,21 @@ const compareIssues = (left: InvkMediaIssue, right: InvkMediaIssue): number =>/** Collects issues in whatever order they happen and hands them back in a stable one. */export const createTransferIssueLog = (): {+ addBoardIssue: (name: string) => void;addBoardItemIssue: (ref: InvkMediaRef, reason: InvkMediaIssueReason) => void;addDocumentReferenceIssue: (ref: InvkMediaRef, reason: InvkMediaIssueReason) => void;toIssues: () => ProjectTransferIssues;} => {+ const boardIssues: InvkBoardIssue[] = [];const boardItemIssues: InvkMediaIssue[] = [];const documentReferenceIssues: InvkMediaIssue[] = [];return {+ addBoardIssue: (name) => boardIssues.push({ name }),addBoardItemIssue: ({ kind, name }, reason) => boardItemIssues.push({ kind, name, reason }),addDocumentReferenceIssue: ({ kind, name }, reason) => documentReferenceIssues.push({ kind, name, reason }),toIssues: () => ({+ boardIssues: [...boardIssues].sort((left, right) => left.name.localeCompare(right.name)),boardItemIssues: [...boardItemIssues].sort(compareIssues),documentReferenceIssues: [...documentReferenceIssues].sort(compareIssues),}),diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex 621ef42ec7..1291c60cea 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -66,7 +66,9 @@ beforeEach(async () => {api.setClientStateValue.mockReset();api.setClientStateValue.mockResolvedValue(undefined);api.getProjectBoardSnapshot.mockReset();- api.getProjectBoardSnapshot.mockResolvedValue({ items: [] });+ api.getProjectBoardSnapshot.mockResolvedValue({+ boards: [{ archived: false, board_id: 'inbox', is_inbox: true, items: [], name: 'Source' }],+ });duplication.duplicateProjectRecord.mockReset();projectLocks.acquireProjectMutationLock.mockReset();projectLocks.acquireProjectMutationLock.mockResolvedValue({ kind: 'acquired', release: () => Promise.resolve() });@@ -407,9 +409,18 @@ describe('library mutations', () => {data: { id: 'source', layout: {}, name: 'Source' },});api.getProjectBoardSnapshot.mockResolvedValue({- items: [{ category: 'general', kind: 'image', name: 'on-board.png', starred: false }],+ boards: [+ {+ archived: false,+ board_id: 'inbox',+ is_inbox: true,+ items: [{ category: 'general', kind: 'image', name: 'on-board.png', starred: false }],+ name: 'Source',+ },+ ],});duplication.duplicateProjectRecord.mockResolvedValue({+ boardIssues: [],boardItemIssues: [{ kind: 'image', name: 'lost.png', reason: 'upload-failed' }],coverImageName: null,documentReferenceIssues: [],@@ -421,7 +432,7 @@ describe('library mutations', () => {// Enumerate the board successfully before creating copy resources.expect(api.getProjectBoardSnapshot).toHaveBeenCalledWith('source', expect.any(AbortSignal));expect(duplication.duplicateProjectRecord.mock.calls[0]?.[0]).toMatchObject({- boardItems: [{ name: 'on-board.png' }],+ boards: [{ is_inbox: true, items: [{ name: 'on-board.png' }] }],record: { project_id: 'source' },});expect(duplicated.summary.id).toBe('copy-id');diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex 2ecfa2b013..30a43f6dde 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -325,7 +325,7 @@ export const duplicateLibraryProject = async (const { duplicateProjectRecord } = await import('./invk/duplicateProject');const duplicated = await duplicateProjectRecord(- { boardItems: snapshot.items, owner, record },+ { boards: snapshot.boards, owner, record },options.onProgress ? { onProgress: options.onProgress } : {});@@ -336,6 +336,7 @@ export const duplicateLibraryProject = async (}return {+ boardIssues: duplicated.boardIssues,boardItemIssues: duplicated.boardItemIssues,documentReferenceIssues: duplicated.documentReferenceIssues,summary: adoptCreatedProject(duplicated.record, owner),diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex a4b51d06b8..1799c1a453 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -2,7 +2,7 @@ import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtimport { createDraftProject } from '@workbench/workbenchState';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { ProjectBoardItemDTO } from './api';+import type { ProjectBoardItemDTO, ProjectBoardSnapshotDTO } from './api';import type * as apiModule from './api';import type * as coversModule from './covers';import type * as assetTransportModule from './invk/assetTransport';@@ -20,7 +20,9 @@ const api = vi.hoisted(() => ({getClientStateValue: vi.fn(() => Promise.resolve(null)),getProject: vi.fn(),// Every export enumerates the project's board; most of these cases do not care what is on it.- getProjectBoardSnapshot: vi.fn((): Promise<{ items: ProjectBoardItemDTO[] }> => Promise.resolve({ items: [] })),+ getProjectBoardSnapshot: vi.fn((): Promise<ProjectBoardSnapshotDTO> =>+ Promise.resolve({ boards: [{ archived: false, board_id: 'inbox', is_inbox: true, items: [], name: 'Project' }] })+ ),isProjectNotFoundError: (error: unknown) =>typeof error === 'object' && error !== null && 'status' in error && error.status === 404,setClientStateValue: vi.fn(() => Promise.resolve()),@@ -58,6 +60,7 @@ const transport = vi.hoisted(() => ({findExistingImageNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),findExistingVideoNames: vi.fn((_names: readonly string[]) => Promise.resolve(new Set<string>())),mimeForEntryName: () => 'image/png',+ placeBoardInProject: vi.fn(() => Promise.resolve()),starImages: vi.fn((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] })),starVideos: vi.fn((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] })),uploadArchiveImage: vi.fn((_bytes: Uint8Array, fileName: string) =>@@ -484,14 +487,14 @@ describe('importing a project board', () => {};};- const boardSnapshot = (): { items: ProjectBoardItemDTO[] } => ({- items: [- { category: 'general', kind: 'image', name: 'shared.png', starred: true },- { category: 'user', kind: 'image', name: 'unreferenced.png', starred: false },- { category: 'general', kind: 'video', name: 'clip.mp4', starred: false },- ],+ const inboxItems: ProjectBoardItemDTO[] = [+ { category: 'general', kind: 'image', name: 'shared.png', starred: true },+ { category: 'user', kind: 'image', name: 'unreferenced.png', starred: false },+ { category: 'general', kind: 'video', name: 'clip.mp4', starred: false },+ ];+ const boardSnapshot = (): ProjectBoardSnapshotDTO => ({+ boards: [{ archived: false, board_id: 'source-inbox', is_inbox: true, items: inboxItems, name: 'Board project' }],});-const exportedBoardArchive = async (): Promise<File> => {api.getProjectBoardSnapshot.mockResolvedValue(boardSnapshot());await projectFile.exportOpenProject(boardProject());@@ -609,14 +612,17 @@ describe('importing a project board', () => {expect(values[0]).toMatchObject({ projectBoardId: 'staging-board', selectedBoardId: 'staging-board' });});- it('creates no staging board for an archive whose board was empty', async () => {+ it('stages and claims the inbox of an archive whose board was empty, uploading nothing', async () => {acceptCreate();await projectFile.exportOpenProject(boardProject());await projectFile.importProjectFile(capturedArchive());- expect(transport.createStagingBoard).not.toHaveBeenCalled();- expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({ minimum_canvas_schema_version: 3 });- expect(api.createProjectSettled.mock.calls[0]![0]).not.toHaveProperty('board_id');+ expect(transport.createStagingBoard).toHaveBeenCalledTimes(1);+ expect(transport.uploadBoardImage).not.toHaveBeenCalled();+ expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({+ board_id: 'staging-board',+ minimum_canvas_schema_version: 3,+ });});it('refuses an incompatible archive before staging or restoring any media', async () => {@@ -1090,3 +1096,119 @@ describe('embedded font project imports', () => {expect(fontTransport.remove).not.toHaveBeenCalled();});});++describe('importing every board of a project', () => {+ const boardProject = () => {+ const project = createDraftProject([]);++ return {+ ...project,+ canvas: {+ ...project.canvas,+ document: { ...project.canvas.document, stacks: stacksFrom([rasterImageLayer('l1', 'shared.png')]) },+ },+ name: 'Board project',+ };+ };+ const multiBoardSnapshot = (): ProjectBoardSnapshotDTO => ({+ boards: [+ {+ archived: false,+ board_id: 'source-inbox',+ is_inbox: true,+ items: [{ category: 'general', kind: 'image', name: 'shared.png', starred: true }],+ name: 'Board project',+ },+ {+ archived: true,+ board_id: 'source-old',+ is_inbox: false,+ items: [{ category: 'general', kind: 'image', name: 'old.png', starred: false }],+ name: 'Old façades',+ },+ { archived: false, board_id: 'source-empty', is_inbox: false, items: [], name: 'Site plan refs' },+ ],+ });+ const exportedArchive = async (): Promise<File> => {+ acceptCreate();+ api.getProjectBoardSnapshot.mockResolvedValue(multiBoardSnapshot());+ await projectFile.exportOpenProject(boardProject());++ return capturedArchive();+ };++ it('stages a board per archive board, claims the inbox on create, then moves the rest in', async () => {+ const archive = await exportedArchive();+ transport.createStagingBoard+ .mockResolvedValueOnce('staging-inbox')+ .mockResolvedValueOnce('staging-old')+ .mockResolvedValueOnce('staging-empty');++ const outcome = await projectFile.importProjectFile(archive);++ // Named for the user: the inbox after the project, the others after themselves, in the archive's order.+ expect((transport.createStagingBoard.mock.calls as unknown[][]).map((call) => call[0])).toEqual([+ 'Board project',+ 'Old façades',+ 'Site plan refs',+ ]);+ expect(+ (transport.uploadBoardImage.mock.calls as unknown[][]).map((call) => [+ call[1],+ (call[2] as { boardId?: string } | undefined)?.boardId,+ ])+ ).toEqual([+ ['shared.png', 'staging-inbox'],+ ['old.png', 'staging-old'],+ ]);+ expect(api.createProjectSettled.mock.calls[0]![0]).toMatchObject({ board_id: 'staging-inbox' });+ // Only once the project exists: the staged members move in, archived as they were.+ const projectId = outcome.record.project_id;+ expect(transport.placeBoardInProject.mock.calls).toEqual([+ ['staging-old', projectId, true, expect.anything()],+ ['staging-empty', projectId, false, expect.anything()],+ ]);+ expect(outcome.boardIssues).toEqual([]);+ expect(outcome.boardItemIssues).toEqual([]);+ });++ it('reports a board it could not place and keeps the imported project', async () => {+ const archive = await exportedArchive();+ transport.createStagingBoard.mockResolvedValueOnce('staging-inbox').mockResolvedValueOnce('staging-old');+ transport.placeBoardInProject.mockRejectedValueOnce(new Error('move refused'));++ const outcome = await projectFile.importProjectFile(archive);++ expect(outcome.boardIssues).toEqual([{ name: 'Old façades' }]);+ expect(transport.deleteStagingBoard).not.toHaveBeenCalled();+ });++ it('deletes every staging board when the create provably did not happen', async () => {+ const archive = await exportedArchive();+ transport.createStagingBoard+ .mockResolvedValueOnce('staging-inbox')+ .mockResolvedValueOnce('staging-old')+ .mockResolvedValueOnce('staging-empty');+ api.createProjectSettled.mockRejectedValueOnce(new ProjectCreateAbsentError(new Error('refused')));++ await expect(projectFile.importProjectFile(archive)).rejects.toBeInstanceOf(ProjectCreateAbsentError);++ expect((transport.deleteStagingBoard.mock.calls as unknown[][]).map((call) => call[0]).sort()).toEqual([+ 'staging-empty',+ 'staging-inbox',+ 'staging-old',+ ]);+ expect(transport.placeBoardInProject).not.toHaveBeenCalled();+ });++ it('deletes the boards it had staged when staging a later one fails, before any upload', async () => {+ const archive = await exportedArchive();+ transport.createStagingBoard.mockResolvedValueOnce('staging-inbox').mockRejectedValueOnce(new Error('refused'));++ await expect(projectFile.importProjectFile(archive)).rejects.toThrow('refused');++ expect(transport.uploadBoardImage).not.toHaveBeenCalled();+ expect(transport.deleteStagingBoard).toHaveBeenCalledExactlyOnceWith('staging-inbox', expect.anything());+ expect(api.createProjectSettled).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 25cb9c15de..61494fa694 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -121,7 +121,12 @@ const exportProjectDocument = async (const plan = planInvkExport({appVersion: APP_VERSION,- boardItems: snapshot.items,+ boards: snapshot.boards.map((board) => ({+ archived: board.archived,+ isInbox: board.is_inbox,+ items: board.items,+ name: board.name,+ })),createdAt: new Date().toISOString(),minimumCanvasSchemaVersion,name,@@ -138,6 +143,7 @@ const exportProjectDocument = async (assertAccountScopeCurrent(owner);return {+ boardIssues: result.boardIssues,boardItemIssues: result.boardItemIssues,documentReferenceIssues: result.documentReferenceIssues,fileName: plan.fileName,@@ -257,16 +263,11 @@ export const importProjectFile = async (assertAccountScopeCurrent(owner);- // Create staging boards only when media needs one.- const stagingBoardId =- archive?.boardSnapshot && archive.boardSnapshot.items.length > 0- ? await (async () => {- const { createStagingBoard } = await import('./invk/assetTransport');-- return createStagingBoard(name, owner.signal);- })()- : null;- const ledger = restoreMedia?.createRestoredMediaLedger(stagingBoardId) ?? null;+ const archiveBoards = archive?.boardSnapshot?.boards ?? [];+ const memberBoards = archiveBoards.length === 0 ? null : await import('./invk/memberBoards');+ // Made before anything is staged: every staging board joins it as it is created, so a restore abandoned at any+ // point can delete them all.+ const ledger = restoreMedia?.createRestoredMediaLedger([]) ?? null;let didCreateProject = false;let didAttemptProjectCreate = false;@@ -284,6 +285,15 @@ export const importProjectFile = async (assertAccountScopeCurrent(owner);}+ // One staging board per archive board; the inbox's rides the create, the rest are placed after.+ const stagedBoards =+ memberBoards === null || ledger === null+ ? []+ : await memberBoards.createStagingBoards(archiveBoards, name, ledger, owner.signal);+ const inboxStagingBoardId = memberBoards?.findInboxStagingBoardId(stagedBoards) ?? null;++ assertAccountScopeCurrent(owner);+const restored =archive === null || ledger === null? null@@ -292,7 +302,7 @@ export const importProjectFile = async (return restoreArchiveMedia(archive,- { boardId: stagingBoardId, ledger, projectDocument: canonicalDocument, projectId: id },+ { ledger, projectDocument: canonicalDocument, projectId: id, stagedBoards },{signal: owner.signal,...(options.onProgress === undefined@@ -321,13 +331,19 @@ export const importProjectFile = async (minimum_canvas_schema_version: minimumCanvasSchemaVersion,name,project_id: id,- ...(stagingBoardId === null ? {} : { board_id: stagingBoardId }),+ ...(inboxStagingBoardId === null ? {} : { board_id: inboxStagingBoardId }),},owner);didCreateProject = true;assertAccountScopeCurrent(owner);+ // The project exists; its other boards can now belong to it. Reported, never fatal, from here on.+ const boardIssues =+ memberBoards === null+ ? []+ : await memberBoards.placeMemberBoards(stagedBoards, record.project_id, { signal: owner.signal });+ assertAccountScopeCurrent(owner);upsertProjectSummary({id: record.project_id,@@ -343,6 +359,7 @@ export const importProjectFile = async (}return {+ boardIssues,boardItemIssues: restored?.boardItemIssues ?? [],documentReferenceIssues: restored?.documentReferenceIssues ?? [],// Bind the initial selection to the authoritative returned board ID, not the requested ID.diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.tsindex 98678c1f59..d646191af8 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts@@ -48,7 +48,7 @@ describe('startProjectFileReport', () => {report.report({ completed: 1, phase: 'bundling', total: 3 });report.report({ completed: 2, phase: 'bundling', total: 3 });- report.succeed('projects.exported', { boardItemIssues: [], documentReferenceIssues: [] });+ report.succeed('projects.exported', { boardIssues: [], boardItemIssues: [], documentReferenceIssues: [] });expect(toaster.create).toHaveBeenCalledTimes(1);expect(toaster.update.mock.calls.every(([id]) => id === 'toast-1')).toBe(true);@@ -104,7 +104,7 @@ describe('startProjectFileReport', () => {it('does not take back a verdict it has already given', () => {const report = toasts.startProjectFileReport(t, 'projects.importing');- report.succeed('projects.imported', { boardItemIssues: [], documentReferenceIssues: [] });+ report.succeed('projects.imported', { boardIssues: [], boardItemIssues: [], documentReferenceIssues: [] });report.fail('projects.importFailed', new Error('navigation blew up'));const settles = toaster.update.mock.calls.filter(([, options]) => options.duration === undefined);@@ -153,6 +153,7 @@ describe('startProjectFileReport', () => {const report = toasts.startProjectFileReport(t, 'projects.exporting');report.succeed('projects.exported', {+ boardIssues: [],boardItemIssues: boardNames.map(issue),documentReferenceIssues: referenceNames.map(issue),});@@ -160,6 +161,23 @@ describe('startProjectFileReport', () => {expect(toaster.update).toHaveBeenCalledWith('toast-1', { duration: undefined, ...expected });});+ it('leads with the boards that stayed in the Library, before the items that were lost', () => {+ const report = toasts.startProjectFileReport(t, 'projects.importing');++ report.succeed('projects.imported', {+ boardIssues: [{ name: 'Old' }],+ boardItemIssues: [{ kind: 'image', name: 'a.png', reason: 'upload-failed' }],+ documentReferenceIssues: [],+ });++ expect(toaster.update).toHaveBeenCalledWith('toast-1', {+ description: 'projects.file.unplacedBoards({"count":1}) projects.file.missingBoardItems({"count":1})',+ duration: undefined,+ title: 'projects.imported',+ type: 'warning',+ });+ });+it('translates a format error into its reason rather than its message', async () => {const { InvkFormatError } = await import('./invk/format');const report = toasts.startProjectFileReport(t, 'projects.importing');diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.tsindex 4871ea0d29..b935c45f05 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.ts@@ -25,6 +25,7 @@ export interface ProjectFileReporter {const MISSING_REASONS: ReadonlySet<InvkMediaIssueReason> = new Set(['fetch-failed', 'missing-entry', 'upload-failed']);const countIssues = (issues: ProjectTransferIssues) => ({+ boards: issues.boardIssues.length,boardItems: issues.boardItemIssues.filter((issue) => MISSING_REASONS.has(issue.reason)).length,documentReferences: issues.documentReferenceIssues.filter((issue) => MISSING_REASONS.has(issue.reason)).length,unstarred: issues.boardItemIssues.filter((issue) => issue.reason === 'star-failed').length,@@ -120,9 +121,9 @@ export const startProjectFileReport = (}, PROGRESS_REDRAW_INTERVAL_MS);},succeed: (successTitle, issues) => {- const { boardItems, documentReferences, unstarred } = countIssues(issues);+ const { boardItems, boards, documentReferences, unstarred } = countIssues(issues);- if (boardItems === 0 && documentReferences === 0 && unstarred === 0) {+ if (boards === 0 && boardItems === 0 && documentReferences === 0 && unstarred === 0) {settle({ title: successTitle, type: 'success' });return;@@ -130,6 +131,7 @@ export const startProjectFileReport = (// Keep toasts bounded to counts; detailed losses remain on the outcome.const parts = [+ ...(boards === 0 ? [] : [t('projects.file.unplacedBoards', { count: boards })]),...(boardItems === 0 ? [] : [t('projects.file.missingBoardItems', { count: boardItems })]),...(documentReferences === 0 ? [] : [t('projects.file.missingReferences', { count: documentReferences })]),...(unstarred === 0 ? [] : [t('projects.file.unstarredItems', { count: unstarred })]),diff --git a/tests/app/routers/test_projects.py b/tests/app/routers/test_projects.pyindex c36f2457d7..4c96cebbfc 100644--- a/tests/app/routers/test_projects.py+++ b/tests/app/routers/test_projects.py@@ -310,9 +310,17 @@ def test_the_board_snapshot_lists_the_projects_visible_media(assert response.status_code == status.HTTP_200_OKassert response.json() == {- "items": [- {"category": "control", "kind": "image", "name": "asset.png", "starred": False},- {"category": "general", "kind": "image", "name": "shown.png", "starred": False},+ "boards": [+ {+ "archived": False,+ "board_id": created["board_id"],+ "is_inbox": True,+ "items": [+ {"category": "control", "kind": "image", "name": "asset.png", "starred": False},+ {"category": "general", "kind": "image", "name": "shown.png", "starred": False},+ ],+ "name": "Project",+ }]}@@ -323,7 +331,11 @@ def test_the_board_snapshot_of_an_empty_project_is_empty(client: TestClient, useresponse = client.get(f"/api/v1/projects/{created['project_id']}/board-snapshot", headers=_auth(user1_token))assert response.status_code == status.HTTP_200_OK- assert response.json() == {"items": []}+ assert response.json() == {+ "boards": [+ {"archived": False, "board_id": created["board_id"], "is_inbox": True, "items": [], "name": "Project"}+ ]+ }def test_the_board_snapshot_of_a_missing_or_foreign_project_is_a_404(@@ -400,3 +412,15 @@ def test_an_unknown_boards_mode_is_rejected_before_anything_is_deleted(client: Tassert refused.status_code == status.HTTP_422_UNPROCESSABLE_CONTENTassert client.get(f"/api/v1/projects/{created['project_id']}", headers=_auth(user1_token)).status_code == 200+++def test_the_board_snapshot_lists_member_boards_after_the_inbox(client: TestClient, user1_token: str):+ created = _create_project(client, user1_token).json()+ member = _create_board_in_project(client, user1_token, created["project_id"], "Member")++ response = client.get(f"/api/v1/projects/{created['project_id']}/board-snapshot", headers=_auth(user1_token))++ assert [(board["board_id"], board["is_inbox"], board["name"]) for board in response.json()["boards"]] == [+ (created["board_id"], True, "Project"),+ (member, False, "Member"),+ ]diff --git a/tests/app/services/project_records/test_project_records.py b/tests/app/services/project_records/test_project_records.pyindex 622d97aa3d..ce52c3cb2b 100644--- a/tests/app/services/project_records/test_project_records.py+++ b/tests/app/services/project_records/test_project_records.py@@ -5,7 +5,10 @@ import pytestfrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.project_records import project_records_sqlitefrom invokeai.app.services.project_records.project_records_common import (+ ProjectBoardItemDTO,ProjectBoardNotFoundError,+ ProjectBoardSnapshotDTO,+ ProjectBoardTooLargeError,ProjectBoardUnavailableError,ProjectCanvasSchemaDowngradeError,ProjectCanvasSchemaUnsupportedError,@@ -625,6 +628,75 @@ def test_get_board_id_is_user_scoped(project_records: ProjectRecordsSqlite, othe# --- board snapshot ---------------------------------------------------------------------------+def _inbox_items(snapshot: ProjectBoardSnapshotDTO) -> list[ProjectBoardItemDTO]:+ """The inbox always leads the snapshot."""+ assert snapshot.boards[0].is_inbox+ return snapshot.boards[0].items+++def _member_board(db: SqliteDatabase, board_id: str, *, project_id: str, name: str, archived: bool = False) -> str:+ _insert_board(db, board_id, name=name, archived=archived)+ with db.transaction() as cursor:+ cursor.execute("UPDATE boards SET project_id = ? WHERE board_id = ?;", (project_id, board_id))+ return board_id+++def test_the_snapshot_lists_every_board_of_the_project_inbox_first(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, other_user_id: str+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Mine", {}, project_id="shared-id")+ # The other account's same-id project has members of its own, which must not leak in.+ theirs = project_records.create(other_user_id, "Theirs", {}, project_id="shared-id")+ _member_board(db, "later", project_id="shared-id", name="Site plan refs")+ _member_board(db, "old", project_id="shared-id", name="Old façades", archived=True)+ _insert_board(db, "their-member", user_id=other_user_id, name="Stripes")+ with db.transaction() as cursor:+ cursor.execute("UPDATE boards SET project_id = 'shared-id' WHERE board_id = 'their-member';")+ cursor.execute("UPDATE boards SET created_at = '2020-01-01 00:00:00.000' WHERE board_id = 'old';")+ _put_image(db, "inbox.png", created.board_id)+ _put_image(db, "later.png", "later")+ _put_video(db, "old.mp4", "old")+ _put_image(db, "theirs.png", "their-member")++ snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)++ assert [(board.board_id, board.name, board.is_inbox, board.archived) for board in snapshot.boards] == [+ (created.board_id, "Mine", True, False),+ ("old", "Old façades", False, True),+ ("later", "Site plan refs", False, False),+ ]+ assert [[item.name for item in board.items] for board in snapshot.boards] == [+ ["inbox.png"],+ ["old.mp4"],+ ["later.png"],+ ]+ assert [+ board.board_id for board in project_records.get_board_snapshot(other_user_id, theirs.project_id).boards+ ] == [+ theirs.board_id,+ "their-member",+ ]+++def test_the_snapshot_ceiling_counts_every_board_together(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(project_records_sqlite, "PROJECT_BOARD_SNAPSHOT_MAX_ITEMS", 2)+ created = project_records.create(SYSTEM_USER_ID, "Full", {})+ _member_board(db, "member", project_id=created.project_id, name="Member")+ _put_image(db, "a.png", created.board_id)+ _put_image(db, "b.png", "member")+ assert (+ sum(len(board.items) for board in project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id).boards)+ == 2+ )++ _put_image(db, "c.png", "member")++ with pytest.raises(ProjectBoardTooLargeError):+ project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)++def _put_image(db: SqliteDatabase,name: str,@@ -671,7 +743,7 @@ def test_the_snapshot_lists_every_visible_category_of_both_kinds(snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)- assert {(item.kind, item.name, item.category) for item in snapshot.items} == {+ assert {(item.kind, item.name, item.category) for item in _inbox_items(snapshot)} == {(kind, f"{category}.{ext}", category)for category in ("general", "control", "mask", "user")for kind, ext in (("image", "png"), ("video", "mp4"))@@ -692,7 +764,7 @@ def test_the_snapshot_excludes_what_the_gallery_does_not_show(snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)- assert [item.name for item in snapshot.items] == ["shown.png", "shown.mp4"]+ assert [item.name for item in _inbox_items(snapshot)] == ["shown.png", "shown.mp4"]def test_the_snapshot_excludes_media_on_other_boards(project_records: ProjectRecordsSqlite, db: SqliteDatabase) -> None:@@ -703,7 +775,7 @@ def test_the_snapshot_excludes_media_on_other_boards(project_records: ProjectRecsnapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, mine.project_id)- assert [item.name for item in snapshot.items] == ["mine.png"]+ assert [item.name for item in _inbox_items(snapshot)] == ["mine.png"]def test_the_snapshot_carries_starring_and_is_ordered_by_kind_then_name(@@ -716,7 +788,7 @@ def test_the_snapshot_carries_starring_and_is_ordered_by_kind_then_name(snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)- assert [(item.kind, item.name, item.starred) for item in snapshot.items] == [+ assert [(item.kind, item.name, item.starred) for item in _inbox_items(snapshot)] == [("image", "a.png", False),("image", "b.png", True),("video", "a.mp4", False),@@ -733,13 +805,13 @@ def test_a_same_name_image_and_video_are_separate_entries(snapshot = project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)- assert [(item.kind, item.name) for item in snapshot.items] == [("image", "twin"), ("video", "twin")]+ assert [(item.kind, item.name) for item in _inbox_items(snapshot)] == [("image", "twin"), ("video", "twin")]def test_an_empty_board_snapshots_to_an_empty_list(project_records: ProjectRecordsSqlite) -> None:created = project_records.create(SYSTEM_USER_ID, "Empty", {})- assert project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id).items == []+ assert _inbox_items(project_records.get_board_snapshot(SYSTEM_USER_ID, created.project_id)) == []def test_snapshotting_someone_elses_project_is_not_found(