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(gallery): group boards by project, with a Library tier and project inboxes
Josh Corbett0ea195671ca9
diff --git a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdxindex e2abf4e2ff..3f187ef184 100644--- a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx+++ b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx@@ -1,23 +1,23 @@---title: Working with Projects-description: Keep each piece of work in its own project, with its canvas, workflows, layout and board, and switch between them without losing your place.-lastUpdated: 2026-09-29+description: Keep each piece of work in its own project, with its canvas, workflows, layout and boards, and switch between them without losing your place.+lastUpdated: 2026-10-08sidebar:order: 0---import { Image } from 'astro:assets';import projectSwitcher from '../assets/project-switcher.webp';-A **project** is a self-contained workspace. Everything you arrange while working on one idea stays together in it: the canvas and its layers, the workflows you have open, the panel layout, your prompt history, and a gallery board that collects the project's images and videos. Open the project again later, on the same computer or another one, and it comes back exactly as you left it.+A **project** is a self-contained workspace. Everything you arrange while working on one idea stays together in it: the canvas and its layers, the workflows you have open, the panel layout, your prompt history, and the gallery boards that collect the project's images and videos. Open the project again later, on the same computer or another one, and it comes back exactly as you left it.Invoke saves projects automatically on the server, so there is no Save button to remember. You can keep several projects open at once and switch between them in a keystroke.## Why use projects- **Pick up where you left off.** Closing the browser, reloading the page or moving to another computer does not lose your arrangement. The Home page offers your most recent project with a single **Resume** button.-- **Keep unrelated work apart.** A character study, a product shoot and a video experiment can each have their own canvas, workflows, layout and board, instead of competing for one workspace.-- **Switch without waiting.** Generations keep running when you switch to another project. Their results still land on the board of the project that started them.-- **Find results easily.** Each project's images and videos collect on its own board, named after the project, rather than piling up in one long gallery.+- **Keep unrelated work apart.** A character study, a product shoot and a video experiment can each have their own canvas, workflows, layout and boards, instead of competing for one workspace.+- **Switch without waiting.** Generations keep running when you switch to another project. Their results still land in the project that started them.+- **Find results easily.** Each project's images and videos collect in its own boards — an **Inbox** for new results, plus any boards you create inside it — rather than piling up in one long gallery.- **Back up and share work.** A project can be exported as a single `.invk` file that includes its images and videos, and imported on any Invoke installation.## What a project keeps@@ -28,9 +28,9 @@ Invoke saves projects automatically on the server, so there is no Save button to| Open workflows, and which one is active | Your workflow library || Panel layout and floating widgets | Saved layout presets || Prompt history, and the Invoke routing (source and destination) | Preferences, theme and hotkeys |-| Widget settings, such as gallery filters | Boards other than the project's own |+| Widget settings, such as gallery filters | Boards in the Library || Project settings: **Use CPU noise**, **Antialias progress images** and the Preview's progress image toggle | Generate recipes |-| The project's board and the images and videos on it | |+| The project's boards and the images and videos on them | |In **Settings**, a badge next to each option says where it is stored: **Saved with this project**, **Saved with this widget in this project**, or **Saved in your preferences** for options that follow you across projects.@@ -52,7 +52,7 @@ To create a project, click **New project**. The arrow beside it (**Choose how toThe starting point only chooses the initial layout. Every tool remains available, and you can [rearrange the workspace](/users-guide/workbench/introduction/) at any time.-New projects are called **Project Name #1**, **Project Name #2** and so on. Give yours a meaningful name early (see [Renaming](#renaming-duplicating-and-deleting)), because the name also labels the project's board in the gallery.+New projects are called **Project Name #1**, **Project Name #2** and so on. Give yours a meaningful name early (see [Renaming](#renaming-duplicating-and-deleting)), because the name also heads the project's boards in the gallery.## Switching between projects@@ -74,15 +74,17 @@ The shortcut works even while you are typing in a prompt box. You can rebind it## Where your images go-Every project owns a private board, created with the project and named after it. In the gallery it appears near the top, after **Uncategorized**, and always shows the current project name.+Boards belong to projects. Every project has an **Inbox**, created with it, where new results land; you can add more boards to a project to sort its work, and they belong to that project alone. Boards that should be available from every project — reference photos, control images, style tests — live in the **Library**, which the gallery shows beneath the open project's boards.-New results go to whichever board is selected in the gallery, so you can send a batch somewhere else when you want to. To send them to one board while you browse others, choose **Auto-add to this board** from that board's menu; see [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes). When a project is first created, imported or duplicated, its own board is selected. If you choose a date view instead of a specific board, results still go to the project board. After that, the project remembers your choice of destination.+The gallery's board list is grouped by this: first the open project's boards, headed by the project's name, with **Inbox** pinned at the top; then **Library**, with **Uncategorized** pinned at the top for media that is on no board. Each group has its own **+** button, so where a new board goes is decided by which one you press.++New results go to whichever board is selected in the gallery, so you can send a batch somewhere else when you want to. To send them to one board while you browse others, choose **Auto-add to this board** from that board's menu; see [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes). When a project is first created, imported or duplicated, its Inbox is selected. If you choose a date view instead of a specific board, results still go to the Inbox. After that, the project remembers your choice of destination.The destination is fixed when you press **Invoke**. Switching to a different project or board while a job runs does not redirect its results.-Boards belonging to your other projects are hidden from the gallery to keep it focused. To see them, turn on **Other projects' boards** in the gallery's board filters. The setting is remembered separately for each project.+Boards belonging to your other projects are hidden from the gallery to keep it focused. To see them, turn on **Other projects' boards** in the gallery's board filters: they appear under **Other projects**, grouped by project. The setting is remembered separately for each project.-A project board is managed through its project: renaming the project renames the board, and the board has no rename, archive or delete commands of its own. Its menu offers **Export project (.invk)** instead.+A project's Inbox is managed through its project: renaming the project renames it, and it cannot be renamed, moved, archived or deleted on its own. Its menu offers **Export project (.invk)** instead. The project's other boards are ordinary boards: rename, archive or delete them, or choose **Move to…** from their menu to move them to the Library or into another project.See [the gallery](/users-guide/gallery/introduction/) for more about boards.@@ -117,14 +119,15 @@ Right-click a project, or use its **Actions** button, for **Open**, **Pin**, **R### Renaming, duplicating and deleting-**Rename…** changes the project name and the name of its board.+**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 on the project's board. 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 in the project's Inbox. Its other boards are not copied. Use it to try a different direction without disturbing the original.**Delete…** removes the project permanently. There is no trash to recover it from.- The project's canvas, workflows, layout and settings are deleted.-- Its board is deleted too, but **the images and videos on it are kept**: they move to **Uncategorized** in the gallery. Deleting a project never empties your gallery.+- Its Inbox is deleted too, but **the images and videos on it are kept**: they move to **Uncategorized** in the gallery.+- If the project has other boards, the dialog asks what to do with them: **keep them in the Library**, with everything on them, or **delete them too**, in which case their media also moves to Uncategorized. Deleting a project never empties your gallery.- A project that is still generating cannot be deleted until its runs finish.If you only want to tidy the switcher, **Close** the project instead of deleting it.@@ -133,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 on its board, and any other media the project uses, such as reference images, so it opens complete on another installation. 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 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.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.@@ -151,11 +154,11 @@ In the Workflow Library dialog, **This project** lists the project's own workflo## Making the most of projects-- **One project per piece of work.** Create a project for each client job, series or experiment, rather than doing everything in one. Each keeps its own layout and board, so switching tasks means switching projects.-- **Name projects as you create them.** Names make the Projects page searchable and label the boards in your gallery.+- **One project per piece of work.** Create a project for each client job, series or experiment, rather than doing everything in one. Each keeps its own layout and boards, so switching tasks means switching projects.+- **Name projects as you create them.** Names make the Projects page searchable and head the boards in your gallery.- **Pin what you're actively working on.** Pinned projects stay at the top of the Projects page no matter how many others you create.- **Duplicate before a big change.** A duplicate is cheap insurance when you want to explore a different direction.-- **Queue work, then switch.** Start a long render or a batch, switch to another project with <kbd>Ctrl</kbd>+<kbd>P</kbd>, and keep working. The progress ring in the switcher shows when it is done, and the results wait on the original project's board. To see only the active project's jobs in the Queue widget, set **Show jobs from** to **Active project** in Settings.+- **Queue work, then switch.** Start a long render or a batch, switch to another project with <kbd>Ctrl</kbd>+<kbd>P</kbd>, and keep working. The progress ring in the switcher shows when it is done, and the results wait in the original project's Inbox. To see only the active project's jobs in the Queue widget, set **Show jobs from** to **Active project** in Settings.- **Close projects you're not using.** It keeps the switcher short and costs nothing: the project stays in your library.- **Export milestones.** Exporting a `.invk` file gives you a self-contained snapshot to archive or share.- **Clean up occasionally.** Long-running projects accumulate temporary files; run **Delete intermediates…** from the project's menu to reclaim disk space.diff --git a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdxindex d740902600..5bf24568bf 100644--- a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx+++ b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx@@ -25,10 +25,11 @@ Hover over a board and click its **⋮** button, or right-click it, to open its* **Auto-add to this board** — makes this the board that receives new results, marked **Auto**, whichever board is selected. On the auto-add board, the item is **Stop auto-adding here**, which goes back to sending results to the selected board. Not offered for date boards or archived boards. See [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes).* **Download Board** — downloads the board (see [below](#downloading-a-board)).* **Rename board** — opens a dialog to change the name.+* **Move to…** — moves the board to the **Library**, into the open project, or into one of your other projects. A board in a project is private to you.* **Archive Board** / **Unarchive Board** — see [below](#archiving-a-board).* **Delete Board** — see [below](#deleting-a-board).-Project boards are managed through their project: their menu has **Export project (.invk)**, **Auto-add to this board** and **Download Board** instead, and renaming the project renames its board. **Uncategorized** offers only **Auto-add to this board** and **Download Board**, and date boards have no menu. If the auto-add board is deleted, results go back to following the selected board.+A project's **Inbox** is managed through its project: its menu has **Export project (.invk)**, **Auto-add to this board** and **Download Board** instead, and renaming the project renames it. **Uncategorized** offers only **Auto-add to this board** and **Download Board**, and date boards have no menu. If the auto-add board is deleted, results go back to following the selected board.### Archiving a board@@ -53,7 +54,7 @@ Choose **Delete Board** from the board's menu. The confirmation dialog shows how**Delete Board and Media** cannot be undone.:::-Queued or running jobs that were sending results to the deleted board send them to **Uncategorized** instead. Project boards cannot be deleted from the Gallery; delete the project instead.+Queued or running jobs that were sending results to the deleted board send them to **Uncategorized** instead. A project's Inbox cannot be deleted from the Gallery; delete the project instead, which also asks what to do with the project's other boards.On a multi-user installation, only a board's owner or an administrator can delete it. When an owner deletes a shared board with its media, only their own media is deleted and other people's items move to Uncategorized; an administrator's deletion removes everything. If some files cannot be removed, those items are kept in Uncategorized and a warning says how many.diff --git a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdxindex 9bdbad5dd3..b530ee2b95 100644--- a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx+++ b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx@@ -14,7 +14,7 @@ import searchHelp from '../assets/gallery-search-help.png';import semanticSearch from '../assets/gallery-semantic-search.png';import selection from '../assets/gallery-selection.webp';-The **Gallery** holds every image and video you generate or upload. It is organized into **boards**: the always-present **Uncategorized** board, a board for each project, and boards you create yourself. From the Gallery you choose where new results go, find media by its prompt or by what it shows, and move, star, download or delete it.+The **Gallery** holds every image and video you generate or upload. It is organized into **boards**. Every board belongs either to a project — each has an **Inbox** for new results, plus any boards you add to it — or to the **Library**, whose boards are available from every project and include the always-present **Uncategorized** board. From the Gallery you choose where new results go, find media by its prompt or by what it shows, and move, star, download or delete it.<Image src={overview} alt="The Gallery with the Concept Art board selected: the board list at the top, the Media and Uploads tabs, the search field, and a grid of images with starred items pinned at the top." width={420} />@@ -23,7 +23,7 @@ The **Gallery** holds every image and video you generate or upload. It is organiThe Gallery has three parts:* **The header** shows the selected board after *Gallery /*. Click the board name to hide or show the board list. The gear button opens the [Gallery settings](/users-guide/gallery/gallery-reference/#gallery-settings).-* **The board list** has a search field (**Search or create boards**), a **Filter & sort boards** button, and the boards themselves, grouped under **Boards** and, when turned on, **By Date** and **Archived**. Each group can be collapsed.+* **The board list** has a search field (**Search or create boards**), a **Filter & sort boards** button, and the boards themselves, grouped under the open project's name, **Library** and, when turned on, **Other projects**, **By Date** and **Archived**. Each group can be collapsed; the project and Library groups show how many boards you have made in them, and **Other projects** how many projects it lists.* **The media area** shows the contents of the selected board, on two tabs:* **Media** — images and videos generated in InvokeAI.* **Uploads** — images, videos and audio you have uploaded.@@ -32,13 +32,13 @@ The Gallery has three parts:When the Gallery is narrow, or docked in a side rail, the board list sits above the media grid. When it is wide, the board list becomes a column on the left. Drag the divider between them to resize the list.-Each board shows its cover image, its name and a count such as **76 | 12**: 76 items on the Media tab and 12 on the Uploads tab. A project's board is marked **Project**. On a multi-user installation, other people's boards show their owner's name.+Each board shows its cover image, its name and a count such as **76 | 12**: 76 items on the Media tab and 12 on the Uploads tab. A project's Inbox is pinned at the top of its group with an inbox icon. On a multi-user installation, other people's boards show their owner's name.## Boards### Creating a board-Type a name into **Search or create boards**. If no board has that name, a **Create board "…"** row appears at the end of the list; click it, or press **Enter**. You can also type the name and click the **+** button next to the **Boards** heading.+Type a name into **Search or create boards**. If no board has that name, a **Create board "…" in …** row appears, in the group the board will go to; click it, or press **Enter**. The open project's group and the **Library** group each have a **+** button: press one to choose where the board goes, then type its name — or type the name first and press the **+** of the group you want.<Image src={createBoard} alt="Typing Seascapes into the board search field shows a Create board "Seascapes" row." width={420} />@@ -48,8 +48,8 @@ The new board is selected straight away, so it also becomes the destination for**By default, new results go to the board that is selected in the Gallery**: select a board, press **Invoke**, and the results land on that board. The destination is fixed when you press Invoke, so you can select another board and queue more work while earlier jobs are still running, without redirecting them.-* A new project starts with its own board selected. See [Projects](/users-guide/projects/introduction/#where-your-images-go).-* If you select a date board (see below), results go to the project's board, because date boards are only a view.+* A new project starts with its Inbox selected. See [Projects](/users-guide/projects/introduction/#where-your-images-go).+* If you select a date board (see below), results go to the project's Inbox, because date boards are only a view.* Uploads go to the selected board.* If you archive or delete the selected board, the selection, and with it the destination, moves to **Uncategorized**.@@ -66,14 +66,14 @@ The **Filter & sort boards** button beside the search field controls which board* **Board visibility*** **Date boards** — adds a **By Date** group with one board per day on which you created media. Date boards are read-only views: you cannot upload to them, drop media on them, or rename or delete them.* **Archived boards** — adds an **Archived** group listing the boards you have archived.- * **Other projects' boards** — shows the boards of your other projects, which are hidden by default to keep the list focused. The current project's board is always shown.-* **Sort by** — **Created** (the default) or **Name**, in descending or ascending order. **Uncategorized** and the current project's board always stay at the top.+ * **Other projects' boards** — adds an **Other projects** group with your other projects' boards, grouped by project. They are hidden by default to keep the list focused; the open project's boards are always shown.+* **Sort by** — **Created** (the default) or **Name**, in descending or ascending order. Each project's **Inbox** and the Library's **Uncategorized** always stay at the top of their group.These choices are saved with the project, so each project can list boards differently.### Renaming, archiving, downloading and deleting boards-Right-click a board, or hover over it and click its **⋯** button, to rename, archive, download or delete it. [Managing boards](/users-guide/gallery/gallery-reference/#managing-boards) in the Gallery Reference describes each action, including what deleting a board does to its media.+Right-click a board, or hover over it and click its **⋯** button, to rename, move, archive, download or delete it. [Managing boards](/users-guide/gallery/gallery-reference/#managing-boards) in the Gallery Reference describes each action, including what deleting a board does to its media.## Finding media in a boarddiff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 2366ac7ca9..a8597f5e04 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1,6 +1,6 @@{"browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome",- "capturedAt": "2026-10-06",+ "capturedAt": "2026-10-08","routes": [{"activatedResourceBaseline": {@@ -14,13 +14,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 124.29999999981374,+ "domContentLoadedMedianMs": 128.09999999962747,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 124.40000000037253,- "longestTaskMaxMs": 79,+ "loadMedianMs": 128.2999999988824,+ "longestTaskMaxMs": 83,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -29,14 +29,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 0,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,- "requestCount": 31,- "scriptRawBytes": 1838770,- "scriptRequestCount": 27,- "totalRawBytes": 2061474+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,+ "requestCount": 30,+ "scriptRawBytes": 1845621,+ "scriptRequestCount": 26,+ "totalRawBytes": 2072526},- "routeReadyMedianMs": 260.70000000018626,+ "routeReadyMedianMs": 269.7999999988824,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"},@@ -52,12 +52,12 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 121.1000000005588,+ "domContentLoadedMedianMs": 123.5,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 121.29999999981374,+ "loadMedianMs": 123.59999999962747,"longestTaskMaxMs": 80,"owner": "app","projectSwitchMedianMs": 0,@@ -67,14 +67,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 0,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,- "requestCount": 31,- "scriptRawBytes": 1838770,- "scriptRequestCount": 27,- "totalRawBytes": 2061474+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,+ "requestCount": 30,+ "scriptRawBytes": 1845621,+ "scriptRequestCount": 26,+ "totalRawBytes": 2072526},- "routeReadyMedianMs": 269.09999999962747,+ "routeReadyMedianMs": 277,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"},@@ -90,29 +90,29 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 122.30000000074506,+ "domContentLoadedMedianMs": 126.19999999925494,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 122.40000000037253,- "longestTaskMaxMs": 153,+ "loadMedianMs": 126.30000000074506,+ "longestTaskMaxMs": 176,"owner": "workbench",- "projectSwitchMedianMs": 34.700000000186265,+ "projectSwitchMedianMs": 39.80000000074506,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 88,- "scriptRawBytes": 4005108,+ "scriptRawBytes": 4037995,"scriptRequestCount": 83,- "totalRawBytes": 4272210+ "totalRawBytes": 4309298},- "routeReadyMedianMs": 407.5,+ "routeReadyMedianMs": 437.59999999962747,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -128,29 +128,29 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 122.5,+ "domContentLoadedMedianMs": 127,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 122.59999999962747,- "longestTaskMaxMs": 164,+ "loadMedianMs": 127.10000000149012,+ "longestTaskMaxMs": 176,"owner": "workbench",- "projectSwitchMedianMs": 41,+ "projectSwitchMedianMs": 47.09999999962747,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 88,- "scriptRawBytes": 4005108,+ "scriptRawBytes": 4037995,"scriptRequestCount": 83,- "totalRawBytes": 4272210+ "totalRawBytes": 4309298},- "routeReadyMedianMs": 434.30000000074506,+ "routeReadyMedianMs": 451.6000000014901,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -159,20 +159,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 309288,+ "largestAssetRawBytes": 305134,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 515489,+ "scriptRawBytes": 514482,"scriptRequestCount": 9,- "totalRawBytes": 515489+ "totalRawBytes": 514482},- "domContentLoadedMedianMs": 124.90000000037253,+ "domContentLoadedMedianMs": 124.5,"id": "editor-canvas",- "layoutAckMedianMs": 2.699999999254942,- "layoutReturnSwitchMedianMs": 54.10000000055879,- "layoutSwitchMedianMs": 68.30000000074506,- "loadMedianMs": 125,- "longestTaskMaxMs": 157,+ "layoutAckMedianMs": 2.600000001490116,+ "layoutReturnSwitchMedianMs": 57.59999999962747,+ "layoutSwitchMedianMs": 75.90000000037253,+ "loadMedianMs": 124.59999999962747,+ "longestTaskMaxMs": 168,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -181,14 +181,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 97,- "scriptRawBytes": 4520597,+ "scriptRawBytes": 4552477,"scriptRequestCount": 92,- "totalRawBytes": 4787699+ "totalRawBytes": 4823780},- "routeReadyMedianMs": 1119.7999999998137,+ "routeReadyMedianMs": 1146.199999999255,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"},@@ -197,20 +197,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 309288,+ "largestAssetRawBytes": 305134,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 515489,+ "scriptRawBytes": 514482,"scriptRequestCount": 9,- "totalRawBytes": 515489+ "totalRawBytes": 514482},- "domContentLoadedMedianMs": 122.79999999981374,+ "domContentLoadedMedianMs": 129,"id": "editor-canvas",- "layoutAckMedianMs": 2.5,- "layoutReturnSwitchMedianMs": 47.10000000055879,- "layoutSwitchMedianMs": 64.29999999981374,- "loadMedianMs": 122.90000000037253,- "longestTaskMaxMs": 174,+ "layoutAckMedianMs": 3,+ "layoutReturnSwitchMedianMs": 55.40000000037253,+ "layoutSwitchMedianMs": 75.30000000074506,+ "loadMedianMs": 129.09999999962747,+ "longestTaskMaxMs": 211,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -219,14 +219,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 97,- "scriptRawBytes": 4520597,+ "scriptRawBytes": 4552477,"scriptRequestCount": 92,- "totalRawBytes": 4787699+ "totalRawBytes": 4823780},- "routeReadyMedianMs": 1104.7999999998137,+ "routeReadyMedianMs": 1145.5999999996275,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"},@@ -235,20 +235,20 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 187139,+ "largestAssetRawBytes": 187107,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 420972,+ "scriptRawBytes": 420934,"scriptRequestCount": 6,- "totalRawBytes": 436385+ "totalRawBytes": 436347},- "domContentLoadedMedianMs": 120,+ "domContentLoadedMedianMs": 129.09999999962747,"id": "editor-workflow",- "layoutAckMedianMs": 2.599999999627471,- "layoutReturnSwitchMedianMs": 32.59999999962747,- "layoutSwitchMedianMs": 66.19999999925494,- "loadMedianMs": 120.1000000005588,- "longestTaskMaxMs": 153,+ "layoutAckMedianMs": 2.800000000745058,+ "layoutReturnSwitchMedianMs": 35.40000000037253,+ "layoutSwitchMedianMs": 75.80000000074506,+ "loadMedianMs": 129.2000000011176,+ "longestTaskMaxMs": 182,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -257,14 +257,14 @@"cssRawBytes": 17572,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 95,- "scriptRawBytes": 4426080,+ "scriptRawBytes": 4458929,"scriptRequestCount": 89,- "totalRawBytes": 4708595+ "totalRawBytes": 4745645},- "routeReadyMedianMs": 1115.8999999994412,+ "routeReadyMedianMs": 1175.5,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "empty"},@@ -273,20 +273,20 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 187139,+ "largestAssetRawBytes": 187107,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 420972,+ "scriptRawBytes": 420934,"scriptRequestCount": 6,- "totalRawBytes": 436385+ "totalRawBytes": 436347},- "domContentLoadedMedianMs": 122,+ "domContentLoadedMedianMs": 127.30000000074506,"id": "editor-workflow",- "layoutAckMedianMs": 2.7999999998137355,- "layoutReturnSwitchMedianMs": 40.200000000186265,- "layoutSwitchMedianMs": 123.5,- "loadMedianMs": 122.20000000018626,- "longestTaskMaxMs": 260,+ "layoutAckMedianMs": 3.400000000372529,+ "layoutReturnSwitchMedianMs": 42.5,+ "layoutSwitchMedianMs": 138.60000000149012,+ "loadMedianMs": 127.40000000037253,+ "longestTaskMaxMs": 282,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -295,14 +295,14 @@"cssRawBytes": 17572,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 95,- "scriptRawBytes": 4426080,+ "scriptRawBytes": 4458929,"scriptRequestCount": 89,- "totalRawBytes": 4708595+ "totalRawBytes": 4745645},- "routeReadyMedianMs": 1172.0999999996275,+ "routeReadyMedianMs": 1209.6000000014901,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "representative"},@@ -318,13 +318,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 124.09999999962747,+ "domContentLoadedMedianMs": 127.09999999962747,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 30.40000000037253,- "loadMedianMs": 124.29999999981374,- "longestTaskMaxMs": 162,+ "layoutSwitchMedianMs": 39.90000000037253,+ "loadMedianMs": 127.09999999962747,+ "longestTaskMaxMs": 170,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -333,14 +333,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 88,- "scriptRawBytes": 4005108,+ "scriptRawBytes": 4037995,"scriptRequestCount": 83,- "totalRawBytes": 4272210+ "totalRawBytes": 4309298},- "routeReadyMedianMs": 1344,+ "routeReadyMedianMs": 1381.199999999255,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -356,13 +356,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 121.40000000037253,+ "domContentLoadedMedianMs": 127.89999999850988,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 37.80000000074506,- "loadMedianMs": 121.5,- "longestTaskMaxMs": 152,+ "layoutSwitchMedianMs": 46.69999999925494,+ "loadMedianMs": 128,+ "longestTaskMaxMs": 180,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -371,14 +371,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 749029,- "otherRawBytes": 196881,+ "largestAssetRawBytes": 752421,+ "otherRawBytes": 201082,"requestCount": 88,- "scriptRawBytes": 4005108,+ "scriptRawBytes": 4037995,"scriptRequestCount": 83,- "totalRawBytes": 4272210+ "totalRawBytes": 4309298},- "routeReadyMedianMs": 1342.5,+ "routeReadyMedianMs": 1400,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"}diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 24166df143..b1946cb307 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -460,7 +460,15 @@"createNewProject": "Create new project","deleteFailed": "Delete failed","deleteProject": "Delete project",- "deleteProjectBoardNote": "Its board goes with it; the images and videos it held return to Uncategorized.",+ "deleteProjectBoardsUnknown": "Its other boards could not be checked; they will be kept in the Library.",+ "deleteProjectCheckingBoards": "Checking its boards…",+ "deleteProjectDeleteBoards": "Delete its other boards too",+ "deleteProjectDeleteBoardsHint": "{{items}} return to Uncategorized.",+ "deleteProjectInboxNote": "Its inbox goes with it; the images and videos it held return to Uncategorized.",+ "deleteProjectItemCount_one": "{{count}} item",+ "deleteProjectItemCount_other": "{{count}} items",+ "deleteProjectKeepBoards": "Keep its other boards in the Library",+ "deleteProjectKeepBoardsHint": "{{boards}} stay where you can find them, with everything on them.","deleteProjectCardBody": "Delete \"{{name}}\"? The project is removed from the server permanently.","deleteProjectQuestion": "Delete project?","deleteProjectTabBody": "Delete \"{{name}}\"? The project and its saved copy on the server are removed permanently. To keep it in your library, close the tab instead.",@@ -3989,9 +3997,22 @@"boardCountsBreakdown": "{{media}} media, {{assets}} uploads","boardCreated": "Created board \"{{name}}\"","boardGroups": {- "boards": "Boards",- "byDate": "By Date"+ "byDate": "By Date",+ "library": "Library",+ "otherProjects": "Other projects"},+ "boardMoved": "Moved board \"{{name}}\" to {{destination}}",+ "changeBoard": "Change Board",+ "createBoardInLibrary": "Create a board in the Library",+ "createBoardInProject": "Create a board in this project",+ "createBoardNamedIn": "Create board \"{{name}}\" in {{destination}}",+ "inbox": "Inbox",+ "inboxOf": "{{project}} / Inbox",+ "libraryBoardsHint": "Boards here are available in every project.",+ "moveBoard": "Move to…",+ "projectBoardsHint": "Boards you create here belong to this project.",+ "removeFromBoard": "Remove from Board",+ "unknownProject": "Another project","boardItemCounts": "{{images}} · {{videos}} · {{assets}}","boardName": "Board name","boardRenamed": "Renamed board to \"{{name}}\"",diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjsindex 15c542a5fb..7ff1d9bdaf 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs@@ -268,7 +268,7 @@ export const projectBoardId = (index) => `fixture-project-board-${ordinal(index,export const PROJECT_FILE_BOARD_ID = projectBoardId(1);-const buildBoard = (boardId, boardName, images, videos, createdAt) => {+const buildBoard = (boardId, boardName, images, videos, createdAt, projectId = null) => {const boardImages = images.filter((image) => image.board_id === boardId);const boardVideos = videos.filter((video) => video.board_id === boardId);const cover = [@@ -303,11 +303,16 @@ const buildBoard = (boardId, boardName, images, videos, createdAt) => {created_at: createdAt,image_count: boardImages.filter((image) => image.image_category === 'general').length,owner_username: null,+ // Membership, as the backend stores it: an inbox belongs to its project, a Library board to none.+ project_id: projectId,user_id: FIXTURE_USER_ID,video_count: boardVideos.length,};};+/** The project ids `createProjects` assigns, so boards can belong to them without the documents in hand. */+export const fixtureProjectId = (index) => `fixture-project-${ordinal(index, 3)}`;+const createBoards = (images, videos, projectCount) => [...range(10, (index) =>buildBoard(@@ -319,7 +324,25 @@ const createBoards = (images, videos, projectCount) => [)),...range(projectCount, (index) =>- buildBoard(projectBoardId(index), `Fixture Project ${ordinal(index, 3)}`, images, videos, timestampAt(index))+ buildBoard(+ projectBoardId(index),+ `Fixture Project ${ordinal(index, 3)}`,+ images,+ videos,+ timestampAt(index),+ fixtureProjectId(index)+ )+ ),+ // The first two projects also hold ordinary boards, so a project section has more than its inbox to show.+ ...range(Math.min(projectCount, 2), (index) =>+ buildBoard(+ `fixture-member-board-${ordinal(index, 2)}`,+ index === 0 ? 'Façade variants' : 'Site plan refs',+ images,+ videos,+ timestampAt(index + 100),+ fixtureProjectId(index)+ )),];@@ -609,7 +632,7 @@ const createWorkflowDocument = ({ description, graphId, index, name, workflowNod* `projectGraph`, which the project-file journey loads, exports and imports through the migration boundary.*/const createProjectDocument = ({ index, layers = [], workflowNodes = [] }) => {- const id = `fixture-project-${ordinal(index, 3)}`;+ const id = fixtureProjectId(index);const graphId = `${id}-graph`;const primaryWorkflow = createWorkflowDocument({description: index === 0 ? 'Representative 100-node workflow.' : '',diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex 4cf34e836e..9e2923c521 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -608,26 +608,34 @@ test('the representative video accessibility journey owns the only generated-medassert.match(source, /INVOKEAI_ACCESSIBILITY_JOURNEY/);});-test('project boards are owned, protected from the generic board routes, and enumerable', async () => {+test('project inboxes are protected from the generic board routes, and members are not', async () => {await withRepresentativeBackend(async (backend) => {const projects = await getJson(backend, '/api/v1/projects/');const project = projects.find((entry) => entry.project_id === 'fixture-project-002');- // Every project owns exactly one board, and no two share one.+ // Every project has exactly one inbox, and no two share one.assert.equal(new Set(projects.map((entry) => entry.board_id)).size, projects.length);assert.ok(project.board_id);const board = await getJson(backend, `/api/v1/boards/${project.board_id}`);assert.equal(board.project_id, project.project_id);+ assert.equal(board.is_inbox, true);assert.equal(board.board_name, project.name);- // An unclaimed board omits the key entirely, matching the backend's null-excluding DTO.+ // A Library board belongs to no project and is nobody's inbox.const plainBoard = await getJson(backend, '/api/v1/boards/fixture-board-02');- assert.equal('project_id' in plainBoard, false);+ assert.equal(plainBoard.project_id, null);+ assert.equal(plainBoard.is_inbox, false);- // The generic routes refuse a claimed board; only the project APIs may touch it.+ // A member is an ordinary board that happens to belong to the project.+ const member = await getJson(backend, '/api/v1/boards/fixture-member-board-02');+ assert.equal(member.project_id, project.project_id);+ assert.equal(member.is_inbox, false);++ // The generic routes refuse to rename, move or delete an inbox; only the project APIs may touch it.for (const [method, path, body] of [['PATCH', `/api/v1/boards/${project.board_id}`, { board_name: 'Renamed' }],+ ['PATCH', `/api/v1/boards/${project.board_id}`, { project_id: null }],['DELETE', `/api/v1/boards/${project.board_id}?include_images=true`, undefined],]) {const refused = await fetch(`${backend.origin}${path}`, {@@ -649,6 +657,54 @@ test('project boards are owned, protected from the generic board routes, and enu});});+test('boards are created in a project or the Library, move between them, and follow a deleted project', async () => {+ await withRepresentativeBackend(async (backend) => {+ const projects = await getJson(backend, '/api/v1/projects/');+ const [first, second] = projects;++ const created = await getJson(backend, `/api/v1/boards/?board_name=Kitchen&project_id=${first.project_id}`, {+ method: 'POST',+ });+ assert.equal(created.project_id, first.project_id);+ assert.equal(created.is_inbox, false);+ assert.equal(+ (+ await fetch(`${backend.origin}/api/v1/boards/?board_name=Nowhere&project_id=no-such-project`, {+ method: 'POST',+ })+ ).status,+ 404+ );++ const move = (projectId) =>+ getJson(backend, `/api/v1/boards/${created.board_id}`, {+ body: JSON.stringify({ project_id: projectId }),+ headers: { 'content-type': 'application/json' },+ method: 'PATCH',+ });+ assert.equal((await move(second.project_id)).project_id, second.project_id);+ assert.equal((await move(null)).project_id, null);+ // A rename without the key leaves membership alone.+ const renamed = await getJson(backend, `/api/v1/boards/${created.board_id}`, {+ body: JSON.stringify({ board_name: 'Pantry' }),+ headers: { 'content-type': 'application/json' },+ method: 'PATCH',+ });+ assert.equal(renamed.project_id, null);+ assert.equal(renamed.board_name, 'Pantry');++ // Deleting a project releases its other boards by default, and takes them when asked.+ await move(second.project_id);+ await fetch(`${backend.origin}/api/v1/projects/${second.project_id}`, { method: 'DELETE' });+ assert.equal((await getJson(backend, `/api/v1/boards/${created.board_id}`)).project_id, null);+ assert.equal((await fetch(`${backend.origin}/api/v1/boards/${second.board_id}`)).status, 404);++ await fetch(`${backend.origin}/api/v1/projects/${first.project_id}?boards=delete`, { method: 'DELETE' });+ assert.equal((await fetch(`${backend.origin}/api/v1/boards/fixture-member-board-01`)).status, 404);+ assert.equal((await fetch(`${backend.origin}/api/v1/boards/${created.board_id}`)).status, 200);+ });+});+test('the board snapshot lists only what the gallery would show on a project board', 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 b81bde35dd..a9e98cbe0f 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -524,8 +524,8 @@ const listVideos = (state, url) => {};};-/** The project that owns this board, if any. Derived, exactly as the backend derives it. */-const projectIdForBoard = (state, boardId) =>+/** The project this board is the inbox of, if any. Derived from `projects.board_id`, as the backend derives it. */+const inboxProjectIdForBoard = (state, boardId) =>[...state.projects.values()].find((project) => project.board_id === boardId)?.project_id ?? null;/** Match /board-snapshot visibility and ordering: exclude intermediate/other items, sort by kind then name. */@@ -585,7 +585,7 @@ const boardDto = (state, board) => {right.name.localeCompare(left.name))[0];- const projectId = projectIdForBoard(state, board.board_id);+ const projectId = board.project_id ?? null;return {...board,@@ -593,8 +593,9 @@ const boardDto = (state, board) => {cover_image_name: cover?.kind === 'image' ? cover.name : null,cover_video_name: cover?.kind === 'video' ? cover.name : null,image_count: images.filter((image) => image.image_category === 'general').length,- is_inbox: projectId !== null,- ...(projectId === null ? {} : { project_id: projectId }),+ is_inbox: inboxProjectIdForBoard(state, board.board_id) !== null,+ // Membership is stored on the board; the backend sends null for a Library board.+ project_id: projectId,video_count: videos.length,};};@@ -909,6 +910,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {const name = requested.name ?? `Project Name #${projectNumber}`;// Adopting a prepopulated board makes project creation the import commit point.+ const projectId = requested.project_id ?? `mock-project-${projectNumber}`;let boardId = requested.board_id ?? null;if (boardId === null) {boardId = `mock-project-board-${projectNumber}`;@@ -920,6 +922,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {created_at: now,deleted_at: null,owner_username: null,+ project_id: projectId,updated_at: now,user_id: MOCK_USER_ID,});@@ -928,10 +931,15 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {if (!board) {return json(404, { detail: 'Board not found' });}- if (board.board_visibility !== 'private' || projectIdForBoard(state, boardId) !== null) {+ if (+ board.board_visibility !== 'private' ||+ inboxProjectIdForBoard(state, boardId) !== null ||+ (board.project_id ?? null) !== null+ ) {return json(409, { detail: 'Board is not available to be claimed by a project' });}board.board_name = name;+ board.project_id = projectId;board.updated_at = now;}@@ -947,7 +955,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {data: requested.data ?? {},minimum_canvas_schema_version: minimum,name,- project_id: requested.project_id ?? `mock-project-${projectNumber}`,+ project_id: projectId,revision: 1,updated_at: now,};@@ -1021,16 +1029,33 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {}if (method === 'DELETE') {if (project) {+ const boardsMode = url.searchParams.get('boards') ?? 'release';+ if (boardsMode !== 'release' && boardsMode !== 'delete') {+ return json(422, { detail: 'boards must be release or delete' });+ }state.projects.delete(projectId);- // The board goes with the project; its media survives as uncategorized.- state.boards.delete(project.board_id);+ // The inbox goes with the project; the other boards are released or go too. Media survives as+ // uncategorized either way.+ const removedBoardIds = new Set([project.board_id]);+ for (const board of state.boards.values()) {+ if ((board.project_id ?? null) === projectId && board.board_id !== project.board_id) {+ if (boardsMode === 'delete') {+ removedBoardIds.add(board.board_id);+ } else {+ board.project_id = null;+ }+ }+ }+ for (const boardId of removedBoardIds) {+ state.boards.delete(boardId);+ }for (const image of state.images.values()) {- if (image.board_id === project.board_id) {+ if (removedBoardIds.has(image.board_id)) {image.board_id = null;}}for (const video of state.videos.values()) {- if (video.board_id === project.board_id) {+ if (removedBoardIds.has(video.board_id)) {video.board_id = null;}}@@ -1473,6 +1498,10 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {if (method === 'POST') {const now = timestamp(state);const boardId = `mock-board-${state.nextBoardNumber}`;+ const projectId = url.searchParams.get('project_id');+ if (projectId !== null && !state.projects.has(projectId)) {+ return json(404, { detail: 'Project not found' });+ }const board = {archived: false,board_id: boardId,@@ -1481,6 +1510,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {created_at: now,deleted_at: null,owner_username: null,+ project_id: projectId,updated_at: now,user_id: MOCK_USER_ID,};@@ -1505,15 +1535,25 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {}if (method === 'PATCH') {const changes = await readJsonBody(request);+ const moves = Object.hasOwn(changes, 'project_id');- // A project's board takes its name, archived state and visibility from the project.+ // An inbox takes its name, archived state and visibility from the project and cannot move.if (- projectIdForBoard(state, boardId) !== null &&+ inboxProjectIdForBoard(state, boardId) !== null &&(changes.board_name !== undefined ||changes.archived !== undefined ||- changes.board_visibility !== undefined)+ changes.board_visibility !== undefined ||+ moves)) {- return json(409, { detail: 'This board belongs to a project' });+ return json(409, { detail: "This board is the project's inbox" });+ }+ const nextProjectId = moves ? changes.project_id : (board.project_id ?? null);+ const nextVisibility = changes.board_visibility ?? board.board_visibility;+ if (nextProjectId !== null && nextVisibility !== 'private') {+ return json(409, { detail: 'Boards in a project must be private and unshared' });+ }+ if (nextProjectId !== null && !state.projects.has(nextProjectId)) {+ return json(404, { detail: 'Project not found' });}for (const key of ['archived', 'board_name', 'board_visibility', 'cover_image_name']) {@@ -1521,14 +1561,17 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {board[key] = changes[key];}}+ if (moves) {+ board.project_id = nextProjectId;+ }board.updated_at = timestamp(state);return json(201, boardDto(state, board));}if (method === 'DELETE') {- if (projectIdForBoard(state, boardId) !== null) {+ if (inboxProjectIdForBoard(state, boardId) !== null) {// Refused before any media is touched — the whole point of the ordering.- return json(409, { detail: 'This board belongs to a project' });+ return json(409, { detail: "This board is the project's inbox" });}const includeImages = url.searchParams.get('include_images') === 'true';diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex 979f95314d..61f6480e2c 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -278,11 +278,12 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryawait exportPage.goto(`${origin}${sourceProjectPath}`, { waitUntil: 'domcontentloaded' });await exportPage.getByRole('main', { exact: true, name: sourceProjectName }).waitFor();- const selectedBoardRow = exportPage.locator('button[aria-current="true"]').filter({ hasText: sourceProjectName });+ // The project's inbox is selected and shown as "Inbox" under the project's own heading.+ const selectedBoardRow = exportPage.locator('button[aria-current="true"]').filter({ hasText: 'Inbox' });await selectedBoardRow.first().waitFor();- await exportPage.getByRole('button', { exact: true, name: `Board actions for ${sourceProjectName}` }).click();+ await exportPage.getByRole('button', { exact: true, name: 'Board actions for Inbox' }).click();await exportPage.getByRole('menuitem', { exact: true, name: 'Export project (.invk)' }).waitFor();await exportPage.getByRole('menuitem', { name: /^Download Board/ }).waitFor();await exportPage.keyboard.press('Escape');diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex 2f2d7107c9..64d058581d 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -1,19 +1,34 @@import type { GalleryItemRef } from '@features/gallery/contracts';-import type { GalleryUiAdapter } from '@features/gallery/react';+import type { GalleryProjectRef, GalleryUiAdapter } from '@features/gallery/react';+import type { ProjectLibrarySnapshot } from '@workbench/projects/library';import type { ReactNode } from 'react';import { GalleryUiProvider } from '@features/gallery/react';import { useMountEffect } from '@platform/react/useMountEffect';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { useProjectLibrarySelector } from '@workbench/projects/library';import { useExportLibraryProject } from '@workbench/projects/useProjectFileActions';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { useLivePreviewFollow } from '@workbench/widgets/preview/livePreviewFollow';import { getProjectWidgetInstance } from '@workbench/widgetState';-import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';+import {+ useActiveProjectSelector,+ useWorkbenchCommands,+ useWorkbenchInternalStore,+ useWorkbenchPersistenceService,+ useWorkbenchQueries,+} from '@workbench/WorkbenchContext';import { lazy, useMemo } from 'react';const EMPTY_WIDGET_VALUES: Record<string, unknown> = Object.freeze({});+const selectGalleryProjects = (snapshot: ProjectLibrarySnapshot): GalleryProjectRef[] =>+ snapshot.summaries.map((summary) => ({ id: summary.id, name: summary.name }));++const areGalleryProjectsEqual = (left: GalleryProjectRef[], right: GalleryProjectRef[]): boolean =>+ left.length === right.length &&+ left.every((project, index) => project.id === right[index]?.id && project.name === right[index]?.name);+// Loaded on first reveal; the label cache is not part of the editor's initial graph.const getItemLabel = (item: GalleryItemRef): Promise<string | null> =>import('@workbench/image-map/imageLabelCache')@@ -45,6 +60,11 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })const accountScope = captureAccountScope();const exportProject = useExportLibraryProject();const openWorkbenchWidget = useOpenWorkbenchWidget();+ // Only what the gallery needs to label other projects' boards, compared structurally: every autosave ack and+ // library refresh rebuilds the summaries, and the gallery must not re-render for cover or timestamp churn.+ const projects = useProjectLibrarySelector(selectGalleryProjects, areGalleryProjectsEqual);+ const store = useWorkbenchInternalStore();+ const persistence = useWorkbenchPersistenceService();// Preload row dependencies here to avoid a second fetch wave after the gallery mounts.useMountEffect(() => {void import('./GalleryImageActionsBridge');@@ -82,6 +102,16 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })notifications,projectId,projectName,+ projects,+ // A board created in or moved into a project needs the project to exist on the server, which a new project+ // does only after its first save; the canvas path makes the same request before its first write.+ ensureProjectOnServer: async () => {+ const project = store.getState().projects.find((candidate) => candidate.id === projectId);++ if (project) {+ await persistence.ensureProjectOnServer(project);+ }+ },widgets: {openGallery: () => openWorkbenchWidget('gallery').ok,patchGalleryValues: (values) => widgets.patchValues('gallery', values),@@ -98,9 +128,12 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })livePreview,notifications,openWorkbenchWidget,+ persistence,projectId,projectName,+ projects,queries,+ store,widgets,]);diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 2bf0048656..0d1e16a746 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -11,7 +11,12 @@ export type {GeneratedImageContract,GeneratedVideoContract,} from './core/types';-export { getGalleryBoardLabel, type GalleryBoardTranslate } from './core/boardLabels';+export {+ getGalleryBoardDestinationGroups,+ getGalleryBoardLabel,+ type GalleryBoardDestinationGroup,+ type GalleryBoardTranslate,+} from './core/boardLabels';export { normalizeGalleryImage } from './core/image';export {assertNeverGalleryItem,diff --git a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.tsindex 9ed35cb641..14b61c6c17 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';import type { GalleryBoard } from './types';-import { getGalleryBoardLabel } from './boardLabels';+import { getGalleryBoardDestinationGroups, getGalleryBoardLabel, getGalleryProjectGroupLabel } from './boardLabels';const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({archived: false,@@ -18,7 +18,16 @@ const createBoard = (overrides: Partial<GalleryBoard> = {}): GalleryBoard => ({...overrides,});-const t = (key: string) => (key === 'widgets.gallery.uncategorized' ? 'Uncategorized' : key);+const t = (key: string) =>+ key === 'widgets.gallery.uncategorized'+ ? 'Uncategorized'+ : key === 'widgets.gallery.inbox'+ ? 'Inbox'+ : key === 'widgets.gallery.boardGroups.library'+ ? 'Library'+ : key === 'widgets.gallery.unknownProject'+ ? 'Another project'+ : key;describe('getGalleryBoardLabel', () => {it('uses the stored name for real boards', () => {@@ -29,3 +38,61 @@ describe('getGalleryBoardLabel', () => {expect(getGalleryBoardLabel(createBoard({ kind: 'uncategorized', name: '' }), t)).toBe('Uncategorized');});});++describe('getGalleryBoardLabel for inboxes', () => {+ it('calls every inbox Inbox, whatever name the server stores it under', () => {+ expect(getGalleryBoardLabel(createBoard({ isInbox: true, name: 'Mahogany House', projectId: 'p1' }), t)).toBe(+ 'Inbox'+ );+ });+});++describe('getGalleryProjectGroupLabel', () => {+ const inbox = createBoard({ id: 'inbox', isInbox: true, name: 'Stored name', projectId: 'p2' });++ it('prefers the account project list, which follows a rename at once', () => {+ expect(getGalleryProjectGroupLabel('p2', [inbox], new Map([['p2', 'Renamed']]), t)).toBe('Renamed');+ });++ it('falls back to the inbox stored name, then to a stand-in', () => {+ expect(getGalleryProjectGroupLabel('p2', [inbox], new Map(), t)).toBe('Stored name');+ expect(getGalleryProjectGroupLabel('p2', [createBoard({ projectId: 'p2' })], new Map(), t)).toBe('Another project');+ });+});++describe('getGalleryBoardDestinationGroups', () => {+ const boards = [+ createBoard({ id: 'zebra-member', name: 'Stripes', projectId: 'pz' }),+ createBoard({ id: 'mine-member', name: 'Façades', projectId: 'p1' }),+ createBoard({ id: 'cats', name: 'Cats' }),+ createBoard({ id: 'zebra', isInbox: true, name: 'Zebra', projectId: 'pz' }),+ createBoard({ id: 'mine', isInbox: true, name: 'Mine', projectId: 'p1' }),+ createBoard({ id: 'apple-member', name: 'Pips', projectId: 'pa' }),+ ];+ const groupsOf = (projectId: string | null, projectNames = new Map<string, string>()) =>+ getGalleryBoardDestinationGroups({ boards, projectId, projectName: 'Mine', projectNames, t }).map((group) => [+ group.label,+ group.boards.map((board) => board.id),+ ]);++ it('lists the open project with its inbox first, then the Library, then other projects by name', () => {+ expect(groupsOf('p1', new Map([['pa', 'Apple']]))).toEqual([+ ['Mine', ['mine', 'mine-member']],+ ['Library', ['cats']],+ ['Apple', ['apple-member']],+ ['Zebra', ['zebra', 'zebra-member']],+ ]);+ });++ it('drops empty tiers and treats every project as other where none is open', () => {+ expect(groupsOf(null)).toEqual([+ ['Library', ['cats']],+ ['Another project', ['apple-member']],+ ['Mine', ['mine', 'mine-member']],+ ['Zebra', ['zebra', 'zebra-member']],+ ]);+ expect(+ getGalleryBoardDestinationGroups({ boards: [], projectId: 'p1', projectName: 'Mine', projectNames: new Map(), t })+ ).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.ts b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.tsindex 8ba9b97735..52f1daf43b 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/boardLabels.ts@@ -2,6 +2,92 @@ import type { GalleryBoard } from './types';export type GalleryBoardTranslate = (key: string) => string;-/** Resolves the localized display label for synthesized and stored boards. */+/**+ * Resolves the localized display label for synthesized and stored boards. An inbox is labelled as such: every+ * surface that lists it also names its project, as a section, a group or the open project itself.+ */export const getGalleryBoardLabel = (board: GalleryBoard, t: GalleryBoardTranslate): string =>- board.kind === 'uncategorized' ? t('widgets.gallery.uncategorized') : board.name;+ board.kind === 'uncategorized'+ ? t('widgets.gallery.uncategorized')+ : board.isInbox+ ? t('widgets.gallery.inbox')+ : board.name;++/** Inbox first, as the fixed row of its tier. */+export const inboxFirst = (boards: readonly GalleryBoard[]): GalleryBoard[] => [+ ...boards.filter((board) => board.isInbox),+ ...boards.filter((board) => !board.isInbox),+];++/**+ * What a group of another project's boards is headed by. The account's project list is authoritative — it follows a+ * rename at once, where the listing's inbox name lags until boards refetch — then the inbox's stored name, which the+ * server keeps equal to the project's, then a stand-in for a project this account cannot see.+ */+export const getGalleryProjectGroupLabel = (+ projectId: string,+ boards: readonly GalleryBoard[],+ projectNames: ReadonlyMap<string, string>,+ t: GalleryBoardTranslate+): string =>+ projectNames.get(projectId) ?? boards.find((board) => board.isInbox)?.name ?? t('widgets.gallery.unknownProject');++export interface GalleryBoardDestinationGroup {+ boards: GalleryBoard[];+ id: string;+ label: string;+}++/**+ * The tiers a flat "move to board" menu offers, in the panel's order: the open project, the Library, then each+ * other project under its own name. Empty groups are dropped so a menu never shows a bare heading.+ */+export const getGalleryBoardDestinationGroups = ({+ boards,+ projectId,+ projectName,+ projectNames,+ t,+}: {+ boards: readonly GalleryBoard[];+ projectId: string | null;+ projectName: string;+ projectNames: ReadonlyMap<string, string>;+ t: GalleryBoardTranslate;+}): GalleryBoardDestinationGroup[] => {+ const otherProjects = new Map<string, GalleryBoard[]>();++ for (const board of boards) {+ if (board.projectId !== null && board.projectId !== projectId) {+ const group = otherProjects.get(board.projectId);++ if (group) {+ group.push(board);+ } else {+ otherProjects.set(board.projectId, [board]);+ }+ }+ }++ const groups: GalleryBoardDestinationGroup[] = [+ {+ boards: inboxFirst(boards.filter((board) => projectId !== null && board.projectId === projectId)),+ id: 'project',+ label: projectName,+ },+ {+ boards: boards.filter((board) => board.projectId === null),+ id: 'library',+ label: t('widgets.gallery.boardGroups.library'),+ },+ ...[...otherProjects]+ .map(([otherProjectId, group]) => ({+ boards: inboxFirst(group),+ id: `project:${otherProjectId}`,+ label: getGalleryProjectGroupLabel(otherProjectId, group, projectNames, t),+ }))+ .sort((left, right) => left.label.localeCompare(right.label)),+ ];++ return groups.filter((group) => group.boards.length > 0);+};diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 71849cc231..1abc29a150 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -5,7 +5,7 @@ export type GalleryThumbnailFit = 'square' | 'aspect';export type GalleryPaginationMode = 'infinite' | 'paginated';/** The collapsible groups in the board panel, in render order. */-export const GALLERY_BOARD_SECTION_IDS = ['boards', 'dates', 'archived'] as const;+export const GALLERY_BOARD_SECTION_IDS = ['project', 'library', 'other-projects', 'dates', 'archived'] as const;export type GalleryBoardSectionId = (typeof GALLERY_BOARD_SECTION_IDS)[number];diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.tsindex bb229bb7f0..5561fb32e1 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts@@ -35,6 +35,12 @@ export interface GeneratedVideoContract {export type GalleryView = 'images' | 'assets';+/** What the gallery needs to know about a project to group its boards: the id boards carry, and a name. */+export interface GalleryProjectRef {+ id: string;+ name: string;+}+export type GalleryOrderDir = 'ASC' | 'DESC';export type GalleryBoardOrderBy = 'created_at' | 'board_name';diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.tsindex a6c7aa609a..2d8955fcbb 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts@@ -18,6 +18,7 @@ vi.mock('@platform/transport/http', () => ({import {addImagesToGalleryBoard,+ createGalleryBoard,deleteGalleryBoard,deleteGalleryImages,downloadGalleryArchive,@@ -36,6 +37,7 @@ import {removeImagesFromGalleryBoard,starGalleryImages,unstarGalleryImages,+ updateGalleryBoard,uploadGalleryImage,uploadGalleryVideo,} from './backend';@@ -942,3 +944,42 @@ describe('fetchImageIndexAvailability', () => {await expect(fetchImageIndexAvailability(new AbortController().signal)).resolves.toEqual(availability);});});++describe('board membership transport', () => {+ const dto = { archived: false, asset_count: 0, board_id: 'b1', board_name: 'B', image_count: 0, is_inbox: false };++ beforeEach(() => {+ accountLifecycle.activate('user-a');+ mocks.apiFetchJson.mockReset();+ mocks.apiFetchJson.mockResolvedValue(dto);+ });++ it('creates in a project only when one is named', async () => {+ await createGalleryBoard('B');+ await createGalleryBoard('B', 'p1');++ expect(mocks.apiFetchJson.mock.calls.map(([url]) => url)).toEqual([+ '/api/v1/boards/?board_name=B',+ '/api/v1/boards/?board_name=B&project_id=p1',+ ]);+ });++ it('sends an explicit null to move a board to the Library, and no key to leave it alone', async () => {+ await updateGalleryBoard('b1', { projectId: null });+ await updateGalleryBoard('b1', { projectId: 'p2' });+ await updateGalleryBoard('b1', { name: 'Renamed' });++ const bodies = mocks.apiFetchJson.mock.calls.map(([, init]) => JSON.parse((init as { body: string }).body));+ expect(bodies[0]).toEqual({ project_id: null });+ expect(bodies[1]).toEqual({ project_id: 'p2' });+ expect(bodies[2]).toEqual({ board_name: 'Renamed' });+ });++ it('reads membership and the inbox flag off the wire', async () => {+ mocks.apiFetchJson.mockResolvedValueOnce({ ...dto, is_inbox: true, project_id: 'p1' });++ const board = await createGalleryBoard('B', 'p1');++ expect(board).toMatchObject({ id: 'b1', isInbox: true, projectId: 'p1' });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 4335e75f9b..eb3f57f68d 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -1032,20 +1032,31 @@ export const getGalleryImageMetadata = async (return body && typeof body === 'object' && !Array.isArray(body) ? (body as GalleryImageMetadata) : null;};-export const createGalleryBoard = async (boardName: string, signal?: AbortSignal): Promise<GalleryBoard> => {- const query = toSearchParams({ board_name: boardName });+/** `projectId` null creates in the Library; a project must be the caller's own, else the backend answers 404. */+export const createGalleryBoard = async (+ boardName: string,+ projectId: string | null = null,+ signal?: AbortSignal+): Promise<GalleryBoard> => {+ const query = toSearchParams({ board_name: boardName, ...(projectId === null ? {} : { project_id: projectId }) });const body = await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/?${query}`, { method: 'POST', signal });return mapBoard(body);};+/** `projectId` moves the board: a project id, or null for the Library. Undefined, like the others, means unchanged. */export const updateGalleryBoard = async (boardId: string,- changes: { name?: string; archived?: boolean },+ changes: { name?: string; archived?: boolean; projectId?: string | null },signal?: AbortSignal): Promise<GalleryBoard> => {const body = await apiFetchJson<BackendBoardDTO>(`/api/v1/boards/${encodeURIComponent(boardId)}`, {- body: JSON.stringify({ archived: changes.archived, board_name: changes.name }),+ // JSON.stringify drops undefined keys, which is what leaves a field unchanged; an explicit null must survive.+ body: JSON.stringify({+ archived: changes.archived,+ board_name: changes.name,+ ...(changes.projectId !== undefined ? { project_id: changes.projectId } : {}),+ }),method: 'PATCH',signal,});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 268f219303..08ba7a9001 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -345,7 +345,7 @@ const isGalleryBoardsData = (value: unknown): value is GalleryBoard[] =>export const patchGalleryBoardCaches = (client: QueryClient,boardId: string,- changes: Partial<Pick<GalleryBoard, 'archived' | 'name'>>+ changes: Partial<Pick<GalleryBoard, 'archived' | 'name' | 'projectId'>>): (() => void) => {const owner = captureAccountScope();const rollbackEntries: BoardCacheRollbackEntry[] = [];diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.tsindex e6fe172b28..0b342973de 100644--- a/invokeai/frontend/webv2/src/features/gallery/react.ts+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts@@ -8,4 +8,5 @@ export {type GalleryItemContextMenuTarget,type GalleryUiAdapter,} from './ui/GalleryUiContext';+export type { GalleryProjectRef } from './core/types';export { useGalleryUploadAction } from './ui/useGalleryUploadAction';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardCover.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardCover.tsxindex 0ee21b84ab..80b830fb6c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardCover.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardCover.tsx@@ -1,7 +1,7 @@import type { GalleryBoard } from '@features/gallery/core/types';import { Flex, Icon, Image } from '@chakra-ui/react';-import { CalendarIcon, ImageIcon, PlayIcon, type LucideIcon } from 'lucide-react';+import { CalendarIcon, ImageIcon, InboxIcon, PlayIcon, type LucideIcon } from 'lucide-react';/** Square swatch shown at the start of every board row and in the stacked header. */export const BoardCoverIcon = ({ icon }: { icon: LucideIcon }) => (@@ -54,5 +54,5 @@ export const BoardCover = ({ board }: { board: GalleryBoard }) => {);}- return <BoardCoverIcon icon={board.kind === 'date' ? CalendarIcon : ImageIcon} />;+ return <BoardCoverIcon icon={board.kind === 'date' ? CalendarIcon : board.isInbox ? InboxIcon : ImageIcon} />;};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsxindex 260349c88b..e637f105bd 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.browser.test.tsx@@ -1,4 +1,6 @@-/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */+import type { GalleryBoard } from '@features/gallery/core/types';+import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { act } from 'react';@@ -28,6 +30,8 @@ vi.mock('react-i18next', () => ({'widgets.gallery.downloadBoardWithOmission': `Download Board (${String(values?.count)} video omitted)`,'widgets.gallery.imageCount': `${String(values?.count)} images`,'widgets.gallery.videoCount': `${String(values?.count)} videos`,+ 'widgets.gallery.boardGroups.library': 'Library',+ 'widgets.gallery.moveBoard': 'Move to…',};return messages[key] ?? key;@@ -54,6 +58,7 @@ const context = {archiveBoard: vi.fn(),deleteBoard: vi.fn(),downloadBoard: vi.fn(),+ moveBoard: vi.fn(),renameBoard: vi.fn(),updateSettings: vi.fn(),},@@ -61,6 +66,12 @@ const context = {projectBoardId: null,settings: { autoAddBoardId: 'follow' },},+ projectId: 'p1',+ projectName: 'Mahogany House',+ projectNames: new Map([+ ['p1', 'Mahogany House'],+ ['p2', 'Harbor Tower'],+ ]),} as unknown as GalleryWidgetContextValue;const targetContext = {...context,@@ -141,3 +152,70 @@ it('hands results back to the selected board from the auto-add board itself', asexpect(context.actions.updateSettings).toHaveBeenLastCalledWith({ autoAddBoardId: 'follow' });});++const renderMenuFor = async (menuBoard: GalleryBoard) => {+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <GalleryWidgetContext value={context}>+ <GalleryBoardMenu target={{ board: menuBoard, x: 20, y: 20 }} onClose={noop} />+ </GalleryWidgetContext>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+};++const menuItemLabels = () =>+ Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).map((item) => item.textContent);++it('offers every tier but the one the board is in, and moves it there', async () => {+ await renderMenuFor({ ...board, projectId: 'p1' } as GalleryBoard);++ const trigger = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(+ (element) => element.textContent === 'Move to…'+ )!;+ await act(() => userEvent.click(trigger));++ await vi.waitFor(() => {+ expect(menuItemLabels()).toContain('Harbor Tower');+ });+ // In a project: the Library and the other projects, never the project it is already in.+ expect(+ menuItemLabels().filter((label) => label === 'Library' || label === 'Harbor Tower' || label === 'Mahogany House')+ ).toEqual(['Library', 'Harbor Tower']);++ const library = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(+ (element) => element.textContent === 'Library'+ )!;+ await act(() => userEvent.click(library));++ expect(context.actions.moveBoard).toHaveBeenCalledExactlyOnceWith('board-1', null, 'Library');+});++it('offers a Library board the open project first', async () => {+ await renderMenuFor(board);++ const trigger = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(+ (element) => element.textContent === 'Move to…'+ )!;+ await act(() => userEvent.click(trigger));++ await vi.waitFor(() => {+ expect(menuItemLabels()).toContain('Harbor Tower');+ });+ expect(+ menuItemLabels().filter((label) => label === 'Library' || label === 'Harbor Tower' || label === 'Mahogany House')+ ).toEqual(['Mahogany House', 'Harbor Tower']);+});++it('leaves an inbox with only the actions its project does not own', async () => {+ await renderMenuFor({ ...board, isInbox: true, projectId: 'p1' } as GalleryBoard);++ const labels = menuItemLabels();++ expect(labels).toContain('widgets.gallery.exportProjectFromBoard');+ expect(labels).not.toContain('Move to…');+ expect(labels).not.toContain('Delete Board');+ expect(labels).not.toContain('widgets.gallery.renameBoard');+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsxindex 99f5e80991..5847a7c917 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx@@ -5,10 +5,13 @@ import { GALLERY_AUTO_ADD_FOLLOW } from '@features/gallery/core/settings';import { Button } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';import { MenuContent } from '@platform/ui/Menu';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import {ArchiveIcon,+ ChevronRightIcon,DownloadIcon,FileDownIcon,+ FolderInputIcon,PencilIcon,SquareArrowDownIcon,Trash2Icon,@@ -153,6 +156,7 @@ export const GalleryBoardMenu = ({{isManagedBoard && (<><BoardRenameMenuItem board={board} onRename={setRenameTarget} onRenameValue={setRenameValue} />+ <BoardMoveSubMenu board={board} /><BoardArchiveMenuItem archived={board.archived} boardId={board.id} /><Menu.Separator /><BoardDeleteMenuItem board={board} onDelete={setDeleteTarget} />@@ -262,6 +266,85 @@ const BoardExportProjectMenuItem = ({ board }: { board: GalleryBoard }) => {);};+const SUBMENU_POSITIONING = { gutter: 2, placement: 'right-start' } as const;++/**+ * Where a board can go: the Library, the open project, then the account's other projects by name — every tier+ * but the one it is in. Nested so the board menu keeps its one-level shape for the common actions.+ */+const BoardMoveSubMenu = ({ board }: { board: GalleryBoard }) => {+ const { t } = useTranslation();+ const { actions, projectId, projectName, projectNames } = useGalleryWidget();+ const destinations = useMemo(() => {+ const others = [...projectNames]+ .filter(([id]) => id !== projectId && id !== board.projectId)+ .map(([id, name]) => ({ id, label: name }))+ .sort((left, right) => left.label.localeCompare(right.label));++ return [+ ...(board.projectId !== null ? [{ id: null, label: t('widgets.gallery.boardGroups.library') }] : []),+ ...(board.projectId !== projectId ? [{ id: projectId, label: projectName }] : []),+ ...others,+ ];+ }, [board.projectId, projectId, projectName, projectNames, t]);++ if (destinations.length === 0) {+ return null;+ }++ return (+ <Menu.Root positioning={SUBMENU_POSITIONING}>+ <Menu.TriggerItem>+ <HStack gap="2" minW="0" w="full">+ <Icon as={FolderInputIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text flex="1" fontSize="md">+ {t('widgets.gallery.moveBoard')}+ </Text>+ <Icon as={ChevronRightIcon} boxSize="3" color="fg.subtle" flexShrink={0} />+ </HStack>+ </Menu.TriggerItem>+ <Portal>+ <Menu.Positioner>+ <MenuContent maxH="18rem" minW="12rem" overflowY="auto">+ {destinations.map((destination) => (+ <BoardMoveMenuItem+ key={destination.id ?? 'library'}+ boardId={board.id}+ destinationId={destination.id}+ label={destination.label}+ onMove={actions.moveBoard}+ />+ ))}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++const BoardMoveMenuItem = ({+ boardId,+ destinationId,+ label,+ onMove,+}: {+ boardId: string;+ destinationId: string | null;+ label: string;+ onMove: (boardId: string, projectId: string | null, destinationLabel: string) => Promise<void>;+}) => {+ const handleClick = useCallback(+ () => void onMove(boardId, destinationId, label),+ [boardId, destinationId, label, onMove]+ );++ return (+ <Menu.Item value={`move-board-to-${destinationId ?? 'library'}`} onClick={handleClick}>+ <MiddleTruncate fontSize="md" minW="0" text={label} />+ </Menu.Item>+ );+};+/** Sets the auto-add board; `follow` hands results back to the selected board. */const BoardAutoAddMenuItem = ({ boardId, label }: { boardId: string; label: string }) => {const { actions } = useGalleryWidget();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsxindex 6aa15e895c..c9de0d26fb 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx@@ -23,6 +23,7 @@ import {import { getBoardCounts } from './galleryStateView';export const GalleryBoardRow = ({+ accessibleName,board,isAutoAddTarget = false,isMenuOpen,@@ -31,6 +32,8 @@ export const GalleryBoardRow = ({onOpenMenu,onSelectBoard,}: {+ /** What assistive tech calls the row when its visible label alone is ambiguous, such as another project's Inbox. */+ accessibleName?: string;board: GalleryBoard;/** Results without a board of their own land here (the gallery is not following its selection). */isAutoAddTarget?: boolean;@@ -46,6 +49,7 @@ export const GalleryBoardRow = ({const { active } = useDndContext();const dragData = active?.data.current;const boardLabel = getGalleryBoardLabel(board, t);+ const spokenLabel = accessibleName ?? boardLabel;const canDropItems =acceptsGalleryItemMoves(board.kind) &&@@ -116,7 +120,7 @@ export const GalleryBoardRow = ({() =>onOpenMenu ? (<IconButton- aria-label={t('widgets.gallery.boardActionsForBoard', { name: boardLabel })}+ aria-label={t('widgets.gallery.boardActionsForBoard', { name: spokenLabel })}className="board-row-actions"flexShrink={0}// Its menu anchors to this button, so it must not fade out beneath it.@@ -132,7 +136,7 @@ export const GalleryBoardRow = ({<MoreVerticalIcon /></IconButton>) : null,- [boardLabel, handleActionsClick, isMenuOpen, onOpenMenu, stopPropagation, t]+ [handleActionsClick, isMenuOpen, onOpenMenu, spokenLabel, stopPropagation, t]);return (@@ -151,6 +155,7 @@ export const GalleryBoardRow = ({<GalleryBoardRowShellref={setNodeRef}actions={actions}+ ariaLabel={accessibleName}cover={cover}isDropTarget={canDropItems}isSelected={isSelected}@@ -166,11 +171,6 @@ export const GalleryBoardRow = ({</Badge></Tooltip>) : null}- {board.isInbox ? (- <Badge colorPalette={isSelected ? undefined : 'accent'} flexShrink={0} variant="subtle">- {t('common.project')}- </Badge>- ) : null}<Tooltip content={countsBreakdown}><Badge aria-label={countsBreakdown} flexShrink={0} fontVariantNumeric="tabular-nums" variant="subtle">{mediaCount} | {counts.assetCount}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSection.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSection.tsxindex e2ae48ff1b..047378256f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSection.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardSection.tsx@@ -15,6 +15,7 @@ const TRIGGER_HOVER_STYLES = { color: 'fg' } as const;export const GalleryBoardSection = ({action,children,+ count,isOpen,label,sectionId,@@ -22,6 +23,8 @@ export const GalleryBoardSection = ({}: {action?: ReactNode;children: ReactNode;+ /** Boards in the section; shown beside the label so a collapsed section still says what it holds. */+ count?: number;isOpen: boolean;label: string;sectionId: GalleryBoardSectionId;@@ -59,6 +62,11 @@ export const GalleryBoardSection = ({>{label}</Text>+ {count !== undefined ? (+ <Text as="span" color="fg.muted" fontSize="xs" fontVariantNumeric="tabular-nums" lineHeight="1">+ {count}+ </Text>+ ) : null}</Collapsible.Trigger>{action}</HStack>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsxindex 23bd6fdfa0..8b31c720a8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx@@ -19,23 +19,20 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({i18n: { language: 'en' },t: (key: string, values?: Record<string, unknown>) => {- if (key === 'widgets.gallery.createBoardNamed') {- return `Create board "${String(values?.name)}"`;- }- if (key === 'widgets.gallery.boardGroups.boards') {- return 'Your boards';- }- if (key === 'widgets.gallery.boardGroups.byDate') {- return 'Dates';- }- if (key === 'common.archived') {- return 'Archived';- }- if (key === 'widgets.gallery.uncategorized') {- return 'Uncategorized';- }-- return key;+ const messages: Record<string, string> = {+ 'common.archived': 'Archived',+ 'widgets.gallery.boardGroups.byDate': 'Dates',+ 'widgets.gallery.boardGroups.library': 'Library',+ 'widgets.gallery.boardGroups.otherProjects': 'Other projects',+ 'widgets.gallery.createBoardNamedIn': `Create board "${String(values?.name)}" in ${String(values?.destination)}`,+ 'widgets.gallery.inbox': 'Inbox',+ 'widgets.gallery.inboxOf': `${String(values?.project)} / Inbox`,+ 'widgets.gallery.libraryBoardsHint': 'Boards here are available in every project.',+ 'widgets.gallery.projectBoardsHint': 'Boards you create here belong to this project.',+ 'widgets.gallery.uncategorized': 'Uncategorized',+ };++ return messages[key] ?? key;},}),}));@@ -43,7 +40,6 @@ vi.mock('react-i18next', () => ({const actions = {createBoard: vi.fn(async () => {}),selectBoard: vi.fn(),- selectProjectBoard: vi.fn(async () => {}),updateSettings: vi.fn(),};@@ -54,8 +50,8 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'assetCount: 3,assetVideoCount: 0,imageCount: 50,- kind: 'board',isInbox: false,+ kind: 'board',projectId: null,videoCount: 0,...overrides,@@ -67,6 +63,10 @@ const boards = [createBoard({ assetCount: 1, id: 'none', imageCount: 1, kind: 'uncategorized', name: '' }),createBoard({ archived: true, id: 'gorl', imageCount: 1, name: 'GORL' }),createBoard({ id: 'by_date:2026-07-30', imageCount: 12, kind: 'date', name: 'Today' }),+ createBoard({ id: 'mine-member', imageCount: 7, name: 'Façades', projectId: 'p1' }),+ createBoard({ id: 'mine', imageCount: 142, isInbox: true, name: 'Mahogany House', projectId: 'p1' }),+ createBoard({ id: 'theirs-member', name: 'Stripes', projectId: 'p2' }),+ createBoard({ id: 'theirs', isInbox: true, name: 'Harbor Tower', projectId: 'p2' }),];const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateView =>@@ -79,7 +79,7 @@ const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateVieitems: [],page: 0,pendingPlaceholders: [],- projectBoardId: null,+ projectBoardId: 'mine',revealTargetPage: null,searchTerm: '',selectedBoardId: 'dogs',@@ -102,7 +102,9 @@ const renderPanel = async (gallery: GalleryStateView = createGallery()) => {boardsState: { error: null, isRetrying: false, retry: () => Promise.resolve(), status: 'ready' },gallery,itemActions,- projectName: 'Project',+ projectId: 'p1',+ projectName: 'Mahogany House',+ projectNames: new Map([['p2', 'Harbor Tower']]),} as unknown as GalleryWidgetContextValue;await act(() =>@@ -119,7 +121,34 @@ const renderPanel = async (gallery: GalleryStateView = createGallery()) => {};const getBoardRows = (): HTMLElement[] =>- Array.from(host?.querySelectorAll<HTMLElement>('[data-part="content"] button[type="button"]') ?? []);+ Array.from(+ host?.querySelectorAll<HTMLElement>(+ '[data-scope="collapsible"][data-part="content"] button[type="button"]:not(.board-row-actions)'+ ) ?? []+ );++/** Row labels in document order, keyed by the section heading each sits under. */+const getRowsBySection = (): Record<string, string[]> => {+ const result: Record<string, string[]> = {};++ host?.querySelectorAll<HTMLElement>('[data-scope="collapsible"][data-part="root"]').forEach((section) => {+ const label = (section.querySelector('[data-part="trigger"]')?.textContent ?? '').replace(/\d+$/, '');++ // The row buttons only: not the section's own trigger, nor a row's trailing ⋮ control.+ result[label] = Array.from(+ section.querySelectorAll<HTMLElement>(+ '[data-scope="collapsible"][data-part="content"] button[type="button"]:not(.board-row-actions)'+ )+ ).map((row) =>+ (row.textContent ?? '')+ .replace(/\d+ \| \d+$/, '')+ .replace('Alice Example', '')+ .trim()+ );+ });++ return result;+};const getSearchInput = (): HTMLInputElement => {const input = host?.querySelector<HTMLInputElement>('input');@@ -141,6 +170,13 @@ const type = async (input: HTMLInputElement, value: string) => {});};+const pressEnter = async (input: HTMLInputElement) => {+ await act(async () => {+ input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));+ await Promise.resolve();+ });+};+const click = async (element: HTMLElement) => {await act(async () => {element.click();@@ -148,9 +184,19 @@ const click = async (element: HTMLElement) => {});};+const getAddButton = (label: string): HTMLButtonElement => {+ const button = host?.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);++ if (!button) {+ throw new Error(`no "+" button labelled ${label}`);+ }++ return button;+};+beforeEach(() => {host = document.createElement('div');- host.style.cssText = 'height:480px;left:20px;position:fixed;top:20px;width:280px;';+ host.style.cssText = 'height:640px;left:20px;position:fixed;top:20px;width:520px;';document.body.append(host);root = createRoot(host);Object.values(actions).forEach((mock) => mock.mockClear());@@ -165,29 +211,40 @@ afterEach(async () => {});describe('GalleryBoardsPanel', () => {- it('renders boards, dates, and archived as separate sections', async () => {+ it('groups the open project, the Library, dates and archived boards into their own sections', async () => {await renderPanel();- const text = host?.textContent ?? '';+ const sections = getRowsBySection();- expect(text).toContain('Your boards');- expect(text).toContain('Dates');- expect(text).toContain('Archived');- expect(text).toContain('GORL');+ expect(Object.keys(sections)).toEqual(['Mahogany House', 'Library', 'Dates', 'Archived']);+ // The inbox is pinned first and shown as the Inbox, not under the project's name.+ expect(sections['Mahogany House']).toEqual(['Inbox', 'Façades']);+ expect(sections.Library).toEqual(['Uncategorized', 'dogs', 'Cats']);+ expect(sections.Archived).toEqual(['GORL']);});- /** Badges and protection follow every board's owner; only hoisting depends on the active project. */- it('marks a project inbox with a Project badge', async () => {- const ownedBoards = boards.map((board) =>- board.id === 'cats' ? { ...board, isInbox: true, projectId: 'p1' } : board- );+ it('lists other projects under their names only when they are shown', async () => {+ await renderPanel();+ expect(host?.textContent).not.toContain('Harbor Tower');- await renderPanel({ ...createGallery(), boards: ownedBoards, projectBoardId: 'cats' } as GalleryStateView);+ await renderPanel(createGallery({ showOtherProjectBoards: true }));- // The hoisted row shows the live project name, not the stored board name.- const projectRow = getBoardRows().find((row) => row.textContent?.includes('Project'));+ const sections = getRowsBySection();+ expect(Object.keys(sections)).toEqual(['Mahogany House', 'Library', 'Other projects', 'Dates', 'Archived']);+ expect(sections['Other projects']).toEqual(['Inbox', 'Stripes']);+ expect(host?.querySelector('[role="heading"][aria-level="4"]')?.textContent).toBe('Harbor Tower');+ });++ it('explains each tier once, while it holds only its fixed row', async () => {+ await renderPanel();+ expect(host?.textContent).not.toContain('belong to this project');+ expect(host?.textContent).not.toContain('available in every project');- expect(projectRow?.textContent).toContain('common.project');+ const onlyFixedRows = boards.filter((board) => board.isInbox || board.kind === 'uncategorized');+ await renderPanel({ ...createGallery(), boards: onlyFixedRows } as GalleryStateView);++ expect(host?.textContent).toContain('Boards you create here belong to this project.');+ expect(host?.textContent).toContain('Boards here are available in every project.');});it('shows media and asset counts together, so the row does not change meaning with the tab', async () => {@@ -216,14 +273,6 @@ describe('GalleryBoardsPanel', () => {expect(dogsRow?.textContent).not.toContain('Alice Example');});- it('shows the count for the active view and switches with the tab', async () => {- await renderPanel();- expect(host?.textContent).toContain('50');-- await renderPanel({ ...createGallery(), galleryView: 'assets' } as GalleryStateView);- expect(host?.textContent).toContain('3');- });-it('selects a board and clears the search on click', async () => {await renderPanel();await type(getSearchInput(), 'cat');@@ -236,17 +285,66 @@ describe('GalleryBoardsPanel', () => {expect(getSearchInput().value).toBe('');});- it('filters the list and offers to create an unmatched name', async () => {+ it('creates an unmatched name in the open project by default', async () => {await renderPanel();await type(getSearchInput(), 'birds');- expect(host?.textContent).toContain('Create board "birds"');+ const sections = getRowsBySection();+ expect(sections['Mahogany House']).toEqual(['Create board "birds" in Mahogany House']);+ expect(sections.Library).toEqual([]);- const createRow = getBoardRows().find((row) => row.textContent?.includes('Create board'));+ await click(getBoardRows().find((row) => row.textContent?.includes('Create board'))!);++ expect(actions.createBoard).toHaveBeenCalledWith('birds', 'p1');+ });- await click(createRow!);+ it('creates in the Library after its "+" chose that tier, and keeps that choice', async () => {+ await renderPanel();+ await click(getAddButton('widgets.gallery.createBoardInLibrary'));+ expect(document.activeElement).toBe(getSearchInput());++ await type(getSearchInput(), 'birds');+ expect(getRowsBySection().Library).toEqual(['Create board "birds" in Library']);++ await pressEnter(getSearchInput());+ expect(actions.createBoard).toHaveBeenCalledWith('birds', null);++ await type(getSearchInput(), 'fish');+ await pressEnter(getSearchInput());+ expect(actions.createBoard).toHaveBeenLastCalledWith('fish', null);++ await click(getAddButton('widgets.gallery.createBoardInProject'));+ await type(getSearchInput(), 'frogs');+ await pressEnter(getSearchInput());+ expect(actions.createBoard).toHaveBeenLastCalledWith('frogs', 'p1');+ });++ it('counts the boards made in each tier, not its fixed row', async () => {+ await renderPanel();- expect(actions.createBoard).toHaveBeenCalledWith('birds');+ const counts = Array.from(+ host?.querySelectorAll<HTMLElement>('[data-scope="collapsible"][data-part="trigger"]') ?? []+ ).map((trigger) => trigger.textContent);++ expect(counts.slice(0, 2)).toEqual(['Mahogany House1', 'Library2']);+ });++ it('names another project inbox for assistive tech while the visible row says Inbox', async () => {+ await renderPanel(createGallery({ showOtherProjectBoards: true }));++ const row = host?.querySelector<HTMLElement>('button[aria-label="Harbor Tower / Inbox"]');++ expect(row?.textContent).toContain('Inbox');+ });++ it('creates at once from a "+" when an unmatched name is already typed', async () => {+ await renderPanel();+ await type(getSearchInput(), 'birds');++ await click(getAddButton('widgets.gallery.createBoardInProject'));++ expect(actions.createBoard).toHaveBeenCalledWith('birds', 'p1');+ expect(getSearchInput().value).toBe('');});it('creates on Enter only when nothing matched', async () => {@@ -254,18 +352,12 @@ describe('GalleryBoardsPanel', () => {const input = getSearchInput();await type(input, 'dog');- await act(async () => {- input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));- await Promise.resolve();- });+ await pressEnter(input);expect(actions.createBoard).not.toHaveBeenCalled();await type(input, 'birds');- await act(async () => {- input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));- await Promise.resolve();- });- expect(actions.createBoard).toHaveBeenCalledWith('birds');+ await pressEnter(input);+ expect(actions.createBoard).toHaveBeenCalledWith('birds', 'p1');});it('persists a collapsed section', async () => {@@ -275,7 +367,7 @@ describe('GalleryBoardsPanel', () => {await click(trigger!);- expect(actions.updateSettings).toHaveBeenCalledWith({ collapsedBoardSections: ['boards'] });+ expect(actions.updateSettings).toHaveBeenCalledWith({ collapsedBoardSections: ['project'] });});it('toggles every board group and the sort order from the one options menu', async () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsxindex becb412bae..027b2be735 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx@@ -3,14 +3,17 @@ import type { GalleryBoardSectionId } from '@features/gallery/core/settings';import type { GalleryBoard } from '@features/gallery/core/types';import { HStack, Icon, ScrollArea, Stack, Text } from '@chakra-ui/react';+import { getGalleryProjectGroupLabel } from '@features/gallery/core/boardLabels';import { toGalleryItemKey } from '@features/gallery/core/items';import { usePreservedScrollOffset } from '@platform/react/usePreservedScrollOffset';import { IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';import { PlusIcon } from 'lucide-react';-import { useCallback, useMemo, useRef, useState } from 'react';+import { useCallback, useMemo, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';+import type { GalleryBoardProjectGroup } from './galleryBoardGroups';+import { BoardCoverIcon } from './GalleryBoardCover';import { GalleryBoardFilters } from './GalleryBoardFilters';import { getGalleryBoardGroups } from './galleryBoardGroups';@@ -24,10 +27,14 @@ import { useGalleryWidget } from './GalleryWidgetContext';const SCROLL_CONTENT_PROPS = { py: '1' } as const;const CREATE_ROW_COVER = <BoardCoverIcon icon={PlusIcon} />;+/** Which tier a board typed into the search field is created in; each tier's "+" chooses it. */+type CreateTier = 'library' | 'project';+export const GalleryBoardsPanel = () => {const { t } = useTranslation();- const { actions, boardsState, gallery, projectName } = useGalleryWidget();+ const { actions, boardsState, gallery, projectId, projectName, projectNames } = useGalleryWidget();const [searchTerm, setSearchTerm] = useState('');+ const [createTier, setCreateTier] = useState<CreateTier>('project');const [boardMenuTarget, setBoardMenuTarget] = useState<GalleryBoardMenuTarget | null>(null);const searchInputRef = useRef<HTMLInputElement>(null);const boardsViewportRef = useRef<HTMLDivElement>(null);@@ -43,7 +50,7 @@ export const GalleryBoardsPanel = () => {getGalleryBoardGroups({boards: gallery.boards,projectBoardId: gallery.projectBoardId,- projectName,+ projectId,searchTerm,showArchived: showArchivedBoards,showDates: showDateBoards,@@ -53,7 +60,7 @@ export const GalleryBoardsPanel = () => {[gallery.boards,gallery.projectBoardId,- projectName,+ projectId,searchTerm,showArchivedBoards,showDateBoards,@@ -69,30 +76,50 @@ export const GalleryBoardsPanel = () => {const trimmedSearchTerm = searchTerm.trim();- const createBoardFromSearch = useCallback(() => {- if (!groups.canCreateFromSearch) {- return;- }+ const createBoardFromSearch = useCallback(+ (tier: CreateTier) => {+ if (!groups.canCreateFromSearch) {+ return;+ }- setSearchTerm('');- void actions.createBoard(trimmedSearchTerm);- }, [actions, groups.canCreateFromSearch, trimmedSearchTerm]);+ setSearchTerm('');+ void actions.createBoard(trimmedSearchTerm, tier === 'project' ? projectId : null);+ },+ [actions, groups.canCreateFromSearch, projectId, trimmedSearchTerm]+ );// Enter creates only with no matches, avoiding accidental near-duplicate boards.const handleSubmitSearch = useCallback(() => {if (!groups.hasAnyMatch) {- createBoardFromSearch();+ createBoardFromSearch(createTier);}- }, [createBoardFromSearch, groups.hasAnyMatch]);+ }, [createBoardFromSearch, createTier, groups.hasAnyMatch]);- const handleAddBoard = useCallback(() => {- if (groups.canCreateFromSearch) {- createBoardFromSearch();- return;- }+ // A "+" with a typed, unmatched name creates at once; otherwise it picks the tier and asks for a name.+ const handleAddBoard = useCallback(+ (tier: CreateTier) => {+ if (groups.canCreateFromSearch) {+ createBoardFromSearch(tier);+ return;+ }- searchInputRef.current?.focus();- }, [createBoardFromSearch, groups.canCreateFromSearch]);+ setCreateTier(tier);+ searchInputRef.current?.focus();+ },+ [createBoardFromSearch, groups.canCreateFromSearch]+ );+ const handleAddProjectBoard = useCallback(() => handleAddBoard('project'), [handleAddBoard]);+ const handleAddLibraryBoard = useCallback(() => handleAddBoard('library'), [handleAddBoard]);+ const addProjectBoardAction = useMemo(+ () => <AddBoardButton label={t('widgets.gallery.createBoardInProject')} onClick={handleAddProjectBoard} />,+ [handleAddProjectBoard, t]+ );+ const addLibraryBoardAction = useMemo(+ () => <AddBoardButton label={t('widgets.gallery.createBoardInLibrary')} onClick={handleAddLibraryBoard} />,+ [handleAddLibraryBoard, t]+ );+ const createProjectBoardFromSearch = useCallback(() => createBoardFromSearch('project'), [createBoardFromSearch]);+ const createLibraryBoardFromSearch = useCallback(() => createBoardFromSearch('library'), [createBoardFromSearch]);const handleSelectBoard = useCallback((boardId: string) => {@@ -121,26 +148,51 @@ export const GalleryBoardsPanel = () => {const isSectionOpen = (sectionId: GalleryBoardSectionId) => !collapsedBoardSections.includes(sectionId);// Without the backend's list, the placeholder Uncategorized row (and "no matches") would claim there is nothing- // else; the failure takes the rows' place instead.+ // else; the failure takes the rows' place instead. While it loads, the fixed rows alone would read as empty tiers.const isBoardListUnavailable = boardsState.status === 'error';+ const isBoardListSettled = boardsState.status !== 'loading' && !isBoardListUnavailable;const focusBoardList = useCallback(() => focusVisibleOperable(boardsViewportRef.current), []);- const addBoardAction = useMemo(- () => (- <Tooltip content={t('widgets.gallery.createBoard')}>- <IconButton- aria-label={t('widgets.gallery.createBoard')}- color="fg.muted"- size="sm"- variant="ghost"- onClick={handleAddBoard}- >- <Icon as={PlusIcon} boxSize="3.5" />- </IconButton>- </Tooltip>- ),- [handleAddBoard, t]+ const renderRow = (board: GalleryBoard, accessibleName?: string) => (+ <GalleryBoardRow+ key={board.id}+ accessibleName={accessibleName}+ board={board}+ isAutoAddTarget={board.id === gallery.settings.autoAddBoardId}+ isMenuOpen={boardMenuTarget?.board.id === board.id}+ isSelected={board.id === gallery.selectedBoardId}+ loadedItemBoardIds={loadedItemBoardIds}+ onOpenMenu={openBoardMenu}+ onSelectBoard={handleSelectBoard}+ />);+ const renderCreateRow = (tier: CreateTier) =>+ groups.canCreateFromSearch && createTier === tier ? (+ <GalleryBoardRowShell+ cover={CREATE_ROW_COVER}+ label={t('widgets.gallery.createBoardNamedIn', {+ destination: tier === 'project' ? projectName : t('widgets.gallery.boardGroups.library'),+ name: trimmedSearchTerm,+ })}+ labelWeight="600"+ onSelect={tier === 'project' ? createProjectBoardFromSearch : createLibraryBoardFromSearch}+ />+ ) : null;+ // One line, shown while a tier holds only its fixed row, so the two tiers explain themselves once.+ const renderHint = (text: string) =>+ trimmedSearchTerm ? null : (+ <Text color="fg.muted" fontSize="xs" pe="2" ps="2" py="1">+ {text}+ </Text>+ );+ const otherProjectLabel = (group: GalleryBoardProjectGroup) =>+ getGalleryProjectGroupLabel(group.projectId, group.boards, projectNames, t);++ const projectBoards = isBoardListUnavailable ? [] : groups.projectBoards;+ const libraryBoards = isBoardListUnavailable ? [] : groups.libraryBoards;+ // Each tier counts the boards made in it; its fixed row (Inbox, Uncategorized) is not one.+ const countCreated = (boards: GalleryBoard[]) =>+ boards.filter((board) => board.kind === 'board' && !board.isInbox).length;return (<Stack flex="1" gap="1" minH="0" minW="0">@@ -154,10 +206,11 @@ export const GalleryBoardsPanel = () => {<ScrollArea.Viewport ref={boardsViewportRef} h="full" w="full"><ScrollArea.Content {...SCROLL_CONTENT_PROPS}><GalleryBoardSection- action={addBoardAction}- isOpen={isSectionOpen('boards')}- label={t('widgets.gallery.boardGroups.boards')}- sectionId="boards"+ action={addProjectBoardAction}+ count={countCreated(projectBoards)}+ isOpen={isSectionOpen('project')}+ label={projectName}+ sectionId="project"onToggle={handleToggleSection}>{boardsState.status === 'error' || boardsState.status === 'stale-error' ? (@@ -172,28 +225,63 @@ export const GalleryBoardsPanel = () => {onFocusLost={focusBoardList}/>) : null}- {(isBoardListUnavailable ? [] : groups.yourBoards).map((board) => (- <GalleryBoardRow- key={board.id}- board={board}- isAutoAddTarget={board.id === gallery.settings.autoAddBoardId}- isMenuOpen={boardMenuTarget?.board.id === board.id}- isSelected={board.id === gallery.selectedBoardId}- loadedItemBoardIds={loadedItemBoardIds}- onOpenMenu={openBoardMenu}- onSelectBoard={handleSelectBoard}- />- ))}- {groups.canCreateFromSearch ? (- <GalleryBoardRowShell- cover={CREATE_ROW_COVER}- label={t('widgets.gallery.createBoardNamed', { name: trimmedSearchTerm })}- labelWeight="600"- onSelect={createBoardFromSearch}- />- ) : null}+ {projectBoards.map((board) => renderRow(board))}+ {renderCreateRow('project')}+ {isBoardListSettled && projectBoards.every((board) => board.isInbox)+ ? renderHint(t('widgets.gallery.projectBoardsHint'))+ : null}+ </GalleryBoardSection>++ <GalleryBoardSection+ action={addLibraryBoardAction}+ count={countCreated(libraryBoards)}+ isOpen={isSectionOpen('library')}+ label={t('widgets.gallery.boardGroups.library')}+ sectionId="library"+ onToggle={handleToggleSection}+ >+ {libraryBoards.map((board) => renderRow(board))}+ {renderCreateRow('library')}+ {isBoardListSettled && libraryBoards.every((board) => board.kind === 'uncategorized')+ ? renderHint(t('widgets.gallery.libraryBoardsHint'))+ : null}</GalleryBoardSection>+ {!isBoardListUnavailable && groups.otherProjects.length > 0 ? (+ <GalleryBoardSection+ count={groups.otherProjects.length}+ isOpen={isSectionOpen('other-projects')}+ label={t('widgets.gallery.boardGroups.otherProjects')}+ sectionId="other-projects"+ onToggle={handleToggleSection}+ >+ {groups.otherProjects.map((group) => (+ <Stack key={group.projectId} gap="0.5">+ <Text+ color="fg.muted"+ fontSize="xs"+ fontWeight="600"+ pe="2"+ ps="2"+ pt="1"+ role="heading"+ aria-level={4}+ truncate+ >+ {otherProjectLabel(group)}+ </Text>+ {group.boards.map((board) =>+ // Every other project's inbox is called "Inbox"; assistive tech needs the project in the name.+ renderRow(+ board,+ board.isInbox ? t('widgets.gallery.inboxOf', { project: otherProjectLabel(group) }) : undefined+ )+ )}+ </Stack>+ ))}+ </GalleryBoardSection>+ ) : null}+{!isBoardListUnavailable && groups.dateBoards.length > 0 ? (<GalleryBoardSectionisOpen={isSectionOpen('dates')}@@ -221,18 +309,7 @@ export const GalleryBoardsPanel = () => {sectionId="archived"onToggle={handleToggleSection}>- {groups.archivedBoards.map((board) => (- <GalleryBoardRow- key={board.id}- board={board}- isAutoAddTarget={board.id === gallery.settings.autoAddBoardId}- isMenuOpen={boardMenuTarget?.board.id === board.id}- isSelected={board.id === gallery.selectedBoardId}- loadedItemBoardIds={loadedItemBoardIds}- onOpenMenu={openBoardMenu}- onSelectBoard={handleSelectBoard}- />- ))}+ {groups.archivedBoards.map((board) => renderRow(board))}</GalleryBoardSection>) : null}@@ -253,3 +330,11 @@ export const GalleryBoardsPanel = () => {</Stack>);};++const AddBoardButton = ({ label, onClick }: { label: string; onClick: () => void }): ReactNode => (+ <Tooltip content={label}>+ <IconButton aria-label={label} color="fg.muted" size="sm" variant="ghost" onClick={onClick}>+ <Icon as={PlusIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsxindex 8a6c333dd9..9e948655e8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx@@ -79,6 +79,7 @@ const adapter: GalleryUiAdapter = {notifications: { add: notificationsAdd, reportError: noop },projectId: 'project-1',projectName: 'Project',+ projects: [],widgets: { openGallery: () => true, patchGalleryValues: noop },};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsxindex 6b2e8dbe99..7431f745a0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLoadFailures.browser.test.tsx@@ -174,6 +174,7 @@ const Harness = ({progressSessions,projectId: 'project-1',projectName: 'Project',+ projects: [],widgets: { openGallery: () => true, patchGalleryValues: patch },};}, [galleryValues, progressSessions]);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsxindex c951f1aa01..3c18607693 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx@@ -104,6 +104,9 @@ const renderBar = async (gallery,itemActions,loadedItems: mergeGalleryLoadedItems(strip.items, gallery.items),+ projectId: 'p1',+ projectName: 'Mahogany House',+ projectNames: new Map([['p2', 'Harbor Tower']]),starredStrip: strip,} as unknown as GalleryWidgetContextValue;@@ -223,6 +226,34 @@ describe('GallerySelectionBar', () => {expect(labels).toEqual(['Cats', 'Uncategorized']);});+ it('groups move targets by the open project, the Library and other projects', async () => {+ await renderBar(+ createGallery({+ boards: [+ createBoard({ id: 'dogs', name: 'dogs' }),+ createBoard({ id: 'theirs-member', name: 'Stripes', projectId: 'p2' }),+ createBoard({ id: 'mine-member', name: 'Façades', projectId: 'p1' }),+ createBoard({ id: 'mine', isInbox: true, name: 'Mahogany House', projectId: 'p1' }),+ createBoard({ id: 'cats', name: 'Cats' }),+ ],+ })+ );+ await click(getButton('widgets.gallery.moveSelectionToBoard'));++ const groups = Array.from(+ document.querySelectorAll<HTMLElement>('[data-scope="menu"] [data-part="item-group"]')+ ).map((group) => [+ group.querySelector('[data-part="item-group-label"]')?.textContent,+ Array.from(group.querySelectorAll('[data-part="item-text"]')).map((element) => element.textContent),+ ]);++ expect(groups).toEqual([+ ['Mahogany House', ['widgets.gallery.inbox', 'Façades']],+ ['widgets.gallery.boardGroups.library', ['Cats']],+ ['Harbor Tower', ['Stripes']],+ ]);+ });+it('disables the move control when there is nowhere to move to', async () => {await renderBar(createGallery({ boards: [createBoard({ id: 'dogs', name: 'dogs' })] }));diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsxindex 3018d8adff..994ede754f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx@@ -1,7 +1,7 @@import type { GalleryBoard } from '@features/gallery/core/types';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';+import { getGalleryBoardDestinationGroups, getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import { parseGalleryItemKey, shouldStarSelection } from '@features/gallery/core/items';import { IconButton } from '@platform/ui/Button';import { MenuContent } from '@platform/ui/Menu';@@ -18,7 +18,7 @@ const MOVE_MENU_POSITIONING = { placement: 'top-end' } as const;export const GallerySelectionBar = () => {const { t } = useTranslation();- const { gallery, itemActions, loadedItems } = useGalleryWidget();+ const { gallery, itemActions, loadedItems, projectId, projectName, projectNames } = useGalleryWidget();const moveTriggerIds = useMenuTriggerIds();const selectedItemKeys = gallery.selectedItemKeys;const selectionCount = selectedItemKeys.length;@@ -36,6 +36,10 @@ export const GallerySelectionBar = () => {),[gallery.boards, gallery.selectedBoardId]);+ const moveGroups = useMemo(+ () => getGalleryBoardDestinationGroups({ boards: moveTargets, projectId, projectName, projectNames, t }),+ [moveTargets, projectId, projectName, projectNames, t]+ );const handleToggleStarred = useCallback(() => void itemActions.setItemsStarred(selectedItemRefs, shouldStar),@@ -101,8 +105,13 @@ export const GallerySelectionBar = () => {<Portal><Menu.Positioner><MenuContent maxH="18rem" minW="12rem" overflowY="auto">- {moveTargets.map((board) => (- <MoveTargetItem key={board.id} board={board} onSelect={handleMoveToBoard} />+ {moveGroups.map((group) => (+ <Menu.ItemGroup key={group.id}>+ <Menu.ItemGroupLabel>{group.label}</Menu.ItemGroupLabel>+ {group.boards.map((board) => (+ <MoveTargetItem key={board.id} board={board} onSelect={handleMoveToBoard} />+ ))}+ </Menu.ItemGroup>))}</MenuContent></Menu.Positioner>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 29f199ee28..68dcb80462 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -1,6 +1,12 @@import type { GalleryImageItem, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/contracts';import type { GallerySettings } from '@features/gallery/core/settings';-import type { GalleryBoard, GalleryBoardDeletionResult, GalleryImage, GalleryView } from '@features/gallery/core/types';+import type {+ GalleryBoard,+ GalleryBoardDeletionResult,+ GalleryImage,+ GalleryProjectRef,+ GalleryView,+} from '@features/gallery/core/types';import type { QueueProgressSession } from '@features/queue/contracts';import { createContext, use, useMemo, type ComponentType, type ReactNode } from 'react';@@ -106,6 +112,13 @@ export interface GalleryUiAdapter {notifications: GalleryNotificationsPort;projectId: string;projectName: string;+ /** The account's projects, for naming the boards that belong to each; the open project need not be among them. */+ projects: readonly GalleryProjectRef[];+ /**+ * Make the open project exist on the server before a board is created in or moved into it: a new project is+ * saved only after its first debounced flush. Absent for hosts without a workbench, which never create in one.+ */+ ensureProjectOnServer?: () => Promise<void>;/*** Export a project as an `.invk`, reporting progress itself. Keyed by project rather than* board because a board menu can offer this for any project's board, not only the open one.@@ -170,7 +183,11 @@ export const useOptionalGalleryUi = (): GalleryUiAdapter | null => use(GalleryUiexport interface GalleryHost {galleryValues: Record<string, unknown>;notifications: GalleryNotificationsPort;+ /** The open project, whose boards list first; absent where there is none (the Launchpad). */+ projectId?: string;projectName: string;+ /** For naming other projects' boards; absent hosts list them unnamed. */+ projects?: readonly GalleryProjectRef[];/** Shows the Gallery widget at a view, switching board when one is given; absent where there is no widget. */revealInGallery?: (location: { boardId: string | null; view: GalleryView }) => boolean;}@@ -189,7 +206,9 @@ export const useGalleryHost = (): GalleryHost => {adapter && {galleryValues: adapter.galleryValues,notifications: adapter.notifications,+ projectId: adapter.projectId,projectName: adapter.projectName,+ projects: adapter.projects,revealInGallery: ({ boardId, view }) => {if (boardId !== null) {adapter.gallery.selectBoard(boardId);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsxindex b7b89cb8a5..2c34407652 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx@@ -12,7 +12,7 @@ import { useTranslation } from 'react-i18next';import type { GalleryWidgetProps } from './GalleryUiContext';import { BoardCover, BoardCoverIcon } from './GalleryBoardCover';-import { getGalleryProjectBoardId, getGallerySelectedBoardId } from './galleryStateView';+import { getGallerySelectedBoardId } from './galleryStateView';import { useGalleryUi } from './GalleryUiContext';type GalleryChromeProps = { region: GalleryWidgetProps['region'] };@@ -43,16 +43,14 @@ const useGalleryChromeBoards = () => {export const GalleryWidgetLabel = ({ region }: GalleryChromeProps) => {const { t } = useTranslation();- const { projectName } = useGalleryUi();- const { boards, gallery, galleryValues, selectedBoardId, settings } = useGalleryChromeBoards();+ const { projectId } = useGalleryUi();+ const { boards, gallery, selectedBoardId, settings } = useGalleryChromeBoards();const selectedBoard = boards.find((board) => board.id === selectedBoardId);- // The project board renames with its project server-side, but the fetched- // list lags a rename; the live project name is authoritative (as in the- // boards panel), so the header follows a rename at once.+ // Another project's inbox is just "Inbox" in its own list; the header has no section to say whose.const boardName = !selectedBoard? t('widgets.gallery.selectedBoardFallback')- : selectedBoard.id === getGalleryProjectBoardId(galleryValues)- ? projectName+ : selectedBoard.isInbox && selectedBoard.projectId !== projectId+ ? t('widgets.gallery.inboxOf', { project: selectedBoard.name }): getGalleryBoardLabel(selectedBoard, t);const isCollapsed = settings.boardPanelCollapsed;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex 8460deebcb..d075b2d14c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -16,12 +16,15 @@ import type { GalleryListingState } from './useGalleryData';*/export interface GalleryActions {archiveBoard: (boardId: string, archived: boolean) => Promise<void>;- createBoard: (boardName: string) => Promise<void>;+ /** In the given project, or in the Library for null. */+ createBoard: (boardName: string, projectId: string | null) => Promise<void>;deleteBoard: (boardId: string, includeImages: boolean) => Promise<void>;downloadBoard: (boardId: string) => Promise<void>;/** Export the project that owns this board as a complete `.invk` archive. */exportProject: (projectId: string, projectName: string) => void;loadMore: () => void;+ /** Into a project, or to the Library for null; `destinationLabel` is what the confirmation names. */+ moveBoard: (boardId: string, projectId: string | null, destinationLabel: string) => Promise<void>;refresh: () => void;renameBoard: (boardId: string, boardName: string) => Promise<void>;selectBoard: (boardId: string) => void;@@ -75,7 +78,10 @@ export interface GalleryWidgetContextValue {/** Everything on hand — strip first, then the listing, without repeats — for lookups by key. */loadedItems: GalleryItem[];starredStrip: GalleryStarredStrip;+ projectId: string;projectName: string;+ /** Names for the projects other boards belong to, keyed by project id. */+ projectNames: ReadonlyMap<string, string>;/** Placement, used only to scope cached viewport measurements. */region: GalleryWidgetProps['region'];runtime: GalleryWidgetRuntime;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex ae40bf4a74..fecb194ac7 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -1,4 +1,5 @@import type { GalleryItem } from '@features/gallery/core/items';+import type { GalleryProjectRef } from '@features/gallery/core/types';import type { GalleryItemsFilter } from '@features/gallery/data/queries';import type { TFunction } from 'i18next';@@ -94,6 +95,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidggenerateValues,projectId,projectName,+ projects,ItemActionsProvider,} = useGalleryUi();const galleryView = getGalleryView(galleryValues);@@ -230,7 +232,9 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgisWindowTruncated={data.isWindowTruncated}listing={data.listing}loadedItems={loadedItems}+ projectId={projectId}projectName={projectName}+ projects={projects}region={region}runtime={runtime}starredStrip={starredStrip}@@ -277,7 +281,9 @@ const GalleryWidgetContent = ({isWindowTruncated,listing,loadedItems,+ projectId,projectName,+ projects,region,runtime,starredStrip,@@ -289,13 +295,16 @@ const GalleryWidgetContent = ({isWindowTruncated: boolean;listing: GalleryListingState;loadedItems: GalleryItem[];+ projectId: string;projectName: string;+ projects: readonly GalleryProjectRef[];region: GalleryWidgetProps['region'];runtime: GalleryWidgetRuntime;starredStrip: GalleryStarredStrip;}) => {const { t } = useTranslation();const itemActions = useGalleryItemActions();+ const projectNames = useMemo(() => new Map(projects.map((project) => [project.id, project.name])), [projects]);const contextValue = useMemo<GalleryWidgetContextValue>(() => ({actions,@@ -306,7 +315,9 @@ const GalleryWidgetContent = ({itemActions,listing,loadedItems,+ projectId,projectName,+ projectNames,region,runtime,starredStrip,@@ -320,7 +331,9 @@ const GalleryWidgetContent = ({itemActions,listing,loadedItems,+ projectId,projectName,+ projectNames,region,runtime,starredStrip,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.tsindex 733af62e59..248ad7890b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.test.ts@@ -9,8 +9,8 @@ const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id'assetCount: 0,assetVideoCount: 0,imageCount: 0,- kind: 'board',isInbox: false,+ kind: 'board',projectId: null,videoCount: 0,...overrides,@@ -21,17 +21,22 @@ const dogs = createBoard({ id: 'dogs', name: 'dogs' });const cats = createBoard({ id: 'cats', name: 'Cats' });const archived = createBoard({ archived: true, id: 'gorl', name: 'GORL' });const dateBoard = createBoard({ id: 'by_date:2026-07-28', kind: 'date', name: '28 July' });-const otherProject = createBoard({ id: 'other', isInbox: true, name: 'Someone else', projectId: 'project-2' });-const ownProject = createBoard({ id: 'mine', isInbox: true, name: 'My project', projectId: 'project-1' });-const ownMember = createBoard({ id: 'mine-member', name: 'Façades', projectId: 'project-1' });-const otherMember = createBoard({ id: 'other-member', name: 'Their façades', projectId: 'project-2' });-const t = (key: string) => (key === 'widgets.gallery.uncategorized' ? 'Uncategorized' : key);+const mine = createBoard({ id: 'mine', isInbox: true, name: 'My project', projectId: 'project-1' });+const mineMember = createBoard({ id: 'mine-member', name: 'Façades', projectId: 'project-1' });+const mineArchived = createBoard({ archived: true, id: 'mine-old', name: 'Old façades', projectId: 'project-1' });+const zebra = createBoard({ id: 'zebra', isInbox: true, name: 'Zebra study', projectId: 'project-z' });+const zebraMember = createBoard({ id: 'zebra-member', name: 'Stripes', projectId: 'project-z' });+const apple = createBoard({ id: 'apple', isInbox: true, name: 'Apple ads', projectId: 'project-a' });+const t = (key: string) =>+ key === 'widgets.gallery.uncategorized' ? 'Uncategorized' : key === 'widgets.gallery.inbox' ? 'Inbox' : key;++const ALL = [uncategorized, dogs, cats, archived, dateBoard, zebraMember, mineMember, zebra, mine, apple, mineArchived];const groupsOf = (overrides: Partial<Parameters<typeof getGalleryBoardGroups>[0]> = {}) =>getGalleryBoardGroups({- boards: [uncategorized, dogs, cats, archived, dateBoard, otherProject, ownProject],- projectBoardId: null,- projectName: 'Project',+ boards: ALL,+ projectBoardId: 'mine',+ projectId: 'project-1',searchTerm: '',showArchived: true,showDates: true,@@ -40,92 +45,101 @@ const groupsOf = (overrides: Partial<Parameters<typeof getGalleryBoardGroups>[0]...overrides,});+const ids = (boards: GalleryBoard[]) => boards.map((board) => board.id);+describe('getGalleryBoardGroups', () => {- it('splits archived boards into their own section instead of the main list', () => {+ it('puts the open project inbox first, then its members, and Uncategorized first in the Library', () => {const groups = groupsOf();- expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'dogs', 'cats', 'other', 'mine']);- expect(groups.archivedBoards.map((board) => board.id)).toEqual(['gorl']);+ expect(ids(groups.projectBoards)).toEqual(['mine', 'mine-member']);+ expect(ids(groups.libraryBoards)).toEqual(['none', 'dogs', 'cats']);});- it('pins Uncategorized first, then the hoisted project board, then other boards', () => {- const groups = groupsOf({ projectBoardId: 'cats' });+ it('claims the open project inbox by id before the listing knows its membership', () => {+ const draftInbox = createBoard({ id: 'draft', isInbox: true, name: 'Draft' });+ const groups = groupsOf({+ boards: [uncategorized, draftInbox, dogs],+ projectBoardId: 'draft',+ projectId: 'p-draft',+ });- expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'cats', 'dogs', 'other', 'mine']);+ expect(ids(groups.projectBoards)).toEqual(['draft']);+ expect(ids(groups.libraryBoards)).toEqual(['none', 'dogs']);});- it('hides the date and archived sections when their toggles are off', () => {- const groups = groupsOf({ showArchived: false, showDates: false });+ it('groups other projects by name with each inbox first, only when they are shown', () => {+ const groups = groupsOf();- expect(groups.archivedBoards).toEqual([]);- expect(groups.dateBoards).toEqual([]);- expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'dogs', 'cats', 'other', 'mine']);+ expect(groups.otherProjects.map((group) => [group.projectId, ids(group.boards)])).toEqual([+ ['project-a', ['apple']],+ ['project-z', ['zebra', 'zebra-member']],+ ]);+ expect(groupsOf({ showOtherProjects: false }).otherProjects).toEqual([]);});- it('drops boards owned by another project when they are hidden', () => {- const groups = groupsOf({ showOtherProjects: false });-- expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'dogs', 'cats']);+ it('keeps other projects archived boards out of the archived section while they are hidden', () => {+ const otherArchived = createBoard({ archived: true, id: 'their-old', name: 'Theirs', projectId: 'project-z' });++ expect(ids(groupsOf({ boards: [...ALL, otherArchived] }).archivedBoards)).toEqual([+ 'gorl',+ 'mine-old',+ 'their-old',+ ]);+ expect(ids(groupsOf({ boards: [...ALL, otherArchived], showOtherProjects: false }).archivedBoards)).toEqual([+ 'gorl',+ 'mine-old',+ ]);});- it('keeps the open project own board even while other projects are hidden', () => {- const groups = groupsOf({ projectBoardId: 'mine', showOtherProjects: false });+ it('treats every project as other where no project is open', () => {+ const groups = groupsOf({ projectBoardId: null, projectId: null });- expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'mine', 'dogs', 'cats']);+ expect(groups.projectBoards).toEqual([]);+ expect(groups.otherProjects.map((group) => group.projectId)).toEqual(['project-a', 'project-1', 'project-z']);});- it('keeps the open project members, but not other projects members, while other projects are hidden', () => {- const groups = groupsOf({- boards: [uncategorized, dogs, ownProject, ownMember, otherProject, otherMember],- projectBoardId: 'mine',- showOtherProjects: false,- });-- expect(groups.yourBoards.map((board) => board.id)).toEqual(['none', 'mine', 'dogs', 'mine-member']);- });+ it('hides the date and archived sections when their toggles are off', () => {+ const groups = groupsOf({ showArchived: false, showDates: false });- /** The fetched list can lag a rename; the live project name wins for the open project's row. */- it('shows the open project board under the live project name, and searches by it', () => {- const groups = groupsOf({ projectBoardId: 'mine', projectName: 'Renamed' });-- expect(groups.yourBoards.find((board) => board.id === 'mine')?.name).toBe('Renamed');- expect(- groupsOf({ projectBoardId: 'mine', projectName: 'Renamed', searchTerm: 'renamed' }).yourBoards- ).toContainEqual(expect.objectContaining({ id: 'mine' }));- expect(- groupsOf({ projectBoardId: 'mine', projectName: 'Renamed', searchTerm: 'My project' }).yourBoards.map(- (board) => board.id- )- ).not.toContain('mine');+ expect(groups.archivedBoards).toEqual([]);+ expect(groups.dateBoards).toEqual([]);});- it('filters every section by a case-insensitive substring match', () => {+ it('filters every section by a case-insensitive substring match on the shown label', () => {const groups = groupsOf({ searchTerm: 'DOG' });- expect(groups.yourBoards.map((board) => board.id)).toEqual(['dogs']);- expect(groups.archivedBoards).toEqual([]);- expect(groups.dateBoards).toEqual([]);+ expect(ids(groups.libraryBoards)).toEqual(['dogs']);+ expect(groups.projectBoards).toEqual([]);+ expect(groups.otherProjects).toEqual([]);expect(groups.hasAnyMatch).toBe(true);++ // Inboxes answer to "Inbox", not to the project name the server stores them under.+ expect(ids(groupsOf({ searchTerm: 'inbox' }).projectBoards)).toEqual(['mine']);+ expect(groupsOf({ searchTerm: 'inbox' }).otherProjects.map((group) => ids(group.boards))).toEqual([+ ['apple'],+ ['zebra'],+ ]);+ expect(groupsOf({ searchTerm: 'zebra' }).hasAnyMatch).toBe(false);});it('matches anywhere in the name, so Uncategorized answers to "cat"', () => {- expect(groupsOf({ searchTerm: 'cat' }).yourBoards.map((board) => board.id)).toEqual(['none', 'cats']);+ expect(ids(groupsOf({ searchTerm: 'cat' }).libraryBoards)).toEqual(['none', 'cats']);});it('offers to create only when the search names no existing board', () => {expect(groupsOf({ searchTerm: 'birds' }).canCreateFromSearch).toBe(true);expect(groupsOf({ searchTerm: 'cats' }).canCreateFromSearch).toBe(false);expect(groupsOf({ searchTerm: ' CATS ' }).canCreateFromSearch).toBe(false);- expect(groupsOf({ searchTerm: '' }).canCreateFromSearch).toBe(false);- });-- it('treats the localized Uncategorized label as an exact match', () => {expect(groupsOf({ searchTerm: 'Uncategorized' }).canCreateFromSearch).toBe(false);+ expect(groupsOf({ searchTerm: 'Inbox' }).canCreateFromSearch).toBe(false);+ expect(groupsOf({ searchTerm: '' }).canCreateFromSearch).toBe(false);});- /** A loading project board still exists; its name must not offer duplicate creation. */- it('treats the project board name as an exact match even before the board arrives', () => {- expect(groupsOf({ searchTerm: 'Project' }).canCreateFromSearch).toBe(false);+ it('lets a name that exists only in a hidden tier be created', () => {+ // "Stripes" lives in project-z, hidden while other projects are off; "GORL" is archived and hidden.+ expect(groupsOf({ searchTerm: 'Stripes', showOtherProjects: false }).canCreateFromSearch).toBe(true);+ expect(groupsOf({ searchTerm: 'GORL', showArchived: false }).canCreateFromSearch).toBe(true);+ expect(groupsOf({ searchTerm: 'Stripes' }).canCreateFromSearch).toBe(false);});it('reports no match when the search excludes every row', () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.tsindex 64bd5c047a..b8031c2669 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts@@ -1,27 +1,38 @@import type { GalleryBoard } from '@features/gallery/core/types';-import { getGalleryBoardLabel, type GalleryBoardTranslate } from '@features/gallery/core/boardLabels';+import { getGalleryBoardLabel, inboxFirst, type GalleryBoardTranslate } from '@features/gallery/core/boardLabels';++/** One other project's boards: its inbox first, named after the project, then the rest. */+export interface GalleryBoardProjectGroup {+ boards: GalleryBoard[];+ projectId: string;+}export interface GalleryBoardGroups {- /** Archived boards, split out of the main list into their own section. */+ /** Archived boards from every tier, split out of the lists into their own section. */archivedBoards: GalleryBoard[];/** The search term names no existing board, so it can create one. */canCreateFromSearch: boolean;dateBoards: GalleryBoard[];/** Any row at all survived the search — drives the "no matches" copy. */hasAnyMatch: boolean;- /** Uncategorized first, then the project board (if any), then other boards. */- yourBoards: GalleryBoard[];+ /** Uncategorized first, then the boards in no project. */+ libraryBoards: GalleryBoard[];+ /** Other projects in name order; empty unless other projects are shown. */+ otherProjects: GalleryBoardProjectGroup[];+ /** The open project's inbox first, then its other boards. */+ projectBoards: GalleryBoard[];}/**- * Apply visibility filters while grouping; GET /boards/ cannot filter other projects and returns the complete- * list.+ * Apply visibility filters while grouping; GET /boards/ cannot filter by project and returns the complete list.+ * Membership is the board's own `projectId`; `projectBoardId` also claims the open project's inbox, which a draft+ * project can know before the listing does.*/export const getGalleryBoardGroups = ({boards,projectBoardId,- projectName,+ projectId,searchTerm,showArchived,showDates,@@ -30,7 +41,8 @@ export const getGalleryBoardGroups = ({}: {boards: readonly GalleryBoard[];projectBoardId: string | null;- projectName: string;+ /** The open project; null where there is none, in which case every project is "other". */+ projectId: string | null;searchTerm: string;showArchived: boolean;showDates: boolean;@@ -38,50 +50,73 @@ export const getGalleryBoardGroups = ({t: GalleryBoardTranslate;}): GalleryBoardGroups => {const normalizedSearchTerm = searchTerm.trim().toLowerCase();- const matchesSearch = (name: string) => !normalizedSearchTerm || name.toLowerCase().includes(normalizedSearchTerm);+ const matchesBoardSearch = (board: GalleryBoard) =>+ !normalizedSearchTerm || getGalleryBoardLabel(board, t).toLowerCase().includes(normalizedSearchTerm);+ const isOpenProjectBoard = (board: GalleryBoard) =>+ board.id === projectBoardId || (projectId !== null && board.projectId === projectId);const uncategorizedBoard = boards.find((board) => board.kind === 'uncategorized') ?? null;- const fetchedProjectBoard = projectBoardId ? (boards.find((board) => board.id === projectBoardId) ?? null) : null;- // The board renames with its project server-side, but the fetched list can lag- // a rename — the live project name is authoritative for the open project's row.- const projectBoard = fetchedProjectBoard ? { ...fetchedProjectBoard, name: projectName } : null;-- const matchesBoardSearch = (board: GalleryBoard) => matchesSearch(getGalleryBoardLabel(board, t));- // The open project's own boards always show, whatever the other-projects filter says. Its id is read off its- // fetched inbox, which is a member of it; until the inbox arrives, no board can be known to be its.- const openProjectId = fetchedProjectBoard?.projectId ?? null;- const belongsToVisibleProject = (board: GalleryBoard) =>- showOtherProjects ||- board.projectId === null ||- board.id === projectBoard?.id ||- (openProjectId !== null && board.projectId === openProjectId);- const regularBoards = boards.filter(- (board) =>- board.kind === 'board' &&- board.id !== projectBoard?.id &&- belongsToVisibleProject(board) &&- matchesBoardSearch(board)- );- const dateBoards = showDates ? boards.filter((board) => board.kind === 'date' && matchesBoardSearch(board)) : [];- const archivedBoards = showArchived ? regularBoards.filter((board) => board.archived) : [];+ const regularBoards = boards.filter((board) => board.kind === 'board' && matchesBoardSearch(board));+ const liveBoards = regularBoards.filter((board) => !board.archived);- // Keep the fixed system row first as boards accumulate.- const yourBoards = [+ const projectBoards = inboxFirst(liveBoards.filter(isOpenProjectBoard));+ const libraryBoards = [...(uncategorizedBoard && matchesBoardSearch(uncategorizedBoard) ? [uncategorizedBoard] : []),- ...(projectBoard && matchesBoardSearch(projectBoard) ? [projectBoard] : []),- ...regularBoards.filter((board) => !board.archived),+ ...liveBoards.filter((board) => board.projectId === null && !isOpenProjectBoard(board)),];- const hasAnyMatch = yourBoards.length > 0 || dateBoards.length > 0 || archivedBoards.length > 0;- const hasExactMatch =- boards.some((board) => getGalleryBoardLabel(board, t).toLowerCase() === normalizedSearchTerm) ||- projectName.toLowerCase() === normalizedSearchTerm;+ const otherProjects: GalleryBoardProjectGroup[] = [];+ if (showOtherProjects) {+ const byProject = new Map<string, GalleryBoard[]>();+ for (const board of liveBoards) {+ if (board.projectId !== null && !isOpenProjectBoard(board)) {+ const group = byProject.get(board.projectId);++ if (group) {+ group.push(board);+ } else {+ byProject.set(board.projectId, [board]);+ }+ }+ }+ for (const [otherProjectId, projectGroupBoards] of byProject) {+ otherProjects.push({ boards: inboxFirst(projectGroupBoards), projectId: otherProjectId });+ }+ // The inbox carries the project's name, so projects sort by it where one is listed.+ const nameOf = (group: GalleryBoardProjectGroup) => group.boards.find((board) => board.isInbox)?.name ?? '';+ otherProjects.sort((left, right) => nameOf(left).localeCompare(nameOf(right)));+ }++ const dateBoards = showDates ? boards.filter((board) => board.kind === 'date' && matchesBoardSearch(board)) : [];+ const archivedBoards = showArchived+ ? regularBoards.filter(+ (board) => board.archived && (showOtherProjects || board.projectId === null || isOpenProjectBoard(board))+ )+ : [];++ const hasAnyMatch =+ projectBoards.length > 0 ||+ libraryBoards.length > 0 ||+ otherProjects.length > 0 ||+ dateBoards.length > 0 ||+ archivedBoards.length > 0;+ // Only the rows on screen count as taken: a name in a hidden project (or an archived board while archived boards+ // are hidden) may legitimately be reused, and refusing it would leave the search with nothing to do.+ const hasExactMatch = [+ ...projectBoards,+ ...libraryBoards,+ ...otherProjects.flatMap((group) => group.boards),+ ...dateBoards,+ ...archivedBoards,+ ].some((board) => getGalleryBoardLabel(board, t).toLowerCase() === normalizedSearchTerm);return {archivedBoards,canCreateFromSearch: normalizedSearchTerm.length > 0 && !hasExactMatch,dateBoards,hasAnyMatch,- yourBoards,+ libraryBoards,+ otherProjects,+ projectBoards,};};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsxindex bd36636d74..396c3f6055 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx@@ -2,7 +2,7 @@ import type { GalleryItem, GalleryItemKey } from '@features/gallery/core/items';import type { KeyboardEvent, RefObject } from 'react';import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';+import { getGalleryProjectGroupLabel, getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import { getGalleryUploadAccept, toGalleryItemKey } from '@features/gallery/core/items';import { BoardCover, BoardCoverIcon } from '@features/gallery/ui/GalleryBoardCover';import { getGalleryBoardGroups } from '@features/gallery/ui/galleryBoardGroups';@@ -61,7 +61,7 @@ export const GalleryPickerView = ({onPick: (item: GalleryItem) => void;}) => {const { t } = useTranslation();- const { galleryValues, projectName, revealInGallery } = useGalleryHost();+ const { galleryValues, projectId = null, projectName, projects, revealInGallery } = useGalleryHost();const { data, gallerySelectedItem, scope, selectBoard, setSearchTerm, setView, settings, togglePane } =useGalleryPickerScope();const idBase = useId();@@ -174,7 +174,7 @@ export const GalleryPickerView = ({const groups = getGalleryBoardGroups({boards: data.boards,projectBoardId: getGalleryProjectBoardId(galleryValues),- projectName,+ projectId,searchTerm: scope.searchTerm,showArchived: settings.showArchivedBoards,showDates: settings.showDateBoards,@@ -182,16 +182,25 @@ export const GalleryPickerView = ({showOtherProjects: true,t,});+ const projectNames = new Map((projects ?? []).map((project) => [project.id, project.name]));return [- { boards: groups.yourBoards, id: 'boards', label: t('widgets.gallery.boardGroups.boards') },+ { boards: groups.projectBoards, id: 'project', label: projectName },+ { boards: groups.libraryBoards, id: 'library', label: t('widgets.gallery.boardGroups.library') },+ ...groups.otherProjects.map((group) => ({+ boards: group.boards,+ id: `project:${group.projectId}`,+ label: getGalleryProjectGroupLabel(group.projectId, group.boards, projectNames, t),+ })),{ boards: groups.dateBoards, id: 'dates', label: t('widgets.gallery.boardGroups.byDate') },{ boards: groups.archivedBoards, id: 'archived', label: t('common.archived') },].filter((group) => group.boards.length > 0);}, [data.boards,galleryValues,+ projectId,projectName,+ projects,scope.searchTerm,settings.showArchivedBoards,settings.showDateBoards,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex 89d7285a01..b2ed97f6e6 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -12,7 +12,9 @@ import type { GalleryActions } from './GalleryWidgetContext';import { useGalleryActions } from './useGalleryActions';const mocks = vi.hoisted(() => ({+ createGalleryBoard: vi.fn(),deleteGalleryBoard: vi.fn(),+ ensureProjectOnServer: vi.fn(async () => {}),downloadBlob: vi.fn(),downloadGalleryArchive: vi.fn(),invalidateGallery: vi.fn(),@@ -25,7 +27,7 @@ const mocks = vi.hoisted(() => ({}));vi.mock('@features/gallery/data/backend', () => ({- createGalleryBoard: vi.fn(),+ createGalleryBoard: (...args: unknown[]) => mocks.createGalleryBoard(...args),deleteGalleryBoard: (...args: unknown[]) => mocks.deleteGalleryBoard(...args),downloadGalleryArchive: (...args: unknown[]) => mocks.downloadGalleryArchive(...args),isDateBoardId: (boardId: string) => boardId.startsWith('by_date:'),@@ -185,6 +187,8 @@ const adapter: GalleryUiAdapter = {},projectId: 'project-1',projectName: 'Project',+ projects: [],+ ensureProjectOnServer: () => mocks.ensureProjectOnServer(),widgets: { openGallery: () => true, patchGalleryValues },};@@ -287,6 +291,45 @@ describe('optimistic board updates', () => {expect(mocks.invalidateGallery).not.toHaveBeenCalled();});+ it('moves before the request and rolls back when the backend rejects', async () => {+ mocks.updateGalleryBoard.mockRejectedValue(new Error('move failed'));++ await act(async () => {+ await actionsRef.current?.moveBoard('board-1', null, 'Library');+ });++ expect(mocks.patchGalleryBoardCaches).toHaveBeenCalledWith(expect.anything(), 'board-1', { projectId: null });+ expect(mocks.updateGalleryBoard).toHaveBeenCalledWith('board-1', { projectId: null }, expect.anything());+ expect(mocks.patchGalleryBoardCaches.mock.results[0]?.value).toHaveBeenCalledOnce();+ expect(mocks.notificationsReportError).toHaveBeenCalledOnce();+ expect(mocks.invalidateGallery).not.toHaveBeenCalled();+ });++ it('makes the project exist on the server before creating or moving a board into it, never for the Library', async () => {+ mocks.createGalleryBoard.mockResolvedValue({ id: 'new', name: 'New' });+ mocks.updateGalleryBoard.mockResolvedValue(undefined);++ await act(async () => {+ await actionsRef.current?.createBoard('New', null);+ await actionsRef.current?.moveBoard('board-1', null, 'Library');+ });+ expect(mocks.ensureProjectOnServer).not.toHaveBeenCalled();++ await act(async () => {+ await actionsRef.current?.createBoard('New', 'p1');+ });+ expect(mocks.ensureProjectOnServer).toHaveBeenCalledOnce();+ expect(mocks.ensureProjectOnServer.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.createGalleryBoard.mock.invocationCallOrder[1] ?? 0+ );+ expect(mocks.createGalleryBoard).toHaveBeenLastCalledWith('New', 'p1', expect.anything());++ await act(async () => {+ await actionsRef.current?.moveBoard('board-1', 'p1', 'Project');+ });+ expect(mocks.ensureProjectOnServer).toHaveBeenCalledTimes(2);+ });+it('keeps a successful rename applied without rolling back', async () => {mocks.updateGalleryBoard.mockResolvedValue(undefined);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex 687afc5f33..078fd40cb5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -37,7 +37,7 @@ export const useGalleryActions = ({loadMore: () => void;selectedBoardId: string;}): GalleryActions => {- const { exportProject, gallery, notifications, widgets } = useGalleryUi();+ const { ensureProjectOnServer, exportProject, gallery, notifications, widgets } = useGalleryUi();const queryClient = useQueryClient();const { t } = useTranslation();const uploadFiles = useGalleryUploadAction({ boards, getCurrentGalleryLocation, selectedBoardId });@@ -90,11 +90,16 @@ export const useGalleryActions = ({recordError(error);}},- createBoard: async (boardName) => {+ createBoard: async (boardName, projectId) => {const owner = captureAccountScope();try {- const board = await createGalleryBoard(boardName, owner.signal);+ if (projectId !== null) {+ await ensureProjectOnServer?.();+ assertAccountScopeCurrent(owner);+ }++ const board = await createGalleryBoard(boardName, projectId, owner.signal);assertAccountScopeCurrent(owner);gallery.selectBoard(board.id);@@ -176,6 +181,32 @@ export const useGalleryActions = ({},exportProject,loadMore,+ moveBoard: async (boardId, projectId, destinationLabel) => {+ const owner = captureAccountScope();+ const rollback = patchGalleryBoardCaches(queryClient, boardId, { projectId });++ try {+ if (projectId !== null) {+ await ensureProjectOnServer?.();+ assertAccountScopeCurrent(owner);+ }++ await updateGalleryBoard(boardId, { projectId }, owner.signal);++ assertAccountScopeCurrent(owner);+ recordSuccess(+ t('widgets.gallery.boardMoved', { destination: destinationLabel, name: getBoardName(boardId) })+ );+ refresh();+ } catch (error: unknown) {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ rollback();+ recordError(error);+ }+ },refresh,renameBoard: async (boardId, boardName) => {const owner = captureAccountScope();@@ -222,6 +253,7 @@ export const useGalleryActions = ({};}, [boards,+ ensureProjectOnServer,exportProject,gallery,getCurrentGalleryLocation,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex 566c6bb6fd..bb55c75f1a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -102,6 +102,7 @@ const adapter: GalleryUiAdapter = {},projectId: 'project-1',projectName: 'Project',+ projects: [],widgets: { openGallery: () => true, patchGalleryValues: noop },};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 49deed4408..d1f3c0fa82 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -134,7 +134,7 @@ export const WorkbenchProvider = ({store.commands.projects.close(projectId);}},- deleteProject: (projectId) => persistence.deleteProjectOnServer(projectId),+ deleteProject: (projectId, boards) => persistence.deleteProjectOnServer(projectId, boards),flushPixels: (projectId) => liveCanvasEngines.flushPendingPixels(projectId),flushProject: (projectId) => {const project = store.getSnapshot().projects.find((candidate) => candidate.id === projectId);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsxindex 213c6dc307..ad4e286172 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx@@ -19,7 +19,12 @@ const findGalleryItem = vi.fn();vi.mock('@workbench/image-actions/useFindGalleryItem', () => ({ useFindGalleryItem: () => findGalleryItem }));vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));+vi.mock('@workbench/projects/library', () => ({+ useProjectLibrarySelector: (selector: (snapshot: { summaries: [] }) => unknown) => selector({ summaries: [] }),+}));vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectId: () => 'project-1',+ useActiveProjectName: () => 'Project',useWorkbenchCommands: () => ({generation: { setSource: vi.fn() },widgets: { patchValues: vi.fn() },@@ -508,7 +513,7 @@ describe('ImageContextMenu mixed-media action visibility', () => {expect(document.querySelector('[aria-label="Download video"]')).not.toBeNull();expect(document.querySelector('[aria-label="Open in preview"]')).not.toBeNull();expect(document.querySelector('[aria-label="Star video"]')).not.toBeNull();- expect(document.body.textContent).toContain('Change Board');+ expect(document.body.textContent).toContain('widgets.gallery.changeBoard');expect(document.body.textContent).toContain('Delete Video');expect(document.body.textContent).not.toContain('Copy to clipboard');expect(document.body.textContent).not.toContain('widgets.preview.copyCurrentFrame');@@ -622,7 +627,7 @@ describe('ImageContextMenu mixed-media action visibility', () => {expect(document.body.textContent).toContain('2 items selected');expect(document.body.textContent).toContain('Star All');expect(document.body.textContent).toContain('Download Selection');- expect(document.body.textContent).toContain('Change Board');+ expect(document.body.textContent).toContain('widgets.gallery.changeBoard');expect(document.body.textContent).toContain('Delete Selection');expect(document.body.textContent).not.toContain('widgets.canvas.import.addToCurrentCanvas');expect(document.body.textContent).not.toContain('widgets.canvas.import.newProjectFromImage');diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex 0e40882eeb..a044f1bcff 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -10,11 +10,13 @@ import {legacyGeneratedImageToGalleryItem,toGalleryItemKey,} from '@features/gallery';+import { getGalleryBoardDestinationGroups, getGalleryBoardLabel } from '@features/gallery/contracts';import { MenuContent, MenuIconItem } from '@platform/ui';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';+import { useProjectLibrarySelector } from '@workbench/projects/library';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useWorkbenchCommands } from '@workbench/WorkbenchContext';+import { useActiveProjectId, useActiveProjectName, useWorkbenchCommands } from '@workbench/WorkbenchContext';import {ClapperboardIcon,AsteriskIcon,@@ -1057,35 +1059,52 @@ const ChangeBoardSubMenu = ({currentBoardId: string | null;onMove: (boardId: string) => void;}) => {+ const { t } = useTranslation();+ const projectId = useActiveProjectId();+ const projectName = useActiveProjectName();+ const librarySummaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);const handleRemoveFromBoard = useCallback(() => onMove('none'), [onMove]);- const visibleBoards = useMemo(- () => boards.filter((board) => board.kind === 'board' && board.id !== currentBoardId),- [boards, currentBoardId]+ const groups = useMemo(+ () =>+ getGalleryBoardDestinationGroups({+ boards: boards.filter((board) => board.kind === 'board' && board.id !== currentBoardId),+ projectId,+ projectName,+ projectNames: new Map(librarySummaries.map((summary) => [summary.id, summary.name])),+ t,+ }),+ [boards, currentBoardId, librarySummaries, projectId, projectName, t]);return (- <ContextSubMenu icon={FolderIcon} label="Change Board" scrollArea>+ <ContextSubMenu icon={FolderIcon} label={t('widgets.gallery.changeBoard')} scrollArea>{currentBoardId !== 'none' && (<ContextMenuItemicon={FolderIcon}- label="Remove from Board"+ label={t('widgets.gallery.removeFromBoard')}value="remove-from-board"onClick={handleRemoveFromBoard}/>)}- {visibleBoards.map((board) => (- <ChangeBoardMenuItem key={board.id} board={board} onMove={onMove} />+ {groups.map((group) => (+ <Menu.ItemGroup key={group.id}>+ <Menu.ItemGroupLabel>{group.label}</Menu.ItemGroupLabel>+ {group.boards.map((board) => (+ <ChangeBoardMenuItem key={board.id} board={board} onMove={onMove} />+ ))}+ </Menu.ItemGroup>))}</ContextSubMenu>);};const ChangeBoardMenuItem = ({ board, onMove }: { board: GalleryBoard; onMove: (boardId: string) => void }) => {+ const { t } = useTranslation();const handleClick = useCallback(() => onMove(board.id), [board.id, onMove]);return (<Menu.Item value={`move-to-${board.id}`} onClick={handleClick}>- <MiddleTruncate fontSize="md" minW="0" text={board.name} />+ <MiddleTruncate fontSize="md" minW="0" text={getGalleryBoardLabel(board, t)} /></Menu.Item>);};diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsxindex c0a87bd07c..1d3a8c0acc 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.browser.test.tsx@@ -3,21 +3,42 @@ import type { MouseEvent } from 'react';import { ChakraProvider } from '@chakra-ui/react';import { IconButton } from '@platform/ui/Button';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act, useCallback, useMemo } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';+const deleteSpy = vi.hoisted(() => vi.fn(() => Promise.resolve()));+vi.mock('./useProjectCardActions', () => ({useProjectCardActions: () => ({- delete: () => Promise.resolve(),+ delete: deleteSpy,duplicate: () => {},export: () => {},rename: () => Promise.resolve(),}),}));+// The host owns the lazy mount and the threading of the user's choice; the dialog's own behaviour has its own test.+vi.mock('@workbench/projects/components/DeleteProjectDialog', () => ({+ DeleteProjectDialog: ({+ isOpen,+ projectId,+ onConfirm,+ }: {+ isOpen: boolean;+ projectId: string | null;+ onConfirm: (boards: 'delete' | 'release') => void;+ }) =>+ isOpen ? (+ <button data-testid="confirm-delete" onClick={() => onConfirm('delete')}>+ delete {projectId}+ </button>+ ) : null,+}));+vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));@@ -39,6 +60,9 @@ const { ProjectActionsMenuProvider, useProjectActionsMenu, useProjectActionsMenu(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+// The delete dialog reads the board list to say what happens to the project's boards.+const queryClient = new QueryClient();+const makeSummary = (id: string): ProjectSummary =>({coverUrl: undefined,@@ -131,9 +155,11 @@ describe('ProjectActionsMenuHost', () => {await act(() =>root?.render(<ChakraProvider value={system}>- <ProjectActionsMenuProvider>- <Card id="one" />- </ProjectActionsMenuProvider>+ <QueryClientProvider client={queryClient}>+ <ProjectActionsMenuProvider>+ <Card id="one" />+ </ProjectActionsMenuProvider>+ </QueryClientProvider></ChakraProvider>));@@ -146,6 +172,35 @@ describe('ProjectActionsMenuHost', () => {});});+ it('mounts the delete dialog on first request and threads the chosen board mode to the action', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <ProjectActionsMenuProvider>+ <Card id="one" />+ </ProjectActionsMenuProvider>+ </QueryClientProvider>+ </ChakraProvider>+ )+ );+ expect(document.querySelector('[data-testid="confirm-delete"]')).toBeNull();++ await act(() => userEvent.click(dotsButton('one')));+ const item = document.querySelector<HTMLElement>('[role="menuitem"][data-value="delete"]')!;+ await act(() => userEvent.click(item));++ await vi.waitFor(() => {+ expect(document.querySelector('[data-testid="confirm-delete"]')?.textContent).toBe('delete one');+ });+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[data-testid="confirm-delete"]')!));++ expect(deleteSpy).toHaveBeenCalledExactlyOnceWith('delete');+ });+it('opens the Preferences intermediates section focused on the project', async () => {const { peekIntermediatesFocus } = await import('@features/intermediates/data/focus');host = document.createElement('div');@@ -154,9 +209,11 @@ describe('ProjectActionsMenuHost', () => {await act(() =>root?.render(<ChakraProvider value={system}>- <ProjectActionsMenuProvider>- <Card id="one" />- </ProjectActionsMenuProvider>+ <QueryClientProvider client={queryClient}>+ <ProjectActionsMenuProvider>+ <Card id="one" />+ </ProjectActionsMenuProvider>+ </QueryClientProvider></ChakraProvider>));@@ -184,10 +241,12 @@ describe('ProjectActionsMenuHost', () => {await act(async () => {root?.render(<ChakraProvider value={system}>- <ProjectActionsMenuProvider>- <Card id="one" />- <Card id="two" />- </ProjectActionsMenuProvider>+ <QueryClientProvider client={queryClient}>+ <ProjectActionsMenuProvider>+ <Card id="one" />+ <Card id="two" />+ </ProjectActionsMenuProvider>+ </QueryClientProvider></ChakraProvider>);await new Promise<void>((resolve) => {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsxindex 72271b522a..f82d1077b4 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectActionsMenuHost.tsx@@ -3,11 +3,10 @@ import type { MouseEvent, ReactNode } from 'react';import { Menu, Portal } from '@chakra-ui/react';import { INTERMEDIATES_SETTING_ID, requestIntermediatesFocus } from '@features/intermediates';-import { ConfirmDialog } from '@platform/ui/ConfirmDialog';import { RenameDialog } from '@platform/ui/RenameDialog';import { useNavigate } from '@tanstack/react-router';import { isProjectSummaryCompatible } from '@workbench/projects/library';-import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';+import { createContext, lazy, Suspense, useCallback, useContext, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import type { ProjectCardActions } from './useProjectCardActions';@@ -15,6 +14,14 @@ import type { ProjectCardActions } from './useProjectCardActions';import { ProjectActionsMenuBody } from './ProjectActionsMenu';import { useProjectCardActions } from './useProjectCardActions';+// The dialog reads the gallery's board query, and this host sits in a boot graph the performance gates pin by source+// file, so even a shared three-line wrapper module would register as growth. Loaded the first time a delete is asked for.+const LazyDeleteProjectDialog = lazy(() =>+ import('@workbench/projects/components/DeleteProjectDialog').then((module) => ({+ default: module.DeleteProjectDialog,+ }))+);+/*** Use one menu host so switching cards cannot race Zag's nested-layer teardown. Keep dialogs beside the menu so* selecting an action does not unmount them.@@ -44,6 +51,7 @@ interface DialogRequest {actions: ProjectCardActions;kind: 'delete' | 'rename';name: string;+ projectId: string;}interface ProjectActionsMenuControl {@@ -69,10 +77,18 @@ export const ProjectActionsMenuProvider = ({ children }: { children: ReactNode }const { t } = useTranslation();const [menuRequest, setMenuRequest] = useState<MenuRequest | null>(null);const [dialogRequest, setDialogRequest] = useState<DialogRequest | null>(null);+ // Once mounted the dialog stays, so its close animation and the lazy chunk are paid for once.+ const [hasRequestedDelete, setHasRequestedDelete] = useState(false);const ticketRef = useRef(0);const closeMenu = useCallback(() => setMenuRequest(null), []);const closeDialog = useCallback(() => setDialogRequest(null), []);+ const requestDialog = useCallback((dialog: DialogRequest) => {+ if (dialog.kind === 'delete') {+ setHasRequestedDelete(true);+ }+ setDialogRequest(dialog);+ }, []);const openAtPointer = useCallback((event: MouseEvent, target: ProjectMenuTarget) => {event.preventDefault();ticketRef.current += 1;@@ -110,7 +126,7 @@ export const ProjectActionsMenuProvider = ({ children }: { children: ReactNode }key={menuKey}request={menuRequest}onClose={closeMenu}- onRequestDialog={setDialogRequest}+ onRequestDialog={requestDialog}/>) : null}@@ -124,14 +140,17 @@ export const ProjectActionsMenuProvider = ({ children }: { children: ReactNode }onSubmit={dialogRequest?.actions.rename ?? NOOP_SUBMIT}/>- <ConfirmDialog- body={`${t('projects.deleteProjectCardBody', { name: dialogRequest?.name ?? '' })} ${t('projects.deleteProjectBoardNote')}`}- confirmLabel={t('projects.deleteProject')}- isOpen={dialogRequest?.kind === 'delete'}- title={t('projects.deleteProjectQuestion')}- onClose={closeDialog}- onConfirm={dialogRequest?.actions.delete ?? NOOP_SUBMIT}- />+ {hasRequestedDelete ? (+ <Suspense fallback={null}>+ <LazyDeleteProjectDialog+ body={t('projects.deleteProjectCardBody', { name: dialogRequest?.name ?? '' })}+ isOpen={dialogRequest?.kind === 'delete'}+ projectId={dialogRequest?.kind === 'delete' ? dialogRequest.projectId : null}+ onClose={closeDialog}+ onConfirm={dialogRequest?.actions.delete ?? NOOP_SUBMIT}+ />+ </Suspense>+ ) : null}</ProjectActionsMenuContext.Provider>);};@@ -207,8 +226,8 @@ const HostedProjectActionsMenu = ({[onClose, request.returnFocus]);const handleRename = useCallback(- () => onRequestDialog({ actions, kind: 'rename', name: request.summary.name }),- [actions, onRequestDialog, request.summary.name]+ () => onRequestDialog({ actions, kind: 'rename', name: request.summary.name, projectId: request.summary.id }),+ [actions, onRequestDialog, request.summary.id, request.summary.name]);const handleDeleteIntermediates = useCallback(() => {// The manager lives in Preferences; it reads this intent when it starts.@@ -221,8 +240,8 @@ const HostedProjectActionsMenu = ({});}, [navigate, onClose, request.summary.id]);const handleDelete = useCallback(- () => onRequestDialog({ actions, kind: 'delete', name: request.summary.name }),- [actions, onRequestDialog, request.summary.name]+ () => onRequestDialog({ actions, kind: 'delete', name: request.summary.name, projectId: request.summary.id }),+ [actions, onRequestDialog, request.summary.id, request.summary.name]);const handleDuplicate = useCallback(() => void actions.duplicate(), [actions]);const handleExport = useCallback(() => void actions.export(), [actions]);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.tsindex 0a01be4dfb..2cfb7face0 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/useProjectCardActions.ts@@ -1,4 +1,7 @@+import type { DeleteProjectBoards } from '@workbench/projects/api';+import { toaster } from '@platform/ui';+import { useQueryClient } from '@tanstack/react-query';import { deleteLibraryProject, renameLibraryProject, type ProjectSummary } from '@workbench/projects/library';import { useDuplicateProject, useExportLibraryProject } from '@workbench/projects/useProjectFileActions';import { useCallback, useMemo } from 'react';@@ -13,13 +16,14 @@ export interface ProjectCardActions {duplicate: () => void;/** Reports its own progress and result, so there is nothing to await here. */export: () => void;- delete: () => Promise<void>;+ delete: (boards?: DeleteProjectBoards) => Promise<void>;}export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActions => {const { t } = useTranslation();const startExport = useExportLibraryProject();const startDuplicate = useDuplicateProject();+ const queryClient = useQueryClient();const rename = useCallback(async (name: string) => {@@ -47,20 +51,29 @@ export const useProjectCardActions = (summary: ProjectSummary): ProjectCardActiostartExport(summary.id, summary.name);}, [startExport, summary.id, summary.name]);- const deleteProject = useCallback(async () => {- try {- await deleteLibraryProject(summary.id);- // Pins are persisted per account, so a deleted project would otherwise- // leave a dead id in preferences forever.- dropProjectPin(summary.id);- } catch (error) {- toaster.create({- description: error instanceof Error ? error.message : undefined,- title: t('projects.deleteFailed'),- type: 'error',- });- }- }, [summary.id, t]);+ const deleteProject = useCallback(+ async (boards?: DeleteProjectBoards) => {+ try {+ await deleteLibraryProject(summary.id, boards);+ // Pins are persisted per account, so a deleted project would otherwise+ // leave a dead id in preferences forever.+ dropProjectPin(summary.id);+ // Its boards were released or deleted with it; any board list on screen is stale either way. Loaded here+ // rather than at the top (the gallery data layer is not part of the Launchpad's initial graph), and never+ // awaited: the project is gone, so a chunk that fails to load must not be reported as a failed delete.+ void import('@features/gallery/queries')+ .then((module) => module.invalidateGallery(queryClient))+ .catch(() => undefined);+ } catch (error) {+ toaster.create({+ description: error instanceof Error ? error.message : undefined,+ title: t('projects.deleteFailed'),+ type: 'error',+ });+ }+ },+ [queryClient, summary.id, t]+ );// Stabilize the actions object so virtualized row renders do not invalidate derived menu callbacks.return useMemo(diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.tsindex 54b90a9248..419809f28f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts@@ -18,6 +18,7 @@ vi.mock('@platform/transport/http', async (importOriginal) => ({}));import {+ deleteProject,createProject,createProjectSettled,getProjectWriteSizeRefusal,@@ -427,3 +428,22 @@ describe('project write size refusals', () => {expect(getProjectWriteSizeRefusal(error)).toBeNull();});});++describe('deleteProject', () => {+ it('asks the server to release the boards unless told to delete them', async () => {+ transport.apiFetch.mockResolvedValue(undefined);++ await deleteProject('project-1');+ await deleteProject('project-1', undefined, 'release');+ await deleteProject('project-1', undefined, 'delete');++ expect(transport.apiFetch.mock.calls.map(([url]) => url)).toEqual([+ '/api/v1/projects/project-1',+ '/api/v1/projects/project-1',+ '/api/v1/projects/project-1?boards=delete',+ ]);+ expect(transport.apiFetch.mock.calls.every(([, init]) => (init as { method: string }).method === 'DELETE')).toBe(+ true+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex 49480ea87e..27e7534f03 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -195,8 +195,18 @@ export const updateProject = ();};-export const deleteProject = async (projectId: string, signal?: AbortSignal): Promise<void> => {- await apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, { method: 'DELETE', signal });+/** What becomes of a deleted project's boards other than its inbox, which always goes with the project. */+export type DeleteProjectBoards = 'delete' | 'release';++/** Media is never deleted: released boards keep theirs in the Library, deleted boards' returns to Uncategorized. */+export const deleteProject = async (+ projectId: string,+ signal?: AbortSignal,+ boards: DeleteProjectBoards = 'release'+): Promise<void> => {+ const query = boards === 'release' ? '' : '?boards=delete';++ await apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}${query}`, { method: 'DELETE', signal });};/** Includes unreferenced visible board media; excludes intermediate/other categories. */diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.browser.test.tsxnew file mode 100644index 0000000000..65f143185a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.browser.test.tsx@@ -0,0 +1,171 @@+import type { GalleryBoard } from '@features/gallery';+import type * as transportModule from '@platform/transport/http';++import { ChakraProvider } from '@chakra-ui/react';+import { galleryBoardsOptions } from '@features/gallery/queries';+import { apiFetchJson } from '@platform/transport/http';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import { DeleteProjectDialog } from './DeleteProjectDialog';++vi.mock('@platform/transport/http', async (importOriginal) => ({+ ...(await importOriginal<typeof transportModule>()),+ apiFetchJson: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, unknown>) => {+ const messages: Record<string, string> = {+ 'projects.deleteProject': 'Delete project',+ 'projects.deleteProjectBoardsUnknown': 'Its other boards could not be checked.',+ 'projects.deleteProjectCheckingBoards': 'Checking its boards…',+ 'projects.deleteProjectDeleteBoards': 'Delete its other boards too',+ 'projects.deleteProjectDeleteBoardsHint': `${String(values?.items)} return to Uncategorized.`,+ 'projects.deleteProjectInboxNote': 'Its inbox goes with it.',+ 'projects.deleteProjectItemCount': `${String(values?.count)} items`,+ 'projects.deleteProjectKeepBoards': 'Keep its other boards in the Library',+ 'projects.deleteProjectKeepBoardsHint': `${String(values?.boards)} stay where you can find them.`,+ 'projects.deleteProjectQuestion': 'Delete project?',+ };++ return messages[key] ?? key;+ },+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const createBoard = (overrides: Partial<GalleryBoard> & Pick<GalleryBoard, 'id' | 'name'>): GalleryBoard => ({+ archived: false,+ assetCount: 0,+ assetVideoCount: 0,+ imageCount: 0,+ isInbox: false,+ kind: 'board',+ projectId: null,+ videoCount: 0,+ ...overrides,+});++const boards = [+ createBoard({ id: 'none', kind: 'uncategorized', name: '' }),+ createBoard({ id: 'inbox', imageCount: 142, isInbox: true, name: 'Mahogany House', projectId: 'p1' }),+ createBoard({ assetCount: 2, id: 'facades', imageCount: 37, name: 'Façade variants', projectId: 'p1' }),+ createBoard({ id: 'site', name: 'Site plan refs', projectId: 'p1', videoCount: 1 }),+ createBoard({ archived: true, id: 'old', imageCount: 5, name: 'Old façades', projectId: 'p1' }),+ createBoard({ id: 'theirs', isInbox: true, name: 'Harbor Tower', projectId: 'p2' }),+];++const onConfirm = vi.fn();+const noop = () => undefined;+let host: HTMLDivElement | null = null;+let root: Root | null = null;++const renderDialog = async (projectId: string, seed = true) => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ if (seed) {+ // Archived members are included: they go with the project just the same.+ queryClient.setQueryData(galleryBoardsOptions({ includeArchived: true }).queryKey, boards);+ }++ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <DeleteProjectDialog+ body="Delete this project?"+ isOpen+ projectId={projectId}+ onClose={noop}+ onConfirm={onConfirm}+ />+ </QueryClientProvider>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+};++const confirmButton = () =>+ [...document.querySelectorAll<HTMLButtonElement>('[role="alertdialog"] button')].find(+ (button) => button.textContent === 'Delete project'+ )!;++beforeEach(() => {+ onConfirm.mockClear();+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('DeleteProjectDialog', () => {+ it('names the other boards and what they hold, and keeps them by default', async () => {+ await renderDialog('p1');++ const text = document.querySelector('[role="alertdialog"]')?.textContent ?? '';+ expect(text).toContain('Façade variants, Site plan refs, Old façades stay where you can find them.');+ expect(text).toContain('45 items return to Uncategorized.');+ expect(text).toContain('Its inbox goes with it.');++ await act(() => userEvent.click(confirmButton()));++ expect(onConfirm).toHaveBeenCalledExactlyOnceWith('release');+ });++ it('deletes the other boards only when that is chosen', async () => {+ await renderDialog('p1');++ const deleteOption = [...document.querySelectorAll<HTMLElement>('[role="alertdialog"] label')].find((label) =>+ label.textContent?.includes('Delete its other boards too')+ )!;+ await act(() => userEvent.click(deleteOption));+ await act(() => userEvent.click(confirmButton()));++ expect(onConfirm).toHaveBeenCalledExactlyOnceWith('delete');+ });++ it('holds confirmation until the boards are known, and says so when they cannot be', async () => {+ vi.mocked(apiFetchJson).mockReturnValue(new Promise(() => {}));+ await renderDialog('p1', false);++ expect(confirmButton().disabled).toBe(true);+ expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('Checking its boards…');++ vi.mocked(apiFetchJson).mockRejectedValue(new Error('offline'));+ await act(() => root?.unmount());+ root = createRoot(host!);+ await renderDialog('p1', false);++ await vi.waitFor(() => {+ expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain(+ 'Its other boards could not be checked.'+ );+ });+ expect(confirmButton().disabled).toBe(false);+ expect(document.querySelector('[role="alertdialog"]')?.textContent).not.toContain('Delete its other boards too');++ await act(() => userEvent.click(confirmButton()));+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith('release');+ });++ it('asks nothing about boards when the project holds only its inbox', async () => {+ await renderDialog('p2');++ const text = document.querySelector('[role="alertdialog"]')?.textContent ?? '';+ expect(text).not.toContain('Keep its other boards');+ expect(text).toContain('Its inbox goes with it.');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.tsxnew file mode 100644index 0000000000..9e06533b8a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/components/DeleteProjectDialog.tsx@@ -0,0 +1,112 @@+import type { DeleteProjectBoards } from '@workbench/projects/api';++import { RadioGroup, Stack, Text } from '@chakra-ui/react';+import { galleryBoardsOptions } from '@features/gallery/queries';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { useQuery } from '@tanstack/react-query';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * Deleting a project also decides what happens to the boards it holds. The inbox always goes with it; the choice+ * is offered only when there are other boards, with their names and what they hold, so the safe default — keeping+ * them in the Library — is never a surprise and the destructive one says what it costs.+ */+export const DeleteProjectDialog = ({+ body,+ finalFocusEl,+ isOpen,+ projectId,+ onClose,+ onConfirm,+}: {+ /** The host's own sentence about the project; the dialog adds what happens to its boards. */+ body: string;+ finalFocusEl?: () => HTMLElement | null;+ isOpen: boolean;+ projectId: string | null;+ onClose: () => void;+ onConfirm: (boards: DeleteProjectBoards) => Promise<void> | void;+}) => {+ const { t } = useTranslation();+ const [boards, setBoards] = useState<DeleteProjectBoards>('release');+ // Archived members go with the project just the same, so the list must include them.+ const { data, isError, isLoading } = useQuery({+ ...galleryBoardsOptions({ includeArchived: true }),+ enabled: isOpen && projectId !== null,+ });+ const members = useMemo(+ () => (data ?? []).filter((board) => board.projectId === projectId && !board.isInbox),+ [data, projectId]+ );+ const itemCount = members.reduce((total, board) => total + board.imageCount + board.assetCount + board.videoCount, 0);++ const handleValueChange = useCallback((event: { value: string | null }) => {+ setBoards(event.value === 'delete' ? 'delete' : 'release');+ }, []);+ const handleConfirm = useCallback(() => onConfirm(boards), [boards, onConfirm]);+ // Each opening starts from the safe choice again.+ const handleExitComplete = useCallback(() => setBoards('release'), []);++ return (+ <ConfirmDialog+ body={+ <>+ <Text fontSize="md">{body}</Text>+ {isLoading ? (+ <Text color="fg.muted" fontSize="xs">+ {t('projects.deleteProjectCheckingBoards')}+ </Text>+ ) : null}+ {isError ? (+ <Text color="fg.muted" fontSize="xs">+ {t('projects.deleteProjectBoardsUnknown')}+ </Text>+ ) : null}+ {members.length > 0 ? (+ <RadioGroup.Root size="sm" value={boards} onValueChange={handleValueChange}>+ <Stack gap="2">+ <RadioGroup.Item alignItems="start" value="release">+ <RadioGroup.ItemHiddenInput />+ <RadioGroup.ItemIndicator mt="0.5" />+ <Stack gap="0">+ <RadioGroup.ItemText>{t('projects.deleteProjectKeepBoards')}</RadioGroup.ItemText>+ <Text color="fg.muted" fontSize="xs">+ {t('projects.deleteProjectKeepBoardsHint', {+ boards: members.map((board) => board.name).join(', '),+ })}+ </Text>+ </Stack>+ </RadioGroup.Item>+ <RadioGroup.Item alignItems="start" value="delete">+ <RadioGroup.ItemHiddenInput />+ <RadioGroup.ItemIndicator mt="0.5" />+ <Stack gap="0">+ <RadioGroup.ItemText>{t('projects.deleteProjectDeleteBoards')}</RadioGroup.ItemText>+ <Text color="fg.muted" fontSize="xs">+ {t('projects.deleteProjectDeleteBoardsHint', {+ items: t('projects.deleteProjectItemCount', { count: itemCount }),+ })}+ </Text>+ </Stack>+ </RadioGroup.Item>+ </Stack>+ </RadioGroup.Root>+ ) : null}+ <Text color="fg.muted" fontSize="xs">+ {t('projects.deleteProjectInboxNote')}+ </Text>+ </>+ }+ confirmLabel={t('projects.deleteProject')}+ finalFocusEl={finalFocusEl}+ // Not before the boards are known: the choice could otherwise appear after the user has already confirmed.+ isConfirmDisabled={isLoading}+ isOpen={isOpen}+ title={t('projects.deleteProjectQuestion')}+ onClose={onClose}+ onConfirm={handleConfirm}+ onExitComplete={handleExitComplete}+ />+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.tsindex a5b6e4fff7..2a07c51d02 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts@@ -18,7 +18,13 @@ import {withAuthoritativeProjectBoard,} from '@workbench/workbenchState';-import type { ProjectCreateRequest, ProjectRecordDTO, ProjectSummaryDTO, ProjectUpdateRequest } from './api';+import type {+ DeleteProjectBoards,+ ProjectCreateRequest,+ ProjectRecordDTO,+ ProjectSummaryDTO,+ ProjectUpdateRequest,+} from './api';import type {ProjectDraft,ProjectDraftCopyReservation,@@ -229,7 +235,7 @@ export interface DurableHydratedWorkbenchSnapshot extends HydratedWorkbenchSnapsexport interface DurableProjectPersistenceApi {createProject(request: ProjectCreateRequest, owner: AccountScope): Promise<ProjectRecordDTO>;- deleteProject(projectId: string, signal?: AbortSignal): Promise<void>;+ deleteProject(projectId: string, signal?: AbortSignal, boards?: DeleteProjectBoards): Promise<void>;deleteSession(signal?: AbortSignal): Promise<void>;getProject(projectId: string, signal?: AbortSignal): Promise<ProjectRecordDTO>;listProjects(signal?: AbortSignal): Promise<ProjectSummaryDTO[]>;@@ -392,7 +398,7 @@ export interface DurableSyncedWorkbenchPersistence {generation: number,updatedAt: number): Promise<void>;- deleteProjectOnServer(projectId: string): Promise<void>;+ deleteProjectOnServer(projectId: string, boards?: DeleteProjectBoards): Promise<void>;ensureProjectOnServer(project: Project): Promise<void>;flushProjectToServer(project: Project): Promise<ProjectPushOutcome>;getProjectDraftDocument(projectId: string): Promise<string | null>;@@ -1983,7 +1989,7 @@ export const createDurableSyncedWorkbenchPersistence = (unopenableDrafts.delete(`${projectId}\u0000${editorSessionId}`);reportSync(lastKnownState?.projects ?? []);}),- deleteProjectOnServer: (projectId) =>+ deleteProjectOnServer: (projectId, boards = 'release') =>enqueue(async () => {const resolvedProjectId = resolveProjectId(projectId);const hadDeleteFence = deletedProjectIds.has(resolvedProjectId);@@ -2002,7 +2008,7 @@ export const createDurableSyncedWorkbenchPersistence = (throw new Error('This tab no longer owns the local project draft.');}try {- await api.deleteProject(resolvedProjectId, owner.signal);+ await api.deleteProject(resolvedProjectId, owner.signal, boards);} catch (error) {if (!isStatus(error, 404)) {throw error;diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex d58b4b595b..621ef42ec7 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -212,7 +212,7 @@ describe('library mutations', () => {await library.deleteLibraryProject('doomed');- expect(api.deleteProject).toHaveBeenCalledWith('doomed', expect.any(AbortSignal));+ expect(api.deleteProject).toHaveBeenCalledWith('doomed', expect.any(AbortSignal), 'release');expect(library.getProjectLibrary().summaries).toHaveLength(0);});@@ -267,12 +267,23 @@ describe('library mutations', () => {expect(api.deleteProject).not.toHaveBeenCalled();});+ it('hands the choice to delete the project boards through whichever path deletes', async () => {+ const { handle } = openProject('open');+ api.deleteProject.mockResolvedValue(undefined);++ await library.deleteLibraryProject('open', 'delete');+ expect(handle.deleteOnServer).toHaveBeenCalledWith('delete');++ await library.deleteLibraryProject('closed', 'delete');+ expect(api.deleteProject).toHaveBeenCalledWith('closed', expect.any(AbortSignal), 'delete');+ });+it('deletes a closed project over HTTP, because no engine holds it', async () => {api.deleteProject.mockResolvedValue(undefined);await library.deleteLibraryProject('closed');- expect(api.deleteProject).toHaveBeenCalledWith('closed', expect.any(AbortSignal));+ expect(api.deleteProject).toHaveBeenCalledWith('closed', expect.any(AbortSignal), 'release');});it('does not delete while another tab owns an active project run', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex f2b6f6e306..2ecfa2b013 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -13,6 +13,7 @@ import { DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION, isCanvasSchemaVersionSupported }import type { ProjectTransferIssues } from './invk/transfer';import {+ type DeleteProjectBoards,deleteProject as apiDeleteProject,getProject as apiGetProject,getProjectBoardSnapshot,@@ -179,8 +180,14 @@ export const isProjectSummaryCompatible = (summary: ProjectSummary): boolean =>/** Open projects mutate through their sync engine; closed projects use the HTTP API directly. */-/** Permanently remove a project from the server, its board with it. The only deletion path. */-export const deleteLibraryProject = async (projectId: string): Promise<void> => {+/**+ * Permanently remove a project from the server, its inbox with it. The only deletion path. Its other boards are+ * released to the Library unless asked to go too; media survives either way.+ */+export const deleteLibraryProject = async (+ projectId: string,+ boards: DeleteProjectBoards = 'release'+): Promise<void> => {const owner = captureAccountScope();const [{ acquireProjectMutationLock }, { createAccountOwnedQueueRunJournal }] = await Promise.all([import('./projectLifecycleLocks'),@@ -209,9 +216,9 @@ export const deleteLibraryProject = async (projectId: string): Promise<void> =>if (openProject) {// Queueing ensures an in-flight save finishes before DELETE is sent.- await openProject.deleteOnServer();+ await openProject.deleteOnServer(boards);} else {- await apiDeleteProject(projectId, owner.signal);+ await apiDeleteProject(projectId, owner.signal, boards);}assertAccountScopeCurrent(owner);diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.tsindex 476fef35fb..d3a13edb10 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.test.ts@@ -138,7 +138,10 @@ describe('createOpenProjectBroker', () => {handle.close();expect(harness.deps.markProjectDeleted).toHaveBeenCalledWith('a');- expect(harness.deps.deleteProject).toHaveBeenCalledWith('a');+ expect(harness.deps.deleteProject).toHaveBeenCalledWith('a', undefined);++ await handle.deleteOnServer('delete');+ expect(harness.deps.deleteProject).toHaveBeenLastCalledWith('a', 'delete');expect(harness.deps.closeProject).toHaveBeenCalledWith('a');});diff --git a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.tsindex 2232ebdf11..b53ba5ac6e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/openProjectBroker.ts@@ -1,5 +1,6 @@import type { Project } from '@workbench/projectContracts';+import type { DeleteProjectBoards } from './api';import type { ProjectPushOutcome } from './projectFlush';import { type OpenProjectHandle, registerOpenProject, unregisterOpenProject } from './syncStore';@@ -9,7 +10,7 @@ export interface OpenProjectBrokerDeps {/** Drop the tab. Called after the project is already gone from the server. */closeProject: (projectId: string) => void;/** Remove the project from the server, in the sync engine's own queue. */- deleteProject: (projectId: string) => Promise<void>;+ deleteProject: (projectId: string, boards?: DeleteProjectBoards) => Promise<void>;/** Push this project's live document and report whether the server took it. */flushProject: (projectId: string) => Promise<ProjectPushOutcome>;/** Persist the project's unsaved canvas pixels into its document. */@@ -33,7 +34,7 @@ export const createOpenProjectBroker = (deps: OpenProjectBrokerDeps): OpenProjecconst buildHandle = (projectId: string): OpenProjectHandle => ({close: () => deps.closeProject(projectId),- deleteOnServer: () => deps.deleteProject(projectId),+ deleteOnServer: (boards) => deps.deleteProject(projectId, boards),flush: () => deps.flushProject(projectId),current: () => deps.getProject(projectId),flushPixels: () => deps.flushPixels(projectId),diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsxindex 0b3b3961f2..2f33434f79 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsx@@ -5,6 +5,7 @@ import type { Project, ProjectLoadResult } from '@workbench/projectContracts';import { ChakraProvider } from '@chakra-ui/react';import { GenerationUiProvider } from '@features/generation/react';import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { GenerateDenoisingStrength } from '@workbench/widgets/canvas/GenerateDenoisingStrength';import {@@ -66,7 +67,7 @@ const generationUi = {sectionPreferences: { sectionsOpen: {}, setSectionOpen: () => undefined },} as unknown as GenerationUiAdapter;-const Harness = () => {+const HarnessBody = () => {const { closeProject, openProject } = useProjectActions();return (<ChakraProvider value={system}>@@ -79,6 +80,14 @@ const Harness = () => {);};+// Deleting invalidates the gallery's board lists, so the hook reads the query client.+const queryClient = new QueryClient();+const Harness = () => (+ <QueryClientProvider client={queryClient}>+ <HarnessBody />+ </QueryClientProvider>+);+const click = (label: 'close' | 'open', project: { id: string; name: string }) =>act(() => {Object.assign(target, { id: project.id, name: project.name });diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.tsindex 54e3848633..32dc7a580b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts@@ -3,6 +3,7 @@ import type { Project } from '@workbench/projectContracts';import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';+import type { DeleteProjectBoards } from './api';import type { ProjectPushOutcome, ProjectSchemaRefusal } from './projectFlush';/** Only the sync engine mutates open projects; closed projects use HTTP. */@@ -52,7 +53,7 @@ export interface OpenProjectHandle {/** Close the tab, after the project has been deleted on the server. */close: () => void;/** Delete through the sync engine's mutation queue so in-flight saves finish first. */- deleteOnServer: () => Promise<void>;+ deleteOnServer: (boards?: DeleteProjectBoards) => Promise<void>;/** Flush returns an acknowledgement outcome; callers reading server bytes must assert success. */flush: () => Promise<ProjectPushOutcome>;/** Persists unsaved canvas pixels into the document; rejects when they cannot be saved. */diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsxindex ec610585f2..1d047a47fb 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx@@ -2,6 +2,7 @@ import type { Project } from '@workbench/projectContracts';import type { ProjectCommandResult } from '@workbench/workbenchStore';import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { createDraftProject } from '@workbench/workbenchState';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -55,7 +56,7 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const Harness = () => {+const HarnessBody = () => {const { closeProject, deleteProject } = useProjectActions();return (<>@@ -65,6 +66,14 @@ const Harness = () => {);};+// Deleting invalidates the gallery's board lists, so the hook reads the query client.+const queryClient = new QueryClient();+const Harness = () => (+ <QueryClientProvider client={queryClient}>+ <HarnessBody />+ </QueryClientProvider>+);+beforeEach(() => {accountLifecycle.activate('use-project-actions-browser-test');harness.project = createDraftProject([]);diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex f7cb405ac8..3ffc29af60 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -1,11 +1,13 @@import type { Project } from '@workbench/projectContracts';+import { invalidateGallery } from '@features/gallery/queries';import {assertAccountScopeCurrent,captureAccountScope,isAccountScopeCurrent,} from '@platform/state/accountLifecycle';import { getApiErrorMessage } from '@platform/transport/http';+import { useQueryClient } from '@tanstack/react-query';import { useNavigate } from '@tanstack/react-router';import { hasActiveQueueRuns } from '@workbench/queue-integration/activeQueueRuns';import { useNotify } from '@workbench/useNotify';@@ -18,6 +20,8 @@ import {} from '@workbench/WorkbenchContext';import { useTranslation } from 'react-i18next';+import type { DeleteProjectBoards } from './api';+import { deleteLibraryProject, refreshProjectLibrary } from './library';import { serializeProjectDocumentV3Json } from './projectDocument';import { describeRefusedProject } from './projectLoadRefusal';@@ -30,7 +34,7 @@ const CLOSE_FLUSH_ATTEMPTS = 3;*/export const useProjectActions = (): {closeProject: (project: Project) => void;- deleteProject: (project: Project) => Promise<void>;+ deleteProject: (project: Project, boards?: DeleteProjectBoards) => Promise<void>;openProject: (projectId: string, name: string) => Promise<void>;} => {const queries = useWorkbenchQueries();@@ -41,6 +45,7 @@ export const useProjectActions = (): {const navigate = useNavigate();const notify = useNotify();const { t } = useTranslation();+ const queryClient = useQueryClient();/** False when the project changed since `unchangedFrom` (an edit was still pending), so it must be pushed again. */const finishClose = async (projectId: string, unchangedFrom?: Project): Promise<boolean> => {@@ -200,7 +205,7 @@ export const useProjectActions = (): {});};- const deleteProject = async (project: Project): Promise<void> => {+ const deleteProject = async (project: Project, boards?: DeleteProjectBoards): Promise<void> => {if (hasActiveQueueRuns(project)) {notify.error(t('projects.deleteFailed'), t('projects.activeRunsMustFinish'));return;@@ -209,12 +214,14 @@ export const useProjectActions = (): {const owner = captureAccountScope();try {// Open projects delete through the sync engine so in-flight saves finish first.- await deleteLibraryProject(project.id);+ await deleteLibraryProject(project.id, boards);} catch (error) {notify.error(t('projects.deleteFailed'), error instanceof Error ? error.message : undefined);return;}+ // Its boards were released or deleted with it; every board list on screen is stale either way.+ void invalidateGallery(queryClient);try {await finishClose(project.id);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsxindex 2bbdd5e881..78fd5aee56 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx@@ -56,6 +56,7 @@ vi.mock('@platform/ui/ConfirmDialog', () => ({ ConfirmDialog: () => null }));vi.mock('@workbench/components/QueueProgressIndicator', () => ({ QueueCircularProgress: () => null }));vi.mock('@workbench/launchpad/formatRelativeTime', () => ({ formatRelativeTime: () => '' }));vi.mock('@workbench/projects/components', () => ({ OpenProjectDialog: () => null }));+vi.mock('@workbench/projects/components/DeleteProjectDialog', () => ({ DeleteProjectDialog: () => null }));vi.mock('@workbench/projects/library', () => ({refreshProjectLibrary: vi.fn(() => Promise.resolve()),renameLibraryProject: vi.fn(() => Promise.resolve()),diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsxindex 3f2f7e2226..18e24ac56c 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx@@ -1,4 +1,5 @@import type { Project } from '@workbench/projectContracts';+import type { DeleteProjectBoards } from '@workbench/projects/api';import type { ProjectSummary } from '@workbench/projects/library';import type { MouseEvent } from 'react';@@ -8,7 +9,6 @@ import { useModelLoads } from '@features/models';import { getProjectQueueIndicatorState } from '@features/queue/contracts';import { useQueueItemProgress } from '@features/queue/react';import { Button } from '@platform/ui/Button';-import { ConfirmDialog } from '@platform/ui/ConfirmDialog';import { MenuContent } from '@platform/ui/Menu';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { RenameDialog } from '@platform/ui/RenameDialog';@@ -37,12 +37,20 @@ import {Trash2Icon,XIcon,} from 'lucide-react';-import { useCallback, useRef, useState } from 'react';+import { lazy, Suspense, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { projectSwitcherStore, setProjectSwitcherOpen } from './projectSwitcherStore';import { HIDE_BELOW_PROJECT_NAME_WIDTH } from './topbarBreakpoints';+// The dialog reads the gallery's board query, and this host sits in a boot graph the performance gates pin by source+// file, so even a shared three-line wrapper module would register as growth. Loaded the first time a delete is asked for.+const LazyDeleteProjectDialog = lazy(() =>+ import('@workbench/projects/components/DeleteProjectDialog').then((module) => ({+ default: module.DeleteProjectDialog,+ }))+);+const MENU_POSITIONING = { placement: 'bottom-start' } as const;const RECENT_PROJECT_LIMIT = 5;@@ -63,6 +71,8 @@ export const ProjectSwitcher = () => {const returnFocus = useCallback(() => triggerRef.current, []);const [renameTarget, setRenameTarget] = useState<{ id: string; name: string } | null>(null);const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);+ // Once mounted the dialog stays, so its close animation and the lazy chunk are paid for once.+ const [hasRequestedDelete, setHasRequestedDelete] = useState(false);const [isOpenDialogVisible, setIsOpenDialogVisible] = useState(false);const isMenuOpen = projectSwitcherStore.useSelector((snapshot) => snapshot.isOpen);@@ -114,21 +124,24 @@ export const ProjectSwitcher = () => {},[renameTarget, t]);- const confirmDeleteProject = useCallback(async () => {- const project = deleteTarget ? getProject(deleteTarget.id) : null;+ const confirmDeleteProject = useCallback(+ async (boards: DeleteProjectBoards) => {+ const project = deleteTarget ? getProject(deleteTarget.id) : null;- if (project) {- await deleteProject(project);- }- }, [deleteProject, deleteTarget, getProject]);+ if (project) {+ await deleteProject(project, boards);+ }+ },+ [deleteProject, deleteTarget, getProject]+ );const renameActiveProject = useCallback(() => setRenameTarget({ id: activeProjectId, name: activeProjectName }),[activeProjectId, activeProjectName]);- const deleteActiveProject = useCallback(- () => setDeleteTarget({ id: activeProjectId, name: activeProjectName }),- [activeProjectId, activeProjectName]- );+ const deleteActiveProject = useCallback(() => {+ setHasRequestedDelete(true);+ setDeleteTarget({ id: activeProjectId, name: activeProjectName });+ }, [activeProjectId, activeProjectName]);const showActiveProjectDetails = useCallback(() => openWorkbenchWidget('project'), [openWorkbenchWidget]);const exportActiveProject = useCallback(() => {flushGenerateDrafts();@@ -266,14 +279,17 @@ export const ProjectSwitcher = () => {onClose={closeRenameDialog}onSubmit={renameProject}/>- <ConfirmDialog- body={`${t('projects.deleteProjectTabBody', { name: deleteTarget?.name ?? '' })} ${t('projects.deleteProjectBoardNote')}`}- confirmLabel={t('projects.deleteProject')}- isOpen={deleteTarget !== null}- title={t('projects.deleteProjectQuestion')}- onClose={closeDeleteDialog}- onConfirm={confirmDeleteProject}- />+ {hasRequestedDelete ? (+ <Suspense fallback={null}>+ <LazyDeleteProjectDialog+ body={t('projects.deleteProjectTabBody', { name: deleteTarget?.name ?? '' })}+ isOpen={deleteTarget !== null}+ projectId={deleteTarget?.id ?? null}+ onClose={closeDeleteDialog}+ onConfirm={confirmDeleteProject}+ />+ </Suspense>+ ) : null}{/** Keep the dialog mounted by open state; its lazyMount/unmountOnExit handle closed cost and preserve exit* animation.